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
16 changes: 16 additions & 0 deletions packages/wasm-solana/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# wasm-solana

## Legacy transaction decoding

`Transaction.fromBytes()` accepts canonical, structurally valid legacy transaction
bytes up to Solana's 1232-byte packet limit. `signablePayload()` returns the
serialized Solana message; `toBytes()` preserves the transaction and signature
slots. The required signers are the first `numSignatures` entries of
`accountKeys()`, in the same order as `signatures`. Signature bytes are not
verified, and structural validity does not imply that a transaction can execute.

`parseTransaction(tx)` is a best-effort semantic decoder, not an admission or
complete review result. Unrecognized instructions are returned as `Unknown` with
their data and message-requested account roles; recognized decodings may also
have limitations. Callers must explicitly determine whether the transaction is
supported. A reference legacy native-payment vector and its regeneration
procedure are documented in `test/fixtures/README.md`.

WASM bindings for Solana cryptographic operations. This package provides Rust-based bindings for Ed25519 keypair generation, public key operations, and signature verification for Solana.

## Building
Expand Down
2 changes: 1 addition & 1 deletion packages/wasm-solana/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default tseslint.config(
},
},
{
ignores: ["dist/", "pkg/", "target/", "node_modules/", "js/wasm/", "*.config.js"],
ignores: ["dist/", "pkg/", "target/", "node_modules/", "js/wasm/", "reference/", "*.config.js"],
},
// Ban Node.js globals in production code
{
Expand Down
23 changes: 13 additions & 10 deletions packages/wasm-solana/js/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,10 @@ export interface SetComputeUnitLimitParams {
units: number;
}

/** Set priority fee parameters */
/** Compute-unit price; this is not the total transaction fee. */
export interface SetPriorityFeeParams {
type: "SetPriorityFee";
/** Micro-lamports per compute unit. */
fee: bigint;
}

Expand Down Expand Up @@ -192,10 +193,11 @@ export interface StakePoolWithdrawStakeParams {
poolTokens: bigint;
}

/** Account metadata for unknown instructions */
/** Account metadata for unknown instructions, as requested by the message. */
export interface AccountMeta {
pubkey: string;
isSigner: boolean;
/** Requested writable role before any runtime demotion. */
isWritable: boolean;
}

Expand Down Expand Up @@ -241,7 +243,8 @@ export interface DurableNonce {
}

/**
* A fully parsed Solana transaction with decoded instructions.
* A best-effort semantic view of a Solana transaction. Unknown instructions
* remain explicit and do not establish complete transaction understanding.
*
* This structure matches BitGoJS's TxData interface for seamless integration.
* All monetary amounts are returned as bigint directly from WASM.
Expand All @@ -259,13 +262,13 @@ export interface ParsedTransaction {
/** If this is a durable nonce transaction, contains the nonce info */
durableNonce?: DurableNonce;

/** All decoded instructions with semantic types */
/** Best-effort instruction decodings, including explicit unknown instructions. */
instructionsData: InstructionParams[];

/** All account keys (base58 strings) */
accountKeys: string[];

/** All signatures (base58 strings). Non-empty signatures indicate signed transaction. */
/** Signature slots as base58 strings. Their validity has not been checked. */
signatures: string[];
}

Expand All @@ -274,17 +277,17 @@ export interface ParsedTransaction {
// =============================================================================

/**
* Parse a Transaction into a plain data object with decoded instructions.
* Parse a Transaction into a best-effort semantic view.
*
* This is the main parsing function that returns structured data with all
* instructions decoded into semantic types (Transfer, StakingActivate, etc.)
* with amounts as bigint.
* Recognized instructions have semantic types such as Transfer, with amounts
* as bigint. Unknown instructions remain explicit; a successful parse does not
* establish that the whole transaction is understood or admitted for signing.
*
* Accepts a `Transaction` object (from `Transaction.fromBytes()`), avoiding
* double deserialization.
*
* @param tx - A Transaction instance (from Transaction.fromBytes())
* @returns A ParsedTransaction with all instructions decoded
* @returns A best-effort ParsedTransaction
*
* @example
* ```typescript
Expand Down
6 changes: 4 additions & 2 deletions packages/wasm-solana/js/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ export class Transaction {
private constructor(private _wasm: WasmTransaction) {}

/**
* Deserialize a transaction from raw bytes
* Deserialize a canonical, structurally valid legacy transaction of at most
* 1232 bytes. Signature slots are preserved, but are not verified.
* @param bytes - The raw transaction bytes
* @returns A Transaction instance
*/
Expand Down Expand Up @@ -157,7 +158,8 @@ export class Transaction {
/**
* Get all signatures as byte arrays.
* Provides compatibility with @solana/web3.js Transaction.signatures API.
* @returns Array of signature byte arrays
* @returns Unverified signature slots, in the same order as the required
* signer keys at the beginning of `accountKeys()`.
*/
get signatures(): Uint8Array[] {
return Array.from(this._wasm.signatures()) as Uint8Array[];
Expand Down
46 changes: 46 additions & 0 deletions packages/wasm-solana/reference/generate-native-payment.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Test-only reference generator. Run with @solana/web3.js 1.66.1 on NODE_PATH.
// Every public key, signature byte and amount is independently invented.
const {
PublicKey,
SystemProgram,
Transaction,
TransactionInstruction,
ComputeBudgetProgram,
} = require("@solana/web3.js");

function key(byte) {
return new PublicKey(Buffer.alloc(32, byte));
}

const source = key(1);
const nonceAuthority = key(2);
const nonceAccount = key(3);
const destination = key(4);
const blockhash = key(5).toBase58();
const memoProgram = new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr");

const tx = new Transaction({ feePayer: source, recentBlockhash: blockhash });
tx.add(SystemProgram.nonceAdvance({ noncePubkey: nonceAccount, authorizedPubkey: nonceAuthority }));
tx.add(ComputeBudgetProgram.setComputeUnitLimit({ units: 200000 }));
tx.add(
new TransactionInstruction({ programId: memoProgram, keys: [], data: Buffer.from("synthetic") }),
);
tx.add(SystemProgram.transfer({ fromPubkey: source, toPubkey: destination, lamports: 123456789 }));
tx.add(SystemProgram.transfer({ fromPubkey: source, toPubkey: destination, lamports: 0 }));
tx.addSignature(nonceAuthority, Buffer.alloc(64, 9)); // unverified test bytes

const message = tx.compileMessage();
const output = {
reference: "@solana/web3.js 1.66.1",
transactionBase64: tx
.serialize({ requireAllSignatures: false, verifySignatures: false })
.toString("base64"),
messageBase64: tx.serializeMessage().toString("base64"),
source: source.toBase58(),
nonceAuthority: nonceAuthority.toBase58(),
nonceAccount: nonceAccount.toBase58(),
destination: destination.toBase58(),
blockhash,
accountKeys: message.accountKeys.map((address) => address.toBase58()),
};
process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
18 changes: 7 additions & 11 deletions packages/wasm-solana/src/instructions/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use spl_stake_pool::instruction::StakePoolInstruction;
pub struct InstructionContext<'a> {
pub program_id: &'a str,
pub accounts: &'a [String],
pub account_metas: &'a [AccountMeta],
pub data: &'a [u8],
}

Expand All @@ -36,10 +37,13 @@ fn decode_system_instruction(ctx: InstructionContext) -> ParsedInstruction {
let Ok(instr) = bincode::deserialize::<SystemInstruction>(ctx.data) else {
return make_unknown(ctx);
};
if bincode::serialize(&instr).ok().as_deref() != Some(ctx.data) {
return make_unknown(ctx);
}

match instr {
SystemInstruction::Transfer { lamports } => {
if ctx.accounts.len() >= 2 {
if ctx.accounts.len() == 2 {
ParsedInstruction::Transfer(TransferParams {
from_address: ctx.accounts[0].clone(),
to_address: ctx.accounts[1].clone(),
Expand Down Expand Up @@ -67,7 +71,7 @@ fn decode_system_instruction(ctx: InstructionContext) -> ParsedInstruction {
}
}
SystemInstruction::AdvanceNonceAccount => {
if ctx.accounts.len() >= 3 {
if ctx.accounts.len() == 3 && ctx.accounts[1] == SYSVAR_RECENT_BLOCKHASHES {
ParsedInstruction::NonceAdvance(NonceAdvanceParams {
wallet_nonce_address: ctx.accounts[0].clone(),
auth_wallet_address: ctx.accounts[2].clone(), // authority is at index 2
Expand Down Expand Up @@ -454,15 +458,7 @@ fn decode_stake_pool_instruction(ctx: InstructionContext) -> ParsedInstruction {
fn make_unknown(ctx: InstructionContext) -> ParsedInstruction {
ParsedInstruction::Unknown(UnknownInstructionParams {
program_id: ctx.program_id.to_string(),
accounts: ctx
.accounts
.iter()
.map(|a| AccountMeta {
pubkey: a.clone(),
is_signer: false, // We don't have this info at decode time
is_writable: false, // We don't have this info at decode time
})
.collect(),
accounts: ctx.account_metas.to_vec(),
data: ctx.data.to_vec(),
})
}
6 changes: 2 additions & 4 deletions packages/wasm-solana/src/instructions/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
//! Internal instruction decoders using official Solana interface crates.
//!
//! This module is NOT publicly exposed. It's used internally by `parseTransaction`.
//! Parsed instruction types used by the existing transaction parser.

mod decode;
mod try_into_js_value;
mod types;

pub(crate) use decode::{decode_instruction, InstructionContext};
pub(crate) use types::*;
pub use types::*;
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 @@ -176,6 +176,7 @@ pub struct SetComputeUnitLimitParams {

#[derive(Debug, Clone)]
pub struct SetPriorityFeeParams {
/// Compute-unit price in micro-lamports per unit, not the total fee.
pub fee: u64,
}

Expand Down
4 changes: 2 additions & 2 deletions packages/wasm-solana/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@
//! ```

mod error;
mod instructions;
pub mod instructions;
pub mod intent;
pub mod keypair;
mod parser;
pub mod parser;
pub mod pubkey;
pub mod transaction;
pub mod versioned;
Expand Down
Loading
Loading