Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
31 changes: 24 additions & 7 deletions app/components/account/history/TokenTransfersCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ 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';
Expand Down Expand Up @@ -42,7 +42,9 @@ type TransferData = {
amountString: string;
blockTime: number | undefined;
childIndex?: number;
decimals: number;
index: number;
rawAmount: string | number;
signature: string;
statusClass: string;
statusText: string;
Expand All @@ -56,15 +58,22 @@ async function fetchTokenInfo([_, address, cluster, url]: ['get-token-info', str

function AmountCell({
amountString,
decimals,
rawAmount,
tokenAddress,
units,
}: {
amountString: string;
decimals: number;
rawAmount: string | number;
tokenAddress: string;
units: string;
}) {
const scaledUiAmountMultiplier = useScaledUiAmountMultiplier(tokenAddress);
const scaledAmount = toScaledUiAmountString(amountString, scaledUiAmountMultiplier);
const multiplier = getAmountMultiplier(scaledUiAmountMultiplier);
// The formatted amount can hold a thousands separator, so an amount with no multiplier keeps it.
const scaledAmount =
multiplier === '1' ? amountString : toScaledUiAmount({ decimals, multiplier, rawAmount }).toFixed();

return (
<>
Expand Down Expand Up @@ -155,6 +164,7 @@ export function TokenTransfersCard({ address }: { address: string }) {
transfers.forEach(({ transfer, index, childIndex }) => {
let units = 'Tokens';
let amountString = '';
let decimals = 0;

// Loading token info, just don't show units
if (tokenInfoLoading) {
Expand All @@ -168,9 +178,8 @@ export function TokenTransfersCard({ address }: { address: string }) {

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

if (tokenInfo?.decimals) {
decimals = tokenInfo.decimals;
} else if (mintMap.has(transfer.source.toBase58())) {
Expand All @@ -189,7 +198,9 @@ export function TokenTransfersCard({ address }: { address: string }) {
amountString,
blockTime: blockTime || undefined,
childIndex,
decimals,
index,
rawAmount: 'tokenAmount' in transfer ? transfer.tokenAmount.amount : transfer.amount,
signature,
statusClass,
statusText,
Expand Down Expand Up @@ -239,8 +250,14 @@ export function TokenTransfersCard({ address }: { address: string }) {
{
cell: { wrap: 'nowrap' },
header: 'Amount',
render: ({ amountString, units }) => (
<AmountCell amountString={amountString} tokenAddress={tokenAddress} units={units} />
render: ({ amountString, decimals, rawAmount, units }) => (
<AmountCell
amountString={amountString}
decimals={decimals}
rawAmount={rawAmount}
tokenAddress={tokenAddress}
units={units}
/>
),
},
{
Expand Down
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
18 changes: 18 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,18 @@
import { describe, expect, it } from 'vitest';

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

describe('toScaledUiAmount', () => {
// Raw amount and UI amount of a mainnet token account. Rounding half up gives 237.07977021.
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 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');
});
});
20 changes: 20 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,20 @@
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 {
// An f64 product rounds a raw amount above 2^53, so an amount with no multiplier stays exact.
const scaledRawAmount =
multiplier === '1'
? new BigNumber(rawAmount)
: new BigNumber(Math.trunc(Number(rawAmount) * Number(multiplier)));
return scaledRawAmount.shiftedBy(-decimals);
}
76 changes: 25 additions & 51 deletions app/features/transaction/ui/TokenBalancesCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import ScaledUiAmountMultiplierTooltip from '@components/account/token-extension
import { Address } from '@components/common/Address';
import { BalanceDelta } from '@components/common/BalanceDelta';
import { cn } from '@components/shared/utils';
import { fetchTokenInfosFromApi, getChainId } from '@entities/token-info';
import { fetchTokenInfosFromApi, getChainId, toScaledUiAmount } from '@entities/token-info';
import { useTransactionDetails } from '@providers/transactions';
import { invariant } from '@shared/lib/invariant';
import { ParsedMessageAccount, PublicKey, TokenBalance } from '@solana/web3.js';
import { Cluster } from '@utils/cluster';
import { SignatureProps } from '@utils/index';
import { BigNumber } from 'bignumber.js';
import useSWRImmutable from 'swr/immutable';

import { getAmountMultiplier, useScaledUiAmountMultiplier } from '@/app/providers/accounts/tokens';
Expand All @@ -22,8 +21,9 @@ type TokenBalanceRow = {
account: PublicKey;
owner?: string;
mint: string;
balance: string;
delta: BigNumber;
preAmount: string;
postAmount: string;
decimals: number;
accountIndex: number;
};

Expand Down Expand Up @@ -75,8 +75,9 @@ export function TokenBalancesCardInner({ rows }: TokenBalancesCardInnerProps) {
key={row.account.toBase58() + row.mint}
account={row.account}
owner={row.owner}
delta={row.delta}
balance={row.balance}
preAmount={row.preAmount}
postAmount={row.postAmount}
decimals={row.decimals}
mint={row.mint}
units={tokenSymbols?.get(row.mint) || 'tokens'}
/>
Expand Down Expand Up @@ -104,24 +105,26 @@ async function fetchTokenSymbols([, mintKey, cluster, genesisHash]: TokenSymbols
function TokenBalanceRow({
account,
owner,
delta,
balance,
preAmount,
postAmount,
decimals,
mint,
units,
index,
}: {
account: PublicKey;
owner?: string;
delta: BigNumber;
balance: string;
preAmount: string;
postAmount: string;
decimals: number;
mint: string;
units: string;
index: number;
}) {
const scaledUiAmountMultiplier = useScaledUiAmountMultiplier(mint);
const multiplier = getAmountMultiplier(scaledUiAmountMultiplier);
const scaledBalance = new BigNumber(balance).multipliedBy(multiplier).toString();
const scaledDelta = delta.multipliedBy(multiplier);
const scaledBalance = toScaledUiAmount({ decimals, multiplier, rawAmount: postAmount });
const scaledDelta = scaledBalance.minus(toScaledUiAmount({ decimals, multiplier, rawAmount: preAmount }));
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
const mintPubkey = new PublicKey(mint);
const ownerPubkey = owner ? new PublicKey(owner) : undefined;

Expand All @@ -148,9 +151,9 @@ function TokenBalanceRow({
<div className="flex shrink-0 flex-col items-end gap-0.5 whitespace-nowrap text-right">
<BalanceDelta delta={scaledDelta} />
<span>
{scaledBalance} {units}
{scaledBalance.toFixed()} {units}
<ScaledUiAmountMultiplierTooltip
rawAmount={balance}
rawAmount={toScaledUiAmount({ decimals, multiplier: '1', rawAmount: postAmount }).toFixed()}
scaledUiAmountMultiplier={scaledUiAmountMultiplier}
/>
</span>
Expand Down Expand Up @@ -196,61 +199,32 @@ export function generateTokenBalanceRows(
const account = accounts.at(accountIndex)?.pubkey;
invariant(account, `account index ${accountIndex} out of range`);

if (!uiTokenAmount.uiAmountString) {
// uiAmount deprecation
continue;
}

const postBalanceUiAmountString = uiTokenAmount.uiAmountString;
const preBalanceUiAmountString = preBalance?.uiTokenAmount.uiAmountString;
const { amount: postAmount, decimals } = uiTokenAmount;

// case where mint changes
if (preBalance && preBalance.mint !== mint) {
if (!preBalanceUiAmountString) {
// uiAmount deprecation
continue;
}

rows.push({
account,
accountIndex,
balance: '0',
delta: new BigNumber(-preBalanceUiAmountString),
decimals: preBalance.uiTokenAmount.decimals,
mint: preBalance.mint,
owner,
postAmount: '0',
preAmount: preBalance.uiTokenAmount.amount,
});

rows.push({
account,
accountIndex,
balance: postBalanceUiAmountString,
delta: new BigNumber(postBalanceUiAmountString),
mint: mint,
owner,
});
rows.push({ account, accountIndex, decimals, mint, owner, postAmount, preAmount: '0' });
continue;
}

let delta;

if (preBalance) {
if (!preBalanceUiAmountString) {
// uiAmount deprecation
continue;
}

delta = new BigNumber(postBalanceUiAmountString).minus(new BigNumber(preBalanceUiAmountString || 0));
} else {
delta = new BigNumber(postBalanceUiAmountString);
}

rows.push({
account,
accountIndex,
balance: postBalanceUiAmountString,
delta,
decimals,
mint,
owner,
postAmount,
preAmount: preBalance?.uiTokenAmount.amount ?? '0',
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@ import { PublicKey } from '@solana/web3.js';
import { nextjsParameters, withMockTransactions, withTokenInfoBatch } from '@storybook-config/decorators';
import { INITIAL_VIEWPORTS, withViewportFromGlobal } from '@storybook-config/responsive-decorators';
import type { Meta, StoryObj } from '@storybook-config/types';
import BigNumber from 'bignumber.js';

import { TokenBalancesCardInner, type TokenBalancesCardInnerProps } from '../TokenBalancesCard';

const sampleRows: TokenBalancesCardInnerProps['rows'] = [
{
account: new PublicKey('11111111111111111111111111111111'),
accountIndex: 0,
balance: '1.234',
delta: new BigNumber('1.234'),
decimals: 6,
mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
postAmount: '1234000',
preAmount: '0',
},
{
account: new PublicKey('SysvarRent111111111111111111111111111111111'),
accountIndex: 1,
balance: '42.0',
delta: new BigNumber('-0.5'),
decimals: 9,
mint: 'So11111111111111111111111111111111111111112',
postAmount: '42000000000',
preAmount: '42500000000',
},
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { MockAccountsProvider } from '@storybook-config/__mocks__/MockAccountsPr
import { MockTokenInfoBatchProvider } from '@storybook-config/__mocks__/MockTokenInfoBatchProvider';
import { nextjsParameters } from '@storybook-config/decorators';
import type { Meta, StoryObj } from '@storybook-config/types';
import { BigNumber } from 'bignumber.js';
import React from 'react';

import { DEFAULT_SIGNATURE, MOCK_PARSED_TX, MOCK_STATUS, RECIPIENT, TOKEN_MINT } from '../__fixtures__/transaction';
Expand Down Expand Up @@ -59,18 +58,20 @@ const SAMPLE_ROWS = [
{
account: RECIPIENT,
accountIndex: 0,
balance: '1.5',
delta: new BigNumber('1.0'),
decimals: 6,
mint: TOKEN_MINT.toBase58(),
owner: RECIPIENT.toBase58(),
postAmount: '1500000',
preAmount: '500000',
},
{
account: new PublicKey('GsbwXfJraMomNxBcpR3DBr9yoWR2PmN93PEaYJz7MSTN'),
accountIndex: 1,
balance: '50.25',
delta: new BigNumber('-2.5'),
decimals: 9,
mint: new PublicKey('So11111111111111111111111111111111111111112').toBase58(),
owner: new PublicKey('9noXzpXnkyEcKF3AeXqUHTdR59V5uvrRBUZ9bwfQwxNq').toBase58(),
postAmount: '50250000000',
preAmount: '52750000000',
},
];

Expand Down
Loading