Skip to content

Commit

Permalink
added additional validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Robiquet committed Feb 27, 2024
1 parent 26f4e27 commit fca7271
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/util/amm2.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import {
calculatePoolAmounts,
isValidBuyAmount,
isValidSellAmount,
calculateReserveAfterSell,
} from "./amm2";
import { ZTG } from "@zeitgeistpm/sdk";

// test cases copied from https://github.com/zeitgeistpm/zeitgeist/blob/f0586d32c692f738b04d03bec4e59a73d6899182/zrml/neo-swaps/src/math.rs
describe("amm2", () => {
Expand Down Expand Up @@ -225,6 +227,18 @@ describe("amm2", () => {
});
});

describe("calculateReserveAfterSell", () => {
test("should work", () => {
const newReserve = calculateReserveAfterSell(
new Decimal(10 * 10 ** 10),
new Decimal(10 * 10 ** 10),
new Decimal(144269504088),
);

expect(newReserve.div(ZTG).toFixed(3)).toEqual("15.850");
});
});

test("all functions", () => {
const liquidity = new Decimal(144.00003701590745);
const reserves = [
Expand Down
21 changes: 21 additions & 0 deletions lib/util/amm2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,32 @@ export const isValidSellAmount = (
return { isValid: false, message: "Price is low to sell" };
} else if (amountIn.greaterThanOrEqualTo(numericalThreshold)) {
return { isValid: false, message: "Amount in too high" };
} else if (
amountIn.greaterThanOrEqualTo(numericalThreshold) ||
calculateReserveAfterSell(
assetReserve,
amountIn,
liquidityParameter,
).greaterThanOrEqualTo(numericalThreshold)
) {
return { isValid: false, message: "Amount in too high" };
} else {
return { isValid: true };
}
};

export const calculateReserveAfterSell = (
assetReserve: Decimal,
amountIn: Decimal,
liquidity: Decimal, // liqudity parameter of the pool
) => {
// new_reserve = old_reserve + b ln(exp(old_reserve/liquidity_param) - 1 + exp(-amount/liquidity_param))
const term1 = assetReserve.div(liquidity).exp();
const term2 = new Decimal(0).minus(amountIn).div(liquidity).exp();

return term1.plus(term2).minus(1).ln().mul(liquidity).plus(assetReserve);
};

const lsmrConstant = 0.1;

const calculatePoolNumericalThreshold = (liquidityParameter: Decimal) =>
Expand Down

0 comments on commit fca7271

Please sign in to comment.