Skip to content

Commit f8ffc4d

Browse files
committed
get the decimal value from the blockchain
Signed-off-by: MarcoMandar <malicemandar@gmail.com>
1 parent 9b6479a commit f8ffc4d

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

core/src/actions/swapDao.ts

+29-1
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,40 @@ import {
77
type Action,
88
} from "../core/types.ts";
99

10+
async function getTokenDecimals(
11+
connection: Connection,
12+
mintAddress: string
13+
): Promise<number> {
14+
const mintPublicKey = new PublicKey(mintAddress);
15+
const tokenAccountInfo =
16+
await connection.getParsedAccountInfo(mintPublicKey);
17+
18+
// Check if the data is parsed and contains the expected structure
19+
if (
20+
tokenAccountInfo.value &&
21+
typeof tokenAccountInfo.value.data === "object" &&
22+
"parsed" in tokenAccountInfo.value.data
23+
) {
24+
const parsedInfo = tokenAccountInfo.value.data.parsed?.info;
25+
if (parsedInfo && typeof parsedInfo.decimals === "number") {
26+
return parsedInfo.decimals;
27+
}
28+
}
29+
30+
throw new Error("Unable to fetch token decimals");
31+
}
32+
1033
async function getQuote(
34+
connection: Connection,
1135
baseToken: string,
1236
outputToken: string,
1337
amount: number
1438
): Promise<any> {
39+
const decimals = await getTokenDecimals(connection, baseToken);
40+
const adjustedAmount = amount * 10 ** decimals;
41+
1542
const quoteResponse = await fetch(
16-
`https://quote-api.jup.ag/v6/quote?inputMint=${baseToken}&outputMint=${outputToken}&amount=${amount * 10 ** 6}&slippageBps=50`
43+
`https://quote-api.jup.ag/v6/quote?inputMint=${baseToken}&outputMint=${outputToken}&amount=${adjustedAmount}&slippageBps=50`
1744
);
1845
const swapTransaction = await quoteResponse.json();
1946
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
@@ -100,6 +127,7 @@ export const executeSwap: Action = {
100127
);
101128

102129
const quoteData = await getQuote(
130+
connection as Connection,
103131
inputToken as string,
104132
outputToken as string,
105133
amount as number

0 commit comments

Comments
 (0)