Skip to content

Commit

Permalink
fix: querying balances for Solana
Browse files Browse the repository at this point in the history
  • Loading branch information
fadeev committed Dec 13, 2024
1 parent c11f0c4 commit 06f3a89
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions packages/client/src/getBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ export const getBalances = async function (
symbol: token.symbol,
zrc20: token.zrc20_contract_address,
});
} else if (supportedChain.vm === "svm") {
tokens.push({
chain_id: token.foreign_chain_id,
coin_type: "SPL",
contract: token.asset,
symbol: token.symbol,
zrc20: token.zrc20_contract_address,
});
}
tokens.push({
chain_id: this.getChainId(`zeta_${this.network}`),
Expand Down Expand Up @@ -307,5 +315,65 @@ export const getBalances = async function (
})
);

// Solana SPL token balances
if (solanaAddress) {
const splTokens = tokens.filter((token) => token.coin_type === "SPL");

await Promise.all(
splTokens.map(async (token) => {
try {
const API = this.getEndpoint("solana", token.chain_name);
// Use getTokenAccountsByOwner to find token accounts for this mint
const response = await fetch(API, {
body: JSON.stringify({
id: 1,
jsonrpc: "2.0",
method: "getTokenAccountsByOwner",
params: [
solanaAddress,
{ mint: token.contract },
{
encoding: "jsonParsed",
},
],
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});

if (!response.ok) {
console.error(
`Failed to fetch SPL token accounts for ${token.symbol}`,
response
);
return;
}

const r = await response.json();
if (r.result && r.result.value && r.result.value.length > 0) {
let totalBalance = 0;
for (const acc of r.result.value) {
const amount = acc.account.data.parsed.info.tokenAmount.amount;
const decimals =
acc.account.data.parsed.info.tokenAmount.decimals;
totalBalance += parseFloat(amount) / Math.pow(10, decimals);
}
balances.push({ ...token, balance: totalBalance.toString() });
} else {
// No token accounts found, balance is 0
balances.push({ ...token, balance: "0" });
}
} catch (err) {
console.error(
`Failed to get SPL balance for ${token.symbol} on ${token.chain_name}:`,
err
);
}
})
);
}

return balances;
};

0 comments on commit 06f3a89

Please sign in to comment.