Skip to content
Open
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
2 changes: 2 additions & 0 deletions modules/sdk-coin-stx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@
"@noble/curves": "1.8.1",
"@stacks/network": "^4.3.0",
"@stacks/transactions": "2.0.1",
"bech32": "^2.0.0",
"bignumber.js": "^9.0.0",
"bn.js": "^5.2.1",
"bs58check": "^2.1.2",
"ethereumjs-util": "7.1.5",
"lodash": "^4.18.0"
},
Expand Down
106 changes: 106 additions & 0 deletions modules/sdk-coin-stx/src/lib/btcAddressUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import * as bs58check from 'bs58check';
import { bech32, bech32m } from 'bech32';

/**
* sBTC address version bytes as defined by the sBTC withdrawal contract.
*/
export enum SbtcAddressVersion {
P2PKH = 0x00,
P2SH = 0x01,
P2WPKH = 0x04,
P2WSH = 0x05,
P2TR = 0x06,
}

interface DecodedBtcAddress {
version: SbtcAddressVersion;
hashBytes: Buffer;
}

const BASE58_MAINNET_P2PKH = 0x00;
const BASE58_MAINNET_P2SH = 0x05;
const BASE58_TESTNET_P2PKH = 0x6f;
const BASE58_TESTNET_P2SH = 0xc4;

/**
* Decode a Bitcoin address into an sBTC version byte and hash bytes.
*
* @param {string} address - A Bitcoin address (P2PKH, P2SH, P2WPKH, P2WSH, or P2TR)
* @returns {DecodedBtcAddress} The sBTC version and raw hash bytes
*/
export function decodeBtcAddress(address: string): DecodedBtcAddress {
// Try base58check first (P2PKH / P2SH)
try {
const decoded = bs58check.decode(address);
const versionByte = decoded[0];
const hash = decoded.slice(1);

if (hash.length !== 20) {
throw new Error(`Invalid base58check hash length: ${hash.length}`);
}

switch (versionByte) {
case BASE58_MAINNET_P2PKH:
case BASE58_TESTNET_P2PKH:
return { version: SbtcAddressVersion.P2PKH, hashBytes: Buffer.from(hash) };
case BASE58_MAINNET_P2SH:
case BASE58_TESTNET_P2SH:
return { version: SbtcAddressVersion.P2SH, hashBytes: Buffer.from(hash) };
default:
throw new Error(`Unknown base58check version byte: 0x${versionByte.toString(16)}`);
}
} catch (e) {
// Not base58check, try bech32/bech32m below
}

// Try bech32 (P2WPKH / P2WSH) and bech32m (P2TR)
let decoded: { prefix: string; words: number[] };
let isBech32m = false;

try {
decoded = bech32.decode(address);
} catch {
try {
decoded = bech32m.decode(address);
isBech32m = true;
} catch {
throw new Error(`Unable to decode Bitcoin address: ${address}`);
}
}

const witnessVersion = decoded.words[0];
const data = Buffer.from(bech32.fromWords(decoded.words.slice(1)));

if (witnessVersion === 0 && !isBech32m) {
if (data.length === 20) {
return { version: SbtcAddressVersion.P2WPKH, hashBytes: data };
} else if (data.length === 32) {
return { version: SbtcAddressVersion.P2WSH, hashBytes: data };
}
throw new Error(`Invalid witness v0 program length: ${data.length}`);
}

if (witnessVersion === 1 && isBech32m) {
if (data.length === 32) {
return { version: SbtcAddressVersion.P2TR, hashBytes: data };
}
throw new Error(`Invalid witness v1 program length: ${data.length}`);
}

throw new Error(`Unsupported witness version ${witnessVersion} for address: ${address}`);
}

/**
* Check whether a string is a valid Bitcoin address decodable for sBTC withdrawals.
*
* @param {string} address - The address to validate
* @returns {boolean} true if the address can be decoded
*/
export function isValidBtcAddress(address: string): boolean {
try {
decodeBtcAddress(address);
return true;
} catch {
return false;
}
}
3 changes: 3 additions & 0 deletions modules/sdk-coin-stx/src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ export const FUNCTION_NAME_SENDMANY = 'send-many';
export const CONTRACT_NAME_SENDMANY = 'send-many-memo';
export const CONTRACT_NAME_STAKING = 'pox-4';
export const FUNCTION_NAME_TRANSFER = 'transfer';
export const CONTRACT_NAME_SBTC_WITHDRAWAL = 'sbtc-withdrawal';
export const FUNCTION_NAME_INITIATE_WITHDRAWAL = 'initiate-withdrawal-request';

export const VALID_CONTRACT_FUNCTION_NAMES = [
'stack-stx',
Expand All @@ -11,6 +13,7 @@ export const VALID_CONTRACT_FUNCTION_NAMES = [
'revoke-delegate-stx',
'send-many',
'transfer',
'initiate-withdrawal-request',
];

export const DEFAULT_SEED_SIZE_BYTES = 64;
Expand Down
6 changes: 6 additions & 0 deletions modules/sdk-coin-stx/src/lib/iface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,9 @@ export interface RecoveryInfo extends BaseTransactionExplanation {
export interface RecoveryTransaction {
txHex: string;
}

export interface SbtcWithdrawParams {
amount: string;
btcAddress: string;
maxFee: string;
}
1 change: 1 addition & 0 deletions modules/sdk-coin-stx/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export { AddressVersion, AddressHashMode } from '@stacks/transactions';
export * from './keyPair';
export * from './transaction';
export * from './transactionBuilderFactory';
export * from './sbtcWithdrawBuilder';
export * as Utils from './utils';
173 changes: 173 additions & 0 deletions modules/sdk-coin-stx/src/lib/sbtcWithdrawBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import { BaseCoin as CoinConfig, NetworkType, StacksNetwork as BitgoStacksNetwork } from '@bitgo/statics';
import BigNum from 'bn.js';
import {
AddressHashMode,
addressToString,
AddressVersion,
bufferCV,
ClarityType,
createAssetInfo,
FungibleConditionCode,
makeStandardFungiblePostCondition,
PostCondition,
PostConditionMode,
tupleCV,
uintCV,
} from '@stacks/transactions';
import { BuildTransactionError } from '@bitgo/sdk-core';
import { Transaction } from './transaction';
import { getSTXAddressFromPubKeys, isValidAmount } from './utils';
import { SbtcWithdrawParams } from './iface';
import { CONTRACT_NAME_SBTC_WITHDRAWAL, FUNCTION_NAME_INITIATE_WITHDRAWAL } from './constants';
import { ContractCallPayload } from '@stacks/transactions/dist/payload';
import { AbstractContractBuilder } from './abstractContractBuilder';
import { decodeBtcAddress, isValidBtcAddress } from './btcAddressUtils';

const SBTC_TOKEN_CONTRACT_NAME = 'sbtc-token';
const SBTC_TOKEN_ASSET_NAME = 'sbtc-token';
const HASHBYTES_BUFFER_LENGTH = 32;

export class SbtcWithdrawBuilder extends AbstractContractBuilder {
private _withdrawParams: SbtcWithdrawParams | undefined;
private _isDeserialized = false;

constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
}

/**
* Check whether a deserialized contract-call payload matches the sBTC withdrawal contract.
*/
public static isValidContractCall(coinConfig: Readonly<CoinConfig>, payload: ContractCallPayload): boolean {
return (
(coinConfig.network as BitgoStacksNetwork).sbtcWithdrawalContractAddress ===
addressToString(payload.contractAddress) &&
CONTRACT_NAME_SBTC_WITHDRAWAL === payload.contractName.content &&
FUNCTION_NAME_INITIATE_WITHDRAWAL === payload.functionName.content
);
}

/**
* Set withdrawal parameters.
*
* @param {SbtcWithdrawParams} params - amount (satoshis), btcAddress, maxFee
* @returns {this}
*/
withdraw(params: SbtcWithdrawParams): this {
if (!params.amount || !isValidAmount(params.amount) || params.amount === '0') {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn’t it better to allow zero-value contract interactions?

throw new BuildTransactionError('Invalid or missing amount, got: ' + params.amount);
}
if (!params.btcAddress || !isValidBtcAddress(params.btcAddress)) {
throw new BuildTransactionError('Invalid or missing btcAddress, got: ' + params.btcAddress);
}
if (!params.maxFee || !isValidAmount(params.maxFee) || params.maxFee === '0') {
throw new BuildTransactionError('Invalid or missing maxFee, got: ' + params.maxFee);
}
this._withdrawParams = params;
return this;
}

initBuilder(tx: Transaction): void {
super.initBuilder(tx);
const payload = tx.stxTransaction.payload as ContractCallPayload;
const args = payload.functionArgs;

if (args.length !== 3) {
throw new BuildTransactionError('Invalid number of function args for sBTC withdrawal');
}

// args[0] = uint (amount)
if (args[0].type !== ClarityType.UInt) {
throw new BuildTransactionError('Expected uint for amount argument');
}
const amount = args[0].value.toString();

// args[1] = tuple { version: (buff 1), hashbytes: (buff 32) }
if (args[1].type !== ClarityType.Tuple) {
throw new BuildTransactionError('Expected tuple for recipient argument');
}
const versionBuf = args[1].data['version'];
const hashbytesBuf = args[1].data['hashbytes'];
if (versionBuf?.type !== ClarityType.Buffer || hashbytesBuf?.type !== ClarityType.Buffer) {
throw new BuildTransactionError('Expected buffer fields in recipient tuple');
}

// args[2] = uint (max-fee)
if (args[2].type !== ClarityType.UInt) {
throw new BuildTransactionError('Expected uint for max-fee argument');
}
const maxFee = args[2].value.toString();

this._withdrawParams = {
amount,
btcAddress: '', // not needed for rebuild; function args are preserved from the original tx
maxFee,
};
this._isDeserialized = true;
}

/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
if (!this._withdrawParams) {
throw new BuildTransactionError('Withdrawal params are not set. Use withdraw() to set them.');
}

const network = this._coinConfig.network as BitgoStacksNetwork;
this._contractAddress = network.sbtcWithdrawalContractAddress;
this._contractName = CONTRACT_NAME_SBTC_WITHDRAWAL;
this._functionName = FUNCTION_NAME_INITIATE_WITHDRAWAL;

// For deserialized transactions, function args are already preserved from the original tx.
// For fresh builds, construct them from the withdraw params.
if (!this._isDeserialized) {
this._functionArgs = this.withdrawParamsToFunctionArgs(this._withdrawParams);
}

this._postConditionMode = PostConditionMode.Deny;
this._postConditions = this.withdrawParamsToPostCondition(this._withdrawParams);
return await super.buildImplementation();
}

private withdrawParamsToFunctionArgs(params: SbtcWithdrawParams) {
const decoded = decodeBtcAddress(params.btcAddress);

// Pad 20-byte hashes to 32 bytes with trailing zeros per sBTC contract spec (buff 32)
let hashBytes = decoded.hashBytes;
if (hashBytes.length < HASHBYTES_BUFFER_LENGTH) {
const padded = Buffer.alloc(HASHBYTES_BUFFER_LENGTH, 0);
hashBytes.copy(padded);
hashBytes = padded;
}

return [
uintCV(params.amount),
tupleCV({
version: bufferCV(Buffer.from([decoded.version])),
hashbytes: bufferCV(hashBytes),
}),
uintCV(params.maxFee),
];
}

private withdrawParamsToPostCondition(params: SbtcWithdrawParams): PostCondition[] {
const amount = new BigNum(params.amount).add(new BigNum(params.maxFee));
const network = this._coinConfig.network as BitgoStacksNetwork;
const sbtcContractAddress = network.sbtcWithdrawalContractAddress;

return [
makeStandardFungiblePostCondition(
getSTXAddressFromPubKeys(
this._fromPubKeys,
this._coinConfig.network.type === NetworkType.MAINNET
? AddressVersion.MainnetMultiSig
: AddressVersion.TestnetMultiSig,
this._fromPubKeys.length > 1 ? AddressHashMode.SerializeP2SH : AddressHashMode.SerializeP2PKH,
this._numberSignatures
).address,
FungibleConditionCode.Equal,
amount,
createAssetInfo(sbtcContractAddress, SBTC_TOKEN_CONTRACT_NAME, SBTC_TOKEN_ASSET_NAME)
),
];
}
}
8 changes: 8 additions & 0 deletions modules/sdk-coin-stx/src/lib/transactionBuilderFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Transaction } from './transaction';
import { ContractBuilder } from './contractBuilder';
import { Utils } from '.';
import { SendmanyBuilder } from './sendmanyBuilder';
import { SbtcWithdrawBuilder } from './sbtcWithdrawBuilder';
import { FungibleTokenTransferBuilder } from './fungibleTokenTransferBuilder';

export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
Expand All @@ -31,6 +32,9 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
if (SendmanyBuilder.isValidContractCall(this._coinConfig, tx.stxTransaction.payload)) {
return this.getSendmanyBuilder(tx);
}
if (SbtcWithdrawBuilder.isValidContractCall(this._coinConfig, tx.stxTransaction.payload)) {
return this.getSbtcWithdrawBuilder(tx);
}
if (FungibleTokenTransferBuilder.isFungibleTokenTransferContractCall(tx.stxTransaction.payload)) {
return this.getFungibleTokenTransferBuilder(tx);
}
Expand Down Expand Up @@ -71,6 +75,10 @@ export class TransactionBuilderFactory extends BaseTransactionBuilderFactory {
return TransactionBuilderFactory.initializeBuilder(new SendmanyBuilder(this._coinConfig), tx);
}

getSbtcWithdrawBuilder(tx?: Transaction): SbtcWithdrawBuilder {
return TransactionBuilderFactory.initializeBuilder(new SbtcWithdrawBuilder(this._coinConfig), tx);
}

getFungibleTokenTransferBuilder(tx?: Transaction): FungibleTokenTransferBuilder {
return TransactionBuilderFactory.initializeBuilder(new FungibleTokenTransferBuilder(this._coinConfig), tx);
}
Expand Down
6 changes: 5 additions & 1 deletion modules/sdk-coin-stx/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,11 @@ export function isValidMemo(memo: string): boolean {
* @returns {boolean} - the validation result
*/
export function isValidContractAddress(addr: string, network: BitgoStacksNetwork): boolean {
return addr === network.stakingContractAddress || addr === network.sendmanymemoContractAddress;
return (
addr === network.stakingContractAddress ||
addr === network.sendmanymemoContractAddress ||
addr === network.sbtcWithdrawalContractAddress
);
}

/**
Expand Down
Loading
Loading