### Complete VTXO Management Example Source: https://docs.arkadeos.com/wallets/advanced/vtxo-management A comprehensive example demonstrating wallet setup, VTXO manager initialization with custom thresholds, and the process of checking and renewing expiring VTXOs, followed by checking and recovering swept VTXOs. ```typescript import { Wallet, MnemonicIdentity, VtxoManager } from '@arkade-os/sdk' import { LocalStorageAdapter } from '@arkade-os/sdk/adapters/localStorage' // Setup wallet const storage = new LocalStorageAdapter() const mnemonic = await storage.getItem('mnemonic') const identity = MnemonicIdentity.fromMnemonic(mnemonic) const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer', storage }) // Create VTXO manager const manager = new VtxoManager(wallet, undefined, { vtxoThreshold: 259200, boardingUtxoSweep: true, }) // Check and renew expiring VTXOs const expiringVtxos = await manager.getExpiringVtxos() if (expiringVtxos.length > 0) { console.log(`Renewing ${expiringVtxos.length} expiring VTXOs...`) const renewTxid = await manager.renewVtxos() console.log('Renewal transaction:', renewTxid) } // Check and recover swept VTXOs const balance = await manager.getRecoverableBalance() if (balance.recoverable > 0n) { console.log(`Recovering ${balance.recoverable} sats...`) const recoverTxid = await manager.recoverVtxos((event) => { console.log('Settlement event:', event.type) }) console.log('Recovery transaction:', recoverTxid) } ``` -------------------------------- ### Arkade SDK Quick Start with TypeScript Source: https://docs.arkadeos.com/wallets/getting-started/ai-agents Initialize Arkade SDK classes for Bitcoin, Lightning, and stablecoin swaps. This example demonstrates creating a wallet, getting an address, checking balance, sending Bitcoin, creating a Lightning invoice, and getting a stablecoin swap quote. ```typescript import { Wallet, MnemonicIdentity } from '@arkade-os/sdk' import { generateMnemonic } from '@scure/bip39' import { wordlist } from '@scure/bip39/wordlists/english' import { ArkadeBitcoinSkill, ArkadeLightningSkill, LendaSwapSkill, } from '@arkade-os/skill' const mnemonic = generateMnemonic(wordlist) const identity = MnemonicIdentity.fromMnemonic(mnemonic) const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer', }) // Bitcoin: instant offchain payments const bitcoin = new ArkadeBitcoinSkill(wallet) const arkadeAddress = await bitcoin.getArkadeAddress() const balance = await bitcoin.getBalance() await bitcoin.send({ address: 'ark1q...', amount: 50000 }) // Lightning: pay and receive via Boltz submarine swaps const lightning = new ArkadeLightningSkill({ wallet }) const invoice = await lightning.createInvoice({ amount: 25000 }) // Stablecoins: non-custodial BTC/USDC/USDT atomic swaps const lendaswap = new LendaSwapSkill({ wallet }) const quote = await lendaswap.getQuoteBtcToStablecoin(100000, 'usdc_pol') ``` -------------------------------- ### Quick Service Worker Wallet Setup Source: https://docs.arkadeos.com/wallets/advanced/service-worker Set up a ServiceWorkerWallet with automatic registration and identity management. This is the simplest way to get started. ```typescript import { ServiceWorkerWallet, MnemonicIdentity } from '@arkade-os/sdk' import { generateMnemonic } from '@scure/bip39' import { wordlist } from '@scure/bip39/wordlists/english' // Create your identity const identity = MnemonicIdentity.fromMnemonic(generateMnemonic(wordlist)) const wallet = await ServiceWorkerWallet.setup({ serviceWorkerPath: '/service-worker.js', arkServerUrl: 'https://arkade.computer', identity }) // That's it! Ready to use immediately: const address = await wallet.getAddress() const balance = await wallet.getBalance() ``` -------------------------------- ### Install SDK and Boltz Swap Package Source: https://docs.arkadeos.com/contracts/chain-swaps Install the necessary Arkade SDK and Boltz swap packages using pnpm. ```bash pnpm add @arkade-os/sdk @arkade-os/boltz-swap ``` -------------------------------- ### Install Arkade SDK Source: https://docs.arkadeos.com/wallets/getting-started/create-your-wallet Install the Arkade SDK using pnpm. Ensure you have Node.js v22 or higher installed. ```bash pnpm add @arkade-os/sdk ``` -------------------------------- ### Example Arkade Addresses Source: https://docs.arkadeos.com/wallets/getting-started/arkade-addresses These examples show how the same components produce different addresses on mainnet and testnet. The P2TR output key and server public key are provided for reference. ```text P2TR output key: 25a43cecfa0e1b1a4f72d64ad15f4cfa7a84d0723e8511c969aa543638ea9967 Server public key: 33ffb3dee353b1a9ebe4ced64b946238d0a4ac364f275d771da6ad2445d07ae0 Mainnet: ark1qqellv77udfmr20tun8dvju5vgudpf9vxe8jwhthrkn26fz96pawqfdy8nk05rsmrf8h94j26905e7n6sng8y059z8ykn2j5xcuw4xt8ngt9rw Testnet: tark1qqellv77udfmr20tun8dvju5vgudpf9vxe8jwhthrkn26fz96pawqfdy8nk05rsmrf8h94j26905e7n6sng8y059z8ykn2j5xcuw4xt846qj6x ``` -------------------------------- ### Install Arkade SDK Dependencies Source: https://docs.arkadeos.com/contracts/setup Install the necessary packages for the Arkade SDK and Scure base encoding using pnpm. ```bash pnpm add @arkade-os/sdk @scure/base ``` -------------------------------- ### Install Arkade Skill for Any Agent Source: https://docs.arkadeos.com/wallets/getting-started/ai-agents Install the Arkade skill for any supported agent using the Vercel Skills CLI. Use the `-g` flag for a global installation. The system will auto-discover compatible agents. ```bash pnpm dlx skills add arkade-os/skill ``` -------------------------------- ### Alice-to-Bob Payment Example Source: https://docs.arkadeos.com/learn/core-concepts/transactions-and-execution Illustrates a concrete example of an Arkade transaction where Alice pays Bob 1000 sats, consuming a 5000 sat VTXO. It shows the structure of inputs with signatures and outputs with Taproot scripts for both the payment and change. ```javascript Transaction { inputs: [ { vtxo: aliceVTXO(5000 sats), witness: [aliceSignature, operatorSignature] } ], outputs: [ { value: 1000, script: Taproot(UNSPENDABLE, [ checkSig(bobPK) && checkSig(operatorPK), checkSig(bobPK) && relativeTimelock(1008) ]) }, { value: 3950, // change minus fee script: Taproot(UNSPENDABLE, [ checkSig(alicePK) && checkSig(operatorPK), checkSig(alicePK) && relativeTimelock(1008) ]) } ] } ``` -------------------------------- ### Setup Arkade Provider and Identities Source: https://docs.arkadeos.com/contracts/spilman-channel Initializes the Arkade provider, retrieves server information, and generates identities for Alice and Bob. This setup is required before interacting with the Arkade network or constructing channel parameters. ```typescript import { Script } from '@scure/btc-signer'; import { hex } from '@scure/base'; import { RestArkProvider, MnemonicIdentity, VtxoScript, networks } from '@arkade-os/sdk'; // Setup const arkProvider = new RestArkProvider('https://arkade.computer'); const info = await arkProvider.getInfo(); const serverPubkey = hex.decode(info.signerPubkey).slice(1); // x-only const exitDelay = BigInt(info.exitDelay); // Identities const alice = MnemonicIdentity.fromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"); const bob = MnemonicIdentity.fromMnemonic("zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong"); const alicePubkey = await alice.xOnlyPublicKey(); const bobPubkey = await bob.xOnlyPublicKey(); // Channel parameters const refundTimeout = BigInt(Math.floor(Date.now() / 1000)) + 86400n; // 1 day from now const unilateralUpdateDelay = exitDelay; const unilateralRefundDelay = exitDelay + 2n; // Slightly longer than update delay ``` -------------------------------- ### Install Arkade Skill for Cursor Source: https://docs.arkadeos.com/wallets/getting-started/ai-agents Install the Arkade skill into your Cursor agent using the Vercel Skills CLI. This action creates a `.cursor/skills/` directory in your project. ```bash pnpm dlx skills add arkade-os/skill --agent cursor ``` -------------------------------- ### Start Local Arkade Operator with Nigiri Source: https://docs.arkadeos.com/wallets/getting-started/developer-resources Use this command to start a local Nigiri environment with Arkade support enabled for local testing. ```bash nigiri start --ark ``` -------------------------------- ### Install Arkade SDK and Expo Crypto Source: https://docs.arkadeos.com/wallets/advanced/expo-react-native Install the necessary Arkade SDK package and the expo-crypto library for React Native and Expo projects. ```bash pnpm add @arkade-os/sdk pnpm dlx expo install expo-crypto ``` -------------------------------- ### Install Arkade Skill for Claude Code Source: https://docs.arkadeos.com/wallets/getting-started/ai-agents Install the Arkade skill into your Claude Code agent using the Vercel Skills CLI. Verify the installation by typing `/skills` within Claude Code. ```bash pnpm dlx skills add arkade-os/skill --agent claude-code ``` -------------------------------- ### Setup and Initialization for HTLC Source: https://docs.arkadeos.com/contracts/hashlock Initializes Arkade providers and retrieves server public key and exit delay. Sets up the receiver's identity and generates a secret preimage, then computes its hash. ```typescript import { Script } from '@scure/btc-signer'; import { hash160 } from '@scure/btc-signer/utils.js'; import { hex } from '@scure/base'; import { RestArkProvider, RestIndexerProvider, MnemonicIdentity, VtxoScript, networks } from '@arkade-os/sdk'; // Setup const arkProvider = new RestArkProvider('https://arkade.computer'); const info = await arkProvider.getInfo(); const serverPubkey = hex.decode(info.signerPubkey).slice(1); // x-only const exitDelay = BigInt(info.exitDelay); // Identities const receiver = MnemonicIdentity.fromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"); const receiverPubkey = await receiver.xOnlyPublicKey(); // The secret (in production, receiver generates this) const preimage = crypto.getRandomValues(new Uint8Array(32)); const preimageHash = hash160(preimage); // RIPEMD160(SHA256(preimage)), 20 bytes ``` -------------------------------- ### Setup Arkade SDK and Channel Participants Source: https://docs.arkadeos.com/contracts/dryja-poon-channel Initializes the Arkade SDK provider, retrieves network information, and sets up identities and public keys for channel participants Alice and Bob. Includes standard Lightning CSV delay for to_local transactions. ```typescript import { Script } from '@scure/btc-signer'; import { hex } from '@scure/base'; import { RestArkProvider, MnemonicIdentity, VtxoScript, networks } from '@arkade-os/sdk'; // Setup const arkProvider = new RestArkProvider('https://arkade.computer'); const info = await arkProvider.getInfo(); const serverPubkey = hex.decode(info.signerPubkey).slice(1); // x-only const exitDelay = BigInt(info.exitDelay); // Channel participants const alice = MnemonicIdentity.fromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"); const bob = MnemonicIdentity.fromMnemonic("zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong"); const alicePubkey = await alice.xOnlyPublicKey(); const bobPubkey = await bob.xOnlyPublicKey(); // Standard Lightning CSV delay for to_local const toLocalDelay = 144n; // ~1 day in blocks ``` -------------------------------- ### Example Intent Message for Registration Source: https://docs.arkadeos.com/arkd/components/intent-system An example of the intent message structure used for registration, specifying onchain output indexes, validity timestamps, and cosigner public keys. ```typescript const message: Intent.RegisterMessage = { type: "register", onchain_output_indexes: onchainOutputsIndexes, valid_at: validAt ? Math.floor(validAt) : 0, expire_at: 0, cosigners_public_keys: cosignerPubKeys, }; ``` -------------------------------- ### Arkade Script Compilation with Options Source: https://docs.arkadeos.com/experimental/arkade-compiler These examples demonstrate various command-line options for the Arkade Compiler. Use these to control optimization levels, output format, debugging, and specify output files. ```bash # Compile with optimization level 2 (more aggressive) arkadec --opt-level=2 contract.ark ``` ```bash # Output assembly instead of bytecode arkadec --output=asm contract.ark ``` ```bash # Generate debug information arkadec --debug contract.ark ``` ```bash # Specify output file arkadec --output-file=contract.json contract.ark ``` -------------------------------- ### Basic Arkade Wallet Setup Source: https://docs.arkadeos.com/wallets/getting-started/create-your-wallet Create a new Arkade wallet instance using a generated mnemonic or an existing private key. For production, use a secure key management solution. This snippet demonstrates generating a new mnemonic and creating a wallet connected to the Arkade server. ```typescript import { MnemonicIdentity, Wallet } from '@arkade-os/sdk' import { generateMnemonic } from '@scure/bip39' import { wordlist } from '@scure/bip39/wordlists/english' // Generate a new mnemonic or load an existing one from secure storage const mnemonic = generateMnemonic(wordlist) const identity = MnemonicIdentity.fromMnemonic(mnemonic) // Create a wallet instance const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer', }) // Receive Bitcoin offchain instantly const address = await wallet.getAddress() console.log('Arkade Address:', address) ``` -------------------------------- ### Initialize Arkade SDK Providers and Identity Source: https://docs.arkadeos.com/contracts/setup Set up RestArkProvider and RestIndexerProvider, retrieve server information, and create a user identity from a mnemonic phrase. This snippet demonstrates the initial setup required to interact with the Arkade network. ```typescript import { RestArkProvider, RestIndexerProvider, MnemonicIdentity, VtxoScript, Transaction, MultisigTapscript, CLTVMultisigTapscript, buildOffchainTx, CSVMultisigTapscript, networks } from '@arkade-os/sdk'; import { hex, base64 } from '@scure/base'; // Setup providers const arkProvider = new RestArkProvider('https://arkade.computer'); const indexerProvider = new RestIndexerProvider('https://arkade.computer'); const info = await arkProvider.getInfo(); // => { signerPubkey: string, fees: ServerFees, ... } // Convert 33-byte compressed pubkey to 32-byte x-only const serverPubkey = hex.decode(info.signerPubkey).slice(1); // Create identity const identity = MnemonicIdentity.fromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"); const myPubkey = await identity.xOnlyPublicKey(); ``` -------------------------------- ### Identity Management with LocalStorageAdapter Source: https://docs.arkadeos.com/wallets/advanced/storage-adapters Manage wallet identity across sessions using `LocalStorageAdapter`. This example demonstrates creating a new identity if none exists and loading an existing one. ```typescript import { Wallet, MnemonicIdentity } from '@arkade-os/sdk' import { LocalStorageAdapter } from '@arkade-os/sdk/adapters/localStorage' import { generateMnemonic } from '@scure/bip39' import { wordlist } from '@scure/bip39/wordlists/english' const storage = new LocalStorageAdapter() // Try to load existing identity let mnemonic = await storage.getItem('mnemonic') if (!mnemonic) { // Create new identity console.log('Creating new wallet identity...') mnemonic = generateMnemonic(wordlist) // Save to storage await storage.setItem('mnemonic', mnemonic) console.log('New identity saved to storage') } else { console.log('Loaded existing identity from storage') } const identity = MnemonicIdentity.fromMnemonic(mnemonic) // Create wallet with persistent storage const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer', storage }) const address = await wallet.getAddress() console.log('Wallet address:', address) ``` -------------------------------- ### Condition Field Example Source: https://docs.arkadeos.com/arkd/components/arkade-psbts Provides the key-value format for additional witness elements used in custom script execution. The value is PSBT witness encoding. ```text Key: 0xDE 0x63 0x6F 0x6E 0x64 0x69 0x74 0x69 0x6F 0x6E ("condition") Value: [witness_encoding] ``` -------------------------------- ### Setup Crypto Polyfill for Expo Source: https://docs.arkadeos.com/wallets/advanced/expo-react-native Resolve 'crypto is not defined' errors in Expo by polyfilling the global crypto object with expo-crypto. ```typescript import * as Crypto from 'expo-crypto' if (!global.crypto) global.crypto = {} as any global.crypto.getRandomValues = Crypto.getRandomValues ``` -------------------------------- ### Cosigner Field Example Source: https://docs.arkadeos.com/arkd/components/arkade-psbts Demonstrates the key-value format for specifying indexed Musig2 cosigner public keys. The key includes a 4-byte big-endian index. ```text Key: 0xDE 0x63 0x6F 0x73 0x69 0x67 0x6E 0x65 0x72 0x00 0x00 0x00 0x01 ("cosigner" + index 1) Value: [33-byte compressed public key] ``` -------------------------------- ### Intent Transaction Output Distribution Source: https://docs.arkadeos.com/learn/arkade-assets/core-concepts Shows an example of how a single asset can be split across multiple destinations via an intent transaction. ```text Intent TX outputs: vout 0 → 50 tokens (collaborative exit → onchain) vout 1 → 30 tokens (new VTXO) vout 2 → 20 tokens (new VTXO) ``` -------------------------------- ### Process Incoming Funds Notification Source: https://docs.arkadeos.com/wallets/operations/receiving-payments An example function to process incoming funds notifications. It handles both 'vtxo' and 'utxo' types, logs received amounts, and triggers UI updates. Remember to implement error handling and deduplication. ```typescript // Example function to process incoming funds async function processIncomingFunds(notification: IncomingFunds) { // Update your application state switch (notification.type) { case 'vtxo': for (const vtxo of notification.newVtxos) { console.log(`Received payment of ${vtxo.value} sats`); // You might want to store the VTXO in your database await storeVtxoInDatabase(vtxo); // Notify the user showNotification(`Received ${vtxo.value} sats!`); // Update the UI await refreshBalanceDisplay(); } break; case 'utxo': // Coins received on boarding addresses (see Ramps documentation) for (const coin of notification.coins) { await storeBoardingUtxoInDatabase(coin) showNotification(`Received ${coin.value} sats on boarding address!`); await refreshBalanceDisplay(); } break; } } // Start the subscription const stop = wallet.notifyIncomingFunds(processIncomingFunds) // Stop the subscription when needed stop() ``` -------------------------------- ### Import SDK and Create Wallet Source: https://docs.arkadeos.com/wallets/operations/assets/check-balance Import the necessary SDK components and initialize a wallet instance. Ensure you have the correct Arkade server URL. ```typescript import { MnemonicIdentity, Wallet } from '@arkade-os/sdk' const identity = MnemonicIdentity.fromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer', }) ``` -------------------------------- ### Initialize Arkade Wallet Source: https://docs.arkadeos.com/wallets/operations/receiving-payments Import necessary SDK modules and generate a mnemonic to create an identity. Then, initialize the Arkade wallet with your identity and the Arkade server URL. ```typescript import { MnemonicIdentity, Wallet, waitForIncomingFunds } from '@arkade-os/sdk' import { generateMnemonic } from '@scure/bip39' import { wordlist } from '@scure/bip39/wordlists/english' const mnemonic = generateMnemonic(wordlist) const identity = MnemonicIdentity.fromMnemonic(mnemonic) const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer', }) ``` -------------------------------- ### Build and Interact with an Escrow Tapscript Source: https://docs.arkadeos.com/contracts/escrow This snippet shows how to set up identities, define multiple spending paths for an escrow contract using MultisigTapscript and CLTVMultisigTapscript, query for VTXOs, build an offchain transaction, sign it cooperatively, and submit it. It also includes steps for finalizing the transaction with checkpoints. ```typescript import { RestArkProvider, RestIndexerProvider, MnemonicIdentity, VtxoScript, Transaction, MultisigTapscript, CLTVMultisigTapscript, buildOffchainTx, CSVMultisigTapscript, networks } from '@arkade-os/sdk'; import { hex, base64 } from '@scure/base'; // Setup const arkProvider = new RestArkProvider('https://arkade.computer'); const indexerProvider = new RestIndexerProvider('https://arkade.computer'); const info = await arkProvider.getInfo(); // Convert 33-byte compressed pubkey to 32-byte x-only const serverPubkey = hex.decode(info.signerPubkey).slice(1); // Identities const buyer = MnemonicIdentity.fromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"); const seller = MnemonicIdentity.fromMnemonic("zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong"); const arbiter = MnemonicIdentity.fromMnemonic("legal winner thank year wave sausage worth useful legal winner thank yellow"); // Build escrow script with 3 paths const buyerPubkey = await buyer.xOnlyPublicKey(); const sellerPubkey = await seller.xOnlyPublicKey(); const arbiterPubkey = await arbiter.xOnlyPublicKey(); // Path 1: Buyer and seller both agree const collaborativePath = MultisigTapscript.encode({ pubkeys: [buyerPubkey, sellerPubkey, serverPubkey] }).script; // Path 2: Arbiter resolves dispute const arbiterPath = MultisigTapscript.encode({ pubkeys: [arbiterPubkey, serverPubkey] }).script; // Path 3: Refund to buyer after 30 days const startTime = BigInt(Math.floor(Date.now() / 1000)); const refundPath = CLTVMultisigTapscript.encode({ pubkeys: [buyerPubkey, serverPubkey], absoluteTimelock: startTime + (86400n * 30n) // 30 days }).script; // Assemble VtxoScript const escrowScript = new VtxoScript([collaborativePath, arbiterPath, refundPath]); const escrowAddress = escrowScript.address(networks.bitcoin.hrp, serverPubkey).encode(); console.log('Escrow address:', escrowAddress); // Query VTXOs at escrow address const result = await indexerProvider.getVtxos({ scripts: [hex.encode(escrowScript.pkScript)], spendableOnly: true, }); if (result.vtxos.length === 0) { console.log('No VTXOs found at escrow address'); process.exit(0); } const vtxo = result.vtxos[0]; // Build transaction to release funds (cooperative path) const serverUnrollScript = CSVMultisigTapscript.decode( hex.decode(info.checkpointTapscript) ); const input = { txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value, tapLeafScript: escrowScript.findLeaf(hex.encode(collaborativePath)), tapTree: escrowScript.encode(), }; const outputs = [ { amount: vtxo.value, // Input amount must equal output amount script: recipientScript.pkScript }, ]; const { arkTx, checkpoints } = buildOffchainTx( [input], outputs, serverUnrollScript ); // Sign with buyer and seller const psbt = arkTx.toPSBT(); const txBuyer = Transaction.fromPSBT(psbt); const signedByBuyer = await buyer.sign(txBuyer); const txSeller = Transaction.fromPSBT(signedByBuyer.toPSBT()); const signedByBoth = await seller.sign(txSeller); // Submit const checkpointPsbts = checkpoints.map(c => c.toPSBT()); const { arkTxid, signedCheckpointTxs } = await arkProvider.submitTx( base64.encode(signedByBoth.toPSBT()), checkpointPsbts.map(c => base64.encode(c)) ); // Finalize - checkpoint needs all parties from the spending path const finalCheckpoints = await Promise.all( signedCheckpointTxs.map(async (cpB64) => { const cpTx = Transaction.fromPSBT(base64.decode(cpB64)); const signedByBuyer = await buyer.sign(cpTx, [0]); const signedByBoth = await seller.sign( Transaction.fromPSBT(signedByBuyer.toPSBT()), [0] ); return base64.encode(signedByBoth.toPSBT()); }) ); await arkProvider.finalizeTx(arkTxid, finalCheckpoints); console.log('Escrow released!'); ``` -------------------------------- ### GetEventStream Source: https://docs.arkadeos.com/arkd/core-services/ark-service Provides clients with real-time batch updates, including batch start, finalization, and failure notifications. ```APIDOC ## GetEventStream ### Description Provides clients with real-time updates on batch events, such as batch start, finalization, and failure notifications. ### Method GET ### Endpoint /eventstream ### Parameters None ### Response #### Success Response (200) - **event** (object) - Real-time event data. Possible event types include batch start, finalization, and failure. ### Response Example (Server-side stream of event objects) ``` -------------------------------- ### Get Array Length Source: https://docs.arkadeos.com/experimental/arkade-functions Returns the number of elements in an array. Use this to check array sizes or iterate. ```solidity int arrayLength = array.length; ``` ```solidity require(pubkeys.length == signatures.length, "Mismatched array lengths"); ``` -------------------------------- ### Aggregate Public Keys Source: https://docs.arkadeos.com/experimental/arkade-functions Aggregates multiple public keys into a single public key. Useful for multisignature setups. ```solidity pubkey aggregatedKey = aggregateKeys(pubkeys); ``` ```solidity pubkey multisigKey = aggregateKeys([alice, bob, charlie]); ``` -------------------------------- ### Initialize Arkade Wallet and BoltzSwapProvider Source: https://docs.arkadeos.com/contracts/chain-swaps Initialize your Arkade wallet and the BoltzSwapProvider with the API URL and network. This sets up the connection for chain swap operations. ```typescript import { Wallet } from '@arkade-os/sdk' import { ArkadeSwaps, BoltzSwapProvider } from '@arkade-os/boltz-swap' // Initialize your Arkade wallet const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer', }) // Initialize the chain swap provider const swapProvider = new BoltzSwapProvider({ apiUrl: 'https://api.ark.boltz.exchange', network: 'bitcoin', }) // Create chainSwaps instance const chainSwaps = new ArkadeSwaps({ wallet, swapProvider, }) ``` -------------------------------- ### Add Arkade Docs MCP Server (Claude) Source: https://docs.arkadeos.com/wallets/getting-started/ai-agents Connect your agent to searchable Arkade documentation using the Claude CLI. Add `--scope user` for global access. ```bash claude mcp add --transport http arkade-docs https://docs.arkadeos.com/mcp ``` -------------------------------- ### Get Virtual UTXOs (Offchain) Source: https://docs.arkadeos.com/wallets/operations/checking-balances Retrieve all your offchain VTXOs. Logs important information about each VTXO, such as ID, amount, and virtual status. ```typescript // Get virtual UTXOs (offchain) const vtxos = await wallet.getVtxos() console.log('Number of VTXOs:', vtxos.length) // Log important information about each VTXO vtxos.forEach((vtxo, index) => { console.log(`VTXO #${index + 1}:`); console.log(` ID: ${vtxo.txid}:${vtxo.vout}`); console.log(` Amount: ${vtxo.value} sats`); console.log(` Batch ID: ${vtxo.virtualStatus.batchTxID}`); console.log(` Status: ${vtxo.virtualStatus.state}`); // "preconfirmed" | "settled" | "swept" | "spent"; }); ``` -------------------------------- ### Create Arkade Wallet with Expo Providers Source: https://docs.arkadeos.com/wallets/advanced/expo-react-native Set up a new Arkade wallet instance using Expo-compatible providers for Arkade and indexing services, along with AsyncStorage for storage. This includes loading or generating a mnemonic and initializing the wallet. ```typescript import { Wallet, MnemonicIdentity } from '@arkade-os/sdk' import { ExpoArkProvider, ExpoIndexerProvider } from '@arkade-os/sdk/adapters/expo' import { AsyncStorageAdapter } from '@arkade-os/sdk/adapters/asyncStorage' import { generateMnemonic } from '@scure/bip39' import { wordlist } from '@scure/bip39/wordlists/english' // Setup storage const storage = new AsyncStorageAdapter() // Load or create identity let mnemonic = await storage.getItem('mnemonic') if (!mnemonic) { mnemonic = generateMnemonic(wordlist) await storage.setItem('mnemonic', mnemonic) } const identity = MnemonicIdentity.fromMnemonic(mnemonic) // Create wallet with Expo providers const wallet = await Wallet.create({ identity, esploraUrl: 'https://mempool.space/api', arkProvider: new ExpoArkProvider('https://arkade.computer'), indexerProvider: new ExpoIndexerProvider('https://arkade.computer'), storage }) // Use wallet normally const address = await wallet.getAddress() const balance = await wallet.getBalance() ``` -------------------------------- ### Taptree Field Example Source: https://docs.arkadeos.com/arkd/components/arkade-psbts Illustrates the key-value format for embedding a Taproot script tree in a PSBT. The value consists of encoded tapscript leaves. ```text Key: 0xDE 0x74 0x61 0x70 0x74 0x72 0x65 0x65 ("taptree") Value: [1][0xC0][script_len][script_bytes][1][0xC0][script_len][script_bytes]... ``` -------------------------------- ### Initialize ArkadeSwaps with Swap Manager Source: https://docs.arkadeos.com/contracts/lightning-swaps Initialize the ArkadeSwaps instance with the wallet, swap provider, and enable the swap manager for background monitoring of pending swaps. ```typescript const lightningSwaps = new ArkadeSwaps({ wallet, swapProvider, swapManager: true, // enable with defaults }); // Query pending swaps const pendingPaymentsToLightning = lightningSwaps.getPendingSubmarineSwaps(); const pendingPaymentsFromLightning = lightningSwaps.getPendingReverseSwaps(); ``` -------------------------------- ### Expiry Field Example Source: https://docs.arkadeos.com/arkd/components/arkade-psbts Shows the key-value format for defining a relative locktime (CSV) condition for an input. The value is encoded using BIP68 sequence encoding. ```text Key: 0xDE 0x65 0x78 0x70 0x69 0x72 0x79 ("expiry") Value: [sequence_bytes] (e.g., 0x80 0x96 0x98 for 10000 blocks) ``` -------------------------------- ### Add Arkade Docs MCP Server (Cursor) Source: https://docs.arkadeos.com/wallets/getting-started/ai-agents Configure Cursor to connect to Arkade documentation by adding the MCP server details to your `.cursor/mcp.json` or `~/.cursor/mcp.json` file. ```json { "mcpServers": { "arkade-docs": { "url": "https://docs.arkadeos.com/mcp" } } } ``` -------------------------------- ### Service Worker Wallet Setup with Storage and Identity Management Source: https://docs.arkadeos.com/wallets/advanced/service-worker Set up a ServiceWorkerWallet that includes persistent storage using LocalStorageAdapter and manages identity creation or loading from storage. ```typescript // main.js import { ServiceWorkerWallet, MnemonicIdentity } from '@arkade-os/sdk' import { LocalStorageAdapter } from '@arkade-os/sdk/adapters/localStorage' import { generateMnemonic } from '@scure/bip39' import { wordlist } from '@scure/bip39/wordlists/english' const storage = new LocalStorageAdapter() // Load or create identity let mnemonic = await storage.getItem('mnemonic') if (!mnemonic) { mnemonic = generateMnemonic(wordlist) await storage.setItem('mnemonic', mnemonic) } const identity = MnemonicIdentity.fromMnemonic(mnemonic) // Setup service worker wallet const wallet = await ServiceWorkerWallet.setup({ serviceWorkerPath: '/service-worker.js', arkServerUrl: 'https://arkade.computer', identity }) // Use wallet normally const address = await wallet.getAddress() console.log('Wallet address:', address) const balance = await wallet.getBalance() console.log('Balance:', balance.total) ``` -------------------------------- ### Initialize ExpoIndexerProvider Source: https://docs.arkadeos.com/wallets/advanced/expo-react-native Instantiate ExpoIndexerProvider for handling address subscriptions and VTXO updates with JSON streaming in Expo. ```typescript import { ExpoIndexerProvider } from '@arkade-os/sdk/adapters/expo' const indexerProvider = new ExpoIndexerProvider('https://arkade.computer') ``` -------------------------------- ### Get Arkade Receiving Address Source: https://docs.arkadeos.com/wallets/operations/receiving-payments Retrieve your offchain Arkade address from the initialized wallet. This address is used for receiving instant, low-fee Bitcoin payments within the Arkade network. ```typescript const offchainAddress = await wallet.getAddress() console.log('Ark Address:', offchainAddress) // ark1qqellv77udfmr20tun8dvju5vgudpf9vxe8jwhthrkn26fz96pawqfdy8nk05rsmrf8h94j26905e7n6sng8y059z8ykn2j5xcuw4xt8ngt9rw ``` -------------------------------- ### Get Wallet Balance Source: https://docs.arkadeos.com/wallets/operations/checking-balances Retrieves the current Arkade wallet balance, which includes total, boarding, available, settled, preconfirmed, and recoverable amounts. This method now supports Arkade Assets. ```typescript const balance = await wallet.getBalance() // Total wallet balance console.log('Total:', balance.total) // Boarding UTXOs waiting to be onboarded console.log('Boarding Total:', balance.boarding.total) // Available balance - spendable in offchain Arkade transactions console.log('Available:', balance.available) // Offchain balance split by settlement state console.log('Settled:', balance.settled) console.log('Preconfirmed:', balance.preconfirmed) // Funds that may require recovery console.log('Recoverable:', balance.recoverable) ``` -------------------------------- ### Finalize Pending Transactions Source: https://docs.arkadeos.com/wallets/operations/sending-payments Call `finalizePendingTxs()` when your app starts or reconnects to ensure all transactions are properly completed. This method retrieves any pending transactions from the server and completes the checkpoint signing process. ```typescript // Finalize any pending transactions const { finalized, pending } = await wallet.finalizePendingTxs() console.log('Pending transactions found:', pending.length) console.log('Successfully finalized:', finalized.length) ``` ```typescript // Get VTXOs and finalize their pending transactions const vtxos = await wallet.getVtxos() const { finalized, pending } = await wallet.finalizePendingTxs(vtxos) ``` -------------------------------- ### Lightning Channel Reference Implementation Source: https://docs.arkadeos.com/contracts/lightning-channels This snippet provides a reference implementation for Lightning Channels on Arkade, developed by Vincenzo Palazzo. It is part of the lampo.rs project. ```rust pub fn create_channel( &mut self, peer_id: NodeId, funding_satoshis: Option, push_msat: Option, ) -> Result { let channel_id = ChannelId::new(peer_id, self.next_channel_index()); let funding_output = FundingOutput::new(channel_id, funding_satoshis, push_msat); self.channels.insert(channel_id, ChannelDetails::new(funding_output)); Ok(channel_id) } ``` -------------------------------- ### GetInfo Source: https://docs.arkadeos.com/arkd/core-services/ark-service Retrieves essential server configuration and network parameters, including signer public key, network type, version, timing, economic parameters, forfeit address, and market hours. ```APIDOC ## GetInfo ### Description Provides essential server configuration and network parameters, including signer public key, network type, version information, timing parameters, economic parameters, forfeit address, and market hour information. ### Method GET ### Endpoint /getinfo ### Parameters None ### Response #### Success Response (200) - **signer_public_key** (string) - The public key of the server's signer. - **network_type** (string) - The type of network the server is operating on. - **version** (string) - The server version information. - **timing_parameters** (object) - Timing parameters like round intervals and expiry delays. - **economic_parameters** (object) - Economic parameters such as dust limits and min/max amounts for UTXOs and VTXOs. - **forfeit_address** (string) - The forfeit address where funds are sent as part of Arkade's security mechanism. - **market_hours** (object) - Market hour information, signaling operational time windows. ### Response Example { "signer_public_key": "...", "network_type": "mainnet", "version": "1.0.0", "timing_parameters": { ... }, "economic_parameters": { ... }, "forfeit_address": "...", "market_hours": { ... } } ``` -------------------------------- ### Get Boarding UTXOs (Onchain) Source: https://docs.arkadeos.com/wallets/operations/checking-balances Retrieve onchain UTXOs that have been sent to a boarding address but not yet converted to VTXOs. Logs details like TXID, output index, amount, and confirmation status. ```typescript // Get boarding UTXOs const boardingUtxos = await wallet.getBoardingUtxos() console.log('Number of boarding UTXOs:', boardingUtxos.length) // Log important information about each boarding UTXO boardingUtxos.forEach((utxo, index) => { console.log(`Boarding UTXO #${index + 1}:`); console.log(` TXID: ${utxo.txid}`); console.log(` Output Index: ${utxo.vout}`); console.log(` Amount: ${utxo.value} sats`); console.log(` Status: ${utxo.status.confirmed ? 'Confirmed' : 'Unconfirmed'}`); }); ``` -------------------------------- ### Create Onchain Wallet for Miner Fees Source: https://docs.arkadeos.com/wallets/advanced/ramps Initializes an onchain wallet to manage Bitcoin for miner fees during the unilateral exit process. Fund the displayed address to cover transaction costs. ```typescript const onchainWallet = new OnchainWallet(wallet.identity, 'regtest'); console.log("Fund this address:", onchainWallet.address) ``` -------------------------------- ### Request Offboarding (Collaborative Exit) Source: https://docs.arkadeos.com/wallets/advanced/ramps Initiate the process to convert your offchain VTXOs back to onchain Bitcoin UTXOs. This requires your destination address, server fee information, and optionally, the amount to exit. ```typescript import { Wallet, MnemonicIdentity } from '@arkade-os/sdk' const identity = MnemonicIdentity.fromMnemonic(mnemonic) const wallet = await Wallet.create({ identity, arkServerUrl: 'https://arkade.computer' }) const info = await wallet.arkProvider.getInfo(); // => ArkInfo object including 'fees' object const exitTxid = await new Ramps(wallet).offboard( destinationAddress, info.fees, amount ); console.log('Exit transaction ID:', exitTxid) ``` -------------------------------- ### Unilateral Exit Initiation using ark-cli Source: https://docs.arkadeos.com/arkd/transactions/exiting-arkade Start a unilateral exit process by using the --force flag. This is typically used when a collaborative exit fails or the operator is unresponsive. You will need to provide your password. ```bash ark-cli redeem --force --password ``` -------------------------------- ### Initialize and Dispose ArkadeSwaps Source: https://docs.arkadeos.com/contracts/chain-swaps Demonstrates the lifecycle management of the ArkadeSwaps instance. It shows how to create an instance with necessary dependencies and how to properly dispose of it when no longer needed. ```typescript const chainSwaps = new ArkadeSwaps({ wallet, swapProvider }) // ... use it await chainSwaps.dispose() ``` -------------------------------- ### new P2WSH Source: https://docs.arkadeos.com/experimental/arkade-functions Creates a Pay-to-Witness-Script-Hash (P2WSH) script. ```APIDOC ## new P2WSH ### Description Creates a Pay-to-Witness-Script-Hash (P2WSH) script. ### Parameters * `witnessScript` (bytes) - The witness script to hash. ### Returns * `bytes` - The P2WSH script. ### Example ```solidity bytes witnessScript = /* complex script */; require(tx.outputs[0].scriptPubKey == new P2WSH(witnessScript), "Output not using correct P2WSH"); ``` ``` -------------------------------- ### Get Transaction History Source: https://docs.arkadeos.com/wallets/operations/payment-history Retrieves the complete transaction history for the wallet. Logs the number of transactions and details for each transaction, including type, amount, settlement status, creation date, and specific transaction IDs if applicable. ```typescript const history = await wallet.getTransactionHistory() console.log('Number of transactions:', history.length) history.forEach((tx, index) => { console.log(`Transaction #${index + 1}:`); console.log(` Type: ${tx.type}`); console.log(` Amount: ${tx.amount} sats`); console.log(` Settled: ${tx.settled ? 'Yes' : 'No'}`); console.log(` Created At: ${tx.createdAt}`); // boarding tx if (tx.key.boardingTxid) { console.log(` Boarding TXID: ${tx.key.boardingTxid}`); } // offchain tx if (tx.key.arkTxid) { console.log(` Ark TXID: ${tx.key.arkTxid}`); } // commitment tx if (tx.key.commitmentTxid) { console.log(` Commitment TXID: ${tx.key.commitmentTxid}`); } }); ``` -------------------------------- ### new P2WPKH Source: https://docs.arkadeos.com/experimental/arkade-functions Creates a Pay-to-Witness-Public-Key-Hash (P2WPKH) script. ```APIDOC ## new P2WPKH ### Description Creates a Pay-to-Witness-Public-Key-Hash (P2WPKH) script. ### Parameters * `pubkey` (pubkey) - The public key to create the script for. ### Returns * `bytes` - The P2WPKH script. ### Example ```solidity require(tx.outputs[0].scriptPubKey == new P2WPKH(recipient), "Output not using P2WPKH"); ``` ``` -------------------------------- ### Get VTXO Status Source: https://docs.arkadeos.com/wallets/advanced/settlement-process Retrieves all VTXOs associated with the wallet and filters them based on their virtual status state, distinguishing between 'preconfirmed' and 'settled' VTXOs. This is useful for monitoring the current state of your assets within the Arkade system. ```typescript const vtxos = await wallet.getVtxos() const pendingVtxos = vtxos.filter(vtxo => vtxo.virtualStatus.state === 'preconfirmed') const settledVtxos = vtxos.filter(vtxo => vtxo.virtualStatus.state === 'settled') console.log('Preconfirmed VTXOs:', pendingVtxos.length) console.log('Settled VTXOs:', settledVtxos.length) ```