import { NitroModules } from 'react-native-nitro-modules'; import type { NitroArk, BarkCreateOpts, RestoreWalletResult as NitroRestoreWalletResult, BarkArkInfo, WalletDebugInfo, Bolt11Invoice, BarkSendManyOutput, ArkoorPaymentResult, OffboardResult, ParsedPaymentRequest as NitroParsedPaymentRequest, PaymentRequestOption as NitroPaymentRequestOption, BarkFeeEstimate, ExitFeeEstimate, BarkFeeRates, OnchainTransactionInfo, ExitProgressStatusResult as NitroExitProgressStatusResult, ExitVtxoResult as NitroExitVtxoResult, ExitStatusResult as NitroExitStatusResult, ExitBlockRefResult as NitroExitBlockRefResult, ExitTxOriginResult as NitroExitTxOriginResult, ExitTxStatusResult as NitroExitTxStatusResult, ExitTxResult as NitroExitTxResult, ExitStateDetailsResult as NitroExitStateDetailsResult, ExitTransactionPackageResult as NitroExitTransactionPackageResult, LightningPaymentResult, OnchainPaymentResult, OffchainBalanceResult, OnchainBalanceResult, NewAddressResult, KeyPairResult, MailboxAuthorizationResult, LightningReceive as NitroLightningReceive, BarkNotificationEvent as NitroBarkNotificationEvent, BarkNotificationSubscription, BarkMovement as NitroBarkMovement, BarkMovementDestination as NitroBarkMovementDestination, BoardResult, PendingRoundStatus as NitroPendingRoundStatus, DelegatedRoundState, WalletSnapshotInfo, WalletSnapshotExpectation, WalletStateChangeEvent as NitroWalletStateChangeEvent, WalletStateChangeSubscription, } from './NitroArk.nitro'; export type VtxoState = 'Spendable' | 'Spent' | 'Locked' | 'Exited' | 'unknown'; export type RestoreWalletResult = Omit & { status: 'completed' | 'failed'; }; export type BarkVtxo = { id: string; amount: number; // u64 expiry_height: number; // u32 server_pubkey: string; exit_delta: number; // u16 anchor_point: string; point: string; state: VtxoState; }; export type MovementStatus = 'pending' | 'successful' | 'failed' | 'canceled'; export type ExitProgressState = | 'Start' | 'Processing' | 'AwaitingDelta' | 'Claimable' | 'ClaimInProgress' | 'Claimed' | 'VtxoAlreadySpent' | 'VtxoSwept' | 'Canceled'; export type ExitStateKind = | 'start' | 'processing' | 'awaiting-delta' | 'claimable' | 'claim-in-progress' | 'claimed' | 'vtxo-already-spent' | 'vtxo-swept' | 'canceled'; export type BlockRef = NitroExitBlockRefResult; export type ExitTxOrigin = NitroExitTxOriginResult; export type ExitTxStatus = NitroExitTxStatusResult; export type ExitTx = NitroExitTxResult; /** Swept exits include spent_inputs as txid:vout strings in current and historical details. */ export type ExitStateDetails = Omit & { kind: ExitStateKind; }; export type ExitProgressStatusResult = Omit< NitroExitProgressStatusResult, 'state' | 'state_details' > & { state: ExitProgressState; state_details: ExitStateDetails; }; export type ExitVtxoResult = Omit< NitroExitVtxoResult, 'state' | 'state_details' | 'history' | 'history_details' > & { state: ExitProgressState; state_details: ExitStateDetails; history: ExitProgressState[]; history_details: ExitStateDetails[]; }; export type ExitTransactionPackageResult = NitroExitTransactionPackageResult; export type ExitStatusResult = Omit< NitroExitStatusResult, 'state' | 'state_details' | 'history' | 'history_details' > & { state: ExitProgressState; state_details: ExitStateDetails; history: ExitProgressState[]; history_details: ExitStateDetails[]; transactions: ExitTransactionPackageResult[]; }; export type LightningReceivePhase = | 'awaiting_payment' | 'htlcs_ready' | 'preimage_revealed' | 'delivering'; type LightningReceiveBase = Omit; export type LightningReceive = | (LightningReceiveBase & { state: 'in_progress'; phase: LightningReceivePhase; amount_sat?: undefined; settled_at?: undefined; }) | (LightningReceiveBase & { state: 'settled'; phase?: undefined; amount_sat: number; settled_at: number; }); export type PaymentMethodType = | 'ark' | 'bitcoin' | 'output-script' | 'invoice' | 'offer' | 'lightning-address' | 'lnurl' | 'custom'; export type BarkMovementDestination = NitroBarkMovementDestination & { payment_method: PaymentMethodType; }; export type PaymentRequestOption = NitroPaymentRequestOption & { method_type: PaymentMethodType; }; export type ParsedPaymentRequest = Omit< NitroParsedPaymentRequest, 'options' > & { options: PaymentRequestOption[]; }; export type BarkMovement = NitroBarkMovement & { status: MovementStatus; sent_to: BarkMovementDestination[]; received_on: BarkMovementDestination[]; }; export type RoundStatus = | 'pending' | 'unconfirmed' | 'confirmed' | 'failed' | 'canceled'; export type PendingRoundStatus = Omit & { status: RoundStatus; }; export type BarkNotificationKind = | 'movementCreated' | 'movementUpdated' | 'channelLagging'; export type BarkNotificationEvent = Omit< NitroBarkNotificationEvent, 'kind' | 'movement' > & { kind: BarkNotificationKind; movement?: BarkMovement; }; export type WalletStateChangeReason = | 'initial' | 'databaseChanged' | 'resyncRequired'; export type WalletStateChangeEvent = Omit< NitroWalletStateChangeEvent, 'reason' > & { reason: WalletStateChangeReason; }; export type { WalletSnapshotInfo, WalletSnapshotExpectation, WalletStateChangeSubscription, }; export type LightningPaymentState = | 'unknown' | 'in_progress' | 'paid' | 'revocation_stuck'; export type LightningPayment = Omit & { state: LightningPaymentState; }; /** * A user-facing payment identifier that has already been resolved to a * Lightning invoice. `custom` preserves protocols Bark does not model * natively while still recording their original identifier. */ export type LightningPaymentOrigin = | { method: 'lightning-address'; value: string } | { method: 'lnurl'; value: string } | { method: 'custom'; value: string }; export const NitroArkHybridObject = NitroModules.createHybridObject('NitroArk'); function enrichExitProgressStatus( result: NitroExitProgressStatusResult ): ExitProgressStatusResult { const { state, state_details, ...rest } = result; return { ...rest, state: state as ExitProgressState, state_details: { ...state_details, kind: state_details.kind as ExitStateKind, }, }; } function enrichExitVtxo(result: NitroExitVtxoResult): ExitVtxoResult { const { state, state_details, history: stateHistory, history_details, ...rest } = result; return { ...rest, state: state as ExitProgressState, state_details: { ...state_details, kind: state_details.kind as ExitStateKind, }, history: stateHistory as ExitProgressState[], history_details: history_details.map((details) => ({ ...details, kind: details.kind as ExitStateKind, })), }; } function enrichExitStatus(result: NitroExitStatusResult): ExitStatusResult { const { state, state_details, history: stateHistory, history_details, ...rest } = result; return { ...rest, state: state as ExitProgressState, state_details: { ...state_details, kind: state_details.kind as ExitStateKind, }, history: stateHistory as ExitProgressState[], history_details: history_details.map((details) => ({ ...details, kind: details.kind as ExitStateKind, })), }; } function enrichLightningReceive( result: NitroLightningReceive ): LightningReceive { return result as LightningReceive; } // --- Management --- /** Returns the semver of the Bark wallet library compiled into the native module. */ export function getBarkVersion(): string { return NitroArkHybridObject.getBarkVersion(); } /** * Creates a new BIP39 mnemonic phrase. * @returns A promise resolving to the mnemonic string. */ export function createMnemonic(): Promise { return NitroArkHybridObject.createMnemonic(); } /** * Creates a new wallet at the specified directory. * @param datadir Path to the data directory. * @param opts The options for wallet creation. * @returns A promise that resolves on success or rejects on error. */ export function createWallet( datadir: string, opts: BarkCreateOpts ): Promise { return NitroArkHybridObject.createWallet(datadir, opts); } /** * Loads an existing wallet or creates a new one at the specified directory. * Once loaded, the wallet state is managed internally. * @param datadir Path to the data directory. * @param config The configuration options for the wallet. * @returns A promise that resolves on success or rejects on error. */ export function loadWallet( datadir: string, config: BarkCreateOpts ): Promise { return NitroArkHybridObject.loadWallet(datadir, config); } /** * Opens a fresh wallet and restores seed-linked VTXOs from the Ark server. * Requires a new or empty directory and no loaded wallet. Initialization errors * reject; preserve any data written. A resolved result leaves the wallet loaded, * even when status is failed. Completed means the scan finished: also inspect * report.is_complete. The report covers the seed scan, not delegated round sync. * Recovery trusts the server; onchainSync remains a separate operation. */ export async function restoreWalletFromArkServer( datadir: string, opts: BarkCreateOpts ): Promise { return (await NitroArkHybridObject.restoreWalletFromArkServer( datadir, opts )) as RestoreWalletResult; } /** * Closes the currently loaded wallet, clearing its state from memory. * @returns A promise that resolves on success or rejects on error. */ export function closeWallet(): Promise { return NitroArkHybridObject.closeWallet(); } /** * Creates a transactionally consistent SQLite snapshot of the loaded wallet. * The destination must not already exist. */ export function createWalletSnapshot( destinationPath: string ): Promise { return NitroArkHybridObject.createWalletSnapshot(destinationPath); } /** * Validates a wallet snapshot without modifying it. When expected identity * fields are omitted, the loaded wallet identity is used when available. */ export function validateWalletSnapshot( path: string, expected?: WalletSnapshotExpectation ): Promise { return NitroArkHybridObject.validateWalletSnapshot(path, expected); } /** * Observes committed native SQLite changes. Sequence values are local to this * subscription and reset when a new subscription is created. */ export function subscribeWalletStateChanges( onEvent: (event: WalletStateChangeEvent) => void ): WalletStateChangeSubscription { return NitroArkHybridObject.subscribeWalletStateChanges( onEvent as (event: NitroWalletStateChangeEvent) => void ); } /** * Refreshes the server state. * @returns A promise that resolves on success or rejects on error. */ export function refreshServer(): Promise { return NitroArkHybridObject.refreshServer(); } /** * Checks if a wallet is currently loaded. * @returns A promise resolving to true if a wallet is loaded, false otherwise. */ export function isWalletLoaded(): Promise { return NitroArkHybridObject.isWalletLoaded(); } /** * Registers all confirmed boards with the server. * @returns A promise that resolves on success. */ export function syncPendingBoards(): Promise { return NitroArkHybridObject.syncPendingBoards(); } /** Runs wallet maintenance, including on-chain synchronization and exit progression. */ export function maintenance(): Promise { return NitroArkHybridObject.maintenance(); } /** Runs delegated wallet maintenance, including on-chain synchronization. */ export function maintenanceDelegated(): Promise { return NitroArkHybridObject.maintenanceDelegated(); } /** * Refreshes vtxos that need to be refreshed. * @returns A promise that resolves on success. */ export function maintenanceRefresh(): Promise { return NitroArkHybridObject.maintenanceRefresh(); } /** * Refreshes the provided VTXOs in delegated mode. * @param vtxoIds Array of VTXO ID strings to refresh. * @returns A pending round state reference, or undefined if no VTXOs needed refresh. */ export function refreshVtxosDelegated( vtxoIds: string[] ): Promise { return NitroArkHybridObject.refreshVtxosDelegated(vtxoIds); } /** * Synchronizes the wallet with the blockchain. * @returns A promise that resolves on success. */ export function sync(): Promise { return NitroArkHybridObject.sync(); } /** * Starts unilateral exits for all eligible wallet VTXOs. * @returns A promise that resolves on success. */ export function startExitForEntireWallet(): Promise { return NitroArkHybridObject.startExitForEntireWallet(); } /** * Starts unilateral exits for selected wallet VTXOs. * @param vtxoIds VTXO IDs to exit. * @returns A promise that resolves on success. */ export function startExitForVtxos(vtxoIds: string[]): Promise { return NitroArkHybridObject.startExitForVtxos(vtxoIds); } /** * Cancels a unilateral exit while its final transaction is still unbroadcast. * The VTXO remains spendable and can be exited again later. * @param vtxoId VTXO ID whose exit should be canceled. * @returns A promise that resolves on success. */ export function cancelExit(vtxoId: string): Promise { return NitroArkHybridObject.cancelExit(vtxoId); } /** * Synchronizes the exit coordinator state. * @returns A promise that resolves on success. */ export function syncExit(): Promise { return NitroArkHybridObject.syncExit(); } /** * Progresses tracked exits by one step. * @param feeRateSatPerKvb Optional fee rate override in sat/kvB. * @returns A promise resolving to simplified exit progress entries. */ export function progressExits( feeRateSatPerKvb?: number ): Promise { return NitroArkHybridObject.progressExits(feeRateSatPerKvb).then((results) => results.map(enrichExitProgressStatus) ); } /** * Estimates the onchain fees required to unilaterally exit selected VTXOs. * Call syncExit() first when fresh chain and mempool state is required. * Estimating does not start or progress an exit and works before funding the onchain wallet. * @param vtxoIds VTXO IDs to include in the emergency exit estimate. * @param feeRateSatPerKvb Optional nonnegative safe integer in sat/kvB, applied to both fee legs. * @param destinationAddress Optional claim destination, which affects the claim transaction weight. * @param feeMargin Optional finite, nonnegative broadcast-fee multiplier. Defaults to 1.2; * 1.0 adds no margin, and 0 produces a zero broadcast estimate. The claim fee is unchanged. * @returns A promise resolving to the CPFP broadcast and later claim fee breakdown. */ export function estimateEmergencyExitFee( vtxoIds: string[], feeRateSatPerKvb?: number, destinationAddress?: string, feeMargin?: number ): Promise { return NitroArkHybridObject.estimateEmergencyExitFee( vtxoIds, feeRateSatPerKvb, destinationAddress, feeMargin ); } /** * Lists all unilateral exits currently tracked by the wallet. * @returns A promise resolving to simplified exit entries. */ export function getExitVtxos(): Promise { return NitroArkHybridObject.getExitVtxos().then((results) => results.map(enrichExitVtxo) ); } /** * Lists tracked unilateral exits that are claimable. * @returns A promise resolving to claimable exit entries. */ export function listClaimable(): Promise { return NitroArkHybridObject.listClaimable().then((results) => results.map(enrichExitVtxo) ); } /** * Gets the detailed unilateral exit status for a tracked VTXO. * @param vtxoId Exit VTXO ID to inspect. * @param includeHistory Whether to include the state transition history. * @param includeTransactions Whether to include exit transaction packages as hex. * @returns A promise resolving to the exit status, or undefined when the VTXO is not tracked as an exit. */ export function getExitStatus( vtxoId: string, includeHistory?: boolean, includeTransactions?: boolean ): Promise { return NitroArkHybridObject.getExitStatus( vtxoId, includeHistory, includeTransactions ).then((result) => (result ? enrichExitStatus(result) : undefined)); } /** * Checks whether the wallet has exits that are still pending. * @returns A promise resolving to true when any tracked exit is not yet claimable. */ export function hasPendingExits(): Promise { return NitroArkHybridObject.hasPendingExits(); } /** * Returns sats whose exit committed onchain and which have not been claimed yet. * Matches offchainBalance().pending_exit; cancelable exits are excluded. * @returns A promise resolving to the pending exit total in satoshis. */ export function pendingExitTotal(): Promise { return NitroArkHybridObject.pendingExitTotal(); } /** * Returns the earliest block height at which all tracked exits are claimable. * @returns A promise resolving to the claimable height, or undefined if not known yet. */ export function allClaimableAtHeight(): Promise { return NitroArkHybridObject.allClaimableAtHeight(); } /** * Builds a base64 PSBT that drains the selected claimable exits to an onchain address. * @param vtxoIds Exit VTXO IDs to claim. * @param destinationAddress Destination onchain address. * @param feeRateSatPerKvb Optional fee rate override in sat/kvB. * @returns A promise resolving to a base64-encoded PSBT. */ export function drainExits( vtxoIds: string[], destinationAddress: string, feeRateSatPerKvb?: number ): Promise { return NitroArkHybridObject.drainExits( vtxoIds, destinationAddress, feeRateSatPerKvb ); } /** * Extracts a raw transaction from a base64 PSBT. * @param psbt Base64-encoded PSBT. * @returns A promise resolving to transaction hex. */ export function extractTransaction(psbt: string): Promise { return NitroArkHybridObject.extractTransaction(psbt); } /** * Broadcasts a raw transaction to the configured blockchain backend. * @param txHex Raw transaction hex. * @returns A promise resolving to the broadcast transaction ID. */ export function broadcastTransaction(txHex: string): Promise { return NitroArkHybridObject.broadcastTransaction(txHex); } /** * Synchronizes pending rounds. * @returns A promise resolving to the statuses returned by Bark for synced pending rounds. */ export function syncPendingRounds(): Promise { return NitroArkHybridObject.syncPendingRounds() as Promise< PendingRoundStatus[] >; } // --- Wallet Info --- /** * Gets the Ark-specific information. * @returns A promise resolving to the BarkArkInfo object. */ export function getArkInfo(): Promise { return NitroArkHybridObject.getArkInfo(); } /** * Gets the offchain balance for the loaded wallet. * All values are satoshis. Use spendable for available funds and total for * funds owned; pending and total overlap the individual pending categories. * Call sync() first to update the wallet state. * @returns A promise resolving to the OffchainBalanceResult object. */ export function offchainBalance(): Promise { return NitroArkHybridObject.offchainBalance(); } /** * Returns the loaded wallet's network, mailbox ID and VTXO extended public key. * Uses local wallet data; rejects if no wallet is loaded. */ export function debugInfo(): Promise { return NitroArkHybridObject.debugInfo(); } /** * Derives the next keypair for the store. * @returns A promise resolving to the KeyPairResult object. */ export function deriveStoreNextKeypair(): Promise { return NitroArkHybridObject.deriveStoreNextKeypair(); } /** * Peeks the wallet's VTXO public key (hex string). * @param index Index of the VTXO pubkey to retrieve. * @returns A promise resolving to the KeyPairResult object. */ export function peekKeyPair(index: number): Promise { return NitroArkHybridObject.peekKeyPair(index); } /** * Peeks a derived address without advancing the wallet's address index. * @param index Index of the address to preview. * @returns A promise resolving to the NewAddressResult object. */ export function peekAddress(index: number): Promise { return NitroArkHybridObject.peekAddress(index); } /** * Gets the wallet's Address. * @returns A promise resolving to NewAddressResult object. */ export function newAddress(): Promise { return NitroArkHybridObject.newAddress(); } /** * Signs a message with the private key at the specified index. * @param message The message to sign. * @param index The index of the keypair to use for signing. * @returns A promise resolving to the signature string. */ export function signMessage(message: string, index: number): Promise { return NitroArkHybridObject.signMessage(message, index); } /** * Signs a message with the private key at the specified index. * @param message The message to sign. * @param mnemonic The BIP39 mnemonic phrase to use for signing. * @param network The network to use for signing. * @param index The index of the keypair to use for signing. * @returns A promise resolving to the signature string. */ export function signMesssageWithMnemonic( message: string, mnemonic: string, network: string, index: number ): Promise { return NitroArkHybridObject.signMesssageWithMnemonic( message, mnemonic, network, index ); } /** * Derives a keypair from a mnemonic. * @param mnemonic The mnemonic to derive the keypair from. * @param network The network to derive the keypair for. * @param index The index to derive the keypair from. * @returns A promise resolving to the KeyPairResult object. */ export function deriveKeypairFromMnemonic( mnemonic: string, network: string, index: number ): Promise { return NitroArkHybridObject.deriveKeypairFromMnemonic( mnemonic, network, index ); } /** * Verifies a signed message. * @param message The original message. * @param signature The signature to verify. * @param publicKey The public key corresponding to the private key used for signing. * @returns A promise resolving to true if the signature is valid, false otherwise. */ export function verifyMessage( message: string, signature: string, publicKey: string ): Promise { return NitroArkHybridObject.verifyMessage(message, signature, publicKey); } /** * Gets the mailbox keypair for the loaded wallet. * @returns A promise resolving to a KeyPairResult object. */ export function mailboxKeypair(): Promise { return NitroArkHybridObject.mailboxKeypair() as Promise; } /** * Gets a mailbox authorization for the loaded wallet. * @param authorizationExpiry Unix timestamp (seconds) for when the authorization expires. * @returns A promise resolving to a MailboxAuthorizationResult object. */ export function mailboxAuthorization( authorizationExpiry: number ): Promise { return NitroArkHybridObject.mailboxAuthorization( authorizationExpiry ) as Promise; } /** * Subscribes to all Bark wallet notifications. * @param onEvent Callback invoked whenever a notification is emitted. * @returns A subscription handle that can be stopped. */ export function subscribeNotifications( onEvent: (event: BarkNotificationEvent) => void ): BarkNotificationSubscription { return NitroArkHybridObject.subscribeNotifications( onEvent as (event: NitroBarkNotificationEvent) => void ); } /** * Subscribes to notifications related to a specific Arkoor address. * @param address Arkoor address to filter by. * @param onEvent Callback invoked whenever a matching notification is emitted. * @returns A subscription handle that can be stopped. */ export function subscribeArkoorAddressMovements( address: string, onEvent: (event: BarkNotificationEvent) => void ): BarkNotificationSubscription { return NitroArkHybridObject.subscribeArkoorAddressMovements( address, onEvent as (event: NitroBarkNotificationEvent) => void ); } /** * Subscribes to notifications related to a specific Lightning payment hash. * @param paymentHash Lightning payment hash to filter by. * @param onEvent Callback invoked whenever a matching notification is emitted. * @returns A subscription handle that can be stopped. */ export function subscribeLightningPaymentMovements( paymentHash: string, onEvent: (event: BarkNotificationEvent) => void ): BarkNotificationSubscription { return NitroArkHybridObject.subscribeLightningPaymentMovements( paymentHash, onEvent as (event: NitroBarkNotificationEvent) => void ); } /** * Gets a paginated list of wallet history (balance changes). * @returns A promise resolving to an array of BarkMovement objects. */ export function history(): Promise { return NitroArkHybridObject.history() as Promise; } /** * Applies an RFC 7396 JSON Merge Patch to a wallet movement's metadata. * The patch must serialize to a JSON object no larger than 16 KiB. * @param movementId The Bark movement ID. * @param patchJson The JSON object merge patch. * @returns A promise that resolves after Bark persists the updated metadata. */ export function updateHistoryMetadata( movementId: number, patchJson: string ): Promise { if ( !Number.isFinite(movementId) || !Number.isInteger(movementId) || movementId < 0 || movementId > 0xffffffff ) { throw new RangeError('movementId must be a finite unsigned 32-bit integer'); } return NitroArkHybridObject.updateHistoryMetadata(movementId, patchJson); } /** * Gets the list of VTXOs as a JSON string for the loaded wallet. * @param no_sync If true, skips synchronization with the blockchain. Defaults to false. * @returns A promise resolving BarkVtxo[] array. */ export function vtxos(): Promise { return NitroArkHybridObject.vtxos() as Promise; } /** * Decodes a serialized VTXO hex string into a BarkVtxo-like object. * The decoded VTXO is not loaded from the wallet, so state is "unknown". * @param vtxoHex Hex-encoded serialized VTXO. * @returns A promise resolving BarkVtxo. */ export function decodeVtxoHex(vtxoHex: string): Promise { return NitroArkHybridObject.decodeVtxoHex(vtxoHex) as Promise; } /** * Imports a serialized VTXO hex string into the loaded wallet. * Uses the configured VTXO key gap limit and checks the server's spend state. * Already-spent VTXOs are imported as spent rather than spendable. * @param vtxoHex Hex-encoded serialized VTXO. * @returns A promise resolving the imported wallet VTXO. */ export function importVtxo(vtxoHex: string): Promise { return NitroArkHybridObject.importVtxo(vtxoHex) as Promise; } /** * Destructively removes a VTXO from the local wallet database. * This can cause loss of funds if used incorrectly. * @param vtxoId VTXO ID to remove. * @returns A promise that resolves on success. */ export function dangerousDropVtxo(vtxoId: string): Promise { return NitroArkHybridObject.dangerousDropVtxo(vtxoId); } /** * Unlocks ownerless VTXO locks and returns those VTXOs to the spendable state. * VTXOs held by wallet subsystems or without an ownerless lock are left unchanged. * Malformed IDs reject the batch before any VTXOs are unlocked. * @param vtxoIds VTXO IDs to unlock. */ export function unlockVtxos(vtxoIds: string[]): Promise { return NitroArkHybridObject.unlockVtxos(vtxoIds); } /** * Gets the first expiring VTXO blockheight for the loaded wallet. * @returns A promise resolving to the first expiring VTXO blockheight. */ export function getFirstExpiringVtxoBlockheight(): Promise { return NitroArkHybridObject.getFirstExpiringVtxoBlockheight(); } /** * Gets the next required refresh blockheight for the loaded wallet for the first expiring VTXO. * @returns A promise resolving to the next required refresh blockheight. */ export function getNextRequiredRefreshBlockheight(): Promise< number | undefined > { return NitroArkHybridObject.getNextRequiredRefreshBlockheight(); } /** * Gets the list of expiring VTXOs as a JSON Object of type BarkVtxo. * @param threshold Number of blocks ahead to check for expiring VTXOs (0–65535). * @returns A promise resolving BarkVtxo[] array. */ export function getExpiringVtxos(threshold: number): Promise { return NitroArkHybridObject.getExpiringVtxos(threshold) as Promise< BarkVtxo[] >; } // --- Onchain Operations --- /** * Gets the onchain balance for the loaded wallet. * @returns A promise resolving to the OnchainBalanceResult object. */ export function onchainBalance(): Promise { return NitroArkHybridObject.onchainBalance(); } /** * Synchronizes the onchain state of the wallet. * @returns A promise that resolves on success. */ export function onchainSync(): Promise { return NitroArkHybridObject.onchainSync(); } /** * Gets the list of unspent onchain outputs as a JSON Object of type BarkVtxo. * @returns A promise resolving to the JSON string of unspent outputs. */ export function onchainListUnspent(): Promise { return NitroArkHybridObject.onchainListUnspent(); } /** * Gets the list of onchain UTXOs as a JSON string for the loaded wallet. * @returns A promise resolving to the JSON string of UTXOs. */ export function onchainUtxos(): Promise { return NitroArkHybridObject.onchainUtxos(); } /** * Gets recommended onchain fee rates in sat/vB for the loaded wallet. * @returns A promise resolving to fast, regular, and slow fee rates. */ export function onchainFeeRates(): Promise { return NitroArkHybridObject.onchainFeeRates(); } /** * Gets BDK onchain wallet transaction history. * @returns A promise resolving to onchain transaction entries. */ export function onchainTransactions(): Promise { return NitroArkHybridObject.onchainTransactions(); } /** * Gets a fresh onchain address for the loaded wallet. * @returns A promise resolving to the Bitcoin address string. */ export function onchainAddress(): Promise { return NitroArkHybridObject.onchainAddress(); } export function onchainIsMine(address: string): Promise { return NitroArkHybridObject.onchainIsMine(address); } /** * Sends funds using the onchain wallet. * @param destination The destination Bitcoin address. * @param amountSat The amount to send in satoshis. * @returns A promise resolving to the OnchainPaymentResult object */ export function onchainSend( destination: string, amountSat: number ): Promise { return NitroArkHybridObject.onchainSend(destination, amountSat); } /** * Sends all funds from the onchain wallet to a destination address. * @param destination The destination Bitcoin address. * @returns A promise resolving to the transaction ID string. */ export function onchainDrain(destination: string): Promise { return NitroArkHybridObject.onchainDrain(destination); } /** * Sends funds to multiple recipients using the onchain wallet. * @param outputs An array of objects containing destination address and amountSat. * @returns A promise resolving to the transaction ID string. */ export function onchainSendMany( outputs: BarkSendManyOutput[] ): Promise { return NitroArkHybridObject.onchainSendMany(outputs); } // --- Lightning Operations --- /** * Creates a Bolt 11 invoice. * @param amountSat The amount in satoshis for the invoice. * @param description Optional invoice description/memo. * @returns A promise resolving to Bolt11Invoice object. */ export function bolt11Invoice( amountSat: number, description?: string, token?: string ): Promise { return NitroArkHybridObject.bolt11Invoice(amountSat, description, token); } /** * Gets the status of a Lightning receive. * @param paymentHash The payment hash of the Lightning receive. * @returns A promise resolving to the Lightning receive status. */ export function lightningReceiveStatus( paymentHash: string ): Promise { return NitroArkHybridObject.lightningReceiveStatus(paymentHash).then( enrichLightningReceive ); } /** * Checks a Lightning payment and optionally waits for completion. * @param paymentHash The payment hash of the Lightning payment. * @param wait Whether to wait for the payment to complete. * @returns A promise resolving to the current Lightning payment state. */ export function checkLightningPayment( paymentHash: string, wait: boolean ): Promise { return NitroArkHybridObject.checkLightningPayment(paymentHash, wait).then( (result) => ({ ...result, state: result.state as LightningPaymentState, }) ); } /** * Attempts to claim a Lightning payment. * @param paymentHash The payment hash of the Lightning payment. * @param wait Whether to wait for the claim to complete. * @returns A promise resolving to the current Lightning receive state. */ export function tryClaimLightningReceive( paymentHash: string, wait: boolean ): Promise { return NitroArkHybridObject.tryClaimLightningReceive(paymentHash, wait).then( enrichLightningReceive ); } /** * Checks and claims all open Lightning receives. * @param wait Whether to wait for the claim to complete. * @returns A promise that resolves on success or rejects on error. */ export function tryClaimAllLightningReceives(wait: boolean): Promise { return NitroArkHybridObject.tryClaimAllLightningReceives(wait); } /** * Pays a Bolt11 Lightning invoice. * @param destination The Lightning invoice. * @param wait Whether to wait for the payment to complete. * @param amountSat The amount in satoshis to send. Use 0 for invoice amount. * @param retryForSeconds Server retry duration in whole seconds (0–4294967295). * Omit for the server default; 0 requests one attempt. The server caps its duration. * Independent of wait; resumed payments keep their original retry duration. * @returns A promise resolving to the current Lightning payment state. */ export function payLightningInvoice( destination: string, wait: boolean, amountSat?: number, retryForSeconds?: number ): Promise { return NitroArkHybridObject.payLightningInvoice( destination, wait, amountSat, retryForSeconds ).then((result) => ({ ...result, state: result.state as LightningPaymentState, })); } /** * Pays a Bolt11 invoice that the caller has already resolved from another * user-facing payment identifier. * * This is a low-level counterpart to helpers such as `payLightningAddress`. * It deliberately performs no remote discovery or callback request. Instead, * it tells Bark which identifier produced the invoice so Bark can persist that * identifier in the Lightning-send checkpoint and movement before settlement. * This keeps payment provenance intact across interruption, history reloads, * and wallet backups instead of recording only the one-time Bolt11 invoice. * * Callers remain responsible for resolving the origin, validating the returned * invoice, and ensuring its amount matches the external protocol request. * This API intentionally has no amount override: the resolved invoice must * contain its exact payment amount. * * The origin becomes durable wallet history and is included in wallet * database backups. Pass the original user-facing identifier, never a callback * URL containing payer data, authorization tokens, or other secrets. * * @param invoice The already-resolved Bolt11 invoice to pay. * @param origin The original destination to store in Bark's movement history. * @param wait Whether to wait for the payment to complete. * @param retryForSeconds Server retry duration in whole seconds (0–4294967295). * Omit for the server default; 0 requests one attempt. The server caps its duration. * Independent of wait; resumed payments keep their original retry duration. * @returns A promise resolving to the current Lightning payment state. */ export function payLightningInvoiceWithOrigin( invoice: string, origin: LightningPaymentOrigin, wait: boolean, retryForSeconds?: number ): Promise { return NitroArkHybridObject.payLightningInvoiceWithOrigin( invoice, origin, wait, retryForSeconds ).then((result) => ({ ...result, state: result.state as LightningPaymentState, })); } /** * Sends a payment to a Bolt12 offer. * @param offer The Bolt12 offer. * @param wait Whether to wait for the payment to complete. * @param amountSat The amount in satoshis to send. Use 0 for invoice amount. * @param retryForSeconds Server retry duration in whole seconds (0–4294967295). * Omit for the server default; 0 requests one attempt. The server caps its duration. * Independent of wait; resumed payments keep their original retry duration. * @returns A promise resolving to the current Lightning payment state. */ export function payLightningOffer( offer: string, wait: boolean, amountSat?: number, retryForSeconds?: number ): Promise { return NitroArkHybridObject.payLightningOffer( offer, wait, amountSat, retryForSeconds ).then((result) => ({ ...result, state: result.state as LightningPaymentState, })); } /** * Sends a payment to a Lightning Address. * @param addr The Lightning Address. * @param amountSat The amount in satoshis to send. * @param comment An optional comment. * @param wait Whether to wait for the payment to complete. * @param retryForSeconds Server retry duration in whole seconds (0–4294967295). * Omit for the server default; 0 requests one attempt. The server caps its duration. * Independent of wait; resumed payments keep their original retry duration. * @returns A promise resolving to the current Lightning payment state. */ export function payLightningAddress( addr: string, amountSat: number, comment: string, wait: boolean, retryForSeconds?: number ): Promise { return NitroArkHybridObject.payLightningAddress( addr, amountSat, comment, wait, retryForSeconds ).then((result) => ({ ...result, state: result.state as LightningPaymentState, })); } /** * Estimates the fee for a Lightning send. * @param amountSat The amount in satoshis to send. * @returns A promise resolving to the fee estimate. */ export function estimateLightningSendFee( amountSat: number ): Promise { return NitroArkHybridObject.estimateLightningSendFee(amountSat); } // --- Ark Operations --- /** * Boards a specific amount from the onchain wallet into Ark. * @param amountSat The amount in satoshis to board. * @returns A promise resolving to a BoardResult object */ export function boardAmount(amountSat: number): Promise { return NitroArkHybridObject.boardAmount(amountSat); } /** * Boards all available funds from the onchain wallet into Ark. * @returns A promise resolving to a BoardResult object. */ export function boardAll(): Promise { return NitroArkHybridObject.boardAll(); } /** * Validates an Arkoor address. * @param address The Arkoor address to validate. * @returns A promise resolving to void. */ export function validateArkoorAddress(address: string): Promise { return NitroArkHybridObject.validateArkoorAddress(address); } /** * Sends an Arkoor payment. * @param destination The destination Arkoor address. * @param amountSat The amount in satoshis to send. * @returns A promise resolving to the ArkoorPaymentResult object */ export function sendArkoorPayment( destination: string, amountSat: number ): Promise { return NitroArkHybridObject.sendArkoorPayment(destination, amountSat); } /** * Parses a pasted payment string into the payment options it offers. * Accepts BIP 321 and lightning: URIs, BOLT11 invoices, BOLT12 offers, * lightning addresses, LNURL-pay links (including lnurlp://), Ark and bitcoin * addresses. Requires a loaded wallet. * @param payment The payment string. * @returns A promise resolving to the parsed request; throws if nothing payable is found. */ export function parsePaymentRequest( payment: string ): Promise { return NitroArkHybridObject.parsePaymentRequest( payment ) as Promise; } /** * Estimates the fee for an Arkoor payment. * @param amountSat The amount in satoshis to send. * @returns A promise resolving to the fee estimate. */ export function estimateArkoorPaymentFee( amountSat: number ): Promise { return NitroArkHybridObject.estimateArkoorPaymentFee(amountSat); } /** * Estimates the Ark protocol fee for boarding an amount into Ark. * This does not include the onchain transaction fee for the board anchor transaction. * @param amountSat The amount in satoshis to board. * @returns A promise resolving to the fee estimate. */ export function estimateBoardOffchainFee( amountSat: number ): Promise { return NitroArkHybridObject.estimateBoardOffchainFee(amountSat); } /** * Estimates the Ark protocol fee for refreshing the provided VTXOs. * @param vtxoIds Array of VTXO ID strings to refresh. * @returns A promise resolving to the fee estimate. */ export function estimateRefreshFee( vtxoIds: string[] ): Promise { return NitroArkHybridObject.estimateRefreshFee(vtxoIds); } /** * Sends an onchain payment via an Ark round. * @param destination The destination Bitcoin address. * @param amountSat The amount in satoshis to send. * @returns A promise resolving to the offboard txid and its movement id. */ export function sendOnchain( destination: string, amountSat: number ): Promise { return NitroArkHybridObject.sendOnchain(destination, amountSat); } /** * Estimates the fee for sending an onchain payment via an Ark round. * @param destination The destination Bitcoin address. * @param amountSat The amount in satoshis to send. * @returns A promise resolving to the fee estimate. */ export function estimateSendOnchain( destination: string, amountSat: number ): Promise { return NitroArkHybridObject.estimateSendOnchain(destination, amountSat); } // --- Offboarding / Exiting --- /** * Offboards specific VTXOs to a destination address. * @param vtxoIds Array of VtxoId strings to offboard. * @param destinationAddress Destination Bitcoin address (if empty, sends to internal wallet). * @returns A promise resolving to the offboard txid and its movement id. */ export function offboardSpecific( vtxoIds: string[], destinationAddress: string ): Promise { return NitroArkHybridObject.offboardSpecific(vtxoIds, destinationAddress); } /** * Offboards all VTXOs to a destination address. * @param destinationAddress Destination Bitcoin address (if empty, sends to internal wallet). * @returns A promise resolving to the offboard txid and its movement id. */ export function offboardAll( destinationAddress: string ): Promise { return NitroArkHybridObject.offboardAll(destinationAddress); } /** * Estimates the fee for offboarding all Ark funds to an onchain address. * @param destinationAddress The destination Bitcoin address. * @returns A promise resolving to the fee estimate. */ export function estimateOffboardAll( destinationAddress: string ): Promise { return NitroArkHybridObject.estimateOffboardAll(destinationAddress); } // --- Re-export types and enums --- export type { NitroArk, BarkCreateOpts, BarkConfigOpts, BarkArkInfo, WalletDebugInfo, Bolt11Invoice, BoardResult, RecoveryGroup, RecoveryReport, DelegatedRoundState, BarkSendManyOutput, ArkoorPaymentResult, OffboardResult, BarkFeeEstimate, ExitFeeEstimate, BarkFeeRates, OnchainTransactionInfo, LightningPaymentResult, OnchainPaymentResult, OffchainBalanceResult, OnchainBalanceResult, NewAddressResult, KeyPairResult, } from './NitroArk.nitro';