Skip to content
Open
Show file tree
Hide file tree
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
13 changes: 6 additions & 7 deletions app/components/account/TokenAccountSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Address } from '@components/common/Address';
import { Copyable } from '@components/common/Copyable';
import { useRefreshAccount } from '@entities/account';
import { isMetaplexNFT } from '@entities/nft';
import { fetchTokenInfoFromApi, getTokenInfoSwrKey } from '@entities/token-info';
import { fetchTokenInfoFromApi, getTokenInfoSwrKey, toScaledUiAmount } from '@entities/token-info';
import { AccountCard } from '@features/account';
import { isSome } from '@metaplex-foundation/umi';
import { Account, NFTData } from '@providers/accounts';
Expand Down Expand Up @@ -127,12 +127,11 @@ function FungibleTokenMintAccountCard({
value: (
<>
<span>
{normalizeTokenAmount(
Number(mintInfo.supply) * Number(scaledUiAmountMultiplier),
mintInfo.decimals,
).toLocaleString('en-US', {
maximumFractionDigits: 20,
})}
{toScaledUiAmount({
decimals: mintInfo.decimals,
multiplier: scaledUiAmountMultiplier,
rawAmount: mintInfo.supply,
}).toFormat()}
</span>
<ScaledUiAmountMultiplierTooltip
rawAmount={normalizeTokenAmount(Number(mintInfo.supply), mintInfo.decimals).toString()}
Expand Down
86 changes: 37 additions & 49 deletions app/components/account/history/TokenTransfersCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,17 @@ import { ErrorCard } from '@components/common/ErrorCard';
import { LoadingCard } from '@components/common/LoadingCard';
import { Signature } from '@components/common/Signature';
import { TokenInstructionType, Transfer, TransferChecked } from '@components/instruction/token/types';
import { fetchTokenInfoFromApi, getTokenInfoSwrKey } from '@entities/token-info';
import { fetchTokenInfoFromApi, getTokenInfoSwrKey, toScaledUiAmount } from '@entities/token-info';
import { type TransactionWithMeta } from '@entities/transaction-data';
import { useFetchAccountHistory } from '@features/transaction-history/model/use-fetch-account-history';
import { isTokenProgramData, useAccountHistory } from '@providers/accounts';
import { toScaledUiAmountString, useScaledUiAmountMultiplier } from '@providers/accounts/tokens';
import { getAmountMultiplier, useScaledUiAmountMultiplier } from '@providers/accounts/tokens';
import { FetchStatus } from '@providers/cache';
import { useCluster } from '@providers/cluster';
import { HistoryCardFooterContent } from '@shared/ui/HistoryCard';
import { address as toAddress } from '@solana/kit';
import { ParsedInstruction, PartiallyDecodedInstruction, PublicKey } from '@solana/web3.js';
import { Cluster } from '@utils/cluster';
import { normalizeTokenAmount } from '@utils/index';
import { InstructionContainer } from '@utils/instruction';
import React, { useMemo } from 'react';
import { create } from 'superstruct';
Expand All @@ -38,39 +37,39 @@ type IndexedTransfer = {
transfer: Transfer | TransferChecked;
};

type TransferData = {
amountString: string;
type RawAmount = { decimals: number; rawAmount: string | number };

type TransferData = RawAmount & {
blockTime: number | undefined;
childIndex?: number;
index: number;
signature: string;
statusClass: string;
statusText: string;
transfer: Transfer | TransferChecked;
units: string;
};

async function fetchTokenInfo([_, address, cluster, url]: ['get-token-info', string, Cluster, string]) {
return await fetchTokenInfoFromApi(new PublicKey(address), cluster, url);
}

function AmountCell({
amountString,
decimals,
rawAmount,
tokenAddress,
units,
}: {
amountString: string;
}: RawAmount & {
tokenAddress: string;
units: string;
}) {
const scaledUiAmountMultiplier = useScaledUiAmountMultiplier(tokenAddress);
const scaledAmount = toScaledUiAmountString(amountString, scaledUiAmountMultiplier);
const multiplier = getAmountMultiplier(scaledUiAmountMultiplier);

return (
<>
{scaledAmount} {units}
{toScaledUiAmount({ decimals, multiplier, rawAmount }).toFixed()} {units}
<ScaledUiAmountMultiplierTooltip
rawAmount={amountString}
rawAmount={toScaledUiAmount({ decimals, multiplier: '1', rawAmount }).toFixed()}
scaledUiAmountMultiplier={scaledUiAmountMultiplier}
/>
</>
Expand Down Expand Up @@ -153,48 +152,15 @@ export function TokenTransfersCard({ address }: { address: string }) {
});

transfers.forEach(({ transfer, index, childIndex }) => {
let units = 'Tokens';
let amountString = '';

// Loading token info, just don't show units
if (tokenInfoLoading) {
units = '';
}

// Loaded symbol, use it
if (tokenInfo?.symbol) {
units = tokenInfo.symbol;
}

if ('tokenAmount' in transfer) {
amountString = transfer.tokenAmount.uiAmountString;
} else {
let decimals = 0;

if (tokenInfo?.decimals) {
decimals = tokenInfo.decimals;
} else if (mintMap.has(transfer.source.toBase58())) {
decimals = mintMap.get(transfer.source.toBase58())?.decimals || 0;
} else if (mintMap.has(transfer.destination.toBase58())) {
decimals = mintMap.get(transfer.destination.toBase58())?.decimals || 0;
}

amountString = new Intl.NumberFormat('en-US', {
maximumFractionDigits: decimals,
minimumFractionDigits: decimals,
}).format(normalizeTokenAmount(transfer.amount, decimals));
}

allTransfers.push({
amountString,
...getRawAmount({ mintMap, tokenInfoDecimals: tokenInfo?.decimals, transfer }),
blockTime: blockTime || undefined,
childIndex,
index,
signature,
statusClass,
statusText,
transfer,
units,
});
});
});
Expand All @@ -203,7 +169,7 @@ export function TokenTransfersCard({ address }: { address: string }) {
allTransfers,
hasTimestamps,
};
}, [history, transactionRows, tokenInfo, pubkey, address, cluster, tokenInfoLoading]);
}, [history, transactionRows, tokenInfo, pubkey, address, cluster]);

if (!history) {
return null;
Expand All @@ -219,6 +185,7 @@ export function TokenTransfersCard({ address }: { address: string }) {

const fetching = history.status === FetchStatus.Fetching;
const tokenAddress = pubkey.toBase58();
const units = tokenInfo?.symbol || (tokenInfoLoading ? '' : 'Tokens');

const columns: GridTableColumn<TransferData>[] = [
{
Expand All @@ -239,8 +206,8 @@ export function TokenTransfersCard({ address }: { address: string }) {
{
cell: { wrap: 'nowrap' },
header: 'Amount',
render: ({ amountString, units }) => (
<AmountCell amountString={amountString} tokenAddress={tokenAddress} units={units} />
render: ({ decimals, rawAmount }) => (
<AmountCell decimals={decimals} rawAmount={rawAmount} tokenAddress={tokenAddress} units={units} />
),
},
{
Expand Down Expand Up @@ -299,6 +266,27 @@ export function TokenTransfersCard({ address }: { address: string }) {
);
}

// A `transfer` instruction holds no decimals, so they come from the token info or from a token balance.
function getRawAmount({
transfer,
tokenInfoDecimals,
mintMap,
}: {
transfer: Transfer | TransferChecked;
tokenInfoDecimals: number | null | undefined;
mintMap: Map<string, MintDetails>;
}): RawAmount {
if ('tokenAmount' in transfer) {
return { decimals: transfer.tokenAmount.decimals, rawAmount: transfer.tokenAmount.amount };
}
const decimals =
tokenInfoDecimals ||
mintMap.get(transfer.source.toBase58())?.decimals ||
mintMap.get(transfer.destination.toBase58())?.decimals ||
0;
return { decimals, rawAmount: transfer.amount };
}

function getTransfer(
instruction: ParsedInstruction | PartiallyDecodedInstruction,
cluster: Cluster,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { type TransactionWithMeta } from '@entities/transaction-data';
import { FetchStatus } from '@providers/cache';
import { PublicKey } from '@solana/web3.js';
import { render, waitFor } from '@testing-library/react';
import { Cluster } from '@utils/cluster';
import { describe, expect, it, vi } from 'vitest';

import { TokenTransfersCard } from '../TokenTransfersCard';

const MINT = 'XsoCS1TfEyfFhfvj8EtZ528L3CaKBDBRqRapnBbDF2W';
const SOURCE = 'GsbwXfJraMomNxBcpR3DBr9yoWR2PmN93PEaYJz7MSTN';
const DESTINATION = '9noXzpXnkyEcKF3AeXqUHTdR59V5uvrRBUZ9bwfQwxNq';
const SIGNATURE = 'signature';

const mocks = vi.hoisted(() => ({ history: undefined as unknown }));

vi.mock('@providers/accounts', async importOriginal => ({
...(await importOriginal<typeof import('@providers/accounts')>()),
useAccountHistory: () => mocks.history,
}));
vi.mock('@features/transaction-history/model/use-fetch-account-history', () => ({
useFetchAccountHistory: () => vi.fn(),
}));
vi.mock('@providers/cluster', () => ({ useCluster: () => ({ cluster: Cluster.Mainnet, url: 'http://rpc' }) }));
vi.mock('@providers/accounts/tokens', async importOriginal => ({
...(await importOriginal<typeof import('@providers/accounts/tokens')>()),
useScaledUiAmountMultiplier: () => ({ multiplier: '1.007474126658766', status: 'known' }),
}));
vi.mock('@entities/token-info', async importOriginal => ({
...(await importOriginal<typeof import('@entities/token-info')>()),
fetchTokenInfoFromApi: () => Promise.resolve(undefined),
}));
vi.mock('@components/common/Address', () => ({ Address: () => <span>address</span> }));
vi.mock('@components/common/Signature', () => ({ Signature: () => <span>signature</span> }));
vi.mock('@components/account/token-extensions/ScaledUiAmountMultiplierTooltip', () => ({ default: () => null }));
vi.mock('@/app/components/shared/ui/refresh-button', () => ({ RefreshButton: () => null }));

describe('TokenTransfersCard amounts', () => {
it('should scale the amount of a transfer with the decimals of a token balance', async () => {
mocks.history = toHistory({
parsed: { info: { amount: '123450000000', destination: DESTINATION, source: SOURCE }, type: 'transfer' },
});

const { container } = render(<TokenTransfersCard address={MINT} />);

await waitFor(() => expect(container.textContent).toContain('1243.72680936 Tokens'));
});

it('should scale the raw amount of a transferChecked, not the UI amount', async () => {
mocks.history = toHistory({
parsed: {
info: {
destination: DESTINATION,
mint: MINT,
source: SOURCE,
tokenAmount: { amount: '250000000', decimals: 8, uiAmountString: '2.5' },
},
type: 'transferChecked',
},
});

const { container } = render(<TokenTransfersCard address={MINT} />);

await waitFor(() => expect(container.textContent).toContain('2.51868531 Tokens'));
});
});

function toHistory(instruction: { parsed: unknown }) {
const transactionWithMeta = {
meta: {
postTokenBalances: [{ accountIndex: 0, mint: MINT, uiTokenAmount: { amount: '0', decimals: 8 } }],
},
transaction: {
message: {
accountKeys: [{ pubkey: new PublicKey(SOURCE) }],
instructions: [{ ...instruction, program: 'spl-token', programId: PublicKey.default }],
},
},
} as unknown as TransactionWithMeta;

return {
data: {
fetched: [{ blockTime: null, err: null, signature: SIGNATURE, slot: 1 }],
foundOldest: true,
transactionMap: new Map([[SIGNATURE, transactionWithMeta]]),
},
status: FetchStatus.Fetched,
};
}
4 changes: 2 additions & 2 deletions app/entities/token-amount/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export { formatTokenAmount, tokenAmountToFiat, tokenAmountToNumber } from './lib/format';
export { formatTokenAmount, tokenAmountToFiat } from './lib/format';
export type { FormatOptions } from './lib/format';
export type { TokenAmount } from './lib/types';
export type { RawTokenBalance, TokenAmount } from './lib/types';
9 changes: 9 additions & 0 deletions app/entities/token-amount/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,12 @@ export type TokenAmount = {
amount: bigint | number;
decimals: number;
};

// An account read adjusts `uiAmountString` for the mint extensions and a transaction does not, so
// a balance holds the raw amount only.
export type RawTokenBalance = {
accountIndex: number;
mint: string;
owner?: string;
uiTokenAmount: { amount: string; decimals: number };
};
1 change: 1 addition & 0 deletions app/entities/token-info/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export { fetchTokenInfoFromApi, fetchTokenInfosFromApi, getTokenInfoSwrKey } fro
export { deriveScaledUiAmountMultiplier } from './lib/derive-scaled-ui-multiplier';
export { TokenInfoHttpError, TokenInfoInvalidResponseError } from './lib/errors';
export { orderMintsByVerification } from './lib/order-mints-by-verification';
export { toScaledUiAmount } from './lib/to-scaled-ui-amount';
export { getChainId } from '@entities/chain-id/@x/token-info';
export type { FetchConfig, TokenInfo } from './lib/types';
export { TokenInfoBatchProvider, useTokenInfoBatch } from './model/token-info-batch-provider';
Expand Down
23 changes: 23 additions & 0 deletions app/entities/token-info/lib/__tests__/to-scaled-ui-amount.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';

import { toScaledUiAmount } from '../to-scaled-ui-amount';

describe('toScaledUiAmount', () => {
it('should truncate a scaled amount to the decimals of the mint', () => {
const uiAmount = toScaledUiAmount({ decimals: 8, multiplier: '1.007474126658766', rawAmount: '23532095161' });

expect(uiAmount.toFixed()).toBe('237.0797702');
});

it('should multiply as an f64, not as an exact decimal', () => {
const uiAmount = toScaledUiAmount({ decimals: 8, multiplier: '1.007474126658766', rawAmount: '6047425270080' });

expect(uiAmount.toFixed()).toBe('60926.24492507');
});

it('should keep every digit of an amount above 2^53 that has no multiplier', () => {
const uiAmount = toScaledUiAmount({ decimals: 9, multiplier: '1', rawAmount: '18446744073709551615' });

expect(uiAmount.toFixed()).toBe('18446744073.709551615');
});
});
19 changes: 19 additions & 0 deletions app/entities/token-info/lib/to-scaled-ui-amount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { BigNumber } from 'bignumber.js';

// The token program scales with an f64 product that it truncates toward zero. Exact decimal
// arithmetic would differ from the amount that the RPC returns.
export function toScaledUiAmount({
rawAmount,
decimals,
multiplier,
}: {
rawAmount: string | number;
decimals: number;
multiplier: string;
}): BigNumber {
const scaledRawAmount =
multiplier === '1'
? new BigNumber(rawAmount)
: new BigNumber(Math.trunc(Number(rawAmount) * Number(multiplier)));
return scaledRawAmount.shiftedBy(-decimals);
}
Loading