Skip to content

Commit dcacb3c

Browse files
authored
Remove expensive call to fetch tokens (#268)
1 parent b59be91 commit dcacb3c

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed
Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,37 @@
1-
import { Connection, PublicKey } from '@solana/web3.js'
1+
import { Connection, Keypair, PublicKey } from '@solana/web3.js'
22
import { PythBalance } from '@pythnetwork/staking'
33
import { BN } from 'bn.js'
4+
import {
5+
ASSOCIATED_TOKEN_PROGRAM_ID,
6+
TOKEN_PROGRAM_ID,
7+
Token,
8+
} from '@solana/spl-token'
49

510
export const getPythTokenBalance = async (
611
connection: Connection,
712
publicKey: PublicKey,
813
pythTokenMint: PublicKey
914
) => {
10-
let balance = new BN(0)
15+
const mint = new Token(
16+
connection,
17+
pythTokenMint,
18+
TOKEN_PROGRAM_ID,
19+
new Keypair()
20+
)
21+
22+
const pythAtaAddress = await Token.getAssociatedTokenAddress(
23+
ASSOCIATED_TOKEN_PROGRAM_ID,
24+
TOKEN_PROGRAM_ID,
25+
pythTokenMint,
26+
publicKey
27+
)
28+
1129
try {
12-
const tokenAccounts = await connection.getTokenAccountsByOwner(publicKey, {
13-
mint: pythTokenMint,
14-
})
15-
for (const account of tokenAccounts.value) {
16-
const test = await connection.getTokenAccountBalance(account.pubkey)
17-
balance.iadd(
18-
new BN(test.value.amount) ? new BN(test.value.amount) : new BN(0)
19-
)
20-
}
30+
const pythAtaAccountInfo = await mint.getAccountInfo(pythAtaAddress)
31+
return new PythBalance(pythAtaAccountInfo.amount)
2132
} catch (e) {
2233
console.error(e)
2334
}
24-
return new PythBalance(balance)
35+
36+
return new PythBalance(new BN(0))
2537
}

0 commit comments

Comments
 (0)