Skip to content
Merged
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
108 changes: 108 additions & 0 deletions examples/ts/sol/sdk-ct-v1-broadcast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* CHALO-1602 Verification: SDK-built Solana v1 Confidential Transfer broadcast
*
* Builds a Token-2022 confidential Transfer as a v1 transaction (SIMD-0296/0385)
* via the SDK ConfidentialTransferBuilder, consumes pre-created proof contexts,
* and broadcasts + confirms on devnet.
*
* Prerequisites (produced by coins-sandbox `sol/confidentialTransfers/ct_sdk_feed.mjs`):
* - sdk-e2e-input.json: source/dest ATA, mint, pre-created proof-context accounts,
* and the transfer ciphertext fields (no credentials).
* - extB_e2e.json: source authority secret (for signing).
* - A funded devnet fee payer secret (base64 of the 64-byte ed25519 secret).
*
* Run:
* SOL_DEVNET_RPC=<rpc> SDK_E2E_INPUT=<path/sdk-e2e-input.json> EXTB_STATE=<path/extB_e2e.json> \
* PAYER_SECRET_B64=<base64> node_modules/.bin/tsx examples/ts/sol/sdk-ct-v1-broadcast.ts
*
* Copyright 2026, BitGo, Inc. All Rights Reserved.
*/
import { KeyPair, Transaction, TransactionBuilderFactory } from '@bitgo/sdk-coin-sol';
import { coins } from '@bitgo/statics';
import { Connection } from '@solana/web3.js';
import * as bs58 from 'bs58';
import { readFileSync } from 'node:fs';

const path = require('path');
const envPath = path.resolve(__dirname, '../../../.env');
require('dotenv').config({ path: envPath });

async function main() {
const rpcUrl = process.env.SOL_DEVNET_RPC;
const inputPath = process.env.SDK_E2E_INPUT;
const statePath = process.env.EXTB_STATE;
const payerSecretB64 = process.env.PAYER_SECRET_B64;
if (!rpcUrl || !inputPath || !statePath || !payerSecretB64) {
throw new Error('SOL_DEVNET_RPC, SDK_E2E_INPUT, EXTB_STATE, PAYER_SECRET_B64 env are required');
}

const input = JSON.parse(readFileSync(inputPath, 'utf8'));
const e2e = JSON.parse(readFileSync(statePath, 'utf8'));
const authoritySecret = bs58.encode(Uint8Array.from(e2e.ownerSecretKey));
const payerSecret = bs58.encode(Uint8Array.from(Buffer.from(payerSecretB64, 'base64')));
const payerAddress = new KeyPair({ prv: payerSecret }).getKeys().pub;
const authorityAddress = input.authorityAddress;

const connection = new Connection(rpcUrl, 'confirmed');
const { blockhash } = await connection.getLatestBlockhash('finalized');

const factory = new TransactionBuilderFactory(coins.get('sol'));
const builder = factory.getConfidentialTransferBuilder();
builder.nonce(blockhash).sender(authorityAddress).feePayer(payerAddress);
builder.sign({ key: payerSecret });
builder.sign({ key: authoritySecret });
builder.version(1).transactionConfig({
computeUnitLimit: 1_400_000,
heapSize: null,
loadedAccountsDataSizeLimit: 1_048_576,
priorityFee: 5_000,
});
builder.confidentialTransfer({
sourceTokenAddress: input.sourceTokenAddress,
mintAddress: input.mintAddress,
destinationTokenAddress: input.destinationTokenAddress,
authorityAddress,
equalityProofContextStateAddress: input.equalityProofContextStateAddress,
ciphertextValidityProofContextStateAddress: input.ciphertextValidityProofContextStateAddress,
rangeProofContextStateAddress: input.rangeProofContextStateAddress,
newSourceDecryptableAvailableBalance: input.newSourceDecryptableAvailableBalance,
transferAmountAuditorCiphertextLo: input.transferAmountAuditorCiphertextLo,
transferAmountAuditorCiphertextHi: input.transferAmountAuditorCiphertextHi,
equalityProofInstructionOffset: 0,
ciphertextValidityProofInstructionOffset: 0,
rangeProofInstructionOffset: 0,
});

const tx = (await builder.build()) as Transaction;
const b64 = tx.toBroadcastFormat();
const wire = Buffer.from(b64, 'base64');
console.log('SDK-built tx isVersioned:', tx.isVersionedTransaction());
console.log('wire[0] = 0x' + wire[0].toString(16) + (wire[0] === 0x81 ? ' (v1)' : ' (NOT v1!)'));
console.log('wire bytes =', wire.length);
if (wire[0] !== 0x81) throw new Error('SDK builder did not produce a v1 transaction');
if (wire.length > 4096) throw new Error('SDK v1 tx exceeds 4096 bytes');

const signature = await connection.sendEncodedTransaction(b64, { encoding: 'base64', maxRetries: 3 });
console.log('broadcast signature:', signature);

let confirmed = false;
for (let i = 0; i < 30; i++) {
await new Promise((r) => setTimeout(r, 2000));
const status = await connection.getSignatureStatus(signature);
const s = status?.value;
if (s && (s.confirmationStatus === 'confirmed' || s.confirmationStatus === 'finalized')) {
confirmed = true;
if (s.err) throw new Error('SDK-built v1 tx failed: ' + JSON.stringify(s.err));
console.log('confirmed at slot', s.slot);
break;
}
if (s?.err) throw new Error('SDK-built v1 tx errored: ' + JSON.stringify(s.err));
}
if (!confirmed) throw new Error('SDK-built v1 tx not confirmed within 60s');
console.log('SDK-built v1 CT Transfer CONFIRMED:', signature, '| wire bytes', wire.length);
}

main().catch((e) => {
console.error('FATAL:', e);
process.exit(1);
});
118 changes: 117 additions & 1 deletion modules/sdk-coin-sol/src/lib/confidentialTransferBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { TransactionType } from '@bitgo/sdk-core';
import { BuildTransactionError, SolTransactionVersion, SolV1TransactionConfig, TransactionType } from '@bitgo/sdk-core';
import { PublicKey, Transaction as SolTransaction, TransactionInstruction } from '@solana/web3.js';
import nacl from 'tweetnacl';
import { Transaction } from './transaction';
import { TransactionBuilder } from './transactionBuilder';
import { InstructionBuilderTypes } from './constants';
Expand All @@ -10,11 +12,15 @@ import {
ConfidentialWithdraw,
ConfigureConfidentialTransferAccount,
InstructionParams,
Memo,
VerifyEqualityProof,
VerifyPubkeyValidity,
VerifyRangeProof,
VerifyValidityProof,
} from './iface';
import { compileTransactionMessage } from './serialization/compileTransactionMessage';
import { serializeWireTransaction } from './serialization/wire-transaction';
import { solInstructionFactory } from './solInstructionFactory';
import assert from 'assert';

/**
Expand Down Expand Up @@ -43,6 +49,8 @@ import assert from 'assert';
*/
export class ConfidentialTransferBuilder extends TransactionBuilder {
private _ctInstructions: InstructionParams[] = [];
private _version?: SolTransactionVersion;
private _v1TransactionConfig?: SolV1TransactionConfig;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
Expand All @@ -53,6 +61,35 @@ export class ConfidentialTransferBuilder extends TransactionBuilder {
return TransactionType.ConfidentialTransfer;
}

/**
* Set the Solana transaction version.
*
* Defaults to legacy until set. When set to `1`, the builder assembles a v1
* (SIMD-0296/0385) transaction: version byte `0x81`, an inline `transactionConfig`
* instead of ComputeBudget instructions, no address lookup tables, and a
* message-first wire format with signatures appended.
*
* @param version - the transaction version (0 = v0, 1 = v1)
* @returns {this} This builder
*/
version(version: SolTransactionVersion): this {
this._version = version;
return this;
}

/**
* Set the v1 transaction config (compute unit limit, heap size, loaded accounts
* data size limit, and priority fee as total lamports). Required when
* `version(1)` is set.
*
* @param config - the v1 transaction config
* @returns {this} This builder
*/
transactionConfig(config: SolV1TransactionConfig): this {
this._v1TransactionConfig = config;
return this;
}

/**
* Override the zk-elgamal-proof program id.
*
Expand Down Expand Up @@ -232,8 +269,87 @@ export class ConfidentialTransferBuilder extends TransactionBuilder {
protected async buildImplementation(): Promise<Transaction> {
assert(this._ctInstructions.length > 0, 'At least one confidential transfer instruction must be specified');

if (this._version === 1) {
return this.buildV1();
}

this._instructionsData = [...this._ctInstructions];

return await super.buildImplementation();
}

/**
* Build a v1 (SIMD-0296/0385) confidential transfer transaction.
*
* Assembles the CT instructions via the shared instruction factory, compiles
* and serializes a v1 message with the inline transaction config, signs the
* message bytes with the builder's signers, and stores the resulting wire
* bytes for broadcast. Also populates a metadata-only SolTransaction so the
* transaction JSON and input/output extraction remain usable.
*
* @returns {Transaction} The built transaction holding the v1 wire bytes
*/
private buildV1(): Transaction {
assert(this._sender, new BuildTransactionError('sender is required before building'));
assert(this._recentBlockhash, new BuildTransactionError('recent blockhash is required before building'));
assert(this._v1TransactionConfig, 'transactionConfig is required to build a v1 confidential transfer transaction');

// ApplyPendingBalance must remain instruction #1 in v1 spend txs (it is idempotent),
// regardless of the order the caller added instructions.
this._ctInstructions = [
...this._ctInstructions.filter((i) => i.type === InstructionBuilderTypes.ApplyPendingBalance),
...this._ctInstructions.filter((i) => i.type !== InstructionBuilderTypes.ApplyPendingBalance),
];

const instructions: TransactionInstruction[] = [];
for (const instruction of this._ctInstructions) {
instructions.push(...solInstructionFactory(instruction, this._zkProofProgramId));
}

if (this._memo) {
const memoData: Memo = {
type: InstructionBuilderTypes.Memo,
params: { memo: this._memo },
};
this._ctInstructions.push(memoData);
instructions.push(...solInstructionFactory(memoData));
}

const feePayer = this._feePayer ? new PublicKey(this._feePayer) : new PublicKey(this._sender);
const messageBytes = compileTransactionMessage({
version: 1,
instructions,
feePayer,
recentBlockhash: this._recentBlockhash,
transactionConfig: this._v1TransactionConfig,
});

const signatures: Uint8Array[] = [];
for (const signer of this._signers) {
const secretKey = signer.getKeys(true).prv;
assert(secretKey instanceof Uint8Array, 'Missing private key');
signatures.push(nacl.sign.detached(messageBytes, secretKey));
}
for (const signature of this.getAdditionalSignatures()) {
signatures.push(new Uint8Array(signature.signature));
}

const v1Wire = serializeWireTransaction(messageBytes, signatures);

this._transaction.v1TransactionBytes = v1Wire;
this._transaction.v1MessageBytes = messageBytes;

// Populate a metadata-only SolTransaction so toJson / loadInputsAndOutputs work.
const metaTx = new SolTransaction();
metaTx.feePayer = feePayer;
metaTx.recentBlockhash = this._recentBlockhash;
metaTx.add(...instructions);
this._transaction.solTransaction = metaTx;

this._transaction.setTransactionType(this.transactionType);
this._transaction.setInstructionsData(this._ctInstructions);
this._transaction.loadInputsAndOutputs();

return this._transaction;
}
}
56 changes: 55 additions & 1 deletion modules/sdk-coin-sol/src/lib/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export class Transaction extends BaseTransaction {
private _useTokenAddressTokenName = false;
private _versionedTransaction: VersionedTransaction | undefined;
private _versionedTransactionData: VersionedTransactionData | undefined;
private _v1TransactionBytes: Uint8Array | undefined;
private _v1MessageBytes: Uint8Array | undefined;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
Expand All @@ -86,6 +88,9 @@ export class Transaction extends BaseTransaction {

/** @inheritDoc */
get signablePayload(): Buffer {
if (this._v1MessageBytes) {
return Buffer.from(this._v1MessageBytes);
}
if (this._versionedTransaction) {
return Buffer.from(this._versionedTransaction.message.serialize());
}
Expand All @@ -95,6 +100,18 @@ export class Transaction extends BaseTransaction {
/** @inheritDoc **/
get id(): string {
// Solana transaction ID === first signature: https://docs.solana.com/terminology#transaction-id
if (this._v1TransactionBytes) {
// v1 wire format: messageBytes followed by 64-byte signatures; the first signature is the tx id
const numRequired = this._v1TransactionBytes[1];
const sigStart = this._v1TransactionBytes.length - numRequired * 64;
if (numRequired > 0 && sigStart >= 0) {
const sig = this._v1TransactionBytes.slice(sigStart, sigStart + 64);
if (sig.some((byte) => byte !== 0)) {
return base58.encode(sig);
}
}
}

if (this._versionedTransaction) {
const sig = this._versionedTransaction.signatures?.[0];
// Check if signature exists and is not a placeholder signature (all zeros)
Expand Down Expand Up @@ -181,7 +198,39 @@ export class Transaction extends BaseTransaction {
* @returns {boolean} True if this is a VersionedTransaction
*/
isVersionedTransaction(): boolean {
return !!this._versionedTransaction || !!this._versionedTransactionData;
return !!this._versionedTransaction || !!this._versionedTransactionData || !!this._v1TransactionBytes;
}

/**
* Get the serialized v1 wire transaction bytes (message + signatures), if this transaction is v1
* @returns {Uint8Array | undefined} The v1 wire bytes or undefined
*/
get v1TransactionBytes(): Uint8Array | undefined {
return this._v1TransactionBytes;
}

/**
* Set the serialized v1 wire transaction bytes (message + signatures)
* @param {Uint8Array | undefined} bytes The v1 wire bytes to store, or undefined to clear
*/
set v1TransactionBytes(bytes: Uint8Array | undefined) {
this._v1TransactionBytes = bytes;
}

/**
* Get the serialized v1 message bytes (without signatures), if this transaction is v1
* @returns {Uint8Array | undefined} The v1 message bytes or undefined
*/
get v1MessageBytes(): Uint8Array | undefined {
return this._v1MessageBytes;
}

/**
* Set the serialized v1 message bytes (without signatures)
* @param {Uint8Array | undefined} bytes The v1 message bytes to store, or undefined to clear
*/
set v1MessageBytes(bytes: Uint8Array | undefined) {
this._v1MessageBytes = bytes;
}

/**
Expand Down Expand Up @@ -257,6 +306,11 @@ export class Transaction extends BaseTransaction {

/** @inheritdoc */
toBroadcastFormat(): string {
if (this._v1TransactionBytes) {
// v1 wire format is message-first with signatures appended (no length prefix)
return Buffer.from(this._v1TransactionBytes).toString('base64');
}

if (this._versionedTransaction) {
// VersionedTransaction.serialize() doesn't need requireAllSignatures parameter
// It automatically handles whatever signatures are present
Expand Down
9 changes: 9 additions & 0 deletions modules/sdk-coin-sol/src/lib/transactionBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,15 @@ export abstract class TransactionBuilder extends BaseTransactionBuilder {
this._signatures.push({ publicKey, signature });
}

/**
* Get the externally-added signatures (via addSignature) in order.
*
* @returns {Signature[]} The list of external signatures
*/
protected getAdditionalSignatures(): Signature[] {
return this._signatures;
}

/**
* Sets the sender of this transaction.
* This account will be responsible for paying transaction fees.
Expand Down
Loading
Loading