Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions modules/sdk-coin-stx/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,29 @@ export function findContractTokenNameUsingContract(contractAddress: string, cont
}
}

/**
* Contract id (`<contract address>.<contract name>`) of a SIP-10 asset id (`<contract id>::<token name>`).
*
* @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 - `<contract address>.<contract name>`
* @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
*
Expand Down
32 changes: 31 additions & 1 deletion modules/sdk-coin-stx/src/sip10Token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<boolean> {
const { txPrebuild: txPrebuild, txParams: txParams } = params;
const { memo } = txParams;
Expand All @@ -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);
Expand Down
91 changes: 87 additions & 4 deletions modules/sdk-coin-stx/src/stx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -45,8 +48,10 @@ import { TransactionBuilder } from './lib/transactionBuilder';
import {
findContractTokenNameUsingContract,
findTokenNameByContract,
findTokenNameByContractId,
getAddressDetails,
getMemoIdAndBaseAddressFromAddress,
removeHexPrefix,
} from './lib/utils';
import {
AddressDetails,
Expand All @@ -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
* (`<contract address>.<contract name>`).
*/
export type TransferredAsset = { type: 'native' } | { type: 'sip10'; contractId: string };

export class Stx extends BaseCoin {
protected readonly _staticsCoin: Readonly<StaticsBaseCoin>;

Expand All @@ -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;
}
Expand Down Expand Up @@ -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}`);
}
Comment thread
prikshitchawla300 marked this conversation as resolved.
Resolved
}

/**
* 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<SignedTransaction> {
this.assertTransferredAssetMatchesCoin(params.txPrebuild.txHex);
const factory = new StxLib.TransactionBuilderFactory(coins.get(this.getChain()));
const txBuilder = factory.from(params.txPrebuild.txHex, {
allowedStakingContracts: params.allowedStakingContracts,
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -515,13 +594,17 @@ export class Stx extends BaseCoin {
*/
protected async formatForOfflineVault(tx: BaseTransaction): Promise<RecoveryInfo> {
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;
}

Expand Down
28 changes: 21 additions & 7 deletions modules/sdk-coin-stx/test/unit/stx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
});

Expand Down Expand Up @@ -222,34 +225,45 @@ 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');
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]));
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:', () => {
Expand Down
Loading
Loading