@babylonlabs-io/ts-sdk 0.19.0 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -12
- package/dist/bitcoin-CNnPFU6Y.cjs +2 -0
- package/dist/bitcoin-CNnPFU6Y.cjs.map +1 -0
- package/dist/{constants-Q7v2O7Ps.js → bitcoin-nOOgeRyl.js} +64 -76
- package/dist/bitcoin-nOOgeRyl.js.map +1 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs +2 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js +1331 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js.map +1 -0
- package/dist/challengeAssert-D1lpvuMv.js +283 -0
- package/dist/challengeAssert-D1lpvuMv.js.map +1 -0
- package/dist/challengeAssert-nYlgeAI8.cjs +2 -0
- package/dist/challengeAssert-nYlgeAI8.cjs.map +1 -0
- package/dist/errors-D9EtjJoD.cjs +2 -0
- package/dist/errors-D9EtjJoD.cjs.map +1 -0
- package/dist/{errors-aMocmFr-.js → errors-D_PI__IT.js} +98 -97
- package/dist/errors-D_PI__IT.js.map +1 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js +70 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js.map +1 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs +2 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs.map +1 -0
- package/dist/index-BpXpESWu.cjs +2 -0
- package/dist/index-BpXpESWu.cjs.map +1 -0
- package/dist/{index-BvFLf3vm.js → index-CFwoGJNQ.js} +146 -518
- package/dist/index-CFwoGJNQ.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +133 -109
- package/dist/payout-DzGsAnhf.js +261 -0
- package/dist/payout-DzGsAnhf.js.map +1 -0
- package/dist/payout-RFIh7GLN.cjs +2 -0
- package/dist/payout-RFIh7GLN.cjs.map +1 -0
- package/dist/psbtInputFields-05ZrwRzf.cjs +2 -0
- package/dist/psbtInputFields-05ZrwRzf.cjs.map +1 -0
- package/dist/psbtInputFields-r1ss6WLU.js +237 -0
- package/dist/psbtInputFields-r1ss6WLU.js.map +1 -0
- package/dist/signing-DeWVBl7m.js +64 -0
- package/dist/signing-DeWVBl7m.js.map +1 -0
- package/dist/signing-cl-lowxV.cjs +2 -0
- package/dist/signing-cl-lowxV.cjs.map +1 -0
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +2 -2
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +3 -1
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +130 -106
- package/dist/tbv/core/managers/PeginManager.d.ts +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +3 -2
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +24 -23
- package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/index.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +2 -3
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +4 -0
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -1
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts +2 -0
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts +77 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/index.d.ts +7 -0
- package/dist/tbv/core/services/activation/index.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts +5 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +4 -0
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/peginState.d.ts +93 -0
- package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/validation.d.ts +114 -0
- package/dist/tbv/core/services/deposit/validation.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.d.ts +3 -0
- package/dist/tbv/core/services/index.d.ts.map +1 -1
- package/dist/tbv/core/services/index.js +25 -7
- package/dist/tbv/core/services/index.js.map +1 -1
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts +2 -0
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/index.d.ts +2 -0
- package/dist/tbv/core/services/pegout/index.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/state.d.ts +30 -0
- package/dist/tbv/core/services/pegout/state.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts +2 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +103 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/errors.d.ts +13 -0
- package/dist/tbv/core/services/refund/errors.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/index.d.ts +8 -0
- package/dist/tbv/core/services/refund/index.d.ts.map +1 -0
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +30 -24
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts +1 -1
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts +62 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/index.d.ts +2 -0
- package/dist/tbv/core/utils/utxo/index.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts +91 -0
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +130 -106
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +3 -3
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +145 -169
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +0 -30
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/index.d.ts +2 -2
- package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
- package/dist/types-B-p4dhEH.cjs +2 -0
- package/dist/types-B-p4dhEH.cjs.map +1 -0
- package/dist/types-DWjaqVfP.js +608 -0
- package/dist/types-DWjaqVfP.js.map +1 -0
- package/package.json +5 -1
- package/dist/challengeAssert-D_k_ADgP.cjs +0 -2
- package/dist/challengeAssert-D_k_ADgP.cjs.map +0 -1
- package/dist/challengeAssert-k5_LWUtO.js +0 -362
- package/dist/challengeAssert-k5_LWUtO.js.map +0 -1
- package/dist/constants-EiyZkXce.cjs +0 -2
- package/dist/constants-EiyZkXce.cjs.map +0 -1
- package/dist/constants-Q7v2O7Ps.js.map +0 -1
- package/dist/errors-DVNYib5y.cjs +0 -2
- package/dist/errors-DVNYib5y.cjs.map +0 -1
- package/dist/errors-aMocmFr-.js.map +0 -1
- package/dist/fundPeginTransaction-DpwnDslW.js +0 -50
- package/dist/fundPeginTransaction-DpwnDslW.js.map +0 -1
- package/dist/fundPeginTransaction-EbrZzlrh.cjs +0 -2
- package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +0 -1
- package/dist/index-BX-V3C9t.js +0 -995
- package/dist/index-BX-V3C9t.js.map +0 -1
- package/dist/index-BgnxXV5G.cjs +0 -2
- package/dist/index-BgnxXV5G.cjs.map +0 -1
- package/dist/index-BvFLf3vm.js.map +0 -1
- package/dist/index-DpKhuCta.cjs +0 -2
- package/dist/index-DpKhuCta.cjs.map +0 -1
- package/dist/payout-Ce9vSs9e.js +0 -164
- package/dist/payout-Ce9vSs9e.js.map +0 -1
- package/dist/payout-CfsDnjKI.cjs +0 -2
- package/dist/payout-CfsDnjKI.cjs.map +0 -1
- package/dist/psbtInputFields-C0nKn_GD.cjs +0 -2
- package/dist/psbtInputFields-C0nKn_GD.cjs.map +0 -1
- package/dist/psbtInputFields-DO0ELwiv.js +0 -116
- package/dist/psbtInputFields-DO0ELwiv.js.map +0 -1
- package/dist/signing-Deg5lCoC.cjs +0 -2
- package/dist/signing-Deg5lCoC.cjs.map +0 -1
- package/dist/signing-Drwr3bXB.js +0 -16
- package/dist/signing-Drwr3bXB.js.map +0 -1
- package/dist/types-D1rYwwCu.js +0 -235
- package/dist/types-D1rYwwCu.js.map +0 -1
- package/dist/types-DEWiqXYp.cjs +0 -2
- package/dist/types-DEWiqXYp.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-DWjaqVfP.js","sources":["../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/clients/vault-provider/types.ts"],"sourcesContent":["/**\n * BTCVaultRegistry Contract ABI\n *\n * Minimal ABI containing only the functions needed by the SDK.\n * Full ABI is available in the vault service package.\n *\n * @module contracts/abis/BTCVaultRegistry\n */\n\n/**\n * Minimal ABI for BTCVaultRegistry contract.\n * Contains submitPeginRequest, submitPeginRequestBatch, activateVaultWithSecret, getPegInFee, and getBtcVaultBasicInfo.\n */\nexport const BTCVaultRegistryABI = [\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"referralCode\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequestBatch\",\n inputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n {\n name: \"requests\",\n type: \"tuple[]\",\n internalType: \"struct IBTCVaultRegistry.BatchPeginRequest[]\",\n components: [\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"btcPopSignature\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"unsignedPrePeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorSignedPeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"hashlock\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"htlcVout\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"referralCode\", type: \"uint32\", internalType: \"uint32\" },\n { name: \"depositorPayoutBtcAddress\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorWotsPkHash\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n ],\n outputs: [\n { name: \"vaultIds\", type: \"bytes32[]\", internalType: \"bytes32[]\" },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"activateVaultWithSecret\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"s\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"activationMetadata\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getPegInFee\",\n inputs: [\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"totalFee\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getBtcVaultBasicInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n { name: \"status\", type: \"uint8\", internalType: \"enum IBTCVaultRegistry.BTCVaultStatus\" },\n { name: \"applicationEntryPoint\", type: \"address\", internalType: \"address\" },\n { name: \"createdAt\", type: \"uint256\", internalType: \"uint256\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"error\",\n name: \"InvalidPeginFee\",\n inputs: [\n {\n name: \"provided\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"required\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n },\n {\n type: \"error\",\n name: \"InvalidSecret\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"ActivationDeadlineExpired\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"DuplicateHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"CapExceeded\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidOutputIndex\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"PeginSignaturesIncomplete\",\n inputs: [],\n },\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"protocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IProtocolParams\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"applicationRegistry\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IApplicationRegistry\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\n * Generic JSON-RPC 2.0 HTTP Client\n *\n * Framework-agnostic client using `fetch()` — works in browsers and Node.js 18+.\n * Includes configurable retry policy and AbortSignal passthrough.\n */\n\nexport interface JsonRpcRequest<T = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params: T;\n id: number | string;\n}\n\nexport interface JsonRpcSuccessResponse<T = unknown> {\n jsonrpc: \"2.0\";\n result: T;\n id: number | string;\n}\n\nexport interface JsonRpcErrorResponse {\n jsonrpc: \"2.0\";\n error: {\n code: number;\n message: string;\n data?: unknown;\n };\n id: number | string;\n}\n\nexport type JsonRpcResponse<T = unknown> =\n | JsonRpcSuccessResponse<T>\n | JsonRpcErrorResponse;\n\nexport interface JsonRpcClientConfig {\n /** Base URL of the RPC service */\n baseUrl: string;\n /** Timeout in milliseconds per request attempt */\n timeout: number;\n /** Optional custom headers */\n headers?: Record<string, string>;\n /** Number of retry attempts for transient errors (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Predicate to determine if a method is safe to retry.\n * Default: only retry `vaultProvider_getPeginStatus` and `vaultProvider_getPegoutStatus`.\n * Write/mutating methods are NOT retried by default.\n */\n retryableFor?: (method: string) => boolean;\n}\n\nexport class JsonRpcError extends Error {\n constructor(\n public code: number,\n message: string,\n ) {\n super(message);\n this.name = \"JsonRpcError\";\n }\n}\n\nexport const JSON_RPC_ERROR_CODES = {\n TIMEOUT: -32000,\n NETWORK: -32001,\n /** VP proxy: request timed out at proxy level */\n PROXY_TIMEOUT: -32002,\n /** VP proxy: VP unreachable / DNS failure / response too large */\n PROXY_UNAVAILABLE: -32003,\n /** SDK client: response missing \"result\" field (malformed JSON-RPC) */\n INVALID_RESPONSE: -32700,\n} as const;\n\n/** JSON-RPC protocol version */\nconst JSON_RPC_VERSION = \"2.0\" as const;\n\n/** Default number of retry attempts for transient errors */\nconst DEFAULT_RETRY_ATTEMPTS = 3;\n\n/** Default initial retry delay in milliseconds */\nconst DEFAULT_RETRY_DELAY_MS = 1000;\n\n/** HTTP status codes that indicate transient server errors and are safe to retry */\nconst RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/** Default retry predicate: only retry read-only / idempotent methods */\nconst DEFAULT_RETRYABLE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_getPeginStatus\",\n \"vaultProvider_getPegoutStatus\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nfunction defaultRetryableFor(method: string): boolean {\n return DEFAULT_RETRYABLE_METHODS.has(method);\n}\n\n/**\n * Generic JSON-RPC 2.0 HTTP client with safe retry policy.\n */\nexport class JsonRpcClient {\n private baseUrl: string;\n private timeout: number;\n private headers: Record<string, string>;\n private requestId = 0;\n private retries: number;\n private retryDelay: number;\n private retryableFor: (method: string) => boolean;\n\n constructor(config: JsonRpcClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\n this.timeout = config.timeout;\n this.headers = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n this.retries = config.retries ?? DEFAULT_RETRY_ATTEMPTS;\n this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;\n this.retryableFor = config.retryableFor ?? defaultRetryableFor;\n }\n\n /**\n * Make a JSON-RPC request with optional retry for safe methods.\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @param signal - Optional AbortSignal for caller-controlled cancellation\n * @returns The result from the RPC method\n * @throws JsonRpcError if the RPC call fails\n */\n async call<TParams, TResult>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<TResult> {\n const response = await this.fetchWithRetry(method, params, signal);\n\n let jsonResponse: unknown;\n try {\n jsonResponse = await response.json();\n } catch {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n \"Invalid JSON-RPC response: body is not valid JSON\",\n );\n }\n\n if (\n jsonResponse === null ||\n typeof jsonResponse !== \"object\" ||\n Array.isArray(jsonResponse)\n ) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: expected an object, got ${typeof jsonResponse}`,\n );\n }\n\n const rpcResponse = jsonResponse as Record<string, unknown>;\n\n if (\"error\" in rpcResponse && rpcResponse.error != null) {\n const err = rpcResponse.error as { code?: number; message?: string };\n throw new JsonRpcError(\n err.code ?? JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n err.message ?? \"Unknown RPC error\",\n );\n }\n\n if (!(\"result\" in rpcResponse)) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: missing \"result\" field`,\n );\n }\n\n return rpcResponse.result as TResult;\n }\n\n /**\n * Make a JSON-RPC request returning the raw Response (unparsed body).\n */\n async callRaw<TParams>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<Response> {\n return this.fetchWithRetry(method, params, signal);\n }\n\n private async fetchWithRetry<TParams>(\n method: string,\n params: TParams,\n callerSignal?: AbortSignal,\n ): Promise<Response> {\n const requestId = ++this.requestId;\n const maxRetries = this.retryableFor(method) ? this.retries : 0;\n\n // jsonrpsee (Rust backend) expects params as an array (positional parameters)\n const request: JsonRpcRequest<TParams[]> = {\n jsonrpc: JSON_RPC_VERSION,\n method,\n params: [params],\n id: requestId,\n };\n\n const body = JSON.stringify(request);\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n // Merge caller signal with per-request timeout signal\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(\n () => timeoutController.abort(),\n this.timeout,\n );\n\n const merged = callerSignal\n ? mergeAbortSignals(callerSignal, timeoutController.signal)\n : null;\n const signal = merged ? merged.signal : timeoutController.signal;\n\n try {\n const response = await fetch(this.baseUrl, {\n method: \"POST\",\n headers: this.headers,\n body,\n signal,\n });\n\n clearTimeout(timeoutId);\n merged?.cleanup();\n\n if (!response.ok) {\n const shouldRetry =\n attempt < maxRetries &&\n RETRYABLE_HTTP_STATUS_CODES.has(response.status);\n\n if (shouldRetry) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n\n throw new Error(\n `HTTP error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n merged?.cleanup();\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if caller aborted (not our timeout)\n if (callerSignal?.aborted) {\n throw new Error(\"Request aborted\");\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.TIMEOUT,\n `Request timeout after ${this.timeout}ms (${maxRetries + 1} attempts)`,\n );\n }\n\n // Handle network errors (CORS, connection refused, etc.)\n if (error instanceof TypeError) {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.NETWORK,\n `Network error: ${error.message} (${maxRetries + 1} attempts)`,\n );\n }\n\n // Don't retry JSON-RPC errors (business logic errors)\n throw error;\n }\n }\n\n throw lastError || new Error(\"Unknown error after retries\");\n }\n\n private sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"Request aborted\"));\n return;\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(new Error(\"Request aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n}\n\ninterface MergedSignal {\n signal: AbortSignal;\n /** Remove listeners from the source signals. Call after the request completes. */\n cleanup: () => void;\n}\n\n/**\n * Merge two AbortSignals — the returned signal aborts if either input aborts.\n * Returns a cleanup function to remove listeners when the request completes\n * normally, preventing listener accumulation in long-lived polling flows.\n */\nfunction mergeAbortSignals(\n a: AbortSignal,\n b: AbortSignal,\n): MergedSignal {\n if (a.aborted) return { signal: a, cleanup: () => {} };\n if (b.aborted) return { signal: b, cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbortA = () => {\n b.removeEventListener(\"abort\", onAbortB);\n controller.abort();\n };\n const onAbortB = () => {\n a.removeEventListener(\"abort\", onAbortA);\n controller.abort();\n };\n a.addEventListener(\"abort\", onAbortA, { once: true });\n b.addEventListener(\"abort\", onAbortB, { once: true });\n\n const cleanup = () => {\n a.removeEventListener(\"abort\", onAbortA);\n b.removeEventListener(\"abort\", onAbortB);\n };\n\n return { signal: controller.signal, cleanup };\n}\n","/**\n * Type definitions for Vault Provider JSON-RPC API.\n *\n * These types match the `vaultProvider_*` RPC namespace defined by the\n * btc-vault daemon. They are the SDK's canonical copy of the VP protocol\n * contract, independent of any frontend framework.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\n// ============================================================================\n// Daemon Status\n// ============================================================================\n\n/**\n * Backend daemon status (vault provider database).\n * Source: btc-vault crates/vaultd/src/workers/claimer/mod.rs PegInStatus enum\n *\n * State flow (happy path):\n * PendingIngestion -> PendingDepositorWotsPK -> PendingBabeSetup -> PendingChallengerPresigning\n * -> PendingPeginSigsAvailability -> PendingPrePegInConfirmations\n * -> PendingDepositorSignatures -> PendingACKs -> PendingActivation -> Activated\n *\n * Terminal / branching states:\n * - Expired: vault timed out before activation\n * - ClaimPosted: claim transaction posted on-chain\n * - PeggedOut: BTC has been returned to the depositor\n */\nexport enum DaemonStatus {\n PENDING_INGESTION = \"PendingIngestion\",\n PENDING_DEPOSITOR_WOTS_PK = \"PendingDepositorWotsPK\",\n PENDING_BABE_SETUP = \"PendingBabeSetup\",\n PENDING_CHALLENGER_PRESIGNING = \"PendingChallengerPresigning\",\n PENDING_PEGIN_SIGS_AVAILABILITY = \"PendingPeginSigsAvailability\",\n PENDING_PRE_PEGIN_CONFIRMATIONS = \"PendingPrePegInConfirmations\",\n PENDING_DEPOSITOR_SIGNATURES = \"PendingDepositorSignatures\",\n PENDING_ACKS = \"PendingACKs\",\n PENDING_ACTIVATION = \"PendingActivation\",\n ACTIVATED = \"Activated\",\n EXPIRED = \"Expired\",\n CLAIM_POSTED = \"ClaimPosted\",\n PEGGED_OUT = \"PeggedOut\",\n}\n\n// ============================================================================\n// Status Groups\n// ============================================================================\n\n/**\n * States where the VP is still processing (no depositor action needed).\n * Excludes PENDING_DEPOSITOR_WOTS_PK (requires depositor action).\n */\nexport const PRE_DEPOSITOR_SIGNATURES_STATES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_INGESTION,\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n];\n\n/** States after PendingDepositorSignatures where the depositor has no action. */\nconst POST_PAYOUT_SIGNATURE_STATUSES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_ACKS,\n DaemonStatus.PENDING_ACTIVATION,\n DaemonStatus.ACTIVATED,\n];\n\n/**\n * Statuses where no depositor action is needed (VP processing or already past\n * depositor interaction). Excludes PENDING_INGESTION and PENDING_DEPOSITOR_WOTS_PK.\n */\nexport const VP_TRANSIENT_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n ...POST_PAYOUT_SIGNATURE_STATUSES,\n]);\n\n/**\n * Terminal VP statuses where no further progress is possible.\n * If the VP reaches one of these states while polling, polling should\n * stop immediately with an error rather than waiting for timeout.\n */\nexport const VP_TERMINAL_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.EXPIRED,\n DaemonStatus.CLAIM_POSTED,\n DaemonStatus.PEGGED_OUT,\n]);\n\n/**\n * Statuses that come after WOTS key submission.\n * If the VP is already in one of these states, the WOTS key was already\n * submitted and we can skip.\n */\nexport const POST_WOTS_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n ...VP_TRANSIENT_STATUSES,\n DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,\n]);\n\n// ============================================================================\n// WOTS Types (needed by SubmitDepositorWotsKeyParams)\n// ============================================================================\n\n/**\n * WOTS configuration for a single block.\n * Matches Rust `babe::wots::Config` serde format.\n */\nexport interface WotsConfig {\n /** Digit bit-width (e.g. 4 → base-16 digits). */\n d: number;\n /** Number of message digits in this block. */\n n: number;\n /** Radix used for the checksum computation. */\n checksum_radix: number;\n}\n\n/**\n * A single block of WOTS public keys.\n * Chain values are arrays of byte values (matching Rust `[u8; 20]`).\n */\nexport interface WotsBlockPublicKey {\n config: WotsConfig;\n message_terminals: number[][];\n checksum_major_terminal: number[];\n checksum_minor_terminal: number[];\n}\n\n// ============================================================================\n// Request Parameter Types\n// ============================================================================\n\n/** Params for requesting the payout/claim/assert transactions to pre-sign. */\nexport interface RequestDepositorPresignTransactionsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for submitting the depositor's WOTS public key to the VP. */\nexport interface SubmitDepositorWotsKeyParams {\n pegin_txid: string;\n depositor_pk: string;\n wots_public_keys: WotsBlockPublicKey[];\n}\n\n/** Per-challenger signatures for the depositor-as-claimer flow. */\nexport interface DepositorPreSigsPerChallenger {\n nopayout_signature: string;\n}\n\n/** Depositor-as-claimer pre-signatures (payout + per-challenger). */\nexport interface DepositorAsClaimerPresignatures {\n payout_signatures: ClaimerSignatures;\n per_challenger: Record<string, DepositorPreSigsPerChallenger>;\n}\n\n/** Params for submitting depositor pre-signatures including claimer presignatures. */\nexport interface SubmitDepositorPresignaturesParams {\n pegin_txid: string;\n depositor_pk: string;\n signatures: Record<string, ClaimerSignatures>;\n depositor_claimer_presignatures: DepositorAsClaimerPresignatures;\n}\n\n/** Payout signatures per claimer. */\nexport interface ClaimerSignatures {\n payout_signature: string;\n}\n\n/** Params for requesting BaBe DecryptorArtifacts from the VP. */\nexport interface RequestDepositorClaimerArtifactsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for querying pegin status. Either pegin_txid or vault_id must be provided. */\nexport type GetPeginStatusParams =\n | { pegin_txid: string; vault_id?: never }\n | { vault_id: string; pegin_txid?: never };\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/** A raw Bitcoin transaction with its hex encoding. */\nexport interface TransactionData {\n tx_hex: string;\n}\n\n/** Set of transactions the depositor must pre-sign for a single claimer. */\nexport interface ClaimerTransactions {\n claimer_pubkey: string;\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n}\n\n/** Per-segment connector data for ChallengeAssert inputs. */\nexport interface ChallengeAssertConnectorData {\n wots_pks_json: string;\n gc_wots_keys_json: string;\n}\n\n/** Challenger-specific transactions and signing data for the depositor graph. */\nexport interface PresignDataPerChallenger {\n challenger_pubkey: string;\n challenge_assert_x_tx: TransactionData;\n challenge_assert_y_tx: TransactionData;\n nopayout_tx: TransactionData;\n nopayout_psbt: string;\n challenge_assert_connectors: ChallengeAssertConnectorData[];\n output_label_hashes: string[];\n}\n\n/** Depositor-as-claimer TxGraph transactions. */\nexport interface DepositorGraphTransactions {\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n challenger_presign_data: PresignDataPerChallenger[];\n offchain_params_version: number;\n}\n\n/** Response from `requestDepositorPresignTransactions`. */\nexport interface RequestDepositorPresignTransactionsResponse {\n txs: ClaimerTransactions[];\n depositor_graph: DepositorGraphTransactions;\n}\n\n/** BaBe garbled-circuit session data for a single challenger. */\nexport interface BaBeSessionData {\n decryptor_artifacts_hex: string;\n}\n\n/** Response from `requestDepositorClaimerArtifacts`. */\nexport interface RequestDepositorClaimerArtifactsResponse {\n tx_graph_json: string;\n verifying_key_hex: string;\n babe_sessions: Record<string, BaBeSessionData>;\n}\n\n/** Progress tracker for a multi-challenger operation. */\nexport interface ChallengerProgress {\n total_challengers: number;\n completed_challengers: number;\n completed_challenger_pubkeys: string[];\n pending_challenger_pubkeys: string[];\n}\n\nexport type GcDataProgress = ChallengerProgress;\nexport type AckCollectionProgress = ChallengerProgress;\n\n/** Extended presigning progress with all 3 concurrent phases. */\nexport interface PresigningProgress extends ChallengerProgress {\n depositor_graph_created?: boolean;\n vk_challenger_presigning_completed?: number;\n vk_challenger_presigning_total?: number;\n}\n\n/** Detailed progress breakdown for an in-progress pegin. */\nexport interface PeginProgressDetails {\n gc_data?: GcDataProgress;\n presigning?: PresigningProgress;\n ack_collection?: AckCollectionProgress;\n claimer_graphs?: ClaimerGraphStatus[];\n}\n\n/** Per-claimer graph status (challenger perspective). */\nexport interface ClaimerGraphStatus {\n claimer_pubkey: string;\n presigned: boolean;\n}\n\n/** Response from `getPeginStatus`. */\nexport interface GetPeginStatusResponse {\n pegin_txid: string;\n status: string;\n progress: PeginProgressDetails;\n health_info: string;\n last_error?: string;\n}\n\n// ============================================================================\n// Pegout Types\n// ============================================================================\n\n/** Params for querying pegout status from the VP daemon. */\nexport interface GetPegoutStatusParams {\n pegin_txid: string;\n}\n\n/** Claimer-side pegout progress. */\nexport interface ClaimerPegoutStatus {\n status: string;\n failed: boolean;\n claim_txid?: string;\n claimer_pubkey?: string;\n challenger_pubkey?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Challenger-side pegout progress. */\nexport interface ChallengerPegoutStatus {\n status: string;\n claim_txid?: string;\n claimer_pubkey?: string;\n assert_txid?: string;\n challenge_assert_txid?: string;\n nopayout_txid?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Response from `getPegoutStatus`. */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n found: boolean;\n claimer?: ClaimerPegoutStatus;\n challenger?: ChallengerPegoutStatus;\n}\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/** JSON-RPC error codes returned by the vault provider. */\nexport enum RpcErrorCode {\n DATABASE_ERROR = -32005,\n PRESIGN_ERROR = -32006,\n JSON_SERIALIZATION_ERROR = -32007,\n TX_GRAPH_ERROR = -32008,\n INVALID_GRAPH = -32009,\n VALIDATION_ERROR = -32010,\n NOT_FOUND = -32011,\n INTERNAL_ERROR = -32603,\n}\n"],"names":["BTCVaultRegistryABI","JsonRpcError","code","message","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","JsonRpcClient","config","__publicField","params","signal","response","jsonResponse","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","error","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_STATUSES","POST_WOTS_STATUSES","RpcErrorCode"],"mappings":";;;AAaO,MAAMA,IAAsB;AAAA,EACjC;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,QAAQ;AAAA,MACN;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAA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|
|
3
|
+
"version": "0.20.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=20.3.0"
|
|
10
|
+
},
|
|
7
11
|
"exports": {
|
|
8
12
|
".": {
|
|
9
13
|
"types": "./dist/index.d.ts",
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const r=require("./constants-EiyZkXce.cjs"),p=require("@babylonlabs-io/babylon-tbv-rust-wasm"),I=require("./fundPeginTransaction-EbrZzlrh.cjs"),a=require("buffer"),d=require("bitcoinjs-lib");function k(e){return r.processPublicKeyToXOnly(e).toLowerCase()}function m(e,t,n){const o=new Set;o.add(k(e));for(const i of t)o.add(k(i));return o.delete(k(n)),o.size}async function S(e){const t=await p.createPrePeginTransaction({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlocks:[...e.hashlocks],timelockRefund:e.timelockRefund,pegInAmounts:[...e.pegInAmounts],feeRate:e.feeRate,numLocalChallengers:e.numLocalChallengers,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:e.network}),o=I.parseUnfundedWasmTransaction(t.txHex).outputs.reduce((i,s)=>i+BigInt(s.value),0n);return{psbtHex:t.txHex,totalOutputValue:o,htlcValues:t.htlcValues,htlcScriptPubKeys:t.htlcScriptPubKeys,htlcAddresses:t.htlcAddresses,peginAmounts:t.peginAmounts,depositorClaimValue:t.depositorClaimValue}}async function H(e){const t=await p.buildPeginTxFromPrePegin({depositorPubkey:e.prePeginParams.depositorPubkey,vaultProviderPubkey:e.prePeginParams.vaultProviderPubkey,vaultKeeperPubkeys:e.prePeginParams.vaultKeeperPubkeys,universalChallengerPubkeys:e.prePeginParams.universalChallengerPubkeys,hashlocks:[...e.prePeginParams.hashlocks],timelockRefund:e.prePeginParams.timelockRefund,pegInAmounts:[...e.prePeginParams.pegInAmounts],feeRate:e.prePeginParams.feeRate,numLocalChallengers:e.prePeginParams.numLocalChallengers,councilQuorum:e.prePeginParams.councilQuorum,councilSize:e.prePeginParams.councilSize,network:e.prePeginParams.network},e.timelockPegin,e.fundedPrePeginTxHex,e.htlcVout);return{txHex:t.txHex,txid:t.txid,vaultScriptPubKey:t.vaultScriptPubKey,vaultValue:t.vaultValue}}async function A(e){const t=r.stripHexPrefix(e.peginTxHex),n=r.stripHexPrefix(e.fundedPrePeginTxHex),o=await p.getPrePeginHtlcConnectorInfo({depositorPubkey:e.depositorPubkey,vaultProviderPubkey:e.vaultProviderPubkey,vaultKeeperPubkeys:e.vaultKeeperPubkeys,universalChallengerPubkeys:e.universalChallengerPubkeys,hashlock:e.hashlock,timelockRefund:e.timelockRefund,network:e.network}),i=d.Transaction.fromHex(t),s=d.Transaction.fromHex(n);if(i.ins.length!==1)throw new Error(`PegIn transaction must have exactly 1 input, got ${i.ins.length}`);const l=i.ins[0],c=s.getId(),u=r.uint8ArrayToHex(new Uint8Array(l.hash).slice().reverse());if(u!==c)throw new Error(`PegIn input does not reference the Pre-PegIn transaction. Expected ${c}, got ${u}`);const P=s.outs[l.index];if(!P)throw new Error(`Pre-PegIn output ${l.index} not found (Pre-PegIn has ${s.outs.length} outputs)`);const h=r.hexToUint8Array(o.hashlockScript),f=r.hexToUint8Array(o.hashlockControlBlock),x=new d.Psbt;x.setVersion(i.version),x.setLocktime(i.locktime),x.addInput({hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:P.script,value:P.value},tapLeafScript:[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(h),controlBlock:a.Buffer.from(f)}],tapInternalKey:a.Buffer.from(p.tapInternalPubkey)});for(const g of i.outs)x.addOutput({script:g.script,value:g.value});return{psbtHex:x.toHex()}}function B(e,t){const o=d.Psbt.fromHex(e).data.inputs[0];if(!o)throw new Error("PegIn PSBT has no inputs");if(o.tapScriptSig&&o.tapScriptSig.length>0){const i=a.Buffer.from(r.hexToUint8Array(t));for(const s of o.tapScriptSig)if(s.pubkey.equals(i))return E(s.signature);throw new Error(`No PegIn input signature found for depositor pubkey: ${t}`)}throw o.finalScriptWitness&&o.finalScriptWitness.length>0?new Error("PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."):new Error("No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT")}function C(e){const t=d.Psbt.fromHex(e);try{t.finalizeAllInputs()}catch(n){if(!t.data.inputs.every(i=>i.finalScriptWitness||i.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${n}`)}return t.extractTransaction().toHex()}function E(e){if(e.length===64)return r.uint8ArrayToHex(new Uint8Array(e));if(e.length===65)return r.uint8ArrayToHex(new Uint8Array(e.subarray(0,64)));throw new Error(`Unexpected PegIn input signature length: ${e.length}`)}async function R(e){await p.initWasm();const{prePeginParams:t,fundedPrePeginTxHex:n,htlcVout:o,refundFee:i,hashlock:s}=e,l=new p.WasmPrePeginTx(t.depositorPubkey,t.vaultProviderPubkey,t.vaultKeeperPubkeys,t.universalChallengerPubkeys,[...t.hashlocks],new BigUint64Array(t.pegInAmounts),t.timelockRefund,t.feeRate,t.numLocalChallengers,t.councilQuorum,t.councilSize,t.network);let c=null;try{c=l.fromFundedTransaction(n);const u=c.buildRefundTx(i,o),P=await p.getPrePeginHtlcConnectorInfo({depositorPubkey:t.depositorPubkey,vaultProviderPubkey:t.vaultProviderPubkey,vaultKeeperPubkeys:t.vaultKeeperPubkeys,universalChallengerPubkeys:t.universalChallengerPubkeys,hashlock:s,timelockRefund:t.timelockRefund,network:t.network}),h=n.startsWith("0x")?n.slice(2):n,f=d.Transaction.fromHex(h),x=f.outs[o];if(!x)throw new Error(`HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${f.outs.length} outputs)`);const g=d.Transaction.fromHex(u);if(g.ins.length!==1)throw new Error(`Refund transaction must have exactly 1 input, got ${g.ins.length}`);const y=g.ins[0],v=f.getId(),T=r.uint8ArrayToHex(new Uint8Array(y.hash).slice().reverse());if(T!==v)throw new Error(`Refund input does not reference the Pre-PegIn transaction. Expected ${v}, got ${T}`);if(y.index!==o)throw new Error(`Refund input index ${y.index} does not match expected htlcVout ${o}`);const b=new d.Psbt;b.setVersion(g.version),b.setLocktime(g.locktime),b.addInput({hash:y.hash,index:y.index,sequence:y.sequence,witnessUtxo:{script:x.script,value:x.value},tapLeafScript:[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(r.hexToUint8Array(P.refundScript)),controlBlock:a.Buffer.from(r.hexToUint8Array(P.refundControlBlock))}],tapInternalKey:a.Buffer.from(p.tapInternalPubkey)});for(const w of g.outs)b.addOutput({script:w.script,value:w.value});return{psbtHex:b.toHex()}}finally{c==null||c.free(),l.free()}}async function U(e){const t=r.stripHexPrefix(e.payoutTxHex),n=d.Transaction.fromHex(t),{payoutScript:o,payoutControlBlock:i}=await p.getPeginPayoutScriptInfo(e.connectorParams),s=r.hexToUint8Array(o),l=r.hexToUint8Array(i),c=new d.Psbt;c.setVersion(n.version),c.setLocktime(n.locktime);for(let u=0;u<n.ins.length;u++){const P=n.ins[u],h=e.prevouts[u];if(!h)throw new Error(`Missing prevout data for input ${u}`);const f={hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:a.Buffer.from(r.hexToUint8Array(r.stripHexPrefix(h.script_pubkey))),value:h.value}};u===0&&(f.tapLeafScript=[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(s),controlBlock:a.Buffer.from(l)}],f.tapInternalKey=a.Buffer.from(p.tapInternalPubkey)),c.addInput(f)}for(const u of n.outs)c.addOutput({script:u.script,value:u.value});return c.toHex()}async function V(e){const t=r.stripHexPrefix(e.noPayoutTxHex),n=d.Transaction.fromHex(t),{noPayoutScript:o,noPayoutControlBlock:i}=await p.getAssertNoPayoutScriptInfo(e.connectorParams,e.challengerPubkey),s=r.hexToUint8Array(o),l=r.hexToUint8Array(i),c=new d.Psbt;c.setVersion(n.version),c.setLocktime(n.locktime);for(let u=0;u<n.ins.length;u++){const P=n.ins[u],h=e.prevouts[u];if(!h)throw new Error(`Missing prevout data for input ${u}`);const f={hash:P.hash,index:P.index,sequence:P.sequence,witnessUtxo:{script:a.Buffer.from(r.hexToUint8Array(r.stripHexPrefix(h.script_pubkey))),value:h.value}};u===0&&(f.tapLeafScript=[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(s),controlBlock:a.Buffer.from(l)}],f.tapInternalKey=a.Buffer.from(p.tapInternalPubkey)),c.addInput(f)}for(const u of n.outs)c.addOutput({script:u.script,value:u.value});return c.toHex()}async function L(e){const t=r.stripHexPrefix(e.challengeAssertTxHex),n=d.Transaction.fromHex(t);if(e.connectorParamsPerInput.length!==n.ins.length)throw new Error(`Expected ${n.ins.length} connector params, got ${e.connectorParamsPerInput.length}`);const o=await Promise.all(e.connectorParamsPerInput.map(s=>p.getChallengeAssertScriptInfo(s))),i=new d.Psbt;i.setVersion(n.version),i.setLocktime(n.locktime);for(let s=0;s<n.ins.length;s++){const l=n.ins[s],c=e.prevouts[s];if(!c)throw new Error(`Missing prevout data for input ${s}`);const{script:u,controlBlock:P}=o[s],h=r.hexToUint8Array(u),f=r.hexToUint8Array(P);i.addInput({hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:a.Buffer.from(r.hexToUint8Array(r.stripHexPrefix(c.script_pubkey))),value:c.value},tapLeafScript:[{leafVersion:r.TAPSCRIPT_LEAF_VERSION,script:a.Buffer.from(h),controlBlock:a.Buffer.from(f)}],tapInternalKey:a.Buffer.from(p.tapInternalPubkey)})}for(const s of n.outs)i.addOutput({script:s.script,value:s.value});return i.toHex()}exports.buildChallengeAssertPsbt=L;exports.buildDepositorPayoutPsbt=U;exports.buildNoPayoutPsbt=V;exports.buildPeginInputPsbt=A;exports.buildPeginTxFromFundedPrePegin=H;exports.buildPrePeginPsbt=S;exports.buildRefundPsbt=R;exports.computeNumLocalChallengers=m;exports.extractPeginInputSignature=B;exports.finalizePeginInputPsbt=C;
|
|
2
|
-
//# sourceMappingURL=challengeAssert-D_k_ADgP.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"challengeAssert-D_k_ADgP.cjs","sources":["../src/tbv/core/primitives/challengers.ts","../src/tbv/core/primitives/psbt/pegin.ts","../src/tbv/core/primitives/psbt/peginInput.ts","../src/tbv/core/primitives/psbt/refund.ts","../src/tbv/core/primitives/psbt/depositorPayout.ts","../src/tbv/core/primitives/psbt/noPayout.ts","../src/tbv/core/primitives/psbt/challengeAssert.ts"],"sourcesContent":["/**\n * Challenger counting utilities.\n *\n * Used for UI-level validation (e.g. computing minimum deposit amounts)\n * where the depositor's identity is known. The transaction builders use\n * `vaultKeeperBtcPubkeys.length` to match the VP's current validation.\n */\n\nimport { processPublicKeyToXOnly } from \"./utils/bitcoin\";\n\n/**\n * Normalize a public key to lowercase x-only hex for reliable comparison.\n *\n * Handles `0x` prefixes, compressed (33-byte), and uncompressed (65-byte) keys.\n */\nfunction normalizeKey(key: string): string {\n return processPublicKeyToXOnly(key).toLowerCase();\n}\n\n/**\n * Compute the number of local challengers for a vault.\n *\n * Mirrors the VP's `compute_num_challengers()` logic:\n * local challengers = {vault_provider} ∪ {vault_keepers} − {depositor}\n *\n * Keys are normalized to x-only lowercase hex before comparison, so\n * `0x`-prefixed, compressed, or mixed-case keys are handled correctly.\n *\n * @param vaultProviderPubkey - Vault provider BTC public key\n * @param vaultKeeperPubkeys - Vault keeper BTC public keys\n * @param depositorPubkey - Depositor (claimer) BTC public key\n * @returns Number of local challengers\n */\nexport function computeNumLocalChallengers(\n vaultProviderPubkey: string,\n vaultKeeperPubkeys: string[],\n depositorPubkey: string,\n): number {\n const localSet = new Set<string>();\n localSet.add(normalizeKey(vaultProviderPubkey));\n for (const vk of vaultKeeperPubkeys) {\n localSet.add(normalizeKey(vk));\n }\n localSet.delete(normalizeKey(depositorPubkey));\n return localSet.size;\n}\n","/**\n * Pre-PegIn PSBT Builder Primitive\n *\n * This module provides pure functions for building unfunded Pre-PegIn transactions\n * and deriving PegIn transactions from them, using the WASM implementation from\n * @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * Pre-PegIn Flow:\n * 1. buildPrePeginPsbt() — creates unfunded Pre-PegIn tx (HTLC output)\n * 2. [caller funds Pre-PegIn tx and computes txid]\n * 3. buildPeginTxFromFundedPrePegin() — derives PegIn tx spending the HTLC\n * 4. buildPeginInputPsbt() — PSBT for depositor to sign PegIn HTLC leaf 0 input\n *\n * @module primitives/psbt/pegin\n */\n\nimport {\n createPrePeginTransaction,\n buildPeginTxFromPrePegin,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\nimport { parseUnfundedWasmTransaction } from \"../../utils/transaction/fundPeginTransaction\";\n\n/**\n * Parameters for building an unfunded Pre-PegIn PSBT\n */\nexport interface PrePeginParams {\n /** Depositor's BTC public key (x-only, 64-char hex without 0x prefix) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Array of vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Array of universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment(s) (64 hex chars = 32 bytes each) */\n hashlocks: readonly string[];\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Amounts to peg in (satoshis), one per deposit */\n pegInAmounts: readonly bigint[];\n /** Fee rate in sat/vB from contract offchain params */\n feeRate: bigint;\n /** Number of local challengers (from contract params) */\n numLocalChallengers: number;\n /** M in M-of-N council multisig (from contract params) */\n councilQuorum: number;\n /** N in M-of-N council multisig (from contract params) */\n councilSize: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building an unfunded Pre-PegIn transaction\n */\nexport interface PrePeginPsbtResult {\n /**\n * Unfunded transaction hex (no inputs, HTLC output + CPFP anchor).\n *\n * The caller is responsible for:\n * - Selecting UTXOs covering totalOutputValue + network fees\n * - Funding the transaction (add inputs and change output)\n * - Computing the funded transaction's txid\n * - Calling buildPeginTxFromFundedPrePegin() with the funded txid\n */\n psbtHex: string;\n /** Sum of all unfunded outputs (HTLC + CPFP anchor) — use this for UTXO selection */\n totalOutputValue: bigint;\n /** HTLC output values in satoshis, one per deposit (each includes peginAmount + depositorClaimValue + minPeginFee) */\n htlcValues: readonly bigint[];\n /** HTLC output scriptPubKeys (hex encoded), one per deposit */\n htlcScriptPubKeys: readonly string[];\n /** HTLC Taproot addresses, one per deposit */\n htlcAddresses: readonly string[];\n /** Pegin amounts in satoshis, one per deposit */\n peginAmounts: readonly bigint[];\n /** Depositor claim value computed by WASM from contract parameters */\n depositorClaimValue: bigint;\n}\n\n/**\n * Parameters for building the PegIn transaction from a funded Pre-PegIn txid\n */\nexport interface BuildPeginTxParams {\n /** Same PrePeginParams used to create the Pre-PegIn transaction */\n prePeginParams: PrePeginParams;\n /** CSV timelock in blocks for the PegIn vault output */\n timelockPegin: number;\n /** Hex-encoded funded Pre-PegIn transaction */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output to spend */\n htlcVout: number;\n}\n\n/**\n * Result of building the PegIn transaction\n */\nexport interface PeginTxResult {\n /** PegIn transaction hex (1 input spending HTLC, 1 vault output) */\n txHex: string;\n /** PegIn transaction ID */\n txid: string;\n /** Vault output scriptPubKey (hex encoded) */\n vaultScriptPubKey: string;\n /** Vault output value in satoshis */\n vaultValue: bigint;\n}\n\n/**\n * Build unfunded Pre-PegIn transaction using WASM.\n *\n * Creates a Bitcoin transaction template with no inputs, an HTLC output, and a\n * CPFP anchor output. The HTLC value is computed internally from the contract\n * parameters — the caller does not need to compute depositorClaimValue separately.\n *\n * @param params - Pre-PegIn parameters\n * @returns Unfunded Pre-PegIn transaction details with HTLC output information\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPrePeginPsbt(\n params: PrePeginParams,\n): Promise<PrePeginPsbtResult> {\n const result = await createPrePeginTransaction({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlocks: [...params.hashlocks],\n timelockRefund: params.timelockRefund,\n pegInAmounts: [...params.pegInAmounts],\n feeRate: params.feeRate,\n numLocalChallengers: params.numLocalChallengers,\n councilQuorum: params.councilQuorum,\n councilSize: params.councilSize,\n network: params.network,\n });\n\n // Parse the unfunded tx to sum all output values (HTLC + CPFP anchor).\n // This is the amount UTXOs must cover before adding network fees.\n const parsed = parseUnfundedWasmTransaction(result.txHex);\n const totalOutputValue = parsed.outputs.reduce(\n (sum, o) => sum + BigInt(o.value),\n 0n,\n );\n\n return {\n psbtHex: result.txHex,\n totalOutputValue,\n htlcValues: result.htlcValues,\n htlcScriptPubKeys: result.htlcScriptPubKeys,\n htlcAddresses: result.htlcAddresses,\n peginAmounts: result.peginAmounts,\n depositorClaimValue: result.depositorClaimValue,\n };\n}\n\n/**\n * Build the PegIn transaction from a funded Pre-PegIn transaction.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output at htlcVout via the\n * hashlock + all-party script (leaf 0).\n *\n * @param params - Build parameters including Pre-PegIn params and funded tx hex\n * @returns PegIn transaction details\n * @throws If WASM initialization fails or parameters are invalid\n */\nexport async function buildPeginTxFromFundedPrePegin(\n params: BuildPeginTxParams,\n): Promise<PeginTxResult> {\n const result = await buildPeginTxFromPrePegin(\n {\n depositorPubkey: params.prePeginParams.depositorPubkey,\n vaultProviderPubkey: params.prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: params.prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.prePeginParams.universalChallengerPubkeys,\n hashlocks: [...params.prePeginParams.hashlocks],\n timelockRefund: params.prePeginParams.timelockRefund,\n pegInAmounts: [...params.prePeginParams.pegInAmounts],\n feeRate: params.prePeginParams.feeRate,\n numLocalChallengers: params.prePeginParams.numLocalChallengers,\n councilQuorum: params.prePeginParams.councilQuorum,\n councilSize: params.prePeginParams.councilSize,\n network: params.prePeginParams.network,\n },\n params.timelockPegin,\n params.fundedPrePeginTxHex,\n params.htlcVout,\n );\n\n return {\n txHex: result.txHex,\n txid: result.txid,\n vaultScriptPubKey: result.vaultScriptPubKey,\n vaultValue: result.vaultValue,\n };\n}\n","/**\n * PegIn Input PSBT Builder\n *\n * Builds the PSBT for the depositor to sign the PegIn transaction's HTLC input\n * (Pre-PegIn HTLC leaf 0 — the hashlock + all-party script).\n *\n * This is the \"Sign Pegin transaction HTLC leaf 0 input\" step in the pre-pegin\n * flow. The depositor signs input 0 of the PegIn transaction,\n * which spends output 0 of the funded Pre-PegIn transaction via script-path.\n *\n * @module primitives/psbt/peginInput\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n tapInternalPubkey,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, stripHexPrefix, uint8ArrayToHex } from \"../utils/bitcoin\";\n\n/**\n * Parameters for building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtParams {\n /**\n * PegIn transaction hex (1 input spending Pre-PegIn HTLC output 0).\n * Returned by buildPeginTxFromFundedPrePegin().\n */\n peginTxHex: string;\n /**\n * Funded Pre-PegIn transaction hex.\n * Used to look up the HTLC output that the PegIn input spends.\n */\n fundedPrePeginTxHex: string;\n /** Depositor's BTC public key (x-only, 64-char hex) */\n depositorPubkey: string;\n /** Vault provider's BTC public key (x-only, 64-char hex) */\n vaultProviderPubkey: string;\n /** Vault keeper BTC public keys (x-only, 64-char hex) */\n vaultKeeperPubkeys: string[];\n /** Universal challenger BTC public keys (x-only, 64-char hex) */\n universalChallengerPubkeys: string[];\n /** SHA256 hash commitment (64 hex chars = 32 bytes) */\n hashlock: string;\n /** CSV timelock in blocks for the HTLC refund path */\n timelockRefund: number;\n /** Bitcoin network */\n network: Network;\n}\n\n/**\n * Result of building the PegIn input PSBT\n */\nexport interface BuildPeginInputPsbtResult {\n /** PSBT hex for the depositor to sign */\n psbtHex: string;\n}\n\n/**\n * Build PSBT for depositor to sign the PegIn transaction's HTLC leaf 0 input.\n *\n * The PegIn transaction spends the Pre-PegIn HTLC output (output 0) via the\n * hashlock + all-party script (leaf 0). The depositor provides one of the required\n * signatures; the vault provider and keepers provide theirs separately via the\n * signPeginInput RPC.\n *\n * The PSBT uses Taproot script-path spending:\n * - witnessUtxo: the Pre-PegIn HTLC output\n * - tapLeafScript: hashlock leaf script + control block\n * - tapInternalKey: NUMS unspendable key (BIP-341 nothing-up-my-sleeve)\n *\n * @param params - PegIn input PSBT parameters\n * @returns PSBT hex ready for depositor signing\n * @throws If PegIn tx does not have exactly 1 input\n * @throws If PegIn input does not reference the Pre-PegIn HTLC output\n * @throws If Pre-PegIn tx output 0 is not found\n */\nexport async function buildPeginInputPsbt(\n params: BuildPeginInputPsbtParams,\n): Promise<BuildPeginInputPsbtResult> {\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const fundedPrePeginTxHex = stripHexPrefix(params.fundedPrePeginTxHex);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: params.depositorPubkey,\n vaultProviderPubkey: params.vaultProviderPubkey,\n vaultKeeperPubkeys: params.vaultKeeperPubkeys,\n universalChallengerPubkeys: params.universalChallengerPubkeys,\n hashlock: params.hashlock,\n timelockRefund: params.timelockRefund,\n network: params.network,\n });\n\n const peginTx = Transaction.fromHex(peginTxHex);\n const prePeginTx = Transaction.fromHex(fundedPrePeginTxHex);\n\n if (peginTx.ins.length !== 1) {\n throw new Error(\n `PegIn transaction must have exactly 1 input, got ${peginTx.ins.length}`,\n );\n }\n\n const peginInput = peginTx.ins[0];\n\n // Verify PegIn input 0 spends Pre-PegIn output 0\n const prePeginTxid = prePeginTx.getId();\n const peginInputTxid = uint8ArrayToHex(\n new Uint8Array(peginInput.hash).slice().reverse(),\n );\n\n if (peginInputTxid !== prePeginTxid) {\n throw new Error(\n `PegIn input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${peginInputTxid}`,\n );\n }\n\n const htlcOutput = prePeginTx.outs[peginInput.index];\n if (!htlcOutput) {\n throw new Error(\n `Pre-PegIn output ${peginInput.index} not found ` +\n `(Pre-PegIn has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const hashlockScript = hexToUint8Array(htlcConnector.hashlockScript);\n const hashlockControlBlock = hexToUint8Array(htlcConnector.hashlockControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(peginTx.version);\n psbt.setLocktime(peginTx.locktime);\n\n // Input 0: PegIn input spending Pre-PegIn HTLC output 0 via hashlock leaf (leaf 0).\n // The depositor signs using Taproot script-path spending.\n psbt.addInput({\n hash: peginInput.hash,\n index: peginInput.index,\n sequence: peginInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hashlockScript),\n controlBlock: Buffer.from(hashlockControlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n for (const output of peginTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n}\n\n/**\n * Extract the depositor's Schnorr signature from a signed PegIn input PSBT.\n *\n * Supports both non-finalized PSBTs (tapScriptSig) and finalized PSBTs (witness).\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's x-only public key (64-char hex)\n * @returns 64-byte Schnorr signature (128 hex chars, no sighash flag)\n * @throws If no signature is found for the depositor's key\n */\nexport function extractPeginInputSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n const input = signedPsbt.data.inputs[0];\n\n if (!input) {\n throw new Error(\"PegIn PSBT has no inputs\");\n }\n\n // Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = Buffer.from(\n hexToUint8Array(depositorPubkey),\n );\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(depositorPubkeyBytes)) {\n return extractSchnorrSig(sigEntry.signature);\n }\n }\n\n throw new Error(\n `No PegIn input signature found for depositor pubkey: ${depositorPubkey}`,\n );\n }\n\n // Finalized PSBT — the witness stack order depends on the wallet's finalizer,\n // so we cannot reliably pick the depositor's signature by position. Require\n // the non-finalized tapScriptSig path which identifies signatures by pubkey.\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n throw new Error(\n \"PegIn input PSBT is already finalized. Cannot reliably extract the \" +\n \"depositor signature from the witness stack. Ensure the wallet returns \" +\n \"a non-finalized PSBT with tapScriptSig entries.\",\n );\n }\n\n throw new Error(\n \"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT\",\n );\n}\n\n/**\n * Finalize a signed PegIn input PSBT and return the depositor-signed transaction hex.\n *\n * The default tapscript finalizer builds the full witness stack [sig, script, controlBlock]\n * that vaultd requires when verifying the depositor signature on-chain.\n *\n * @param signedPsbtHex - Non-finalized signed PSBT hex (returned by wallet with autoFinalized: false)\n * @returns Depositor-signed PegIn transaction hex with full taproot witness stack\n */\nexport function finalizePeginInputPsbt(signedPsbtHex: string): string {\n const psbt = Psbt.fromHex(signedPsbtHex);\n\n // Some wallets (UniSat, OKX) ignore autoFinalized: false and return\n // already-finalized PSBTs. finalizeAllInputs() throws in that case,\n // so fall back to verifying the wallet already finalized all inputs.\n try {\n psbt.finalizeAllInputs();\n } catch (e) {\n const allFinalized = psbt.data.inputs.every(\n (inp) => inp.finalScriptWitness || inp.finalScriptSig,\n );\n if (!allFinalized) {\n throw new Error(\n `PSBT finalization failed and wallet did not auto-finalize: ${e}`,\n );\n }\n }\n\n return psbt.extractTransaction().toHex();\n}\n\n/** Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present. */\nfunction extractSchnorrSig(sig: Uint8Array): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n }\n if (sig.length === 65) {\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(`Unexpected PegIn input signature length: ${sig.length}`);\n}\n\n","/**\n * Refund PSBT Builder Primitive\n *\n * Builds an unsigned refund PSBT for a depositor to reclaim BTC from\n * a timed-out Pre-PegIn HTLC output via the refund script (leaf 1).\n *\n * The refund script enforces a CSV timelock (timelockRefund blocks) and\n * requires only the depositor's Schnorr signature — no vault provider or\n * keeper involvement.\n *\n * @module primitives/psbt/refund\n */\n\nimport {\n getPrePeginHtlcConnectorInfo,\n initWasm,\n tapInternalPubkey,\n WasmPrePeginTx,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport { TAPSCRIPT_LEAF_VERSION, hexToUint8Array, uint8ArrayToHex } from \"../utils/bitcoin\";\nimport type { PrePeginParams } from \"./pegin\";\n\n/**\n * Parameters for building a refund PSBT\n */\nexport interface BuildRefundPsbtParams {\n /** Same PrePeginParams used when the original Pre-PegIn tx was created */\n prePeginParams: PrePeginParams;\n /** Funded Pre-PegIn transaction hex (the tx whose HTLC output is being refunded) */\n fundedPrePeginTxHex: string;\n /** Index of the HTLC output in the Pre-PegIn transaction */\n htlcVout: number;\n /** Transaction fee in satoshis for the refund transaction */\n refundFee: bigint;\n /** SHA256 hash commitment for the HTLC (64 hex chars, no 0x prefix) */\n hashlock: string;\n}\n\n/**\n * Result of building a refund PSBT\n */\nexport interface BuildRefundPsbtResult {\n /** PSBT hex ready for depositor signing */\n psbtHex: string;\n}\n\n/**\n * Build a PSBT for signing the refund transaction.\n *\n * The refund transaction spends the Pre-PegIn HTLC output via leaf 1\n * (the refund script: `<timelockRefund> CSV DROP <depositorPubkey> CHECKSIG`).\n * The PSBT includes the tapLeafScript entry so the depositor's wallet can\n * sign using Taproot script-path spending.\n *\n * The input's sequence is set to `timelockRefund` by the WASM, enforcing\n * the Bitcoin CSV timelock. The refund broadcast will be rejected by the\n * network if the timelock has not yet expired.\n *\n * @param params - Refund PSBT parameters\n * @returns PSBT hex for depositor signing\n * @throws If the HTLC output at htlcVout is not found\n * @throws If the refund transaction does not have exactly 1 input\n */\nexport async function buildRefundPsbt(\n params: BuildRefundPsbtParams,\n): Promise<BuildRefundPsbtResult> {\n await initWasm();\n\n const { prePeginParams, fundedPrePeginTxHex, htlcVout, refundFee, hashlock } =\n params;\n\n const unfundedTx = new WasmPrePeginTx(\n prePeginParams.depositorPubkey,\n prePeginParams.vaultProviderPubkey,\n prePeginParams.vaultKeeperPubkeys,\n prePeginParams.universalChallengerPubkeys,\n [...prePeginParams.hashlocks],\n new BigUint64Array(prePeginParams.pegInAmounts),\n prePeginParams.timelockRefund,\n prePeginParams.feeRate,\n prePeginParams.numLocalChallengers,\n prePeginParams.councilQuorum,\n prePeginParams.councilSize,\n prePeginParams.network,\n );\n\n let fundedTx: WasmPrePeginTx | null = null;\n try {\n fundedTx = unfundedTx.fromFundedTransaction(fundedPrePeginTxHex);\n\n const refundTxHex = fundedTx.buildRefundTx(refundFee, htlcVout);\n\n const htlcConnector = await getPrePeginHtlcConnectorInfo({\n depositorPubkey: prePeginParams.depositorPubkey,\n vaultProviderPubkey: prePeginParams.vaultProviderPubkey,\n vaultKeeperPubkeys: prePeginParams.vaultKeeperPubkeys,\n universalChallengerPubkeys: prePeginParams.universalChallengerPubkeys,\n hashlock,\n timelockRefund: prePeginParams.timelockRefund,\n network: prePeginParams.network,\n });\n\n const cleanPrePeginHex = fundedPrePeginTxHex.startsWith(\"0x\")\n ? fundedPrePeginTxHex.slice(2)\n : fundedPrePeginTxHex;\n const prePeginTx = Transaction.fromHex(cleanPrePeginHex);\n\n const htlcOutput = prePeginTx.outs[htlcVout];\n if (!htlcOutput) {\n throw new Error(\n `HTLC output at vout ${htlcVout} not found in funded Pre-PegIn tx ` +\n `(tx has ${prePeginTx.outs.length} outputs)`,\n );\n }\n\n const refundTx = Transaction.fromHex(refundTxHex);\n\n if (refundTx.ins.length !== 1) {\n throw new Error(\n `Refund transaction must have exactly 1 input, got ${refundTx.ins.length}`,\n );\n }\n\n const refundInput = refundTx.ins[0];\n\n // Verify the refund input spends the correct Pre-PegIn HTLC output\n const prePeginTxid = prePeginTx.getId();\n const refundInputTxid = uint8ArrayToHex(\n new Uint8Array(refundInput.hash).slice().reverse(),\n );\n if (refundInputTxid !== prePeginTxid) {\n throw new Error(\n `Refund input does not reference the Pre-PegIn transaction. ` +\n `Expected ${prePeginTxid}, got ${refundInputTxid}`,\n );\n }\n if (refundInput.index !== htlcVout) {\n throw new Error(\n `Refund input index ${refundInput.index} does not match expected htlcVout ${htlcVout}`,\n );\n }\n\n const psbt = new Psbt();\n psbt.setVersion(refundTx.version);\n psbt.setLocktime(refundTx.locktime);\n\n psbt.addInput({\n hash: refundInput.hash,\n index: refundInput.index,\n sequence: refundInput.sequence,\n witnessUtxo: {\n script: htlcOutput.script,\n value: htlcOutput.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(hexToUint8Array(htlcConnector.refundScript)),\n controlBlock: Buffer.from(\n hexToUint8Array(htlcConnector.refundControlBlock),\n ),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n\n for (const output of refundTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return { psbtHex: psbt.toHex() };\n } finally {\n fundedTx?.free();\n unfundedTx.free();\n }\n}\n","/**\n * Depositor Payout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's own Payout transaction\n * (depositor-as-claimer path). The depositor signs input 0 using the\n * payout taproot script from WasmPeginPayoutConnector (PegIn vault UTXO).\n *\n * Input 0 spends PegIn:0 (the vault UTXO) — the same connector used for\n * VP/VK payout signing. The VP verifies this signature using the\n * PeginPayoutConnector's payout script.\n *\n * @module primitives/psbt/depositorPayout\n * @see btc-vault crates/vault/src/sign.rs — verify_depositor_signature / get_payout_tap_leaf_hash\n */\n\nimport {\n type PayoutConnectorParams,\n getPeginPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a depositor Payout PSBT\n */\nexport interface DepositorPayoutParams {\n /** Payout transaction hex (unsigned) from VP */\n payoutTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the PeginPayout connector (depositor, VP, VKs, UCs, timelock) */\n connectorParams: PayoutConnectorParams;\n}\n\n/**\n * Build unsigned depositor Payout PSBT.\n *\n * The depositor's payout transaction has 2 inputs:\n * - Input 0: PegIn:0 (vault UTXO) — depositor signs using PeginPayoutConnector payout script\n * - Input 1: Assert:0 — NOT signed by depositor\n *\n * @param params - Depositor payout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildDepositorPayoutPsbt(\n params: DepositorPayoutParams,\n): Promise<string> {\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const payoutTx = Transaction.fromHex(payoutTxHex);\n\n // Get payout script and control block from WASM (PeginPayoutConnector)\n const { payoutScript, payoutControlBlock } = await getPeginPayoutScriptInfo(\n params.connectorParams,\n );\n const scriptBytes = hexToUint8Array(payoutScript);\n const controlBlock = hexToUint8Array(payoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < payoutTx.ins.length; i++) {\n const input = payoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n\n","/**\n * NoPayout PSBT Builder\n *\n * Builds unsigned PSBTs for the depositor's NoPayout transaction\n * (depositor-as-claimer path, per challenger). The depositor signs input 0\n * using the NoPayout taproot script from WasmAssertPayoutNoPayoutConnector.\n *\n * @module primitives/psbt/noPayout\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — Assert output 0 NoPayout connector\n */\n\nimport {\n type AssertPayoutNoPayoutConnectorParams,\n getAssertNoPayoutScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a NoPayout PSBT\n */\nexport interface NoPayoutParams {\n /** NoPayout transaction hex (unsigned) from VP */\n noPayoutTxHex: string;\n /** Challenger's x-only public key (hex encoded) */\n challengerPubkey: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Parameters for the Assert Payout/NoPayout connector */\n connectorParams: AssertPayoutNoPayoutConnectorParams;\n}\n\n/**\n * Build unsigned NoPayout PSBT.\n *\n * The NoPayout transaction is specific to each challenger.\n * Input 0 is the one the depositor signs using the NoPayout taproot script path.\n *\n * @param params - NoPayout parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildNoPayoutPsbt(\n params: NoPayoutParams,\n): Promise<string> {\n const noPayoutTxHex = stripHexPrefix(params.noPayoutTxHex);\n const noPayoutTx = Transaction.fromHex(noPayoutTxHex);\n\n // Get NoPayout script and control block for this challenger\n const { noPayoutScript, noPayoutControlBlock } =\n await getAssertNoPayoutScriptInfo(\n params.connectorParams,\n params.challengerPubkey,\n );\n\n const scriptBytes = hexToUint8Array(noPayoutScript);\n const controlBlockBytes = hexToUint8Array(noPayoutControlBlock);\n\n const psbt = new Psbt();\n psbt.setVersion(noPayoutTx.version);\n psbt.setLocktime(noPayoutTx.locktime);\n\n // Add all inputs - depositor signs input 0 only\n for (let i = 0; i < noPayoutTx.ins.length; i++) {\n const input = noPayoutTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const inputData: Parameters<typeof psbt.addInput>[0] = {\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n };\n\n // Input 0: depositor signs using taproot script path\n if (i === 0) {\n inputData.tapLeafScript = [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ];\n inputData.tapInternalKey = Buffer.from(tapInternalPubkey);\n }\n\n psbt.addInput(inputData);\n }\n\n // Add outputs\n for (const output of noPayoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n","/**\n * ChallengeAssert PSBT Builder\n *\n * Builds an unsigned PSBT for a ChallengeAssert transaction\n * (depositor-as-claimer path, per challenger). The ChallengeAssert tx has\n * NUM_UTXOS_FOR_CHALLENGE_ASSERT (3) inputs, each spending a different Assert\n * output segment. The depositor signs ALL inputs, each with its own taproot\n * script derived from the per-segment connector params.\n *\n * @module primitives/psbt/challengeAssert\n * @see btc-vault crates/vault/docs/btc-transactions-spec.md — ChallengeAssert connector (NUM_UTXOS_FOR_CHALLENGE_ASSERT=3)\n */\n\nimport {\n type ChallengeAssertConnectorParams,\n getChallengeAssertScriptInfo,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\n\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building a ChallengeAssert PSBT\n */\nexport interface ChallengeAssertParams {\n /** ChallengeAssert transaction hex (unsigned) from VP */\n challengeAssertTxHex: string;\n /** Prevouts for all inputs [{script_pubkey, value}] from VP (flat, one per input) */\n prevouts: Array<{ script_pubkey: string; value: number }>;\n /** Per-input connector params (one per input/segment, determines the taproot script) */\n connectorParamsPerInput: ChallengeAssertConnectorParams[];\n}\n\n/**\n * Build unsigned ChallengeAssert PSBT.\n *\n * The ChallengeAssert transaction has 3 inputs (one per Assert output segment).\n * Each input has its own taproot script derived from its connector params.\n * The depositor signs all inputs.\n *\n * @param params - ChallengeAssert parameters\n * @returns Unsigned PSBT hex ready for signing\n */\nexport async function buildChallengeAssertPsbt(\n params: ChallengeAssertParams,\n): Promise<string> {\n const challengeAssertTxHex = stripHexPrefix(params.challengeAssertTxHex);\n const challengeAssertTx = Transaction.fromHex(challengeAssertTxHex);\n\n if (params.connectorParamsPerInput.length !== challengeAssertTx.ins.length) {\n throw new Error(\n `Expected ${challengeAssertTx.ins.length} connector params, got ${params.connectorParamsPerInput.length}`,\n );\n }\n\n // Get script and control block for each input from WASM\n const scriptInfos = await Promise.all(\n params.connectorParamsPerInput.map((cp) => getChallengeAssertScriptInfo(cp)),\n );\n\n const psbt = new Psbt();\n psbt.setVersion(challengeAssertTx.version);\n psbt.setLocktime(challengeAssertTx.locktime);\n\n // Add all inputs — depositor signs every input\n for (let i = 0; i < challengeAssertTx.ins.length; i++) {\n const input = challengeAssertTx.ins[i];\n const prevout = params.prevouts[i];\n\n if (!prevout) {\n throw new Error(`Missing prevout data for input ${i}`);\n }\n\n const { script, controlBlock } = scriptInfos[i];\n const scriptBytes = hexToUint8Array(script);\n const controlBlockBytes = hexToUint8Array(controlBlock);\n\n psbt.addInput({\n hash: input.hash,\n index: input.index,\n sequence: input.sequence,\n witnessUtxo: {\n script: Buffer.from(hexToUint8Array(stripHexPrefix(prevout.script_pubkey))),\n value: prevout.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(scriptBytes),\n controlBlock: Buffer.from(controlBlockBytes),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n });\n }\n\n // Add outputs\n for (const output of challengeAssertTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return psbt.toHex();\n}\n"],"names":["normalizeKey","key","processPublicKeyToXOnly","computeNumLocalChallengers","vaultProviderPubkey","vaultKeeperPubkeys","depositorPubkey","localSet","vk","buildPrePeginPsbt","params","result","createPrePeginTransaction","totalOutputValue","parseUnfundedWasmTransaction","sum","o","buildPeginTxFromFundedPrePegin","buildPeginTxFromPrePegin","buildPeginInputPsbt","peginTxHex","stripHexPrefix","fundedPrePeginTxHex","htlcConnector","getPrePeginHtlcConnectorInfo","peginTx","Transaction","prePeginTx","peginInput","prePeginTxid","peginInputTxid","uint8ArrayToHex","htlcOutput","hashlockScript","hexToUint8Array","hashlockControlBlock","psbt","Psbt","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPeginInputSignature","signedPsbtHex","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","finalizePeginInputPsbt","e","inp","sig","buildRefundPsbt","initWasm","prePeginParams","htlcVout","refundFee","hashlock","unfundedTx","WasmPrePeginTx","fundedTx","refundTxHex","cleanPrePeginHex","refundTx","refundInput","refundInputTxid","buildDepositorPayoutPsbt","payoutTxHex","payoutTx","payoutScript","payoutControlBlock","getPeginPayoutScriptInfo","scriptBytes","controlBlock","i","prevout","inputData","buildNoPayoutPsbt","noPayoutTxHex","noPayoutTx","noPayoutScript","noPayoutControlBlock","getAssertNoPayoutScriptInfo","controlBlockBytes","buildChallengeAssertPsbt","challengeAssertTxHex","challengeAssertTx","scriptInfos","cp","getChallengeAssertScriptInfo","script"],"mappings":"4MAeA,SAASA,EAAaC,EAAqB,CACzC,OAAOC,EAAAA,wBAAwBD,CAAG,EAAE,YAAA,CACtC,CAgBO,SAASE,EACdC,EACAC,EACAC,EACQ,CACR,MAAMC,MAAe,IACrBA,EAAS,IAAIP,EAAaI,CAAmB,CAAC,EAC9C,UAAWI,KAAMH,EACfE,EAAS,IAAIP,EAAaQ,CAAE,CAAC,EAE/B,OAAAD,EAAS,OAAOP,EAAaM,CAAe,CAAC,EACtCC,EAAS,IAClB,CC4EA,eAAsBE,EACpBC,EAC6B,CAC7B,MAAMC,EAAS,MAAMC,4BAA0B,CAC7C,gBAAiBF,EAAO,gBACxB,oBAAqBA,EAAO,oBAC5B,mBAAoBA,EAAO,mBAC3B,2BAA4BA,EAAO,2BACnC,UAAW,CAAC,GAAGA,EAAO,SAAS,EAC/B,eAAgBA,EAAO,eACvB,aAAc,CAAC,GAAGA,EAAO,YAAY,EACrC,QAASA,EAAO,QAChB,oBAAqBA,EAAO,oBAC5B,cAAeA,EAAO,cACtB,YAAaA,EAA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M,kCAAkCD,CAAC,EAAE,EAGvD,KAAM,CAAE,OAAAgB,EAAQ,aAAAjB,GAAiBc,EAAYb,CAAC,EACxCF,EAActC,EAAAA,gBAAgBwD,CAAM,EACpCP,EAAoBjD,EAAAA,gBAAgBuC,CAAY,EAEtDrC,EAAK,SAAS,CACZ,KAAMQ,EAAM,KACZ,MAAOA,EAAM,MACb,SAAUA,EAAM,SAChB,YAAa,CACX,OAAQL,EAAAA,OAAO,KAAKL,EAAAA,gBAAgBb,EAAAA,eAAesD,EAAQ,aAAa,CAAC,CAAC,EAC1E,MAAOA,EAAQ,KAAA,EAEjB,cAAe,CACb,CACE,YAAarC,EAAAA,uBACb,OAAQC,EAAAA,OAAO,KAAKiC,CAAW,EAC/B,aAAcjC,EAAAA,OAAO,KAAK4C,CAAiB,CAAA,CAC7C,EAEF,eAAgB5C,EAAAA,OAAO,KAAKC,EAAAA,iBAAiB,CAAA,CAC9C,CACH,CAGA,UAAWC,KAAU6C,EAAkB,KACrClD,EAAK,UAAU,CACb,OAAQK,EAAO,OACf,MAAOA,EAAO,KAAA,CACf,EAGH,OAAOL,EAAK,MAAA,CACd"}
|
|
@@ -1,362 +0,0 @@
|
|
|
1
|
-
import { p as B, s as g, u as m, h as P, j as b } from "./constants-Q7v2O7Ps.js";
|
|
2
|
-
import { createPrePeginTransaction as A, buildPeginTxFromPrePegin as E, getPrePeginHtlcConnectorInfo as C, tapInternalPubkey as w, initWasm as R, WasmPrePeginTx as V, getPeginPayoutScriptInfo as K, getAssertNoPayoutScriptInfo as $, getChallengeAssertScriptInfo as L } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
3
|
-
import { p as z } from "./fundPeginTransaction-DpwnDslW.js";
|
|
4
|
-
import { Buffer as c } from "buffer";
|
|
5
|
-
import { Transaction as x, Psbt as k } from "bitcoinjs-lib";
|
|
6
|
-
function S(e) {
|
|
7
|
-
return B(e).toLowerCase();
|
|
8
|
-
}
|
|
9
|
-
function Q(e, t, n) {
|
|
10
|
-
const o = /* @__PURE__ */ new Set();
|
|
11
|
-
o.add(S(e));
|
|
12
|
-
for (const r of t)
|
|
13
|
-
o.add(S(r));
|
|
14
|
-
return o.delete(S(n)), o.size;
|
|
15
|
-
}
|
|
16
|
-
async function _(e) {
|
|
17
|
-
const t = await A({
|
|
18
|
-
depositorPubkey: e.depositorPubkey,
|
|
19
|
-
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
20
|
-
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
21
|
-
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
22
|
-
hashlocks: [...e.hashlocks],
|
|
23
|
-
timelockRefund: e.timelockRefund,
|
|
24
|
-
pegInAmounts: [...e.pegInAmounts],
|
|
25
|
-
feeRate: e.feeRate,
|
|
26
|
-
numLocalChallengers: e.numLocalChallengers,
|
|
27
|
-
councilQuorum: e.councilQuorum,
|
|
28
|
-
councilSize: e.councilSize,
|
|
29
|
-
network: e.network
|
|
30
|
-
}), o = z(t.txHex).outputs.reduce(
|
|
31
|
-
(r, i) => r + BigInt(i.value),
|
|
32
|
-
0n
|
|
33
|
-
);
|
|
34
|
-
return {
|
|
35
|
-
psbtHex: t.txHex,
|
|
36
|
-
totalOutputValue: o,
|
|
37
|
-
htlcValues: t.htlcValues,
|
|
38
|
-
htlcScriptPubKeys: t.htlcScriptPubKeys,
|
|
39
|
-
htlcAddresses: t.htlcAddresses,
|
|
40
|
-
peginAmounts: t.peginAmounts,
|
|
41
|
-
depositorClaimValue: t.depositorClaimValue
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
async function D(e) {
|
|
45
|
-
const t = await E(
|
|
46
|
-
{
|
|
47
|
-
depositorPubkey: e.prePeginParams.depositorPubkey,
|
|
48
|
-
vaultProviderPubkey: e.prePeginParams.vaultProviderPubkey,
|
|
49
|
-
vaultKeeperPubkeys: e.prePeginParams.vaultKeeperPubkeys,
|
|
50
|
-
universalChallengerPubkeys: e.prePeginParams.universalChallengerPubkeys,
|
|
51
|
-
hashlocks: [...e.prePeginParams.hashlocks],
|
|
52
|
-
timelockRefund: e.prePeginParams.timelockRefund,
|
|
53
|
-
pegInAmounts: [...e.prePeginParams.pegInAmounts],
|
|
54
|
-
feeRate: e.prePeginParams.feeRate,
|
|
55
|
-
numLocalChallengers: e.prePeginParams.numLocalChallengers,
|
|
56
|
-
councilQuorum: e.prePeginParams.councilQuorum,
|
|
57
|
-
councilSize: e.prePeginParams.councilSize,
|
|
58
|
-
network: e.prePeginParams.network
|
|
59
|
-
},
|
|
60
|
-
e.timelockPegin,
|
|
61
|
-
e.fundedPrePeginTxHex,
|
|
62
|
-
e.htlcVout
|
|
63
|
-
);
|
|
64
|
-
return {
|
|
65
|
-
txHex: t.txHex,
|
|
66
|
-
txid: t.txid,
|
|
67
|
-
vaultScriptPubKey: t.vaultScriptPubKey,
|
|
68
|
-
vaultValue: t.vaultValue
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
async function M(e) {
|
|
72
|
-
const t = g(e.peginTxHex), n = g(e.fundedPrePeginTxHex), o = await C({
|
|
73
|
-
depositorPubkey: e.depositorPubkey,
|
|
74
|
-
vaultProviderPubkey: e.vaultProviderPubkey,
|
|
75
|
-
vaultKeeperPubkeys: e.vaultKeeperPubkeys,
|
|
76
|
-
universalChallengerPubkeys: e.universalChallengerPubkeys,
|
|
77
|
-
hashlock: e.hashlock,
|
|
78
|
-
timelockRefund: e.timelockRefund,
|
|
79
|
-
network: e.network
|
|
80
|
-
}), r = x.fromHex(t), i = x.fromHex(n);
|
|
81
|
-
if (r.ins.length !== 1)
|
|
82
|
-
throw new Error(
|
|
83
|
-
`PegIn transaction must have exactly 1 input, got ${r.ins.length}`
|
|
84
|
-
);
|
|
85
|
-
const l = r.ins[0], u = i.getId(), s = m(
|
|
86
|
-
new Uint8Array(l.hash).slice().reverse()
|
|
87
|
-
);
|
|
88
|
-
if (s !== u)
|
|
89
|
-
throw new Error(
|
|
90
|
-
`PegIn input does not reference the Pre-PegIn transaction. Expected ${u}, got ${s}`
|
|
91
|
-
);
|
|
92
|
-
const a = i.outs[l.index];
|
|
93
|
-
if (!a)
|
|
94
|
-
throw new Error(
|
|
95
|
-
`Pre-PegIn output ${l.index} not found (Pre-PegIn has ${i.outs.length} outputs)`
|
|
96
|
-
);
|
|
97
|
-
const f = P(o.hashlockScript), p = P(o.hashlockControlBlock), d = new k();
|
|
98
|
-
d.setVersion(r.version), d.setLocktime(r.locktime), d.addInput({
|
|
99
|
-
hash: l.hash,
|
|
100
|
-
index: l.index,
|
|
101
|
-
sequence: l.sequence,
|
|
102
|
-
witnessUtxo: {
|
|
103
|
-
script: a.script,
|
|
104
|
-
value: a.value
|
|
105
|
-
},
|
|
106
|
-
tapLeafScript: [
|
|
107
|
-
{
|
|
108
|
-
leafVersion: b,
|
|
109
|
-
script: c.from(f),
|
|
110
|
-
controlBlock: c.from(p)
|
|
111
|
-
}
|
|
112
|
-
],
|
|
113
|
-
tapInternalKey: c.from(w)
|
|
114
|
-
// sighashType omitted — defaults to SIGHASH_DEFAULT (0x00) for Taproot
|
|
115
|
-
});
|
|
116
|
-
for (const h of r.outs)
|
|
117
|
-
d.addOutput({
|
|
118
|
-
script: h.script,
|
|
119
|
-
value: h.value
|
|
120
|
-
});
|
|
121
|
-
return { psbtHex: d.toHex() };
|
|
122
|
-
}
|
|
123
|
-
function j(e, t) {
|
|
124
|
-
const o = k.fromHex(e).data.inputs[0];
|
|
125
|
-
if (!o)
|
|
126
|
-
throw new Error("PegIn PSBT has no inputs");
|
|
127
|
-
if (o.tapScriptSig && o.tapScriptSig.length > 0) {
|
|
128
|
-
const r = c.from(
|
|
129
|
-
P(t)
|
|
130
|
-
);
|
|
131
|
-
for (const i of o.tapScriptSig)
|
|
132
|
-
if (i.pubkey.equals(r))
|
|
133
|
-
return U(i.signature);
|
|
134
|
-
throw new Error(
|
|
135
|
-
`No PegIn input signature found for depositor pubkey: ${t}`
|
|
136
|
-
);
|
|
137
|
-
}
|
|
138
|
-
throw o.finalScriptWitness && o.finalScriptWitness.length > 0 ? new Error(
|
|
139
|
-
"PegIn input PSBT is already finalized. Cannot reliably extract the depositor signature from the witness stack. Ensure the wallet returns a non-finalized PSBT with tapScriptSig entries."
|
|
140
|
-
) : new Error(
|
|
141
|
-
"No tapScriptSig or finalScriptWitness found in signed PegIn input PSBT"
|
|
142
|
-
);
|
|
143
|
-
}
|
|
144
|
-
function X(e) {
|
|
145
|
-
const t = k.fromHex(e);
|
|
146
|
-
try {
|
|
147
|
-
t.finalizeAllInputs();
|
|
148
|
-
} catch (n) {
|
|
149
|
-
if (!t.data.inputs.every(
|
|
150
|
-
(r) => r.finalScriptWitness || r.finalScriptSig
|
|
151
|
-
))
|
|
152
|
-
throw new Error(
|
|
153
|
-
`PSBT finalization failed and wallet did not auto-finalize: ${n}`
|
|
154
|
-
);
|
|
155
|
-
}
|
|
156
|
-
return t.extractTransaction().toHex();
|
|
157
|
-
}
|
|
158
|
-
function U(e) {
|
|
159
|
-
if (e.length === 64)
|
|
160
|
-
return m(new Uint8Array(e));
|
|
161
|
-
if (e.length === 65)
|
|
162
|
-
return m(new Uint8Array(e.subarray(0, 64)));
|
|
163
|
-
throw new Error(`Unexpected PegIn input signature length: ${e.length}`);
|
|
164
|
-
}
|
|
165
|
-
async function G(e) {
|
|
166
|
-
await R();
|
|
167
|
-
const { prePeginParams: t, fundedPrePeginTxHex: n, htlcVout: o, refundFee: r, hashlock: i } = e, l = new V(
|
|
168
|
-
t.depositorPubkey,
|
|
169
|
-
t.vaultProviderPubkey,
|
|
170
|
-
t.vaultKeeperPubkeys,
|
|
171
|
-
t.universalChallengerPubkeys,
|
|
172
|
-
[...t.hashlocks],
|
|
173
|
-
new BigUint64Array(t.pegInAmounts),
|
|
174
|
-
t.timelockRefund,
|
|
175
|
-
t.feeRate,
|
|
176
|
-
t.numLocalChallengers,
|
|
177
|
-
t.councilQuorum,
|
|
178
|
-
t.councilSize,
|
|
179
|
-
t.network
|
|
180
|
-
);
|
|
181
|
-
let u = null;
|
|
182
|
-
try {
|
|
183
|
-
u = l.fromFundedTransaction(n);
|
|
184
|
-
const s = u.buildRefundTx(r, o), a = await C({
|
|
185
|
-
depositorPubkey: t.depositorPubkey,
|
|
186
|
-
vaultProviderPubkey: t.vaultProviderPubkey,
|
|
187
|
-
vaultKeeperPubkeys: t.vaultKeeperPubkeys,
|
|
188
|
-
universalChallengerPubkeys: t.universalChallengerPubkeys,
|
|
189
|
-
hashlock: i,
|
|
190
|
-
timelockRefund: t.timelockRefund,
|
|
191
|
-
network: t.network
|
|
192
|
-
}), f = n.startsWith("0x") ? n.slice(2) : n, p = x.fromHex(f), d = p.outs[o];
|
|
193
|
-
if (!d)
|
|
194
|
-
throw new Error(
|
|
195
|
-
`HTLC output at vout ${o} not found in funded Pre-PegIn tx (tx has ${p.outs.length} outputs)`
|
|
196
|
-
);
|
|
197
|
-
const h = x.fromHex(s);
|
|
198
|
-
if (h.ins.length !== 1)
|
|
199
|
-
throw new Error(
|
|
200
|
-
`Refund transaction must have exactly 1 input, got ${h.ins.length}`
|
|
201
|
-
);
|
|
202
|
-
const y = h.ins[0], I = p.getId(), T = m(
|
|
203
|
-
new Uint8Array(y.hash).slice().reverse()
|
|
204
|
-
);
|
|
205
|
-
if (T !== I)
|
|
206
|
-
throw new Error(
|
|
207
|
-
`Refund input does not reference the Pre-PegIn transaction. Expected ${I}, got ${T}`
|
|
208
|
-
);
|
|
209
|
-
if (y.index !== o)
|
|
210
|
-
throw new Error(
|
|
211
|
-
`Refund input index ${y.index} does not match expected htlcVout ${o}`
|
|
212
|
-
);
|
|
213
|
-
const v = new k();
|
|
214
|
-
v.setVersion(h.version), v.setLocktime(h.locktime), v.addInput({
|
|
215
|
-
hash: y.hash,
|
|
216
|
-
index: y.index,
|
|
217
|
-
sequence: y.sequence,
|
|
218
|
-
witnessUtxo: {
|
|
219
|
-
script: d.script,
|
|
220
|
-
value: d.value
|
|
221
|
-
},
|
|
222
|
-
tapLeafScript: [
|
|
223
|
-
{
|
|
224
|
-
leafVersion: b,
|
|
225
|
-
script: c.from(P(a.refundScript)),
|
|
226
|
-
controlBlock: c.from(
|
|
227
|
-
P(a.refundControlBlock)
|
|
228
|
-
)
|
|
229
|
-
}
|
|
230
|
-
],
|
|
231
|
-
tapInternalKey: c.from(w)
|
|
232
|
-
});
|
|
233
|
-
for (const H of h.outs)
|
|
234
|
-
v.addOutput({
|
|
235
|
-
script: H.script,
|
|
236
|
-
value: H.value
|
|
237
|
-
});
|
|
238
|
-
return { psbtHex: v.toHex() };
|
|
239
|
-
} finally {
|
|
240
|
-
u == null || u.free(), l.free();
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
async function J(e) {
|
|
244
|
-
const t = g(e.payoutTxHex), n = x.fromHex(t), { payoutScript: o, payoutControlBlock: r } = await K(
|
|
245
|
-
e.connectorParams
|
|
246
|
-
), i = P(o), l = P(r), u = new k();
|
|
247
|
-
u.setVersion(n.version), u.setLocktime(n.locktime);
|
|
248
|
-
for (let s = 0; s < n.ins.length; s++) {
|
|
249
|
-
const a = n.ins[s], f = e.prevouts[s];
|
|
250
|
-
if (!f)
|
|
251
|
-
throw new Error(`Missing prevout data for input ${s}`);
|
|
252
|
-
const p = {
|
|
253
|
-
hash: a.hash,
|
|
254
|
-
index: a.index,
|
|
255
|
-
sequence: a.sequence,
|
|
256
|
-
witnessUtxo: {
|
|
257
|
-
script: c.from(P(g(f.script_pubkey))),
|
|
258
|
-
value: f.value
|
|
259
|
-
}
|
|
260
|
-
};
|
|
261
|
-
s === 0 && (p.tapLeafScript = [
|
|
262
|
-
{
|
|
263
|
-
leafVersion: b,
|
|
264
|
-
script: c.from(i),
|
|
265
|
-
controlBlock: c.from(l)
|
|
266
|
-
}
|
|
267
|
-
], p.tapInternalKey = c.from(w)), u.addInput(p);
|
|
268
|
-
}
|
|
269
|
-
for (const s of n.outs)
|
|
270
|
-
u.addOutput({
|
|
271
|
-
script: s.script,
|
|
272
|
-
value: s.value
|
|
273
|
-
});
|
|
274
|
-
return u.toHex();
|
|
275
|
-
}
|
|
276
|
-
async function Y(e) {
|
|
277
|
-
const t = g(e.noPayoutTxHex), n = x.fromHex(t), { noPayoutScript: o, noPayoutControlBlock: r } = await $(
|
|
278
|
-
e.connectorParams,
|
|
279
|
-
e.challengerPubkey
|
|
280
|
-
), i = P(o), l = P(r), u = new k();
|
|
281
|
-
u.setVersion(n.version), u.setLocktime(n.locktime);
|
|
282
|
-
for (let s = 0; s < n.ins.length; s++) {
|
|
283
|
-
const a = n.ins[s], f = e.prevouts[s];
|
|
284
|
-
if (!f)
|
|
285
|
-
throw new Error(`Missing prevout data for input ${s}`);
|
|
286
|
-
const p = {
|
|
287
|
-
hash: a.hash,
|
|
288
|
-
index: a.index,
|
|
289
|
-
sequence: a.sequence,
|
|
290
|
-
witnessUtxo: {
|
|
291
|
-
script: c.from(P(g(f.script_pubkey))),
|
|
292
|
-
value: f.value
|
|
293
|
-
}
|
|
294
|
-
};
|
|
295
|
-
s === 0 && (p.tapLeafScript = [
|
|
296
|
-
{
|
|
297
|
-
leafVersion: b,
|
|
298
|
-
script: c.from(i),
|
|
299
|
-
controlBlock: c.from(l)
|
|
300
|
-
}
|
|
301
|
-
], p.tapInternalKey = c.from(w)), u.addInput(p);
|
|
302
|
-
}
|
|
303
|
-
for (const s of n.outs)
|
|
304
|
-
u.addOutput({
|
|
305
|
-
script: s.script,
|
|
306
|
-
value: s.value
|
|
307
|
-
});
|
|
308
|
-
return u.toHex();
|
|
309
|
-
}
|
|
310
|
-
async function Z(e) {
|
|
311
|
-
const t = g(e.challengeAssertTxHex), n = x.fromHex(t);
|
|
312
|
-
if (e.connectorParamsPerInput.length !== n.ins.length)
|
|
313
|
-
throw new Error(
|
|
314
|
-
`Expected ${n.ins.length} connector params, got ${e.connectorParamsPerInput.length}`
|
|
315
|
-
);
|
|
316
|
-
const o = await Promise.all(
|
|
317
|
-
e.connectorParamsPerInput.map((i) => L(i))
|
|
318
|
-
), r = new k();
|
|
319
|
-
r.setVersion(n.version), r.setLocktime(n.locktime);
|
|
320
|
-
for (let i = 0; i < n.ins.length; i++) {
|
|
321
|
-
const l = n.ins[i], u = e.prevouts[i];
|
|
322
|
-
if (!u)
|
|
323
|
-
throw new Error(`Missing prevout data for input ${i}`);
|
|
324
|
-
const { script: s, controlBlock: a } = o[i], f = P(s), p = P(a);
|
|
325
|
-
r.addInput({
|
|
326
|
-
hash: l.hash,
|
|
327
|
-
index: l.index,
|
|
328
|
-
sequence: l.sequence,
|
|
329
|
-
witnessUtxo: {
|
|
330
|
-
script: c.from(P(g(u.script_pubkey))),
|
|
331
|
-
value: u.value
|
|
332
|
-
},
|
|
333
|
-
tapLeafScript: [
|
|
334
|
-
{
|
|
335
|
-
leafVersion: b,
|
|
336
|
-
script: c.from(f),
|
|
337
|
-
controlBlock: c.from(p)
|
|
338
|
-
}
|
|
339
|
-
],
|
|
340
|
-
tapInternalKey: c.from(w)
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
for (const i of n.outs)
|
|
344
|
-
r.addOutput({
|
|
345
|
-
script: i.script,
|
|
346
|
-
value: i.value
|
|
347
|
-
});
|
|
348
|
-
return r.toHex();
|
|
349
|
-
}
|
|
350
|
-
export {
|
|
351
|
-
D as a,
|
|
352
|
-
_ as b,
|
|
353
|
-
Q as c,
|
|
354
|
-
M as d,
|
|
355
|
-
j as e,
|
|
356
|
-
X as f,
|
|
357
|
-
G as g,
|
|
358
|
-
J as h,
|
|
359
|
-
Y as i,
|
|
360
|
-
Z as j
|
|
361
|
-
};
|
|
362
|
-
//# sourceMappingURL=challengeAssert-k5_LWUtO.js.map
|