From b758951f703ad142771f8f26bae4899e0ab5e45e Mon Sep 17 00:00:00 2001 From: prikshitchawla300 Date: Thu, 12 Nov 2026 12:37:03 +0530 Subject: [PATCH] fix(sdk-coin-stx): only handle transfers of the coin's own asset Stx and Sip10Token explain, sign and verify now check the asset decoded from the transaction against the coin instance: - Native Stx refuses SIP-10 token transfers. - Sip10Token accepts only a transfer of its own contract, and refuses native STX transfers, other tokens' transfers and other payloads. - formatForOfflineVault labels a recovery file with the coin of the asset it moves, so a token sweep built from native stx is labelled with the token, and a native sweep built from a token is labelled stx. BREAKING CHANGE: native stx/tstx no longer explains, signs or verifies SIP-10 token transfers, and a Sip10Token coin no longer handles transactions other than a transfer of its own token. Token transfers must be explained and signed through the token's coin (for example stx:sbtc). Offline vault files for token transfers that are labelled only stx must be regenerated. Ticket: CSHLD-2217 --- modules/sdk-coin-stx/src/lib/utils.ts | 23 ++ modules/sdk-coin-stx/src/sip10Token.ts | 32 +- modules/sdk-coin-stx/src/stx.ts | 91 +++++- modules/sdk-coin-stx/test/unit/stx.ts | 28 +- .../test/unit/transferredAsset.ts | 292 ++++++++++++++++++ 5 files changed, 454 insertions(+), 12 deletions(-) create mode 100644 modules/sdk-coin-stx/test/unit/transferredAsset.ts diff --git a/modules/sdk-coin-stx/src/lib/utils.ts b/modules/sdk-coin-stx/src/lib/utils.ts index cfae45b7e99..2fb80163cfa 100644 --- a/modules/sdk-coin-stx/src/lib/utils.ts +++ b/modules/sdk-coin-stx/src/lib/utils.ts @@ -672,6 +672,29 @@ export function findContractTokenNameUsingContract(contractAddress: string, cont } } +/** + * Contract id (`.`) of a SIP-10 asset id (`::`). + * + * @param {String} assetId + * @returns {String} + */ +export function getContractIdFromAssetId(assetId: string): string { + return assetId.split('::')[0]; +} + +/** + * Function to get the coin name of the SIP-10 token whose contract id matches exactly + * + * @param {String} contractId - `.` + * @returns {String|Undefined} + */ +export function findTokenNameByContractId(contractId: string): string | undefined { + const tokenNames = coins + .filter((coin) => coin instanceof Sip10Token && getContractIdFromAssetId(coin.assetId) === contractId) + .map((coin) => coin.name); + return tokenNames.length > 0 ? tokenNames[0] : undefined; +} + /** * Function to get address and memo details from address input * diff --git a/modules/sdk-coin-stx/src/sip10Token.ts b/modules/sdk-coin-stx/src/sip10Token.ts index a89387c4660..a11af96a4c7 100644 --- a/modules/sdk-coin-stx/src/sip10Token.ts +++ b/modules/sdk-coin-stx/src/sip10Token.ts @@ -7,7 +7,7 @@ import { BaseCoin as StaticsBaseCoin, coins, Sip10TokenConfig, tokens } from '@b import { Stx } from './stx'; import { TransactionBuilderFactory } from './lib'; import { TransactionBuilder } from './lib/transactionBuilder'; -import { getMemoIdAndBaseAddressFromAddress } from './lib/utils'; +import { getContractIdFromAssetId, getMemoIdAndBaseAddressFromAddress } from './lib/utils'; export class Sip10Token extends Stx { public readonly tokenConfig: Sip10TokenConfig; @@ -75,6 +75,33 @@ export class Sip10Token extends Stx { return new TransactionBuilderFactory(coinConfig).getFungibleTokenTransferBuilder(); } + /** + * Throws unless the transaction is a transfer of this token. A token coin only moves its own + * token, so it refuses native STX transfers, other tokens' transfers, and every other payload + * (send-many, staking, sBTC withdrawal and other contract calls). + * @param txHex + */ + protected assertTransferredAssetMatchesCoin(txHex: string): void { + const asset = this.getTransferredAsset(txHex); + const ownContractId = getContractIdFromAssetId(this.assetId); + if (asset?.type === 'sip10' && asset.contractId === ownContractId) { + return; + } + if (asset?.type === 'native') { + throw new Error(`${this.getChain()} cannot sign or explain a native STX transfer`); + } + if (asset?.type === 'sip10') { + throw new Error( + `${this.getChain()} cannot sign or explain a transfer of SIP-10 token ${ + asset.contractId + }, expected ${ownContractId}` + ); + } + throw new Error( + `${this.getChain()} cannot sign or explain a transaction that is not a transfer of ${ownContractId}` + ); + } + async verifyTransaction(params: VerifyTransactionOptions): Promise { const { txPrebuild: txPrebuild, txParams: txParams } = params; const { memo } = txParams; @@ -87,6 +114,9 @@ export class Sip10Token extends Stx { if (!rawTx) { throw new Error('missing required tx prebuild property txHex'); } + // explainTransaction below runs this check too; it is repeated here so a mismatched asset is + // refused with a clear error before transaction.from() fails on a non-token payload. + this.assertTransferredAssetMatchesCoin(rawTx); const coinConfig = coins.get(this.getChain()); const transaction = this.getTransaction(coinConfig); transaction.from(rawTx); diff --git a/modules/sdk-coin-stx/src/stx.ts b/modules/sdk-coin-stx/src/stx.ts index 6d6c23f6892..f2b306001d4 100644 --- a/modules/sdk-coin-stx/src/stx.ts +++ b/modules/sdk-coin-stx/src/stx.ts @@ -22,13 +22,16 @@ import { } from '@bitgo/sdk-core'; import { BaseCoin as StaticsBaseCoin, CoinFamily, coins } from '@bitgo/statics'; import { + addressToString, bufferCVFromString, + BytesReader, ClarityType, ClarityValue, cvToString, cvToValue, deserializeTransaction, noneCV, + PayloadType, privateKeyToHex, publicKeyToHex, serializePayload, @@ -45,8 +48,10 @@ import { TransactionBuilder } from './lib/transactionBuilder'; import { findContractTokenNameUsingContract, findTokenNameByContract, + findTokenNameByContractId, getAddressDetails, getMemoIdAndBaseAddressFromAddress, + removeHexPrefix, } from './lib/utils'; import { AddressDetails, @@ -62,6 +67,12 @@ import { import { TransferBuilder } from './lib/transferBuilder'; import { FungibleTokenTransferBuilder } from './lib/fungibleTokenTransferBuilder'; +/** + * The asset a transfer moves: native STX, or a SIP-10 token identified by its contract id + * (`.`). + */ +export type TransferredAsset = { type: 'native' } | { type: 'sip10'; contractId: string }; + export class Stx extends BaseCoin { protected readonly _staticsCoin: Readonly; @@ -83,6 +94,13 @@ export class Stx extends BaseCoin { return this._staticsCoin.name; } + /** + * The native coin of this chain. Sip10Token overrides this to return its parent coin. + */ + getBaseChain(): string { + return this.getChain(); + } + getFamily(): CoinFamily { return this._staticsCoin.family; } @@ -278,11 +296,71 @@ export class Stx extends BaseCoin { } } + /** + * The asset a transaction transfers, decoded from its bytes: native STX for a token-transfer + * payload, or the SIP-10 contract id for a fungible-token `transfer` call. Undefined for other + * payloads (staking, send-many, sBTC withdrawal and other contract calls). + * @param txHex + */ + protected getTransferredAsset(txHex: string): TransferredAsset | undefined { + // Validate first so malformed input keeps failing with the factory's errors + // (InvalidTransactionError / ParseTransactionError) rather than raw decoder errors. + new StxLib.TransactionBuilderFactory(coins.get(this.getChain())).validateRawTransaction(txHex); + const { payload } = deserializeTransaction(new BytesReader(removeHexPrefix(txHex))); + if (payload.payloadType === PayloadType.TokenTransfer) { + return { type: 'native' }; + } + if ( + payload.payloadType === PayloadType.ContractCall && + FungibleTokenTransferBuilder.isFungibleTokenTransferContractCall(payload) + ) { + return { + type: 'sip10', + contractId: `${addressToString(payload.contractAddress)}.${payload.contractName.content}`, + }; + } + return undefined; + } + + /** + * Throws if the transaction transfers an asset other than this coin. The native coin only + * transfers STX, so it refuses SIP-10 token transfers. + * @param txHex + */ + protected assertTransferredAssetMatchesCoin(txHex: string): void { + const asset = this.getTransferredAsset(txHex); + if (asset?.type === 'sip10') { + throw new Error(`${this.getChain()} cannot sign or explain a transfer of SIP-10 token ${asset.contractId}`); + } + } + + /** + * The coin whose label matches the asset the transaction transfers: the SIP-10 token's coin + * for a token transfer, the base coin for a native STX transfer, otherwise this coin. + * @param txHex + */ + protected getCoinForTransferredAsset(txHex: string): Stx { + const asset = this.getTransferredAsset(txHex); + if (asset?.type === 'native') { + // A token coin can build a native sweep (recover without contractId); label it as STX. + return this.getBaseChain() === this.getChain() ? this : (this.bitgo.coin(this.getBaseChain()) as Stx); + } + if (asset?.type !== 'sip10') { + return this; + } + const tokenName = findTokenNameByContractId(asset.contractId); + if (!tokenName) { + throw new Error(`unsupported SIP-10 token contract ${asset.contractId}`); + } + return this.bitgo.coin(tokenName) as Stx; + } + /** * Signs stacks transaction * @param params */ async signTransaction(params: StxSignTransactionOptions): Promise { + this.assertTransferredAssetMatchesCoin(params.txPrebuild.txHex); const factory = new StxLib.TransactionBuilderFactory(coins.get(this.getChain())); const txBuilder = factory.from(params.txPrebuild.txHex, { allowedStakingContracts: params.allowedStakingContracts, @@ -317,6 +395,7 @@ export class Stx extends BaseCoin { if (!txHex || !params.feeInfo) { throw new Error('missing explain tx parameters'); } + this.assertTransferredAssetMatchesCoin(txHex); const factory = new StxLib.TransactionBuilderFactory(coins.get(this.getChain())); const txBuilder = factory.from(txHex, { allowedStakingContracts: params.allowedStakingContracts }); @@ -515,13 +594,17 @@ export class Stx extends BaseCoin { */ protected async formatForOfflineVault(tx: BaseTransaction): Promise { const txJson: TxData = tx.toJson(); - const transactionExplanation: RecoveryInfo = (await this.explainTransaction({ - txHex: tx.toBroadcastFormat(), + const txHex = tx.toBroadcastFormat(); + // Label the file with the asset the transaction actually moves, so a token sweep built from + // the native coin is explained and signed as that token. + const coin = this.getCoinForTransferredAsset(txHex); + const transactionExplanation: RecoveryInfo = (await coin.explainTransaction({ + txHex, feeInfo: { fee: txJson.fee }, })) as RecoveryInfo; - transactionExplanation.coin = this.getChain(); + transactionExplanation.coin = coin.getChain(); transactionExplanation.feeInfo = { fee: txJson.fee }; - transactionExplanation.txHex = tx.toBroadcastFormat(); + transactionExplanation.txHex = txHex; return transactionExplanation; } diff --git a/modules/sdk-coin-stx/test/unit/stx.ts b/modules/sdk-coin-stx/test/unit/stx.ts index 13aa4c973c4..08b278e8f55 100644 --- a/modules/sdk-coin-stx/test/unit/stx.ts +++ b/modules/sdk-coin-stx/test/unit/stx.ts @@ -10,7 +10,7 @@ import { cvToString, deserializeCV, privateKeyToPublic, publicKeyToHex } from '@ import * as testData from '../fixtures'; import * as resources from './resources'; import { pox5RegisterForBondArgsHex } from './registerForBondRealArgs'; -import { Stx, StxLib, Tstx } from '../../src'; +import { Sip10Token, Stx, StxLib, Tstx } from '../../src'; import { RecoveryInfo, RecoveryOptions, RecoveryTransaction } from '../../src/lib/iface'; const { KeyPair } = StxLib; @@ -45,6 +45,9 @@ describe('STX:', function () { bitgo.initializeTestVars(); bitgo.safeRegister('stx', Stx.createInstance); bitgo.safeRegister('tstx', Tstx.createInstance); + Sip10Token.createTokenConstructors().forEach(({ name, coinConstructor }) => { + bitgo.safeRegister(name, coinConstructor); + }); basecoin = bitgo.coin(coinNameTest); }); @@ -222,26 +225,37 @@ describe('STX:', function () { assert.doesNotThrow(() => JSON.stringify(explain.contractFunctionArgs)); }); + it('should refuse to explain a fungible token transfer transaction with the native coin', async function () { + await assert.rejects( + basecoin.explainTransaction({ txHex: testData.txForExplainFungibleTokenTransfer, feeInfo: { fee: '' } }), + /cannot sign or explain a transfer of SIP-10 token/ + ); + }); + it('should explain a fungible token transfer transaction with memo', async function () { - const explain = await basecoin.explainTransaction({ + const tokenCoin = bitgo.coin(testData.fungibleTokenTransferTx.tokenName) as Sip10Token; + const explain = await tokenCoin.explainTransaction({ txHex: testData.txForExplainFungibleTokenTransfer, feeInfo: { fee: '' }, }); + assert.ok(explain); explain.id.should.equal(testData.fungibleTokenTransferTx.id); explain.fee.should.equal(testData.fungibleTokenTransferTx.fee); - explain.memo.should.equal('1'); + assert.strictEqual(explain.memo, '1'); explain.outputAmount.should.equal(testData.fungibleTokenTransferTx.functionArgs[2].value); explain.outputs[0].amount.should.equal(testData.fungibleTokenTransferTx.functionArgs[2].value); explain.outputs[0].address.should.equal(cvToString(testData.fungibleTokenTransferTx.functionArgs[1])); - explain.outputs[0].memo.should.equal('1'); - explain.outputs[0].tokenName.should.equal(testData.fungibleTokenTransferTx.tokenName); + assert.strictEqual(explain.outputs[0].memo, '1'); + assert.strictEqual(explain.outputs[0].tokenName, testData.fungibleTokenTransferTx.tokenName); }); it('should explain a fungible token transfer transaction without memo', async function () { - const explain = await basecoin.explainTransaction({ + const tokenCoin = bitgo.coin(testData.fungibleTokenTransferTx.tokenName) as Sip10Token; + const explain = await tokenCoin.explainTransaction({ txHex: testData.txForExplainFungibleTokenTransferWithoutMemo, feeInfo: { fee: '' }, }); + assert.ok(explain); explain.id.should.equal(testData.hexWithoutMemoTransferId); explain.fee.should.equal(testData.fungibleTokenTransferTx.fee); assert.deepEqual(explain.memo, undefined, 'memo should be undefined'); @@ -249,7 +263,7 @@ describe('STX:', function () { explain.outputs[0].amount.should.equal(testData.fungibleTokenTransferTx.functionArgs[2].value); explain.outputs[0].address.should.equal(cvToString(testData.fungibleTokenTransferTx.functionArgs[1])); assert.deepEqual(explain.outputs[0].memo, undefined, 'memo should be undefined'); - explain.outputs[0].tokenName.should.equal(testData.fungibleTokenTransferTx.tokenName); + assert.strictEqual(explain.outputs[0].tokenName, testData.fungibleTokenTransferTx.tokenName); }); describe('Keypairs:', () => { diff --git a/modules/sdk-coin-stx/test/unit/transferredAsset.ts b/modules/sdk-coin-stx/test/unit/transferredAsset.ts new file mode 100644 index 00000000000..3d85398c7ad --- /dev/null +++ b/modules/sdk-coin-stx/test/unit/transferredAsset.ts @@ -0,0 +1,292 @@ +import assert from 'assert'; +import nock from 'nock'; +import { TestBitGo, TestBitGoAPI } from '@bitgo/sdk-test'; +import { BitGoAPI } from '@bitgo/sdk-api'; +import { BaseTransaction, Wallet } from '@bitgo/sdk-core'; +import { coins } from '@bitgo/statics'; +import { noneCV, privateKeyToPublic, publicKeyToHex, standardPrincipalCV, uintCV } from '@stacks/transactions'; + +import { Sip10Token, Stx, StxLib } from '../../src'; +import { RecoveryInfo, RecoveryOptions } from '../../src/lib/iface'; +import * as fixtures from '../fixtures'; +import * as testData from './resources'; + +// A coin instance must only explain, sign and verify transfers of its own asset: the native coin +// refuses SIP-10 token transfers, and a token refuses native transfers and other tokens' transfers. +describe('Stacks: transferred asset must match the coin', function () { + const SBTC_CONTRACT_ADDRESS = 'SM3VDXK3WZZSA84XXFKAFAF15NNZX32CTSG82JFQ4'; + const SBTC_CONTRACT_NAME = 'sbtc-token'; + const SBTC_CONTRACT_ID = `${SBTC_CONTRACT_ADDRESS}.${SBTC_CONTRACT_NAME}`; + const MISMATCH = /cannot sign or explain/; + + let bitgo: TestBitGoAPI; + // Signed transactions carry the sender's public key, so they can be explained without passing + // publicKeys. The unsigned one is used where the coin itself signs. + let sbtcTransfer: BaseTransaction; + let unsignedSbtcTransfer: BaseTransaction; + let nativeTransfer: BaseTransaction; + // Testnet payloads that are not token transfers + let sbtcWithdrawal: BaseTransaction; + const sendMany = testData.SIGNED_SEND_MANY_WITH_MEMO; + const staking = testData.SIGNED_SELF_STACK_CONTRACT_CALL; + + async function buildSbtcWithdrawal(): Promise { + const builder = new StxLib.TransactionBuilderFactory(coins.get('tstx')).getSbtcWithdrawBuilder(); + builder.fee({ fee: '1000' }); + builder.nonce(1); + builder.fromPubKey(testData.prvKeysString.map((prv) => publicKeyToHex(privateKeyToPublic(prv)))); + builder.numberSignatures(2); + builder.withdraw({ amount: '100000', btcAddress: '1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2', maxFee: '5000' }); + builder.sign({ key: testData.prvKeysString[0] }); + builder.sign({ key: testData.prvKeysString[1] }); + return builder.build(); + } + + async function buildSbtcTransfer({ signed }: { signed: boolean }): Promise { + const builder = new StxLib.TransactionBuilderFactory(coins.get('stx:sbtc')).getFungibleTokenTransferBuilder(); + builder.fee({ fee: '180' }); + builder.nonce(0); + builder.contractAddress(SBTC_CONTRACT_ADDRESS); + builder.contractName(SBTC_CONTRACT_NAME); + builder.functionName('transfer'); + builder.tokenName('sbtc-token'); + builder.functionArgs([ + uintCV('100000000'), // 1 sBTC + standardPrincipalCV(testData.address1), + standardPrincipalCV(testData.address2), + noneCV(), + ]); + builder.fromPubKey(testData.pub1); + builder.numberSignatures(1); + if (signed) { + builder.sign({ key: testData.prv1 }); + } + return builder.build(); + } + + async function buildNativeTransfer(): Promise { + const builder = new StxLib.TransactionBuilderFactory(coins.get('stx')).getTransferBuilder(); + builder.fee({ fee: '180' }); + builder.nonce(0); + builder.to(testData.address2); + builder.amount('1000000000000'); // 1,000,000 STX + builder.sign({ key: testData.prv1 }); + return builder.build(); + } + + function explain(coin: Stx, tx: BaseTransaction) { + return coin.explainTransaction({ txHex: tx.toBroadcastFormat(), feeInfo: { fee: '' } }); + } + + function sign(coin: Stx, tx: BaseTransaction) { + return coin.signTransaction({ + txPrebuild: { txHex: tx.toBroadcastFormat(), source: testData.address1 }, + prv: testData.prv1, + }); + } + + function verify(coin: Stx, tx: BaseTransaction, amount: string) { + return coin.verifyTransaction({ + txPrebuild: { txHex: tx.toBroadcastFormat() }, + txParams: { recipients: [{ address: testData.address2, amount }] }, + wallet: new Wallet(bitgo, coin, {}), + }); + } + + before(async function () { + bitgo = TestBitGo.decorate(BitGoAPI, { env: 'mock' }); + bitgo.initializeTestVars(); + bitgo.safeRegister('stx', Stx.createInstance); + Sip10Token.createTokenConstructors().forEach(({ name, coinConstructor }) => { + bitgo.safeRegister(name, coinConstructor); + }); + sbtcTransfer = await buildSbtcTransfer({ signed: true }); + unsignedSbtcTransfer = await buildSbtcTransfer({ signed: false }); + nativeTransfer = await buildNativeTransfer(); + sbtcWithdrawal = await buildSbtcWithdrawal(); + }); + + afterEach(function () { + nock.cleanAll(); + }); + + describe('native stx refuses a SIP-10 transfer', function () { + it('explainTransaction', async function () { + await assert.rejects(explain(bitgo.coin('stx') as Stx, sbtcTransfer), MISMATCH); + }); + + it('signTransaction', async function () { + await assert.rejects(sign(bitgo.coin('stx') as Stx, unsignedSbtcTransfer), MISMATCH); + }); + + it('verifyTransaction, even when the amount matches', async function () { + await assert.rejects(verify(bitgo.coin('stx') as Stx, sbtcTransfer, '100000000'), MISMATCH); + }); + }); + + describe('a SIP-10 token refuses a transfer of a different token', function () { + it('explainTransaction', async function () { + await assert.rejects(explain(bitgo.coin('stx:aeusdc') as Stx, sbtcTransfer), MISMATCH); + }); + + it('signTransaction', async function () { + await assert.rejects(sign(bitgo.coin('stx:aeusdc') as Stx, sbtcTransfer), MISMATCH); + }); + + it('verifyTransaction', async function () { + await assert.rejects(verify(bitgo.coin('stx:aeusdc') as Stx, sbtcTransfer, '100000000'), MISMATCH); + }); + }); + + describe('a SIP-10 token refuses a native STX transfer', function () { + it('explainTransaction', async function () { + await assert.rejects(explain(bitgo.coin('stx:sbtc') as Stx, nativeTransfer), MISMATCH); + }); + + it('signTransaction', async function () { + await assert.rejects(sign(bitgo.coin('stx:sbtc') as Stx, nativeTransfer), MISMATCH); + }); + + it('verifyTransaction', async function () { + await assert.rejects(verify(bitgo.coin('stx:sbtc') as Stx, nativeTransfer, '1000000000000'), MISMATCH); + }); + }); + + describe('a SIP-10 token refuses payloads that are not its own transfer', function () { + const cases: Array<{ name: string; coin: string; txHex: () => string }> = [ + { name: 'send-many (moves native STX)', coin: 'tstx:tsip6dp', txHex: () => sendMany }, + { name: 'staking contract call', coin: 'tstx:tsip6dp', txHex: () => staking }, + { name: 'sBTC withdrawal', coin: 'tstx:tsbtc', txHex: () => sbtcWithdrawal.toBroadcastFormat() }, + ]; + + for (const { name, coin, txHex } of cases) { + it(`${coin} refuses to explain ${name}`, async function () { + await assert.rejects( + (bitgo.coin(coin) as Stx).explainTransaction({ txHex: txHex(), feeInfo: { fee: '' } }), + MISMATCH + ); + }); + + it(`${coin} refuses to sign ${name}`, async function () { + await assert.rejects( + (bitgo.coin(coin) as Stx).signTransaction({ + txPrebuild: { txHex: txHex(), source: testData.address1 }, + prv: testData.prvKeysString[2], + }), + MISMATCH + ); + }); + } + }); + + describe('native stx still accepts payloads that move or lock STX', function () { + const cases: Array<{ name: string; txHex: () => string }> = [ + { name: 'send-many', txHex: () => sendMany }, + { name: 'staking contract call', txHex: () => staking }, + { name: 'sBTC withdrawal', txHex: () => sbtcWithdrawal.toBroadcastFormat() }, + ]; + + for (const { name, txHex } of cases) { + it(`tstx explains ${name}`, async function () { + const explained = await (bitgo.coin('tstx') as Stx).explainTransaction({ + txHex: txHex(), + feeInfo: { fee: '' }, + }); + assert.ok(explained); + }); + } + }); + + describe('malformed input keeps the factory errors', function () { + it('non-hex txHex fails with ParseTransactionError', async function () { + await assert.rejects( + (bitgo.coin('stx') as Stx).explainTransaction({ txHex: 'zz', feeInfo: { fee: '' } }), + /Invalid raw transaction/ + ); + }); + + it('truncated txHex fails with ParseTransactionError', async function () { + const truncated = nativeTransfer.toBroadcastFormat().slice(0, 40); + await assert.rejects( + (bitgo.coin('stx') as Stx).explainTransaction({ txHex: truncated, feeInfo: { fee: '' } }), + /Invalid raw transaction/ + ); + }); + }); + + describe('matching assets still work', function () { + it('native stx explains a native transfer', async function () { + const explained = await explain(bitgo.coin('stx') as Stx, nativeTransfer); + assert.strictEqual(explained?.outputAmount, '1000000000000'); + }); + + it('stx:sbtc explains an sBTC transfer', async function () { + const explained = await explain(bitgo.coin('stx:sbtc') as Stx, sbtcTransfer); + assert.strictEqual(explained?.outputAmount, '100000000'); + assert.strictEqual(explained?.outputs[0].tokenName, 'stx:sbtc'); + }); + + it('stx:sbtc signs an sBTC transfer', async function () { + const signed = await (bitgo.coin('stx:sbtc') as Stx).signTransaction({ + txPrebuild: { txHex: unsignedSbtcTransfer.toBroadcastFormat(), source: testData.address1 }, + prv: testData.prv1, + pubKeys: [testData.pub1], + }); + assert.ok('txHex' in signed || 'halfSigned' in signed); + }); + }); + + describe('offline vault files are labelled with the transferred asset', function () { + it('a token sweep built from native stx is labelled with the token', async function () { + const stx = bitgo.coin('stx') as Stx; + const info = await stx['formatForOfflineVault'](sbtcTransfer); + assert.strictEqual(info.coin, 'stx:sbtc'); + assert.strictEqual(info.outputs[0].tokenName, 'stx:sbtc'); + }); + + it('an unsigned token sweep through native tstx recover() is labelled with the token', async function () { + const rootAddress = fixtures.COLD_WALLET_ROOT_ADDRESS; + nock('https://api.testnet.hiro.so') + .get(`/extended/v2/addresses/${rootAddress}/balances/stx`) + .reply(200, fixtures.ACCOUNT_BALANCE_RESPONSE); + nock('https://api.testnet.hiro.so') + .get(`/extended/v2/addresses/${rootAddress}/balances/ft/${fixtures.STX_TOKEN_ASSET_ID}`) + .reply(200, fixtures.TOKEN_BALANCE_RESPONSE); + nock('https://api.testnet.hiro.so', { allowUnmocked: true }) + .get(`/extended/v1/address/${rootAddress}/nonces`) + .reply(200, fixtures.ACCOUNT_NONCE_RESPONSE); + nock('https://api.testnet.hiro.so') + .post('/v2/fees/transaction') + .reply(200, fixtures.FEE_ESTIMATION_TOKEN_RESPONSE); + + const recoveryOptions: RecoveryOptions = { + backupKey: fixtures.COLD_WALLET_PUBLIC_KEY_INFO.BACKUP_KEY, + userKey: fixtures.COLD_WALLET_PUBLIC_KEY_INFO.USER_KEY, + rootAddress, + recoveryDestination: fixtures.DESTINATION_ADDRESS_WRW, + bitgoKey: fixtures.COLD_WALLET_PUBLIC_KEY_INFO.BITGO_PUB_KEY, + contractId: 'STAG18E45W613FZ3H4ZMF6QHH426EXM5QTSAVWYH.tsip6dp-token', + }; + const response = (await (bitgo.coin('tstx') as Stx).recover(recoveryOptions)) as RecoveryInfo; + assert.strictEqual(response.txHex, fixtures.COLD_WALLET_TOKEN_UNSIGNED_SWEEP_TX_HEX); + assert.strictEqual(response.coin, 'tstx:tsip6dp'); + }); + + it('a native sweep built from a token coin is labelled with the base coin', async function () { + const sbtc = bitgo.coin('stx:sbtc') as Stx; + const info = await sbtc['formatForOfflineVault'](nativeTransfer); + assert.strictEqual(info.coin, 'stx'); + }); + + it('a native sweep stays labelled stx', async function () { + const stx = bitgo.coin('stx') as Stx; + const info = await stx['formatForOfflineVault'](nativeTransfer); + assert.strictEqual(info.coin, 'stx'); + }); + }); + + it('matches the sBTC contract id exactly', function () { + assert.strictEqual(StxLib.Utils.findTokenNameByContractId(SBTC_CONTRACT_ID), 'stx:sbtc'); + assert.strictEqual(StxLib.Utils.findTokenNameByContractId(`${SBTC_CONTRACT_ID}-v2`), undefined); + }); +});