@catena/sdk 0.0.0-bootstrap.0 → 0.4.0

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.
package/README.md CHANGED
@@ -1,4 +1,912 @@
1
1
  # @catena/sdk
2
2
 
3
- Bootstrap placeholder. Use @catena/sdk@latest once the CI-published release is
4
- available.
3
+ **Build agents that can move money without bypassing policy or approvals.**
4
+
5
+ `@catena/sdk` is the typed Node.js client for the Catena agent API. Use it to
6
+ read financial data, manage counterparties, move money through policy-checked
7
+ intents, and pay MPP or x402 HTTP 402 challenges.
8
+
9
+ Every Catena API request is signed. Every money movement follows Catena policy
10
+ and approval rules.
11
+
12
+ Node.js 20+. ESM. Framework-free.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ npm install @catena/sdk
18
+ ```
19
+
20
+ ## Contents
21
+
22
+ - [Quick start](#quick-start)
23
+ - [Common workflows](#common-workflows)
24
+ - [How intents work](#how-intents-work)
25
+ - [Protocol payments](#protocol-payments)
26
+ - [Error handling](#error-handling)
27
+ - [API reference](#api-reference)
28
+
29
+ ## Quick start
30
+
31
+ Create a client with your linked agent's private key:
32
+
33
+ ```ts
34
+ import { createCatenaClient } from "@catena/sdk"
35
+
36
+ const client = createCatenaClient({ privateKeyHex })
37
+ ```
38
+
39
+ Inspect the available source accounts and counterparty rails:
40
+
41
+ ```ts
42
+ const { accounts } = await client.listAccounts()
43
+ const { counterparties } = await client.listCounterparties()
44
+ ```
45
+
46
+ Choose the intended IDs, then submit a send intent. `counterpartyRailId` is a
47
+ rail ID, not a counterparty ID.
48
+
49
+ ```ts
50
+ const sourceAccountId = "acct_..."
51
+ const counterpartyRailId = "cpr_..."
52
+
53
+ const intent = await client.submitIntent({
54
+ action: {
55
+ type: "send",
56
+ accountId: sourceAccountId,
57
+ counterpartyRailId,
58
+ amount: "12.50",
59
+ method: "ach",
60
+ },
61
+ })
62
+
63
+ console.log(intent.status)
64
+ ```
65
+
66
+ You may omit `accountId` when policy allows exactly one source account. USD
67
+ intent amounts are decimal strings: `"12.50"` means $12.50, not cents or atomic
68
+ units.
69
+
70
+ ## Common workflows
71
+
72
+ ### Read account data
73
+
74
+ ```ts
75
+ const agent = await client.whoami()
76
+ const policy = await client.getPolicy()
77
+ const { accounts } = await client.listAccounts()
78
+
79
+ const account = accounts[0]
80
+ if (!account) throw new Error("No account is available")
81
+
82
+ const balance = await client.getAccountBalance(account.id)
83
+ const totalBalance = balance.balances?.total ?? balance.balance
84
+ const availableBalance = balance.balances?.available
85
+ const { transactions } = await client.listAccountTransactions(account.id, {
86
+ limit: 25,
87
+ })
88
+ ```
89
+
90
+ `balances.available` is the most one payment can move. It is below
91
+ `balances.total` when the account holds money it cannot spend in one payment:
92
+ money an in-flight send holds, money in transit between chains, money on another
93
+ network, or money the account cannot spend at all. It is zero while the account
94
+ is not active, and so is every `balances.byNetwork` `available`. The deprecated
95
+ flat `balance` field equals `balances.total`. If `balances` is absent on an
96
+ older API, the available balance is unknown.
97
+
98
+ `balances.byNetwork` gives `total` and `available` for each network that the
99
+ account holds and agents may use, so it says where the money sits:
100
+
101
+ ```ts
102
+ for (const { network, available } of balance.balances?.byNetwork ?? []) {
103
+ console.log(network, available.amount)
104
+ }
105
+ ```
106
+
107
+ `balances.byNetwork` is absent until the money of the account is split by
108
+ network. An empty array means the money is split, but no network of the account
109
+ is open to agents. The entries can add up to less than `balances.total`, which
110
+ also counts a network agents may not use. Their `available` values can add up to
111
+ more than `balances.available`, because one payment binds one network unless a
112
+ plan carries it across them.
113
+
114
+ `policy.capabilities` lists broad permissions. `policy.policyCapabilities`
115
+ contains per-account rules. `policy.counterpartyRules` controls counterparty
116
+ access, while `kind` and `expiresAt` identify an active temporary override.
117
+
118
+ For an on-chain deposit address:
119
+
120
+ ```ts
121
+ const deposit = await client.getAccountDepositAddress(walletAccountId, {
122
+ network: "base",
123
+ asset: "usdc",
124
+ })
125
+ ```
126
+
127
+ `deposit.source` is `wallet` or `liquidation`. x402, MPP, and viem require an
128
+ account whose deposit address returns `source: "wallet"` on the chosen network.
129
+
130
+ ### Manage counterparties
131
+
132
+ Create a counterparty with contact information:
133
+
134
+ ```ts
135
+ const created = await client.submitIntent({
136
+ action: {
137
+ type: "create_counterparty",
138
+ name: "Acme Vendor",
139
+ email: "billing@acme.test",
140
+ },
141
+ })
142
+ ```
143
+
144
+ The action may require approval. Poll it to a final state, then narrow the
145
+ runtime result before reading the new ID:
146
+
147
+ ```ts
148
+ let result = created
149
+ while (result.status === "pending" || result.status === "processing") {
150
+ await new Promise((resolve) => setTimeout(resolve, 2_000))
151
+ result = await client.getIntent(result.id)
152
+ }
153
+
154
+ const counterparty = result.data?.counterparty
155
+
156
+ if (
157
+ result.status !== "completed" ||
158
+ typeof counterparty !== "object" ||
159
+ counterparty === null ||
160
+ !("id" in counterparty) ||
161
+ typeof counterparty.id !== "string"
162
+ ) {
163
+ throw new Error(`Counterparty is not ready: ${result.status}`)
164
+ }
165
+
166
+ const counterpartyId = counterparty.id
167
+ ```
168
+
169
+ An email-only counterparty has no rails, and creating it does not send an email.
170
+
171
+ Request those details through Catena. Bank details require a KYB-verified
172
+ organization with fiat rails enabled.
173
+
174
+ ```ts
175
+ await client.submitIntent({
176
+ action: {
177
+ type: "request_counterparty_details",
178
+ counterpartyId,
179
+ methods: { bank: true, wallet: false },
180
+ },
181
+ })
182
+ ```
183
+
184
+ The request follows policy and may wait for approval. A second request while an
185
+ invitation is active returns HTTP 409 with
186
+ `counterparty_payment_request_conflict`; `error.details.invite` identifies the
187
+ existing invitation. Set at least one requested method to `true`.
188
+
189
+ You can also create a counterparty with a wallet rail already attached:
190
+
191
+ ```ts
192
+ await client.submitIntent({
193
+ action: {
194
+ type: "create_counterparty",
195
+ name: "Treasury",
196
+ rail: {
197
+ type: "wallet",
198
+ walletAddress: "0x1111111111111111111111111111111111111111",
199
+ network: "base",
200
+ },
201
+ },
202
+ })
203
+ ```
204
+
205
+ <details>
206
+ <summary><strong>Create a counterparty with a bank rail</strong></summary>
207
+
208
+ Bank rails require a KYB-verified organization with fiat rails enabled.
209
+
210
+ ```ts
211
+ await client.submitIntent({
212
+ action: {
213
+ type: "create_counterparty",
214
+ name: "Acme Vendor",
215
+ email: "billing@acme.test",
216
+ rail: {
217
+ type: "bank",
218
+ bankName: "Example Bank",
219
+ routingNumber: "021000021",
220
+ accountNumber: "123456789",
221
+ accountType: "checking",
222
+ addressStreet: "1 Main Street",
223
+ addressCity: "New York",
224
+ addressState: "NY",
225
+ addressPostalCode: "10001",
226
+ addressCountry: "USA",
227
+ },
228
+ },
229
+ })
230
+ ```
231
+
232
+ `routingNumber` must contain 9 digits. `accountNumber` accepts 4–17 digits.
233
+ `accountType` is `checking` or `savings`. `accountType`, `addressCountry`, and
234
+ the action-level `email` are optional; the remaining fields are required.
235
+
236
+ </details>
237
+
238
+ When sending, match the method to the rail: `ach` and `wire` require a bank
239
+ rail; `on-chain` requires a wallet rail.
240
+
241
+ ### Transfer between accounts
242
+
243
+ ```ts
244
+ const intent = await client.submitIntent({
245
+ action: {
246
+ type: "transfer",
247
+ accountId: sourceAccountId,
248
+ toAccountId: destinationAccountId,
249
+ amount: "100.00",
250
+ memo: "Treasury rebalance",
251
+ },
252
+ })
253
+ ```
254
+
255
+ ACH and wire `send` actions accept an optional `memo`, which is sent with the
256
+ bank payment. All `send` actions accept an optional `description` for an
257
+ internal Catena note. On-chain `memo` remains accepted for compatibility but is
258
+ deprecated and is not sent to the blockchain. `transfer` accepts both fields.
259
+
260
+ ### Sends that cross chains
261
+
262
+ A `send` to a counterparty wallet on the other side of the Base and Arc lane is
263
+ an ordinary `send`. When the account cannot pay it from its balance on the
264
+ rail's network, the send crosses chains under the same intent: `submitIntent`
265
+ signs the burn toward the agent's own address on the other chain, and
266
+ `continueIntent` signs the send to the counterparty once the funds land. One
267
+ intent covers the whole payment, so policy, spend limits and any approval are
268
+ evaluated once. Gas on both legs is paid by Catena.
269
+
270
+ ```ts
271
+ let intent = await client.submitIntent({
272
+ action: {
273
+ type: "send",
274
+ accountId,
275
+ counterpartyRailId: walletRailIdOnTheOtherChain,
276
+ amount: "250.00",
277
+ method: "on-chain",
278
+ description: "Invoice 1042",
279
+ },
280
+ })
281
+
282
+ while (intent.crossChain && intent.crossChain.nextStep === "wait") {
283
+ await new Promise((resolve) => setTimeout(resolve, 30_000))
284
+ intent = await client.getIntent(intent.id)
285
+ }
286
+
287
+ if (intent.crossChain?.nextStep === "continue") {
288
+ intent = await client.continueIntent({ intentId: intent.id })
289
+ // Poll getIntent until crossChain.nextStep reads "done".
290
+ }
291
+ ```
292
+
293
+ `crossChain` is present only when the send crossed. Its `nextStep` is the whole
294
+ contract: `wait` while the crossing runs, `continue` when `continueIntent` is
295
+ due, `done` once the counterparty was paid, `blocked` when the crossing cannot
296
+ continue, with `failureReason` saying why; read it before choosing a recovery,
297
+ since not every reason needs an operator. `continue` is served only once the
298
+ funds are credited on the destination, and it waits a day for `continueIntent`;
299
+ past that the crossing is `blocked` with `failureReason: "not_continued"`, and
300
+ the funds sit in the account's balance on the destination, so a plain send pays
301
+ the counterparty from there. A few minutes is typical; up to twenty on the
302
+ Standard lane. A network the provider does not sponsor yet is refused with
303
+ `wallet_send_action_not_yet_enabled` rather than charged to you; on
304
+ `continueIntent` the intent stays at `continue`, so call it again later.
305
+
306
+ ### Payments a person approves
307
+
308
+ A `send` or `transfer` over the organization's approval threshold parks for a
309
+ person rather than being refused. Once a person approves it, an admin signs it
310
+ in the Catena console. You do not finish it: poll it until it is done or
311
+ blocked.
312
+
313
+ Poll the intent with `getIntent` and read `movement`. It is served on a read,
314
+ not on the `submitIntent` result, and only for a payment carried by a movement
315
+ plan. `movement.nextStep` is what `status` cannot tell you: a payment waiting on
316
+ a person and one an admin is signing both read `processing`.
317
+
318
+ ```ts
319
+ const action = {
320
+ type: "send",
321
+ accountId,
322
+ counterpartyRailId,
323
+ amount: "2500.00",
324
+ method: "on-chain",
325
+ } as const
326
+
327
+ const submitted = await client.submitIntent({ action })
328
+
329
+ // `movement` is served by getIntent, not by submitIntent, so read it first.
330
+ let intent = await client.getIntent(submitted.id)
331
+ while (intent.movement?.nextStep === "wait") {
332
+ await new Promise((resolve) => setTimeout(resolve, 30_000))
333
+ intent = await client.getIntent(intent.id)
334
+ }
335
+ ```
336
+
337
+ - `wait` — a person is deciding it, an admin is signing it, or its signature is
338
+ in flight. Read it again with `getIntent`.
339
+ - `done` — the payment completed.
340
+ - `blocked` — it ended without paying. `reasons` says why, and is empty when an
341
+ approval lapsed.
342
+
343
+ `movement.nextStep` never reads `continue`. `continueIntent` refuses a payment a
344
+ person approved with `movement_admin_completes_payment`, and sending the same
345
+ request again on the same idempotency key hands back the payment's intent
346
+ without signing anything. Both are answers, not failures: keep polling.
347
+
348
+ A payment nobody had to approve is still yours to sign, and `submitIntent` hands
349
+ you its stamp. If you restarted before signing it, send the original request
350
+ again on the same idempotency key. Within about five minutes of the first send
351
+ it answers `movement_authorization_in_progress`; after that it hands the payment
352
+ back for you to sign.
353
+
354
+ The SDK checks a movement stamp against the `action` you submitted before it
355
+ signs. It is the one check that compares the payment against something Catena
356
+ did not supply. Where every payload that can move value states its amount in a
357
+ field the signature covers, a payment that would not pay the amount you asked
358
+ for is refused before anything is signed. A payment delivered as a raw
359
+ transaction or a batched call instead carries its amount inside call data this
360
+ client reproduces without decoding, so that one check is left unbound rather
361
+ than guessed at.
362
+
363
+ Signing a movement stamp needs the optional `viem` peer (`>=2.24.0`). A movement
364
+ is signed as pre-hashed digests, and the SDK rebuilds them locally rather than
365
+ trust what it is handed — it will not sign digests it cannot check. Without
366
+ `viem` installed, a movement stamp is refused before anything is signed. A
367
+ crossing needs none of this and works either way.
368
+
369
+ An approval does not wait forever. If no admin signs the payment before it
370
+ lapses, it expires unpaid and has to be asked for again.
371
+
372
+ ### Request a temporary policy override
373
+
374
+ Policy overrides always wait for human approval. This example requests a higher
375
+ per-transaction send limit for one hour:
376
+
377
+ ```ts
378
+ const intent = await client.submitIntent({
379
+ action: {
380
+ type: "policy_override",
381
+ operations: [
382
+ {
383
+ type: "increase_limit",
384
+ accountId,
385
+ capability: "send",
386
+ limitType: "per_transaction_amount",
387
+ newLimit: { amount: "5000.00", assetId: "USD" },
388
+ },
389
+ ],
390
+ durationSeconds: 3_600,
391
+ reason: "Pay an approved vendor invoice",
392
+ },
393
+ })
394
+ ```
395
+
396
+ Amount limits use `per_transaction_amount`, `daily_amount`, `weekly_amount`, or
397
+ `monthly_amount`. Count limits use `hourly_count` or `daily_count` with
398
+ `newLimit: { count }`. `capability` is `send` or `transfer`. Amounts are
399
+ positive decimal strings with up to six fractional digits; counts are positive
400
+ integers. Overrides last from one minute to seven days, starting at approval.
401
+ Submit 1–10 unique account, capability, and limit combinations. `reason` must
402
+ contain 1–280 characters.
403
+
404
+ ## How intents work
405
+
406
+ Policy-controlled actions use `submitIntent`. Catena evaluates policy, collects
407
+ any required approval, and co-signs the action when needed.
408
+
409
+ `submitIntent` returns the intent's current state. It does not guarantee that
410
+ execution is finished.
411
+
412
+ | Status | Meaning |
413
+ | ------------ | --------------------------------------------------------------- |
414
+ | `completed` | The action succeeded. |
415
+ | `pending` | The intent is waiting for human approval. |
416
+ | `processing` | Catena accepted the intent and is still working. |
417
+ | `blocked` | Policy or an operator declined the intent. This state is final. |
418
+ | `failed` | The intent failed, expired, or reversed. This state is final. |
419
+
420
+ Read `reasons` for a non-completed outcome and `expiresAt` for an approval
421
+ deadline. For ordinary actions, poll `pending` and `processing` intents with a
422
+ delay until they reach a final state. Treat only `completed` as success.
423
+
424
+ Two kinds of intent never reach a final state by polling alone. MPP and x402
425
+ payments: after approval, repeat the original paid request so its fresh
426
+ challenge can use the approval. For these protocols, `completed` means Catena
427
+ delivered the payment authorization, and on-chain settlement is verified
428
+ separately. A `send` or `transfer` a person approved: it rests at `processing`
429
+ while an admin signs it, and `movement.nextStep` reads `wait` until it is done
430
+ or blocked — see [Payments a person approves](#payments-a-person-approves).
431
+
432
+ ### Result data
433
+
434
+ `IntentResult.data` is runtime data. Narrow it before use.
435
+
436
+ | Action | Result data when available |
437
+ | ------------------------------ | ------------------------------------------------------------- |
438
+ | `send`, `transfer` | `data.transaction` |
439
+ | `create_counterparty` | `data.counterparty` |
440
+ | `request_counterparty_details` | `data.counterpartyId`, `data.counterpartyName`, `data.invite` |
441
+ | `x402`, `mpp` | `data.paymentCredential`, `data.transaction` |
442
+ | `policy_override` | `data.policyOverride.policyId` |
443
+
444
+ `metadata.dataUrl`, when present, links to the relevant approval or result in
445
+ the Catena console.
446
+
447
+ ### Source selection
448
+
449
+ For `send`, omit `accountId` only when policy allows exactly one source account.
450
+ Zero eligible accounts returns HTTP 403 with `policy_send_account_unavailable`;
451
+ multiple eligible accounts returns HTTP 400 with `policy_send_account_required`.
452
+
453
+ Catena pins the selected source to the intent. A later policy change does not
454
+ silently switch accounts. Transfers always require `accountId`.
455
+
456
+ ### Idempotency
457
+
458
+ The SDK generates a fresh idempotency key for every `submitIntent` call unless
459
+ you provide one. Use an explicit key when separate calls or processes must refer
460
+ to the same logical operation.
461
+
462
+ Reuse a key only with the same action and source. The source account stays
463
+ pinned even if policy changes. A different action or source returns HTTP 409.
464
+ When `intent.replayed` is `true`, Catena returned the existing intent without
465
+ starting the action again.
466
+
467
+ ## Protocol payments
468
+
469
+ | Use case | Import |
470
+ | ------------------------------- | ------------------ |
471
+ | Managed x402 payment loop | `@catena/sdk/x402` |
472
+ | Managed or custom MPP loop | `@catena/sdk/mpp` |
473
+ | viem-compatible x402 account | `@catena/sdk/viem` |
474
+ | Direct agent API payment intent | `@catena/sdk` |
475
+
476
+ ### Pay x402 challenges
477
+
478
+ The helper supports x402 v2 `exact` EIP-3009 payments on structurally valid EVM
479
+ networks and token contracts. The connected Catena server decides which networks
480
+ and canonical assets are payable. Native USDC on Base and Base Sepolia is
481
+ supported where enabled. Arc support is rolling out. Wrap `fetch` to pay a
482
+ compatible challenge and retry once with `PAYMENT-SIGNATURE`:
483
+
484
+ ```ts
485
+ import { createCatenaClient } from "@catena/sdk"
486
+ import { wrapFetchWithX402Payment } from "@catena/sdk/x402"
487
+
488
+ const client = createCatenaClient({ privateKeyHex })
489
+ const fetchWithPayment = wrapFetchWithX402Payment(client, {
490
+ accountId: walletAccountId,
491
+ maxAtomicAmount: 1_000_000n,
492
+ })
493
+
494
+ const response = await fetchWithPayment("https://api.example.com/paid-thing")
495
+ ```
496
+
497
+ `maxAtomicAmount` uses atomic USDC units, so `1_000_000n` is 1 USDC. Ordinary
498
+ responses and 402s without a decodable v2 challenge pass through untouched. A
499
+ decoded but unpayable challenge throws `X402PaymentError`.
500
+
501
+ Request bodies must be replayable. Put a string, `URLSearchParams`, `Blob`,
502
+ `ArrayBuffer`, typed array, or `DataView` in the `init` argument. Body-bearing
503
+ `Request` objects and streams are rejected before payment.
504
+
505
+ The helper examines at most the first five `exact` candidates and stops at the
506
+ first one Catena can pay.
507
+
508
+ For direct control, use `decodePaymentRequired(response)` and
509
+ `payX402Challenge(client, options)`. The latter returns a receipt containing the
510
+ intent ID, selected requirements, and `paymentSignature` header value. It pays
511
+ but does not retry the HTTP request for you.
512
+
513
+ <details>
514
+ <summary><strong>x402 challenge requirements</strong></summary>
515
+
516
+ A structurally valid challenge must use x402 v2, the `exact` scheme, an EVM
517
+ CAIP-2 network, a valid token contract, and an EIP-3009 authorization. The
518
+ amount must be a canonical atomic-unit integer, `payTo` must be a valid EVM
519
+ address, and `maxTimeoutSeconds` must be from 1 to 3,600. The requirement must
520
+ include an EIP-712 domain name and version. The server separately validates
521
+ network support, the canonical asset and domain, and the saved counterparty.
522
+
523
+ </details>
524
+
525
+ ### Pay MPP challenges
526
+
527
+ Install the optional peers with the SDK:
528
+
529
+ ```sh
530
+ npm install @catena/sdk mppx@^0.9.0 viem@^2.54.0
531
+ ```
532
+
533
+ The managed wrapper recognizes `evm/charge` and `usdc/charge` for structurally
534
+ valid EVM networks and token contracts. The connected Catena server decides
535
+ which networks and canonical USDC contracts are payable. Native USDC on Base and
536
+ Base Sepolia is supported where enabled. Arc support is rolling out:
537
+
538
+ ```ts
539
+ import { createCatenaClient } from "@catena/sdk"
540
+ import {
541
+ MppCounterpartyNotFoundError,
542
+ wrapFetchWithMppPayment,
543
+ } from "@catena/sdk/mpp"
544
+
545
+ const client = createCatenaClient({ privateKeyHex })
546
+ const fetchWithPayment = wrapFetchWithMppPayment(client, {
547
+ accountId: walletAccountId,
548
+ maxAtomicAmount: 1_000_000n,
549
+ })
550
+
551
+ const response = await fetchWithPayment("https://api.example.com/paid-thing")
552
+ ```
553
+
554
+ The wrapper tries up to five supported candidates, creates at most one
555
+ credential, and retries the request once. `onPayment` runs after payment and
556
+ before the retry. Its receipt contains no credential. Non-replayable bodies and
557
+ cross-origin redirects are rejected before payment.
558
+
559
+ The receipt contains `intentId`, `method`, `atomicAmount`, `network`,
560
+ `recipient`, and `resourceUrl`.
561
+
562
+ When a recipient is not saved, the server-resolved `requiredRail` can be passed
563
+ directly to a deliberate counterparty intent:
564
+
565
+ ```ts
566
+ try {
567
+ await fetchWithPayment(url)
568
+ } catch (error) {
569
+ if (error instanceof MppCounterpartyNotFoundError && error.requiredRail) {
570
+ await client.submitIntent({
571
+ action: {
572
+ type: "create_counterparty",
573
+ name: "Approved seller",
574
+ rail: error.requiredRail,
575
+ },
576
+ })
577
+ }
578
+ }
579
+ ```
580
+
581
+ `X402CounterpartyNotFoundError.requiredRail` has the same contract.
582
+
583
+ Need custom transport, hooks, or candidate selection? Add Catena's methods to
584
+ your own mppx client:
585
+
586
+ ```ts
587
+ import { createCatenaClient } from "@catena/sdk"
588
+ import { catena } from "@catena/sdk/mpp"
589
+ import { Mppx } from "mppx/client"
590
+
591
+ const client = createCatenaClient({ privateKeyHex })
592
+
593
+ const mppx = Mppx.create({
594
+ methods: [
595
+ catena({
596
+ client,
597
+ accountId: walletAccountId,
598
+ maxAtomicAmount: 1_000_000n,
599
+ }),
600
+ ],
601
+ maxPaymentRetries: 1,
602
+ polyfill: false,
603
+ })
604
+
605
+ const response = await mppx.fetch("https://api.example.com/paid-thing")
606
+ ```
607
+
608
+ `catena.charge(options)` is an alias for `catena(options)`. By default, mppx can
609
+ make up to three payment attempts per fetch. Set `maxPaymentRetries: 1` to allow
610
+ one. Separate fetch calls can still pay again. `maxAtomicAmount` applies to each
611
+ attempt, not the combined total.
612
+
613
+ With mppx 0.9, pass the HTTP method and body in the fetch `init` argument, not
614
+ only in a `Request`. Buffer the body first; streams and raw `FormData` are not
615
+ safe to replay.
616
+
617
+ <details>
618
+ <summary><strong>MPP challenge requirements</strong></summary>
619
+
620
+ The client forwards structurally valid EVM networks and token contracts to the
621
+ server. The server decides which are payable. Native USDC on Base and Base
622
+ Sepolia is supported where enabled. Arc support is rolling out. A challenge must
623
+ also meet these rules:
624
+
625
+ - `method` is `evm` or `usdc`, and `intent` is `charge`;
626
+ - `id` and `realm` contain 1–256 characters, the serialized request is at most
627
+ 16 KiB, and the full challenge is at most 32 KiB;
628
+ - `expires` is UTC with a trailing `Z`, has at most three fractional digits, and
629
+ leaves between 5 seconds and 1 hour;
630
+ - the amount is a positive canonical integer of at most 78 digits and does not
631
+ exceed `maxAtomicAmount`, when configured;
632
+ - the currency and recipient are valid EVM addresses;
633
+ - method details use 6 decimals and a single authorization credential; splits
634
+ are unsupported, and an optional Permit2 address must be valid;
635
+ - `description` is at most 1,024 characters and `externalId` is at most 256;
636
+ - `header` is omitted or exactly `Payment-Authorization`;
637
+ - `digest` uses `sha-256=:<base64>:` or `sha-256=<base64>` with canonical,
638
+ padded standard Base64;
639
+ - `opaque`, when present, is nonempty unpadded Base64url of at most 8 KiB;
640
+ - addresses are lowercase or valid EIP-55;
641
+ - `description` and `externalId` contain valid Unicode.
642
+
643
+ mppx may report `No method found for challenges` when one of these requirements
644
+ fails, even if `evm.charge` or `usdc.charge` appears available.
645
+
646
+ </details>
647
+
648
+ ### Use a Catena wallet with viem
649
+
650
+ `createCatenaAccount` returns a viem `Account` for x402 clients that expect
651
+ `{ address, signTypedData }`:
652
+
653
+ ```sh
654
+ npm install @catena/sdk viem@^2.21
655
+ ```
656
+
657
+ ```ts
658
+ import { createCatenaClient } from "@catena/sdk"
659
+ import { createCatenaAccount } from "@catena/sdk/viem"
660
+
661
+ const client = createCatenaClient({ privateKeyHex })
662
+ const account = await createCatenaAccount(client, {
663
+ accountId: walletAccountId,
664
+ network: "base",
665
+ })
666
+ ```
667
+
668
+ Pass `account` to any x402 client that accepts a viem account or
669
+ `{ address, signTypedData }` signer.
670
+
671
+ A Catena wallet is custodial. The account signs only structurally valid x402
672
+ EIP-3009 `TransferWithAuthorization` data. The server decides which EVM networks
673
+ and canonical token contracts are payable. `signMessage`, `signTransaction`, and
674
+ raw-hash signing are unavailable.
675
+
676
+ The account must resolve to a deposit address whose source is `wallet`.
677
+ `network` defaults to `base`; pass `arc` for an Arc wallet when enabled or
678
+ `base-sepolia` for a testnet wallet. The network must match the wallet account.
679
+
680
+ ## Error handling
681
+
682
+ Branch on stable fields and error classes, not message text.
683
+
684
+ ### Core client errors
685
+
686
+ | Error | Recovery |
687
+ | ------------------- | --------------------------------------------------------------------------------- |
688
+ | `InvalidKeyError` | Supply a valid linked P-256 private key. |
689
+ | `ApiError` | Branch on `code`; inspect `status`, `fields`, and `details`. |
690
+ | `TimeoutError` | Treat the request as uncertain until its operation-specific recovery is complete. |
691
+ | `IntentSubmitError` | Branch on `outcome`; use `intentId` to reconcile an uncertain submission. |
692
+
693
+ The SDK combines the API's error summary and field explanations in `message`,
694
+ identifying the affected request fields and what needs correction. `fields`
695
+ preserves the individual explanations keyed by request field path, such as
696
+ `action.memo`. The `request` key represents a request-wide issue rather than a
697
+ field; its explanation appears in `message` without a field-path prefix.
698
+ Malformed `fields` are ignored without discarding the error's message or code.
699
+
700
+ For `IntentSubmitError`:
701
+
702
+ - `not-submitted` means no money moved. Fix the cause and submit again with a
703
+ new idempotency key.
704
+ - `unknown` means Catena may have acted. Poll `getIntent(error.intentId)` and
705
+ submit again only after the intent becomes `blocked` or `failed`.
706
+
707
+ A timeout means the SDK stopped waiting, not necessarily that the server stopped
708
+ working. For an exact `submitIntent` retry after a create timeout, you must have
709
+ chosen and persisted an `idempotencyKey` before the first call. Retry the
710
+ unchanged action with that key.
711
+
712
+ If an exact retry returns `wallet_send_intent_not_executing`,
713
+ `x402_intent_state_mismatch`, or `mpp_intent_state_mismatch`, do not create a
714
+ replacement payment. Reconcile the existing intent with the operator.
715
+
716
+ Payment errors use CAIP-2 network IDs. Missing-counterparty errors may also
717
+ include a server-resolved `requiredRail` whose product network identifier can be
718
+ passed directly to a `create_counterparty` intent. Known mappings are
719
+ `eip155:8453` to `base`, `eip155:84532` to `base-sepolia`, and `eip155:5042` to
720
+ `arc`.
721
+
722
+ <details>
723
+ <summary><strong>x402 recovery</strong></summary>
724
+
725
+ | Error | Recovery |
726
+ | ------------------------------- | ----------------------------------------------------------------------------------------------------- |
727
+ | `X402PaymentError` | Do not retry automatically. If no subclass provides a safe recovery path, escalate to an operator. |
728
+ | `X402NetworkMismatchError` | Use an account on one of `requiredNetworks`. |
729
+ | `X402CounterpartyNotFoundError` | Create a counterparty from `requiredRail` when present; otherwise resolve the rail manually. |
730
+ | `X402ApprovalPendingError` | Approve the intent, then repeat the original request. |
731
+ | `X402RetryFailedError` | Payment completed. Retry manually with `receipt.paymentSignature`; do not run the payment loop again. |
732
+ | `X402SubmitInterruptedError` | Check `getIntent(intentId)` before paying again. |
733
+
734
+ A create-phase `TimeoutError` from the x402 wrapper means no payment was
735
+ authorized, so the request can be run again. For an interrupted submission:
736
+
737
+ - `completed`: reuse `data.paymentCredential.value` as `PAYMENT-SIGNATURE`;
738
+ - `processing`: keep polling; and
739
+ - `blocked` or `failed`: a new payment attempt is safe.
740
+
741
+ </details>
742
+
743
+ <details>
744
+ <summary><strong>MPP recovery</strong></summary>
745
+
746
+ | Error | Recovery |
747
+ | ------------------------------ | ----------------------------------------------------------------- |
748
+ | `MppFetchPaymentError` | If `intentId` is present, reconcile it before paying again. |
749
+ | `MppNetworkMismatchError` | Fund the payment from one of `requiredNetworks`. |
750
+ | `MppCounterpartyNotFoundError` | Create a counterparty from `requiredRail` when present. |
751
+ | `MppApprovalPendingError` | Approve the intent, then repeat the original request. |
752
+ | `MppPaymentDeclinedError` | Treat the result as final. |
753
+ | `MppSubmitInterruptedError` | Reconcile `intentId` before authorizing another payment. |
754
+ | `MppRetryFailedError` | Payment completed. Reconcile `receipt.intentId` before any retry. |
755
+
756
+ An `MppPaymentError` from a custom mppx integration exposes `intentId`,
757
+ `status`, `reasons`, and `expiresAt`. A completed MPP intent proves that Catena
758
+ produced an authorization, not that the seller settled it or delivered the
759
+ resource.
760
+
761
+ When mppx makes multiple attempts, the final error identifies only its own
762
+ intent. Reconcile every known attempt before paying again.
763
+
764
+ </details>
765
+
766
+ <details>
767
+ <summary><strong>viem recovery</strong></summary>
768
+
769
+ | Error | Meaning |
770
+ | ----------------------------------- | ------------------------------------------------------------------------------------ |
771
+ | `UnsupportedTypedDataError` | Refused client-side; nothing was submitted. Inspect `reason`. |
772
+ | `UnsupportedAccountCapabilityError` | The requested signing method is not available. |
773
+ | `NotAWalletAccountError` | Choose an account whose deposit-address source is `wallet`. |
774
+ | `X402ApprovalPendingError` | Approve the intent, then let the x402 tooling retry. |
775
+ | `X402PaymentDeclinedError` | Policy blocked or failed the payment. This result is final. |
776
+ | `X402PaymentInFlightError` | Reconcile `intentId`. Polling will not advance it; repeat the original paid request. |
777
+ | `X402SubmitInterruptedError` | Reconcile `intentId`; do not pay again. |
778
+ | `X402PaymentSignatureUnusableError` | Payment completed. Reconcile `intentId`; do not pay again. |
779
+ | `SignatureVerificationFailedError` | Payment completed. Do not use the signature or pay again. |
780
+
781
+ `data.paymentCredential.value` is the Base64 x402 envelope used as the
782
+ `PAYMENT-SIGNATURE` header. `signTypedData` returns the inner hex signature.
783
+ They are not interchangeable.
784
+
785
+ </details>
786
+
787
+ ## API reference
788
+
789
+ ### Client methods
790
+
791
+ | Method | Purpose |
792
+ | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
793
+ | `whoami()` | Return the linked agent. |
794
+ | `submitFeedback(body)` | Send integration feedback to Catena operators. This has no money effect. |
795
+ | `getPolicy()` | Return the agent's effective policy. |
796
+ | `listAccounts()` | List accounts visible to the agent. |
797
+ | `getAccountBalance(accountId)` | Return total and available balances, overall and per network. |
798
+ | `listAccountTransactions(accountId, params?)` | List transactions with optional `start`, `end`, `limit`, and `offset`. |
799
+ | `getAccountDepositAddress(accountId, params)` | Resolve an address for a `network` and `asset`. |
800
+ | `listCounterparties(params?)` | List counterparties; address and network filters check wallet ownership within a network class. A wallet rail omits `network` when its configured destination is unavailable to the agent and cannot receive an agent send until that changes. |
801
+ | `submitIntent({ action, idempotencyKey? })` | Submit a policy-checked action. |
802
+ | `getIntent(id)` | Read the current intent state. |
803
+ | `continueIntent({ intentId, idempotencyKey?, action? })` | Finish the second leg of a send that crossed chains, once `crossChain.nextStep` reads `continue`. A payment carried by a movement plan is refused with `movement_admin_completes_payment`. |
804
+ | `unlinkAgent()` | Permanently revoke the current agent link and its active keys. |
805
+ | `reportSettlement(params)` | Report an on-chain settlement. Managed payment wrappers call this automatically. |
806
+
807
+ Transaction ranges use inclusive ISO 8601 `start` and `end` timestamps. `limit`
808
+ defaults to 50 and is capped at 200; `offset` defaults to 0. `reportSettlement`
809
+ accepts `{ intentId, txHash, receipt? }`.
810
+
811
+ ### Intent actions
812
+
813
+ | Action | Purpose |
814
+ | ------------------------------ | ------------------------------------------------- |
815
+ | `send` | Send by ACH, wire, or on-chain rail. |
816
+ | `transfer` | Transfer between Catena accounts. |
817
+ | `create_counterparty` | Save a counterparty with contact or rail details. |
818
+ | `request_counterparty_details` | Request bank or wallet details. |
819
+ | `x402` | Submit a low-level x402 payment requirement. |
820
+ | `mpp` | Submit a low-level MPP charge. |
821
+ | `policy_override` | Request a temporary increase to policy limits. |
822
+
823
+ Use the x402 and MPP helpers for ordinary protocol payments. They parse the
824
+ challenge, enforce replay safety, submit the intent, and handle the paid retry.
825
+
826
+ For direct intents, `x402` requires `accountId` and `paymentRequirements`, with
827
+ optional `resource`, `authorization`, and `signedOffer`. `mpp` requires
828
+ `accountId` and `challenge`, with optional `resource`.
829
+
830
+ ### Payment helper options
831
+
832
+ | API | Required options | Optional options |
833
+ | -------------------------- | ------------------------------ | ------------------------------------------- |
834
+ | `wrapFetchWithX402Payment` | `accountId` | `baseFetch`, `maxAtomicAmount`, `onPayment` |
835
+ | `payX402Challenge` | `accountId`, `paymentRequired` | `resource`, `maxAtomicAmount` |
836
+ | `wrapFetchWithMppPayment` | `accountId` | `baseFetch`, `maxAtomicAmount`, `onPayment` |
837
+ | `catena` / `catena.charge` | `client`, `accountId` | `maxAtomicAmount` |
838
+ | `createCatenaAccount` | `accountId` | `network` |
839
+
840
+ `baseFetch` injects a custom transport. `onPayment` runs after Catena completes
841
+ the payment and before the paid retry. If it throws, the payment remains
842
+ complete and the wrapper throws a retry error carrying the receipt.
843
+
844
+ ### Client options
845
+
846
+ | Option | Purpose |
847
+ | ---------------- | --------------------------------------------------------------------------- |
848
+ | `privateKeyHex` | Linked 64-character P-256 private key. |
849
+ | `baseUrl` | API origin. Defaults to the hosted Catena API. |
850
+ | `identityUrl` | Stable signer identity URL. The default follows the key thumbprint. |
851
+ | `appInfo` | `{ name, version?, url? }` added to the User-Agent. |
852
+ | `defaultHeaders` | Headers merged into every request. The SDK strips auth and sets User-Agent. |
853
+ | `fetch` | Custom fetch transport for proxies, instrumentation, or tests. |
854
+ | `timeout` | Per-exchange deadline in milliseconds. Defaults to 80,000. |
855
+
856
+ You can omit `privateKeyHex` and set `CATENA_SECRET_KEY` instead. An explicit
857
+ value always wins, including when it is empty or invalid. The SDK validates the
858
+ key at construction. It never stores credentials or reads CLI profiles.
859
+
860
+ Each operation may make more than one HTTP exchange. Every exchange receives a
861
+ fresh timeout; `timeout` is not an overall operation deadline. It must be a
862
+ positive integer no greater than 2,147,483,647.
863
+
864
+ `identityUrl` must be an HTTP(S) URL of at most 255 printable ASCII characters.
865
+ `appInfo.name` and `version` must be HTTP tokens; its URL must be safe in a
866
+ User-Agent comment.
867
+
868
+ ### Entry points
869
+
870
+ | Import | Public surface |
871
+ | --------------------- | -------------------------------------------------------- |
872
+ | `@catena/sdk` | Client, intent and account types, errors, and constants. |
873
+ | `@catena/sdk/x402` | Managed and low-level x402 payment APIs. |
874
+ | `@catena/sdk/mpp` | Managed MPP wrapper and Catena-backed mppx methods. |
875
+ | `@catena/sdk/viem` | Custodial viem account for x402 typed data. |
876
+ | `@catena/sdk/keypair` | Low-level P-256 credential utilities. |
877
+
878
+ The root entry point also exports request and response types, action unions,
879
+ error classes, and constants for actions, policies, transactions, and send
880
+ methods.
881
+
882
+ <details>
883
+ <summary><strong>Low-level key utilities</strong></summary>
884
+
885
+ Most integrations receive a linked private key through their host flow. The
886
+ keypair entry point is available when the host owns credential creation or
887
+ conversion:
888
+
889
+ | Export | Purpose |
890
+ | ----------------------------------------- | ---------------------------------- |
891
+ | `P256Keypair` | P-256 private and public key data. |
892
+ | `InvalidKeyError` | Invalid key input. |
893
+ | `generateP256Keypair()` | Generate a new P-256 keypair. |
894
+ | `p256KeypairFromPrivateKeyHex(value)` | Derive and validate a keypair. |
895
+ | `computeP256PublicKeyThumbprint(value)` | Compute the public-key thumbprint. |
896
+ | `p256PointFromCompressedHex(value)` | Decode a compressed public key. |
897
+ | `p256PublicKeyThumbprintFromPoint(value)` | Thumbprint a decoded public point. |
898
+
899
+ The SDK never persists a generated private key or links its public half to an
900
+ agent. The host owns both steps.
901
+
902
+ </details>
903
+
904
+ ## Stability
905
+
906
+ The SDK is in initial development. Patch releases within a `0.x` minor are
907
+ intended to remain compatible. A new minor may change the public API. Test the
908
+ upgrade before moving to a new `0.x` minor.
909
+
910
+ ## License
911
+
912
+ [Apache-2.0](./LICENSE)