From b502bcba272169fdb6fbfaebb52a131db1e6591f Mon Sep 17 00:00:00 2001 From: Bhavi Dhingra Date: Tue, 29 Sep 2026 21:03:32 +0530 Subject: [PATCH] feat(sdk-coin-sol): add v1 confidential transfer build, ops, example Refs: CHALO-1602 --- examples/ts/sol/sdk-ct-v1-broadcast.ts | 108 +++++++++++++ .../src/lib/confidentialTransferBuilder.ts | 118 +++++++++++++- modules/sdk-coin-sol/src/lib/transaction.ts | 56 ++++++- .../src/lib/transactionBuilder.ts | 9 ++ .../confidentialTransferV1.ts | 128 ++++++++++++++++ .../confidentialTransferV1Ops.ts | 144 ++++++++++++++++++ 6 files changed, 561 insertions(+), 2 deletions(-) create mode 100644 examples/ts/sol/sdk-ct-v1-broadcast.ts create mode 100644 modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1.ts create mode 100644 modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1Ops.ts diff --git a/examples/ts/sol/sdk-ct-v1-broadcast.ts b/examples/ts/sol/sdk-ct-v1-broadcast.ts new file mode 100644 index 00000000000..6857c0ac69c --- /dev/null +++ b/examples/ts/sol/sdk-ct-v1-broadcast.ts @@ -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= SDK_E2E_INPUT= EXTB_STATE= \ + * PAYER_SECRET_B64= 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); +}); diff --git a/modules/sdk-coin-sol/src/lib/confidentialTransferBuilder.ts b/modules/sdk-coin-sol/src/lib/confidentialTransferBuilder.ts index 760fc6dd6db..7f55f676e94 100644 --- a/modules/sdk-coin-sol/src/lib/confidentialTransferBuilder.ts +++ b/modules/sdk-coin-sol/src/lib/confidentialTransferBuilder.ts @@ -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'; @@ -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'; /** @@ -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) { super(_coinConfig); @@ -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. * @@ -232,8 +269,87 @@ export class ConfidentialTransferBuilder extends TransactionBuilder { protected async buildImplementation(): Promise { 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; + } } diff --git a/modules/sdk-coin-sol/src/lib/transaction.ts b/modules/sdk-coin-sol/src/lib/transaction.ts index 2e2c15b5949..b726090e11d 100644 --- a/modules/sdk-coin-sol/src/lib/transaction.ts +++ b/modules/sdk-coin-sol/src/lib/transaction.ts @@ -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) { super(_coinConfig); @@ -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()); } @@ -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) @@ -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; } /** @@ -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 diff --git a/modules/sdk-coin-sol/src/lib/transactionBuilder.ts b/modules/sdk-coin-sol/src/lib/transactionBuilder.ts index 0fb4f70111e..05f1a04ea90 100644 --- a/modules/sdk-coin-sol/src/lib/transactionBuilder.ts +++ b/modules/sdk-coin-sol/src/lib/transactionBuilder.ts @@ -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. diff --git a/modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1.ts b/modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1.ts new file mode 100644 index 00000000000..9da3a5a9cdc --- /dev/null +++ b/modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1.ts @@ -0,0 +1,128 @@ +import 'should'; +import { KeyPair, Sol, Transaction, Utils } from '../../../src'; +import * as testData from '../../resources/sol'; +import { getBuilderFactory } from '../getBuilderFactory'; + +describe('Solana Confidential Transfer Builder - v1', () => { + const factory = getBuilderFactory('sol'); + const account = new KeyPair(testData.associatedTokenAccounts.accounts[0]).getKeys(); + const recentBlockHash = 'GHtXQBsoZHVnNFa9YevAzFr17DJjgHXk3ycTKD5xD3Zi'; + + const mintAddress = testData.associatedTokenAccountsForSol2022.mintId; + const tokenAddress = testData.associatedTokenAccountsForSol2022.accounts[0].ata; + const destinationTokenAddress = 'ENn8a2tGMS9bR5XV7smGHJvNgzkyxJmnD2eUvQxY5jSP'; + const authorityAddress = account.pub; + + const zeroBytes36 = '00'.repeat(36); + const zeroBytes64 = '00'.repeat(64); + const proofDataHex = '00'.repeat(320); + + const v1Config = { + computeUnitLimit: 200_000, + heapSize: 32_768, + loadedAccountsDataSizeLimit: 65_536, + priorityFee: 5_000, + }; + + const ctBuilder = () => { + const txBuilder = factory.getConfidentialTransferBuilder(); + txBuilder.nonce(recentBlockHash); + txBuilder.sender(account.pub); + txBuilder.sign({ key: account.prv }); + return txBuilder; + }; + + const addTransfer = (builder: ReturnType) => { + builder + .applyPendingBalance({ + tokenAddress, + authorityAddress, + expectedPendingBalanceCreditCounter: '2', + newDecryptableAvailableBalance: zeroBytes36, + }) + .verifyEqualityProof({ proofData: proofDataHex }) + .verifyValidityProof({ proofData: proofDataHex }) + .verifyRangeProof({ proofData: '00'.repeat(1000) }) + .confidentialTransfer({ + sourceTokenAddress: tokenAddress, + mintAddress, + destinationTokenAddress, + authorityAddress, + newSourceDecryptableAvailableBalance: zeroBytes36, + transferAmountAuditorCiphertextLo: zeroBytes64, + transferAmountAuditorCiphertextHi: zeroBytes64, + equalityProofInstructionOffset: 1, + ciphertextValidityProofInstructionOffset: 2, + rangeProofInstructionOffset: 3, + }); + }; + + it('should build a v1 confidential transfer transaction (0x81 prefix, within 4096 bytes)', async () => { + const builder = ctBuilder(); + addTransfer(builder); + builder.version(1).transactionConfig(v1Config); + + const tx = await builder.build(); + + (tx as Transaction).isVersionedTransaction().should.equal(true); + (tx as Transaction).v1TransactionBytes!.should.be.an.instanceOf(Uint8Array); + + const rawTx = tx.toBroadcastFormat(); + const wire = Buffer.from(rawTx, 'base64'); + + // v1 version byte prefix + wire[0].should.equal(0x81); + // within the v1 wire size limit + wire.length.should.be.lessThanOrEqual(4096); + + // config preserved in the decoded v1 message + }); + + it('should require transactionConfig when version(1) is set', async () => { + const builder = ctBuilder(); + addTransfer(builder); + builder.version(1); + + await builder.build().should.be.rejectedWith(/transactionConfig is required/); + }); + + it('should reject v1 transactions that exceed the 4096-byte wire limit at broadcast', async () => { + const builder = ctBuilder(); + addTransfer(builder); + builder.version(1).transactionConfig(v1Config); + + const tx = await builder.build(); + const rawTx = (tx as Transaction).toBroadcastFormat(); + + // Force an oversized v1 payload by padding the wire bytes past the limit. + const wire = Buffer.from(rawTx, 'base64'); + const oversized = Buffer.concat([wire, Buffer.alloc(4097)]); + oversized[0].should.equal(0x81); + + // Broadcast the oversized v1 tx through Sol.prototype.broadcastTransaction with an RPC + // stub that must not be reached - the size guard short-circuits before the RPC call. + const coin = { getDataFromNode: () => Promise.reject(new Error('RPC should not be reached')) } as unknown as Sol; + await (Sol.prototype.broadcastTransaction as (opts: { serializedSignedTransaction: string }) => Promise) + .call(coin, { serializedSignedTransaction: oversized.toString('base64') }) + .should.be.rejectedWith(/exceeds the 4096-byte size limit/); + }); + + it('should leave the non-v1 path unchanged (v0/legacy default)', async () => { + const builder = ctBuilder(); + builder.configureAccount({ + tokenAddress, + mintAddress, + authorityAddress, + decryptableZeroBalance: zeroBytes36, + maximumPendingBalanceCreditCounter: '65536', + proofInstructionOffset: 1, + }); + + const tx = await builder.build(); + const rawTx = (tx as Transaction).toBroadcastFormat(); + // legacy transaction does not carry the 0x81 v1 prefix + Buffer.from(rawTx, 'base64')[0].should.not.equal(0x81); + (tx as Transaction).isVersionedTransaction().should.equal(false); + Utils.isValidRawTransaction(rawTx).should.equal(true); + }); +}); diff --git a/modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1Ops.ts b/modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1Ops.ts new file mode 100644 index 00000000000..c8368aba062 --- /dev/null +++ b/modules/sdk-coin-sol/test/unit/transactionBuilder/confidentialTransferV1Ops.ts @@ -0,0 +1,144 @@ +import 'should'; +import { KeyPair, Transaction } from '../../../src'; +import * as testData from '../../resources/sol'; +import { getBuilderFactory } from '../getBuilderFactory'; + +describe('Solana Confidential Transfer Builder - v1 per-op', () => { + const factory = getBuilderFactory('sol'); + const account = new KeyPair(testData.associatedTokenAccounts.accounts[0]).getKeys(); + const recentBlockHash = 'GHtXQBsoZHVnNFa9YevAzFr17DJjgHXk3ycTKD5xD3Zi'; + + const mintAddress = testData.associatedTokenAccountsForSol2022.mintId; + const tokenAddress = testData.associatedTokenAccountsForSol2022.accounts[0].ata; + const destinationTokenAddress = 'ENn8a2tGMS9bR5XV7smGHJvNgzkyxJmnD2eUvQxY5jSP'; + const authorityAddress = account.pub; + + const zeroBytes36 = '00'.repeat(36); + const zeroBytes64 = '00'.repeat(64); + const proofDataHex = '00'.repeat(320); + + const v1Config = { + computeUnitLimit: 200_000, + heapSize: 32_768, + loadedAccountsDataSizeLimit: 65_536, + priorityFee: 5_000, + }; + + const ctBuilder = () => { + const b = factory.getConfidentialTransferBuilder(); + b.nonce(recentBlockHash).sender(account.pub).sign({ key: account.prv }); + return b; + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const toV1 = (b: any) => b.version(1).transactionConfig(v1Config); + + const assertV1 = (tx: Transaction) => { + const wire = Buffer.from((tx as Transaction).toBroadcastFormat(), 'base64'); + wire[0].should.equal(0x81); + wire.length.should.be.lessThanOrEqual(4096); + (tx as Transaction).v1MessageBytes!.should.be.an.instanceOf(Uint8Array); + }; + + it('should build a Deposit as a valid v1 transaction', async () => { + const b = ctBuilder(); + b.confidentialDeposit({ tokenAddress, mintAddress, authorityAddress, amount: '1000000', decimals: 6 }); + const tx = await toV1(b).build(); + assertV1(tx); + }); + + it('should build a Withdraw (with equality + range proofs) as a valid v1 transaction', async () => { + const b = ctBuilder(); + b.confidentialWithdraw({ + tokenAddress, + mintAddress, + authorityAddress, + amount: '500000', + decimals: 6, + newDecryptableAvailableBalance: zeroBytes36, + equalityProofInstructionOffset: 1, + rangeProofInstructionOffset: 2, + }) + .verifyEqualityProof({ proofData: proofDataHex }) + .verifyRangeProof({ proofData: '00'.repeat(1000) }); + const tx = await toV1(b).build(); + assertV1(tx); + }); + + it('should force ApplyPendingBalance to instruction #1 even when added last', async () => { + const b = ctBuilder(); + // Deliberately add Deposit first, then ApplyPendingBalance out of order. + b.confidentialDeposit({ + tokenAddress, + mintAddress, + authorityAddress, + amount: '1000000', + decimals: 6, + }).applyPendingBalance({ + tokenAddress, + authorityAddress, + expectedPendingBalanceCreditCounter: '2', + newDecryptableAvailableBalance: zeroBytes36, + }); + const tx = await toV1(b).build(); + assertV1(tx); + const instructions = tx.toJson().instructionsData; + instructions.should.have.length(2); + instructions[0].type.should.equal('ApplyPendingBalance'); + instructions[1].type.should.equal('ConfidentialDeposit'); + }); + + it('should build a private Transfer with all proofs as a valid v1 transaction', async () => { + const b = ctBuilder(); + b.applyPendingBalance({ + tokenAddress, + authorityAddress, + expectedPendingBalanceCreditCounter: '2', + newDecryptableAvailableBalance: zeroBytes36, + }) + .verifyEqualityProof({ proofData: proofDataHex }) + .verifyValidityProof({ proofData: proofDataHex }) + .verifyRangeProof({ proofData: '00'.repeat(1000) }) + .confidentialTransfer({ + sourceTokenAddress: tokenAddress, + mintAddress, + destinationTokenAddress, + authorityAddress, + newSourceDecryptableAvailableBalance: zeroBytes36, + transferAmountAuditorCiphertextLo: zeroBytes64, + transferAmountAuditorCiphertextHi: zeroBytes64, + equalityProofInstructionOffset: 1, + ciphertextValidityProofInstructionOffset: 2, + rangeProofInstructionOffset: 3, + }); + const tx = await toV1(b).build(); + assertV1(tx); + const instructions = tx.toJson().instructionsData; + instructions[0].type.should.equal('ApplyPendingBalance'); + instructions[4].type.should.equal('ConfidentialTransfer'); + }); + + it('should build ConfigureAccount + VerifyPubkeyValidity as a valid v1 transaction', async () => { + const b = ctBuilder(); + b.configureAccount({ + tokenAddress, + mintAddress, + authorityAddress, + decryptableZeroBalance: zeroBytes36, + maximumPendingBalanceCreditCounter: '65536', + proofInstructionOffset: 1, + }).verifyPubkeyValidity({ proofData: proofDataHex }); + const tx = await toV1(b).build(); + assertV1(tx); + }); + + it('should build each verify-proof instruction through v1', async () => { + const b = ctBuilder(); + b.verifyEqualityProof({ proofData: proofDataHex }) + .verifyValidityProof({ proofData: proofDataHex }) + .verifyRangeProof({ proofData: '00'.repeat(1000) }) + .verifyPubkeyValidity({ proofData: proofDataHex }); + const tx = await toV1(b).build(); + assertV1(tx); + }); +});