Skip to content

Instantly share code, notes, and snippets.

@mgild
Created November 20, 2022 14:27
Show Gist options
  • Select an option

  • Save mgild/df5932e2eb1618214c827ca8def3b179 to your computer and use it in GitHub Desktop.

Select an option

Save mgild/df5932e2eb1618214c827ca8def3b179 to your computer and use it in GitHub Desktop.
public async calculateSwapPrice(poolAddress: PublicKey): Promise<Big> {
// calculate swap for normal orca lp pool
try {
const [pool, poolParameters, tokenA, tokenB] = this.getPool(poolAddress);
const quote = await pool.getQuote(
tokenA,
new Decimal(1), // swap amount of tokenA to tokenB
new Decimal(0.5) // allowable slippage
);
const rate = quote.getRate();
return fromDecimal(rate);
} catch (error: any) {
if (!(error instanceof FailedToFindOrcaPool)) {
throw error;
}
}
// calculate swap for whirlpool
const pool = await this.whirlpool.getPool(poolAddress, true);
if (!pool) {
throw new Error(`Failed to find Orca LP Pool for ${poolAddress}`);
}
const poolData = pool.getData();
const tokenA: TokenInfo = pool.getTokenAInfo();
const tokenB: TokenInfo = pool.getTokenBInfo();
const price = PriceMath.sqrtPriceX64ToPrice(
poolData.sqrtPrice,
tokenA.decimals,
tokenB.decimals
);
return fromDecimal(price);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment