Skip to content

Commit

Permalink
fix: perform more precise sqrt on bignumbers in FluidDex
Browse files Browse the repository at this point in the history
  • Loading branch information
KanievskyiDanylo committed Oct 30, 2024
1 parent 28ad697 commit 631cd72
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
17 changes: 7 additions & 10 deletions src/dex/fluid-dex/fluid-dex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { extractReturnAmountPosition } from '../../executor/utils';
import { MultiResult } from '../../lib/multi-wrapper';
import { generalDecoder } from '../../lib/decoders';
import { BigNumber } from 'ethers';
import { sqrt } from './utils';

export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
eventPools: { [id: string]: FluidDexEventPool } = {};
Expand Down Expand Up @@ -610,18 +611,14 @@ export class FluidDex extends SimpleExchange implements IDex<FluidDexData> {
): bigint {
// Adding 1e18 precision

const xyRoot = BigInt(Math.floor(Math.sqrt(Number(x * y * BigInt(1e18)))));
const x2y2Root = BigInt(
Math.floor(Math.sqrt(Number(x2 * y2 * BigInt(1e18)))),
);
const xyRoot = sqrt(BigNumber.from(x).mul(y).mul(BigInt(1e18))).toBigInt();
const x2y2Root = sqrt(
BigNumber.from(x2).mul(y2).mul(BigInt(1e18)),
).toBigInt();

// Calculating 'a' using the given formula
const a =
(Number(y2) * Number(xyRoot) +
Number(t) * Number(xyRoot) -
Number(y) * Number(x2y2Root)) /
(Number(xyRoot) + Number(x2y2Root));
return BigInt(Math.floor(a));
const a = (y2 * xyRoot + t * xyRoot - y * x2y2Root) / (xyRoot + x2y2Root);
return a;
}

/**
Expand Down
15 changes: 15 additions & 0 deletions src/dex/fluid-dex/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { BigNumber } from 'ethers';

const ONE = BigNumber.from(1);
const TWO = BigNumber.from(2);

export function sqrt(value: BigNumber) {
let x = value;
let z = x.add(ONE).div(TWO);
let y = x;
while (z.sub(y).isNegative()) {
y = z;
z = x.div(z).add(z).div(TWO);
}
return y;
}

0 comments on commit 631cd72

Please sign in to comment.