Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper to get the swap price #216

Merged
merged 1 commit into from Aug 29, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/stableswap-sdk/src/calculator/index.ts
@@ -1,2 +1,3 @@
export * from "./amounts";
export * from "./curve";
export * from "./price";
44 changes: 44 additions & 0 deletions packages/stableswap-sdk/src/calculator/price.ts
@@ -0,0 +1,44 @@
import { Price, TokenAmount } from "@saberhq/token-utils";
import BN from "bn.js";

import type { IExchangeInfo } from "..";
import { calculateEstimatedSwapOutputAmount } from "..";

/**
* Gets the price of the second token in the swap, i.e. "Token 1", with respect to "Token 0".
*
* To get the price of "Token 0", use `.invert()` on the result of this function.
* @returns
*/
export const calculateSwapPrice = (exchangeInfo: IExchangeInfo): Price => {
const reserve0 = exchangeInfo.reserves[0].amount;
const reserve1 = exchangeInfo.reserves[1].amount;

// We try to get at least 4 decimal points of precision here
// Otherwise, we attempt to swap 1% of total supply of the pool
// or at most, $1
const inputAmountNum = Math.max(
10_000,
Math.min(
10 ** reserve0.token.decimals,
Math.floor(parseInt(reserve0.toU64().div(new BN(100)).toString()))
)
);

const inputAmount = new TokenAmount(reserve0.token, inputAmountNum);
const outputAmount = calculateEstimatedSwapOutputAmount(
exchangeInfo,
inputAmount
);

const frac = outputAmount.outputAmountBeforeFees.asFraction.divide(
inputAmount.asFraction
);

return new Price(
reserve0.token,
reserve1.token,
frac.denominator,
frac.numerator
);
};