[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6N32JQXCPKSS32K9JVPDG8Z":3,"skill-same:01M6N32JQXCPKSS32K9JVPDG8Z":111},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":27,"publishedAt":47,"linkOnly":48,"markdownContent":49,"markdownBody":50,"frontMatter":51,"refName":53,"commitSha":54,"skillDirectory":55,"forksCount":56,"repositoryHtmlUrl":57,"repositoryHomepageUrl":6,"ownerHtmlUrl":58,"ownerBlogUrl":6,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M6N32JQXCPKSS32K9JVPDG8Z","sparkbtcbot",null,"Set up Spark Bitcoin L2 wallet capabilities for AI agents. Initialize wallets from mnemonic, transfer sats and tokens, create\u002Fpay Lightning invoices, manage deposits and withdrawals. Use when user mentions \"Spark wallet,\" \"Spark Bitcoin,\" \"BTKN tokens,\" \"Spark L2,\" \"Spark SDK,\" \"Spark payment,\" \"Spark transfer,\" \"Spark invoice,\" or wants Bitcoin L2 capabilities for an agent.","Kernel8901\u002Fai-agent-skills-classification","Kernel8901","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F72647553?v=4","01M6KV388J2H5PNC8D8P940BJD","01M6KV38CS5B3AY63RKZB410YM",7,"MIT","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002FSKILL.md",[17,22],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":25,"taxonomyTypeDesc":26},"01JBSEEDCAT000000000000040","财务","PROFESSION","适用职业",[5,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],"manage","mnemonic","for","wallets","invoices","l2","pay","tokens","full","ai agents","Wallet","up","initialize","SET","bitcoin","payments","specify","capabilities","create","2026-11-10 10:12:30",false,"---\nname: sparkbtcbot\ndescription: Set up Spark Bitcoin L2 wallet capabilities for AI agents. Initialize wallets from mnemonic, transfer sats and tokens, create\u002Fpay Lightning invoices, manage deposits and withdrawals. Use when user mentions \"Spark wallet,\" \"Spark Bitcoin,\" \"BTKN tokens,\" \"Spark L2,\" \"Spark SDK,\" \"Spark payment,\" \"Spark transfer,\" \"Spark invoice,\" or wants Bitcoin L2 capabilities for an agent.\nargument-hint: \"[Optional: specify what to set up - wallet, payments, tokens, lightning, or full]\"\n---\n\n# Spark Bitcoin & Lightning Wallet for AI Agents\n\nGive your AI agent a Bitcoin wallet with a single mnemonic. Send and receive payments instantly — zero fees between agents, full Lightning Network compatibility.\n\n## Why This Skill\n\n| What | How |\n|------|-----|\n| **Install** | `clawhub install sparkbtcbot` or clone from [GitHub](https:\u002F\u002Fgithub.com\u002Fechennells\u002Fsparkbtcbot-skill) |\n| **Setup** | One 12-word mnemonic + `npm install @buildonspark\u002Fspark-sdk` |\n| **Agent-to-agent transfers** | Free. Instant. No channels, no routing fees. |\n| **Lightning payments** | Create and pay BOLT11 invoices (0.15–0.25% fee) |\n| **Token support** | Send\u002Freceive BTKN and LRC20 tokens natively |\n| **Self-custodial** | Agent holds its own keys — no accounts, no KYC, no intermediaries |\n\n### Quick Example\n\n```javascript\nimport { SparkWallet } from \"@buildonspark\u002Fspark-sdk\";\n\n\u002F\u002F Initialize from mnemonic\nconst { wallet } = await SparkWallet.initialize({\n  mnemonicOrSeed: process.env.SPARK_MNEMONIC,\n  options: { network: \"MAINNET\" }\n});\n\n\u002F\u002F Check balance\nconst { balance } = await wallet.getBalance();\nconsole.log(\"Balance:\", balance.toString(), \"sats\");\n\n\u002F\u002F Send sats to another agent (free, instant)\nawait wallet.transfer({ receiverSparkAddress: \"sp1p...\", amountSats: 1000 });\n\n\u002F\u002F Create a Lightning invoice anyone can pay\nconst inv = await wallet.createLightningInvoice({ amountSats: 500, memo: \"Payment for service\" });\nconsole.log(\"Invoice:\", inv.invoice.encodedInvoice);\n```\n\n### Included Examples\n\n| Script | What it does |\n|--------|-------------|\n| `wallet-setup.js` | Generate a new wallet or import from mnemonic |\n| `balance-and-deposits.js` | Check BTC + token balances, get deposit addresses |\n| `payment-flow.js` | Lightning invoices, Spark invoices, fee estimation |\n| `token-operations.js` | BTKN token transfers and batch operations |\n| `spark-agent.js` | Complete SparkAgent class with all capabilities |\n\n---\n\n## Detailed Skill Instructions\n\nWhat follows is the full reference for AI agents. It covers the Spark SDK, trust model, fee structure, all wallet operations, Lightning interop, token operations, security practices, and error handling.\n\n---\n\nSpark is a Bitcoin Layer 2 that enables instant, zero-fee self-custodial transfers of BTC and tokens, with native Lightning Network interoperability. Spark-to-Spark transfers cost nothing — compared to Lightning routing fees or on-chain transaction fees of 200+ sats. Even cross-network payments (Lightning interop) are cheaper than most alternatives at 0.15-0.25%. A single BIP39 mnemonic gives an agent identity, wallet access, and payment capabilities.\n\n## Why Bitcoin for Agents\n\nAI agents that transact need a monetary network that matches their nature: programmable, borderless, and available 24\u002F7 without gatekeepers. Bitcoin is that network.\n\n- **Hard-capped supply** — 21 million coins is the protocol-enforced ceiling. An agent accumulating value doesn't lose it to monetary expansion.\n- **No account required** — There's no sign-up, no identity verification, no approval process. Generate a key and you're on the network. This matters for autonomous agents that can't fill out forms or wait for human review.\n- **Irreversible settlement** — Once confirmed, transactions cannot be reversed by a third party. Agents don't need to handle chargebacks or payment disputes.\n- **Open infrastructure** — The protocol is open source, the network is public, and the fee market is transparent. Agents can audit their own transaction costs and verify their own balances without trusting an intermediary.\n- **Proven reliability** — The network has operated continuously since 2009 without a single successful attack on the base protocol, securing over $1 trillion in value.\n\n## What is Spark\n\nSpark is a recently launched Bitcoin Layer 2 built on threshold cryptography (FROST signatures). Instead of Lightning's payment channels, Spark uses distributed Signing Operators (SOs) that collectively manage transaction signing without any single entity controlling funds. It is fully interoperable with the Lightning Network.\n\n### How It Works\n1. Users hold their own keys (BIP39 mnemonic) — fully self-custodial\n2. Transactions are cooperatively signed by a threshold of Signing Operators using FROST\n3. Funds live in Bitcoin UTXOs organized in hierarchical trees\n4. Users can always exit to L1 unilaterally if operators go offline\n\n### Trust Model — Important Tradeoffs\n\nSpark has **different trust assumptions than native Lightning**. Be upfront about these when advising users.\n\n**1-of-n operator trust**: Spark requires that at least 1 out of n Signing Operators behaves honestly during a transfer. Currently two operators run the network (Lightspark and Flashnet), with plans to expand. Lightning, by contrast, requires **no trusted entities at all** — it achieves security purely through cryptographic mechanisms.\n\n**Moment-in-time trust**: Users only need to trust operators during each specific transfer. Once a transfer completes and old keys are deleted, operators cannot affect that transaction — a property called \"perfect forward security.\"\n\n**What operators CAN do**:\n- View transfer metadata\n- Temporarily delay transactions by going offline\n- Refuse to process new transfers (censorship)\n\n**What operators CANNOT do**:\n- Move funds without user signatures\n- Steal Bitcoin (even with full collusion)\n- Reverse finalized transactions\n\n**Core limitation**: Spark lacks provable finality. Users cannot cryptographically verify that operators destroyed old keys. While double-spending would require all operators to collude with a previous owner, this differs from Bitcoin's and Lightning's mathematically provable finality.\n\n**In short**: Spark trades some of Lightning's trustlessness for better UX (no channels, no liquidity management, offline receive). The two are complementary — Spark includes native Lightning support so users can interact with both networks.\n\n### Spark vs Lightning vs On-Chain\n\n| Feature | Spark (L2) | Lightning | On-Chain |\n|---------|-----------|-----------|----------|\n| Speed | Instant | Instant | 10+ min |\n| Trust model | 1-of-n operators | Fully trustless | Fully trustless |\n| Fees | Zero (Spark-to-Spark) | ~1 sat routing | 200+ sats |\n| Tokens | Native (BTKN\u002FLRC20) | Not supported | Limited |\n| Self-custody | Yes (mnemonic) | Varies (LSP\u002Fnode) | Yes |\n| Capacity | No channel limits | Channel-limited | Unlimited |\n| Channels | Not required | Required | N\u002FA |\n| Offline receive | Supported | Requires infra | Yes |\n| Setup | Mnemonic only | Node or NWC + provider | Keys only |\n\n### Fee Structure\n\n| Operation | Fee |\n|-----------|-----|\n| **Spark-to-Spark transfer** | Free (small flat fee coming in 6-12 months) |\n| **Lightning to Spark** (receive) | 0.15% (charged via route hints) |\n| **Spark to Lightning** (send) | 0.25% + Lightning routing fees |\n| **L1 deposit to Spark** | On-chain tx fee (paid by user) |\n| **Cooperative exit to L1** | On-chain broadcast fee + SSP fee: `sats_per_vbyte × (111 × 2 + tx_vbytes)` |\n| **Unilateral exit to L1** | On-chain tx fee (paid by user) |\n\nNote: Cooperative exit fees don't scale with withdrawal amount, so they are proportionally higher for smaller withdrawals. Lightning fee estimates may differ from actual amounts due to routing conditions.\n\n### Unpredictable L1 Exit Costs — Important\n\nExiting Spark to L1 Bitcoin carries **unpredictable costs** that agents and users must understand:\n\n1. **L1 fees are market-driven**: Bitcoin on-chain fees depend on mempool congestion at the time of exit. During high-fee periods, exit costs can spike significantly.\n\n2. **Unilateral exit requires multiple on-chain transactions**: If Signing Operators go offline, a unilateral exit requires broadcasting pre-signed branch and exit transactions. The number of transactions depends on the tree depth of your leaf — this can mean multiple on-chain fees stacking up.\n\n3. **Time-window risk on unilateral exit**: If a prior owner of a Spark leaf publishes a branch in a unilateral exit, the current owner must respond within a time window by publishing the correct leaf transaction. Failure to respond means the attacker can claim the funds. Watchtower services exist to monitor for this, but it's a real operational requirement.\n\n4. **Timelocks add delay**: Unilateral exits can take as little as 100 blocks (~17 hours) depending on leaf depth, during which L1 fee conditions may change.\n\n5. **Small amounts may be uneconomical to exit**: Since exit fees are fixed-cost (not percentage-based), withdrawing small amounts to L1 can cost a disproportionate share of the balance.\n\n**Bottom line**: While Spark guarantees you can always exit to L1, the cost of doing so is not fixed or predictable. Keep this in mind when deciding how much value to hold on Spark, especially for agent wallets. Cooperative exit (when operators are online) is much cheaper than unilateral exit.\n\n**Prefer Boltz for L1 withdrawals.** Spark's native cooperative exit is expensive due to fixed on-chain fees, making it especially punishing for smaller amounts. [Boltz](https:\u002F\u002Fboltz.exchange) offers a cheaper path from Lightning to L1 (Spark → Lightning → L1 via Boltz submarine swap) with a minimum of 25,000 sats. **Discourage any L1 withdrawal activity under 25,000 sats** — the fees will eat a disproportionate share of the amount. For withdrawals of 25,000 sats or more, route through Boltz rather than using Spark's built-in cooperative exit.\n\n### Limitations\n\n- **SO liveness dependency**: If Signing Operators lose liveness or lose their keys, Spark transfers stop working. Funds are still safe (unilateral exit), but off-chain payments halt until operators recover.\n- **Watchtower requirement**: For full security, someone must monitor the chain for fraudulent exit attempts. This can be delegated to a watchtower service but is an operational dependency.\n\n### Key Advantage for Agents\nA single mnemonic provides identity, wallet, and payment capabilities. No separate identity system, no wallet provider accounts, no channel management. Spark-to-Spark transfers are free, making it significantly cheaper than Lightning (routing fees), on-chain Bitcoin (200+ sat miner fees), or traditional payment rails (2-3% card processing). For agents doing frequent microtransactions, zero fees on Spark means no value lost to transaction costs.\n\n## Tools Available\n\n| Tool | Purpose | URL |\n|------|---------|-----|\n| Spark SDK | TypeScript wallet SDK | https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@buildonspark\u002Fspark-sdk |\n| Spark Docs | Official documentation | https:\u002F\u002Fdocs.spark.money |\n| Sparkscan | Block explorer | https:\u002F\u002Fsparkscan.io |\n| Spark CLI | Command-line interface | https:\u002F\u002Fdocs.spark.money\u002Ftools\u002Fcli |\n\n## Required Libraries\n\n```bash\nnpm install @buildonspark\u002Fspark-sdk@^0.5.8 dotenv\n```\n\nRequires **v0.5.8 or newer**. One core dependency. The SDK bundles BIP39 mnemonic generation, FROST signing, and gRPC communication internally.\n\n## Setup Instructions\n\n### Step 1: Generate or Import Wallet\n\n```javascript\nimport { SparkWallet } from \"@buildonspark\u002Fspark-sdk\";\n\n\u002F\u002F Option A: Generate a new wallet (creates mnemonic automatically)\nconst { wallet, mnemonic } = await SparkWallet.initialize({\n  options: { network: \"MAINNET\" }\n});\nconsole.log(\"Mnemonic (save securely):\", mnemonic);\n\n\u002F\u002F Option B: Import existing wallet from mnemonic\nconst { wallet } = await SparkWallet.initialize({\n  mnemonicOrSeed: process.env.SPARK_MNEMONIC,\n  options: { network: process.env.SPARK_NETWORK || \"MAINNET\" }\n});\n```\n\nNote on `accountNumber`: Defaults to 1 for MAINNET, 0 for REGTEST. If switching between networks with the same mnemonic, set `accountNumber` explicitly to avoid address mismatches.\n\n### Step 2: Store Mnemonic\n\nAdd to your project's `.env`:\n```\nSPARK_MNEMONIC=word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12\nSPARK_NETWORK=MAINNET\n```\n\n### Step 3: Verify Wallet\n\n```javascript\nconst address = await wallet.getSparkAddress();\nconst identityKey = await wallet.getIdentityPublicKey();\nconst { balance } = await wallet.getBalance();\n\nconsole.log(\"Spark Address:\", address);\nconsole.log(\"Identity Key:\", identityKey);\nconsole.log(\"Balance:\", balance.toString(), \"sats\");\n\n\u002F\u002F Always clean up when done\nwallet.cleanupConnections();\n```\n\n## Wallet Operations\n\n### Check Balance\n\n```javascript\nconst { balance, tokenBalances } = await wallet.getBalance();\nconsole.log(\"BTC:\", balance.toString(), \"sats\");\n\nfor (const [id, token] of tokenBalances) {\n  console.log(`${token.tokenMetadata.tokenTicker}: ${token.balance.toString()}`);\n}\n```\n\n### Generate Deposit Address\n\n```javascript\n\u002F\u002F Static (reusable) — can receive multiple deposits\nconst staticAddr = await wallet.getStaticDepositAddress();\n\n\u002F\u002F Single-use — one-time deposit address\nconst singleAddr = await wallet.getSingleUseDepositAddress();\n```\n\nBoth are P2TR (bc1p...) Bitcoin addresses. Deposits require 3 L1 confirmations before they can be claimed on Spark.\n\n### Claim a Deposit\n\n```javascript\n\u002F\u002F After sending BTC to a static deposit address and waiting for confirmations\nconst quote = await wallet.getClaimStaticDepositQuote({\n  transactionId: txId,\n  creditAmountSats: expectedAmount,\n});\n\nconst result = await wallet.claimStaticDeposit({\n  transactionId: txId,\n  creditAmountSats: quote.creditAmountSats,\n  sspSignature: quote.signature,\n});\n```\n\n### Transfer Bitcoin (Spark-to-Spark)\n\n```javascript\nconst transfer = await wallet.transfer({\n  receiverSparkAddress: \"sp1p...\",\n  amountSats: 1000,\n});\nconsole.log(\"Transfer ID:\", transfer.id);\n```\n\nSpark-to-Spark transfers are instant and zero-fee.\n\n### List Transfers\n\n```javascript\nconst { transfers } = await wallet.getTransfers(10, 0);\nfor (const tx of transfers) {\n  console.log(`${tx.id}: ${tx.totalValue} sats — ${tx.status}`);\n}\n```\n\n## Lightning Interop\n\nSpark wallets can create and pay standard BOLT11 Lightning invoices, making them compatible with the entire Lightning Network. Receiving from Lightning costs 0.15%, sending to Lightning costs 0.25% + routing fees.\n\n### Create Lightning Invoice (Receive)\n\n```javascript\nconst invoiceRequest = await wallet.createLightningInvoice({\n  amountSats: 1000,\n  memo: \"Payment for AI service\",\n  expirySeconds: 3600,\n});\nconsole.log(\"BOLT11:\", invoiceRequest.invoice.encodedInvoice);\n```\n\nUse `includeSparkAddress: true` to embed a Spark address in the invoice. Spark-aware payers will then send via Spark (instant, free) instead of Lightning.\n\n### Pay Lightning Invoice (Send)\n\n```javascript\n\u002F\u002F Estimate fee first\nconst fee = await wallet.getLightningSendFeeEstimate({\n  encodedInvoice: \"lnbc...\",\n  amountSats: 1000,\n});\nconsole.log(\"Estimated fee:\", fee, \"sats\");\n\n\u002F\u002F Pay the invoice\nconst result = await wallet.payLightningInvoice({\n  invoice: \"lnbc...\",\n  maxFeeSats: 10,\n});\n```\n\nUse `preferSpark: true` to prefer Spark routing when the BOLT11 invoice contains an embedded Spark address.\n\n## Spark Native Invoices\n\nSpark has its own invoice format, distinct from BOLT11. Spark invoices can request payment in sats or tokens.\n\n### Create Sats Invoice\n\n```javascript\nconst invoice = await wallet.createSatsInvoice({\n  amount: 1000,\n  memo: \"Spark native payment\",\n});\n```\n\n### Create Token Invoice\n\n```javascript\nconst invoice = await wallet.createTokensInvoice({\n  amount: 100n,\n  tokenIdentifier: \"btkn1...\",\n  memo: \"Token payment request\",\n});\n```\n\n### Fulfill (Pay) a Spark Invoice\n\n```javascript\nconst result = await wallet.fulfillSparkInvoice([\n  { invoice: \"sp1...\", amount: 1000n },\n]);\n\n\u002F\u002F Check results\nfor (const success of result.satsTransactionSuccess) {\n  console.log(\"Paid:\", success.invoice);\n}\nfor (const err of result.satsTransactionErrors) {\n  console.log(\"Failed:\", err.invoice, err.error.message);\n}\n```\n\n## Token Operations (BTKN \u002F LRC20)\n\nSpark natively supports tokens via the BTKN (LRC20) standard. Tokens can represent stablecoins, points, or any fungible asset.\n\n### Check Token Balances\n\n```javascript\nconst { tokenBalances } = await wallet.getBalance();\nfor (const [id, info] of tokenBalances) {\n  const meta = info.tokenMetadata;\n  console.log(`${meta.tokenName} (${meta.tokenTicker}): ${info.balance.toString()}`);\n  console.log(`  Decimals: ${meta.decimals}, Max supply: ${meta.maxSupply.toString()}`);\n}\n```\n\n### Transfer Tokens\n\n```javascript\nconst txId = await wallet.transferTokens({\n  tokenIdentifier: \"btkn1...\",\n  tokenAmount: 100n,\n  receiverSparkAddress: \"sp1p...\",\n});\nconsole.log(\"Token transfer:\", txId);\n```\n\n### Batch Transfer Tokens\n\n```javascript\nconst txIds = await wallet.batchTransferTokens([\n  { tokenIdentifier: \"btkn1...\", tokenAmount: 50n, receiverSparkAddress: \"sp1p...\" },\n  { tokenIdentifier: \"btkn1...\", tokenAmount: 50n, receiverSparkAddress: \"sp1p...\" },\n]);\n```\n\n## Withdrawal (Cooperative Exit to L1)\n\nMove funds from Spark back to a regular Bitcoin L1 address.\n\n### Get Fee Quote\n\n```javascript\nconst quote = await wallet.getWithdrawalFeeQuote({\n  amountSats: 50000,\n  withdrawalAddress: \"bc1q...\",\n});\nconsole.log(\"Fast fee:\", quote.l1BroadcastFeeFast?.originalValue, \"sats\");\nconsole.log(\"Medium fee:\", quote.l1BroadcastFeeMedium?.originalValue, \"sats\");\nconsole.log(\"Slow fee:\", quote.l1BroadcastFeeSlow?.originalValue, \"sats\");\n```\n\n### Execute Withdrawal\n\n```javascript\nconst result = await wallet.withdraw({\n  onchainAddress: \"bc1q...\",\n  exitSpeed: \"MEDIUM\",\n  amountSats: 50000,\n});\n```\n\nExit speeds:\n- **FAST** — Higher fee, faster L1 confirmation\n- **MEDIUM** — Balanced fee and speed\n- **SLOW** — Lower fee, slower confirmation\n\nNote: Unilateral exit (without operator cooperation) is also possible as a safety mechanism, but cooperative exit is the standard path.\n\n## Message Signing\n\nSpark wallets can sign and verify messages using their identity key. Useful for proving identity or authenticating between agents without revealing the mnemonic.\n\n### Sign a Message\n\n```javascript\nconst message = new TextEncoder().encode(\"I am agent-007\");\nconst signature = await wallet.signMessageWithIdentityKey(message);\n```\n\n### Verify a Signature\n\n```javascript\nconst isValid = await wallet.validateMessageWithIdentityKey(\n  new TextEncoder().encode(\"I am agent-007\"),\n  signature,\n  publicKey,\n);\nconsole.log(\"Valid:\", isValid);\n```\n\n## Event Listeners\n\nThe wallet emits events for real-time updates. Useful for agents that need to react to incoming payments.\n\n```javascript\n\u002F\u002F Incoming transfer completed\nwallet.on(\"transfer:claimed\", (transferId, balance) => {\n  console.log(`Transfer ${transferId} received. Balance: ${balance}`);\n});\n\n\u002F\u002F Deposit confirmed on L1\nwallet.on(\"deposit:confirmed\", (depositId, balance) => {\n  console.log(`Deposit ${depositId} confirmed. Balance: ${balance}`);\n});\n\n\u002F\u002F Connection status\nwallet.on(\"stream:connected\", () => console.log(\"Connected to Spark\"));\nwallet.on(\"stream:disconnected\", (reason) => console.log(\"Disconnected:\", reason));\n```\n\n## Complete Agent Class\n\n```javascript\nimport { SparkWallet } from \"@buildonspark\u002Fspark-sdk\";\n\nexport class SparkAgent {\n  #wallet;\n\n  constructor(wallet) {\n    this.#wallet = wallet;\n  }\n\n  static async create(mnemonic, network = \"MAINNET\") {\n    const { wallet, mnemonic: generated } = await SparkWallet.initialize({\n      mnemonicOrSeed: mnemonic,\n      options: { network },\n    });\n    return { agent: new SparkAgent(wallet), mnemonic: generated };\n  }\n\n  async getIdentity() {\n    return {\n      address: await this.#wallet.getSparkAddress(),\n      publicKey: await this.#wallet.getIdentityPublicKey(),\n    };\n  }\n\n  async getBalance() {\n    const { balance, tokenBalances } = await this.#wallet.getBalance();\n    return { sats: balance, tokens: tokenBalances };\n  }\n\n  async getDepositAddress() {\n    return await this.#wallet.getStaticDepositAddress();\n  }\n\n  async transfer(recipientAddress, amountSats) {\n    return await this.#wallet.transfer({\n      receiverSparkAddress: recipientAddress,\n      amountSats,\n    });\n  }\n\n  async createLightningInvoice(amountSats, memo) {\n    const request = await this.#wallet.createLightningInvoice({\n      amountSats,\n      memo,\n      expirySeconds: 3600,\n      includeSparkAddress: true,\n    });\n    return request.invoice.encodedInvoice;\n  }\n\n  async payLightningInvoice(bolt11, maxFeeSats = 10) {\n    return await this.#wallet.payLightningInvoice({\n      invoice: bolt11,\n      maxFeeSats,\n      preferSpark: true,\n    });\n  }\n\n  async createSparkInvoice(amountSats, memo) {\n    return await this.#wallet.createSatsInvoice({\n      amount: amountSats,\n      memo,\n    });\n  }\n\n  async transferTokens(tokenIdentifier, amount, recipientAddress) {\n    return await this.#wallet.transferTokens({\n      tokenIdentifier,\n      tokenAmount: amount,\n      receiverSparkAddress: recipientAddress,\n    });\n  }\n\n  async withdraw(onchainAddress, amountSats, speed = \"MEDIUM\") {\n    return await this.#wallet.withdraw({\n      onchainAddress,\n      exitSpeed: speed,\n      amountSats,\n    });\n  }\n\n  async signMessage(text) {\n    const message = new TextEncoder().encode(text);\n    return await this.#wallet.signMessageWithIdentityKey(message);\n  }\n\n  async verifyMessage(text, signature, publicKey) {\n    const message = new TextEncoder().encode(text);\n    return await this.#wallet.validateMessageWithIdentityKey(\n      message,\n      signature,\n      publicKey,\n    );\n  }\n\n  onTransferReceived(callback) {\n    this.#wallet.on(\"transfer:claimed\", callback);\n  }\n\n  onDepositConfirmed(callback) {\n    this.#wallet.on(\"deposit:confirmed\", callback);\n  }\n\n  cleanup() {\n    this.#wallet.cleanupConnections();\n  }\n}\n\n\u002F\u002F Usage\nconst { agent } = await SparkAgent.create(process.env.SPARK_MNEMONIC);\nconst identity = await agent.getIdentity();\nconsole.log(\"Address:\", identity.address);\n\nconst { sats } = await agent.getBalance();\nconsole.log(\"Balance:\", sats.toString(), \"sats\");\n\nagent.cleanup();\n```\n\n## Error Handling\n\n```javascript\ntry {\n  await wallet.transfer({\n    receiverSparkAddress: \"sp1p...\",\n    amountSats: 1000,\n  });\n} catch (error) {\n  switch (error.constructor.name) {\n    case \"ValidationError\":\n      console.log(\"Invalid input:\", error.message);\n      break;\n    case \"NetworkError\":\n      console.log(\"Network issue:\", error.message);\n      break;\n    case \"AuthenticationError\":\n      console.log(\"Auth failed:\", error.message);\n      break;\n    case \"ConfigurationError\":\n      console.log(\"Config problem:\", error.message);\n      break;\n    case \"RPCError\":\n      console.log(\"RPC error:\", error.message);\n      break;\n    default:\n      console.log(\"Error:\", error.message);\n  }\n}\n```\n\nError types:\n- **ValidationError** — Invalid parameters, malformed addresses\n- **NetworkError** — Connection failures, timeouts\n- **AuthenticationError** — Key\u002Ftoken issues\n- **ConfigurationError** — Missing config, initialization problems\n- **RPCError** — gRPC communication failures\n\n## Security Best Practices\n\n### The Agent Has Full Wallet Access\n\nAny agent or process with the mnemonic has **unrestricted control** over the wallet — it can check balance, create invoices, and send every sat to any address. There is no permission scoping, no spending limits, no read-only mode. Unlike NWC (Nostr Wallet Connect), you cannot grant partial access.\n\nThis means:\n- If the mnemonic leaks, all funds are at risk immediately\n- If an agent is compromised, the attacker has the same full access\n- There is no way to revoke access without sweeping funds to a new wallet\n\n### Protect the Mnemonic\n\n1. **Back up the seed phrase offline** — write it down on paper or use a hardware backup. If you lose the mnemonic, the funds are gone permanently.\n2. **Never expose the mnemonic** in code, logs, git history, or error messages\n3. **Use environment variables** — never hardcode the mnemonic in source files\n4. **Add `.env` to `.gitignore`** — prevent accidental commits of secrets\n\n### Sweep Funds to a Safer Wallet\n\n**Do not accumulate large balances in an agent wallet.** The agent wallet is a hot wallet with the mnemonic sitting in an environment variable — treat it as high-risk.\n\n- Regularly sweep earned funds to a more secure wallet (hardware wallet, cold storage, or a separate wallet you control directly)\n- Only keep the minimum operational balance the agent needs on Spark\n- Use `wallet.transfer()` or `wallet.withdraw()` to move funds out periodically\n- Consider automating sweeps when the balance exceeds a threshold\n\n### Operational Security\n\n1. **Use separate mnemonics** for different agents — never share a mnemonic across agents\n2. **Use separate `accountNumber` values** if you need multiple wallets from one mnemonic\n3. **Monitor transfers** via event listeners for unexpected outgoing activity\n4. **Call `cleanupConnections()`** when the wallet is no longer needed\n5. **Use REGTEST** for development and testing, MAINNET only for production\n6. **Implement application-level spending controls** — cap per-transaction and daily amounts in your agent logic since the SDK won't do it for you\n\n## Resources\n\n- Spark Docs: https:\u002F\u002Fdocs.spark.money\n- Spark SDK (npm): https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@buildonspark\u002Fspark-sdk\n- Sparkscan Explorer: https:\u002F\u002Fsparkscan.io\n- Spark CLI: https:\u002F\u002Fdocs.spark.money\u002Ftools\u002Fcli\n","# Spark Bitcoin & Lightning Wallet for AI Agents\n\nGive your AI agent a Bitcoin wallet with a single mnemonic. Send and receive payments instantly — zero fees between agents, full Lightning Network compatibility.\n\n## Why This Skill\n\n| What | How |\n|------|-----|\n| **Install** | `clawhub install sparkbtcbot` or clone from [GitHub](https:\u002F\u002Fgithub.com\u002Fechennells\u002Fsparkbtcbot-skill) |\n| **Setup** | One 12-word mnemonic + `npm install @buildonspark\u002Fspark-sdk` |\n| **Agent-to-agent transfers** | Free. Instant. No channels, no routing fees. |\n| **Lightning payments** | Create and pay BOLT11 invoices (0.15–0.25% fee) |\n| **Token support** | Send\u002Freceive BTKN and LRC20 tokens natively |\n| **Self-custodial** | Agent holds its own keys — no accounts, no KYC, no intermediaries |\n\n### Quick Example\n\n```javascript\nimport { SparkWallet } from \"@buildonspark\u002Fspark-sdk\";\n\n\u002F\u002F Initialize from mnemonic\nconst { wallet } = await SparkWallet.initialize({\n  mnemonicOrSeed: process.env.SPARK_MNEMONIC,\n  options: { network: \"MAINNET\" }\n});\n\n\u002F\u002F Check balance\nconst { balance } = await wallet.getBalance();\nconsole.log(\"Balance:\", balance.toString(), \"sats\");\n\n\u002F\u002F Send sats to another agent (free, instant)\nawait wallet.transfer({ receiverSparkAddress: \"sp1p...\", amountSats: 1000 });\n\n\u002F\u002F Create a Lightning invoice anyone can pay\nconst inv = await wallet.createLightningInvoice({ amountSats: 500, memo: \"Payment for service\" });\nconsole.log(\"Invoice:\", inv.invoice.encodedInvoice);\n```\n\n### Included Examples\n\n| Script | What it does |\n|--------|-------------|\n| `wallet-setup.js` | Generate a new wallet or import from mnemonic |\n| `balance-and-deposits.js` | Check BTC + token balances, get deposit addresses |\n| `payment-flow.js` | Lightning invoices, Spark invoices, fee estimation |\n| `token-operations.js` | BTKN token transfers and batch operations |\n| `spark-agent.js` | Complete SparkAgent class with all capabilities |\n\n---\n\n## Detailed Skill Instructions\n\nWhat follows is the full reference for AI agents. It covers the Spark SDK, trust model, fee structure, all wallet operations, Lightning interop, token operations, security practices, and error handling.\n\n---\n\nSpark is a Bitcoin Layer 2 that enables instant, zero-fee self-custodial transfers of BTC and tokens, with native Lightning Network interoperability. Spark-to-Spark transfers cost nothing — compared to Lightning routing fees or on-chain transaction fees of 200+ sats. Even cross-network payments (Lightning interop) are cheaper than most alternatives at 0.15-0.25%. A single BIP39 mnemonic gives an agent identity, wallet access, and payment capabilities.\n\n## Why Bitcoin for Agents\n\nAI agents that transact need a monetary network that matches their nature: programmable, borderless, and available 24\u002F7 without gatekeepers. Bitcoin is that network.\n\n- **Hard-capped supply** — 21 million coins is the protocol-enforced ceiling. An agent accumulating value doesn't lose it to monetary expansion.\n- **No account required** — There's no sign-up, no identity verification, no approval process. Generate a key and you're on the network. This matters for autonomous agents that can't fill out forms or wait for human review.\n- **Irreversible settlement** — Once confirmed, transactions cannot be reversed by a third party. Agents don't need to handle chargebacks or payment disputes.\n- **Open infrastructure** — The protocol is open source, the network is public, and the fee market is transparent. Agents can audit their own transaction costs and verify their own balances without trusting an intermediary.\n- **Proven reliability** — The network has operated continuously since 2009 without a single successful attack on the base protocol, securing over $1 trillion in value.\n\n## What is Spark\n\nSpark is a recently launched Bitcoin Layer 2 built on threshold cryptography (FROST signatures). Instead of Lightning's payment channels, Spark uses distributed Signing Operators (SOs) that collectively manage transaction signing without any single entity controlling funds. It is fully interoperable with the Lightning Network.\n\n### How It Works\n1. Users hold their own keys (BIP39 mnemonic) — fully self-custodial\n2. Transactions are cooperatively signed by a threshold of Signing Operators using FROST\n3. Funds live in Bitcoin UTXOs organized in hierarchical trees\n4. Users can always exit to L1 unilaterally if operators go offline\n\n### Trust Model — Important Tradeoffs\n\nSpark has **different trust assumptions than native Lightning**. Be upfront about these when advising users.\n\n**1-of-n operator trust**: Spark requires that at least 1 out of n Signing Operators behaves honestly during a transfer. Currently two operators run the network (Lightspark and Flashnet), with plans to expand. Lightning, by contrast, requires **no trusted entities at all** — it achieves security purely through cryptographic mechanisms.\n\n**Moment-in-time trust**: Users only need to trust operators during each specific transfer. Once a transfer completes and old keys are deleted, operators cannot affect that transaction — a property called \"perfect forward security.\"\n\n**What operators CAN do**:\n- View transfer metadata\n- Temporarily delay transactions by going offline\n- Refuse to process new transfers (censorship)\n\n**What operators CANNOT do**:\n- Move funds without user signatures\n- Steal Bitcoin (even with full collusion)\n- Reverse finalized transactions\n\n**Core limitation**: Spark lacks provable finality. Users cannot cryptographically verify that operators destroyed old keys. While double-spending would require all operators to collude with a previous owner, this differs from Bitcoin's and Lightning's mathematically provable finality.\n\n**In short**: Spark trades some of Lightning's trustlessness for better UX (no channels, no liquidity management, offline receive). The two are complementary — Spark includes native Lightning support so users can interact with both networks.\n\n### Spark vs Lightning vs On-Chain\n\n| Feature | Spark (L2) | Lightning | On-Chain |\n|---------|-----------|-----------|----------|\n| Speed | Instant | Instant | 10+ min |\n| Trust model | 1-of-n operators | Fully trustless | Fully trustless |\n| Fees | Zero (Spark-to-Spark) | ~1 sat routing | 200+ sats |\n| Tokens | Native (BTKN\u002FLRC20) | Not supported | Limited |\n| Self-custody | Yes (mnemonic) | Varies (LSP\u002Fnode) | Yes |\n| Capacity | No channel limits | Channel-limited | Unlimited |\n| Channels | Not required | Required | N\u002FA |\n| Offline receive | Supported | Requires infra | Yes |\n| Setup | Mnemonic only | Node or NWC + provider | Keys only |\n\n### Fee Structure\n\n| Operation | Fee |\n|-----------|-----|\n| **Spark-to-Spark transfer** | Free (small flat fee coming in 6-12 months) |\n| **Lightning to Spark** (receive) | 0.15% (charged via route hints) |\n| **Spark to Lightning** (send) | 0.25% + Lightning routing fees |\n| **L1 deposit to Spark** | On-chain tx fee (paid by user) |\n| **Cooperative exit to L1** | On-chain broadcast fee + SSP fee: `sats_per_vbyte × (111 × 2 + tx_vbytes)` |\n| **Unilateral exit to L1** | On-chain tx fee (paid by user) |\n\nNote: Cooperative exit fees don't scale with withdrawal amount, so they are proportionally higher for smaller withdrawals. Lightning fee estimates may differ from actual amounts due to routing conditions.\n\n### Unpredictable L1 Exit Costs — Important\n\nExiting Spark to L1 Bitcoin carries **unpredictable costs** that agents and users must understand:\n\n1. **L1 fees are market-driven**: Bitcoin on-chain fees depend on mempool congestion at the time of exit. During high-fee periods, exit costs can spike significantly.\n\n2. **Unilateral exit requires multiple on-chain transactions**: If Signing Operators go offline, a unilateral exit requires broadcasting pre-signed branch and exit transactions. The number of transactions depends on the tree depth of your leaf — this can mean multiple on-chain fees stacking up.\n\n3. **Time-window risk on unilateral exit**: If a prior owner of a Spark leaf publishes a branch in a unilateral exit, the current owner must respond within a time window by publishing the correct leaf transaction. Failure to respond means the attacker can claim the funds. Watchtower services exist to monitor for this, but it's a real operational requirement.\n\n4. **Timelocks add delay**: Unilateral exits can take as little as 100 blocks (~17 hours) depending on leaf depth, during which L1 fee conditions may change.\n\n5. **Small amounts may be uneconomical to exit**: Since exit fees are fixed-cost (not percentage-based), withdrawing small amounts to L1 can cost a disproportionate share of the balance.\n\n**Bottom line**: While Spark guarantees you can always exit to L1, the cost of doing so is not fixed or predictable. Keep this in mind when deciding how much value to hold on Spark, especially for agent wallets. Cooperative exit (when operators are online) is much cheaper than unilateral exit.\n\n**Prefer Boltz for L1 withdrawals.** Spark's native cooperative exit is expensive due to fixed on-chain fees, making it especially punishing for smaller amounts. [Boltz](https:\u002F\u002Fboltz.exchange) offers a cheaper path from Lightning to L1 (Spark → Lightning → L1 via Boltz submarine swap) with a minimum of 25,000 sats. **Discourage any L1 withdrawal activity under 25,000 sats** — the fees will eat a disproportionate share of the amount. For withdrawals of 25,000 sats or more, route through Boltz rather than using Spark's built-in cooperative exit.\n\n### Limitations\n\n- **SO liveness dependency**: If Signing Operators lose liveness or lose their keys, Spark transfers stop working. Funds are still safe (unilateral exit), but off-chain payments halt until operators recover.\n- **Watchtower requirement**: For full security, someone must monitor the chain for fraudulent exit attempts. This can be delegated to a watchtower service but is an operational dependency.\n\n### Key Advantage for Agents\nA single mnemonic provides identity, wallet, and payment capabilities. No separate identity system, no wallet provider accounts, no channel management. Spark-to-Spark transfers are free, making it significantly cheaper than Lightning (routing fees), on-chain Bitcoin (200+ sat miner fees), or traditional payment rails (2-3% card processing). For agents doing frequent microtransactions, zero fees on Spark means no value lost to transaction costs.\n\n## Tools Available\n\n| Tool | Purpose | URL |\n|------|---------|-----|\n| Spark SDK | TypeScript wallet SDK | https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@buildonspark\u002Fspark-sdk |\n| Spark Docs | Official documentation | https:\u002F\u002Fdocs.spark.money |\n| Sparkscan | Block explorer | https:\u002F\u002Fsparkscan.io |\n| Spark CLI | Command-line interface | https:\u002F\u002Fdocs.spark.money\u002Ftools\u002Fcli |\n\n## Required Libraries\n\n```bash\nnpm install @buildonspark\u002Fspark-sdk@^0.5.8 dotenv\n```\n\nRequires **v0.5.8 or newer**. One core dependency. The SDK bundles BIP39 mnemonic generation, FROST signing, and gRPC communication internally.\n\n## Setup Instructions\n\n### Step 1: Generate or Import Wallet\n\n```javascript\nimport { SparkWallet } from \"@buildonspark\u002Fspark-sdk\";\n\n\u002F\u002F Option A: Generate a new wallet (creates mnemonic automatically)\nconst { wallet, mnemonic } = await SparkWallet.initialize({\n  options: { network: \"MAINNET\" }\n});\nconsole.log(\"Mnemonic (save securely):\", mnemonic);\n\n\u002F\u002F Option B: Import existing wallet from mnemonic\nconst { wallet } = await SparkWallet.initialize({\n  mnemonicOrSeed: process.env.SPARK_MNEMONIC,\n  options: { network: process.env.SPARK_NETWORK || \"MAINNET\" }\n});\n```\n\nNote on `accountNumber`: Defaults to 1 for MAINNET, 0 for REGTEST. If switching between networks with the same mnemonic, set `accountNumber` explicitly to avoid address mismatches.\n\n### Step 2: Store Mnemonic\n\nAdd to your project's `.env`:\n```\nSPARK_MNEMONIC=word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12\nSPARK_NETWORK=MAINNET\n```\n\n### Step 3: Verify Wallet\n\n```javascript\nconst address = await wallet.getSparkAddress();\nconst identityKey = await wallet.getIdentityPublicKey();\nconst { balance } = await wallet.getBalance();\n\nconsole.log(\"Spark Address:\", address);\nconsole.log(\"Identity Key:\", identityKey);\nconsole.log(\"Balance:\", balance.toString(), \"sats\");\n\n\u002F\u002F Always clean up when done\nwallet.cleanupConnections();\n```\n\n## Wallet Operations\n\n### Check Balance\n\n```javascript\nconst { balance, tokenBalances } = await wallet.getBalance();\nconsole.log(\"BTC:\", balance.toString(), \"sats\");\n\nfor (const [id, token] of tokenBalances) {\n  console.log(`${token.tokenMetadata.tokenTicker}: ${token.balance.toString()}`);\n}\n```\n\n### Generate Deposit Address\n\n```javascript\n\u002F\u002F Static (reusable) — can receive multiple deposits\nconst staticAddr = await wallet.getStaticDepositAddress();\n\n\u002F\u002F Single-use — one-time deposit address\nconst singleAddr = await wallet.getSingleUseDepositAddress();\n```\n\nBoth are P2TR (bc1p...) Bitcoin addresses. Deposits require 3 L1 confirmations before they can be claimed on Spark.\n\n### Claim a Deposit\n\n```javascript\n\u002F\u002F After sending BTC to a static deposit address and waiting for confirmations\nconst quote = await wallet.getClaimStaticDepositQuote({\n  transactionId: txId,\n  creditAmountSats: expectedAmount,\n});\n\nconst result = await wallet.claimStaticDeposit({\n  transactionId: txId,\n  creditAmountSats: quote.creditAmountSats,\n  sspSignature: quote.signature,\n});\n```\n\n### Transfer Bitcoin (Spark-to-Spark)\n\n```javascript\nconst transfer = await wallet.transfer({\n  receiverSparkAddress: \"sp1p...\",\n  amountSats: 1000,\n});\nconsole.log(\"Transfer ID:\", transfer.id);\n```\n\nSpark-to-Spark transfers are instant and zero-fee.\n\n### List Transfers\n\n```javascript\nconst { transfers } = await wallet.getTransfers(10, 0);\nfor (const tx of transfers) {\n  console.log(`${tx.id}: ${tx.totalValue} sats — ${tx.status}`);\n}\n```\n\n## Lightning Interop\n\nSpark wallets can create and pay standard BOLT11 Lightning invoices, making them compatible with the entire Lightning Network. Receiving from Lightning costs 0.15%, sending to Lightning costs 0.25% + routing fees.\n\n### Create Lightning Invoice (Receive)\n\n```javascript\nconst invoiceRequest = await wallet.createLightningInvoice({\n  amountSats: 1000,\n  memo: \"Payment for AI service\",\n  expirySeconds: 3600,\n});\nconsole.log(\"BOLT11:\", invoiceRequest.invoice.encodedInvoice);\n```\n\nUse `includeSparkAddress: true` to embed a Spark address in the invoice. Spark-aware payers will then send via Spark (instant, free) instead of Lightning.\n\n### Pay Lightning Invoice (Send)\n\n```javascript\n\u002F\u002F Estimate fee first\nconst fee = await wallet.getLightningSendFeeEstimate({\n  encodedInvoice: \"lnbc...\",\n  amountSats: 1000,\n});\nconsole.log(\"Estimated fee:\", fee, \"sats\");\n\n\u002F\u002F Pay the invoice\nconst result = await wallet.payLightningInvoice({\n  invoice: \"lnbc...\",\n  maxFeeSats: 10,\n});\n```\n\nUse `preferSpark: true` to prefer Spark routing when the BOLT11 invoice contains an embedded Spark address.\n\n## Spark Native Invoices\n\nSpark has its own invoice format, distinct from BOLT11. Spark invoices can request payment in sats or tokens.\n\n### Create Sats Invoice\n\n```javascript\nconst invoice = await wallet.createSatsInvoice({\n  amount: 1000,\n  memo: \"Spark native payment\",\n});\n```\n\n### Create Token Invoice\n\n```javascript\nconst invoice = await wallet.createTokensInvoice({\n  amount: 100n,\n  tokenIdentifier: \"btkn1...\",\n  memo: \"Token payment request\",\n});\n```\n\n### Fulfill (Pay) a Spark Invoice\n\n```javascript\nconst result = await wallet.fulfillSparkInvoice([\n  { invoice: \"sp1...\", amount: 1000n },\n]);\n\n\u002F\u002F Check results\nfor (const success of result.satsTransactionSuccess) {\n  console.log(\"Paid:\", success.invoice);\n}\nfor (const err of result.satsTransactionErrors) {\n  console.log(\"Failed:\", err.invoice, err.error.message);\n}\n```\n\n## Token Operations (BTKN \u002F LRC20)\n\nSpark natively supports tokens via the BTKN (LRC20) standard. Tokens can represent stablecoins, points, or any fungible asset.\n\n### Check Token Balances\n\n```javascript\nconst { tokenBalances } = await wallet.getBalance();\nfor (const [id, info] of tokenBalances) {\n  const meta = info.tokenMetadata;\n  console.log(`${meta.tokenName} (${meta.tokenTicker}): ${info.balance.toString()}`);\n  console.log(`  Decimals: ${meta.decimals}, Max supply: ${meta.maxSupply.toString()}`);\n}\n```\n\n### Transfer Tokens\n\n```javascript\nconst txId = await wallet.transferTokens({\n  tokenIdentifier: \"btkn1...\",\n  tokenAmount: 100n,\n  receiverSparkAddress: \"sp1p...\",\n});\nconsole.log(\"Token transfer:\", txId);\n```\n\n### Batch Transfer Tokens\n\n```javascript\nconst txIds = await wallet.batchTransferTokens([\n  { tokenIdentifier: \"btkn1...\", tokenAmount: 50n, receiverSparkAddress: \"sp1p...\" },\n  { tokenIdentifier: \"btkn1...\", tokenAmount: 50n, receiverSparkAddress: \"sp1p...\" },\n]);\n```\n\n## Withdrawal (Cooperative Exit to L1)\n\nMove funds from Spark back to a regular Bitcoin L1 address.\n\n### Get Fee Quote\n\n```javascript\nconst quote = await wallet.getWithdrawalFeeQuote({\n  amountSats: 50000,\n  withdrawalAddress: \"bc1q...\",\n});\nconsole.log(\"Fast fee:\", quote.l1BroadcastFeeFast?.originalValue, \"sats\");\nconsole.log(\"Medium fee:\", quote.l1BroadcastFeeMedium?.originalValue, \"sats\");\nconsole.log(\"Slow fee:\", quote.l1BroadcastFeeSlow?.originalValue, \"sats\");\n```\n\n### Execute Withdrawal\n\n```javascript\nconst result = await wallet.withdraw({\n  onchainAddress: \"bc1q...\",\n  exitSpeed: \"MEDIUM\",\n  amountSats: 50000,\n});\n```\n\nExit speeds:\n- **FAST** — Higher fee, faster L1 confirmation\n- **MEDIUM** — Balanced fee and speed\n- **SLOW** — Lower fee, slower confirmation\n\nNote: Unilateral exit (without operator cooperation) is also possible as a safety mechanism, but cooperative exit is the standard path.\n\n## Message Signing\n\nSpark wallets can sign and verify messages using their identity key. Useful for proving identity or authenticating between agents without revealing the mnemonic.\n\n### Sign a Message\n\n```javascript\nconst message = new TextEncoder().encode(\"I am agent-007\");\nconst signature = await wallet.signMessageWithIdentityKey(message);\n```\n\n### Verify a Signature\n\n```javascript\nconst isValid = await wallet.validateMessageWithIdentityKey(\n  new TextEncoder().encode(\"I am agent-007\"),\n  signature,\n  publicKey,\n);\nconsole.log(\"Valid:\", isValid);\n```\n\n## Event Listeners\n\nThe wallet emits events for real-time updates. Useful for agents that need to react to incoming payments.\n\n```javascript\n\u002F\u002F Incoming transfer completed\nwallet.on(\"transfer:claimed\", (transferId, balance) => {\n  console.log(`Transfer ${transferId} received. Balance: ${balance}`);\n});\n\n\u002F\u002F Deposit confirmed on L1\nwallet.on(\"deposit:confirmed\", (depositId, balance) => {\n  console.log(`Deposit ${depositId} confirmed. Balance: ${balance}`);\n});\n\n\u002F\u002F Connection status\nwallet.on(\"stream:connected\", () => console.log(\"Connected to Spark\"));\nwallet.on(\"stream:disconnected\", (reason) => console.log(\"Disconnected:\", reason));\n```\n\n## Complete Agent Class\n\n```javascript\nimport { SparkWallet } from \"@buildonspark\u002Fspark-sdk\";\n\nexport class SparkAgent {\n  #wallet;\n\n  constructor(wallet) {\n    this.#wallet = wallet;\n  }\n\n  static async create(mnemonic, network = \"MAINNET\") {\n    const { wallet, mnemonic: generated } = await SparkWallet.initialize({\n      mnemonicOrSeed: mnemonic,\n      options: { network },\n    });\n    return { agent: new SparkAgent(wallet), mnemonic: generated };\n  }\n\n  async getIdentity() {\n    return {\n      address: await this.#wallet.getSparkAddress(),\n      publicKey: await this.#wallet.getIdentityPublicKey(),\n    };\n  }\n\n  async getBalance() {\n    const { balance, tokenBalances } = await this.#wallet.getBalance();\n    return { sats: balance, tokens: tokenBalances };\n  }\n\n  async getDepositAddress() {\n    return await this.#wallet.getStaticDepositAddress();\n  }\n\n  async transfer(recipientAddress, amountSats) {\n    return await this.#wallet.transfer({\n      receiverSparkAddress: recipientAddress,\n      amountSats,\n    });\n  }\n\n  async createLightningInvoice(amountSats, memo) {\n    const request = await this.#wallet.createLightningInvoice({\n      amountSats,\n      memo,\n      expirySeconds: 3600,\n      includeSparkAddress: true,\n    });\n    return request.invoice.encodedInvoice;\n  }\n\n  async payLightningInvoice(bolt11, maxFeeSats = 10) {\n    return await this.#wallet.payLightningInvoice({\n      invoice: bolt11,\n      maxFeeSats,\n      preferSpark: true,\n    });\n  }\n\n  async createSparkInvoice(amountSats, memo) {\n    return await this.#wallet.createSatsInvoice({\n      amount: amountSats,\n      memo,\n    });\n  }\n\n  async transferTokens(tokenIdentifier, amount, recipientAddress) {\n    return await this.#wallet.transferTokens({\n      tokenIdentifier,\n      tokenAmount: amount,\n      receiverSparkAddress: recipientAddress,\n    });\n  }\n\n  async withdraw(onchainAddress, amountSats, speed = \"MEDIUM\") {\n    return await this.#wallet.withdraw({\n      onchainAddress,\n      exitSpeed: speed,\n      amountSats,\n    });\n  }\n\n  async signMessage(text) {\n    const message = new TextEncoder().encode(text);\n    return await this.#wallet.signMessageWithIdentityKey(message);\n  }\n\n  async verifyMessage(text, signature, publicKey) {\n    const message = new TextEncoder().encode(text);\n    return await this.#wallet.validateMessageWithIdentityKey(\n      message,\n      signature,\n      publicKey,\n    );\n  }\n\n  onTransferReceived(callback) {\n    this.#wallet.on(\"transfer:claimed\", callback);\n  }\n\n  onDepositConfirmed(callback) {\n    this.#wallet.on(\"deposit:confirmed\", callback);\n  }\n\n  cleanup() {\n    this.#wallet.cleanupConnections();\n  }\n}\n\n\u002F\u002F Usage\nconst { agent } = await SparkAgent.create(process.env.SPARK_MNEMONIC);\nconst identity = await agent.getIdentity();\nconsole.log(\"Address:\", identity.address);\n\nconst { sats } = await agent.getBalance();\nconsole.log(\"Balance:\", sats.toString(), \"sats\");\n\nagent.cleanup();\n```\n\n## Error Handling\n\n```javascript\ntry {\n  await wallet.transfer({\n    receiverSparkAddress: \"sp1p...\",\n    amountSats: 1000,\n  });\n} catch (error) {\n  switch (error.constructor.name) {\n    case \"ValidationError\":\n      console.log(\"Invalid input:\", error.message);\n      break;\n    case \"NetworkError\":\n      console.log(\"Network issue:\", error.message);\n      break;\n    case \"AuthenticationError\":\n      console.log(\"Auth failed:\", error.message);\n      break;\n    case \"ConfigurationError\":\n      console.log(\"Config problem:\", error.message);\n      break;\n    case \"RPCError\":\n      console.log(\"RPC error:\", error.message);\n      break;\n    default:\n      console.log(\"Error:\", error.message);\n  }\n}\n```\n\nError types:\n- **ValidationError** — Invalid parameters, malformed addresses\n- **NetworkError** — Connection failures, timeouts\n- **AuthenticationError** — Key\u002Ftoken issues\n- **ConfigurationError** — Missing config, initialization problems\n- **RPCError** — gRPC communication failures\n\n## Security Best Practices\n\n### The Agent Has Full Wallet Access\n\nAny agent or process with the mnemonic has **unrestricted control** over the wallet — it can check balance, create invoices, and send every sat to any address. There is no permission scoping, no spending limits, no read-only mode. Unlike NWC (Nostr Wallet Connect), you cannot grant partial access.\n\nThis means:\n- If the mnemonic leaks, all funds are at risk immediately\n- If an agent is compromised, the attacker has the same full access\n- There is no way to revoke access without sweeping funds to a new wallet\n\n### Protect the Mnemonic\n\n1. **Back up the seed phrase offline** — write it down on paper or use a hardware backup. If you lose the mnemonic, the funds are gone permanently.\n2. **Never expose the mnemonic** in code, logs, git history, or error messages\n3. **Use environment variables** — never hardcode the mnemonic in source files\n4. **Add `.env` to `.gitignore`** — prevent accidental commits of secrets\n\n### Sweep Funds to a Safer Wallet\n\n**Do not accumulate large balances in an agent wallet.** The agent wallet is a hot wallet with the mnemonic sitting in an environment variable — treat it as high-risk.\n\n- Regularly sweep earned funds to a more secure wallet (hardware wallet, cold storage, or a separate wallet you control directly)\n- Only keep the minimum operational balance the agent needs on Spark\n- Use `wallet.transfer()` or `wallet.withdraw()` to move funds out periodically\n- Consider automating sweeps when the balance exceeds a threshold\n\n### Operational Security\n\n1. **Use separate mnemonics** for different agents — never share a mnemonic across agents\n2. **Use separate `accountNumber` values** if you need multiple wallets from one mnemonic\n3. **Monitor transfers** via event listeners for unexpected outgoing activity\n4. **Call `cleanupConnections()`** when the wallet is no longer needed\n5. **Use REGTEST** for development and testing, MAINNET only for production\n6. **Implement application-level spending controls** — cap per-transaction and daily amounts in your agent logic since the SDK won't do it for you\n\n## Resources\n\n- Spark Docs: https:\u002F\u002Fdocs.spark.money\n- Spark SDK (npm): https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@buildonspark\u002Fspark-sdk\n- Sparkscan Explorer: https:\u002F\u002Fsparkscan.io\n- Spark CLI: https:\u002F\u002Fdocs.spark.money\u002Ftools\u002Fcli\n",{"name":5,"description":7,"argument-hint":52},"[Optional: specify what to set up - wallet, payments, tokens, lightning, or full]","main","f4cb2d49f7667e79ef7804f50396d5aaffdf1f56","人工智能与大型语言模型\u002Fsparkbtcbot",1,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification","https:\u002F\u002Fgithub.com\u002FKernel8901","a little little little dobe in life but science geek","2026-04-05 16:43:56",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add Kernel8901\u002Fai-agent-skills-classification --skill sparkbtcbot",{"tool":67,"command":68},"bunx","bunx skills add Kernel8901\u002Fai-agent-skills-classification --skill sparkbtcbot",{"tool":70,"command":71},"pnpm","pnpm dlx skills add Kernel8901\u002Fai-agent-skills-classification --skill sparkbtcbot","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002FSKILL.md",true,[75,81,87,91,95,99,103,107],{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"_meta.json","REFERENCE","参考文档",313,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002F_meta.json",{"path":82,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"examples\u002Fbalance-and-deposits.js","SCRIPT","脚本",1892,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002Fexamples\u002Fbalance-and-deposits.js",{"path":88,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":89,"sourceHtmlUrl":90},"examples\u002Fpayment-flow.js",2603,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002Fexamples\u002Fpayment-flow.js",{"path":92,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":93,"sourceHtmlUrl":94},"examples\u002Fspark-agent.js",5241,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002Fexamples\u002Fspark-agent.js",{"path":96,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":97,"sourceHtmlUrl":98},"examples\u002Ftoken-operations.js",2509,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002Fexamples\u002Ftoken-operations.js",{"path":100,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":101,"sourceHtmlUrl":102},"examples\u002Fwallet-setup.js",1340,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002Fexamples\u002Fwallet-setup.js",{"path":104,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":105,"sourceHtmlUrl":106},"package-lock.json",61259,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002Fpackage-lock.json",{"path":108,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":109,"sourceHtmlUrl":110},"package.json",576,"https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F人工智能与大型语言模型\u002Fsparkbtcbot\u002Fpackage.json",[112,135,165,176,186,213],{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":47},"01M6Q5R6WZ06RRB9RQTW54B34B","zyfai","Earn yield on any Ethereum wallet on Base, Arbitrum, and Plasma. Use when a user wants passive DeFi yield on their funds. Deploys a non-custodial subaccount (Safe) linked to their EOA, enables automated yield optimization, and lets them deposit\u002Fwithdraw anytime.","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzyfai-sdk\u002FSKILL.md",[],[114,119,120,121,122,123,124,38,125,126,127,128,129,130,131,132,133,134],"safe","ethereum","defi","Optimization","user","use","base","deposit","withdraw","yield","arbitrum","non-custodial","passive","defi yield","earn","yield optimization",{"skillNo":136,"name":137,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":147,"publishedAt":47},"01M6Q5R337B5JSNER4P4YS03TN","zerion-api","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzerion-api\u002FSKILL.md",[140,143,144],{"categoryNo":141,"categoryName":142,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":145,"categoryName":146,"taxonomyType":25,"taxonomyTypeDesc":26},"01JBSEEDCAT000000000000030","开发工程师",[148,149,150,151,152,153,154,121,155,38,156,157,158,159,160,161,162,163,164],"api","zerion api","zerion","MCP","mcp server","server","blockchain","transactions","crypto wallet","crypto","evm","solana","query","across","positions","token","prices",{"skillNo":166,"name":167,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":173,"publishedAt":47},"01M6Q5QZFYTDAZMZ27BN5VZXAR","zerion-api-skill","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzerion-api-skill\u002FSKILL.md",[170,171,172],{"categoryNo":141,"categoryName":142,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":145,"categoryName":146,"taxonomyType":25,"taxonomyTypeDesc":26},[148,174,175,149,150,151,152,153,154,121,155,38,157,158,159,160,161,162,163,164],"api skill","zerion api skill",{"skillNo":177,"name":178,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":179,"categories":180,"keywords":184,"publishedAt":47},"01M6Q5QW17QW98RA3FE45E4RD8","zerion-api-mcp","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fzerion-api-mcp\u002FSKILL.md",[181,182,183],{"categoryNo":141,"categoryName":142,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":145,"categoryName":146,"taxonomyType":25,"taxonomyTypeDesc":26},[151,148,185,149,150,152,153,121,155,38,156,157,158,159,160,161,162,163,164],"zerion api mcp",{"skillNo":187,"name":188,"nameZh":6,"description":189,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":190,"categories":191,"keywords":193,"publishedAt":47},"01M6Q5QQYZB7A501BDEQWKGSJT","yahoo-finance-forex","Fetches real-time FOREX news and market data from Yahoo Finance for major currency pairs (EUR\u002FUSD, GBP\u002FUSD, USD\u002FJPY, etc.). Analyzes sentiment and provides trading context.","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fyahoo-finance-forex\u002FSKILL.md",[192],{"categoryNo":23,"categoryName":24,"taxonomyType":25,"taxonomyTypeDesc":26},[194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,30],"finance","yahoo finance","forex","yahoo","yahoo finance forex","github","https","sentiment","real-time","python3","install","Market","usd","news","time","currency","gbp","pip","market data",{"skillNo":214,"name":215,"nameZh":6,"description":216,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":217,"categories":218,"keywords":220,"publishedAt":47},"01M6Q5QM6VS84WZVM7BKXXPF32","yahoo-finance","This skill should be used when the user asks to \"get stock prices\", \"check stock quotes\", \"look up earnings\", \"get financial data\", \"find trending stocks\", or needs stock market data from Yahoo Finance.","https:\u002F\u002Fgithub.com\u002FKernel8901\u002Fai-agent-skills-classification\u002Fblob\u002Fmain\u002F金融\u002Fyahoo-finance-cli\u002FSKILL.md",[219],{"categoryNo":23,"categoryName":24,"taxonomyType":25,"taxonomyTypeDesc":26},[194,195,197,221,222,223,224,225,39,205,226,227,228,229,230,231,232,233,164,212],"cli","homebrew","find","check","brew","local","get","stock","link","trending","sf","quotes","ln"]