@arkade-os/swap 0.1.0-rc.9 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +261 -252
  2. package/dist/advanced.cjs +6613 -3224
  3. package/dist/advanced.d.cts +328 -283
  4. package/dist/advanced.d.ts +328 -283
  5. package/dist/advanced.js +347 -34
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-FMRAV77W.js +3065 -0
  8. package/dist/chunk-T4FHBWZI.js +3459 -0
  9. package/dist/{chunk-NS3K6BZG.js → chunk-YHESEL4I.js} +1792 -636
  10. package/dist/index.cjs +6901 -3901
  11. package/dist/index.d.cts +71 -243
  12. package/dist/index.d.ts +71 -243
  13. package/dist/index.js +131 -167
  14. package/dist/lockupContract-CIXkJPxV.d.ts +148 -0
  15. package/dist/lockupContract-CkhWMKCo.d.cts +148 -0
  16. package/dist/node/index.cjs +61 -10
  17. package/dist/node/index.d.cts +307 -635
  18. package/dist/node/index.d.ts +307 -635
  19. package/dist/node/index.js +65 -10
  20. package/dist/nostr.cjs +427 -49
  21. package/dist/nostr.d.cts +59 -70
  22. package/dist/nostr.d.ts +59 -70
  23. package/dist/nostr.js +268 -36
  24. package/dist/offer-BPD2ortO.d.ts +269 -0
  25. package/dist/offer-Diff5Flc.d.cts +269 -0
  26. package/dist/offerFillPlan-B-5ae_gQ.d.cts +1671 -0
  27. package/dist/offerFillPlan-CJzneX6F.d.ts +1671 -0
  28. package/dist/protocol.cjs +5717 -4275
  29. package/dist/protocol.d.cts +258 -328
  30. package/dist/protocol.d.ts +258 -328
  31. package/dist/protocol.js +200 -224
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BBVRh9ez.d.ts +2357 -0
  41. package/dist/repository-C4pvymhs.d.cts +2357 -0
  42. package/dist/{rfq-BO6o7NwS.d.ts → rfq-C0tHOvn6.d.cts} +323 -444
  43. package/dist/{rfq-BO6o7NwS.d.cts → rfq-C0tHOvn6.d.ts} +323 -444
  44. package/dist/watch-7BiRa4oB.d.ts +74 -0
  45. package/dist/watch-Bxq-lx_6.d.cts +74 -0
  46. package/package.json +10 -10
  47. package/dist/chunk-JFKGMPMH.js +0 -3456
  48. package/dist/chunk-LLG7RD2T.js +0 -1499
  49. package/dist/chunk-U7VWWTL6.js +0 -66
  50. package/dist/errors-CNISbN0M.d.ts +0 -2218
  51. package/dist/errors-DwNhIP0N.d.cts +0 -2218
  52. package/dist/lockupContract-C8-Mcg69.d.ts +0 -664
  53. package/dist/lockupContract-mIt4syse.d.cts +0 -664
  54. package/dist/repository-CGPLbjBe.d.ts +0 -3489
  55. package/dist/repository-DSGGq0ct.d.cts +0 -3489
  56. package/dist/watch-DWyVqyEN.d.cts +0 -96
  57. package/dist/watch-DmvHNX6T.d.ts +0 -96
package/README.md CHANGED
@@ -1,252 +1,261 @@
1
- # @arkade-os/swap
2
-
3
- The swap client for [Arkade Intents](https://arkade.money). You state a route — what to give,
4
- what to take, and where the value ends up — and the client resolves the market, picks the
5
- contract, decodes the destination, seals the secret, funds with the right packet, persists before
6
- it watches, claims, and refunds. Framework-free TypeScript over `@arkade-os/sdk`: no DOM and no
7
- Node-specific APIs in the core, so it runs in Node, the browser and React Native alike.
8
-
9
- ```ts
10
- import { createSwapClient, IndexedDbAssetSwapRepository } from "@arkade-os/swap";
11
-
12
- const client = createSwapClient({ wallet, repository: new IndexedDbAssetSwapRepository() });
13
- ```
14
-
15
- Construction is synchronous and inert: no network, no wallet read, no repository open. The first
16
- call that needs one does it.
17
-
18
- Market discovery needs no configuration either: the client defaults to the reference solver
19
- registry's index for the wallet's network (`REGISTRY_URL[network]`, exported). Follow your own
20
- registry instead with `discovery: { registryUrl }`, or opt out of registries entirely with
21
- `discovery: { registryUrl: null }` — `discovery: { snapshot }` resolves against a fixed market
22
- list without touching the network.
23
-
24
- ## The four routes
25
-
26
- Each is one `quote` → `accept` chain. `quote` returns binding, verified terms and touches nothing
27
- durable; `accept` writes the record, then funds.
28
-
29
- ```ts
30
- const BTC = btcOn("arkade", "bitcoin"); // arkade:bitcoin/slip44:0
31
- const USDT = "arkade:bitcoin/asset:…";
32
-
33
- // arkade -> lightning: pay an invoice. The amount is the invoice's.
34
- await client.accept(await client.quote({ give: BTC, to: bolt11 }));
35
-
36
- // arkade -> arkade: swap one asset for another.
37
- await client.accept(
38
- await client.quote({ give: BTC, take: USDT, amount: 1_000_000n, amountOn: "give" }),
39
- );
40
-
41
- // arkade -> onchain: withdraw to a bitcoin address.
42
- await client.accept(
43
- await client.quote({ give: BTC, to: "bc1p…", amount: 100_000n, amountOn: "take" }),
44
- );
45
-
46
- // lightning -> arkade: receive. The artifact is the invoice the solver minted.
47
- const r = await client.receive({ via: "lightning", amount: 50_000n });
48
- showToPayer(r.artifact.bolt11);
49
- ```
50
-
51
- The receive is the one route that is not a two-step, and the asymmetry is deliberate. Its
52
- artifact is an invoice whose claim secret has to be durable before a payer can act on it, so
53
- `receive` returns only after `accept` has persisted. Reaching for `quote` and reading the invoice
54
- off it would show a payer an invoice this client could not yet claim; the verb removes the
55
- ordering from the caller.
56
-
57
- `onchain -> arkade` is not in the union. It resolves and quotes to `UnsupportedRoute` until the
58
- client owns the trader's L1 refund path end to end.
59
-
60
- An `arkade -> onchain` withdrawal claims the solver's L1 HTLC itself, and that claim's miner fee
61
- comes out of the HTLC output — so the client grosses the take leg up by the claim's cost and the
62
- recipient nets exactly the `amount` written, with the estimate folded into the reported `fee`. The
63
- claim is built and broadcast by the client itself once the fill is claimable, signed by the
64
- wallet's payout key and priced off a per-network fee-rate floor
65
- (`discovery`/corridor overrides aside, that floor is the only environment-specific input). A
66
- routing UI should raise it in congestion — the claim has a consensus deadline — via
67
- `corridors: { onchain: { claimFeeRateSatVb } }`; set it to `null` to take the claim over manually
68
- (the drive then reports the L1 half as your job rather than blocking it). Wire your own builder
69
- with `corridors: { onchain: { claim } }` and it wins over the default.
70
-
71
- ### One call instead of two
72
-
73
- `pay`, `receive` and `exchange` are `quote` → fee ceiling → `accept`, and add no capability the
74
- client did not already have. What they add is the ceiling; what they subtract is vocabulary — a
75
- product integrating payments never types the words route, corridor, market or quote.
76
-
77
- ```ts
78
- await client.pay(destination, { amount: 50_000n, maxFee: { amount: 500n, asset: BTC } });
79
- await client.receive({ via: "lightning", amount: 50_000n });
80
- await client.exchange({ give: BTC, take: USDT, amount: 1_000_000n, amountOn: "give" });
81
- ```
82
-
83
- `pay` takes any of the four destination forms — a bolt11 invoice, a bitcoin address, an Arkade
84
- address, or a BIP21 URI carrying one of them — and exactly one corridor claims each. A plain
85
- Arkade address is not a swap and does not become one: same asset, same rail, rate 1. It returns a
86
- txid and no swap id, which is why `PayResult` has two arms.
87
-
88
- Omit `amount` exactly when the destination pins it. An amount-bearing invoice does; passing one
89
- beside it is `AmountMismatch` rather than a silent preference.
90
-
91
- ## Asset ids and amounts
92
-
93
- Asset ids are CAIP-19 with the rail as the CAIP-2 namespace, `<rail>:<network>/<namespace>:<ref>`.
94
- `arkade`, `bolt11` and `bitcoin` are the implemented rails, and BTC has one id per rail. Use
95
- `btcOn(rail, network)` and `arkadeAsset(network, id)` rather than writing the strings, and
96
- `canonicalAssetId` when the input is human:
97
-
98
- ```ts
99
- const asset = canonicalAssetId("BTC", {
100
- network: "regtest",
101
- assets: [{ ticker: "BTC", id: "arkade:regtest/slip44:0" }],
102
- });
103
- ```
104
-
105
- Ticker matching is case-insensitive, scoped to the wallet's network, and refuses a collision
106
- instead of guessing.
107
-
108
- Amounts are `bigint` atomic units everywhere inside the client. Decimal strings exist at two
109
- boundaries and mean different things at each: display decimals (`"0.001"`) belong to the UI, atomic
110
- decimals (`"100000"`) belong to records and RFQ payloads. `Amount.parse` and `Amount.format` cross
111
- the first; the client crosses the second itself.
112
-
113
- ## Watching, history and cancelling
114
-
115
- There is no required `start()`. The client reads its repository once — `await client.ready` is
116
- that read — and arms the drive when it finds live work, or on the first `accept` when it does
117
- not. `start()` and `stop()` exist for manual control; `stop()` is a pause, not a cancellation, and
118
- disposal is terminal cleanup that leaves every durable record and wallet registration recoverable.
119
-
120
- ```ts
121
- const off = client.onUpdate(({ swap, outcome, detail }) => render(swap.id, outcome, detail));
122
-
123
- const live = await client.swaps({ outcome: "funded" });
124
- const { outcome } = await client.cancel(swapId);
125
- const result = await client.recover(swapId);
126
- ```
127
-
128
- `onUpdate` replays the current outcome of every swap it knows, then streams transitions, keyed on
129
- the derived outcome so a legal backslide is delivered once. `Outcome` is one trader-centric
130
- vocabulary across both families: `refunded` always means the value came back and a receive-leg
131
- solver reclaim is `lapsed`, never the same word. The protocol's own state string is on `detail`
132
- for logs.
133
-
134
- `cancel` is typed to asset swaps, because that is where a cancel right exists. Corridor swaps
135
- decompose into quote expiry, a timelocked refund and a lapse instead. A cancel that loses the race
136
- to a fill reports the fill rather than throwing.
137
-
138
- ## Errors
139
-
140
- Sixteen classes, each a condition noun, all reachable from the root; `SWAP_ERROR_NAMES` is the
141
- complete list. `SwapRefusal` is the solver declining — a decision, not a fault — and it is the one
142
- member the protocol layer owns. Everything else names what the client refused and why:
143
- `UnsupportedRoute`, `AmbiguousDestination`, `AmountMismatch`, `QuoteExpired`, `MaxFeeExceeded`,
144
- `InsufficientFunds`, `QuoteVerificationFailed`, `NotCancellable`, `ClientDisposed`,
145
- `MissingCorridorDep` and the rest.
146
-
147
- ## Storage backends
148
-
149
- | Backend | Import from | For |
150
- | ------------------------------ | ------------------------------------- | ----------------------------------------------- |
151
- | `InMemoryAssetSwapRepository` | `@arkade-os/swap` | tests, one-shot scripts — nothing survives exit |
152
- | `IndexedDbAssetSwapRepository` | `@arkade-os/swap` | the browser (or a polyfilled IndexedDB) |
153
- | `SQLiteAssetSwapRepository` | `@arkade-os/swap/repositories/sqlite` | React Native, over your SQLite driver |
154
- | `RealmAssetSwapRepository` | `@arkade-os/swap/repositories/realm` | React Native, over your Realm instance |
155
- | `nodeSwapRepository()` | `@arkade-os/swap/node` | Node — file-backed SQLite, opened for you |
156
-
157
- There is no implicit default and never an in-memory fallback: accepting a swap with nowhere to
158
- write it is the silent loss the rule exists to forbid, so `accept` refuses with
159
- `MissingCorridorDep("arkade", "repository")` instead. In-memory is available, explicitly, which is
160
- the only way ephemeral storage is on the table.
161
-
162
- Neither React Native subpath adds a dependency — they take the SDK's structural `SQLExecutor` and
163
- `RealmLike` handles, so you pass the database you already opened. `@arkade-os/swap/node` is the
164
- exception and the only entry point that imports `node:` builtins, which is why it is a subpath
165
- rather than something the main entry falls back to. It opens the database under the platform
166
- config directory at `arkade/swaps/swaps-<network>.sqlite`, and it is the one backend whose
167
- disposal closes a connection, because it is the one that opened it:
168
-
169
- ```ts
170
- import { nodeSwapRepository } from "@arkade-os/swap/node";
171
-
172
- await using swaps = nodeSwapRepository({ network: "mainnet" }); // or { path } to choose the file
173
- ```
174
-
175
- Records are stored whole. The SQLite and Realm backends serialize each record to JSON with only
176
- the queryable columns mapped out, so a field they do not know about survives — which is what a
177
- consumer's cast-extended record relies on. JSON is narrower than IndexedDB's structured clone,
178
- though: a `Date` in a field you added comes back an ISO string, a `Set` or `Map` comes back empty,
179
- and a `bigint` throws on save. The package's own records are JSON-safe by design; keep yours that
180
- way too.
181
-
182
- ### Restore an imported wallet
183
-
184
- Register swap recovery before calling the core wallet's explicit `restore()`:
185
-
186
- ```ts
187
- import { IndexedDbAssetSwapRepository, registerAssetSwapRestore } from "@arkade-os/swap";
188
-
189
- const repository = new IndexedDbAssetSwapRepository();
190
- const unregisterSwapRestore = registerAssetSwapRestore(wallet, {
191
- arkServerUrl,
192
- repository,
193
- onResult: ({ changes, coverageError }) => {
194
- if (coverageError) console.warn("Swap coverage was incomplete", coverageError);
195
- console.info(`Restored or updated ${changes.length} swaps`);
196
- },
197
- });
198
-
199
- await wallet.restore();
200
- ```
201
-
202
- Core address, contract, history, and balance recovery finishes before the swap scan. Registering
203
- again replaces the prior hook, so setup is idempotent; call `unregisterSwapRestore()` when the
204
- integration no longer owns the wallet. A proxy or custom `IWallet` must also pass `indexer` and
205
- `serverPubkey` when it does not expose them. Keep calling `restoreAssetSwapRepository` directly
206
- during ordinary startup: hooks run only for an explicit `wallet.restore()`.
207
-
208
- ## Runtime requirements
209
-
210
- The one global the core requires is `crypto.getRandomValues`. Node and browsers have it; React
211
- Native does not, so install `react-native-get-random-values` (or `expo-crypto`) and import it
212
- before this package. `crypto.subtle` is unused. `EventSource` and `WebSocket` are needed only by
213
- the watch and relay transports, each of which takes an injected implementation.
214
-
215
- The client takes no server URL anywhere. Server info, chain reads and broadcast are all derived
216
- from the wallet, which is the single place that knows which operator it speaks to.
217
-
218
- ## Subpaths
219
-
220
- | Subpath | What it is |
221
- | ---------------------------------- | ----------------------------------------------------------------- |
222
- | `@arkade-os/swap` | the client, the verbs, the vocabulary, the error taxonomy |
223
- | `@arkade-os/swap/advanced` | the orchestration below the verbs: the drive, corridors, RFQ wire |
224
- | `@arkade-os/swap/node` | the Node storage default |
225
- | `@arkade-os/swap/repositories/*` | the React Native backends |
226
- | `@arkade-os/swap/nostr` | the Nostr RFQ transport, for hand-building one |
227
- | `@arkade-os/swap/protocol` | the v1 building blocks, deprecated |
228
-
229
- The root is a curated surface — if a name the client's modules define is not on it, it is on
230
- `./advanced` (manual driving with `createSwapDrive`, destination claiming with `corridorSet`,
231
- custom quote flows with `acceptQuote`/`quoteViaRfq`, record reading with `recordLeg`/`swapOf`).
232
- "Advanced" is a deliberate deep subpath, not a second compatibility promise: those names move
233
- with the client's internals across minor versions; the root is what stays put.
234
-
235
- `./nostr` is a floor and not a deprecation: the client opens the card's rendezvous itself, and the
236
- subpath is what keeps that an escape hatch rather than a wall. It is a separate entry point
237
- because `nostr-tools` is an optional peer dependency, so a consumer who never hand-builds a
238
- transport never pays for it.
239
-
240
- `./protocol` is the other kind of subpath, and it is a floor rather than a staging area. Every
241
- name on it was the integration surface before this client — requests, covenants, records, the RFQ
242
- manager, the restore scan — and each carries an `@deprecated` pointer naming what replaces it.
243
- None of them is on the root: this release breaks against `0.1.0-rc.1` regardless, so a period of
244
- re-exports would have split one migration into two and left 200 v1 names on a root whose claim is
245
- to be the v2 surface. Nothing on the subpath is scheduled to be removed, and the tags mean "the
246
- client does this for you now" rather than "this goes away next release". `MIGRATION.md` has the
247
- table, including the names that have no floor and why.
248
-
249
- ## Further reading
250
-
251
- - [MIGRATION.md](./MIGRATION.md) — every rename, every removal, and where each v1 name went.
252
- - [V2_API.md](./V2_API.md) — the developer UX note on the client surface.
1
+ # @arkade-os/swap
2
+
3
+ The swap client for [Arkade Intents](https://arkade.money). You state a route — what to give,
4
+ what to take, and where the value ends up — and the client resolves the market, picks the
5
+ contract, decodes the destination, seals the secret, funds with the right packet, persists before
6
+ it watches, claims, and refunds. Framework-free TypeScript over `@arkade-os/sdk`: no DOM and no
7
+ Node-specific APIs in the core, so it runs in Node, the browser and React Native alike.
8
+
9
+ ```ts
10
+ import { createSwapClient, IndexedDbAssetSwapRepository } from "@arkade-os/swap";
11
+
12
+ const client = createSwapClient({ wallet, repository: new IndexedDbAssetSwapRepository() });
13
+ ```
14
+
15
+ Construction is synchronous and inert: no network, no wallet read, no repository open. The first
16
+ call that needs one does it.
17
+
18
+ Market discovery needs no configuration either: the client defaults to the reference solver
19
+ registry's index for the wallet's network (`REGISTRY_URL[network]`, exported). Follow your own
20
+ registry instead with `discovery: { registryUrl }`, or opt out of registries entirely with
21
+ `discovery: { registryUrl: null }` — `discovery: { snapshot }` resolves against a fixed market
22
+ list without touching the network.
23
+
24
+ ## The four routes
25
+
26
+ Each is one `quote` → `accept` chain. `quote` returns binding, verified terms and touches nothing
27
+ durable; `accept` writes the record, then funds.
28
+
29
+ ```ts
30
+ const BTC = btcOn("arkade", "bitcoin"); // arkade:bitcoin/slip44:0 (slip44:1 on test networks)
31
+ const USDT = "arkade:bitcoin/asset:…";
32
+
33
+ // arkade -> lightning: pay an invoice. The amount is the invoice's.
34
+ await client.accept(await client.quote({ give: BTC, to: bolt11 }));
35
+
36
+ // arkade -> arkade: swap one asset for another.
37
+ await client.accept(
38
+ await client.quote({ give: BTC, take: USDT, amount: 1_000_000n, amountOn: "give" }),
39
+ );
40
+
41
+ // arkade -> onchain: withdraw to a bitcoin address.
42
+ await client.accept(
43
+ await client.quote({ give: BTC, to: "bc1p…", amount: 100_000n, amountOn: "take" }),
44
+ );
45
+
46
+ // lightning -> arkade: receive. The artifact is the invoice the solver minted.
47
+ const r = await client.receive({ via: "lightning", amount: 50_000n });
48
+ showToPayer(r.artifact.bolt11);
49
+ ```
50
+
51
+ The receive is the one route that is not a two-step, and the asymmetry is deliberate. Its
52
+ artifact is an invoice whose claim secret has to be durable before a payer can act on it, so
53
+ `receive` returns only after `accept` has persisted. Reaching for `quote` and reading the invoice
54
+ off it would show a payer an invoice this client could not yet claim; the verb removes the
55
+ ordering from the caller.
56
+
57
+ `onchain -> arkade` is a receive too: `client.receive({ via: "onchain", amount })` returns a
58
+ `deposit` artifact naming the L1 HTLC to fund, for exactly its `amount`, from any bitcoin wallet.
59
+ The client claims the solver's Arkade lockup once it is funded. If the solver never funds it, the
60
+ client takes the L1 funding back itself once the HTLC's refund leaf matures, paying a boarding
61
+ address of this wallet fixed at quote time and signing with the wallet key the HTLC was derived
62
+ with. The refund is built at the same `claimFeeRateSatVb` as the `arkade -> onchain` claim; wire
63
+ your own with `corridors: { onchain: { refund } }`.
64
+
65
+ An `arkade -> onchain` withdrawal claims the solver's L1 HTLC itself, and that claim's miner fee
66
+ comes out of the HTLC output — so the client grosses the take leg up by the claim's cost and the
67
+ recipient nets exactly the `amount` written, with the estimate folded into the reported `fee`. The
68
+ claim is built and broadcast by the client itself once the fill is claimable, signed by the
69
+ wallet's payout key and priced off a per-network fee-rate floor. A routing UI should raise it in
70
+ congestion — the claim has a consensus deadline — via
71
+ `corridors: { onchain: { claimFeeRateSatVb } }`; set it to `null` to take the claim over manually
72
+ (the drive then reports the L1 half as your job rather than blocking it). Wire your own builder
73
+ with `corridors: { onchain: { claim } }` and it wins over the default.
74
+
75
+ ### One call instead of two
76
+
77
+ `pay`, `receive` and `exchange` are `quote` → fee ceiling → `accept`, and add no capability the
78
+ client did not already have. What they add is the ceiling; what they subtract is vocabulary — a
79
+ product integrating payments never types the words route, corridor, market or quote.
80
+
81
+ ```ts
82
+ await client.pay(destination, { amount: 50_000n, maxFee: { amount: 500n, asset: BTC } });
83
+ await client.receive({ via: "lightning", amount: 50_000n });
84
+ await client.exchange({ give: BTC, take: USDT, amount: 1_000_000n, amountOn: "give" });
85
+ ```
86
+
87
+ `pay` takes any of the four destination forms — a bolt11 invoice, a bitcoin address, an Arkade
88
+ address, or a BIP21 URI carrying one of them — and exactly one corridor claims each. A plain
89
+ Arkade address is not a swap and does not become one: same asset, same rail, rate 1. It returns a
90
+ txid and no swap id, which is why `PayResult` has two arms.
91
+
92
+ Omit `amount` exactly when the destination pins it. An amount-bearing invoice does; passing one
93
+ beside it is `AmountMismatch` rather than a silent preference.
94
+
95
+ ## Asset ids and amounts
96
+
97
+ Asset ids are CAIP-19 with the rail as the CAIP-2 namespace, `<rail>:<network>/<namespace>:<ref>`.
98
+ `arkade`, `bolt11` and `bitcoin` are the implemented rails, and BTC has one id per rail. Use
99
+ `btcOn(rail, network)` and `arkadeAsset(network, id)` rather than writing the strings, and
100
+ `canonicalAssetId` when the input is human:
101
+
102
+ ```ts
103
+ const asset = canonicalAssetId("BTC", {
104
+ network: "regtest",
105
+ assets: [{ ticker: "BTC", id: "arkade:regtest/slip44:1" }],
106
+ });
107
+ ```
108
+
109
+ Ticker matching is case-insensitive, scoped to the wallet's network, and refuses a collision
110
+ instead of guessing.
111
+
112
+ Amounts are `bigint` atomic units everywhere inside the client. Decimal strings exist at two
113
+ boundaries and mean different things at each: display decimals (`"0.001"`) belong to the UI, atomic
114
+ decimals (`"100000"`) belong to records and RFQ payloads. `Amount.parse` and `Amount.format` cross
115
+ the first; the client crosses the second itself.
116
+
117
+ ## Watching, history and cancelling
118
+
119
+ There is no required `start()`. The client reads its repository once — `await client.ready` is
120
+ that read — and arms the drive when it finds live work, or on the first `accept` when it does
121
+ not. `start()` and `stop()` exist for manual control; `stop()` is a pause, not a cancellation, and
122
+ disposal is terminal cleanup that leaves every durable record and wallet registration recoverable.
123
+
124
+ ```ts
125
+ const off = client.onUpdate(({ swap, outcome, detail }) => render(swap.id, outcome, detail));
126
+
127
+ const live = await client.swaps({ outcome: "funded" });
128
+ const { outcome } = await client.cancel(swapId);
129
+ const result = await client.recover(swapId);
130
+ ```
131
+
132
+ `onUpdate` replays the current outcome of every swap it knows, then streams transitions, keyed on
133
+ the derived outcome so a legal backslide is delivered once. `Outcome` is one trader-centric
134
+ vocabulary across both families: `refunded` always means the value came back and a receive-leg
135
+ solver reclaim is `lapsed`, never the same word. The protocol's own state string is on `detail`
136
+ for logs.
137
+
138
+ `cancel` is typed to asset swaps, because that is where a cancel right exists. Corridor swaps
139
+ decompose into quote expiry, a timelocked refund and a lapse instead. A cancel that loses the race
140
+ to a fill reports the fill rather than throwing.
141
+
142
+ ## Errors
143
+
144
+ Sixteen classes, each a condition noun, all reachable from the root; `SWAP_ERROR_NAMES` is the
145
+ complete list. `SwapRefusal` is the solver declining — a decision, not a fault — and it is the one
146
+ member the protocol layer owns. Everything else names what the client refused and why:
147
+ `UnsupportedRoute`, `AmbiguousDestination`, `AmountMismatch`, `QuoteExpired`, `MaxFeeExceeded`,
148
+ `InsufficientFunds`, `QuoteVerificationFailed`, `NotCancellable`, `ClientDisposed`,
149
+ `MissingCorridorDep` and the rest.
150
+
151
+ ## Storage backends
152
+
153
+ | Backend | Import from | For |
154
+ | ------------------------------ | ------------------------------------- | ----------------------------------------------- |
155
+ | `InMemoryAssetSwapRepository` | `@arkade-os/swap` | tests, one-shot scripts — nothing survives exit |
156
+ | `IndexedDbAssetSwapRepository` | `@arkade-os/swap` | the browser (or a polyfilled IndexedDB) |
157
+ | `SQLiteAssetSwapRepository` | `@arkade-os/swap/repositories/sqlite` | React Native, over your SQLite driver |
158
+ | `RealmAssetSwapRepository` | `@arkade-os/swap/repositories/realm` | React Native, over your Realm instance |
159
+ | `nodeSwapRepository()` | `@arkade-os/swap/node` | Node — file-backed SQLite, opened for you |
160
+
161
+ There is no implicit default and never an in-memory fallback: accepting a swap with nowhere to
162
+ write it is the silent loss the rule exists to forbid, so `accept` refuses with
163
+ `MissingCorridorDep("arkade", "repository")` instead. In-memory is available, explicitly, which is
164
+ the only way ephemeral storage is on the table.
165
+
166
+ Neither React Native subpath adds a dependency — they take the SDK's structural `SQLExecutor` and
167
+ `RealmLike` handles, so you pass the database you already opened. `@arkade-os/swap/node` is the
168
+ exception and the only entry point that imports `node:` builtins, which is why it is a subpath
169
+ rather than something the main entry falls back to. It opens the database under the platform
170
+ config directory at `arkade/swaps/swaps-<network>.sqlite`, and it is the one backend whose
171
+ disposal closes a connection, because it is the one that opened it:
172
+
173
+ ```ts
174
+ import { nodeSwapRepository } from "@arkade-os/swap/node";
175
+
176
+ await using swaps = nodeSwapRepository({ network: "bitcoin" }); // or { path } to choose the file
177
+ ```
178
+
179
+ Records are stored whole. The SQLite and Realm backends serialize each record to JSON with only
180
+ the queryable columns mapped out, so a field they do not know about survives — which is what a
181
+ consumer's cast-extended record relies on. JSON is narrower than IndexedDB's structured clone,
182
+ though: a `Date` in a field you added comes back an ISO string, a `Set` or `Map` comes back empty,
183
+ and a `bigint` throws on save. The package's own records are JSON-safe by design; keep yours that
184
+ way too.
185
+
186
+ For bounded reads, all four backends provide `getAssetSwapsPage`,
187
+ `getRfqSwapsPage`, and `getSwapRecordsPage`. Pass `{ limit, after? }` with a
188
+ limit of 1–500, then use each result's `nextCursor` for the following page.
189
+ Asset swaps and swap records sort by ID. RFQ swaps sort by `(updatedAt, rfqId)`
190
+ and accept `{ state?, since? }`; `since` is inclusive Unix seconds. Keep the
191
+ filter fixed while paging. Repository collection reads use pages directly;
192
+ internal recovery and lifecycle paths consume every page before acting.
193
+ SDK transaction-history page `since` values use Unix milliseconds instead.
194
+ SQLite RFQ pages use a row-value comparison, so they need SQLite 3.15.0 or
195
+ newer.
196
+
197
+ ### Restore an imported wallet
198
+
199
+ Run the core wallet's `restore()` first (addresses, contracts, history), **then** create the client:
200
+
201
+ ```ts
202
+ await wallet.restore();
203
+ const client = createSwapClient({ wallet, repository: new IndexedDbAssetSwapRepository() });
204
+ await client.ready;
205
+ ```
206
+
207
+ `client.ready` rebuilds a record for every offer deposit in that history, with
208
+ `market: { kind: "restored" }`. A client created before `restore()` finishes rebuilds only what
209
+ history held at that moment, until its next construction. Corridor swaps a `0.0.x` client stored
210
+ are adopted the same way, with `backend: "rfq"`.
211
+
212
+ ## Runtime requirements
213
+
214
+ The one global the core requires is `crypto.getRandomValues`. Node and browsers have it; React
215
+ Native does not, so install `react-native-get-random-values` (or `expo-crypto`) and import it
216
+ before this package. `crypto.subtle` is unused. `EventSource` and `WebSocket` are needed only by
217
+ the watch and relay transports, each of which takes an injected implementation.
218
+
219
+ The client takes no server URL. Server info, Arkade chain reads and broadcast are all derived
220
+ from the wallet, which is the single place that knows which operator it speaks to. The onchain
221
+ corridor is the exception: `IWallet` carries no L1 provider, so it reads bitcoin from Esplora at
222
+ `ESPLORA_URL[network]`. Point it elsewhere with
223
+ `corridors: { onchain: { chain: { esploraUrl } } }`, or pass `{ provider }` to read through your
224
+ own `OnchainProvider` — an Electrum-backed wallet then watches and claims the HTLC over its own
225
+ backend.
226
+
227
+ ## Subpaths
228
+
229
+ | Subpath | What it is |
230
+ | ---------------------------------- | ----------------------------------------------------------------- |
231
+ | `@arkade-os/swap` | the client, the verbs, the vocabulary, the error taxonomy |
232
+ | `@arkade-os/swap/advanced` | the orchestration below the verbs: the drive, corridors, RFQ wire |
233
+ | `@arkade-os/swap/node` | the Node storage default |
234
+ | `@arkade-os/swap/repositories/*` | the React Native backends |
235
+ | `@arkade-os/swap/nostr` | the Nostr RFQ transport, for hand-building one |
236
+ | `@arkade-os/swap/protocol` | the v1 building blocks, deprecated |
237
+
238
+ The root is a curated surface — if a name the client's modules define is not on it, it is on
239
+ `./advanced` (manual driving with `createSwapDrive`, destination claiming with `corridorSet`,
240
+ custom quote flows with `acceptQuote`/`quoteViaRfq`, record reading with `recordLeg`/`swapOf`).
241
+ "Advanced" is a deliberate deep subpath, not a second compatibility promise: those names move
242
+ with the client's internals across minor versions; the root is what stays put.
243
+
244
+ `./nostr` is a floor and not a deprecation: the client opens the card's rendezvous itself, and the
245
+ subpath is what keeps that an escape hatch rather than a wall. It is a separate entry point
246
+ because `nostr-tools` is an optional peer dependency, so a consumer who never hand-builds a
247
+ transport never pays for it.
248
+
249
+ `./protocol` is the other kind of subpath, and it is a floor rather than a staging area. Every
250
+ name on it was the integration surface before this client — requests, covenants, records, the RFQ
251
+ manager, the restore scan — and each carries an `@deprecated` pointer naming what replaces it.
252
+ None of them is on the root: this release breaks against `0.1.0-rc.1` regardless, so a period of
253
+ re-exports would have split one migration into two and left 200 v1 names on a root whose claim is
254
+ to be the v2 surface. Nothing on the subpath is scheduled to be removed, and the tags mean "the
255
+ client does this for you now" rather than "this goes away next release". `MIGRATION.md` has the
256
+ table, including the names that have no floor and why.
257
+
258
+ ## Further reading
259
+
260
+ - [MIGRATION.md](./MIGRATION.md) — every rename, every removal, and where each v1 name went.
261
+ - [V2_API.md](./V2_API.md) — the developer UX note on the client surface.