Skip to content

Commit

Permalink
Show token balance changes on a simulated transaction (#286)
Browse files Browse the repository at this point in the history
Currently, the simulation only shows whether or not the transaction
succeeds and the logs.

It would be very useful for this to include token balance changes since
the token program doesnt log the accounts or amounts. This should bring
the displayed information of a simulation up to parity with what the
explorer does for completed transactions.

The difficult part of this is that the simulateTransaction RPC spec does
not include the pre/post token balances similar to asking for a
completed transaction. To address this, we request the accountData for
all accounts immediately before simulating and record the values of all
token accounts. Then the simulateTransaction allows optional arguments
for accounts to get their post simulation data. Parse that to get the
post transaction token balance. Then convert it to the same format that
the existing token balances component from the transaction page.

Example with token balances (before, the simulate was the same thing
without the token changes component):

![image](https://github.com/solana-labs/explorer/assets/1320260/f53a2c60-a287-4839-9038-1431c68cb9cd)

---------

Co-authored-by: Callum McIntyre <[email protected]>
  • Loading branch information
brittcyr and mcintyre94 authored Sep 14, 2023
1 parent 4b26de2 commit b91b274
Show file tree
Hide file tree
Showing 5 changed files with 184 additions and 24 deletions.
14 changes: 7 additions & 7 deletions app/components/inspector/InspectorPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ function decodeUrlParams(params: URLSearchParams): [TransactionData | string, UR
}
}

export function TransactionInspectorPage({ signature }: { signature?: string }) {
export function TransactionInspectorPage({ signature, showTokenBalanceChanges }: { signature?: string; showTokenBalanceChanges: boolean }) {
const [transaction, setTransaction] = React.useState<TransactionData>();
const currentSearchParams = useSearchParams();
const currentPathname = usePathname();
Expand Down Expand Up @@ -196,17 +196,17 @@ export function TransactionInspectorPage({ signature }: { signature?: string })
</div>
</div>
{signature ? (
<PermalinkView signature={signature} reset={reset} />
<PermalinkView signature={signature} reset={reset} showTokenBalanceChanges={showTokenBalanceChanges} />
) : transaction ? (
<LoadedView transaction={transaction} onClear={reset} />
<LoadedView transaction={transaction} onClear={reset} showTokenBalanceChanges={showTokenBalanceChanges} />
) : (
<RawInput value={paramString} setTransactionData={setTransaction} />
)}
</div>
);
}

function PermalinkView({ signature }: { signature: string; reset: () => void }) {
function PermalinkView({ signature, showTokenBalanceChanges }: { signature: string; reset: () => void; showTokenBalanceChanges: boolean }) {
const details = useRawTransactionDetails(signature);
const fetchTransaction = useFetchRawTransaction();
const refreshTransaction = () => fetchTransaction(signature);
Expand All @@ -233,10 +233,10 @@ function PermalinkView({ signature }: { signature: string; reset: () => void })
const { message, signatures } = transaction;
const tx = { message, rawMessage: message.serialize(), signatures };

return <LoadedView transaction={tx} onClear={reset} />;
return <LoadedView transaction={tx} onClear={reset} showTokenBalanceChanges={showTokenBalanceChanges} />;
}

function LoadedView({ transaction, onClear }: { transaction: TransactionData; onClear: () => void }) {
function LoadedView({ transaction, onClear, showTokenBalanceChanges }: { transaction: TransactionData; onClear: () => void; showTokenBalanceChanges: boolean }) {
const { message, rawMessage, signatures } = transaction;

const fetchAccountInfo = useFetchAccountInfo();
Expand All @@ -249,7 +249,7 @@ function LoadedView({ transaction, onClear }: { transaction: TransactionData; on
return (
<>
<OverviewCard message={message} raw={rawMessage} onClear={onClear} />
<SimulatorCard message={message} />
<SimulatorCard message={message} showTokenBalanceChanges={showTokenBalanceChanges} />
{signatures && <TransactionSignatures message={message} signatures={signatures} rawMessage={rawMessage} />}
<AccountsCard message={message} />
<AddressTableLookupsCard message={message} />
Expand Down
184 changes: 172 additions & 12 deletions app/components/inspector/SimulatorCard.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { ProgramLogsCardBody } from '@components/ProgramLogsCardBody';
import { useCluster } from '@providers/cluster';
import { Connection, VersionedMessage, VersionedTransaction } from '@solana/web3.js';
import { AccountLayout, MintLayout, TOKEN_PROGRAM_ID } from "@solana/spl-token";
import { AccountInfo, AddressLookupTableAccount, Connection, MessageAddressTableLookup, ParsedAccountData, ParsedMessageAccount, SimulatedTransactionAccountInfo, TokenBalance, VersionedMessage, VersionedTransaction } from '@solana/web3.js';
import { PublicKey } from '@solana/web3.js';
import { InstructionLogs, parseProgramLogs } from '@utils/program-logs';
import React from 'react';

export function SimulatorCard({ message }: { message: VersionedMessage }) {
import { generateTokenBalanceRows,TokenBalancesCardInner, TokenBalancesCardInnerProps } from '../transaction/TokenBalancesCard';

export function SimulatorCard({ message, showTokenBalanceChanges }: { message: VersionedMessage; showTokenBalanceChanges: boolean }) {
const { cluster, url } = useCluster();
const { simulate, simulating, simulationLogs: logs, simulationError } = useSimulator(message);
const { simulate, simulating, simulationLogs: logs, simulationError, simulationTokenBalanceRows } = useSimulator(message);
if (simulating) {
return (
<div className="card">
Expand Down Expand Up @@ -49,15 +53,20 @@ export function SimulatorCard({ message }: { message: VersionedMessage }) {
}

return (
<div className="card">
<div className="card-header">
<h3 className="card-header-title">Transaction Simulation</h3>
<button className="btn btn-sm d-flex btn-white" onClick={simulate}>
Retry
</button>
<>
<div className="card">
<div className="card-header">
<h3 className="card-header-title">Transaction Simulation</h3>
<button className="btn btn-sm d-flex btn-white" onClick={simulate}>
Retry
</button>
</div>
<ProgramLogsCardBody message={message} logs={logs} cluster={cluster} url={url} />
</div>
<ProgramLogsCardBody message={message} logs={logs} cluster={cluster} url={url} />
</div>
{showTokenBalanceChanges && simulationTokenBalanceRows && !simulationError && simulationTokenBalanceRows.rows.length ? (
<TokenBalancesCardInner rows={simulationTokenBalanceRows.rows} />
) : null}
</>
);
}

Expand All @@ -66,6 +75,7 @@ function useSimulator(message: VersionedMessage) {
const [simulating, setSimulating] = React.useState(false);
const [logs, setLogs] = React.useState<Array<InstructionLogs> | null>(null);
const [error, setError] = React.useState<string>();
const [tokenBalanceRows, setTokenBalanceRows] = React.useState<TokenBalancesCardInnerProps>();

React.useEffect(() => {
setLogs(null);
Expand All @@ -81,11 +91,115 @@ function useSimulator(message: VersionedMessage) {
const connection = new Connection(url, 'confirmed');
(async () => {
try {
// Simulate without signers to skip signer verification
const addressTableLookups: MessageAddressTableLookup[] = message.addressTableLookups;
const addressTableLookupKeys: PublicKey[] = addressTableLookups.map((addressTableLookup: MessageAddressTableLookup) => {
return addressTableLookup.accountKey;
});
const addressTableLookupsFetched: (AccountInfo<Buffer> | null)[] = await connection.getMultipleAccountsInfo(addressTableLookupKeys);
const nonNullAddressTableLookups: AccountInfo<Buffer>[] = addressTableLookupsFetched.filter((o): o is AccountInfo<Buffer> => !!o);

const addressLookupTablesParsed: AddressLookupTableAccount[] = nonNullAddressTableLookups.map((addressTableLookup: AccountInfo<Buffer>, index) => {
return new AddressLookupTableAccount({
key: addressTableLookupKeys[index],
state: AddressLookupTableAccount.deserialize(addressTableLookup.data)
});
})

// Fetch all the accounts before simulating
const accountKeys = message.getAccountKeys({
addressLookupTableAccounts: addressLookupTablesParsed,
}).staticAccountKeys;
const parsedAccountsPre = await connection.getMultipleParsedAccounts(accountKeys);

// Simulate without signers to skip signer verification. Request
// all account data after the simulation.
const resp = await connection.simulateTransaction(new VersionedTransaction(message), {
accounts: {
addresses: accountKeys.map(function (key) {
return key.toBase58();
}),
encoding: 'base64',
},
replaceRecentBlockhash: true,
});

const mintToDecimals: { [mintPk: string]: number} = getMintDecimals(
accountKeys,
parsedAccountsPre.value,
resp.value.accounts as SimulatedTransactionAccountInfo[],
)

const preTokenBalances: TokenBalance[] = [];
const postTokenBalances: TokenBalance[] = [];
const tokenAccountKeys: ParsedMessageAccount[] = [];

for (let index = 0; index < accountKeys.length; index++) {
const key = accountKeys[index];
const parsedAccountPre = parsedAccountsPre.value[index];
const accountDataPost = resp.value.accounts?.at(index)?.data[0];
const accountOwnerPost = resp.value.accounts?.at(index)?.owner;

if (
(parsedAccountPre?.owner.toBase58() == TOKEN_PROGRAM_ID.toBase58() ||
parsedAccountPre?.owner.toBase58() == "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb") &&
(parsedAccountPre?.data as ParsedAccountData).parsed.type === 'account'
) {
const mint = (parsedAccountPre?.data as ParsedAccountData).parsed.info.mint;
const owner = (parsedAccountPre?.data as ParsedAccountData).parsed.info.owner;
const tokenAmount = (parsedAccountPre?.data as ParsedAccountData).parsed.info.tokenAmount;
const preTokenBalance = {
accountIndex: tokenAccountKeys.length,
mint: mint,
owner: owner,
uiTokenAmount: tokenAmount,
};
preTokenBalances.push(preTokenBalance);
}

if (
(accountOwnerPost === TOKEN_PROGRAM_ID.toBase58() ||
accountOwnerPost === "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb") &&
Buffer.from(accountDataPost!, 'base64').length >= 165
) {
const accountParsedPost = AccountLayout.decode(Buffer.from(accountDataPost!, 'base64'));
const mint = new PublicKey(accountParsedPost.mint);
const owner = new PublicKey(accountParsedPost.owner);
const postRawAmount = Number(accountParsedPost.amount.readBigUInt64LE(0));

const decimals = mintToDecimals[mint.toBase58()];
const tokenAmount = postRawAmount / 10 ** decimals;

const postTokenBalance = {
accountIndex: tokenAccountKeys.length,
mint: mint.toBase58(),
owner: owner.toBase58(),
uiTokenAmount: {
amount: postRawAmount.toString(),
decimals: decimals,
uiAmount: tokenAmount,
uiAmountString: tokenAmount.toString(),
},
};
postTokenBalances.push(postTokenBalance);
}
// All fields are ignored other than key, so set placeholders.
const parsedMessageAccount = {
pubkey: key,
signer: false,
writable: true,
};
tokenAccountKeys.push(parsedMessageAccount);
}

const tokenBalanceRows = generateTokenBalanceRows(
preTokenBalances,
postTokenBalances,
tokenAccountKeys
);
if (tokenBalanceRows) {
setTokenBalanceRows({ rows: tokenBalanceRows });
}

if (resp.value.logs === null) {
throw new Error('Expected to receive logs from simulation');
}
Expand All @@ -97,6 +211,10 @@ function useSimulator(message: VersionedMessage) {
// Prettify logs
setLogs(parseProgramLogs(resp.value.logs, resp.value.err, cluster));
}
// If the response has an error, the logs will say what it it, so no need to parse here.
if (resp.value.err) {
setError('TransactionError');
}
} catch (err) {
console.error(err);
setLogs(null);
Expand All @@ -113,5 +231,47 @@ function useSimulator(message: VersionedMessage) {
simulating,
simulationError: error,
simulationLogs: logs,
simulationTokenBalanceRows: tokenBalanceRows,
};
}

function getMintDecimals(
accountKeys: PublicKey[],
parsedAccountsPre: (AccountInfo<ParsedAccountData | Buffer> | null)[],
accountDatasPost: SimulatedTransactionAccountInfo[]
): { [mintPk: string]: number} {
const mintToDecimals: { [mintPk: string]: number } = {};
// Get all the necessary mint decimals by looking at parsed token accounts
// and mints before, as well as mints after.
for (let index = 0; index < accountKeys.length; index++) {
const parsedAccount = parsedAccountsPre[index];
const key = accountKeys[index];

// Token account before
if (
parsedAccount?.owner.toBase58() == TOKEN_PROGRAM_ID.toBase58() &&
(parsedAccount?.data as ParsedAccountData).parsed.type === 'account'
) {
mintToDecimals[(parsedAccount?.data as ParsedAccountData).parsed.info.mint] = (
parsedAccount?.data as ParsedAccountData
).parsed.info.tokenAmount.decimals;
}
// Mint account before
if (
parsedAccount?.owner.toBase58() == TOKEN_PROGRAM_ID.toBase58() &&
(parsedAccount?.data as ParsedAccountData).parsed.type === 'mint'
) {
mintToDecimals[key.toBase58()] = (parsedAccount?.data as ParsedAccountData).parsed.info.decimals;
}

// Token account after
const accountDataPost = accountDatasPost.at(index)?.data[0];
const accountOwnerPost = accountDatasPost.at(index)?.owner;
if (accountOwnerPost === TOKEN_PROGRAM_ID.toBase58() && Buffer.from(accountDataPost!, 'base64').length === 82) {
const accountParsedPost = MintLayout.decode(Buffer.from(accountDataPost!, 'base64'));
mintToDecimals[key.toBase58()] = accountParsedPost.decimals;
}
}

return mintToDecimals;
}
6 changes: 3 additions & 3 deletions app/components/transaction/TokenBalancesCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ export function TokenBalancesCard({ signature }: SignatureProps) {
return <TokenBalancesCardInner rows={rows} />
}

type TokenBalancesCardInnerProps = {
export type TokenBalancesCardInnerProps = {
rows: TokenBalanceRow[]
}


function TokenBalancesCardInner({ rows }: TokenBalancesCardInnerProps) {
export function TokenBalancesCardInner({ rows }: TokenBalancesCardInnerProps) {
const { cluster, url } = useCluster();
const [tokenInfosLoading, setTokenInfosLoading] = useState(true);
const [tokenSymbols, setTokenSymbols] = useState<Map<string, string>>(new Map());
Expand Down Expand Up @@ -107,7 +107,7 @@ function TokenBalancesCardInner({ rows }: TokenBalancesCardInnerProps) {
);
}

function generateTokenBalanceRows(
export function generateTokenBalanceRows(
preTokenBalances: TokenBalance[],
postTokenBalances: TokenBalance[],
accounts: ParsedMessageAccount[]
Expand Down
2 changes: 1 addition & 1 deletion app/tx/(inspector)/[signature]/inspect/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ export async function generateMetadata({ params: { signature } }: Props): Promis
}

export default function TransactionInspectionPage({ params: { signature } }: Props) {
return <TransactionInspectorPage signature={signature} />;
return <TransactionInspectorPage signature={signature} showTokenBalanceChanges={false} />;
}
2 changes: 1 addition & 1 deletion app/tx/(inspector)/inspector/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ type Props = Readonly<{
}>;

export default function Page({ params: { signature } }: Props) {
return <TransactionInspectorPage signature={signature} />;
return <TransactionInspectorPage signature={signature} showTokenBalanceChanges={true} />;
}

1 comment on commit b91b274

@vercel
Copy link

@vercel vercel bot commented on b91b274 Sep 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

explorer – ./

explorer.solana.com
explorer-solana-labs.vercel.app
explorer-git-master-solana-labs.vercel.app

Please sign in to comment.