# IBIRAPAY Spark: integration guide Version 2026-11-27 (revision 4: the Enterprise 30 free days, prorated first paid month, priority and active wallet described as the system applies them, and the support channel). For developers who add a self-custodied Spark wallet (a BIP-39 mnemonic that sends and receives Lightning payments) to an app, using the Breez Spark SDK against the **IBIRAPAY Spark network**. ## 1. At a glance | Item | Value | |---|---| | SDK | `ibirapay/spark-sdk`, a fork of `breez/spark-sdk` with the patches our network needs | | Repository | https://github.com/ibirapay/spark-sdk (public) | | Pinned commit (use exactly this) | `d2ca7cfc6a8efbd15328b05c3fb617e0f7e781ef` | | Network | Bitcoin mainnet, IBIRAPAY's own Spark deployment: 3 signing operators (threshold 2 of 3) and one SSP | | Keys | The mnemonic stays on your device or server. IBIRAPAY never sees it | | Minimum payment | **330 sats**, both directions (smaller amounts are refused) | | Breez API key | Not needed. Do not set one | | Access | Wallets inside your users' apps connect directly, with no key. Your server-side (central) wallet uses an API key and secret, a SOCKS5 login that you create yourself at **https://ibirapay.com/spark**; it goes in the SDK's `proxy` setting (section 5.1) | | Plans | **Free**: connect with no account. **Enterprise**: an account at https://ibirapay.com/spark, free for 30 days from activation; your backend registers your wallets (section 5.5) and, until the end of the first paid month, they keep sending Lightning payments when the SSP's Lightning capacity is low (section 9). Section 5.4 compares the two | | Lightning send refused | `LIQUIDITY_RESERVED` in the error of `prepareSendPayment`: a wallet without priority (Free, or Enterprise after the first paid month), while the SSP's Lightning capacity is low (section 9) | | Required setting | `leafOptimizationConfig: autoEnabled: false` (section 5.3). With the default, received funds are locked for a while and the balance reads 0 | | Lightning Address / LNURL receive | Not available on this deployment (`lnurl_domain` is unset) | **Use the pinned commit, not Breez's releases.** The fork contains fixes that the IBIRAPAY operators rely on (a fallback for operators that do not return a leaf field, durable single-use signing nonces, a forced sync that reports failure instead of silently returning stale balances, and a mainnet mode that needs no Breez key). Breez's precompiled binaries do not have them. Build the library from source, as in section 4. **Trust model, in one sentence:** you hold the keys, and IBIRAPAY runs the Spark operators and the SSP. A balance can only be spent with your mnemonic, but payments need our servers to be online. ### What IBIRAPAY has verified | Area | Status | |---|---| | Flutter on Android | Built, and used in IBIRAPAY's own point-of-sale terminals (the Caixa app), where Spark runs with small limits | | Linux x86_64 | Built from this commit in Docker with a pinned toolchain; used in the Caixa desktop app | | Receive Lightning (BOLT11) | Verified on 2026-11-09 with a new wallet through the proxy: 5,000 sats received, balance kept after a restart (with `autoEnabled: false`) | | Send Lightning (BOLT11) to an external invoice | Verified on 2026-11-09: a new wallet paid a 600 sat invoice created on a separate mainnet Lightning node; the node showed it `SETTLED` and the wallet balance went 5,000 to 4,400. Tested with a client built from the pinned commit | | API key and proxy | Verified on 2026-11-09: a valid API key connects and is metered; a wrong secret or an unreachable proxy makes every network call fail (the SDK does not fall back to a direct connection) | | Lightning liquidity reserve | Verified on 2026-11-10 with a client built from the pinned commit: with the SSP's Lightning capacity below the reserve, a wallet that was not on the Enterprise list was refused with `LIQUIDITY_RESERVED`, and a wallet on the list paid a Lightning invoice, which the receiving node showed `SETTLED` | ## 2. Concepts - **Mnemonic**: 12 (or 24) BIP-39 words. They are the wallet. Whoever has them controls the funds. - **Instance**: one connected SDK object. It keeps its state in a **storage directory**. Two instances must never share a directory, and one directory must only ever be used with one mnemonic. - **Operators and SSP**: operators co-sign transfers (FROST, 2 of 3). The SSP is the Lightning gateway: it pays your invoices out to the network and receives Lightning payments on your behalf. Both are configured by one JSON document (section 5). - **Sats**: all amounts are in satoshis (`BigInt` in Dart). ## 3. Choose your path | Your app | Use | Notes | |---|---|---| | Flutter (Android, iOS) | `packages/flutter` of the fork, as a git dependency | Verified on Android | | Flutter desktop on Linux | Same package plus a separately built `.so` | The Flutter plugin does not build the Linux library; section 4.1 | | Native Android / iOS | UniFFI bindings in `crates/breez-sdk/bindings` (`make bindings-kotlin`, `make bindings-swift`) | Same configuration as the Flutter path | | React Native | `packages/react-native` | Same configuration as the Flutter path | | A server (company payout wallet) | The Rust crate, the Python or Kotlin bindings, or Node via `packages/wasm` | Prefer the Rust crate or the bindings you can run and test best | The rest of this guide uses Dart, because it is the reference integration. The other bindings expose the same operations (`connect`, `getInfo`, `receivePayment`, `parse`, `prepareSendPayment`, `sendPayment`, `listPayments`); check the exact names in the generated bindings. Upstream documentation: https://sdk-doc-spark.breez.technology/ (API names match; the network configuration and the pinned commit are specific to IBIRAPAY). ## 4. Get and build the SDK ### 4.1 Linux (x86_64) The plugin does not compile the Linux library, so build it once per SDK commit. ```bash # needs: docker, git, network, about 8 GB RAM, 20+ minutes (release build with LTO) mkdir -p ~/spark-build/out && cd ~/spark-build git init -q spark-sdk && cd spark-sdk git fetch --depth 1 https://github.com/ibirapay/spark-sdk.git d2ca7cfc6a8efbd15328b05c3fb617e0f7e781ef git checkout -q --detach FETCH_HEAD test "$(git rev-parse HEAD)" = d2ca7cfc6a8efbd15328b05c3fb617e0f7e781ef # must print nothing and exit 0 ``` Then compile the Flutter bridge library in Rust 1.95.0 (the version the SDK's `rust-toolchain.toml` demands): ```bash docker run --rm -i -e RUSTUP_TOOLCHAIN=1.95.0 -e HOST_UID="$(id -u)" -e HOST_GID="$(id -g)" -v "$PWD":/src:ro -v "$PWD/../out":/out rust:1.95.0-bookworm bash -s <<'EOF' set -euo pipefail apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends protobuf-compiler libprotobuf-dev cd /src/packages/flutter/rust cargo build --locked --features secp-lowmemory,release-max-level-debug \ -p breez_sdk_spark_flutter --release --target x86_64-unknown-linux-gnu --target-dir /tmp/target cp /tmp/target/x86_64-unknown-linux-gnu/release/libbreez_sdk_spark_flutter.so /out/ chown "$HOST_UID:$HOST_GID" /out/libbreez_sdk_spark_flutter.so EOF sha256sum ../out/libbreez_sdk_spark_flutter.so ``` Notes: the bookworm image gives a library that asks for glibc 2.34 or older symbols, so it runs on current Debian and Ubuntu. IBIRAPAY's own build script (`tool/build-spark-linux.sh` in the Caixa repository) additionally pins the Docker image by digest and sets reproducibility flags; record the SHA-256 of what you ship. Put the `.so` next to your Linux app's binaries (in the `lib/` folder of the Flutter bundle). ### 4.2 Android (Flutter) Requirements: Flutter 3.35.3 or newer (Dart 3.9.2 or newer; IBIRAPAY's app builds with Dart 3.13), Android SDK and NDK (Flutter's default NDK is used), Rust installed through `rustup` (cargokit adds the Android targets itself); if the build complains about `protoc`, install `protobuf-compiler`. In `pubspec.yaml`: ```yaml dependencies: breez_sdk_spark_flutter: git: url: https://github.com/ibirapay/spark-sdk.git ref: d2ca7cfc6a8efbd15328b05c3fb617e0f7e781ef # the exact commit, never a branch path: packages/flutter ``` Create `cargokit_options.yaml` **in your app's root** with: ```yaml use_precompiled_binaries: false # build from the pinned source; never download Breez's binary ``` Then `flutter pub get && flutter build apk --release` (or `appbundle`). The first build compiles Rust for each Android ABI and takes a long time. The package supports Android Gradle Plugin 8.x and 9 (the fork contains the fix for Gradle 9). ### 4.3 iOS (Flutter) Requirements: a Mac with Xcode, CocoaPods, Rust installed through `rustup`. The pod targets iOS 13 or newer and builds the Rust library in a script phase (`cargokit/build_pod.sh`). Use the same `pubspec.yaml` dependency and the same `cargokit_options.yaml` as on Android, then: ```bash flutter pub get cd ios && pod install && cd .. flutter build ios --release # or build from Xcode ``` If the build asks for a Rust target, add it with `rustup target add aarch64-apple-ios` (and `aarch64-apple-ios-sim`, `x86_64-apple-ios` for the simulator). Test a real receive and a real send on a device before you ship. If this path fails, tell IBIRAPAY with the full error. ### 4.4 Native Swift or Kotlin (without Flutter) The fork has UniFFI bindings (`crates/breez-sdk/bindings`). Its Makefile has `bindings-swift`, `package-xcframework` (iOS and macOS), `bindings-kotlin` and `build-android` (needs the Android NDK). Build from the same pinned commit and use the same configuration JSON (section 5). ## 5. Create an instance ### 5.1 Connecting: users' wallets and your central wallet There are two kinds of wallet, and they connect differently: - **A wallet inside your users' app** (one wallet per user, the mnemonic on the user's device): connect **directly**. Do not set `proxy` and do not ship any key in the app. The public endpoints in the configuration (section 5.2) are open. - **Your central wallet** (on your server, holding the balance you pay from): connect through the IBIRAPAY front door with an API key and secret. This lets IBIRAPAY measure your use and revoke access. The rest of this section is for the central wallet. 1. Open **https://ibirapay.com/spark**, fill in the company, your name and e-mail, and accept the terms. 2. Confirm the e-mail (the link is valid for 24 hours). The page then shows your first key **once**: proxy host and port, API key (`ik_...`, goes in `username`) and secret (`sk_...`, goes in `password`). Copy it into your secret store. IBIRAPAY keeps only a hash. 3. The e-mail you receive afterwards has a link to your account page, where you create up to 5 active keys (for example one per app or environment) and revoke them. Treat that link like a password. The page also shows your **account ID**, which goes in the text a wallet signs when you register it (section 5.5). A key has a type, chosen when you create it: a **proxy key** (the SOCKS5 login for the central wallet, described here) or a **registration key** (for the registration API of section 5.5; it does not open the proxy, and a proxy key does not open the registration API). The API key and secret are a **SOCKS5 login** (API key = `username`, secret = `password`) for the IBIRAPAY front door (`proxy.ibirapay.com`, port 1080). It identifies your company, lets IBIRAPAY measure your use, and can be revoked at once (open connections are cut within about 15 seconds). It is **not** what protects your users' money: that is the mnemonic. SOCKS5 sends the secret without encryption of its own, so rotate a key that may have leaked. Use one key per server and per environment, and never put it in an app that runs on your users' devices (see section 10). ### 5.2 The deployment configuration The deployment configuration is public data (identity keys are public keys). Treat the addresses as final. ```dart const ibirapaySparkJson = ''' { "coordinator_identifier": "0000000000000000000000000000000000000000000000000000000000000001", "threshold": 2, "signing_operators": [ { "id": 0, "identifier": "0000000000000000000000000000000000000000000000000000000000000001", "address": "https://so0.ibirapay.com:8535", "identity_public_key": "0398d822e97c0c28837fc8994aad582aa7cc5c3a9ceb2951577d84345e9ff8dab2" }, { "id": 1, "identifier": "0000000000000000000000000000000000000000000000000000000000000002", "address": "https://so1.ibirapay.com:8536", "identity_public_key": "022239a448bee910538fcda9d4717abe6ad8b3c04db25121981e4dd8db03dcc686" }, { "id": 2, "identifier": "0000000000000000000000000000000000000000000000000000000000000003", "address": "https://so2.ibirapay.com:8537", "identity_public_key": "03b76b179afad94ccda293a5172ad07e9f14db6443a902cfe16d446c00db7d94d1" } ], "ssp_config": { "base_url": "https://api.ibirapay.com:9443", "identity_public_key": "02693f14e2151204af19ccffa8a9050029bd69fba865e5895433172cd93f752292" }, "expected_withdraw_bond_sats": 10000, "expected_withdraw_relative_block_locktime": 1000 } '''; ``` ```dart import 'package:breez_sdk_spark_flutter/breez_sdk_spark.dart' as breez; import 'package:path_provider/path_provider.dart'; bool _libReady = false; Future connectWallet(String mnemonic) async { if (!_libReady) { await breez.BreezSdkSparkLib.init(); // once per process, before anything else _libReady = true; } final config = breez .defaultConfig(network: breez.Network.mainnet) .copyWith( sparkConfig: breez.parseSparkConfig(json: ibirapaySparkJson), preferSparkOverLightning: false, // section 7 proxy: breez.ProxyConfig( // CENTRAL (server) wallet only, section 5.1; omit in users' apps host: 'proxy.ibirapay.com', port: 1080, username: sparkApiKey, password: sparkSecret, ), // section 5.3: REQUIRED on this network leafOptimizationConfig: const breez.LeafOptimizationConfig( autoEnabled: false, multiplicity: 0, ), ); // one directory per mnemonic final dir = '${(await getApplicationSupportDirectory()).path}/spark'; return breez.connect( request: breez.ConnectRequest( config: config, seed: breez.Seed.mnemonic(mnemonic: mnemonic), // 12 or 24 BIP-39 words storageDir: dir, ), ); } ``` ### 5.3 Why `autoEnabled: false` is required By default the SDK re-splits every received amount into small power-of-two pieces (1, 2, 4, 8, ... sats). The IBIRAPAY SSP refuses to create pieces under 330 sats, so that swap fails and the received funds stay locked for a while: `getInfo` shows a balance of 0 and a send fails with "insufficient funds". In our tests the funds came back by themselves after some minutes, but a user would see an empty wallet. With `autoEnabled: false` there is no swap after a receive, and the balance is kept across restarts (verified on 2026-11-09). Payments still swap when they need change; keep amounts and the remaining change at 330 sats or more. - **Do not set the `apiKey` field of `Config`.** That field is a Breez key, not the IBIRAPAY API key. Your IBIRAPAY API key and secret go in `proxy` (`username` and `password`, section 5.1). A mainnet configuration without the Breez `apiKey` runs against the configured operators and SSP only. - **One live instance per process.** Reuse it. To switch mnemonic, `await sdk.disconnect()` first, then connect again with a different directory. Opening the same directory twice is an error. - **The first connect syncs with the operators and can take a while.** Show progress; do not time it out at a few seconds. - Call `await sdk.disconnect()` when the app shuts down cleanly. ### 5.4 Plans: Free and Enterprise | | Free | Enterprise | |---|---|---| | Access | Direct to the public endpoints (section 5.2), no account, no key | An account at https://ibirapay.com/spark, with keys (section 5.1) | | Wallets | Not registered | Your users' wallets, and your central wallet, registered by your backend (section 5.5) | | Lightning sends when the SSP's Lightning capacity is low | Refused with `LIQUIDITY_RESERVED` (section 9) | Registered wallets keep sending until the end (UTC) of the account's first paid month; after that, they are refused like Free ones | | Receiving, Spark-to-Spark transfers | Not affected | Not affected | | Price | Free | Free for 30 days from the account's activation. The month in which the 30 days end is charged pro rata; later months, from R$ 1.00 per active wallet per month, minimum R$ 99 per month (see Enterprise price below) | Free access is shared by everyone who connects without an account, and IBIRAPAY may limit the number of connections per address. Enterprise priority applies to a wallet registered (and not removed) to an active account, until the end of the account's first paid month: the calendar month (UTC) in which the 30 free days end (see the example below). After that month, the account's wallets lose the priority: when the SSP's Lightning capacity is low, their Lightning sends are refused with `LIQUIDITY_RESERVED`, like those of a Free wallet. The account, the keys and the registrations stay valid. Nothing else about how you build the wallet changes between the two plans: same configuration, same SDK, same commit. #### Enterprise price The account is activated when you confirm the e-mail (section 5.1). The 30 days from the activation are free: wallets are counted and nothing is charged. The calendar month (UTC) in which the 30 days end is the first paid month and is charged pro rata: the whole month's price (with the wallets active in the whole month) times the share of the month after the end of the 30 days, rounded down to the centavo. Later months pay the full price. The monthly price is per active wallet, in tiers; each tier applies to the wallets inside it: | Active wallets in the month | Price per wallet per month | |---|---| | 1 to 200 | R$ 1.00 | | 201 to 2,000 | R$ 0.50 | | above 2,000 | R$ 0.25 | The minimum is R$ 99 per month and always applies, also with zero active wallets; in the prorated month it is prorated like the rest of the price. Examples of a full month: 50 wallets pay R$ 99 (the minimum), 100 wallets pay R$ 100, 500 pay R$ 350, 1,000 pay R$ 600 and 5,000 pay R$ 1,850. Example: an account activated on 20 November 2026 at 10:00 UTC is free until 20 December 2026 at 10:00 UTC. November is not charged. December is the first paid month: its part after the end of the 30 days is 11 days and 14 hours, 1,000,800 of the month's 2,678,400 seconds. With zero active wallets, December costs R$ 36.99 (R$ 99 × 1,000,800 / 2,678,400 = R$ 36.9919..., rounded down); with 500 active wallets, R$ 130.77 (R$ 350 × 1,000,800 / 2,678,400 = R$ 130.7795..., rounded down). From January 2027 on, each month is charged in full (R$ 99 and R$ 350, with the same active wallets). The registered wallets have priority until 1 January 2027 at 00:00 UTC, the end of December. An **active wallet** in a month is a wallet registered to your account (section 5.5) at some point in that calendar month (UTC) and seen in that same month by the SSP (a session or a request) or by the operators (a completed transfer, as sender or receiver). A wallet counts once. IBIRAPAY confirms the price to you in writing before the first charge. ### 5.5 Registering your wallets (Enterprise) The operators and the SSP see a wallet's identity public key but do not know whose wallet it is. Your **backend** tells IBIRAPAY which identity keys belong to your account, with a **registration key** (section 5.1) that never leaves your server. To stop anyone from claiming a wallet they do not control, the **wallet signs its own registration**: the app signs a short text with the wallet's identity key and your backend forwards the signature. **1. In the app (or in your backend, for the central wallet), after connecting:** get the identity public key, build the exact text below, and sign it with the SDK. The SDK hashes the text with SHA-256 and signs it with the wallet's identity key. ``` ibirapay-spark-registro:v1::: ``` `` is shown on your account page; `` is the 66-character hex key in **lowercase**; `` is the current UTC time. No spaces, no line break at the end. ```dart Future<({String identity, String signature, int timestamp})> signRegistration(breez.BreezSdk sdk, String accountId) async { final info = await sdk.getInfo(request: breez.GetInfoRequest(ensureSynced: false)); final identity = info.identityPubkey.toLowerCase(); // 66 hex characters final ts = DateTime.now().toUtc().millisecondsSinceEpoch ~/ 1000; // unix seconds final signed = await sdk.signMessage( request: breez.SignMessageRequest( message: 'ibirapay-spark-registro:v1:$accountId:$identity:$ts', compact: true, // 64-byte hex; DER is accepted too ), ); return (identity: identity, signature: signed.signature, timestamp: ts); } ``` **2. The app sends `identity`, `signature` and `timestamp` to your backend**, which authenticates the user in its own way. The account ID is not a secret and may be in the app; the registration key and secret must not be. **3. Your backend calls the registration API** with HTTP Basic (registration key as the user name, its secret as the password): ```bash # a quick test from a trusted shell; production code uses its HTTP client's Basic auth setting curl -sS -u "$REGISTRO_KEY:$REGISTRO_SECRET" -H 'Content-Type: application/json' \ -d '{"identity_pubkey":"<66 hex>","signature":"","timestamp":1790000000}' \ https://ibirapay.com/spark/api/carteiras ``` | Answer | Meaning | |---|---| | `201` `{"ok":true,"estado":"criada"}` or `"reativada"` | Registered (or registered again after a removal) | | `200` `{"ok":true,"estado":"existente"}` | Already registered to your account; nothing changed | | `400` `{"erro":"..."}` | Not a valid identity key, a signature that is missing, wrong or older or newer than 10 minutes, or the limit of 100,000 registered wallets; the text says which (in Portuguese) | | `401` | Wrong key or secret, a revoked key, a suspended account, or a proxy key used here | | `409` | The wallet is registered to another account. The first account to register an identity keeps it for good | | `429` | Too many calls; wait and try again | To take a wallet off your account: `DELETE https://ibirapay.com/spark/api/carteiras/` with the same Basic authentication. `204` means removed (repeating it is fine), `404` means it is not on your account. A removed wallet registers again with a new signature. Rules: - The timestamp must be within 10 minutes of the server's clock, so sign when you register, not earlier, and keep your servers' clocks on NTP. A retry after the 10 minutes needs a new signature (a wallet already registered answers `200` without one). - The signed text is checked as written above: lowercase identity key, your account ID, no extra characters. - Register a wallet once, right after it is created or restored. A new registration reaches the SSP in about 30 seconds. - Register your **central wallet** the same way (your backend signs with its own SDK instance): it pays your users' invoices, so it needs the priority too. - Limits: 300 calls per minute per IP address, 120 per minute per key, 600 per minute for the whole service, 100,000 registered (not removed) wallets and 5 active keys per account. The proxy accepts up to 128 simultaneous connections per proxy key. ## 6. The mnemonic 1. Generate it once with a vetted BIP-39 library and a cryptographically secure random source (128 bits of entropy gives 12 words). Do not invent your own word list or generator. 2. Store it in the platform secret store (Android Keystore through `flutter_secure_storage`, iOS Keychain, or on a server a secrets manager). Never in a database, preferences, logs, analytics or crash reports. 3. Make the user write the words down (or, for a company wallet, put them in your secret backup procedure) before the wallet receives funds. **Losing the mnemonic means losing the funds; IBIRAPAY cannot recover it.** 4. To restore, connect with the same mnemonic and a **fresh** storage directory. The SDK rebuilds the state from the operators. 5. A mnemonic is a different wallet on a different Spark deployment. Words used here are not the same wallet on Lightspark's network. ## 7. Receive a payment ```dart Future<({String invoice, String hash})> createInvoice(breez.BreezSdk sdk, int sats, String memo) async { if (sats < 330) throw ArgumentError('minimum is 330 sats'); final r = await sdk.receivePayment( request: breez.ReceivePaymentRequest( paymentMethod: breez.ReceivePaymentMethod.bolt11Invoice( description: memo, amountSats: BigInt.from(sats), expirySecs: 600, ), ), ); final parsed = await sdk.parse(input: r.paymentRequest); if (parsed is! breez.InputType_Bolt11Invoice) throw StateError('not a BOLT11 invoice'); return (invoice: r.paymentRequest, hash: parsed.field0.paymentHash); // show `invoice` as text and QR } ``` Detect the payment in one of two ways: - **Events**: `sdk.addEventListener()` returns a `Stream`; use it to refresh the balance and the list when something settles. Do not make a ledger entry from an event alone. - **List**: the authoritative check. The SDK lists a receive **only once it is paid**; an unpaid invoice is simply absent. ```dart Future findPaid(breez.BreezSdk sdk, String hashHex) async { for (var offset = 0;; offset += 100) { final page = (await sdk.listPayments( request: breez.ListPaymentsRequest( typeFilter: const [breez.PaymentType.receive], sortAscending: false, offset: offset, limit: 100), )).payments; for (final p in page) { final d = p.details; if (d is breez.PaymentDetails_Lightning && d.htlcDetails.paymentHash == hashHex) return p; } if (page.length < 100) return null; } } // p.status: completed = credited | pending = in flight | failed = will not complete ``` Rules that matter for money: - Match on the **payment hash**, not on the amount or the time. - Keep checking an expired invoice for 24 hours before you give up: a late payment can still arrive. Credit it once. - Keep `preferSparkOverLightning: false`. With it on, a payer on the same Spark network may pay by a Spark transfer, which is listed **without** the invoice's hash, so your code would not match it. - Credit the user only when `status == completed`. ## 8. Send a payment Sending is two steps: prepare (shows the fee and validates), then send. ```dart Future payInvoice(breez.BreezSdk sdk, String bolt11, {BigInt? amountSats, required String idempotencyKey}) async { final parsed = await sdk.parse(input: bolt11); if (parsed is! breez.InputType_Bolt11Invoice) throw StateError('not a BOLT11 invoice'); if (parsed.field0.amountMsat == null && amountSats == null) throw StateError('invoice has no amount'); final prep = await sdk.prepareSendPayment( request: breez.PrepareSendPaymentRequest( paymentRequest: breez.PaymentRequest.input(input: bolt11), amount: amountSats, // only for amount-less invoices ), ); if (prep.amount < BigInt.from(330)) throw StateError('minimum is 330 sats'); final m = prep.paymentMethod; final fee = m is breez.SendPaymentMethod_Bolt11Invoice ? m.lightningFeeSats : BigInt.zero; // show or log: prep.amount + fee; check the balance covers both before sending final res = await sdk.sendPayment( request: breez.SendPaymentRequest( prepareResponse: prep, options: const breez.SendPaymentOptions.bolt11Invoice(preferSpark: false, completionTimeoutSecs: 30), idempotencyKey: idempotencyKey, // a UUID you store BEFORE the call: a retry must reuse it ), ); return res.payment; // status completed | pending | failed } ``` Rules that matter for money: - **Idempotency.** Create the key, save it with the payout in your database, then call. After a crash or a timeout, retry with the **same** key. Never create a new key for the same payout. - **`pending` is not `failed`.** After the 30 second wait the payment may still complete. Poll `listPayments` or `getPayment` for the final status before you refund or retry. Only `failed` means the funds did not leave. - Check the balance first: `getInfo(request: GetInfoRequest(ensureSynced: false))` returns `balanceSats`. For a fresh figure call `syncWallet` first. If the sync cannot reach the operators it throws; treat that as "unknown", not as zero. - Lightning routing can fail (no route, recipient offline). Show the user the real error and let them retry later. - `prepareSendPayment` can fail with `LIQUIDITY_RESERVED` when the SSP's Lightning capacity is low and the wallet has no priority (section 5.4). No funds have moved. Handle it as described in section 9. ## 9. Fund the wallet The simplest way to get a first balance is the receive flow in section 7: pay a BOLT11 invoice of your own wallet from any Lightning wallet. The SDK also exposes a Bitcoin deposit address (`ReceivePaymentMethod.bitcoinAddress`); if you use it, try a small amount first. ### One wallet per user, paid from a central wallet Each user's app embeds the SDK with its own mnemonic on the device. Your server runs one central wallet that holds the balance you pay from. 1. The user's app shows its Spark address (`ReceivePaymentMethod.sparkAddress`). 2. Your server pays that address from the central wallet with the same parse, prepare and send calls used for invoices. Paying a Spark address is a direct Spark transfer: no Lightning and no routing fee (verified on 2026-11-09 between two wallets: 1,000 sats, status `completed`, fee 0). 3. To withdraw, the user pays any Lightning invoice from their own wallet. Keep the amount, and the change left in the sending wallet, at 330 sats or more. A smaller piece makes the wallet's funds lock for a while (a 100 sat transfer failed this way in our test). Keep `preferSparkOverLightning: false` and pay the Spark address explicitly. Fund the central wallet by Lightning (see Lightning liquidity). ### Lightning liquidity Lightning payments in and out go through IBIRAPAY's SSP and its Lightning channels. The SSP can pay out only what its channels hold on its side, and that grows when wallets receive Lightning payments. IBIRAPAY watches this balance and reinforces it, with no amount guaranteed. **Fund your wallet first, then pay out, and tell IBIRAPAY your largest expected single payment and your monthly volume** so the channels can be sized before you launch. A payment larger than the available channel balance fails with a routing error and loses nothing. **The reserve for Enterprise wallets.** When the SSP's Lightning capacity falls low, the SSP keeps what is left for the wallets with priority: those registered to an Enterprise account (section 5.5), until the end of the account's first paid month (section 5.4). A Lightning send from any other wallet is refused **before any funds move**, while receiving and Spark-to-Spark transfers keep working. The refusal is an error from `prepareSendPayment` whose text contains `LIQUIDITY_RESERVED` (the full text today is `LIQUIDITY_RESERVED: liquidez reservada, tente mais tarde`). In your app: ```dart try { prep = await sdk.prepareSendPayment(request: request); } catch (e) { if (e.toString().contains('LIQUIDITY_RESERVED')) { // Lightning payouts are paused for this wallet for now. Nothing left the wallet. // Keep the payout queued, tell the user to try again later, retry after a few minutes. return; } rethrow; } ``` Match on `LIQUIDITY_RESERVED`, not on the sentence after it. Do not retry in a tight loop. A wallet with priority is not refused. If your registered wallet gets this error before the end of the account's first paid month, check that it is registered (a new registration reaches the SSP in about 30 seconds) and tell IBIRAPAY; after that month, the refusal is the expected behaviour (section 5.4). **Fund your wallet by Lightning, not by an on-chain deposit.** A Lightning deposit adds to the SSP's side of the channel, which is what pays your later payouts, so deposits and payouts keep the channel balanced. An on-chain deposit raises your Spark balance without adding to the channel, and every payout then draws the channel down with nothing to replace it. If you must deposit on-chain, tell IBIRAPAY first so the channel can be refilled. ## 10. Production checklist 1. SDK built from the pinned commit; the SHA-256 of the native library is recorded. 2. Mnemonic generated with a secure source, stored in the secret store, backed up before first funding. 3. One instance per process, one storage directory per mnemonic, `disconnect()` on shutdown. 4. No Breez API key; `preferSparkOverLightning: false`; `leafOptimizationConfig` with `autoEnabled: false`. Central wallet: `proxy` set with your IBIRAPAY API key and secret (section 5.1), kept in your server's secret store. Users' wallets: no `proxy` and no key in the app. 5. 330 sat minimum enforced before calling the SDK. 6. Receives credited on `completed` only, matched by payment hash, with a 24 h late-payment window. 7. Sends use an idempotency key that is stored before the call; `pending` is polled, never refunded early. 8. Mnemonic, seed and storage directory contents never appear in logs, analytics or crash reports. 9. A test with a real small receive and a real small send on a real device or server, per platform you ship. 10. Pin upgrades: change the commit only after IBIRAPAY says the new one works with the network. 11. Enterprise: your backend registers every user wallet and the central wallet, each with the wallet's own signature (section 5.5); the registration key stays on your server; `LIQUIDITY_RESERVED` is handled in every wallet, registered or not, because the priority ends at the end of the account's first paid month (sections 5.4 and 9). ## 11. Support Report problems to IBIRAPAY with: the platform and OS version, the SDK commit, the SHA-256 of the native library, what you called, the error text, and the time (UTC). Never send the mnemonic or the storage directory. Talk to IBIRAPAY on WhatsApp: .