Skip to content

Commit

Permalink
Remove expensive call to fetch tokens (#268)
Browse files Browse the repository at this point in the history
  • Loading branch information
guibescos authored Nov 14, 2023
1 parent b59be91 commit dcacb3c
Showing 1 changed file with 24 additions and 12 deletions.
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))
}

2 comments on commit dcacb3c

@vercel
Copy link

@vercel vercel bot commented on dcacb3c Nov 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

staking-devnet – ./

staking-devnet-git-main-pyth-web.vercel.app
governance-nu.vercel.app
staking-devnet-pyth-web.vercel.app

@vercel
Copy link

@vercel vercel bot commented on dcacb3c Nov 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.