Skip to content

Commit b1becba

Browse files
committed
feat: add get usdc balance
1 parent d709947 commit b1becba

File tree

1 file changed

+44
-5
lines changed

1 file changed

+44
-5
lines changed

src/solana/SolanaManager.ts

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,19 @@ export class SolanaManager {
6464
return this.#signer
6565
}
6666

67+
/**
68+
* Get account info for a given address
69+
* @param address - The public key or address string
70+
*/
71+
accountInfo(address: PublicKey | string) {
72+
const pubkey = typeof address === 'string' ? new PublicKey(address) : address
73+
const addressStr = pubkey.toBase58()
74+
75+
return this._query(['solana', 'accountInfo', addressStr], () => {
76+
return this.#client.getAccountInfo(pubkey)
77+
})
78+
}
79+
6780
/**
6881
* Get the balance of a Solana account in lamports
6982
* @param address - The public key or address string
@@ -78,15 +91,41 @@ export class SolanaManager {
7891
}
7992

8093
/**
81-
* Get account info for a given address
82-
* @param address - The public key or address string
94+
* Get the USDC balance for a given Solana wallet address
95+
* Returns the balance as a Balance object
96+
* @param address - The wallet's public key or address string
97+
* @returns Observable that emits the USDC balance
8398
*/
84-
accountInfo(address: PublicKey | string) {
99+
usdcBalance(address: PublicKey | string) {
85100
const pubkey = typeof address === 'string' ? new PublicKey(address) : address
86101
const addressStr = pubkey.toBase58()
87102

88-
return this._query(['solana', 'accountInfo', addressStr], () => {
89-
return this.#client.getAccountInfo(pubkey)
103+
return this._query(['solana', 'usdcBalance', addressStr], () => {
104+
return new Observable<Balance>((subscriber) => {
105+
;(async () => {
106+
try {
107+
const environment = this.#root.config.environment
108+
const usdcMint = new PublicKey(getUsdcMintAddress(environment))
109+
const tokenAccount = await getAssociatedTokenAddress(usdcMint, pubkey)
110+
111+
const accountInfo = await this.connection.getTokenAccountBalance(tokenAccount)
112+
const balance = new Balance(BigInt(accountInfo.value.amount), 6)
113+
114+
subscriber.next(balance)
115+
subscriber.complete()
116+
} catch (error) {
117+
if (error && typeof error === 'object' && 'message' in error) {
118+
const errorMessage = (error as Error).message
119+
if (errorMessage.includes('could not find account') || errorMessage.includes('Invalid param')) {
120+
subscriber.next(new Balance(0n, 6))
121+
subscriber.complete()
122+
return
123+
}
124+
}
125+
subscriber.error(error)
126+
}
127+
})()
128+
})
90129
})
91130
}
92131

0 commit comments

Comments
 (0)