From f097c77ab2535d6dafd2a27d41d6e6e34dc5f661 Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Mon, 30 Nov 2026 15:57:13 -0500 Subject: [PATCH 01/15] fix(sdk-coin-hbar): use stellar-base for key conversion TICKET: WCN-5238 --- modules/sdk-coin-hbar/package.json | 2 +- modules/sdk-coin-hbar/src/hbar.ts | 4 ++-- modules/sdk-coin-hbar/src/lib/utils.ts | 6 +++--- modules/sdk-coin-hbar/src/seedValidator.ts | 6 +++--- modules/sdk-coin-hbar/test/unit/utils.ts | 8 ++++---- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/sdk-coin-hbar/package.json b/modules/sdk-coin-hbar/package.json index 4aced5d1a4b..114425e6596 100644 --- a/modules/sdk-coin-hbar/package.json +++ b/modules/sdk-coin-hbar/package.json @@ -50,7 +50,7 @@ "lodash": "^4.18.0", "long": "^5.2.3", "protobufjs": "^7.5.8", - "stellar-sdk": "^10.0.1", + "stellar-base": "^8.2.2", "superagent": "^9.0.1", "tweetnacl": "^1.0.3" }, diff --git a/modules/sdk-coin-hbar/src/hbar.ts b/modules/sdk-coin-hbar/src/hbar.ts index 81586a463ec..d9981291999 100644 --- a/modules/sdk-coin-hbar/src/hbar.ts +++ b/modules/sdk-coin-hbar/src/hbar.ts @@ -33,7 +33,7 @@ import { RecoveryKeyMismatchError, } from '@bitgo/sdk-core'; import { BigNumber } from 'bignumber.js'; -import * as stellar from 'stellar-sdk'; +import { StrKey } from 'stellar-base'; import { SeedValidator } from './seedValidator'; import { KeyPair as HbarKeyPair, TransactionBuilderFactory, Transaction, Recipient as HederaRecipient } from './lib'; import * as Utils from './lib/utils'; @@ -889,7 +889,7 @@ export class Hbar extends BaseCoin { } if (SeedValidator.isValidEd25519SeedForCoin(seed, CoinFamily.XLM)) { - const keyFromSeed = new HbarKeyPair({ seed: stellar.StrKey.decodeEd25519SecretSeed(seed) }); + const keyFromSeed = new HbarKeyPair({ seed: StrKey.decodeEd25519SecretSeed(seed) }); const keys = keyFromSeed.getKeys(); if (keys !== undefined && keys.prv) { return keys.prv; diff --git a/modules/sdk-coin-hbar/src/lib/utils.ts b/modules/sdk-coin-hbar/src/lib/utils.ts index e41a633c7ed..5e084c2121e 100644 --- a/modules/sdk-coin-hbar/src/lib/utils.ts +++ b/modules/sdk-coin-hbar/src/lib/utils.ts @@ -2,7 +2,7 @@ import * as _ from 'lodash'; import { AccountId, PrivateKey, PublicKey, TokenId, TransactionId } from '@hashgraph/sdk'; import { proto } from '@hashgraph/proto'; import BigNumber from 'bignumber.js'; -import * as stellar from 'stellar-sdk'; +import { StrKey } from 'stellar-base'; import { AddressDetails } from './iface'; import url from 'url'; import { toHex, toUint8Array, UtilsError } from '@bitgo/sdk-core'; @@ -213,11 +213,11 @@ export function createRawKey(prv: string): PrivateKey { * @returns {string} */ export function convertFromStellarPub(stellarPub: string): string { - if (!stellar.StrKey.isValidEd25519PublicKey(stellarPub)) { + if (!StrKey.isValidEd25519PublicKey(stellarPub)) { throw new Error('Not a valid stellar pub.'); } - const rawKey: Buffer = stellar.StrKey.decodeEd25519PublicKey(stellarPub); + const rawKey: Buffer = StrKey.decodeEd25519PublicKey(stellarPub); return rawKey.toString('hex'); } diff --git a/modules/sdk-coin-hbar/src/seedValidator.ts b/modules/sdk-coin-hbar/src/seedValidator.ts index 5e12732ad6a..fa12e7c8e58 100644 --- a/modules/sdk-coin-hbar/src/seedValidator.ts +++ b/modules/sdk-coin-hbar/src/seedValidator.ts @@ -1,4 +1,4 @@ -import * as stellar from 'stellar-sdk'; +import { StrKey } from 'stellar-base'; import * as _ from 'lodash'; import { CoinFamily } from '@bitgo/statics'; import { createRawKey } from './lib/utils'; @@ -23,7 +23,7 @@ export class SeedValidator { // competing seed format check if (AlgoLib.algoUtils.isValidSeed(seed)) coin = CoinFamily.ALGO; - if (stellar.StrKey.isValidEd25519SecretSeed(seed)) coin = CoinFamily.XLM; + if (StrKey.isValidEd25519SecretSeed(seed)) coin = CoinFamily.XLM; if (SeedValidator.isValidHbarSeedFormat(seed)) coin = CoinFamily.HBAR; } @@ -47,7 +47,7 @@ export class SeedValidator { */ static hasCompetingSeedFormats(seed: string): boolean { const isAlgoSeed = AlgoLib.algoUtils.isValidSeed(seed); - const isStellarSeed = stellar.StrKey.isValidEd25519SecretSeed(seed); + const isStellarSeed = StrKey.isValidEd25519SecretSeed(seed); const isHbarSeed = SeedValidator.isValidHbarSeedFormat(seed); return _.sum([isAlgoSeed, isStellarSeed, isHbarSeed]) !== 1; diff --git a/modules/sdk-coin-hbar/test/unit/utils.ts b/modules/sdk-coin-hbar/test/unit/utils.ts index a5785cbc954..9c26dd07f37 100644 --- a/modules/sdk-coin-hbar/test/unit/utils.ts +++ b/modules/sdk-coin-hbar/test/unit/utils.ts @@ -1,6 +1,6 @@ import assert from 'assert'; import should from 'should'; -import * as stellar from 'stellar-sdk'; +import { Keypair, StrKey } from 'stellar-base'; import * as Utils from '../../src/lib/utils'; import * as testData from '../resources/hbar'; import { isValidEd25519PublicKey } from '@bitgo/sdk-core'; @@ -101,9 +101,9 @@ describe('HBAR util library', function () { const stellarPub = 'GBVEZT27ZUCMJABF76XIPPO7M3KUABVR4GZNPBAD3YTPXUSDA57ANRLD'; const newPub = Utils.convertFromStellarPub(stellarPub); - const stellarDecoded = stellar.StrKey.encodeEd25519PublicKey(Buffer.from(newPub, 'hex')); - const beginStellarKeyPair = stellar.Keypair.fromPublicKey(stellarPub); - const endStellarKeyPair = stellar.Keypair.fromPublicKey(stellarDecoded); + const stellarDecoded = StrKey.encodeEd25519PublicKey(Buffer.from(newPub, 'hex')); + const beginStellarKeyPair = Keypair.fromPublicKey(stellarPub); + const endStellarKeyPair = Keypair.fromPublicKey(stellarDecoded); should.equal(beginStellarKeyPair.publicKey(), endStellarKeyPair.publicKey()); }); From 1af4777dd24b67602dbb2523ebcdeb58d9c5dd2c Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Mon, 30 Nov 2026 15:57:02 -0500 Subject: [PATCH 02/15] fix(sdk-coin-algo): use stellar-base for key conversion TICKET: WCN-5232 --- modules/sdk-coin-algo/package.json | 2 +- modules/sdk-coin-algo/src/algo.ts | 6 +++--- modules/sdk-coin-algo/src/lib/utils.ts | 12 ++++++------ modules/sdk-coin-algo/src/seedValidator.ts | 6 +++--- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/sdk-coin-algo/package.json b/modules/sdk-coin-algo/package.json index 0a12e37e2a8..1ecf19e4a3c 100644 --- a/modules/sdk-coin-algo/package.json +++ b/modules/sdk-coin-algo/package.json @@ -50,7 +50,7 @@ "joi": "^17.4.0", "js-sha512": "0.8.0", "lodash": "^4.18.0", - "stellar-sdk": "^10.0.1", + "stellar-base": "^8.2.2", "tweetnacl": "^1.0.3" }, "devDependencies": { diff --git a/modules/sdk-coin-algo/src/algo.ts b/modules/sdk-coin-algo/src/algo.ts index 7b51d89cd9f..82b7034c9ae 100644 --- a/modules/sdk-coin-algo/src/algo.ts +++ b/modules/sdk-coin-algo/src/algo.ts @@ -39,7 +39,7 @@ import { AuditDecryptedKeyParams, TxIntentMismatchError, } from '@bitgo/sdk-core'; -import stellar from 'stellar-sdk'; +import { StrKey } from 'stellar-base'; import BigNumber from 'bignumber.js'; import Utils from './lib/utils'; import { TxData } from './lib/ifaces'; @@ -1175,8 +1175,8 @@ export class Algo extends BaseCoin { } // we have a stellar key - if (stellar.StrKey.isValidEd25519PublicKey(addressOrPubKey)) { - const stellarPub = stellar.StrKey.decodeEd25519PublicKey(addressOrPubKey); + if (StrKey.isValidEd25519PublicKey(addressOrPubKey)) { + const stellarPub = StrKey.decodeEd25519PublicKey(addressOrPubKey); const algoAddress = AlgoLib.algoUtils.encodeAddress(stellarPub); if (this.isValidAddress(algoAddress)) { return algoAddress; diff --git a/modules/sdk-coin-algo/src/lib/utils.ts b/modules/sdk-coin-algo/src/lib/utils.ts index 9e248d8b84e..ae5977a0590 100644 --- a/modules/sdk-coin-algo/src/lib/utils.ts +++ b/modules/sdk-coin-algo/src/lib/utils.ts @@ -1,5 +1,5 @@ import algosdk from 'algosdk'; -import stellar from 'stellar-sdk'; +import { StrKey } from 'stellar-base'; import * as hex from '@stablelib/hex'; import * as nacl from 'tweetnacl'; import base32 from 'hi-base32'; @@ -421,23 +421,23 @@ export class Utils implements BaseUtils { } /** - * Validates the key with the stellar-sdk + * Validates a Stellar StrKey public key * * @param publicKey * @returns boolean */ protected isValidEd25519PublicKeyStellar(publicKey: string): boolean { - return stellar.StrKey.isValidEd25519PublicKey(publicKey); + return StrKey.isValidEd25519PublicKey(publicKey); } /** - * Decodes the key with the stellar-sdk + * Decodes a Stellar StrKey public key * * @param publicKey * @returns Buffer */ protected decodeEd25519PublicKeyStellar(publicKey: string): Buffer { - return stellar.StrKey.decodeEd25519PublicKey(publicKey); + return StrKey.decodeEd25519PublicKey(publicKey); } /** @@ -447,7 +447,7 @@ export class Utils implements BaseUtils { * @returns string the encoded seed */ convertFromStellarSeed(seed: string): string { - return SeedEncoding.encode(stellar.StrKey.decodeEd25519SecretSeed(seed)); + return SeedEncoding.encode(StrKey.decodeEd25519SecretSeed(seed)); } /** diff --git a/modules/sdk-coin-algo/src/seedValidator.ts b/modules/sdk-coin-algo/src/seedValidator.ts index 64bcea32d07..86e571a2ddd 100644 --- a/modules/sdk-coin-algo/src/seedValidator.ts +++ b/modules/sdk-coin-algo/src/seedValidator.ts @@ -1,4 +1,4 @@ -import * as stellar from 'stellar-sdk'; +import { StrKey } from 'stellar-base'; import * as _ from 'lodash'; import { CoinFamily } from '@bitgo/statics'; import { algoUtils } from './lib'; @@ -23,7 +23,7 @@ export class SeedValidator { // competing seed format check if (algoUtils.isValidSeed(seed)) coin = CoinFamily.ALGO; - if (stellar.StrKey.isValidEd25519SecretSeed(seed)) coin = CoinFamily.XLM; + if (StrKey.isValidEd25519SecretSeed(seed)) coin = CoinFamily.XLM; if (SeedValidator.isValidHbarSeedFormat(seed)) coin = CoinFamily.HBAR; } @@ -47,7 +47,7 @@ export class SeedValidator { */ static hasCompetingSeedFormats(seed: string): boolean { const isAlgoSeed = algoUtils.isValidSeed(seed); - const isStellarSeed = stellar.StrKey.isValidEd25519SecretSeed(seed); + const isStellarSeed = StrKey.isValidEd25519SecretSeed(seed); const isHbarSeed = SeedValidator.isValidHbarSeedFormat(seed); return _.sum([isAlgoSeed, isStellarSeed, isHbarSeed]) !== 1; From e260012224aa85d09c103340a7ae93223793ea2d Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Mon, 30 Nov 2026 15:56:45 -0500 Subject: [PATCH 03/15] refactor(sdk-coin-polygon): move ethers to test dependencies TICKET: WCN-5233 --- modules/sdk-coin-polygon/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/sdk-coin-polygon/package.json b/modules/sdk-coin-polygon/package.json index 473264fb733..2fd3864901a 100644 --- a/modules/sdk-coin-polygon/package.json +++ b/modules/sdk-coin-polygon/package.json @@ -47,13 +47,13 @@ "@ethereumjs/common": "^2.6.5", "bignumber.js": "^9.1.2", "ethereumjs-abi": "^0.6.5", - "ethereumjs-util": "7.1.5", - "ethers": "^5.1.3" + "ethereumjs-util": "7.1.5" }, "devDependencies": { "@bitgo/sdk-api": "^3.5.0", "@bitgo/sdk-test": "^9.1.100", "@bitgo/sjcl": "^1.1.0", + "ethers": "^5.1.3", "secp256k1": "5.0.1" }, "gitHead": "18e460ddf02de2dbf13c2aa243478188fb539f0c", From ee7bf32758187c7facb0387495aff0ddaff1e20a Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Mon, 30 Nov 2026 15:56:41 -0500 Subject: [PATCH 04/15] fix(sdk-api): move test-only proxy agent to dev dependencies (WCN-5237) --- modules/sdk-api/package.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/sdk-api/package.json b/modules/sdk-api/package.json index c10476629ad..1024c67422a 100644 --- a/modules/sdk-api/package.json +++ b/modules/sdk-api/package.json @@ -5,7 +5,6 @@ "main": "./dist/src/index.js", "types": "./dist/src/index.d.ts", "browser": { - "proxy-agent": false, "https": false, "tls": false }, @@ -54,12 +53,14 @@ "eol": "^0.5.0", "io-ts": "npm:@bitgo-forks/io-ts@2.1.4", "lodash": "^4.18.0", - "proxy-agent": "6.4.0", "sanitize-html": "^2.17.4", "secp256k1": "5.0.1", "secrets.js-grempe": "^1.1.0", "superagent": "^9.0.1" }, + "devDependencies": { + "proxy-agent": "6.4.0" + }, "overrides": { "degenerator": "5.0.0" }, From 3320052b13d8a5f864821186fb0be9b2cbebba4b Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Tue, 1 Dec 2026 16:06:23 -0500 Subject: [PATCH 05/15] test(sdk-coin-polygon): use standalone ethers packages in send test Import defaultAbiCoder and keccak256 from @ethersproject/abi and @ethersproject/keccak256, the same 5.8.0 packages abstract-eth pins, so the Polygon package no longer needs the full ethers package even as a development dependency. TICKET: WCN-5233 Co-Authored-By: Claude Opus 5.5 --- modules/sdk-coin-polygon/package.json | 3 ++- modules/sdk-coin-polygon/test/unit/transactionBuilder/send.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/sdk-coin-polygon/package.json b/modules/sdk-coin-polygon/package.json index 2fd3864901a..900ecc0396d 100644 --- a/modules/sdk-coin-polygon/package.json +++ b/modules/sdk-coin-polygon/package.json @@ -53,7 +53,8 @@ "@bitgo/sdk-api": "^3.5.0", "@bitgo/sdk-test": "^9.1.100", "@bitgo/sjcl": "^1.1.0", - "ethers": "^5.1.3", + "@ethersproject/abi": "5.8.0", + "@ethersproject/keccak256": "5.8.0", "secp256k1": "5.0.1" }, "gitHead": "18e460ddf02de2dbf13c2aa243478188fb539f0c", diff --git a/modules/sdk-coin-polygon/test/unit/transactionBuilder/send.ts b/modules/sdk-coin-polygon/test/unit/transactionBuilder/send.ts index 1b48953635f..8d5db54cf4e 100644 --- a/modules/sdk-coin-polygon/test/unit/transactionBuilder/send.ts +++ b/modules/sdk-coin-polygon/test/unit/transactionBuilder/send.ts @@ -5,7 +5,8 @@ import { decodeTransferData } from '@bitgo/abstract-eth'; import { getBuilder } from '../../getBuilder'; import { TransactionBuilder, KeyPair } from '../../../src'; import * as testData from '../../resources'; -import { defaultAbiCoder, keccak256 } from 'ethers/lib/utils'; +import { defaultAbiCoder } from '@ethersproject/abi'; +import { keccak256 } from '@ethersproject/keccak256'; describe('Polygon transaction builder send', () => { describe('should sign and build', () => { From 1d8e7c68937c89e4402ab9bed78ef56ff7541b62 Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Tue, 1 Dec 2026 16:33:38 -0500 Subject: [PATCH 06/15] chore(sdk-api): remove unused degenerator overrides degenerator is only reachable through proxy-agent, which is now a development dependency, and the root package.json already pins it. TICKET: WCN-5237 Co-Authored-By: Claude Opus 5.5 --- modules/sdk-api/package.json | 6 ------ 1 file changed, 6 deletions(-) diff --git a/modules/sdk-api/package.json b/modules/sdk-api/package.json index 1024c67422a..3310f64af22 100644 --- a/modules/sdk-api/package.json +++ b/modules/sdk-api/package.json @@ -61,12 +61,6 @@ "devDependencies": { "proxy-agent": "6.4.0" }, - "overrides": { - "degenerator": "5.0.0" - }, - "resolutions": { - "degenerator": "5.0.0" - }, "gitHead": "18e460ddf02de2dbf13c2aa243478188fb539f0c", "files": [ "dist" From 50af1975e05541e92cfe53b13f073df7361f877b Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Tue, 1 Dec 2026 16:33:01 -0500 Subject: [PATCH 07/15] test(sdk-coin-algo): cover Stellar seed and public key conversion TICKET: WCN-5232 Co-Authored-By: Claude Opus 5.5 --- modules/sdk-coin-algo/test/unit/algo.ts | 15 +++++++++++++++ .../test/unit/algoIsWalletAddress.ts | 10 ++++++++++ 2 files changed, 25 insertions(+) diff --git a/modules/sdk-coin-algo/test/unit/algo.ts b/modules/sdk-coin-algo/test/unit/algo.ts index 672df571d4c..57d56a3295e 100644 --- a/modules/sdk-coin-algo/test/unit/algo.ts +++ b/modules/sdk-coin-algo/test/unit/algo.ts @@ -932,6 +932,21 @@ describe('ALGO:', function () { }); }); + describe('Stellar seed conversion', function () { + const stellarSeed = 'SBMWLNV75BPI2VB4G27RWOMABVRTSSF7352CCYGVELZDSHCXWCYFKXIX'; + + it('should recognize a Stellar seed', function () { + basecoin.isStellarSeed(stellarSeed).should.be.true(); + basecoin.isStellarSeed(receiver.secretKey.toString('hex')).should.be.false(); + }); + + it('should convert a Stellar seed to the Algorand seed for the same key', function () { + basecoin + .convertFromStellarSeed(stellarSeed) + .should.equal('LFS3NP7IL2GVIPBWX4NTTAANMM4URP67OQQWBVJC6I4RYV5QWBKUJUZOCE'); + }); + }); + describe('deriveKeyWithSeed', function () { it('should derive key with seed', function () { (() => { diff --git a/modules/sdk-coin-algo/test/unit/algoIsWalletAddress.ts b/modules/sdk-coin-algo/test/unit/algoIsWalletAddress.ts index 94fcf6a658d..8a75222f464 100644 --- a/modules/sdk-coin-algo/test/unit/algoIsWalletAddress.ts +++ b/modules/sdk-coin-algo/test/unit/algoIsWalletAddress.ts @@ -125,5 +125,15 @@ describe('Algo class', function () { } }); }); + + it('should validate the root address when keychains hold the same keys as Stellar public keys', async function () { + const stellarKeychains = [ + { pub: 'GDVBD5YS46XGQOONPBS7KUSIOIPZXHHMJFKLA5JWCGT6G3IASYEFTBSV' }, + { pub: 'GDZFS6IHP5SY2MBNMKSSVEZJQLROAKTMQRE6GGTFRB2CLQJ5OCTJKI62' }, + { pub: 'GBY7OYRPLKV7YQB6VCQ6TEJIHDEREWJPEPNLR5LTRTEKWIDSEWIHK6T3' }, + ]; + const params = { ...makeVerifyAddressOptions(ROOT_ADDRESS, ROOT_ADDRESS), keychains: stellarKeychains }; + (await basecoin.isWalletAddress(params)).should.be.true(); + }); }); }); From 044350fae0dec20204c17ef7a4d3e7f355a353d7 Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Mon, 30 Nov 2026 15:56:41 -0500 Subject: [PATCH 08/15] fix(sdk-lib-safes): import key derivation from secp256k1 (WCN-5239) --- modules/sdk-lib-safes/package.json | 2 +- modules/sdk-lib-safes/src/safeDerivation.ts | 2 +- modules/sdk-lib-safes/test/unit/safeDerivation.ts | 2 +- modules/sdk-lib-safes/tsconfig.json | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/sdk-lib-safes/package.json b/modules/sdk-lib-safes/package.json index 160881b84d0..cb739877040 100644 --- a/modules/sdk-lib-safes/package.json +++ b/modules/sdk-lib-safes/package.json @@ -32,8 +32,8 @@ }, "dependencies": { "@bitgo/public-types": "7.1.0", + "@bitgo/secp256k1": "^1.11.1", "@bitgo/statics": "^59.35.0", - "@bitgo/utxo-lib": "^11.25.2", "create-hmac": "^1.1.7", "fp-ts": "^2.12.2", "io-ts": "npm:@bitgo-forks/io-ts@2.1.4", diff --git a/modules/sdk-lib-safes/src/safeDerivation.ts b/modules/sdk-lib-safes/src/safeDerivation.ts index bfca618970d..5e22f235ee0 100644 --- a/modules/sdk-lib-safes/src/safeDerivation.ts +++ b/modules/sdk-lib-safes/src/safeDerivation.ts @@ -13,7 +13,7 @@ */ import * as t from 'io-ts'; import * as nacl from 'tweetnacl'; -import { bip32, BIP32Interface } from '@bitgo/utxo-lib'; +import { bip32, BIP32Interface } from '@bitgo/secp256k1'; import { coins, MAX_BIP32_INDEX, SAFE_ROOT_SLOT_ORDINALS } from '@bitgo/statics'; import type { RootKeyType } from '@bitgo/public-types'; import { Ed25519KeyDeriver } from './ed25519KeyDeriver'; diff --git a/modules/sdk-lib-safes/test/unit/safeDerivation.ts b/modules/sdk-lib-safes/test/unit/safeDerivation.ts index ba5aae7787b..a7dd2aa9a3b 100644 --- a/modules/sdk-lib-safes/test/unit/safeDerivation.ts +++ b/modules/sdk-lib-safes/test/unit/safeDerivation.ts @@ -1,5 +1,5 @@ import 'should'; -import { bip32 } from '@bitgo/utxo-lib'; +import { bip32 } from '@bitgo/secp256k1'; import { buildSafeBip44Path, deriveAndSelfCheckSafeChildHardened, diff --git a/modules/sdk-lib-safes/tsconfig.json b/modules/sdk-lib-safes/tsconfig.json index eeef9d106c0..36769bc274f 100644 --- a/modules/sdk-lib-safes/tsconfig.json +++ b/modules/sdk-lib-safes/tsconfig.json @@ -11,10 +11,10 @@ "exclude": ["node_modules"], "references": [ { - "path": "../statics" + "path": "../secp256k1" }, { - "path": "../utxo-lib" + "path": "../statics" } ] } From b1326110edc2828d9badcac1711550179717c426 Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Mon, 30 Nov 2026 15:57:56 -0500 Subject: [PATCH 09/15] fix(sdk-coin-xrp): move test codec to dev dependencies (WCN-5243) --- modules/sdk-coin-xrp/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/sdk-coin-xrp/package.json b/modules/sdk-coin-xrp/package.json index 1efa2a5a45a..65182fb2058 100644 --- a/modules/sdk-coin-xrp/package.json +++ b/modules/sdk-coin-xrp/package.json @@ -45,13 +45,13 @@ "@bitgo/statics": "^59.35.0", "bignumber.js": "^9.0.0", "lodash": "^4.18.0", - "ripple-binary-codec": "2.1.0", "ripple-keypairs": "2.0.0", "xrpl": "4.6.0" }, "devDependencies": { "@bitgo/sdk-api": "^4.0.0", - "@bitgo/sdk-test": "^9.1.101" + "@bitgo/sdk-test": "^9.1.101", + "ripple-binary-codec": "2.1.0" }, "gitHead": "18e460ddf02de2dbf13c2aa243478188fb539f0c", "files": [ From ef55e70153c905fffeae6027e38a036b2e8abd48 Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Mon, 30 Nov 2026 16:11:39 -0500 Subject: [PATCH 10/15] fix(sdk-lib-safes): refresh generated docker dependency order TICKET: WCN-5239 --- Dockerfile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6993a71a13c..1a646db76a0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -51,11 +51,11 @@ COPY --from=builder /tmp/bitgo/modules/sdk-lib-mpc /var/modules/sdk-lib-mpc/ COPY --from=builder /tmp/bitgo/modules/sdk-opensslbytes /var/modules/sdk-opensslbytes/ COPY --from=builder /tmp/bitgo/modules/sjcl /var/modules/sjcl/ COPY --from=builder /tmp/bitgo/modules/sdk-lib-safes /var/modules/sdk-lib-safes/ +COPY --from=builder /tmp/bitgo/modules/secp256k1 /var/modules/secp256k1/ COPY --from=builder /tmp/bitgo/modules/statics /var/modules/statics/ COPY --from=builder /tmp/bitgo/modules/utxo-lib /var/modules/utxo-lib/ COPY --from=builder /tmp/bitgo/modules/blake2b /var/modules/blake2b/ COPY --from=builder /tmp/bitgo/modules/blake2b-wasm /var/modules/blake2b-wasm/ -COPY --from=builder /tmp/bitgo/modules/secp256k1 /var/modules/secp256k1/ COPY --from=builder /tmp/bitgo/modules/logger /var/modules/logger/ COPY --from=builder /tmp/bitgo/modules/bitgo /var/modules/bitgo/ COPY --from=builder /tmp/bitgo/modules/abstract-utxo /var/modules/abstract-utxo/ @@ -157,11 +157,11 @@ cd /var/modules/sdk-lib-mpc && yarn link && \ cd /var/modules/sdk-opensslbytes && yarn link && \ cd /var/modules/sjcl && yarn link && \ cd /var/modules/sdk-lib-safes && yarn link && \ +cd /var/modules/secp256k1 && yarn link && \ cd /var/modules/statics && yarn link && \ cd /var/modules/utxo-lib && yarn link && \ cd /var/modules/blake2b && yarn link && \ cd /var/modules/blake2b-wasm && yarn link && \ -cd /var/modules/secp256k1 && yarn link && \ cd /var/modules/logger && yarn link && \ cd /var/modules/bitgo && yarn link && \ cd /var/modules/abstract-utxo && yarn link && \ @@ -266,11 +266,11 @@ RUN cd /var/bitgo-express && \ yarn link @bitgo/sdk-opensslbytes && \ yarn link @bitgo/sjcl && \ yarn link @bitgo/sdk-lib-safes && \ + yarn link @bitgo/secp256k1 && \ yarn link @bitgo/statics && \ yarn link @bitgo/utxo-lib && \ yarn link @bitgo/blake2b && \ yarn link @bitgo/blake2b-wasm && \ - yarn link @bitgo/secp256k1 && \ yarn link @bitgo/logger && \ yarn link bitgo && \ yarn link @bitgo/abstract-utxo && \ From 7bf44630bb90b25fb2860d5b6b696960e2b6138e Mon Sep 17 00:00:00 2001 From: Gautam2305 Date: Thu, 3 Dec 2026 16:28:23 +0530 Subject: [PATCH 11/15] fix(sdk-coin-sui): dispatch verifyTransaction through explainTransaction Sui.verifyTransaction hardcoded TransferTransaction, which only reads TransferObjects/public_transfer commands and returns outputs: [] for AddStake and WalrusStakeWithPool PTBs. When EddsaMPCv2Utils runs pre-sign verification with intent.recipients via resolveEffectiveTxParams, staking failed with: 'Tx outputs does not match with expected txParams recipients'. Use this.explainTransaction({ txHex: rawTx }) so TransactionBuilderFactory dispatches to the matching transaction class (StakingTransaction, WalrusStakingTransaction, TransferTransaction, etc.). Ticket: WCI-2438 --- modules/sdk-coin-sui/src/sui.ts | 5 +- modules/sdk-coin-sui/test/unit/sui.ts | 132 +++++++++++++++++++++++++- 2 files changed, 132 insertions(+), 5 deletions(-) diff --git a/modules/sdk-coin-sui/src/sui.ts b/modules/sdk-coin-sui/src/sui.ts index 822044e9078..624a1107dad 100644 --- a/modules/sdk-coin-sui/src/sui.ts +++ b/modules/sdk-coin-sui/src/sui.ts @@ -155,16 +155,13 @@ export class Sui extends BaseCoin { async verifyTransaction(params: VerifyTransactionOptions): Promise { let totalAmount = new BigNumber(0); - const coinConfig = coins.get(this.getChain()); const { txPrebuild: txPrebuild, txParams: txParams, verification, wallet } = params; - const transaction = new TransferTransaction(coinConfig); const rawTx = txPrebuild.txHex; if (!rawTx) { throw new Error('missing required tx prebuild property txHex'); } - transaction.fromRawTransaction(Buffer.from(rawTx, 'hex').toString('base64')); - const explainedTx = transaction.explainTransaction(); + const explainedTx = await this.explainTransaction({ txHex: rawTx }); if (txParams.recipients && txParams.recipients.length > 0) { const filteredRecipients = txParams.recipients?.map((recipient) => { diff --git a/modules/sdk-coin-sui/test/unit/sui.ts b/modules/sdk-coin-sui/test/unit/sui.ts index bf224a607dd..e5a56dc36a2 100644 --- a/modules/sdk-coin-sui/test/unit/sui.ts +++ b/modules/sdk-coin-sui/test/unit/sui.ts @@ -3,7 +3,7 @@ import nacl from 'tweetnacl'; import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; import { BitGoAPI, encrypt } from '@bitgo/sdk-api'; -import { Sui, TokenTransferTransaction, TransferTransaction, Tsui } from '../../src'; +import { Sui, SuiToken, TokenTransferTransaction, TransferTransaction, Tsui } from '../../src'; import * as testData from '../resources/sui'; import _ from 'lodash'; import sinon from 'sinon'; @@ -23,8 +23,10 @@ import { MPCRecoveryOptions, MPCTxs, RecoveryProviderError, + resolveEffectiveTxParams, signRecoveryEddsaMPCv2, TransactionPrebuild, + TxRequest, Wallet, } from '@bitgo/sdk-core'; import nock from 'nock'; @@ -329,6 +331,134 @@ describe('SUI:', function () { assert.fail('Transaction should pass verification'); } }); + + it('should verify an AddStake transaction via resolveEffectiveTxParams', async function () { + const txRequest = { + intent: { + intentType: 'stake', + stakingRequestId: 'c3228b1c-8c7e-4b0e-9c93-5f47044a75e1', + recipients: [ + { + address: { address: testData.requestAddStake.validatorAddress }, + amount: { value: testData.requestAddStake.amount.toString(), symbol: 'tsui' }, + }, + ], + }, + } as unknown as TxRequest; + const effectiveTxParams = resolveEffectiveTxParams(txRequest, undefined, basecoin.getChain()); + const isVerified = await basecoin.verifyTransaction({ + txPrebuild: { txHex: Buffer.from(testData.ADD_STAKE, 'base64').toString('hex') }, + txParams: effectiveTxParams, + }); + isVerified.should.equal(true); + }); + + it('should verify an AddStake transaction with fundsInAddressBalance', async function () { + const factory = getBuilderFactory('tsui'); + const txBuilder = factory.getStakingBuilder(); + txBuilder.type(SuiTransactionType.AddStake); + txBuilder.sender(testData.sender.address); + txBuilder.stake([testData.requestAddStake]); + txBuilder.gasData(testData.gasData); + txBuilder.fundsInAddressBalance('5000000000'); + const tx = await txBuilder.build(); + + const isVerified = await basecoin.verifyTransaction({ + txPrebuild: { txHex: Buffer.from(tx.toBroadcastFormat(), 'base64').toString('hex') }, + txParams: { + recipients: [ + { + address: testData.requestAddStake.validatorAddress, + amount: testData.requestAddStake.amount.toString(), + }, + ], + }, + }); + isVerified.should.equal(true); + }); + + it('should verify WalrusStakeWithPool transactions (coin objects and fundsInAddressBalance) on SuiToken', async function () { + const walBitgo = TestBitGo.decorate(BitGoAPI, { env: 'test' }); + SuiToken.createTokenConstructors().forEach(({ name, coinConstructor }) => { + walBitgo.safeRegister(name, coinConstructor); + }); + walBitgo.initializeTestVars(); + const tsuiWal = walBitgo.coin('tsui:wal'); + const factory = getBuilderFactory('tsui:wal'); + + const coinObjTx = await factory + .getWalrusStakingBuilder() + .type(SuiTransactionType.WalrusStakeWithPool) + .sender(testData.sender.address) + .stake([testData.requestWalrusStakeWithPool]) + .gasData(testData.gasData) + .inputObjects([testData.walToken]) + .build(); + + const addrBalTx = await factory + .getWalrusStakingBuilder() + .type(SuiTransactionType.WalrusStakeWithPool) + .sender(testData.sender.address) + .stake([testData.requestWalrusStakeWithPool]) + .gasData(testData.gasData) + .fundsInAddressBalance(testData.STAKING_AMOUNT.toString()) + .build(); + + const txRequest = { + intent: { + intentType: 'stake', + stakingRequestId: 'f4c69c5b-5db9-4c9a-9f67-86a076214f52', + recipients: [ + { + address: { address: testData.requestWalrusStakeWithPool.validatorAddress }, + amount: { value: testData.requestWalrusStakeWithPool.amount.toString(), symbol: 'tsui:wal' }, + }, + ], + }, + } as unknown as TxRequest; + const effectiveTxParams = resolveEffectiveTxParams(txRequest, undefined, tsuiWal.getChain()); + + for (const tx of [coinObjTx, addrBalTx]) { + const isVerified = await tsuiWal.verifyTransaction({ + txPrebuild: { txHex: Buffer.from(tx.toBroadcastFormat(), 'base64').toString('hex') }, + txParams: effectiveTxParams, + wallet: {} as unknown as Wallet, + }); + isVerified.should.equal(true); + } + }); + + it('should reject an AddStake transaction when validator address or amount does not match', async function () { + const txPrebuild = { txHex: Buffer.from(testData.ADD_STAKE, 'base64').toString('hex') }; + + await basecoin + .verifyTransaction({ + txPrebuild, + txParams: { + recipients: [ + { + address: testData.VALIDATOR_ADDRESS_2, + amount: testData.requestAddStake.amount.toString(), + }, + ], + }, + }) + .should.be.rejectedWith('Tx outputs does not match with expected txParams recipients'); + + await basecoin + .verifyTransaction({ + txPrebuild, + txParams: { + recipients: [ + { + address: testData.requestAddStake.validatorAddress, + amount: (testData.requestAddStake.amount + 1).toString(), + }, + ], + }, + }) + .should.be.rejectedWith('Tx outputs does not match with expected txParams recipients'); + }); }); describe('Explain Transaction: ', () => { From 92bd78ad05b5b5aae5b24b9ad95d19147cc17944 Mon Sep 17 00:00:00 2001 From: Venkat Annavazzala Date: Mon, 23 Nov 2026 13:48:39 +0530 Subject: [PATCH 12/15] fix(sdk-coin-sol): verify deserialized versioned tx message Ticket: CHALO-447 --- .../src/lib/customInstructionBuilder.ts | 272 +++---- modules/sdk-coin-sol/src/lib/index.ts | 2 +- modules/sdk-coin-sol/src/sol.ts | 372 +++++++++- modules/sdk-coin-sol/test/unit/sol.ts | 682 +++++++++++++++++- 4 files changed, 1166 insertions(+), 162 deletions(-) diff --git a/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts b/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts index 6fd7e881500..30a42838f36 100644 --- a/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts +++ b/modules/sdk-coin-sol/src/lib/customInstructionBuilder.ts @@ -4,11 +4,153 @@ import { MessageV0, PublicKey, SystemProgram, SYSVAR_RECENT_BLOCKHASHES_PUBKEY } import { Transaction } from './transaction'; import { TransactionBuilder } from './transactionBuilder'; import { InstructionBuilderTypes } from './constants'; -import { CustomInstruction, VersionedCustomInstruction, VersionedTransactionData } from './iface'; +import { CustomInstruction, DurableNonceParams, VersionedCustomInstruction, VersionedTransactionData } from './iface'; import { isSolLegacyInstruction } from './utils'; import assert from 'assert'; import base58 from 'bs58'; +/** + * Pure deterministic transform that injects a SystemProgram AdvanceNonceAccount instruction + * at index 0 of a Solana v0 VersionedTransactionData envelope, rebuilding staticAccountKeys + * section by section (writable signers, read-only signers, writable non-signers, read-only + * non-signers) and remapping every static and lookup-table instruction account index. + * + * Shared by both CustomInstructionBuilder (build path) and Sol.verifyVersionedTransaction + * (verification path) so the two cannot drift. + */ +export function injectVersionedNonceAdvanceInstruction( + data: VersionedTransactionData, + nonceParams: DurableNonceParams +): VersionedTransactionData { + const { walletNonceAddress, authWalletAddress } = nonceParams; + const SYSTEM_PROGRAM = SystemProgram.programId.toBase58(); + const SYSVAR_RECENT_BLOCKHASHES = SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58(); + + const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = data.messageHeader; + const oldStaticLen = data.staticAccountKeys.length; + if ( + numReadonlySignedAccounts > numRequiredSignatures || + numRequiredSignatures + numReadonlyUnsignedAccounts > oldStaticLen + ) { + throw new BuildTransactionError( + `Invalid message header: readonly counts (${numReadonlySignedAccounts}, ${numReadonlyUnsignedAccounts}) ` + + `are inconsistent with ${numRequiredSignatures} required signatures and ${oldStaticLen} static account keys` + ); + } + + // Split the original static keys into the four MessageV0 header sections. + const writableSigners = data.staticAccountKeys.slice(0, numRequiredSignatures - numReadonlySignedAccounts); + const readonlySigners = data.staticAccountKeys.slice( + numRequiredSignatures - numReadonlySignedAccounts, + numRequiredSignatures + ); + const writableNonSigners = data.staticAccountKeys.slice( + numRequiredSignatures, + oldStaticLen - numReadonlyUnsignedAccounts + ); + const readonlyNonSigners = data.staticAccountKeys.slice(oldStaticLen - numReadonlyUnsignedAccounts); + + // The nonce authority must be a signer for AdvanceNonceAccount. If it is already present + // as a non-signer, move it into the signers, keeping its writability (a writable + // non-signer becomes a writable signer, a read-only one a read-only signer). + const authorityIsSigner = writableSigners.includes(authWalletAddress) || readonlySigners.includes(authWalletAddress); + if (!authorityIsSigner) { + const asReadonlyNonSigner = readonlyNonSigners.indexOf(authWalletAddress); + const asWritableNonSigner = writableNonSigners.indexOf(authWalletAddress); + if (asReadonlyNonSigner >= 0) { + readonlyNonSigners.splice(asReadonlyNonSigner, 1); + readonlySigners.push(authWalletAddress); + } else if (asWritableNonSigner >= 0) { + writableNonSigners.splice(asWritableNonSigner, 1); + writableSigners.push(authWalletAddress); + } else { + // A brand-new authority is a read-only signer for AdvanceNonceAccount. + readonlySigners.push(authWalletAddress); + } + } + + // The nonce account must be writable for AdvanceNonceAccount. If it is already present, + // keep it in place when writable, or move it into the writable section when read-only. + const nonceAsReadonlyNonSigner = readonlyNonSigners.indexOf(walletNonceAddress); + const nonceAsReadonlySigner = readonlySigners.indexOf(walletNonceAddress); + if (nonceAsReadonlyNonSigner >= 0) { + readonlyNonSigners.splice(nonceAsReadonlyNonSigner, 1); + writableNonSigners.push(walletNonceAddress); + } else if (nonceAsReadonlySigner >= 0) { + readonlySigners.splice(nonceAsReadonlySigner, 1); + writableSigners.push(walletNonceAddress); + } else if (!writableSigners.includes(walletNonceAddress) && !writableNonSigners.includes(walletNonceAddress)) { + writableNonSigners.push(walletNonceAddress); + } + + // The system program and the recent blockhashes sysvar are read-only non-signers for + // AdvanceNonceAccount. + const isPresent = (key: string) => + writableSigners.includes(key) || + readonlySigners.includes(key) || + writableNonSigners.includes(key) || + readonlyNonSigners.includes(key); + if (!isPresent(SYSTEM_PROGRAM)) { + readonlyNonSigners.push(SYSTEM_PROGRAM); + } + if (!isPresent(SYSVAR_RECENT_BLOCKHASHES)) { + readonlyNonSigners.push(SYSVAR_RECENT_BLOCKHASHES); + } + + const newStaticAccountKeys = [...writableSigners, ...readonlySigners, ...writableNonSigners, ...readonlyNonSigners]; + + // Build one full old-index to new-index map covering static and lookup-table indexes. + // Static indexes follow their key to its new position; lookup-table indexes, which are + // appended after the static keys, shift by the number of inserted static keys. + const indexMap = new Map(); + data.staticAccountKeys.forEach((key, oldIdx) => indexMap.set(oldIdx, newStaticAccountKeys.indexOf(key))); + const shift = newStaticAccountKeys.length - oldStaticLen; + const addressLookupTables = data.addressLookupTables ?? []; + const lookupKeyCount = addressLookupTables.reduce( + (sum, alt) => sum + alt.writableIndexes.length + alt.readonlyIndexes.length, + 0 + ); + for (let i = oldStaticLen; i < oldStaticLen + lookupKeyCount; i++) { + indexMap.set(i, i + shift); + } + const remapIndex = (index: number): number => { + const mapped = indexMap.get(index); + if (mapped === undefined) { + throw new BuildTransactionError(`Invalid account key index ${index} in versioned instruction`); + } + return mapped; + }; + + const nonceAdvanceInstruction: SolVersionedInstruction = { + programIdIndex: newStaticAccountKeys.indexOf(SYSTEM_PROGRAM), + accountKeyIndexes: [ + newStaticAccountKeys.indexOf(walletNonceAddress), + newStaticAccountKeys.indexOf(SYSVAR_RECENT_BLOCKHASHES), + newStaticAccountKeys.indexOf(authWalletAddress), + ], + data: '6vx8P', // SystemProgram AdvanceNonceAccount (0x04000000) in base58 + }; + + return { + ...data, + addressLookupTables, + versionedInstructions: [ + nonceAdvanceInstruction, + ...data.versionedInstructions.map((inst) => ({ + programIdIndex: remapIndex(inst.programIdIndex), + accountKeyIndexes: inst.accountKeyIndexes.map(remapIndex), + data: inst.data, + })), + ], + staticAccountKeys: newStaticAccountKeys, + messageHeader: { + numRequiredSignatures: writableSigners.length + readonlySigners.length, + numReadonlySignedAccounts: readonlySigners.length, + numReadonlyUnsignedAccounts: readonlyNonSigners.length, + }, + }; +} + /** * Transaction builder for custom Solana instructions. * Allows building transactions with any set of raw Solana instructions. @@ -163,133 +305,7 @@ export class CustomInstructionBuilder extends TransactionBuilder { * @private */ private injectNonceAdvanceInstruction(data: VersionedTransactionData): VersionedTransactionData { - const { walletNonceAddress, authWalletAddress } = this._nonceInfo!.params; - const SYSTEM_PROGRAM = SystemProgram.programId.toBase58(); - const SYSVAR_RECENT_BLOCKHASHES = SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58(); - - const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = data.messageHeader; - const oldStaticLen = data.staticAccountKeys.length; - if ( - numReadonlySignedAccounts > numRequiredSignatures || - numRequiredSignatures + numReadonlyUnsignedAccounts > oldStaticLen - ) { - throw new BuildTransactionError( - `Invalid message header: readonly counts (${numReadonlySignedAccounts}, ${numReadonlyUnsignedAccounts}) ` + - `are inconsistent with ${numRequiredSignatures} required signatures and ${oldStaticLen} static account keys` - ); - } - - // Split the original static keys into the four MessageV0 header sections. - const writableSigners = data.staticAccountKeys.slice(0, numRequiredSignatures - numReadonlySignedAccounts); - const readonlySigners = data.staticAccountKeys.slice( - numRequiredSignatures - numReadonlySignedAccounts, - numRequiredSignatures - ); - const writableNonSigners = data.staticAccountKeys.slice( - numRequiredSignatures, - oldStaticLen - numReadonlyUnsignedAccounts - ); - const readonlyNonSigners = data.staticAccountKeys.slice(oldStaticLen - numReadonlyUnsignedAccounts); - - // The nonce authority must be a signer for AdvanceNonceAccount. If it is already present - // as a non-signer, move it into the signers, keeping its writability (a writable - // non-signer becomes a writable signer, a read-only one a read-only signer). - const authorityIsSigner = - writableSigners.includes(authWalletAddress) || readonlySigners.includes(authWalletAddress); - if (!authorityIsSigner) { - const asReadonlyNonSigner = readonlyNonSigners.indexOf(authWalletAddress); - const asWritableNonSigner = writableNonSigners.indexOf(authWalletAddress); - if (asReadonlyNonSigner >= 0) { - readonlyNonSigners.splice(asReadonlyNonSigner, 1); - readonlySigners.push(authWalletAddress); - } else if (asWritableNonSigner >= 0) { - writableNonSigners.splice(asWritableNonSigner, 1); - writableSigners.push(authWalletAddress); - } else { - // A brand-new authority is a read-only signer for AdvanceNonceAccount. - readonlySigners.push(authWalletAddress); - } - } - - // The nonce account must be writable for AdvanceNonceAccount. If it is already present, - // keep it in place when writable, or move it into the writable section when read-only. - const nonceAsReadonlyNonSigner = readonlyNonSigners.indexOf(walletNonceAddress); - const nonceAsReadonlySigner = readonlySigners.indexOf(walletNonceAddress); - if (nonceAsReadonlyNonSigner >= 0) { - readonlyNonSigners.splice(nonceAsReadonlyNonSigner, 1); - writableNonSigners.push(walletNonceAddress); - } else if (nonceAsReadonlySigner >= 0) { - readonlySigners.splice(nonceAsReadonlySigner, 1); - writableSigners.push(walletNonceAddress); - } else if (!writableSigners.includes(walletNonceAddress) && !writableNonSigners.includes(walletNonceAddress)) { - writableNonSigners.push(walletNonceAddress); - } - - // The system program and the recent blockhashes sysvar are read-only non-signers for - // AdvanceNonceAccount. - const isPresent = (key: string) => - writableSigners.includes(key) || - readonlySigners.includes(key) || - writableNonSigners.includes(key) || - readonlyNonSigners.includes(key); - if (!isPresent(SYSTEM_PROGRAM)) { - readonlyNonSigners.push(SYSTEM_PROGRAM); - } - if (!isPresent(SYSVAR_RECENT_BLOCKHASHES)) { - readonlyNonSigners.push(SYSVAR_RECENT_BLOCKHASHES); - } - - const newStaticAccountKeys = [...writableSigners, ...readonlySigners, ...writableNonSigners, ...readonlyNonSigners]; - - // Build one full old-index to new-index map covering static and lookup-table indexes. - // Static indexes follow their key to its new position; lookup-table indexes, which are - // appended after the static keys, shift by the number of inserted static keys. - const indexMap = new Map(); - data.staticAccountKeys.forEach((key, oldIdx) => indexMap.set(oldIdx, newStaticAccountKeys.indexOf(key))); - const shift = newStaticAccountKeys.length - oldStaticLen; - const lookupKeyCount = data.addressLookupTables.reduce( - (sum, alt) => sum + alt.writableIndexes.length + alt.readonlyIndexes.length, - 0 - ); - for (let i = oldStaticLen; i < oldStaticLen + lookupKeyCount; i++) { - indexMap.set(i, i + shift); - } - const remapIndex = (index: number): number => { - const mapped = indexMap.get(index); - if (mapped === undefined) { - throw new BuildTransactionError(`Invalid account key index ${index} in versioned instruction`); - } - return mapped; - }; - - const nonceAdvanceInstruction: SolVersionedInstruction = { - programIdIndex: newStaticAccountKeys.indexOf(SYSTEM_PROGRAM), - accountKeyIndexes: [ - newStaticAccountKeys.indexOf(walletNonceAddress), - newStaticAccountKeys.indexOf(SYSVAR_RECENT_BLOCKHASHES), - newStaticAccountKeys.indexOf(authWalletAddress), - ], - data: '6vx8P', // SystemProgram AdvanceNonceAccount (0x04000000) in base58 - }; - - const processed: VersionedTransactionData = { - ...data, - versionedInstructions: [ - nonceAdvanceInstruction, - ...data.versionedInstructions.map((inst) => ({ - programIdIndex: remapIndex(inst.programIdIndex), - accountKeyIndexes: inst.accountKeyIndexes.map(remapIndex), - data: inst.data, - })), - ], - staticAccountKeys: newStaticAccountKeys, - messageHeader: { - numRequiredSignatures: writableSigners.length + readonlySigners.length, - numReadonlySignedAccounts: readonlySigners.length, - numReadonlyUnsignedAccounts: readonlyNonSigners.length, - }, - }; - + const processed = injectVersionedNonceAdvanceInstruction(data, this._nonceInfo!.params); this.validateInjectedMessage(processed); return processed; } diff --git a/modules/sdk-coin-sol/src/lib/index.ts b/modules/sdk-coin-sol/src/lib/index.ts index 8c7fd1f2497..f68b754cd5d 100644 --- a/modules/sdk-coin-sol/src/lib/index.ts +++ b/modules/sdk-coin-sol/src/lib/index.ts @@ -4,7 +4,7 @@ import * as Utils from './utils'; export { AtaInitializationBuilder } from './ataInitializationBuilder'; export { CloseAtaBuilder } from './closeAtaBuilder'; export { ConfidentialTransferBuilder } from './confidentialTransferBuilder'; -export { CustomInstructionBuilder } from './customInstructionBuilder'; +export { CustomInstructionBuilder, injectVersionedNonceAdvanceInstruction } from './customInstructionBuilder'; export { KeyPair } from './keyPair'; export { StakingActivateBuilder } from './stakingActivateBuilder'; export { StakingAuthorizeBuilder } from './stakingAuthorizeBuilder'; diff --git a/modules/sdk-coin-sol/src/sol.ts b/modules/sdk-coin-sol/src/sol.ts index 2d7a745c307..bf19f708612 100644 --- a/modules/sdk-coin-sol/src/sol.ts +++ b/modules/sdk-coin-sol/src/sol.ts @@ -3,7 +3,16 @@ */ import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { AccountInfo, Connection, PublicKey as SolPublicKey, SystemInstruction, SystemProgram } from '@solana/web3.js'; +import { + AccountInfo, + Connection, + MessageV0, + PublicKey as SolPublicKey, + SystemInstruction, + SystemProgram, + SYSVAR_RECENT_BLOCKHASHES_PUBKEY, + VersionedTransaction, +} from '@solana/web3.js'; import BigNumber from 'bignumber.js'; import * as base58 from 'bs58'; import * as _ from 'lodash'; @@ -79,13 +88,16 @@ import { TransactionBuilder, TransactionBuilderFactory, explainSolTransaction, + injectVersionedNonceAdvanceInstruction, } from './lib'; import { AtaClose, AtaRecoverNested, + DurableNonceParams, ExtraAccountMeta, StakingDeactivate, TransactionExplanation as SolLibTransactionExplanation, + VersionedTransactionData, } from './lib/iface'; import { InstructionBuilderTypes, MEMO_PROGRAM_PK } from './lib/constants'; import { @@ -637,67 +649,365 @@ export class Sol extends BaseCoin { } } + private validateVersionedTransactionData(versionedData: SolVersionedTransactionData): VersionedTransactionData { + if (!versionedData || typeof versionedData !== 'object') { + throw new Error('solVersionedTransactionData must be an object'); + } + + if ('version' in versionedData && versionedData.version !== undefined && versionedData.version !== 0) { + throw new Error(`unsupported versioned transaction version: ${String(versionedData.version)}`); + } + + if (!Array.isArray(versionedData.versionedInstructions) || versionedData.versionedInstructions.length === 0) { + throw new Error('versioned transaction must have at least one instruction'); + } + + if (!Array.isArray(versionedData.staticAccountKeys) || versionedData.staticAccountKeys.length === 0) { + throw new Error('versioned transaction must have at least one static account key'); + } + + if (!versionedData.messageHeader || typeof versionedData.messageHeader !== 'object') { + throw new Error('versioned transaction must have a message header'); + } + + const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = + versionedData.messageHeader; + const staticLen = versionedData.staticAccountKeys.length; + if ( + !Number.isInteger(numRequiredSignatures) || + numRequiredSignatures < 1 || + !Number.isInteger(numReadonlySignedAccounts) || + numReadonlySignedAccounts < 0 || + !Number.isInteger(numReadonlyUnsignedAccounts) || + numReadonlyUnsignedAccounts < 0 || + numReadonlySignedAccounts > numRequiredSignatures || + numRequiredSignatures + numReadonlyUnsignedAccounts > staticLen + ) { + throw new Error('versioned transaction has an invalid message header'); + } + + const seenStaticKeys = new Set(); + for (const key of versionedData.staticAccountKeys) { + let canonical: string; + try { + canonical = new SolPublicKey(key).toBase58(); + } catch { + throw new Error(`versioned transaction contains invalid static account key: ${String(key)}`); + } + if (canonical !== key) { + throw new Error(`versioned transaction contains non-canonical static account key: ${key}`); + } + if (seenStaticKeys.has(key)) { + throw new Error(`versioned transaction contains duplicate static account key: ${key}`); + } + seenStaticKeys.add(key); + } + + if (versionedData.addressLookupTables !== undefined && !Array.isArray(versionedData.addressLookupTables)) { + throw new Error('versioned transaction addressLookupTables must be an array'); + } + const addressLookupTables = versionedData.addressLookupTables ?? []; + let lookupKeyCount = 0; + for (const alt of addressLookupTables) { + if (!alt || typeof alt !== 'object') { + throw new Error('versioned transaction contains invalid address lookup table entry'); + } + let canonicalAlt: string; + try { + canonicalAlt = new SolPublicKey(alt.accountKey).toBase58(); + } catch { + throw new Error(`versioned transaction contains invalid ALT accountKey: ${String(alt.accountKey)}`); + } + if (canonicalAlt !== alt.accountKey) { + throw new Error(`versioned transaction contains non-canonical ALT accountKey: ${alt.accountKey}`); + } + if (!Array.isArray(alt.writableIndexes) || !Array.isArray(alt.readonlyIndexes)) { + throw new Error('versioned transaction ALT writableIndexes and readonlyIndexes must be arrays'); + } + for (const idx of [...alt.writableIndexes, ...alt.readonlyIndexes]) { + if (!Number.isInteger(idx) || idx < 0 || idx > 255) { + throw new Error(`versioned transaction ALT contains invalid index: ${String(idx)}`); + } + } + lookupKeyCount += alt.writableIndexes.length + alt.readonlyIndexes.length; + } + + const totalAccountKeys = staticLen + lookupKeyCount; + for (const ix of versionedData.versionedInstructions) { + if (!ix || typeof ix !== 'object') { + throw new Error('versioned transaction contains invalid instruction'); + } + if (!Number.isInteger(ix.programIdIndex) || ix.programIdIndex < 0 || ix.programIdIndex >= staticLen) { + throw new Error(`versioned transaction instruction has out-of-bounds programIdIndex: ${ix.programIdIndex}`); + } + if (!Array.isArray(ix.accountKeyIndexes)) { + throw new Error('versioned transaction instruction accountKeyIndexes must be an array'); + } + for (const idx of ix.accountKeyIndexes) { + if (!Number.isInteger(idx) || idx < 0 || idx >= totalAccountKeys) { + throw new Error(`versioned transaction instruction has out-of-bounds accountKeyIndex: ${idx}`); + } + } + if (typeof ix.data !== 'string') { + throw new Error('versioned transaction instruction data must be a base58 string'); + } + try { + base58.decode(ix.data); + } catch { + throw new Error('versioned transaction instruction data is not valid base58'); + } + } + + return { + versionedInstructions: versionedData.versionedInstructions, + addressLookupTables, + staticAccountKeys: versionedData.staticAccountKeys, + messageHeader: versionedData.messageHeader, + recentBlockhash: versionedData.recentBlockhash, + }; + } + + private decodeVersionedAdvanceNonceInstruction(message: MessageV0): DurableNonceParams | undefined { + if (message.compiledInstructions.length === 0) { + return undefined; + } + const ix0 = message.compiledInstructions[0]; + const staticKeys = message.staticAccountKeys; + if (ix0.programIdIndex >= staticKeys.length) { + return undefined; + } + if (staticKeys[ix0.programIdIndex].toBase58() !== SystemProgram.programId.toBase58()) { + return undefined; + } + // SystemProgram.AdvanceNonceAccount discriminator is 4-byte little-endian uint32(4). + if (ix0.data.length !== 4 || ix0.data[0] !== 4 || ix0.data[1] !== 0 || ix0.data[2] !== 0 || ix0.data[3] !== 0) { + return undefined; + } + if (ix0.accountKeyIndexes.length !== 3) { + return undefined; + } + const [nonceIdx, sysvarIdx, authIdx] = ix0.accountKeyIndexes; + if (nonceIdx >= staticKeys.length || sysvarIdx >= staticKeys.length || authIdx >= staticKeys.length) { + return undefined; + } + if (staticKeys[sysvarIdx].toBase58() !== SYSVAR_RECENT_BLOCKHASHES_PUBKEY.toBase58()) { + return undefined; + } + + const { numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts } = message.header; + const nonceIsWritable = + nonceIdx < numRequiredSignatures - numReadonlySignedAccounts || + (nonceIdx >= numRequiredSignatures && nonceIdx < staticKeys.length - numReadonlyUnsignedAccounts); + const authIsSigner = authIdx < numRequiredSignatures; + if (!nonceIsWritable || !authIsSigner) { + return undefined; + } + + return { + walletNonceAddress: staticKeys[nonceIdx].toBase58(), + authWalletAddress: staticKeys[authIdx].toBase58(), + }; + } + + private assertVersionedMessageMatchesData(message: MessageV0, expected: VersionedTransactionData): void { + const { header } = message; + if ( + header.numRequiredSignatures !== expected.messageHeader.numRequiredSignatures || + header.numReadonlySignedAccounts !== expected.messageHeader.numReadonlySignedAccounts || + header.numReadonlyUnsignedAccounts !== expected.messageHeader.numReadonlyUnsignedAccounts + ) { + throw new Error('Versioned transaction messageHeader does not match solVersionedTransactionData'); + } + + if (message.staticAccountKeys.length !== expected.staticAccountKeys.length) { + throw new Error('Versioned transaction staticAccountKeys length does not match solVersionedTransactionData'); + } + for (let i = 0; i < expected.staticAccountKeys.length; i++) { + if (message.staticAccountKeys[i].toBase58() !== expected.staticAccountKeys[i]) { + throw new Error(`Versioned transaction staticAccountKeys[${i}] does not match solVersionedTransactionData`); + } + } + + const expectedAlts = expected.addressLookupTables ?? []; + if (message.addressTableLookups.length !== expectedAlts.length) { + throw new Error('Versioned transaction addressTableLookups length does not match solVersionedTransactionData'); + } + for (let i = 0; i < expectedAlts.length; i++) { + const actualAlt = message.addressTableLookups[i]; + const expectedAlt = expectedAlts[i]; + if ( + actualAlt.accountKey.toBase58() !== expectedAlt.accountKey || + !_.isEqual(actualAlt.writableIndexes, expectedAlt.writableIndexes) || + !_.isEqual(actualAlt.readonlyIndexes, expectedAlt.readonlyIndexes) + ) { + throw new Error(`Versioned transaction addressTableLookups[${i}] does not match solVersionedTransactionData`); + } + } + + if (message.compiledInstructions.length !== expected.versionedInstructions.length) { + throw new Error('Versioned transaction instruction count does not match solVersionedTransactionData'); + } + for (let i = 0; i < expected.versionedInstructions.length; i++) { + const actualIx = message.compiledInstructions[i]; + const expectedIx = expected.versionedInstructions[i]; + const expectedData = Buffer.from(base58.decode(expectedIx.data)); + if ( + actualIx.programIdIndex !== expectedIx.programIdIndex || + !_.isEqual(actualIx.accountKeyIndexes, expectedIx.accountKeyIndexes) || + !Buffer.from(actualIx.data).equals(expectedData) + ) { + throw new Error(`Versioned transaction instruction[${i}] does not match solVersionedTransactionData`); + } + } + } + /** - * Verify a versioned Solana transaction with basic structural validation + * Fully deserialize a Solana v0 versioned transaction and verify its message + * (header, staticAccountKeys, addressTableLookups, and compiledInstructions) + * matches txParams.solVersionedTransactionData (or the exact deterministic + * durable-nonce-injected form when Wallet Platform prepends AdvanceNonceAccount). + * + * Note: recentBlockhash is intentionally not pinned to versionedData.recentBlockhash + * because Wallet Platform refreshes stale blockhashes before signing (DEFI-820). + * * @param params - verification parameters * @returns true if verification passes */ private async verifyVersionedTransaction(params: SolVerifyTransactionOptions): Promise { - const { txParams, txPrebuild } = params; + const { txParams, txPrebuild, durableNonce, verification: verificationOptions } = params; const rawTx = txPrebuild.txBase64 || txPrebuild.txHex; if (!rawTx) { throw new Error('missing required tx prebuild property txBase64 or txHex'); } - // Validate that the versioned transaction data is well-formed if (!this.hasSolVersionedTransactionData(txParams)) { throw new Error('solVersionedTransactionData is required for versioned transaction verification'); } - const versionedData = txParams.solVersionedTransactionData; + if (txParams.type !== undefined && txParams.type !== 'customTx') { + throw new Error('solVersionedTransactionData is only supported for customTx transactions'); + } - if (!versionedData.versionedInstructions || versionedData.versionedInstructions.length === 0) { - throw new Error('versioned transaction must have at least one instruction'); + if (txParams.recipients && txParams.recipients.length > 0) { + throw new Error('recipients are not supported with solVersionedTransactionData'); } - if (!versionedData.staticAccountKeys || versionedData.staticAccountKeys.length === 0) { - throw new Error('versioned transaction must have at least one static account key'); + if (txPrebuild.consolidateId !== undefined || verificationOptions?.consolidationToBaseAddress) { + throw new Error('consolidations are not supported with solVersionedTransactionData'); } - if (!versionedData.messageHeader) { - throw new Error('versioned transaction must have a message header'); + const versionedData = this.validateVersionedTransactionData(txParams.solVersionedTransactionData); + + let txBytes: Buffer; + if (HEX_REGEX.test(rawTx) && rawTx.length % 2 === 0) { + txBytes = Buffer.from(rawTx, 'hex'); + } else if (/^[A-Za-z0-9+/]+={0,2}$/.test(rawTx)) { + txBytes = Buffer.from(rawTx, 'base64'); + } else { + throw new Error('failed to validate versioned transaction format: invalid raw transaction encoding'); } - // Validate that we can deserialize the transaction - let rawTxBase64 = rawTx; - if (HEX_REGEX.test(rawTx)) { - rawTxBase64 = Buffer.from(rawTx, 'hex').toString('base64'); + if (txBytes.length < 1) { + throw new Error('failed to validate versioned transaction format: transaction bytes are empty'); } + let deserializedTx: VersionedTransaction; try { - const txBytes = Buffer.from(rawTxBase64, 'base64'); - if (txBytes.length < 1) { - throw new Error('transaction bytes are empty'); - } + deserializedTx = VersionedTransaction.deserialize(txBytes); + } catch (error) { + throw new Error(`failed to deserialize versioned transaction: ${error.message}`); + } + + if (deserializedTx.version !== 0) { + throw new Error(`transaction is not a v0 versioned transaction: got ${String(deserializedTx.version)}`); + } + + const reserializedBytes = Buffer.from(deserializedTx.serialize()); + if (!reserializedBytes.equals(txBytes)) { + throw new Error('versioned transaction has non-canonical encoding or trailing bytes'); + } - // Check version byte (after signatures) - const numSignatures = txBytes[0]; - const signatureSize = 64; - const versionByteOffset = 1 + numSignatures * signatureSize; + const message = deserializedTx.message as MessageV0; + const actualIxCount = message.compiledInstructions.length; + const expectedIxCount = versionedData.versionedInstructions.length; - if (txBytes.length <= versionByteOffset) { - throw new Error('transaction bytes are too short to contain version byte'); + if (actualIxCount === expectedIxCount) { + this.assertVersionedMessageMatchesData(message, versionedData); + + if (durableNonce) { + const decodedNonce = this.decodeVersionedAdvanceNonceInstruction(message); + if ( + !decodedNonce || + decodedNonce.walletNonceAddress !== durableNonce.walletNonceAddress || + decodedNonce.authWalletAddress !== String(durableNonce.authWalletAddress) + ) { + throw new Error('Tx durableNonce does not match with param durableNonce'); + } + } + } else if (actualIxCount === expectedIxCount + 1) { + const decodedNonce = this.decodeVersionedAdvanceNonceInstruction(message); + if (!decodedNonce) { + throw new Error('Versioned transaction contains unexpected extra instruction'); + } + + if (durableNonce) { + if ( + decodedNonce.walletNonceAddress !== durableNonce.walletNonceAddress || + decodedNonce.authWalletAddress !== String(durableNonce.authWalletAddress) + ) { + throw new Error('Tx durableNonce does not match with param durableNonce'); + } + } else { + // Without an explicit durableNonce param, do not allow nonce injection to escalate + // privileges of accounts already present in the user's staticAccountKeys. + const origHeader = versionedData.messageHeader; + const origStaticLen = versionedData.staticAccountKeys.length; + const existingAuthIdx = versionedData.staticAccountKeys.indexOf(decodedNonce.authWalletAddress); + if (existingAuthIdx >= origHeader.numRequiredSignatures) { + throw new Error('Injected nonce authority cannot escalate an existing non-signer account to a signer'); + } + const existingNonceIdx = versionedData.staticAccountKeys.indexOf(decodedNonce.walletNonceAddress); + if (existingNonceIdx >= 0) { + const wasReadonlySigner = + existingNonceIdx >= origHeader.numRequiredSignatures - origHeader.numReadonlySignedAccounts && + existingNonceIdx < origHeader.numRequiredSignatures; + const wasReadonlyNonSigner = existingNonceIdx >= origStaticLen - origHeader.numReadonlyUnsignedAccounts; + if (wasReadonlySigner || wasReadonlyNonSigner) { + throw new Error('Injected nonce account cannot escalate an existing read-only account to writable'); + } + } } - const versionByte = txBytes[versionByteOffset]; - const isVersioned = (versionByte & 0x80) !== 0; + const expectedWithNonce = injectVersionedNonceAdvanceInstruction(versionedData, decodedNonce); + this.assertVersionedMessageMatchesData(message, expectedWithNonce); + } else { + throw new Error('Versioned transaction instruction count does not match solVersionedTransactionData'); + } - if (!isVersioned) { - throw new Error('transaction does not have versioned format'); + const declaredFeePayer = + params.feePayer ?? + (typeof txParams === 'object' && + txParams !== null && + 'feePayer' in txParams && + typeof txParams.feePayer === 'string' + ? txParams.feePayer + : undefined); + const actualFeePayer = message.staticAccountKeys[0].toBase58(); + if (declaredFeePayer && actualFeePayer !== declaredFeePayer) { + throw new Error( + `Tx fee payer ${actualFeePayer} does not match the declared sponsored fee payer ${declaredFeePayer}` + ); + } + + const walletRootAddress = params.wallet?.coinSpecific()?.rootAddress; + if (walletRootAddress) { + const requiredSigners = message.staticAccountKeys + .slice(0, message.header.numRequiredSignatures) + .map((key) => key.toBase58()); + if (!requiredSigners.includes(walletRootAddress)) { + throw new Error('Wallet root address is not a required signer of the versioned transaction'); } - } catch (error) { - throw new Error(`failed to validate versioned transaction format: ${error.message}`); } return true; diff --git a/modules/sdk-coin-sol/test/unit/sol.ts b/modules/sdk-coin-sol/test/unit/sol.ts index 16ed66510bb..e1bd98bd98b 100644 --- a/modules/sdk-coin-sol/test/unit/sol.ts +++ b/modules/sdk-coin-sol/test/unit/sol.ts @@ -5,7 +5,14 @@ import * as should from 'should'; import * as sinon from 'sinon'; import { getExtraAccountMetaAddress, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { Keypair, PublicKey, SystemProgram, TransactionInstruction } from '@solana/web3.js'; +import { + Keypair, + MessageV0, + PublicKey, + SystemProgram, + TransactionInstruction, + VersionedTransaction, +} from '@solana/web3.js'; import * as base58 from 'bs58'; import * as nacl from 'tweetnacl'; @@ -48,7 +55,13 @@ import { Tsol, } from '../../src'; import { Transaction } from '../../src/lib'; -import { AtaInit, ExtraAccountMeta, InstructionParams, TokenTransfer } from '../../src/lib/iface'; +import { + AtaInit, + ExtraAccountMeta, + InstructionParams, + TokenTransfer, + VersionedTransactionData, +} from '../../src/lib/iface'; import { TOKEN_ACL_FLAG_ACCOUNT_SEED, TOKEN_ACL_MINT_CONFIG_SEED, @@ -1649,6 +1662,671 @@ describe('SOL:', function () { .should.be.rejectedWith('CustomTx prebuild instruction 0 key 0 mismatch'); }); }); + + describe('versioned transactions', () => { + const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'; + const altAccountKey = Keypair.generate().publicKey.toBase58(); + const extraProgramKey = Keypair.generate().publicKey.toBase58(); + const extraWritableKey = Keypair.generate().publicKey.toBase58(); + const extraReadonlyKey = Keypair.generate().publicKey.toBase58(); + const attackerKey = Keypair.generate().publicKey.toBase58(); + const relayerKey = Keypair.generate().publicKey.toBase58(); + const nonceAccountKey = Keypair.generate().publicKey.toBase58(); + const nonceAuthKey = Keypair.generate().publicKey.toBase58(); + const refreshedBlockHash = Keypair.generate().publicKey.toBase58(); + + const makeBasicVersionedData = (): VersionedTransactionData => ({ + versionedInstructions: [ + { + programIdIndex: 1, + accountKeyIndexes: [0], + data: base58.encode(Buffer.from('Hello Versioned Tx', 'utf-8')), + }, + ], + addressLookupTables: [], + staticAccountKeys: [wallet.pub, MEMO_PROGRAM_ID], + messageHeader: { + numRequiredSignatures: 1, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }); + + const makeAltVersionedData = (): VersionedTransactionData => ({ + versionedInstructions: [ + { + programIdIndex: 3, + accountKeyIndexes: [0, 1, 2, 4, 5, 6], + data: base58.encode(Buffer.from([1, 2, 3, 4, 5, 6, 7, 8])), + }, + ], + addressLookupTables: [ + { + accountKey: altAccountKey, + writableIndexes: [0, 2], + readonlyIndexes: [5], + }, + ], + staticAccountKeys: [wallet.pub, extraWritableKey, extraReadonlyKey, extraProgramKey], + messageHeader: { + numRequiredSignatures: 1, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 2, + }, + recentBlockhash: blockHash, + }); + + const buildRawVersionedTx = ( + data: VersionedTransactionData, + overrideBlockhash?: string + ): VersionedTransaction => { + const messageV0 = new MessageV0({ + header: data.messageHeader, + staticAccountKeys: data.staticAccountKeys.map((k) => new PublicKey(k)), + recentBlockhash: overrideBlockhash ?? data.recentBlockhash ?? blockHash, + compiledInstructions: data.versionedInstructions.map((ix) => ({ + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accountKeyIndexes, + data: Buffer.from(base58.decode(ix.data)), + })), + addressTableLookups: (data.addressLookupTables ?? []).map((alt) => ({ + accountKey: new PublicKey(alt.accountKey), + writableIndexes: alt.writableIndexes, + readonlyIndexes: alt.readonlyIndexes, + })), + }); + return new VersionedTransaction(messageV0); + }; + + it('should verify a valid v0 versioned transaction (base64)', async function () { + const versionedData = makeBasicVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .fromVersionedTransactionData(versionedData) + .build(); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 versioned transaction (hex, matching Wallet Platform serializedTxHex)', async function () { + const versionedData = makeBasicVersionedData(); + const rawHex = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('hex'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txHex: rawHex }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 versioned transaction with Address Lookup Tables (ALTs)', async function () { + const versionedData = makeAltVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .fromVersionedTransactionData(versionedData) + .build(); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction after DEFI-820 recentBlockhash refresh', async function () { + const versionedData = makeAltVersionedData(); + const refreshedRaw = Buffer.from(buildRawVersionedTx(versionedData, refreshedBlockHash).serialize()).toString( + 'base64' + ); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: refreshedRaw }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with a third-party gasless fee payer when wallet root is a required signer', async function () { + const versionedData = { + versionedInstructions: [ + { + programIdIndex: 2, + accountKeyIndexes: [0, 1], + data: base58.encode(Buffer.from('gasless swap', 'utf-8')), + }, + ], + addressLookupTables: [], + staticAccountKeys: [relayerKey, wallet.pub, MEMO_PROGRAM_ID], + messageHeader: { + numRequiredSignatures: 2, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }; + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with declared sponsored feePayer matching staticAccountKeys[0]', async function () { + const versionedData = { + versionedInstructions: [ + { + programIdIndex: 2, + accountKeyIndexes: [0, 1], + data: base58.encode(Buffer.from('sponsored', 'utf-8')), + }, + ], + addressLookupTables: [], + staticAccountKeys: [relayerKey, wallet.pub, MEMO_PROGRAM_ID], + messageHeader: { + numRequiredSignatures: 2, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }; + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + feePayer: relayerKey, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with empty instruction data', async function () { + const versionedData = { + ...makeBasicVersionedData(), + versionedInstructions: [ + { + programIdIndex: 1, + accountKeyIndexes: [0], + data: '', + }, + ], + }; + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any); + valid.should.equal(true); + }); + + it('should verify a valid v0 transaction with WP-injected durable nonce (including shifted ALT indexes)', async function () { + const versionedData = makeAltVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + // Without explicit durableNonce param + const validWithoutParam = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + wallet: walletObj, + } as any); + validWithoutParam.should.equal(true); + + // With matching durableNonce param + const validWithParam = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + durableNonce: { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }, + wallet: walletObj, + } as any); + validWithParam.should.equal(true); + }); + + it('should reject a substituted SystemProgram.transfer draining wallet funds', async function () { + const versionedData = makeBasicVersionedData(); + const maliciousTransferIx = SystemProgram.transfer({ + fromPubkey: new PublicKey(wallet.pub), + toPubkey: new PublicKey(attackerKey), + lamports: 1_000_000_000, + }); + const maliciousData = { + versionedInstructions: [ + { + programIdIndex: 2, + accountKeyIndexes: [0, 1], + data: base58.encode(maliciousTransferIx.data), + }, + ], + addressLookupTables: [], + staticAccountKeys: [wallet.pub, attackerKey, SystemProgram.programId.toBase58()], + messageHeader: { + numRequiredSignatures: 1, + numReadonlySignedAccounts: 0, + numReadonlyUnsignedAccounts: 1, + }, + recentBlockhash: blockHash, + }; + const maliciousRaw = Buffer.from(buildRawVersionedTx(maliciousData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: maliciousRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/does not match solVersionedTransactionData/); + }); + + it('should reject modified instruction data bytes', async function () { + const versionedData = makeBasicVersionedData(); + const tamperedData = { + ...versionedData, + versionedInstructions: [ + { + ...versionedData.versionedInstructions[0], + data: base58.encode(Buffer.from('Tampered Data', 'utf-8')), + }, + ], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[0\] does not match/); + }); + + it('should reject modified instruction accountKeyIndexes', async function () { + const versionedData = makeAltVersionedData(); + const tamperedData = { + ...versionedData, + versionedInstructions: [ + { + ...versionedData.versionedInstructions[0], + accountKeyIndexes: [0, 2, 1, 4, 5, 6], + }, + ], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[0\] does not match/); + }); + + it('should reject an extra injected non-nonce instruction', async function () { + const versionedData = makeBasicVersionedData(); + const tamperedData = { + ...versionedData, + versionedInstructions: [ + ...versionedData.versionedInstructions, + { + programIdIndex: 1, + accountKeyIndexes: [0], + data: base58.encode(Buffer.from('extra', 'utf-8')), + }, + ], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/unexpected extra instruction/); + }); + + it('should reject modified staticAccountKeys', async function () { + const versionedData = makeAltVersionedData(); + const tamperedData = { + ...versionedData, + staticAccountKeys: [wallet.pub, attackerKey, extraReadonlyKey, extraProgramKey], + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/staticAccountKeys\[1\] does not match/); + }); + + it('should reject substituted ALT accountKey or lookup indexes', async function () { + const versionedData = makeAltVersionedData(); + + const tamperedAltKey = { + ...versionedData, + addressLookupTables: [{ ...versionedData.addressLookupTables[0], accountKey: attackerKey }], + }; + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: Buffer.from(buildRawVersionedTx(tamperedAltKey).serialize()).toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/addressTableLookups\[0\] does not match/); + + const tamperedAltIndexes = { + ...versionedData, + addressLookupTables: [{ ...versionedData.addressLookupTables[0], writableIndexes: [0, 9] }], + }; + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { + txBase64: Buffer.from(buildRawVersionedTx(tamperedAltIndexes).serialize()).toString('base64'), + }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/addressTableLookups\[0\] does not match/); + }); + + it('should reject modified messageHeader flags', async function () { + const versionedData = makeAltVersionedData(); + const tamperedHeader = { + ...versionedData, + messageHeader: { ...versionedData.messageHeader, numReadonlyUnsignedAccounts: 1 }, + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedHeader).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/messageHeader does not match/); + }); + + it('should reject nonce injection that escalates an existing non-signer or read-only account', async function () { + const versionedData = makeAltVersionedData(); + + // Attempt to escalate existing non-signer extraWritableKey to signer via nonce authority + const escalatedAuthTx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: extraWritableKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: escalatedAuthTx.toBroadcastFormat() }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/cannot escalate an existing non-signer account to a signer/); + + // Attempt to escalate existing read-only extraReadonlyKey to writable via nonce account + const escalatedNonceTx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: extraReadonlyKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: escalatedNonceTx.toBroadcastFormat() }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/cannot escalate an existing read-only account to writable/); + }); + + it('should reject mismatched durableNonce param', async function () { + const versionedData = makeAltVersionedData(); + const tx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(versionedData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tx.toBroadcastFormat() }, + durableNonce: { walletNonceAddress: attackerKey, authWalletAddress: nonceAuthKey }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/Tx durableNonce does not match/); + }); + + it('should reject fake 2-byte [0x00, 0x80] stub, legacy tx, v1 wire bytes, and trailing bytes', async function () { + const versionedData = makeBasicVersionedData(); + + // 2-byte [0x00, 0x80] buffer that passed the old stub + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: Buffer.from([0x00, 0x80]).toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/failed to deserialize versioned transaction/); + + // Legacy Solana transaction bytes + const legacyTx = await factory + .getTransferBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .send({ address: attackerKey, amount: '1000' }) + .build(); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: legacyTx.toBroadcastFormat() }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/not a v0 versioned transaction/); + + // v1 (0x81) wire bytes + const v1HeaderBytes = Buffer.concat([Buffer.from([0x00, 0x81]), Buffer.alloc(64)]); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: v1HeaderBytes.toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/failed to deserialize versioned transaction/); + + // Valid v0 tx with trailing smuggled byte + const validBytes = Buffer.from(buildRawVersionedTx(versionedData).serialize()); + const trailingBytes = Buffer.concat([validBytes, Buffer.from([0x00])]); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: trailingBytes.toString('base64') }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/non-canonical encoding or trailing bytes/); + }); + + it('should fail closed on non-customTx type, non-empty recipients, consolidation flags, or version !== 0', async function () { + const versionedData = makeBasicVersionedData(); + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'transfer', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/only supported for customTx/); + + await basecoin + .verifyTransaction({ + txParams: { + type: 'customTx', + recipients: [{ address: attackerKey, amount: '1000' }], + solVersionedTransactionData: versionedData, + }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/recipients are not supported/); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64, consolidateId: 'consolidate-1' }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/consolidations are not supported/); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: { ...versionedData, version: 1 } }, + txPrebuild: { txBase64: rawBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/unsupported versioned transaction version/); + }); + + it('should reject mismatched declared feePayer or wallet root absent from required signers', async function () { + const versionedData = makeBasicVersionedData(); + const rawBase64 = Buffer.from(buildRawVersionedTx(versionedData).serialize()).toString('base64'); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: rawBase64 }, + feePayer: relayerKey, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/does not match the declared sponsored fee payer/); + + const nonWalletData = { + ...versionedData, + staticAccountKeys: [relayerKey, MEMO_PROGRAM_ID], + }; + const nonWalletRaw = Buffer.from(buildRawVersionedTx(nonWalletData).serialize()).toString('base64'); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: nonWalletData }, + txPrebuild: { txBase64: nonWalletRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/Wallet root address is not a required signer/); + }); + + it('should verify a real multi-instruction multi-ALT Jupiter v0 swap and reject tampering', async function () { + const jupiterBase64 = + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAFDTWoM5DBCGn7cn5aV56fomo6mhD2K1c5XYhQIan41E6dG9t06ox6DMdvVuBnSEATyN/8qIq246iO5aDm1jm82x4wM40FR8Q7xSZUpUtB0lbvelaZ46oRQ2GM9hWGMukHG1EUsA1R9ZO55ClUvNMyw8IQOrfRmu3ONG50oNeluT4LgaOacN+I4d0HStcu+oh0no4XXgVUwjzk5+egiUaQDkCCjXAlSDAb46ahLAfWeKOqzO/HC/z2WgRk8RS1yc6heMZzBbR3SPDwrNvWlCZGaETaixiH9ufdOJ823Gv+MnxH1SOu6TCsX1+TMskj94D3NElDpado8okFQbUuzaijU9oAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIyXJY9OJInxuz0QKRSODYMLWhOZ2v8QhASOe9jb6fhZAwZGb+UhFzL/7K26csOb57yM5bvF9xJrLEObOkAAAAAEedVb8jHAbu50xW7OaBUH/bGy3qP0jlECsc2iVrwTjwbd9uHXZaGT2cvhRs7reawctIXtX1s3kTqM9YV+/wCp+mGpF4I4ZrV12bapJ7p61Babt3ty7HYDUKtMso38OYgHCgAFAooyBAAKAAkDoQ4BAAAAAAAIAgAFDAIAAAAwKyIAAAAAAAsFBQAgDAgJk/F7ZPSErnb/CQYABwAdCAwBAQs/HgAFDg0HIB0MDBwLJg8mEBIODSAdESYeDAwkJgIDBgsmGyYWGQ4EICUaJh4MDCQmGBcBCyIjDCEeBA0VExQfMtGYU5N8/tjpC0ANAwAAAAAAWqwAAAAAAAAyAAAAAAADAAAAJiwaAAMm5AwAAgoQJwIDDAMFAAABCQQpv5UHKk+/BN9xdZPnOLzMIScoFcJHGoDZ+fVVsNSEJQI0IwUAKA4CFyo9SDjsPdfWXAdMF0mu2+xZbw9rbR6rzNAEeFkLmyKwBGBmYWUAMHCJ6Oi0A1Qjpjp1Yv3xP+sPLm2qJ//TKZd5Z9KzjvEDwb3CA77DwOtKd1MCu6h4XJjC42yc8TcL92nhzFUR6HLW3XrAIZOvBo6Ki5CRjQOMk5Q='; + const original = VersionedTransaction.deserialize(Buffer.from(jupiterBase64, 'base64')); + const staticAccountKeys = original.message.staticAccountKeys.map((k) => k.toBase58()); + staticAccountKeys[0] = wallet.pub; + + const versionedData: VersionedTransactionData = { + versionedInstructions: original.message.compiledInstructions.map((ix) => ({ + programIdIndex: ix.programIdIndex, + accountKeyIndexes: ix.accountKeyIndexes, + data: base58.encode(ix.data), + })), + addressLookupTables: (original.message.addressTableLookups ?? []).map((lookup) => ({ + accountKey: lookup.accountKey.toBase58(), + writableIndexes: lookup.writableIndexes, + readonlyIndexes: lookup.readonlyIndexes, + })), + staticAccountKeys, + messageHeader: original.message.header, + recentBlockhash: original.message.recentBlockhash, + }; + + const built = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash) + .fromVersionedTransactionData(versionedData) + .build(); + + const valid = await basecoin.verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txHex: Buffer.from(built.toBroadcastFormat(), 'base64').toString('hex') }, + wallet: walletObj, + } as any); + valid.should.equal(true); + + // Tamper with one instruction inside the Jupiter swap + const tamperedData: VersionedTransactionData = { + ...versionedData, + versionedInstructions: versionedData.versionedInstructions.map((ix, i) => + i === versionedData.versionedInstructions.length - 1 + ? { ...ix, data: base58.encode(Buffer.from([0xde, 0xad, 0xbe, 0xef])) } + : ix + ), + }; + const tamperedRaw = Buffer.from(buildRawVersionedTx(tamperedData).serialize()).toString('base64'); + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', recipients: [], solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedRaw }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[\d+\] does not match/); + }); + + it('should reject a valid WP-injected nonce paired with a tampered user instruction', async function () { + const versionedData = makeAltVersionedData(); + const tamperedUserData: VersionedTransactionData = { + ...versionedData, + versionedInstructions: [ + { + ...versionedData.versionedInstructions[0], + data: base58.encode(Buffer.from([9, 9, 9, 9])), + }, + ], + }; + const tamperedWithNonceTx = await factory + .getCustomInstructionBuilder() + .sender(wallet.pub) + .nonce(blockHash, { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }) + .fromVersionedTransactionData(tamperedUserData) + .build(); + + await basecoin + .verifyTransaction({ + txParams: { type: 'customTx', solVersionedTransactionData: versionedData }, + txPrebuild: { txBase64: tamperedWithNonceTx.toBroadcastFormat() }, + durableNonce: { walletNonceAddress: nonceAccountKey, authWalletAddress: nonceAuthKey }, + wallet: walletObj, + } as any) + .should.be.rejectedWith(/instruction\[1\] does not match/); + }); + }); }); describe('getAmountBasedOnEndianness', () => { From fae9677dd92f11169ca488369fd8731b6622e360 Mon Sep 17 00:00:00 2001 From: Bhavi Dhingra Date: Fri, 4 Dec 2026 16:46:33 +0530 Subject: [PATCH 13/15] fix(sdk-coin-sol): forward configureAccount on enableToken intents Sol.setCoinSpecificFieldsInIntent now copies the enableToken configureAccount opt-in onto the populated intent. The copy is scoped to enableToken (matching the sdk-core tail in populateIntent) and guarded on `!== undefined`, so an absent flag leaves the legacy ATA-init lane untouched, an explicit null never reaches the Wallet Platform intent codec, and other Sol intents gain no field. Mirrors the `version: 0|1` forwarding added for the same seam in #10027. The sdk-core intent shaping (PrebuildTransactionWithIntentOptions, PopulatedIntent, PrebuildTransactionOptions, the enabletoken prebuild intent literal and populateIntent) already carried the field; the coin-owned seam was the only copy site that did not, so a caller relying on it degraded to the legacy lane. Refs: CHALO-2109 --- modules/sdk-coin-sol/src/sol.ts | 8 ++ .../test/unit/solIntentConfigureAccount.ts | 80 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 modules/sdk-coin-sol/test/unit/solIntentConfigureAccount.ts diff --git a/modules/sdk-coin-sol/src/sol.ts b/modules/sdk-coin-sol/src/sol.ts index bf19f708612..dc4dacdca19 100644 --- a/modules/sdk-coin-sol/src/sol.ts +++ b/modules/sdk-coin-sol/src/sol.ts @@ -2880,5 +2880,13 @@ export class Sol extends BaseCoin { if (params.version !== undefined) { intent.version = params.version; } + + // enableToken's ConfigureAccount opt-in (Solana Token-2022 confidential transfers). + // Scoped to enableToken like the sdk-core tail, and guarded on `!== undefined`: an + // explicit `null` is rejected by the Wallet Platform intent codec, and an absent key + // keeps the legacy ATA-init lane untouched. + if (params.intentType === 'enableToken' && params.configureAccount !== undefined) { + intent.configureAccount = params.configureAccount; + } } } diff --git a/modules/sdk-coin-sol/test/unit/solIntentConfigureAccount.ts b/modules/sdk-coin-sol/test/unit/solIntentConfigureAccount.ts new file mode 100644 index 00000000000..13adb456761 --- /dev/null +++ b/modules/sdk-coin-sol/test/unit/solIntentConfigureAccount.ts @@ -0,0 +1,80 @@ +import * as should from 'should'; +import { BitGoAPI } from '@bitgo/sdk-api'; +import { + MpcUtils, + RequestTracer, + type KeychainsTriplet, + type PopulatedIntent, + type PrebuildTransactionWithIntentOptions, +} from '@bitgo/sdk-core'; +import { Tsol } from '../../src'; + +class TestMpcUtils extends MpcUtils { + createKeychains(): Promise { + return Promise.reject(new Error('unused')); + } +} + +describe('Sol.setCoinSpecificFieldsInIntent — enableToken configureAccount', function () { + const bitgo = new BitGoAPI({ env: 'test' }); + bitgo.register('tsol', Tsol.createInstance); + const sol = bitgo.coin('tsol'); + + const intentParams: PrebuildTransactionWithIntentOptions = { + reqId: new RequestTracer(), + intentType: 'enableToken', + }; + + it('forwards configureAccount: true onto the intent', function () { + const intent: PopulatedIntent = { intentType: 'enableToken' }; + sol.setCoinSpecificFieldsInIntent(intent, { ...intentParams, configureAccount: true }); + should.equal(intent.configureAccount, true); + }); + + it('forwards configureAccount: false explicitly (opt-out stays selectable)', function () { + const intent: PopulatedIntent = { intentType: 'enableToken' }; + sol.setCoinSpecificFieldsInIntent(intent, { ...intentParams, configureAccount: false }); + should.equal(intent.configureAccount, false); + }); + + it('leaves the intent without a configureAccount key when the option is absent', function () { + const intent: PopulatedIntent = { intentType: 'enableToken' }; + sol.setCoinSpecificFieldsInIntent(intent, intentParams); + should.equal('configureAccount' in intent, false); + }); + + it('does not forward configureAccount onto a non-enableToken intent', function () { + const intent: PopulatedIntent = { intentType: 'payment' }; + sol.setCoinSpecificFieldsInIntent(intent, { ...intentParams, intentType: 'payment', configureAccount: true }); + should.equal('configureAccount' in intent, false); + }); +}); + +describe('enableToken configureAccount — populated intent (Sol + sdk-core)', function () { + const bitgo = new BitGoAPI({ env: 'test' }); + bitgo.register('tsol', Tsol.createInstance); + const sol = bitgo.coin('tsol'); + const mpcUtils = new TestMpcUtils(bitgo, sol); + + const enableTokenParams: PrebuildTransactionWithIntentOptions = { + reqId: new RequestTracer(), + intentType: 'enableToken', + recipients: [], + enableTokens: [{ name: 'tsol:t22mint' }], + }; + + it('carries configureAccount: true into the populated intent', function () { + const intent = mpcUtils.populateIntent(sol, { ...enableTokenParams, configureAccount: true }); + should.equal(intent.configureAccount, true); + }); + + it('carries configureAccount: false into the populated intent', function () { + const intent = mpcUtils.populateIntent(sol, { ...enableTokenParams, configureAccount: false }); + should.equal(intent.configureAccount, false); + }); + + it('leaves configureAccount unset when the option is omitted (legacy lane unchanged)', function () { + const intent = mpcUtils.populateIntent(sol, enableTokenParams); + should.equal(intent.configureAccount, undefined); + }); +}); From 3cc5b409ea9981d4cd78cea30b67dbb297fe64b6 Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Fri, 4 Dec 2026 10:48:01 -0500 Subject: [PATCH 14/15] chore: bump @bitgo/public-types to 7.6.5 Align every module on 7.6.5, which declares the Apache-2.0 license and ships a LICENSE file (earlier 6.90.0 and 7.1.0 tarballs declared UNLICENSED, which a customer license scanner flagged). Collapses three resolved versions in yarn.lock into one. The only breaking change between 6.90.0 and 7.6.5 is 7.0.0 requiring all defiParams fields in TxSendBody; no module in this repo references defiParams or TxSendBody, and no symbol imported from the package was removed. TICKET: WCN-5332 Co-Authored-By: Claude Sonnet 5.5 --- modules/abstract-lightning/package.json | 2 +- modules/bitgo/package.json | 2 +- modules/express/package.json | 2 +- modules/passkey-crypto/package.json | 2 +- modules/sdk-coin-canton/package.json | 2 +- modules/sdk-coin-flrp/package.json | 2 +- modules/sdk-coin-sol/package.json | 2 +- modules/sdk-core/package.json | 2 +- modules/sdk-lib-safes/package.json | 2 +- yarn.lock | 30 ++++--------------------- 10 files changed, 13 insertions(+), 35 deletions(-) diff --git a/modules/abstract-lightning/package.json b/modules/abstract-lightning/package.json index a43c9f302ea..1d0be7c4358 100644 --- a/modules/abstract-lightning/package.json +++ b/modules/abstract-lightning/package.json @@ -39,7 +39,7 @@ ] }, "dependencies": { - "@bitgo/public-types": "6.90.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-core": "^40.11.0", "@bitgo/statics": "^59.35.0", "@bitgo/utxo-lib": "^11.25.2", diff --git a/modules/bitgo/package.json b/modules/bitgo/package.json index 2356543f49a..7439608c6b1 100644 --- a/modules/bitgo/package.json +++ b/modules/bitgo/package.json @@ -144,7 +144,7 @@ "superagent": "^9.0.1" }, "devDependencies": { - "@bitgo/public-types": "6.90.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-opensslbytes": "^2.1.0", "@bitgo/sdk-test": "^9.1.101", "@openpgp/web-stream-tools": "0.0.14", diff --git a/modules/express/package.json b/modules/express/package.json index bf7df9ca167..a6e0e9a7abf 100644 --- a/modules/express/package.json +++ b/modules/express/package.json @@ -43,7 +43,7 @@ "@api-ts/typed-express-router": "2.0.0", "@bitgo/abstract-lightning": "^8.7.7", "@bitgo/logger": "^1.4.0", - "@bitgo/public-types": "7.1.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-core": "^40.11.0", "@bitgo/utxo-lib": "^11.25.2", "@types/proxyquire": "^1.3.31", diff --git a/modules/passkey-crypto/package.json b/modules/passkey-crypto/package.json index 846d0e26587..8416a5a732e 100644 --- a/modules/passkey-crypto/package.json +++ b/modules/passkey-crypto/package.json @@ -35,7 +35,7 @@ "access": "public" }, "dependencies": { - "@bitgo/public-types": "6.90.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-core": "^40.11.0" }, "devDependencies": { diff --git a/modules/sdk-coin-canton/package.json b/modules/sdk-coin-canton/package.json index a3872f9ee76..0e8549fc2d5 100644 --- a/modules/sdk-coin-canton/package.json +++ b/modules/sdk-coin-canton/package.json @@ -58,7 +58,7 @@ ] }, "dependencies": { - "@bitgo/public-types": "7.6.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-core": "^40.11.0", "@bitgo/statics": "^59.35.0", "@protobuf-ts/runtime": "^2.11.1", diff --git a/modules/sdk-coin-flrp/package.json b/modules/sdk-coin-flrp/package.json index 009ed705888..1677e06d096 100644 --- a/modules/sdk-coin-flrp/package.json +++ b/modules/sdk-coin-flrp/package.json @@ -48,7 +48,7 @@ "nock": "^13.3.1" }, "dependencies": { - "@bitgo/public-types": "6.90.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-core": "^40.11.0", "@bitgo/secp256k1": "^1.11.1", "@bitgo/statics": "^59.35.0", diff --git a/modules/sdk-coin-sol/package.json b/modules/sdk-coin-sol/package.json index 547ae5a2a74..1951e83067c 100644 --- a/modules/sdk-coin-sol/package.json +++ b/modules/sdk-coin-sol/package.json @@ -57,7 +57,7 @@ }, "dependencies": { "@bitgo/logger": "^1.4.0", - "@bitgo/public-types": "6.90.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-core": "^40.11.0", "@bitgo/sdk-lib-mpc": "^11.7.1", "@bitgo/statics": "^59.35.0", diff --git a/modules/sdk-core/package.json b/modules/sdk-core/package.json index cd9ad0fa54c..d63c859403e 100644 --- a/modules/sdk-core/package.json +++ b/modules/sdk-core/package.json @@ -40,7 +40,7 @@ ] }, "dependencies": { - "@bitgo/public-types": "7.6.0", + "@bitgo/public-types": "7.6.5", "@bitgo/sdk-lib-mpc": "^11.7.1", "@bitgo/sdk-lib-safes": "^1.11.3", "@bitgo/secp256k1": "^1.11.1", diff --git a/modules/sdk-lib-safes/package.json b/modules/sdk-lib-safes/package.json index cb739877040..f1bf0ba9bb2 100644 --- a/modules/sdk-lib-safes/package.json +++ b/modules/sdk-lib-safes/package.json @@ -31,7 +31,7 @@ "access": "public" }, "dependencies": { - "@bitgo/public-types": "7.1.0", + "@bitgo/public-types": "7.6.5", "@bitgo/secp256k1": "^1.11.1", "@bitgo/statics": "^59.35.0", "create-hmac": "^1.1.7", diff --git a/yarn.lock b/yarn.lock index 4166e6d004e..7e8cc19ab7d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1034,32 +1034,10 @@ "@scure/base" "1.1.5" micro-eth-signer "0.7.2" -"@bitgo/public-types@6.90.0": - version "6.90.0" - resolved "https://registry.npmjs.org/@bitgo/public-types/-/public-types-6.90.0.tgz#01cbded37315be24451c0e357df57f99dc7668ca" - integrity sha512-8JmcPhiovAjfm75/z5/BCtFJC/jjyCL6D52yE+LtQL2T2A58XccNrzEQZey5Ndo5gs1ARyFqxatL3CD8CZkoGw== - dependencies: - fp-ts "^2.0.0" - io-ts "npm:@bitgo-forks/io-ts@2.1.4" - io-ts-types "^0.5.16" - monocle-ts "^2.3.13" - newtype-ts "^0.3.5" - -"@bitgo/public-types@7.1.0": - version "7.1.0" - resolved "https://registry.npmjs.org/@bitgo/public-types/-/public-types-7.1.0.tgz#659956b7dd280d5ba2f191783cf7e66af9dedaff" - integrity sha512-7HiK2ajVN2TVDc/YphQy/xPRAzoRIWsIMWLFn1k7ad/nnXYTtioTwrBIg2NzWSjaz2lAGy2hS2AkgBuf3x4GfQ== - dependencies: - fp-ts "^2.0.0" - io-ts "npm:@bitgo-forks/io-ts@2.1.4" - io-ts-types "^0.5.16" - monocle-ts "^2.3.13" - newtype-ts "^0.3.5" - -"@bitgo/public-types@7.6.0": - version "7.6.0" - resolved "https://registry.npmjs.org/@bitgo/public-types/-/public-types-7.6.0.tgz#4e4bc12c105b5785928df3cc7c4288a3c8089e63" - integrity sha512-QHjU8Xj++gCU86AZv9uHEhh68ulYSiER15Sg7GtzZwpox0J7++SelytyQJ4PUwNETJ57spDeiNqAismwqmAzQA== +"@bitgo/public-types@7.6.5": + version "7.6.5" + resolved "https://registry.npmjs.org/@bitgo/public-types/-/public-types-7.6.5.tgz#6e9727fcc841911d3a98945eaf8706e4090920a4" + integrity sha512-E+gGIcFEQL+lZvANH2IGpfqxxIrooe3uzebiwZ19v7BvNGQ9GsyeQ7aaVhHg6L+2KYM35XC9SclZpYR9ZFPNCw== dependencies: fp-ts "^2.0.0" io-ts "npm:@bitgo-forks/io-ts@2.1.4" From b949a4e842adae4c30ae6e4459c596d664a46d65 Mon Sep 17 00:00:00 2001 From: Zahin Mohammad Date: Fri, 4 Dec 2026 11:01:39 -0500 Subject: [PATCH 15/15] fix(express): resolve io-ts refinement in OpenAPI generation public-types 7.6.x defines `BaseIntentCatchAll` with `t.refinement`, which the OpenAPI generator has no handler for. It emitted a dangling `#/components/schemas/refinement` reference, failing the Vacuum audit and reporting the catch-all intent's fields as removed in the breaking-change check. Register a `refinement` handler that returns the wrapped codec's schema, since a refinement only narrows decoding at runtime and leaves the wire shape unchanged. The generator merges custom handlers per package, so an `io-ts` entry would drop every built-in io-ts handler; fall back to them through the public `Project#resolveKnownImport` rather than importing the generator's `dist` internals. TICKET: WCN-5332 Co-Authored-By: Claude Sonnet 5.5 --- modules/express/openapi-generator.rc.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/modules/express/openapi-generator.rc.js b/modules/express/openapi-generator.rc.js index 9eb2b4ff797..7a6cfdbd0bb 100644 --- a/modules/express/openapi-generator.rc.js +++ b/modules/express/openapi-generator.rc.js @@ -3,8 +3,24 @@ * Custom codec handlers for OpenAPI generation */ +const { Project } = require('@api-ts/openapi-generator'); + +// The CLI merges this file over its built-in table one package key deep, so an 'io-ts' entry +// replaces every built-in io-ts handler. Fall back to the built-ins through the public +// Project#resolveKnownImport instead of copying them or importing the generator's dist internals. +const builtins = new Project(); +const withBuiltins = (pkg, overrides) => + new Proxy(overrides, { + get: (target, name) => + typeof name === 'string' && !(name in target) ? builtins.resolveKnownImport(pkg, name) : target[name], + }); + module.exports = (E) => { return { + 'io-ts': withBuiltins('io-ts', { + // A refinement only narrows decoding at runtime; its wire shape is the inner codec's. + refinement: (_, innerSchema) => E.right(innerSchema), + }), '.': { JsonFromStringifiedJson: () => E.right({ type: 'string' }), Optional: (_, innerSchema) => E.right({ type: 'union', schemas: [innerSchema, { type: 'undefined' }] }),