Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/common/abis/deployer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { parseAbi } from "viem";

const _StackItem = `bytes32` as const;
const _SourceIndexV2 = `uint256` as const;
const _FullyQualifiedNamespace = `uint256` as const;
const _EvalV4 =
`(address store, ${_FullyQualifiedNamespace} namespace, bytes bytecode, ${_SourceIndexV2} sourceIndex, bytes32[][] context, ${_StackItem}[] inputs, bytes32[] stateOverlay)` as const;

const _deployer = [
"function parse2(bytes memory data) external view returns (bytes memory bytecode)",
"function iStore() external view returns (address)",
"function iInterpreter() external view returns (address)",
"function iParser() external view returns (address)",
`function eval4(${_EvalV4} calldata eval) external view returns (${_StackItem}[] calldata stack, bytes32[] calldata writes)`,
] as const;

/** Keeps ExpressionDeployer related ABIs */
Expand All @@ -20,4 +27,12 @@ export namespace DeployerAbi {
/** ExpressionDeployerNPE2 signature ABI */
export const deployer = _deployer;
}

/** Deployer and Interpreter structs ABI */
export namespace Structs {
export const EvalV4 = _EvalV4;
export const StackItem = _StackItem;
export const SourceIndexV2 = _SourceIndexV2;
export const FullyQualifiedNamespace = _FullyQualifiedNamespace;
}
}
268 changes: 187 additions & 81 deletions src/common/abis/orderbook.ts

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/core/modes/inter/simulate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ describe("Test InterOrderbookTradeSimulator", () => {
).toString(),
);
expect(encodeFunctionData).toHaveBeenCalledWith({
abi: ABI.Orderbook.Primary.Orderbook,
abi: ABI.Orderbook.V4.Primary.Orderbook,
functionName: "takeOrders2",
args: [
{
Expand Down Expand Up @@ -217,7 +217,7 @@ describe("Test InterOrderbookTradeSimulator", () => {
);
expect(encodeFunctionData).toHaveBeenCalledTimes(1);
expect(encodeFunctionData).toHaveBeenCalledWith({
abi: ABI.Orderbook.Primary.Arb,
abi: ABI.Orderbook.V4.Primary.Arb,
functionName: "arb3",
args: [
tradeArgs.orderDetails.orderbook as `0x${string}`,
Expand Down
4 changes: 2 additions & 2 deletions src/core/modes/inter/simulate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ export class InterOrderbookTradeSimulator extends TradeSimulatorBase {

// encode takeOrders2() and build tx fields
const encodedFN = encodeFunctionData({
abi: ABI.Orderbook.Primary.Orderbook,
abi: ABI.Orderbook.V4.Primary.Orderbook,
functionName: "takeOrders2",
args: [
{
Expand Down Expand Up @@ -171,7 +171,7 @@ export class InterOrderbookTradeSimulator extends TradeSimulatorBase {
};

params.rawtx.data = encodeFunctionData({
abi: ABI.Orderbook.Primary.Arb,
abi: ABI.Orderbook.V4.Primary.Arb,
functionName: "arb3",
args: [
this.tradeArgs.orderDetails.orderbook as `0x${string}`,
Expand Down
2 changes: 1 addition & 1 deletion src/core/modes/intra/simulation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ describe("Test IntraOrderbookTradeSimulator", () => {
);
expect(encodeFunctionData).toHaveBeenCalledTimes(4);
expect(encodeFunctionData).toHaveBeenCalledWith({
abi: ABI.Orderbook.Primary.Orderbook,
abi: ABI.Orderbook.V4.Primary.Orderbook,
functionName: "multicall",
args: [["0xencodedData", "0xencodedData", "0xencodedData"]],
});
Expand Down
8 changes: 4 additions & 4 deletions src/core/modes/intra/simulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,12 @@ export class IntraOrderbookTradeSimulator extends TradeSimulatorBase {
signedContext: [],
};
const withdrawInputCalldata = encodeFunctionData({
abi: ABI.Orderbook.Primary.Orderbook,
abi: ABI.Orderbook.V4.Primary.Orderbook,
functionName: "withdraw2",
args: [this.tradeArgs.orderDetails.buyToken, this.inputBountyVaultId, maxUint256, []],
});
const withdrawOutputCalldata = encodeFunctionData({
abi: ABI.Orderbook.Primary.Orderbook,
abi: ABI.Orderbook.V4.Primary.Orderbook,
functionName: "withdraw2",
args: [
this.tradeArgs.orderDetails.sellToken,
Expand All @@ -143,7 +143,7 @@ export class IntraOrderbookTradeSimulator extends TradeSimulatorBase {
],
});
const clear2Calldata = encodeFunctionData({
abi: ABI.Orderbook.Primary.Orderbook,
abi: ABI.Orderbook.V4.Primary.Orderbook,
functionName: "clear2",
args: [
this.tradeArgs.orderDetails.takeOrder.struct.order,
Expand All @@ -169,7 +169,7 @@ export class IntraOrderbookTradeSimulator extends TradeSimulatorBase {
],
});
params.rawtx.data = encodeFunctionData({
abi: ABI.Orderbook.Primary.Orderbook,
abi: ABI.Orderbook.V4.Primary.Orderbook,
functionName: "multicall",
args: [[clear2Calldata, withdrawInputCalldata, withdrawOutputCalldata]],
});
Expand Down
2 changes: 1 addition & 1 deletion src/core/modes/router/simulate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ describe("Test RouterTradeSimulator", () => {
simulator.tradeArgs.solver.state.dispair,
);
expect(encodeFunctionData).toHaveBeenCalledWith({
abi: ABI.Orderbook.Primary.Arb,
abi: ABI.Orderbook.V4.Primary.Arb,
functionName: "arb3",
args: [
tradeArgs.orderDetails.orderbook as `0x${string}`,
Expand Down
2 changes: 1 addition & 1 deletion src/core/modes/router/simulate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export class RouterTradeSimulator extends TradeSimulatorBase {
signedContext: [],
};
params.rawtx.data = encodeFunctionData({
abi: ABI.Orderbook.Primary.Arb,
abi: ABI.Orderbook.V4.Primary.Arb,
functionName: "arb3",
args: [
this.tradeArgs.orderDetails.orderbook as `0x${string}`,
Expand Down
2 changes: 1 addition & 1 deletion src/core/process/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export function getActualClearAmount(
} else {
try {
const logs = parseEventLogs({
abi: [ABI.Orderbook.Primary.Orderbook[2]],
abi: [ABI.Orderbook.V4.Primary.Orderbook[2]],
eventName: "AfterClear",
logs: receipt.logs,
});
Expand Down
16 changes: 10 additions & 6 deletions src/core/process/round.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,23 @@ export async function initializeRound(
?.get(owner)
?.get(orderDetails.sellToken)
?.get(
orderDetails.takeOrder.struct.order.validOutputs[
orderDetails.takeOrder.struct.outputIOIndex
].vaultId,
BigInt(
orderDetails.takeOrder.struct.order.validOutputs[
orderDetails.takeOrder.struct.outputIOIndex
].vaultId,
),
)?.balance ?? orderDetails.sellTokenVaultBalance;
orderDetails.buyTokenVaultBalance =
this.orderManager.ownerTokenVaultMap
.get(orderDetails.orderbook)
?.get(owner)
?.get(orderDetails.buyToken)
?.get(
orderDetails.takeOrder.struct.order.validInputs[
orderDetails.takeOrder.struct.inputIOIndex
].vaultId,
BigInt(
orderDetails.takeOrder.struct.order.validInputs[
orderDetails.takeOrder.struct.inputIOIndex
].vaultId,
),
)?.balance ?? orderDetails.buyTokenVaultBalance;

// skip if the output vault is empty
Expand Down
9 changes: 6 additions & 3 deletions src/error/revert.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,11 +397,14 @@ describe("Test revert error handling functions", () => {

expect(result).toBe(frontrunHash);
expect(decodeFunctionData).toHaveBeenCalledWith({
abi: [ABI.Orderbook.Primary.Arb[1]],
abi: [ABI.Orderbook.V4.Primary.Arb[1]],
data: mockRawTx.data,
});
expect(mockViemClient.getLogs).toHaveBeenCalledWith({
events: [ABI.Orderbook.Primary.Orderbook[13], ABI.Orderbook.Primary.Orderbook[15]],
events: [
ABI.Orderbook.V4.Primary.Orderbook[13],
ABI.Orderbook.V4.Primary.Orderbook[15],
],
address: "0xOrderbook",
blockHash: mockReceipt.blockHash,
});
Expand Down Expand Up @@ -432,7 +435,7 @@ describe("Test revert error handling functions", () => {

expect(result).toBe(frontrunHash);
expect(decodeFunctionData).toHaveBeenCalledWith({
abi: [ABI.Orderbook.Primary.Orderbook[12]],
abi: [ABI.Orderbook.V4.Primary.Orderbook[12]],
data: mockRawTx.data,
});
});
Expand Down
8 changes: 4 additions & 4 deletions src/error/revert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,14 @@ export async function tryDetectFrontrun(
if (rawtx.data!.toLowerCase().startsWith("0x7ea0b76a")) {
// arb3 trade
const result = decodeFunctionData({
abi: [ABI.Orderbook.Primary.Arb[1]],
abi: [ABI.Orderbook.V4.Primary.Arb[1]],
data: rawtx.data!,
});
return (result?.args?.[1] as any)?.orders?.[0];
} else {
// clear2 trade
const result = decodeFunctionData({
abi: [ABI.Orderbook.Primary.Orderbook[12]],
abi: [ABI.Orderbook.V4.Primary.Orderbook[12]],
data: rawtx.data!,
});
return result?.args?.[1];
Expand All @@ -173,8 +173,8 @@ export async function tryDetectFrontrun(
const logs = (
await viemClient.getLogs({
events: [
ABI.Orderbook.Primary.Orderbook[13],
ABI.Orderbook.Primary.Orderbook[15],
ABI.Orderbook.V4.Primary.Orderbook[13],
ABI.Orderbook.V4.Primary.Orderbook[15],
],
address: orderbook,
blockHash: receipt.blockHash,
Expand Down
41 changes: 23 additions & 18 deletions src/order/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,15 @@ vi.mock("./types", async (importOriginal) => {
return {
...(await importOriginal()),
Order: {
tryFromBytes: vi.fn().mockImplementation((value: any) =>
Result.ok({
owner: value === "0xadminBytes" ? "0xadmin" : "0xowner",
validInputs: [{ token: "0xinput", decimals: 18, vaultId: 1n }],
validOutputs: [{ token: "0xoutput", decimals: 18, vaultId: 1n }],
}),
),
V3: {
tryFromBytes: vi.fn().mockImplementation((value: any) =>
Result.ok({
owner: value === "0xadminBytes" ? "0xadmin" : "0xowner",
validInputs: [{ token: "0xinput", decimals: 18, vaultId: 1n }],
validOutputs: [{ token: "0xoutput", decimals: 18, vaultId: 1n }],
}),
),
},
},
};
});
Expand Down Expand Up @@ -274,10 +276,11 @@ describe("Test OrderManager", () => {
],
};

(Order.tryFromBytes as Mock).mockReturnValueOnce(Result.err("some error"));
(Order.V3.tryFromBytes as Mock).mockReturnValueOnce(Result.err("some error"));
const result = await orderManager.addOrder(order as any);
assert(result.isErr());
expect(result.error).instanceOf(OrderManagerError);
expect(Order.V3.tryFromBytes).toHaveBeenCalledTimes(1);

const getOrderPairsSpy = vi.spyOn(orderManager, "getOrderPairs");
getOrderPairsSpy.mockResolvedValueOnce(Result.err(new OrderManagerError("err", 1)));
Expand Down Expand Up @@ -633,23 +636,24 @@ describe("Test OrderManager", () => {
outputs: [{ token: { address: "0xinput", symbol: "IN" }, balance: 1n }],
inputs: [{ token: { address: "0xoutput", symbol: "OUT" }, balance: 1n }],
};
(Order.tryFromBytes as Mock)
(Order.V3.tryFromBytes as Mock)
.mockReturnValueOnce(
Result.ok({
owner: "0xowner",
validInputs: [{ token: "0xinput", decimals: 18 }],
validOutputs: [{ token: "0xoutput", decimals: 18 }],
validInputs: [{ token: "0xinput", decimals: 18, vaultId: 1n }],
validOutputs: [{ token: "0xoutput", decimals: 18, vaultId: 1n }],
}),
)
.mockReturnValueOnce(
Result.ok({
owner: "0xowner",
validInputs: [{ token: "0xoutput", decimals: 18 }],
validOutputs: [{ token: "0xinput", decimals: 18 }],
validInputs: [{ token: "0xoutput", decimals: 18, vaultId: 1n }],
validOutputs: [{ token: "0xinput", decimals: 18, vaultId: 1n }],
}),
);
await orderManager.addOrder(orderA as any);
await orderManager.addOrder(orderB as any);
expect(Order.V3.tryFromBytes).toHaveBeenCalledTimes(2);

// get a bundled order for orderA (buyToken: 0xinput, sellToken: 0xoutput)
const roundOrders = orderManager.getNextRoundOrders();
Expand Down Expand Up @@ -682,23 +686,24 @@ describe("Test OrderManager", () => {
outputs: [{ token: { address: "0xinput", symbol: "IN" }, balance: 1n }],
inputs: [{ token: { address: "0xoutput", symbol: "OUT" }, balance: 1n }],
};
(Order.tryFromBytes as Mock)
(Order.V3.tryFromBytes as Mock)
.mockReturnValueOnce(
Result.ok({
owner: "0xowner",
validInputs: [{ token: "0xinput", decimals: 18 }],
validOutputs: [{ token: "0xoutput", decimals: 18 }],
validInputs: [{ token: "0xinput", decimals: 18, vaultId: 1n }],
validOutputs: [{ token: "0xoutput", decimals: 18, vaultId: 1n }],
}),
)
.mockReturnValueOnce(
Result.ok({
owner: "0xowner",
validInputs: [{ token: "0xoutput", decimals: 18 }],
validOutputs: [{ token: "0xinput", decimals: 18 }],
validInputs: [{ token: "0xoutput", decimals: 18, vaultId: 1n }],
validOutputs: [{ token: "0xinput", decimals: 18, vaultId: 1n }],
}),
);
await orderManager.addOrder(orderA as any);
await orderManager.addOrder(orderB as any);
expect(Order.V3.tryFromBytes).toHaveBeenCalledTimes(2);

// get a bundled order for orderA (buyToken: 0xinput, sellToken: 0xoutput)
const roundOrders = orderManager.getNextRoundOrders();
Expand Down
17 changes: 8 additions & 9 deletions src/order/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { downscaleProtection } from "./protection";
import { errorSnapshot, RainSolverBaseError } from "../error";
import { addToPairMap, removeFromPairMap, getSortedPairList } from "./pair";
import {
IO,
Pair,
Order,
OrderbooksPairMap,
Expand Down Expand Up @@ -165,7 +164,7 @@ export class OrderManager {
const orderHash = orderDetails.orderHash.toLowerCase();
const orderbook = orderDetails.orderbook.id.toLowerCase();

const orderStructResult = Order.tryFromBytes(orderDetails.orderBytes);
const orderStructResult = Order.V3.tryFromBytes(orderDetails.orderBytes);
if (orderStructResult.isErr()) {
return Result.err(
new OrderManagerError(
Expand Down Expand Up @@ -253,21 +252,21 @@ export class OrderManager {
owner,
{
address: outputVault.token.toLowerCase(),
decimals: outputVault.decimals,
decimals: pair.sellTokenDecimals,
symbol: pair.sellTokenSymbol,
},
outputVault.vaultId,
BigInt(outputVault.vaultId),
pair.sellTokenVaultBalance,
);
this.updateVault(
orderbook,
owner,
{
address: inputVault.token.toLowerCase(),
decimals: inputVault.decimals,
decimals: pair.buyTokenDecimals,
symbol: pair.buyTokenSymbol,
},
inputVault.vaultId,
BigInt(inputVault.vaultId),
pair.buyTokenVaultBalance,
);
}
Expand Down Expand Up @@ -326,7 +325,7 @@ export class OrderManager {
const orderbook = orderDetails.orderbook.id.toLowerCase();
const orderHash = orderDetails.orderHash.toLowerCase();

const orderStructResult = Order.tryFromBytes(orderDetails.orderBytes);
const orderStructResult = Order.V3.tryFromBytes(orderDetails.orderBytes);
if (orderStructResult.isErr()) continue;

const orderStruct = orderStructResult.value;
Expand Down Expand Up @@ -381,7 +380,7 @@ export class OrderManager {
*/
async getOrderPairs(
orderHash: string,
orderStruct: Order,
orderStruct: Order.V3,
orderDetails: SgOrder,
): Promise<Result<Pair[], OrderManagerError>> {
const pairs: Pair[] = [];
Expand All @@ -401,7 +400,7 @@ export class OrderManager {

// helper function to handle token details
const handleToken = async (
io: IO,
io: Order.V3.IO,
tokensList: SgOrder["outputs"],
): Promise<
Result<{ symbol: string; decimals: number; balance: string }, OrderManagerError>
Expand Down
Loading
Loading