Skip to content
Draft
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
100 changes: 97 additions & 3 deletions modules/sdk-coin-sol/src/lib/explainTransactionWasm.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { ITokenEnablement } from '@bitgo/sdk-core';
import { Transaction, parseTransaction, type ParsedTransaction, type InstructionParams } from '@bitgo/wasm-solana';
import {
stakeProgramId,
Transaction,
parseTransaction,
type Instruction,
type ParsedTransaction,
type InstructionParams,
type StakingWithdrawParams,
} from '@bitgo/wasm-solana';
import {
UNAVAILABLE_TEXT,
ZK_ELGAMAL_PROOF_PROGRAM_ID,
Expand Down Expand Up @@ -230,6 +238,84 @@ function mapStakingAuthorize(instr: {
};
}

// =============================================================================
// Staking withdraw destination recovery
// =============================================================================

/**
* `@bitgo/wasm-solana` decodes the Stake Withdraw instruction without its destination
* (`toPubkey`), which is the account the withdrawn lamports are paid to. Recover it from the
* instruction accounts of the same transaction bytes instead of assuming it is the withdraw
* authority, and fail closed when it cannot be determined.
*/
const STAKE_WITHDRAW_INSTRUCTION_INDEX = 4; // Stake program instruction index, u32 LE prefix
const STAKE_WITHDRAW_STAKE_ACCOUNT_INDEX = 0;
const STAKE_WITHDRAW_DESTINATION_ACCOUNT_INDEX = 1; // `toPubkey`
const STAKE_WITHDRAW_DATA_LENGTH = 4 + 8; // instruction index (u32) + lamports (u64)
const STAKE_WITHDRAW_LAMPORTS_OFFSET = 4;

interface DecodedStakeWithdraw {
stakeAddress: string;
destination: string;
authority: string;
lamports: bigint;
}

/**
* Returns the destination (`toPubkey`) of every Stake Withdraw instruction, in transaction order,
* and checks that they pair one-to-one with the WASM parser's StakingWithdraw instructions.
*
* @throws when the destination cannot be resolved from the transaction bytes, or when the two
* decoders disagree, so a fabricated destination is never reported.
*/
function resolveStakingWithdrawDestinations(
instructions: Instruction[],
parsedWithdraws: StakingWithdrawParams[]
): string[] {
const decoded = instructions.flatMap((instruction, instructionIndex): DecodedStakeWithdraw[] => {
if (instruction.programId !== stakeProgramId() || instruction.data.length !== STAKE_WITHDRAW_DATA_LENGTH) {
return [];
}
const data = Buffer.from(instruction.data);
if (data.readUInt32LE(0) !== STAKE_WITHDRAW_INSTRUCTION_INDEX) {
return [];
}
const accountKeys = instruction.accounts.map((account) => account.pubkey);
const stakeAddress = accountKeys[STAKE_WITHDRAW_STAKE_ACCOUNT_INDEX];
const destination = accountKeys[STAKE_WITHDRAW_DESTINATION_ACCOUNT_INDEX];
// The withdraw authority is the signer of the instruction; the remaining accounts are sysvars.
const authority = instruction.accounts.find((account) => account.isSigner)?.pubkey;
if (!stakeAddress || !destination || !authority) {
// Versioned transactions may reference accounts through address lookup tables, whose keys are
// not part of the transaction bytes.
throw new Error(
`Unable to determine the destination (toPubkey) of staking withdraw instruction ${instructionIndex}: its account keys are not resolvable from the transaction bytes`
);
}
return [{ stakeAddress, destination, authority, lamports: data.readBigUInt64LE(STAKE_WITHDRAW_LAMPORTS_OFFSET) }];
});

if (decoded.length !== parsedWithdraws.length) {
throw new Error(
`Unable to determine the destination (toPubkey) of the staking withdraw instruction: ${decoded.length} Stake Withdraw instruction(s) in the transaction bytes but ${parsedWithdraws.length} parsed by the WASM parser`
);
}

return decoded.map((withdraw, index) => {
const parsedWithdraw = parsedWithdraws[index];
if (
parsedWithdraw.stakingAddress !== withdraw.stakeAddress ||
parsedWithdraw.fromAddress !== withdraw.authority ||
parsedWithdraw.amount !== withdraw.lamports
) {
throw new Error(
`Unable to match staking withdraw instruction ${index} between the transaction bytes and the WASM parser output`
);
}
return withdraw.destination;
});
}

// =============================================================================
// Main explain function
// =============================================================================
Expand All @@ -249,6 +335,13 @@ export function explainSolTransaction(params: ExplainTransactionWasmOptions): So
const tx = Transaction.fromBytes(txBytes);
const parsed: ParsedTransaction = parseTransaction(tx);

// --- Staking withdraw destinations (not exposed by the WASM parser) ---
const parsedWithdraws = parsed.instructionsData.filter(
(instruction): instruction is StakingWithdrawParams => instruction.type === 'StakingWithdraw'
);
const withdrawDestinations =
parsedWithdraws.length > 0 ? resolveStakingWithdrawDestinations(tx.instructions, parsedWithdraws) : [];

// --- Transaction ID ---
const id = extractTransactionId(parsed.signatures);

Expand Down Expand Up @@ -280,6 +373,7 @@ export function explainSolTransaction(params: ExplainTransactionWasmOptions): So
// --- Extract outputs and inputs ---
const outputs: { address: string; amount: bigint; tokenName?: string }[] = [];
const inputs: { address: string; value: bigint }[] = [];
let withdrawIndex = 0;

if (combined?.kind === 'StakingActivate') {
outputs.push({ address: combined.stakingAddress, amount: combined.amount });
Expand All @@ -304,8 +398,8 @@ export function explainSolTransaction(params: ExplainTransactionWasmOptions): So
inputs.push({ address: instr.fromAddress, value: instr.amount });
break;
case 'StakingWithdraw':
// Withdraw: SOL flows FROM staking address TO the recipient (fromAddress)
outputs.push({ address: instr.fromAddress, amount: instr.amount });
// Withdraw: SOL flows FROM the staking address TO the instruction's `toPubkey` recipient.
outputs.push({ address: withdrawDestinations[withdrawIndex++], amount: instr.amount });
inputs.push({ address: instr.stakingAddress, value: instr.amount });
break;
case 'StakePoolDepositSol':
Expand Down
13 changes: 12 additions & 1 deletion modules/sdk-coin-sol/src/lib/iface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,18 @@ export interface StakingDeactivate {

export interface StakingWithdraw {
type: InstructionBuilderTypes.StakingWithdraw;
params: { fromAddress: string; stakingAddress: string; amount: string };
params: {
fromAddress: string;
stakingAddress: string;
amount: string;
/**
* Account that receives the withdrawn lamports, i.e. the Stake Withdraw instruction's `toPubkey`.
* It is not required to be the withdraw authority (`fromAddress`) that signs the transaction.
* Optional only for backwards compatibility with params produced by older versions; when it is
* absent the destination is assumed to be `fromAddress`.
*/
toAddress?: string;
};
}

export interface StakingAuthorize {
Expand Down
1 change: 1 addition & 0 deletions modules/sdk-coin-sol/src/lib/instructionParamsFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1109,6 +1109,7 @@ function parseStakingWithdrawInstructions(
fromAddress: withdrawInstruction.authorizedPubkey.toString(),
stakingAddress: withdrawInstruction.stakePubkey.toString(),
amount: withdrawInstruction.lamports.toString(),
toAddress: withdrawInstruction.toPubkey.toString(),
},
};
instructionData.push(stakingWithdraw);
Expand Down
4 changes: 2 additions & 2 deletions modules/sdk-coin-sol/src/lib/solInstructionFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ function stakingDeactivateInstruction(data: StakingDeactivate): TransactionInstr
*/
function stakingWithdrawInstruction(data: StakingWithdraw): TransactionInstruction[] {
const {
params: { fromAddress, stakingAddress, amount },
params: { fromAddress, stakingAddress, amount, toAddress },
} = data;
assert(fromAddress, 'Missing fromAddress param');
assert(stakingAddress, 'Missing stakingAddress param');
Expand All @@ -560,7 +560,7 @@ function stakingWithdrawInstruction(data: StakingWithdraw): TransactionInstructi
const withdrawStaking = StakeProgram.withdraw({
stakePubkey: new PublicKey(stakingAddress),
authorizedPubkey: new PublicKey(fromAddress),
toPubkey: new PublicKey(fromAddress),
toPubkey: new PublicKey(toAddress ?? fromAddress),
lamports: new BigNumber(amount).toNumber(),
});

Expand Down
18 changes: 18 additions & 0 deletions modules/sdk-coin-sol/src/lib/stakingWithdrawBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { isValidStakingAmount, validateAddress } from './utils';
export class StakingWithdrawBuilder extends TransactionBuilder {
protected _stakingAddress: string;
protected _amount: string;
protected _toAddress?: string;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
Expand All @@ -29,6 +30,9 @@ export class StakingWithdrawBuilder extends TransactionBuilder {
this.sender(withdrawInstruction.params.fromAddress);
this.stakingAddress(withdrawInstruction.params.stakingAddress);
this.amount(withdrawInstruction.params.amount);
if (withdrawInstruction.params.toAddress) {
this.toAddress(withdrawInstruction.params.toAddress);
}
}
}
}
Expand Down Expand Up @@ -61,6 +65,19 @@ export class StakingWithdrawBuilder extends TransactionBuilder {
return this;
}

/**
* The address that receives the withdrawn lamports (the Stake Withdraw instruction's `toPubkey`).
* Defaults to the sender when not set.
*
* @param {string} toAddress public address of the destination account
* @returns {StakingWithdrawBuilder} This staking withdraw builder.
*/
toAddress(toAddress: string): this {
validateAddress(toAddress, 'toAddress');
this._toAddress = toAddress;
return this;
}

/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
assert(this._sender, 'Sender must be set before building the transaction');
Expand All @@ -77,6 +94,7 @@ export class StakingWithdrawBuilder extends TransactionBuilder {
fromAddress: this._sender,
stakingAddress: this._stakingAddress,
amount: this._amount,
...(this._toAddress ? { toAddress: this._toAddress } : {}),
},
};
this._instructionsData =
Expand Down
4 changes: 2 additions & 2 deletions modules/sdk-coin-sol/src/lib/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ export class Transaction extends BaseTransaction {
coin: this._coinConfig.name,
});
outputs.push({
address: instruction.params.fromAddress,
address: instruction.params.toAddress ?? instruction.params.fromAddress,
value: instruction.params.amount,
coin: this._coinConfig.name,
});
Expand Down Expand Up @@ -754,7 +754,7 @@ export class Transaction extends BaseTransaction {
case InstructionBuilderTypes.StakingWithdraw:
const stakingWithdrawInstruction = instruction as StakingWithdraw;
outputs.push({
address: stakingWithdrawInstruction.params.fromAddress,
address: stakingWithdrawInstruction.params.toAddress ?? stakingWithdrawInstruction.params.fromAddress,
amount: stakingWithdrawInstruction.params.amount,
});
outputAmount = outputAmount.plus(stakingWithdrawInstruction.params.amount);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { TransactionType } from '@bitgo/sdk-core';
import { InstructionParams, Nonce, StakingActivate, StakingDeactivate, StakingWithdraw } from '../../src/lib/iface';
import { InstructionBuilderTypes, MEMO_PROGRAM_PK, STAKE_ACCOUNT_RENT_EXEMPT_AMOUNT } from '../../src/lib/constants';
import {
ComputeBudgetProgram,
Keypair as SolKeypair,
Lockup,
PublicKey,
Expand Down Expand Up @@ -1078,6 +1079,7 @@ describe('Instruction Parser Staking Tests: ', function () {
fromAddress: fromAccount.toString(),
stakingAddress: stakingAccount.toString(),
amount,
toAddress: fromAccount.toString(),
},
};

Expand Down Expand Up @@ -1130,6 +1132,7 @@ describe('Instruction Parser Staking Tests: ', function () {
fromAddress: fromAccount.toString(),
stakingAddress: stakingAccount.toString(),
amount,
toAddress: fromAccount.toString(),
},
};

Expand Down Expand Up @@ -1164,6 +1167,7 @@ describe('Instruction Parser Staking Tests: ', function () {
fromAddress: fromAccount.toString(),
stakingAddress: stakingAccount.toString(),
amount,
toAddress: fromAccount.toString(),
},
};

Expand All @@ -1173,6 +1177,83 @@ describe('Instruction Parser Staking Tests: ', function () {
should.deepEqual(result, instructionsData);
});

it('Should keep the withdraw destination when it differs from the withdraw authority', () => {
const fromAccount = new PublicKey(testData.authAccount.pub);
const destination = new PublicKey(testData.authAccount2.pub);
const stakingAccount = new PublicKey(testData.stakeAccount.pub);
const amount = '100000';

// The Stake Withdraw instruction pays lamports to `toPubkey`, which is not required to be
// the withdraw authority signing the transaction.
const withdrawStakeInstructions = StakeProgram.withdraw({
authorizedPubkey: fromAccount,
stakePubkey: stakingAccount,
toPubkey: destination,
lamports: new BigNumber(amount).toNumber(),
}).instructions;

const expectedParams: StakingWithdraw = {
type: InstructionBuilderTypes.StakingWithdraw,
params: {
fromAddress: fromAccount.toString(),
stakingAddress: stakingAccount.toString(),
amount,
toAddress: destination.toString(),
},
};

const result = instructionParamsFactory(TransactionType.StakingWithdraw, withdrawStakeInstructions);
should.deepEqual(result, [expectedParams]);
});

it('Should parse withdraw stake tx instructions with nonce advance, compute-budget and memo instructions', () => {
const fromAccount = new PublicKey(testData.authAccount.pub);
const nonceAccount = new PublicKey(testData.nonceAccount.pub);
const stakingAccount = new PublicKey(testData.stakeAccount.pub);
const memo = 'claim memo';
const amount = '100000';
const units = 300000;
const fee = 5000;

const instructions = [
SystemProgram.nonceAdvance({ noncePubkey: nonceAccount, authorizedPubkey: fromAccount }),
ComputeBudgetProgram.setComputeUnitLimit({ units }),
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: fee }),
...StakeProgram.withdraw({
authorizedPubkey: fromAccount,
stakePubkey: stakingAccount,
toPubkey: fromAccount,
lamports: new BigNumber(amount).toNumber(),
}).instructions,
new TransactionInstruction({
keys: [],
programId: new PublicKey(MEMO_PROGRAM_PK),
data: Buffer.from(memo),
}),
];

const expectedParams: InstructionParams[] = [
{
type: InstructionBuilderTypes.NonceAdvance,
params: { walletNonceAddress: nonceAccount.toString(), authWalletAddress: fromAccount.toString() },
},
{ type: InstructionBuilderTypes.SetComputeUnitLimit, params: { units } },
{ type: InstructionBuilderTypes.SetPriorityFee, params: { fee: BigInt(fee) } },
{
type: InstructionBuilderTypes.StakingWithdraw,
params: {
fromAddress: fromAccount.toString(),
stakingAddress: stakingAccount.toString(),
amount,
toAddress: fromAccount.toString(),
},
},
{ type: InstructionBuilderTypes.Memo, params: { memo } },
];

should.deepEqual(instructionParamsFactory(TransactionType.StakingWithdraw, instructions), expectedParams);
});

it('Should reject withdraw stake tx instructions if there are unexpected instructions', () => {
const fromAccount = new PublicKey(testData.authAccount.pub);
const stakingAccount = new PublicKey(testData.stakeAccount.pub);
Expand Down
Loading
Loading