Skip to content

Commit

Permalink
feat: fetch token prices at runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
genaroibc committed Nov 2, 2023
1 parent 017040e commit 850f792
Showing 1 changed file with 31 additions and 4 deletions.
35 changes: 31 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,21 @@ export class Squid extends TokensChains {
return this.handlers.evm.getRawTxHex({ ...data });
}

public getFromAmount({
public async getTokenPrice({
tokenAddress,
chainId
}: {
tokenAddress: string;
chainId: string | number;
}) {
const response = await this.httpInstance.axios.get("/v2/token-price", {
params: { tokenAddress, chainId }
});

return response.data.token.usdPrice;
}

public async getFromAmount({
fromToken,
toAmount,
toToken,
Expand All @@ -235,9 +249,22 @@ export class Squid extends TokensChains {
toToken: Token;
toAmount: string;
slippagePercentage?: number;
}): string {
const toTokenPrice = Number(toToken.usdPrice ?? 0);
const fromTokenPrice = Number(fromToken.usdPrice ?? 0);
}): Promise<string> {
// if there is an error getting real-time prices,
// use the price at the time of initialization
const [
fromTokenPrice = fromToken.usdPrice,
toTokenPrice = toToken.usdPrice
] = await Promise.all([
this.getTokenPrice({
chainId: fromToken.chainId,
tokenAddress: fromToken.address
}),
this.getTokenPrice({
chainId: toToken.chainId,
tokenAddress: toToken.address
})
]);

// example fromAmount: 10
const fromAmount = (toTokenPrice * Number(toAmount ?? 0)) / fromTokenPrice;
Expand Down

0 comments on commit 850f792

Please sign in to comment.