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
1 change: 1 addition & 0 deletions src/router/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -929,6 +929,7 @@ describe("RainSolverRouter", () => {
mockSwapAmount,
mockGasPrice,
"single",
false,
);

sushiSpy.mockRestore();
Expand Down
2 changes: 2 additions & 0 deletions src/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ export class RainSolverRouter extends RainSolverRouterBase {
maximumInputFixed: bigint,
gasPriceBI: bigint,
routeType: "single" | "multi" = "single",
absolute = false,
): bigint | undefined {
return this.sushi?.findLargestTradeSize(
orderDetails,
Expand All @@ -298,6 +299,7 @@ export class RainSolverRouter extends RainSolverRouterBase {
maximumInputFixed,
gasPriceBI,
routeType,
absolute,
);
}

Expand Down
4 changes: 4 additions & 0 deletions src/router/sushi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,7 @@ export class SushiRouter extends RainSolverRouterBase {
maximumInputFixed: bigint,
gasPriceBI: bigint,
routeType: "single" | "multi" = "single",
absolute = false,
): bigint | undefined {
const result: bigint[] = [];
const gasPrice = Number(gasPriceBI);
Expand All @@ -506,6 +507,9 @@ export class SushiRouter extends RainSolverRouterBase {

if (route.status == "NoWay") {
maximumInput = maximumInput - initAmount / 2n ** i;
} else if (absolute) {
result.unshift(maxInput18);
maximumInput = maximumInput + initAmount / 2n ** i;
} else {
const price = calculatePrice18(
maximumInput,
Expand Down
149 changes: 136 additions & 13 deletions src/state/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ describe("Test SharedState", () => {
initL1GasPrice: 0n,
router: {
getMarketPrice: vi.fn(),
findLargestTradeSize: vi.fn(),
},
appOptions: { route: "multi" },
gasManager: {
Expand Down Expand Up @@ -335,20 +336,49 @@ describe("Test SharedState", () => {
});

describe("Test getMarketPrice method", () => {
it("should call getMarketPrice with correct params", () => {
const token1 = new Token({
chainId: 1,
address: `0x${"1".repeat(40)}`,
symbol: "TKN1",
decimals: 18,
});
const token2 = new Token({
chainId: 1,
address: `0x${"2".repeat(40)}`,
symbol: "TKN2",
decimals: 18,
const token1 = new Token({
chainId: 1,
address: `0x${"1".repeat(40)}`,
symbol: "TKN1",
decimals: 18,
});
const token2 = new Token({
chainId: 1,
address: `0x${"2".repeat(40)}`,
symbol: "TKN2",
decimals: 18,
});

it("should call getMarketPrice with correct params for 1 unit size happy", async () => {
(sharedState.router.getMarketPrice as Mock).mockResolvedValueOnce(
Result.ok({ price: 1n }),
);
const result = await sharedState.getMarketPrice(token1, token2, 12345n);

assert(result.isOk());
expect(result.value).toEqual({ price: 1n });
expect(sharedState.router.getMarketPrice).toHaveBeenCalledTimes(1);
expect(sharedState.router.findLargestTradeSize).not.toHaveBeenCalled();
expect(sharedState.router.getMarketPrice).toHaveBeenCalledWith({
fromToken: token1,
toToken: token2,
blockNumber: 12345n,
skipFetch: false,
gasPrice: sharedState.gasPrice,
amountIn: 1000000000000000000n,
sushiRouteType: sharedState.appOptions.route,
});
sharedState.getMarketPrice(token1, token2, 12345n);
});

it("should call getMarketPrice with correct params for partial size unhappy", async () => {
(sharedState.router.getMarketPrice as Mock).mockResolvedValueOnce(Result.err("error"));
(sharedState.router.findLargestTradeSize as Mock).mockReturnValueOnce(undefined);
const result = await sharedState.getMarketPrice(token1, token2, 12345n);

assert(result.isErr());
expect(result.error).toBe("error");
expect(sharedState.router.getMarketPrice).toHaveBeenCalledTimes(1);
expect(sharedState.router.findLargestTradeSize).toHaveBeenCalledTimes(1);
expect(sharedState.router.getMarketPrice).toHaveBeenCalledWith({
fromToken: token1,
toToken: token2,
Expand All @@ -358,6 +388,99 @@ describe("Test SharedState", () => {
amountIn: 1000000000000000000n,
sushiRouteType: sharedState.appOptions.route,
});
expect(sharedState.router.findLargestTradeSize).toHaveBeenCalledWith(
{ takeOrder: { quote: { ratio: 0n } } } as any,
token2,
token1,
1000000000000000000n,
sharedState.gasPrice,
sharedState.appOptions.route,
true,
);
});

it("should call getMarketPrice with correct params for partial size happy", async () => {
(sharedState.router.getMarketPrice as Mock)
.mockResolvedValueOnce(Result.err("error"))
.mockResolvedValueOnce(Result.ok({ price: 1n }));
(sharedState.router.findLargestTradeSize as Mock).mockReturnValueOnce(
500000000000000000n,
);
const result = await sharedState.getMarketPrice(token1, token2, 12345n);

assert(result.isOk());
expect(result.value).toEqual({ price: 1n });
expect(sharedState.router.getMarketPrice).toHaveBeenCalledTimes(2);
expect(sharedState.router.findLargestTradeSize).toHaveBeenCalledTimes(1);
expect(sharedState.router.getMarketPrice).toHaveBeenNthCalledWith(1, {
fromToken: token1,
toToken: token2,
blockNumber: 12345n,
skipFetch: false,
gasPrice: sharedState.gasPrice,
amountIn: 1000000000000000000n,
sushiRouteType: sharedState.appOptions.route,
});
expect(sharedState.router.getMarketPrice).toHaveBeenNthCalledWith(2, {
fromToken: token1,
toToken: token2,
blockNumber: 12345n,
skipFetch: false,
gasPrice: sharedState.gasPrice,
amountIn: 500000000000000000n,
sushiRouteType: sharedState.appOptions.route,
});
expect(sharedState.router.findLargestTradeSize).toHaveBeenCalledWith(
{ takeOrder: { quote: { ratio: 0n } } } as any,
token2,
token1,
1000000000000000000n,
sharedState.gasPrice,
sharedState.appOptions.route,
true,
);
});

it("should call getMarketPrice with correct params for partial size unhappy all", async () => {
(sharedState.router.getMarketPrice as Mock)
.mockResolvedValueOnce(Result.err("error1"))
.mockResolvedValueOnce(Result.err("error2"));
(sharedState.router.findLargestTradeSize as Mock).mockReturnValueOnce(
500000000000000000n,
);
const result = await sharedState.getMarketPrice(token1, token2, 12345n);

assert(result.isErr());
expect(result.error).toBe("error1");
expect(sharedState.router.getMarketPrice).toHaveBeenCalledTimes(2);
expect(sharedState.router.findLargestTradeSize).toHaveBeenCalledTimes(1);
expect(sharedState.router.getMarketPrice).toHaveBeenNthCalledWith(1, {
fromToken: token1,
toToken: token2,
blockNumber: 12345n,
skipFetch: false,
gasPrice: sharedState.gasPrice,
amountIn: 1000000000000000000n,
sushiRouteType: sharedState.appOptions.route,
});
expect(sharedState.router.getMarketPrice).toHaveBeenNthCalledWith(2, {
fromToken: token1,
toToken: token2,
blockNumber: 12345n,
skipFetch: false,
gasPrice: sharedState.gasPrice,
amountIn: 500000000000000000n,
sushiRouteType: sharedState.appOptions.route,
});
expect(sharedState.router.findLargestTradeSize).toHaveBeenCalledWith(
{ takeOrder: { quote: { ratio: 0n } } } as any,
token2,
token1,
1000000000000000000n,
sharedState.gasPrice,
sharedState.appOptions.route,
true,
);
});
});
});
40 changes: 37 additions & 3 deletions src/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,15 +310,49 @@ export class SharedState {
* @param skipFetch - (optional) Skips a fresh onchain call to fetch pools
* @returns The market price for the token pair or undefined if no route were found
*/
getMarketPrice(fromToken: Token, toToken: Token, blockNumber?: bigint, skipFetch?: boolean) {
return this.router.getMarketPrice({
async getMarketPrice(
fromToken: Token,
toToken: Token,
blockNumber?: bigint,
skipFetch?: boolean,
) {
const amountIn = parseUnits("1", fromToken.decimals);
const result = await this.router.getMarketPrice({
fromToken,
toToken,
blockNumber,
gasPrice: this.gasPrice,
amountIn,
sushiRouteType: this.appOptions.route,
skipFetch: !!skipFetch,
});
if (result.isOk()) {
return result;
}
const partialAmountIn = this.router.findLargestTradeSize(
{ takeOrder: { quote: { ratio: 0n } } } as any, // ratio unused when absolute
toToken,
fromToken,
amountIn,
this.gasPrice,
this.appOptions.route,
true, // absolute
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
if (typeof partialAmountIn !== "bigint") {
return result;
}
const partialResult = await this.router.getMarketPrice({
fromToken,
toToken,
blockNumber,
gasPrice: this.gasPrice,
amountIn: parseUnits("1", fromToken.decimals),
amountIn: partialAmountIn,
sushiRouteType: this.appOptions.route,
skipFetch: !!skipFetch,
});
Comment on lines +341 to 352

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Guard against zero-sized partial quotes.
If findLargestTradeSize returns 0n (or another non-positive sentinel), the retry will call getMarketPrice with amountIn=0n, which is likely invalid. Add a non‑positive guard to avoid unnecessary/erroneous calls.

🔧 Suggested fix
-        if (typeof partialAmountIn !== "bigint") {
+        if (typeof partialAmountIn !== "bigint" || partialAmountIn <= 0n) {
             return result;
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (typeof partialAmountIn !== "bigint") {
return result;
}
const partialResult = await this.router.getMarketPrice({
fromToken,
toToken,
blockNumber,
gasPrice: this.gasPrice,
amountIn: parseUnits("1", fromToken.decimals),
amountIn: partialAmountIn,
sushiRouteType: this.appOptions.route,
skipFetch: !!skipFetch,
});
if (typeof partialAmountIn !== "bigint" || partialAmountIn <= 0n) {
return result;
}
const partialResult = await this.router.getMarketPrice({
fromToken,
toToken,
blockNumber,
gasPrice: this.gasPrice,
amountIn: partialAmountIn,
sushiRouteType: this.appOptions.route,
skipFetch: !!skipFetch,
});
🤖 Prompt for AI Agents
In `@src/state/index.ts` around lines 341 - 352, The retry path currently treats
any non-bigint partialAmountIn as a guard but misses zero or negative bigints;
add a check for partialAmountIn <= 0n before calling this.router.getMarketPrice
and skip the retry (return result or handle as before) to avoid calling
getMarketPrice with amountIn=0n; locate the variable partialAmountIn (and the
call to this.router.getMarketPrice) and short-circuit when partialAmountIn is
not a positive bigint.

if (partialResult.isOk()) {
return partialResult;
}
return result;
}
}
Loading