Handle token accounts with invalid mints

This commit is contained in:
Gary Wang 2020-08-05 21:40:42 -07:00
parent a515840db1
commit 9643de889b
2 changed files with 46 additions and 12 deletions

View File

@ -5,6 +5,10 @@ export const TOKEN_PROGRAM_ID = new PublicKey(
'TokenSVp5gheXUvJ6jGWGeCsgPKgnE3YgdGKRVCMY9o', 'TokenSVp5gheXUvJ6jGWGeCsgPKgnE3YgdGKRVCMY9o',
); );
export const WRAPPED_SOL_MINT = new PublicKey(
'So11111111111111111111111111111111111111111',
);
const LAYOUT = BufferLayout.union(BufferLayout.u8('instruction')); const LAYOUT = BufferLayout.union(BufferLayout.u8('instruction'));
LAYOUT.addVariant( LAYOUT.addVariant(
0, 0,

View File

@ -12,7 +12,7 @@ import {
getOwnedTokenAccounts, getOwnedTokenAccounts,
transferTokens, transferTokens,
} from './tokens'; } from './tokens';
import { TOKEN_PROGRAM_ID } from './tokens/instructions'; import { TOKEN_PROGRAM_ID, WRAPPED_SOL_MINT } from './tokens/instructions';
import { import {
ACCOUNT_LAYOUT, ACCOUNT_LAYOUT,
parseMintData, parseMintData,
@ -142,30 +142,60 @@ export function useBalanceInfo(publicKey) {
let [mintInfo, mintInfoLoaded] = useAccountInfo(mint); let [mintInfo, mintInfoLoaded] = useAccountInfo(mint);
let { name, symbol } = useTokenName(mint); let { name, symbol } = useTokenName(mint);
if (accountInfoLoaded && mint && mintInfoLoaded) { if (!accountInfoLoaded) {
let { decimals } = parseMintData(mintInfo.data); return null;
}
if (mint && mint.equals(WRAPPED_SOL_MINT)) {
return { return {
amount, amount,
decimals, decimals: 9,
mint, mint,
owner, owner,
tokenName: name, tokenName: 'Wrapped SOL',
tokenSymbol: symbol, tokenSymbol: 'SOL',
initialized: true, valid: true,
}; };
} else if (accountInfoLoaded && !mint) { }
if (mint && mintInfoLoaded) {
try {
let { decimals } = parseMintData(mintInfo.data);
return {
amount,
decimals,
mint,
owner,
tokenName: name,
tokenSymbol: symbol,
valid: true,
};
} catch (e) {
return {
amount,
decimals: 0,
mint,
owner,
tokenName: 'Invalid',
tokenSymbol: 'INVALID',
valid: false,
};
}
}
if (!mint) {
return { return {
amount: accountInfo?.lamports ?? 0, amount: accountInfo?.lamports ?? 0,
decimals: 9, decimals: 9,
mint: null, mint: null,
owner: publicKey, owner: publicKey,
tokenName: 'Solana', tokenName: 'SOL',
tokenSymbol: 'SOL', tokenSymbol: 'SOL',
initialized: false, valid: true,
}; };
} else {
return null;
} }
return null;
} }
export function useWalletSelector() { export function useWalletSelector() {