|
| 1 | +import { BaseCoin as CoinConfig, NetworkType, StacksNetwork as BitgoStacksNetwork } from '@bitgo/statics'; |
| 2 | +import BigNum from 'bn.js'; |
| 3 | +import { |
| 4 | + AddressHashMode, |
| 5 | + addressToString, |
| 6 | + AddressVersion, |
| 7 | + bufferCV, |
| 8 | + ClarityType, |
| 9 | + createAssetInfo, |
| 10 | + FungibleConditionCode, |
| 11 | + makeStandardFungiblePostCondition, |
| 12 | + PostCondition, |
| 13 | + PostConditionMode, |
| 14 | + tupleCV, |
| 15 | + uintCV, |
| 16 | +} from '@stacks/transactions'; |
| 17 | +import { BuildTransactionError } from '@bitgo/sdk-core'; |
| 18 | +import { Transaction } from './transaction'; |
| 19 | +import { getSTXAddressFromPubKeys, isValidAmount } from './utils'; |
| 20 | +import { SbtcWithdrawParams } from './iface'; |
| 21 | +import { CONTRACT_NAME_SBTC_WITHDRAWAL, FUNCTION_NAME_INITIATE_WITHDRAWAL } from './constants'; |
| 22 | +import { ContractCallPayload } from '@stacks/transactions/dist/payload'; |
| 23 | +import { AbstractContractBuilder } from './abstractContractBuilder'; |
| 24 | +import { decodeBtcAddress, isValidBtcAddress } from './btcAddressUtils'; |
| 25 | + |
| 26 | +const SBTC_TOKEN_CONTRACT_NAME = 'sbtc-token'; |
| 27 | +const SBTC_TOKEN_ASSET_NAME = 'sbtc-token'; |
| 28 | +const HASHBYTES_BUFFER_LENGTH = 32; |
| 29 | + |
| 30 | +export class SbtcWithdrawBuilder extends AbstractContractBuilder { |
| 31 | + private _withdrawParams: SbtcWithdrawParams | undefined; |
| 32 | + private _isDeserialized = false; |
| 33 | + |
| 34 | + constructor(_coinConfig: Readonly<CoinConfig>) { |
| 35 | + super(_coinConfig); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Check whether a deserialized contract-call payload matches the sBTC withdrawal contract. |
| 40 | + */ |
| 41 | + public static isValidContractCall(coinConfig: Readonly<CoinConfig>, payload: ContractCallPayload): boolean { |
| 42 | + return ( |
| 43 | + (coinConfig.network as BitgoStacksNetwork).sbtcWithdrawalContractAddress === |
| 44 | + addressToString(payload.contractAddress) && |
| 45 | + CONTRACT_NAME_SBTC_WITHDRAWAL === payload.contractName.content && |
| 46 | + FUNCTION_NAME_INITIATE_WITHDRAWAL === payload.functionName.content |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Set withdrawal parameters. |
| 52 | + * |
| 53 | + * @param {SbtcWithdrawParams} params - amount (satoshis), btcAddress, maxFee |
| 54 | + * @returns {this} |
| 55 | + */ |
| 56 | + withdraw(params: SbtcWithdrawParams): this { |
| 57 | + if (!params.amount || !isValidAmount(params.amount) || params.amount === '0') { |
| 58 | + throw new BuildTransactionError('Invalid or missing amount, got: ' + params.amount); |
| 59 | + } |
| 60 | + if (!params.btcAddress || !isValidBtcAddress(params.btcAddress)) { |
| 61 | + throw new BuildTransactionError('Invalid or missing btcAddress, got: ' + params.btcAddress); |
| 62 | + } |
| 63 | + if (!params.maxFee || !isValidAmount(params.maxFee) || params.maxFee === '0') { |
| 64 | + throw new BuildTransactionError('Invalid or missing maxFee, got: ' + params.maxFee); |
| 65 | + } |
| 66 | + this._withdrawParams = params; |
| 67 | + return this; |
| 68 | + } |
| 69 | + |
| 70 | + initBuilder(tx: Transaction): void { |
| 71 | + super.initBuilder(tx); |
| 72 | + const payload = tx.stxTransaction.payload as ContractCallPayload; |
| 73 | + const args = payload.functionArgs; |
| 74 | + |
| 75 | + if (args.length !== 3) { |
| 76 | + throw new BuildTransactionError('Invalid number of function args for sBTC withdrawal'); |
| 77 | + } |
| 78 | + |
| 79 | + // args[0] = uint (amount) |
| 80 | + if (args[0].type !== ClarityType.UInt) { |
| 81 | + throw new BuildTransactionError('Expected uint for amount argument'); |
| 82 | + } |
| 83 | + const amount = args[0].value.toString(); |
| 84 | + |
| 85 | + // args[1] = tuple { version: (buff 1), hashbytes: (buff 32) } |
| 86 | + if (args[1].type !== ClarityType.Tuple) { |
| 87 | + throw new BuildTransactionError('Expected tuple for recipient argument'); |
| 88 | + } |
| 89 | + const versionBuf = args[1].data['version']; |
| 90 | + const hashbytesBuf = args[1].data['hashbytes']; |
| 91 | + if (versionBuf?.type !== ClarityType.Buffer || hashbytesBuf?.type !== ClarityType.Buffer) { |
| 92 | + throw new BuildTransactionError('Expected buffer fields in recipient tuple'); |
| 93 | + } |
| 94 | + |
| 95 | + // args[2] = uint (max-fee) |
| 96 | + if (args[2].type !== ClarityType.UInt) { |
| 97 | + throw new BuildTransactionError('Expected uint for max-fee argument'); |
| 98 | + } |
| 99 | + const maxFee = args[2].value.toString(); |
| 100 | + |
| 101 | + this._withdrawParams = { |
| 102 | + amount, |
| 103 | + btcAddress: '', // not needed for rebuild; function args are preserved from the original tx |
| 104 | + maxFee, |
| 105 | + }; |
| 106 | + this._isDeserialized = true; |
| 107 | + } |
| 108 | + |
| 109 | + /** @inheritdoc */ |
| 110 | + protected async buildImplementation(): Promise<Transaction> { |
| 111 | + if (!this._withdrawParams) { |
| 112 | + throw new BuildTransactionError('Withdrawal params are not set. Use withdraw() to set them.'); |
| 113 | + } |
| 114 | + |
| 115 | + const network = this._coinConfig.network as BitgoStacksNetwork; |
| 116 | + this._contractAddress = network.sbtcWithdrawalContractAddress; |
| 117 | + this._contractName = CONTRACT_NAME_SBTC_WITHDRAWAL; |
| 118 | + this._functionName = FUNCTION_NAME_INITIATE_WITHDRAWAL; |
| 119 | + |
| 120 | + // For deserialized transactions, function args are already preserved from the original tx. |
| 121 | + // For fresh builds, construct them from the withdraw params. |
| 122 | + if (!this._isDeserialized) { |
| 123 | + this._functionArgs = this.withdrawParamsToFunctionArgs(this._withdrawParams); |
| 124 | + } |
| 125 | + |
| 126 | + this._postConditionMode = PostConditionMode.Deny; |
| 127 | + this._postConditions = this.withdrawParamsToPostCondition(this._withdrawParams); |
| 128 | + return await super.buildImplementation(); |
| 129 | + } |
| 130 | + |
| 131 | + private withdrawParamsToFunctionArgs(params: SbtcWithdrawParams) { |
| 132 | + const decoded = decodeBtcAddress(params.btcAddress); |
| 133 | + |
| 134 | + // Pad 20-byte hashes to 32 bytes with trailing zeros per sBTC contract spec (buff 32) |
| 135 | + let hashBytes = decoded.hashBytes; |
| 136 | + if (hashBytes.length < HASHBYTES_BUFFER_LENGTH) { |
| 137 | + const padded = Buffer.alloc(HASHBYTES_BUFFER_LENGTH, 0); |
| 138 | + hashBytes.copy(padded); |
| 139 | + hashBytes = padded; |
| 140 | + } |
| 141 | + |
| 142 | + return [ |
| 143 | + uintCV(params.amount), |
| 144 | + tupleCV({ |
| 145 | + version: bufferCV(Buffer.from([decoded.version])), |
| 146 | + hashbytes: bufferCV(hashBytes), |
| 147 | + }), |
| 148 | + uintCV(params.maxFee), |
| 149 | + ]; |
| 150 | + } |
| 151 | + |
| 152 | + private withdrawParamsToPostCondition(params: SbtcWithdrawParams): PostCondition[] { |
| 153 | + const amount = new BigNum(params.amount).add(new BigNum(params.maxFee)); |
| 154 | + const network = this._coinConfig.network as BitgoStacksNetwork; |
| 155 | + const sbtcContractAddress = network.sbtcWithdrawalContractAddress; |
| 156 | + |
| 157 | + return [ |
| 158 | + makeStandardFungiblePostCondition( |
| 159 | + getSTXAddressFromPubKeys( |
| 160 | + this._fromPubKeys, |
| 161 | + this._coinConfig.network.type === NetworkType.MAINNET |
| 162 | + ? AddressVersion.MainnetMultiSig |
| 163 | + : AddressVersion.TestnetMultiSig, |
| 164 | + this._fromPubKeys.length > 1 ? AddressHashMode.SerializeP2SH : AddressHashMode.SerializeP2PKH, |
| 165 | + this._numberSignatures |
| 166 | + ).address, |
| 167 | + FungibleConditionCode.Equal, |
| 168 | + amount, |
| 169 | + createAssetInfo(sbtcContractAddress, SBTC_TOKEN_CONTRACT_NAME, SBTC_TOKEN_ASSET_NAME) |
| 170 | + ), |
| 171 | + ]; |
| 172 | + } |
| 173 | +} |
0 commit comments