import { Psbt, networks as networks$1 } from 'bitcoinjs-lib'; import { isBtcTestnetAddress, isBtcMainnetAddress, ethers } from '@rsksmart/bridges-core-sdk'; import TrezorConnect from '@trezor/connect-web'; import { CreateTransactionArg } from '@ledgerhq/hw-app-btc/lib/createTransaction'; /** Priority level used to look up a Bitcoin network fee rate. */ type FeeLevel = 'slow' | 'average' | 'fast'; /** * Contract that a Bitcoin signing backend (e.g. {@link TrezorSigner}, {@link LedgerSigner}) must implement * so {@link PowPegSDK} can derive addresses and sign peg-in transactions with it. */ interface BitcoinSigner { getNonChangeAddresses(bundleSize: number): Promise; getChangeAddresses(bundleSize: number): Promise; signTransaction(psbt: Psbt, inputs?: Utxo[], transactions?: string[]): Promise; } /** * Contract for a Bitcoin data provider (fee rates, UTXOs, raw transactions, broadcasting). * {@link PowPegSDK} falls back to its built-in 2WP API-backed implementation when none is supplied. */ interface BitcoinDataSource { getFeeRate(level: FeeLevel): Promise; getTxHex(txId: string): Promise; getOutputs(address: string): Promise; broadcast(hexTx: string): Promise; getAddressDetails(address: string): Promise; } /** A Bitcoin address together with its current balance and transaction count. */ interface AddressWithDetails { address: string; balance: number; txCount: number; } /** A spendable Bitcoin unspent transaction output. */ interface Utxo { address: string; txid: string; amount: bigint; vout: number; } /** Estimated Bitcoin and Rootstock fees for a peg-out. */ interface PegoutFeeEstimation { bitcoinFee: bigint; rootstockFee: bigint; } /** Browser support flags for a feature, as reported by the 2WP API. */ interface SupportedBrowsers { chrome: boolean; firefox: boolean; safari: boolean; edge: boolean; brave: boolean; chromium: boolean; opera: boolean; } /** A feature flag entry returned by the 2WP API `/features` endpoint. */ interface Feature { name: string; value: string; version: number; supportedBrowsers?: SupportedBrowsers; } /** Distinguishes a peg-in (BTC -> RBTC) from a peg-out (RBTC -> BTC) transaction. */ declare enum TxType { PEGIN = "PEGIN", PEGOUT = "PEGOUT" } /** Lifecycle status of a peg-out transaction, as reported by the 2WP API. */ declare enum PegoutStatuses { RECEIVED = "RECEIVED", REJECTED = "REJECTED", WAITING_FOR_CONFIRMATION = "WAITING_FOR_CONFIRMATION", WAITING_FOR_SIGNATURE = "WAITING_FOR_SIGNATURE", SIGNED = "SIGNED", NOT_FOUND = "NOT_FOUND", PENDING = "PENDING", NOT_PEGOUT_TX = "NOT_PEGOUT_TX", RELEASE_BTC = "RELEASE_BTC" } /** Lifecycle status of a peg-in transaction, as reported by the 2WP API. */ declare enum PeginStatuses { NOT_IN_BTC_YET = "NOT_IN_BTC_YET", WAITING_CONFIRMATIONS = "WAITING_CONFIRMATIONS", NOT_IN_RSK_YET = "NOT_IN_RSK_YET", CONFIRMED = "CONFIRMED", REJECTED_NO_REFUND = "REJECTED_NO_REFUND", REJECTED_REFUND = "REJECTED_REFUND", ERROR_NOT_A_PEGIN = "ERROR_NOT_A_PEGIN", ERROR_BELOW_MIN = "ERROR_BELOW_MIN", ERROR_UNEXPECTED = "ERROR_UNEXPECTED" } /** Maps the bridge's numeric rejection codes to a human-readable peg-out rejection reason. */ declare const RejectedPegoutReasons: { readonly 1: "LOW_AMOUNT"; readonly 2: "CALLER_CONTRACT"; readonly 3: "FEE_ABOVE_VALUE"; }; /** A human-readable reason a peg-out was rejected, as reported by the 2WP API. */ type RejectedPegoutReason = (typeof RejectedPegoutReasons)[keyof typeof RejectedPegoutReasons]; /** Bitcoin and Rootstock-side details of a peg-in transaction. */ interface PeginTxDetails { btc: { txId: string; creationDate: string; federationAddress: string; amountTransferred: number; fees: number; refundAddress: string; confirmations: number; requiredConfirmation: number; btcWTxId: string; senderAddress: string; }; rsk: { recipientAddress: string; }; status: PeginStatuses; } /** Details of a peg-out transaction, including its Bitcoin release once processed. */ interface PegoutTxDetails { originatingRskTxHash: string; rskTxHash: string; rskSenderAddress: string; btcRecipientAddress: string; valueRequestedInSatoshis: number; valueInSatoshisToBeReceived: number; feeInSatoshisToBePaid: number; status: PegoutStatuses; btcRawTransaction: string; reason?: RejectedPegoutReason; } /** Status payload for a peg-out transaction, as returned by {@link PowPegSDK.getTransactionStatus}. */ interface PegoutStatusData { type: TxType.PEGOUT; txDetails: PegoutTxDetails; } /** Status payload for a peg-in transaction, as returned by {@link PowPegSDK.getTransactionStatus}. */ interface PeginStatusData { type: TxType.PEGIN; txDetails: PeginTxDetails; } /** Discriminated union of the two possible {@link PowPegSDK.getTransactionStatus} payloads. */ type StatusData = PegoutStatusData | PeginStatusData; /** An unsigned, fee-funded peg-in PSBT ready to be signed, as returned by {@link PowPegSDK.createAndFundPegin}. */ interface UnsignedPegin { psbt: Psbt; inputs: Utxo[]; transactions: string[]; fee: number; } declare const supportedAddressTypes: { readonly 'NATIVE SEGWIT': { readonly path: "84"; readonly format: "bech32"; }; readonly SEGWIT: { readonly path: "49"; readonly format: "p2sh"; }; readonly LEGACY: { readonly path: "44"; readonly format: "legacy"; }; }; declare const networks: { readonly TEST: { readonly currency: "bitcoin_testnet"; readonly coin: "1"; readonly lib: networks$1.Network; readonly xpubVersion: 70617039; readonly isBtcAddress: typeof isBtcTestnetAddress; }; readonly MAIN: { readonly currency: "bitcoin"; readonly coin: "0"; readonly lib: networks$1.Network; readonly xpubVersion: 76067358; readonly isBtcAddress: typeof isBtcMainnetAddress; }; }; type AddressType = keyof typeof supportedAddressTypes; type Network = keyof typeof networks; /** * SDK for creating, funding, signing and broadcasting native PowPeg peg-in (BTC -> RBTC) * and peg-out (RBTC -> BTC) transactions. */ declare class PowPegSDK { private _bitcoinSigner; private _bitcoinDataSource; private network; private maxBundleSize; private burnDustValue; private maxFeeRateSatPerByte; private maxFeeToAmountRatio; private txHeaderSizeInBytes; private txOutputSizeInBytes; private txInputSizeInBytes; private pegInOutputs; private powpegRsktHeader; private burnDustMaxValue; private funding; private psbtSigner; private minPeginAmount; private peginFeeEstimationInputs; private minPegoutAmount; private btcNetworkConfig; private bridge; private api; private rskProvider; private publicNodes; /** * @param {BitcoinSigner | null} _bitcoinSigner - An instance of a class that implements the BitcoinSigner interface. * @param {BitcoinDataSource | null} _bitcoinDataSource - An instance of a class that implements the BitcoinDataSource interface or null if you won't use peg-in operations. * @param {Network} network - The network to use. Either 'MAIN' or 'TEST'. * @param {string} rpcProviderUrl - URL of either your own Rootstock node, the Rootstock RPC API or a third-party node provider. If not provided, it will default to the Rootstock public node for the specified network. * @param {string} apiUrl - The URL of the API to use. If not provided, it will default to the production 2WP API URL for the specified network and use it as BitcoinDataSource. * @param {number} maxBundleSize - The maximum number of addresses to ask for while creating a peg-in transaction. Defaults to 10. * @param {number} burnDustValue - The value in satoshis to consider as dust to burn. Defaults to 2000. * @param {number} maxFeeRateSatPerByte - Upper bound, in sat/B, for a fee rate coming from the configured BitcoinDataSource. Defaults to 1000. * @param {number} maxFeeToAmountRatio - Upper bound for the ratio of total fee to peg-in amount. Defaults to 0.5. */ constructor(_bitcoinSigner: BitcoinSigner | null, _bitcoinDataSource: BitcoinDataSource | null, network: Network, rpcProviderUrl?: string, apiUrl?: string, maxBundleSize?: number, burnDustValue?: number, maxFeeRateSatPerByte?: number, maxFeeToAmountRatio?: number); private get bitcoinSigner(); private set bitcoinSigner(value); private get bitcoinDataSource(); private getUtxos; private getAddressesWithDetails; private groupAddressesByUsage; private groupAddressesByBalance; private getAddressesGroupedByUsage; private validateRskRecipient; private getVerifiedFederationAddress; private getRskOutput; /** * Estimates the Bitcoin network fee (in satoshis) to pay for a peg-in transaction of the given amount. * @param {bigint} amount - Amount to peg in, in satoshis. * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. * @param {Utxo[]} [utxos] - UTXOs available to fund the peg-in. When provided, the estimate runs the * same input selection used to fund the transaction; otherwise it assumes a fixed number of inputs. * @returns {Promise} The estimated total fee in satoshis. */ estimatePeginFee(amount: bigint, feeLevel?: FeeLevel, utxos?: Utxo[]): Promise; /** * Builds an unsigned peg-in PSBT that sends `amount` satoshis to the federation's Bitcoin address, * encoding `recipientAddress` (and an unused refund address, if available) in an OP_RETURN output. * Also records the UTXOs and change address {@link fundPegin} will use to fund the transaction. * @param {bigint} amount - Amount to peg in, in satoshis. * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC. * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses. * @param {BitcoinSigner} [signer] - Signer to bind this PSBT to. Defaults to the signer configured in the constructor. * @returns {Promise} The unsigned, unfunded peg-in PSBT. */ createPegin(amount: bigint, recipientAddress: string, selectedUtxos?: Utxo[], signer?: BitcoinSigner): Promise; private selectInputs; private validatePeginAmount; private validateFeeRate; private getValidatedFeeRate; private calculatePeginFee; private calculateFeeAndSelectedInputs; /** * Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT, * using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}. * @param {Psbt} psbt - The peg-in PSBT to fund. * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. Ignored if `feeRate` is provided. * @param {bigint} [value] - Amount being sent, in satoshis. Defaults to the PSBT's second output value. * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently to pin funding to that exact value instead of risking a second, possibly different, fetch. * @returns {Promise} The funded PSBT along with its inputs, their raw transactions, and the total fee. */ fundPegin(psbt: Psbt, feeLevel?: FeeLevel, value?: bigint, feeRate?: number): Promise<{ psbt: Psbt; inputs: Utxo[]; transactions: string[]; fee: number; }>; /** * Convenience method that creates and funds a peg-in PSBT in one call. * @param {bigint} amount - Amount to peg in, in satoshis. * @param {string} recipientAddress - Rootstock address that will receive the pegged-in RBTC. * @param {BitcoinSigner} signer - Bitcoin signer used to derive the addresses funding this peg-in. * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. * @param {Utxo[]} [selectedUtxos] - UTXOs to fund the transaction with. If omitted, they're derived from the signer's used addresses. * @param {number} [feeRate] - Fee rate, in sat/B, to fund with. When omitted, a fresh rate is fetched from the configured `BitcoinDataSource` and validated. Pass a rate obtained independently (e.g. from a prior `estimatePeginFee` call) to pin funding to that exact value instead of risking a second, possibly different, fetch. * @returns {Promise} The funded, unsigned peg-in PSBT along with its inputs, raw transactions, and total fee. */ createAndFundPegin(amount: bigint, recipientAddress: string, signer: BitcoinSigner, feeLevel?: FeeLevel, selectedUtxos?: Utxo[], feeRate?: number): Promise; /** * Builds and funds a generic PSBT paying `amount` satoshis to `recipientAddress` using the given UTXOs, * without routing through the federation address (unlike {@link createPegin}). * @param {bigint} amount - Amount to send, in satoshis. * @param {string} recipientAddress - Bitcoin address to receive the payment. * @param {Utxo[]} utxos - UTXOs to fund the transaction with. * @param {FeeLevel} feeLevel - Fee priority level used to look up the current network fee rate. Defaults to `'fast'`. * @param {BitcoinSigner} [signer] - Signer to bind to the returned PSBT for {@link signAndBroadcastPegin}. Required to sign the result, since this method takes no signer otherwise. * @returns {Promise} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee. */ createAndFundPsbt(amount: bigint, recipientAddress: string, utxos: Utxo[], feeLevel?: FeeLevel, signer?: BitcoinSigner): Promise; private signPegin; /** * Signs a peg-in PSBT with the configured Bitcoin signer and broadcasts it via the configured data source. * @param {Psbt} psbt - The funded peg-in PSBT to sign and broadcast. * @param {Utxo[]} [inputs] - The PSBT's funding UTXOs (the `inputs` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT. * @param {string[]} [transactions] - Raw hex transactions for `inputs` (the `transactions` field returned by `fundPegin`/`createAndFundPegin`), forwarded to the signer if it needs them. Required for the bundled hardware-wallet signers (Ledger, Trezor); optional only for signers that can sign directly from the PSBT. * @returns {Promise} The broadcast transaction's ID. */ signAndBroadcastPegin(psbt: Psbt, inputs?: Utxo[], transactions?: string[]): Promise; private validateMinimumPegoutAmount; private createPegoutTransaction; /** * Estimates the Bitcoin and Rootstock fees for a peg-out of the given RBTC amount. * @param {string} amount - Amount to peg out, in RBTC (18 decimals). * @param {string} [fromAddress] - Rootstock sender address used to estimate gas. Defaults to the zero address. * @returns {Promise} The estimated Bitcoin fee (satoshis) and Rootstock gas fee (wei). */ estimatePegoutFees(amount: string, fromAddress?: string): Promise; /** * Validates the requested amount and the sender's balance, then builds an unsigned peg-out * transaction (a value-transfer call to the bridge precompile) together with its estimated fees. * @param {string} amount - Amount to peg out, in RBTC (18 decimals). * @param {string} senderAccount - Rootstock address that will send the peg-out. * @returns The unsigned transaction request and its estimated Bitcoin/Rootstock fees. * @throws {NotEnoughFundsError} If `senderAccount`'s balance is lower than `amount`. */ createPegout(amount: string, senderAccount: string): Promise<{ tx: { from: string; to: string; value: string; }; rootstockFee: bigint; bitcoinFee: bigint; }>; /** * Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer * and waits for it to be mined. * @param {{ from: string, to: string, value: string }} tx - The peg-out transaction request. * @param {ethers.Signer} signer - Ethers signer used to send the transaction. * @returns The mined transaction receipt, if the signer's provider is set. */ signAndBroadcastPegout(tx: { from: string; to: string; value: string; }, signer: ethers.Signer): Promise; /** * Fetches the current status of a peg-in or peg-out transaction from the configured API. * @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up. * @param {T} txType - Whether `txHash` is a peg-in or a peg-out transaction. * @returns {Promise>} The transaction's type-narrowed status details. */ getTransactionStatus(txHash: string, txType: T): Promise | Extract>; /** * Retrieves the feature flags from the 2WP API `/features` endpoint. * @returns {Promise} The feature flags as returned by the API. */ getFeatures(): Promise; /** * Returns the spendable UTXOs for the given Bitcoin address(es). * @param {string | string[]} addresses - One or more Bitcoin addresses to fetch UTXOs for. * @returns {Promise} The UTXOs available across the given address(es). * @throws {InvalidAddressError} If any address doesn't belong to the SDK's configured network. */ getAvailableUtxos(addresses: string | string[]): Promise; } /** {@link BitcoinSigner} backed by a Trezor hardware wallet, connected via `@trezor/connect-web`. */ declare class TrezorSigner implements BitcoinSigner { private readonly network; private _addressType; private readonly bitcoinTxVersion; private readonly addresses; private constructor(); /** * Initializes the Trezor connection and returns a ready-to-use signer. * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`. * @param {Partial[0]>} [initOptions] - Extra options merged into the `TrezorConnect.init` call. * @returns {Promise} The initialized signer. */ static init(network?: Network, initOptions?: Partial[0]>): Promise; /** * Disposes the current Trezor connection and re-initializes it. * @returns {Promise} A freshly initialized signer for the default (`'TEST'`) network. */ static reinit(): Promise; /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */ set addressType(addressType: AddressType); get addressType(): AddressType; private getPathPurpose; private getPathCoin; private getAddresses; /** * @param {number} bundleSize - Number of change addresses to derive. * @returns {Promise} `bundleSize` change addresses derived from the Trezor device. */ getChangeAddresses(bundleSize: number): Promise; /** * @param {number} bundleSize - Number of receive addresses to derive. * @returns {Promise} `bundleSize` receive (non-change) addresses derived from the Trezor device. */ getNonChangeAddresses(bundleSize: number): Promise; private getScriptType; private getInputs; private getOutputScriptType; private isChangePath; private getOutputs; /** * Signs the given PSBT's inputs/outputs on the Trezor device. * @param {Psbt} psbt - The PSBT to sign. * @param {Utxo[]} [utxos] - The PSBT's inputs, used to look up each input's derivation path and script type. Required — TrezorSigner cannot sign from the PSBT alone. * @returns {Promise} The serialized signed transaction, or an empty string if signing didn't succeed. */ signTransaction(psbt: Psbt, utxos?: Utxo[]): Promise; } /** * {@link BitcoinSigner} backed by a Ledger hardware wallet, connected over WebUSB. * Device operations are queued so only one runs against the transport at a time. */ declare class LedgerSigner implements BitcoinSigner { private readonly connection; private readonly transport; private readonly network; private _addressType; private readonly addresses; private readonly transportService; private constructor(); /** * Opens a WebUSB transport to a connected Ledger device and returns a ready-to-use signer. * @param {Network} [network] - The network to derive addresses for. Defaults to `'TEST'`. * @returns {Promise} The initialized signer. */ static init(network?: Network): Promise; /** * Closes and reopens the WebUSB transport to the Ledger device, queued behind any in-flight operation. * @returns {Promise} A freshly initialized signer for the default (`'TEST'`) network. */ reinit(): Promise; /** The Bitcoin address type used to derive addresses (`'LEGACY'`, `'SEGWIT'` or `'NATIVE SEGWIT'`). */ set addressType(addressType: AddressType); get addressType(): AddressType; private getPathPurpose; private getPathCoin; private getAddressFormat; private getXpubVersion; private isSegwit; getAddresses(bundleSize: number, change?: boolean): Promise; /** * @param {number} bundleSize - Number of change addresses to derive. * @returns {Promise} `bundleSize` change addresses derived from the Ledger device. */ getChangeAddresses(bundleSize: number): Promise; /** * @param {number} bundleSize - Number of receive addresses to derive. * @returns {Promise} `bundleSize` receive (non-change) addresses derived from the Ledger device. */ getNonChangeAddresses(bundleSize: number): Promise; getInputs(inputs: Utxo[], transactions: string[]): CreateTransactionArg['inputs']; private isChangePath; private getChangePath; getOutputScriptHex(psbt: Psbt): string; /** * Signs the given PSBT on the Ledger device, queued behind any in-flight operation. * @param {Psbt} psbt - The PSBT to sign. * @param {Utxo[]} [inputs] - The PSBT's inputs, used to look up each input's previously derived address path. Required — LedgerSigner cannot sign from the PSBT alone. * @param {string[]} [transactions] - Raw hex transactions for `inputs`, required by the Ledger app to verify each input. * @returns {Promise} The signed, serialized transaction. */ signTransaction(psbt: Psbt, inputs?: Utxo[], transactions?: string[]): Promise; } /** Thrown when a requested peg-in or peg-out amount is below the protocol's minimum allowed amount. */ declare class AmountBelowMinError extends Error { constructor(message?: string); } /** Thrown when the available UTXOs/balance can't cover the requested amount plus fees. */ declare class NotEnoughFundsError extends Error { constructor(message?: string); } /** Thrown when the 2WP API responds with an error, a failed request, or an unexpected failure. */ declare class APIError extends Error { readonly statusCode?: number; readonly data?: unknown; constructor(message: string, statusCode?: number, data?: unknown); } /** Thrown when the federation address can't be retrieved from the pegin configuration endpoint or doesn't match the Bridge contract's value. */ declare class FederationAddressError extends Error { constructor(message?: string); } /** Thrown when one or more addresses are invalid: a Bitcoin address that doesn't belong to the SDK's configured network, or a malformed Rootstock recipient address. */ declare class InvalidAddressError extends Error { readonly invalidAddresses: string[]; constructor(invalidAddresses: string[], message?: string); } /** Thrown when a fee rate from the configured BitcoinDataSource is missing, non-numeric, non-positive, exceeds the configured bound, or produces a fee disproportionate to the amount being sent. */ declare class InvalidFeeRateError extends Error { constructor(message?: string); } export { APIError, type AddressWithDetails, AmountBelowMinError, type BitcoinDataSource, type BitcoinSigner, type Feature, FederationAddressError, type FeeLevel, InvalidAddressError, InvalidFeeRateError, LedgerSigner, NotEnoughFundsError, type PeginStatusData, PeginStatuses, type PeginTxDetails, type PegoutFeeEstimation, type PegoutStatusData, PegoutStatuses, type PegoutTxDetails, PowPegSDK, type RejectedPegoutReason, RejectedPegoutReasons, type StatusData, type SupportedBrowsers, TrezorSigner, TxType, type UnsignedPegin, type Utxo };