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
1 change: 1 addition & 0 deletions packages/wasm-solana/js/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export interface StakingWithdrawParams {
type: "StakingWithdraw";
fromAddress: string;
stakingAddress: string;
toAddress: string;
amount: bigint;
}

Expand Down
43 changes: 43 additions & 0 deletions packages/wasm-solana/src/instructions/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
ParsedInstruction::StakingWithdraw(StakingWithdrawParams {
staking_address: ctx.accounts[0].clone(),
from_address: ctx.accounts[4].clone(),
to_address: ctx.accounts[1].clone(),
amount: lamports,
})
} else {
Expand Down Expand Up @@ -466,3 +467,45 @@
data: ctx.data.to_vec(),
})
}

#[cfg(test)]
mod tests {
use super::*;
use solana_stake_interface::instruction::StakeInstruction;

fn decode_withdraw(recipient: &str) -> StakingWithdrawParams {
let data = bincode::serialize(&StakeInstruction::Withdraw(100_000)).unwrap();
let accounts = vec![
"stake-account".to_owned(),
recipient.to_owned(),
"clock-sysvar".to_owned(),
"stake-history-sysvar".to_owned(),
"withdraw-authority".to_owned(),
];

match decode_instruction(InstructionContext {
program_id: STAKE_PROGRAM_ID,
accounts: &accounts,
data: &data,
}) {
ParsedInstruction::StakingWithdraw(params) => params,
other => panic!("Expected StakingWithdraw, got {other:?}"),
}
}

#[test]
fn stake_withdraw_preserves_distinct_recipients() {
let first = decode_withdraw("recipient-one");
let second = decode_withdraw("recipient-two");

assert_eq!(first.staking_address, "stake-account");
assert_eq!(first.from_address, "withdraw-authority");
assert_eq!(first.to_address, "recipient-one");
assert_eq!(first.amount, 100_000);
assert_eq!(second.staking_address, first.staking_address);
assert_eq!(second.from_address, first.from_address);
assert_eq!(second.amount, first.amount);
assert_eq!(second.to_address, "recipient-two");
assert_ne!(first.to_address, second.to_address);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ impl TryIntoJsValue for StakingWithdrawParams {
"type" => "StakingWithdraw",
"fromAddress" => self.from_address,
"stakingAddress" => self.staking_address,
"toAddress" => self.to_address,
"amount" => self.amount
)
}
Expand Down
1 change: 1 addition & 0 deletions packages/wasm-solana/src/instructions/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ pub struct StakingDeactivateParams {
pub struct StakingWithdrawParams {
pub from_address: String,
pub staking_address: String,
pub to_address: String,
pub amount: u64,
}

Expand Down
9 changes: 7 additions & 2 deletions packages/wasm-solana/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,13 @@ fn parse_transaction_inner(
let accounts: Vec<String> = instruction
.accounts
.iter()
.filter_map(|&i| account_keys.get(i as usize).cloned())
.collect();
.map(|&i| {
account_keys
.get(i as usize)
.cloned()
.ok_or_else(|| format!("Invalid account index {} in instruction {}", i, idx))
})
.collect::<Result<_, _>>()?;

// Decode the instruction
let ctx = InstructionContext {
Expand Down
97 changes: 97 additions & 0 deletions packages/wasm-solana/test/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,75 @@ describe("parseTransaction", () => {
});
});

const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

function decodeBase58(value: string): Uint8Array {
const bytes = [0];
for (const character of value) {
let carry = BASE58_ALPHABET.indexOf(character);
assert.notStrictEqual(carry, -1);
for (let i = 0; i < bytes.length; i++) {
carry += bytes[i] * 58;
bytes[i] = carry & 0xff;
carry >>= 8;
}
while (carry > 0) {
bytes.push(carry & 0xff);
carry >>= 8;
}
}

const leadingZeroes = value.match(/^1*/)?.[0].length ?? 0;
const decoded = bytes.reverse();
while (decoded.length > 0 && decoded[0] === 0) {
decoded.shift();
}
return new Uint8Array([...new Array(leadingZeroes).fill(0), ...decoded]);
}

function shortVec(value: number): number[] {
const bytes: number[] = [];
while (value >= 0x80) {
bytes.push((value & 0x7f) | 0x80);
value >>= 7;
}
bytes.push(value);
return bytes;
}

function createStakeWithdrawTransaction(recipientByte: number, missingRecipient = false): Uint8Array {
const accountKeys = [
new Uint8Array(32).fill(1), // withdraw authority and fee payer
new Uint8Array(32).fill(2), // stake account
new Uint8Array(32).fill(recipientByte),
decodeBase58("SysvarC1ock11111111111111111111111111111111"),
decodeBase58("SysvarStakeHistory1111111111111111111111111"),
decodeBase58("Stake11111111111111111111111111111111111111"),
...(missingRecipient ? [new Uint8Array(32).fill(7)] : []),
];
for (const key of accountKeys) {
assert.strictEqual(key.length, 32);
}

const instructionAccounts = missingRecipient ? [1, 255, 3, 4, 0, 6] : [1, 2, 3, 4, 0];
const instructionData = new Uint8Array(12);
const dataView = new DataView(instructionData.buffer);
dataView.setUint32(0, 4, true); // StakeInstruction::Withdraw
dataView.setBigUint64(4, 100_000n, true);

const message = [1, ...new Uint8Array(64)]; // one unsigned signature
message.push(1, 0, accountKeys.length - 3); // legacy header
message.push(...shortVec(accountKeys.length));
for (const key of accountKeys) {
message.push(...key);
}
message.push(...new Uint8Array(32)); // recent blockhash
message.push(...shortVec(1), 5); // one instruction, stake program at index 5
message.push(...shortVec(instructionAccounts.length), ...instructionAccounts);
message.push(...shortVec(instructionData.length), ...instructionData);
return Uint8Array.from(message);
}

describe("StakingAuthorize parsing", () => {
it("should parse CLI-generated StakingAuthorize transaction that web3.js cannot decode", () => {
// This is a raw CLI-generated Stake Authorize transaction that web3.js fails to decode
Expand Down Expand Up @@ -112,3 +181,31 @@ describe("StakingAuthorize parsing", () => {
assert.strictEqual(authorizeInstr.authorizeType, "Withdrawer");
});
});

describe("StakingWithdraw parsing", () => {
it("preserves the recipient and distinguishes withdrawals that differ only by recipient", () => {
const first = parseTransaction(Transaction.fromBytes(createStakeWithdrawTransaction(3)));
const second = parseTransaction(Transaction.fromBytes(createStakeWithdrawTransaction(4)));
const firstWithdraw = first.instructionsData[0];
const secondWithdraw = second.instructionsData[0];

assert.strictEqual(firstWithdraw.type, "StakingWithdraw");
assert.strictEqual(secondWithdraw.type, "StakingWithdraw");
if (firstWithdraw.type !== "StakingWithdraw" || secondWithdraw.type !== "StakingWithdraw") {
return;
}

assert.strictEqual(firstWithdraw.toAddress, first.accountKeys[2]);
assert.strictEqual(secondWithdraw.toAddress, second.accountKeys[2]);
assert.notStrictEqual(firstWithdraw.toAddress, secondWithdraw.toAddress);
assert.strictEqual(firstWithdraw.stakingAddress, secondWithdraw.stakingAddress);
assert.strictEqual(firstWithdraw.fromAddress, secondWithdraw.fromAddress);
assert.strictEqual(firstWithdraw.amount, secondWithdraw.amount);
});

it("rejects a withdraw whose recipient account index cannot be resolved", () => {
assert.throws(() => {
parseTransaction(Transaction.fromBytes(createStakeWithdrawTransaction(3, true)));
});
});
});
Loading