diff --git a/modules/sdk-coin-sol/src/lib/explainTransactionWasm.ts b/modules/sdk-coin-sol/src/lib/explainTransactionWasm.ts index 481f4749f2..4164b33221 100644 --- a/modules/sdk-coin-sol/src/lib/explainTransactionWasm.ts +++ b/modules/sdk-coin-sol/src/lib/explainTransactionWasm.ts @@ -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, @@ -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 // ============================================================================= @@ -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); @@ -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 }); @@ -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': diff --git a/modules/sdk-coin-sol/src/lib/iface.ts b/modules/sdk-coin-sol/src/lib/iface.ts index 9a9740b079..7774df42e2 100644 --- a/modules/sdk-coin-sol/src/lib/iface.ts +++ b/modules/sdk-coin-sol/src/lib/iface.ts @@ -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 { diff --git a/modules/sdk-coin-sol/src/lib/instructionParamsFactory.ts b/modules/sdk-coin-sol/src/lib/instructionParamsFactory.ts index 9302f19ca8..ccb021e62a 100644 --- a/modules/sdk-coin-sol/src/lib/instructionParamsFactory.ts +++ b/modules/sdk-coin-sol/src/lib/instructionParamsFactory.ts @@ -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); diff --git a/modules/sdk-coin-sol/src/lib/solInstructionFactory.ts b/modules/sdk-coin-sol/src/lib/solInstructionFactory.ts index de76c5c478..2e61bed527 100644 --- a/modules/sdk-coin-sol/src/lib/solInstructionFactory.ts +++ b/modules/sdk-coin-sol/src/lib/solInstructionFactory.ts @@ -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'); @@ -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(), }); diff --git a/modules/sdk-coin-sol/src/lib/stakingWithdrawBuilder.ts b/modules/sdk-coin-sol/src/lib/stakingWithdrawBuilder.ts index f350ea2331..136271cee9 100644 --- a/modules/sdk-coin-sol/src/lib/stakingWithdrawBuilder.ts +++ b/modules/sdk-coin-sol/src/lib/stakingWithdrawBuilder.ts @@ -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) { super(_coinConfig); @@ -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); + } } } } @@ -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 { assert(this._sender, 'Sender must be set before building the transaction'); @@ -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 = diff --git a/modules/sdk-coin-sol/src/lib/transaction.ts b/modules/sdk-coin-sol/src/lib/transaction.ts index aead086ff1..fb120c59f4 100644 --- a/modules/sdk-coin-sol/src/lib/transaction.ts +++ b/modules/sdk-coin-sol/src/lib/transaction.ts @@ -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, }); @@ -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); diff --git a/modules/sdk-coin-sol/test/unit/instructionParamsFactory.staking.ts b/modules/sdk-coin-sol/test/unit/instructionParamsFactory.staking.ts index 9d7e2c329e..d42e7089ce 100644 --- a/modules/sdk-coin-sol/test/unit/instructionParamsFactory.staking.ts +++ b/modules/sdk-coin-sol/test/unit/instructionParamsFactory.staking.ts @@ -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, @@ -1078,6 +1079,7 @@ describe('Instruction Parser Staking Tests: ', function () { fromAddress: fromAccount.toString(), stakingAddress: stakingAccount.toString(), amount, + toAddress: fromAccount.toString(), }, }; @@ -1130,6 +1132,7 @@ describe('Instruction Parser Staking Tests: ', function () { fromAddress: fromAccount.toString(), stakingAddress: stakingAccount.toString(), amount, + toAddress: fromAccount.toString(), }, }; @@ -1164,6 +1167,7 @@ describe('Instruction Parser Staking Tests: ', function () { fromAddress: fromAccount.toString(), stakingAddress: stakingAccount.toString(), amount, + toAddress: fromAccount.toString(), }, }; @@ -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); diff --git a/modules/sdk-coin-sol/test/unit/solStakingWithdrawVerify.ts b/modules/sdk-coin-sol/test/unit/solStakingWithdrawVerify.ts new file mode 100644 index 0000000000..71004b0188 --- /dev/null +++ b/modules/sdk-coin-sol/test/unit/solStakingWithdrawVerify.ts @@ -0,0 +1,65 @@ +import 'should'; +import { coins } from '@bitgo/statics'; +import { BitGoBase, IWallet, TransactionParams, TransactionPrebuild } from '@bitgo/sdk-core'; +import { PublicKey, StakeProgram, Transaction as SolTransaction } from '@solana/web3.js'; + +import { Sol } from '../../src'; +import * as testData from '../resources/sol'; + +/** + * Verifies a staking withdraw prebuild against the declared recipients. + * + * These tests deliberately avoid `TestBitGo.decorate`, which requires the CI-only + * BITGOJS_TEST_PASSWORD secret, so the recipient check stays covered in local runs. + */ +describe('SOL staking withdraw verification', () => { + const walletRoot = testData.authAccount.pub; + const stakeAccount = testData.stakeAccount.pub; + const destination = testData.authAccount2.pub; + const blockHash = testData.blockHashes.validBlockHashes[0]; + const amount = '10000'; + + // `Sol`'s constructor only uses `url`, and verifyTransaction never touches the other collaborators. + const basecoin = new Sol({ url: () => '' } as unknown as BitGoBase, coins.get('sol')); + // verifyTransaction only reads the wallet's root address. + const wallet = { coinSpecific: () => ({ rootAddress: walletRoot }) } as unknown as IWallet; + + const prebuildPayingTo = (toAddress: string): TransactionPrebuild => { + const rawTx = new SolTransaction().add( + ...StakeProgram.withdraw({ + stakePubkey: new PublicKey(stakeAccount), + authorizedPubkey: new PublicKey(walletRoot), + toPubkey: new PublicKey(toAddress), + lamports: Number(amount), + }).instructions + ); + rawTx.feePayer = new PublicKey(walletRoot); + rawTx.recentBlockhash = blockHash; + return { + txBase64: rawTx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64'), + txInfo: { feePayer: walletRoot, nonce: blockHash }, + }; + }; + + const verifyPayingTo = (toAddress: string, recipientAddress: string) => { + const txParams: TransactionParams = { recipients: [{ address: recipientAddress, amount }] }; + return basecoin.verifyTransaction({ + txParams, + txPrebuild: prebuildPayingTo(toAddress), + wallet, + feePayer: walletRoot, + blockhash: blockHash, + }); + }; + + it('rejects a staking withdraw that pays a destination other than the declared recipient', async () => { + await verifyPayingTo(destination, walletRoot).should.be.rejectedWith( + 'Tx outputs does not match with expected txParams recipients' + ); + }); + + it('accepts a staking withdraw that pays the declared recipient', async () => { + const result = await verifyPayingTo(destination, destination); + result.should.equal(true); + }); +}); diff --git a/modules/sdk-coin-sol/test/unit/transaction.ts b/modules/sdk-coin-sol/test/unit/transaction.ts index 80b5f248f9..eb68341a55 100644 --- a/modules/sdk-coin-sol/test/unit/transaction.ts +++ b/modules/sdk-coin-sol/test/unit/transaction.ts @@ -1,9 +1,18 @@ import assert from 'assert'; import should from 'should'; +import { TransactionType } from '@bitgo/sdk-core'; import { coins } from '@bitgo/statics'; import { KeyPair, Transaction } from '../../src/lib'; +import { MEMO_PROGRAM_PK } from '../../src/lib/constants'; +import { getTransactionType } from '../../src/lib/utils'; import * as testData from '../resources/sol'; -import { PublicKey, Transaction as SolTransaction } from '@solana/web3.js'; +import { + PublicKey, + StakeProgram, + SystemProgram, + Transaction as SolTransaction, + TransactionInstruction, +} from '@solana/web3.js'; import { getBuilderFactory } from './getBuilderFactory'; describe('Sol Transaction', () => { @@ -955,6 +964,152 @@ describe('Sol Transaction', () => { }); }); + it('should explain the withdraw destination instead of the withdraw authority', function () { + const destination = testData.authAccount2.pub; + const withdrawInstructions = StakeProgram.withdraw({ + stakePubkey: new PublicKey(stakeAccount.pub), + authorizedPubkey: new PublicKey(wallet.pub), + toPubkey: new PublicKey(destination), + lamports: Number(amount), + }).instructions; + + const rawTx = new SolTransaction().add(...withdrawInstructions); + rawTx.feePayer = new PublicKey(wallet.pub); + rawTx.recentBlockhash = blockHash; + + const tx = new Transaction(coins.get('sol')); + tx.fromRawTransaction( + rawTx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64') + ); + + const explainedTransaction = tx.explainTransaction(); + explainedTransaction.type.should.equal('StakingWithdraw'); + explainedTransaction.inputs?.should.deepEqual([{ address: stakeAccount.pub, value: amount }]); + explainedTransaction.outputs.should.deepEqual([{ address: destination, amount }]); + explainedTransaction.outputAmount.should.equal(amount); + }); + + // A staking withdraw is only explained if every instruction in it is accounted for. These + // shapes are typed StakingWithdraw by getTransactionType (a present Deactivate, or a + // PrepareForRevoke memo, bypasses the Send shortcut), so they must not be explained with the + // extra instructions missing from the outputs. + const expectWithdrawRiderRejected = (instructions: TransactionInstruction[], coin: string) => { + const rawTx = new SolTransaction().add(...instructions); + rawTx.feePayer = new PublicKey(wallet.pub); + rawTx.recentBlockhash = blockHash; + // getTransactionType still classifies the transaction as a staking withdraw, so it must be + // rejected rather than explained with the rider instruction missing from the outputs. + getTransactionType(rawTx).should.equal(TransactionType.StakingWithdraw); + should(() => + new Transaction(coins.get(coin)).fromRawTransaction( + rawTx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64') + ) + ).throwError(/Invalid withdraw stake transaction, instruction type not supported/); + }; + const withdrawInstructions = () => + StakeProgram.withdraw({ + stakePubkey: new PublicKey(stakeAccount.pub), + authorizedPubkey: new PublicKey(wallet.pub), + toPubkey: new PublicKey(wallet.pub), + lamports: Number(amount), + }).instructions; + const deactivateInstructions = () => + StakeProgram.deactivate({ + stakePubkey: new PublicKey(stakeAccount.pub), + authorizedPubkey: new PublicKey(wallet.pub), + }).instructions; + const transferToDestination = () => + SystemProgram.transfer({ + fromPubkey: new PublicKey(wallet.pub), + toPubkey: new PublicKey(testData.authAccount2.pub), + lamports: Number(amount), + }); + const memoInstruction = (memo: string) => + new TransactionInstruction({ keys: [], programId: new PublicKey(MEMO_PROGRAM_PK), data: Buffer.from(memo) }); + + it('should reject a withdraw tx hiding a system transfer behind a deactivate instruction', () => { + expectWithdrawRiderRejected( + [...withdrawInstructions(), ...deactivateInstructions(), transferToDestination()], + 'sol' + ); + }); + + it('should not treat a withdraw with a transfer rider behind a bare PrepareForRevoke memo as a clean staking withdraw (typed Send, explain fails closed)', () => { + const rawTx = new SolTransaction().add( + ...withdrawInstructions(), + transferToDestination(), + memoInstruction('PrepareForRevoke') + ); + rawTx.feePayer = new PublicKey(wallet.pub); + rawTx.recentBlockhash = blockHash; + // A bare memo no longer bypasses the Send classification; only a well-formed Marinade unstake does. + getTransactionType(rawTx).should.equal(TransactionType.Send); + should(() => + new Transaction(coins.get('sol')).fromRawTransaction( + rawTx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64') + ) + ).throwError('Invalid transaction, instruction type not supported: Withdraw'); + }); + + it('should reject a withdraw tx carrying a non-transfer rider instruction', () => { + expectWithdrawRiderRejected([...withdrawInstructions(), ...deactivateInstructions()], 'sol'); + }); + + it('should reject the same withdraw-with-transfer shape on the tsol path', () => { + // tsol explains through WASM, but the withdraw instruction params are parsed by the same + // code first, so the rider is rejected there instead of being dropped from the outputs. + expectWithdrawRiderRejected( + [...withdrawInstructions(), ...deactivateInstructions(), transferToDestination()], + 'tsol' + ); + }); + + it('should explain the withdraw destination on the tsol (WASM) path', function () { + const destination = testData.authAccount2.pub; + const withdrawInstructions = StakeProgram.withdraw({ + stakePubkey: new PublicKey(stakeAccount.pub), + authorizedPubkey: new PublicKey(wallet.pub), + toPubkey: new PublicKey(destination), + lamports: Number(amount), + }).instructions; + + const rawTx = new SolTransaction().add(...withdrawInstructions); + rawTx.feePayer = new PublicKey(wallet.pub); + rawTx.recentBlockhash = blockHash; + + const tx = new Transaction(coins.get('tsol')); + tx.fromRawTransaction( + rawTx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64') + ); + + const explainedTransaction = tx.explainTransaction(); + explainedTransaction.type.should.equal('StakingWithdraw'); + explainedTransaction.inputs?.should.deepEqual([{ address: stakeAccount.pub, value: amount }]); + explainedTransaction.outputs.should.deepEqual([{ address: destination, amount }]); + explainedTransaction.outputAmount.should.equal(amount); + }); + + it('should keep explaining a self-withdraw to the authority on the tsol (WASM) path', function () { + const withdrawInstructions = StakeProgram.withdraw({ + stakePubkey: new PublicKey(stakeAccount.pub), + authorizedPubkey: new PublicKey(wallet.pub), + toPubkey: new PublicKey(wallet.pub), + lamports: Number(amount), + }).instructions; + + const rawTx = new SolTransaction().add(...withdrawInstructions); + rawTx.feePayer = new PublicKey(wallet.pub); + rawTx.recentBlockhash = blockHash; + + const tx = new Transaction(coins.get('tsol')); + tx.fromRawTransaction( + rawTx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64') + ); + + const explainedTransaction = tx.explainTransaction(); + explainedTransaction.outputs.should.deepEqual([{ address: wallet.pub, amount }]); + }); + it('should explain single token transfer transaction', async function () { const tx = await factory .getTokenTransferBuilder() diff --git a/modules/sdk-coin-sol/test/unit/transactionBuilder/StakingWithdrawBuilder.ts b/modules/sdk-coin-sol/test/unit/transactionBuilder/StakingWithdrawBuilder.ts index 59ed25711d..07fea9fa1f 100644 --- a/modules/sdk-coin-sol/test/unit/transactionBuilder/StakingWithdrawBuilder.ts +++ b/modules/sdk-coin-sol/test/unit/transactionBuilder/StakingWithdrawBuilder.ts @@ -1,4 +1,5 @@ import should from 'should'; +import { StakeInstruction, StakeProgram, Transaction as SolTransaction } from '@solana/web3.js'; import { getBuilderFactory } from '../getBuilderFactory'; import { KeyPair, Utils } from '../../../src'; @@ -37,6 +38,7 @@ describe('Sol Staking Withdraw Builder', () => { fromAddress: wallet.pub, stakingAddress: stakeAccount.pub, amount: amount, + toAddress: wallet.pub, }, }, ]); @@ -63,6 +65,7 @@ describe('Sol Staking Withdraw Builder', () => { fromAddress: wallet.pub, stakingAddress: stakeAccount.pub, amount: amount, + toAddress: wallet.pub, }, }, { @@ -75,6 +78,40 @@ describe('Sol Staking Withdraw Builder', () => { should.equal(rawTx, testData.STAKING_WITHDRAW_SIGNED_TX_WITH_MEMO); }); + it('building a staking withdraw tx to an explicit destination', async () => { + const destination = testData.authAccount2.pub; + const txBuilder = factory.getStakingWithdrawBuilder(); + txBuilder + .sender(wallet.pub) + .stakingAddress(stakeAccount.pub) + .amount(amount) + .toAddress(destination) + .nonce(recentBlockHash); + const tx = await txBuilder.build(); + const rawTx = tx.toBroadcastFormat(); + should.equal(Utils.isValidRawTransaction(rawTx), true); + + // The destination must be the on-chain `toPubkey` of the Stake Withdraw instruction. + const solTx = SolTransaction.from(Buffer.from(rawTx, 'base64')); + const withdrawInstruction = solTx.instructions.find((instruction) => + instruction.programId.equals(StakeProgram.programId) + ); + should.exist(withdrawInstruction); + StakeInstruction.decodeWithdraw(withdrawInstruction!).toPubkey.toBase58().should.equal(destination); + + tx.toJson().instructionsData.should.deepEqual([ + { + type: 'Withdraw', + params: { + fromAddress: wallet.pub, + stakingAddress: stakeAccount.pub, + amount: amount, + toAddress: destination, + }, + }, + ]); + }); + it('building a staking withdraw unsigned tx', async () => { const txBuilder = factory.getStakingWithdrawBuilder(); txBuilder.sender(wallet.pub).stakingAddress(stakeAccount.pub).amount(amount).nonce(recentBlockHash); @@ -89,6 +126,7 @@ describe('Sol Staking Withdraw Builder', () => { fromAddress: wallet.pub, stakingAddress: stakeAccount.pub, amount: amount, + toAddress: wallet.pub, }, }, ]); @@ -114,6 +152,7 @@ describe('Sol Staking Withdraw Builder', () => { fromAddress: wallet.pub, stakingAddress: stakeAccount.pub, amount: amount, + toAddress: wallet.pub, }, }, {