-
Notifications
You must be signed in to change notification settings - Fork 302
CSHLD-597: Add sBTC burn function to BitGo JS SDK #8641
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
abhi-bitgo
wants to merge
1
commit into
master
Choose a base branch
from
CSHLD-597-add-sbtc-withdraw-builder
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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') { | ||
| 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) | ||
| ), | ||
| ]; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?