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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove expensive call to fetch tokens #268

Merged
merged 1 commit into from
Nov 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 24 additions & 12 deletions frontend/pages/api/getPythTokenBalance.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,37 @@
import { Connection, PublicKey } from '@solana/web3.js'
import { Connection, Keypair, PublicKey } from '@solana/web3.js'
import { PythBalance } from '@pythnetwork/staking'
import { BN } from 'bn.js'
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
Token,
} from '@solana/spl-token'

export const getPythTokenBalance = async (
connection: Connection,
publicKey: PublicKey,
pythTokenMint: PublicKey
) => {
let balance = new BN(0)
const mint = new Token(
connection,
pythTokenMint,
TOKEN_PROGRAM_ID,
new Keypair()
)

const pythAtaAddress = await Token.getAssociatedTokenAddress(
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
pythTokenMint,
publicKey
)

try {
const tokenAccounts = await connection.getTokenAccountsByOwner(publicKey, {
mint: pythTokenMint,
})
for (const account of tokenAccounts.value) {
const test = await connection.getTokenAccountBalance(account.pubkey)
balance.iadd(
new BN(test.value.amount) ? new BN(test.value.amount) : new BN(0)
)
}
const pythAtaAccountInfo = await mint.getAccountInfo(pythAtaAddress)
return new PythBalance(pythAtaAccountInfo.amount)
} catch (e) {
console.error(e)
}
return new PythBalance(balance)

return new PythBalance(new BN(0))
}
Loading