@catena/sdk 0.1.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,316 +1,595 @@
1
1
  # @catena/sdk
2
2
 
3
- Typed client for the Catena agent API: read accounts, balances, and policy, move
4
- money through policy-checked intents, and pay MPP or x402 HTTP 402 challenges.
5
- Node >= 20; no framework dependencies.
3
+ **Build agents that can move money without bypassing policy or approvals.**
6
4
 
7
- ## Status
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
8
 
9
- The SDK is in initial development. Patch releases within a `0.x` minor are
10
- intended to remain compatible; a new minor may change the public API. Test
11
- upgrades before moving to a new `0.x` minor.
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
12
15
 
13
16
  ```sh
14
17
  npm install @catena/sdk
15
18
  ```
16
19
 
17
- ## Entry points
18
-
19
- - `@catena/sdk` — the client: `createCatenaClient`, intents, accounts,
20
- counterparties, error types.
21
- - `@catena/sdk/keypair` — generate or derive the P-256 credential and compute
22
- its thumbprint.
23
- - `@catena/sdk/mpp` — a managed MPP `fetch` wrapper plus Catena-backed
24
- `evm/charge` and `usdc/charge` methods for custom mppx integrations. Requires
25
- `mppx` and its viem peer dependencies (both optional SDK peer dependencies;
26
- install `mppx@0.9.0` and `viem@^2.54.0`).
27
- - `@catena/sdk/x402` — a `fetch` wrapper that pays x402 402 challenges through
28
- Catena.
29
- - `@catena/sdk/viem` — a viem `Account` backed by a Catena wallet, for x402
30
- client tooling that expects an account or `{ address, signTypedData }`.
31
- Requires `viem` (an optional peer dependency — install it yourself, `^2.21`).
32
-
33
- ## Authentication
34
-
35
- Every request is signed (RFC 9421) with a P-256 private key; there are no API
36
- tokens or sessions. The key must first be linked to a Catena agent by a host app
37
- — for example the Catena CLI or the Catena console. How the key was generated
38
- does not matter to this SDK, only that it is a valid P-256 key whose public half
39
- is linked.
40
-
41
- Pass the key as `privateKeyHex`, or set `CATENA_SECRET_KEY` and omit the option.
42
- An explicit value always wins, including when it is empty or invalid; the SDK
43
- reads the environment only when `privateKeyHex` is `undefined`. The resolved key
44
- is validated and its public half is derived at construction. The SDK never
45
- persists credentials or reads CLI profiles and credential stores.
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:
46
32
 
47
33
  ```ts
48
34
  import { createCatenaClient } from "@catena/sdk"
49
35
 
50
- const client = createCatenaClient({
51
- privateKeyHex: privateKeyFromSecretManager,
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
+ },
52
61
  })
62
+
63
+ console.log(intent.status)
53
64
  ```
54
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
+
55
74
  ```ts
56
- import { generateP256Keypair } from "@catena/sdk/keypair"
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")
57
81
 
58
- const keypair = generateP256Keypair()
59
- // Persist keypair.privateKeyHex yourself; link keypair.publicKeyHex to an
60
- // agent in a host app before the client can authenticate.
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
+ })
61
88
  ```
62
89
 
63
- ## Quickstart
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:
64
100
 
65
101
  ```ts
66
- import { createCatenaClient } from "@catena/sdk"
102
+ for (const { network, available } of balance.balances?.byNetwork ?? []) {
103
+ console.log(network, available.amount)
104
+ }
105
+ ```
67
106
 
68
- // CATENA_SECRET_KEY contains the linked P-256 private key.
69
- const client = createCatenaClient()
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.
70
113
 
71
- const { accounts } = await client.listAccounts()
72
- const { counterparties } = await client.listCounterparties()
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.
73
117
 
74
- await client.submitIntent({
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({
75
136
  action: {
76
137
  type: "create_counterparty",
77
138
  name: "Acme Vendor",
78
139
  email: "billing@acme.test",
79
140
  },
80
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:
81
146
 
82
- // Email-only creation saves a counterparty without sending an email. A completed
83
- // intent returns data.counterparty with status "awaiting_details" and no rails.
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
+ ```
84
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
85
175
  await client.submitIntent({
86
176
  action: {
87
177
  type: "request_counterparty_details",
88
- counterpartyId: counterparties[0].id,
178
+ counterpartyId,
89
179
  methods: { bank: true, wallet: false },
90
180
  },
91
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
+ ```
92
231
 
93
- // The request follows policy and may remain pending for human approval. While
94
- // an invitation is outstanding, another request returns ApiError status 409
95
- // with code "counterparty_payment_request_conflict" and details.invite.
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.
96
235
 
97
- // The rail must match the method: "ach" and "wire" need a bank rail,
98
- // "on-chain" needs a wallet rail. Pass the rail id, not the counterparty id.
99
- const bankRail = counterparties
100
- .flatMap((counterparty) => counterparty.rails)
101
- .find((rail) => rail.type === "bank")!
236
+ </details>
102
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
103
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({
104
272
  action: {
105
273
  type: "send",
106
- counterpartyRailId: bankRail.id,
107
- // Decimal USD string: "12.50" is $12.50. Never cents or atomic units.
108
- amount: "12.50",
109
- method: "ach",
274
+ accountId,
275
+ counterpartyRailId: walletRailIdOnTheOtherChain,
276
+ amount: "250.00",
277
+ method: "on-chain",
278
+ description: "Invoice 1042",
110
279
  },
111
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
+ }
112
291
  ```
113
292
 
114
- For `send`, omit `accountId` when the agent's current effective policy allows
115
- sends from exactly one account. Other readable or transfer accounts do not
116
- count. The server rejects zero send accounts with HTTP 403
117
- (`policy_send_account_unavailable`) and multiple send accounts with HTTP 400
118
- (`policy_send_account_required`). An explicit account always stays explicit; it
119
- is never replaced with another account. Transfers still require `accountId`.
120
-
121
- The result's `accountId` is the resolved source, pinned at creation and returned
122
- by `getIntent` too, including for pending or blocked intents. Approval checks
123
- the pinned account against the current policy; it never chooses a new source.
124
-
125
- Each new accountless operation resolves the current policy. Reusing an explicit
126
- idempotency key keeps the original intent's source, even if the policy now
127
- selects another account or no longer has a unique send account. Changed payment
128
- details or an explicitly different source return HTTP 409. Policy-blocked
129
- attempts are reevaluated against the current policy with the source still
130
- pinned. Use a new key for a new operation. If the outcome of a submission is
131
- unknown, check that intent before submitting again.
132
-
133
- `submitIntent` returns a disposition, not a guarantee of execution — branch on
134
- `intent.status`:
135
-
136
- - `"completed"` — the action succeeded: money moved for send, transfer, and
137
- wallet_send; for MPP and x402 the payment authorization was delivered
138
- (on-chain settlement is verified separately); the counterparty exists for
139
- create_counterparty.
140
- - `"pending"` — parked, typically awaiting a human approval; `reasons` says why,
141
- `expiresAt` says when the approval request lapses.
142
- - `"processing"` — accepted and in progress. Executing intents advance on their
143
- own; poll `getIntent(intent.id)`. An approved MPP or x402 payment instead
144
- rests here until the paid request is re-run — polling never advances it.
145
- - `"blocked"` — declined by policy or denied by an operator; `reasons` explains
146
- why approval was required, not necessarily why it was denied. Terminal.
147
- - `"failed"` — failed, expired, or reversed. Terminal.
148
-
149
- ## Timeouts
150
-
151
- Each HTTP exchange with Catena has an 80,000ms deadline by default. Configure a
152
- different positive integer no greater than 2,147,483,647 at client construction:
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`.
153
317
 
154
318
  ```ts
155
- const client = createCatenaClient({
156
- timeout: 30_000,
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
+ },
157
393
  })
158
394
  ```
159
395
 
160
- The deadline starts when a signed request is dispatched and remains active
161
- through complete response-body parsing. Local signing is outside the deadline.
162
- Operations with more than one HTTP exchange, such as `submitIntent`, receive a
163
- fresh deadline for each exchange. The timeout is not an overall operation
164
- deadline, so a multi-exchange operation may take several timeout periods.
165
-
166
- ## Errors
167
-
168
- - `InvalidKeyError` — construction could not resolve a key from either
169
- `privateKeyHex` or `CATENA_SECRET_KEY`, or the resolved value is not a valid
170
- P-256 private key.
171
- - `ApiError` — any non-OK API response. Branch on `code` (the stable error
172
- code), not on message prose; `status` is the HTTP status.
173
- - `TimeoutError` — an HTTP exchange exceeded the configured deadline.
174
- `timeoutMs` contains that deadline. A create-intent timeout propagates
175
- directly; a submit-stamp timeout is the `cause` of an `IntentSubmitError`
176
- whose `outcome` is `"unknown"`.
177
- - A timeout means the SDK stopped waiting, not that the server did no work.
178
- - Each `submitIntent` invocation generates a fresh UUID when `idempotencyKey`
179
- is omitted. Matching actions alone are not deduplicated.
180
- - To recover an exact submission after a create-intent timeout, choose and
181
- persist an explicit `idempotencyKey` before the first call, then retry the
182
- unchanged action with that key. Reusing it with a different action
183
- returns 409. If the first call omitted the key, do not treat a second call
184
- as its retry: it is a new logical operation.
185
- - If that retry throws an `ApiError` with status `409` and code
186
- `wallet_send_intent_not_executing` or `x402_intent_state_mismatch`, the SDK
187
- cannot reissue the co-signing body and the response carries no intent ID.
188
- Reconcile with the operator before starting a distinct attempt.
189
- - A `TimeoutError` from the x402 wrapper is create-phase only, so no payment
190
- was authorized and re-running cannot double-pay. If the first intent was
191
- already executing, the retry starts a new intent and leaves the first
192
- awaiting expiry. A payment pending or granted approval is instead matched by
193
- its canonical requirements and reused; a lapsed approval may park again.
194
- - `IntentSubmitError` — `submitIntent` failed after the intent was created.
195
- Branch on `outcome`:
196
-
197
- - `"not-submitted"` means no money moved. Recover with a new `submitIntent`
198
- invocation and a new key, typically after fixing the signing credential.
199
- Omit `idempotencyKey` to generate one, or supply a different value. Reusing
200
- the original key finds the stranded intent and can return a 409 rather than
201
- restart signing.
202
- - `"unknown"` means the server may have acted — poll `getIntent(err.intentId)`
203
- to a terminal status and resubmit only after blocked or failed, never
204
- blindly.
205
-
206
- ## Paying x402 challenges
207
-
208
- `wrapFetchWithX402Payment` returns a drop-in `fetch`: when a response is a 402
209
- with a decodable v2 challenge, it pays through Catena (policy checks included)
210
- and retries once with the `PAYMENT-SIGNATURE` header. Everything else passes
211
- through untouched.
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`:
212
483
 
213
484
  ```ts
214
485
  import { createCatenaClient } from "@catena/sdk"
215
486
  import { wrapFetchWithX402Payment } from "@catena/sdk/x402"
216
487
 
217
- const client = createCatenaClient()
218
-
488
+ const client = createCatenaClient({ privateKeyHex })
219
489
  const fetchWithPayment = wrapFetchWithX402Payment(client, {
220
- // Wallet account the payments draw from.
221
490
  accountId: walletAccountId,
222
- // Refuse challenges above this price, in atomic USDC units ("1000000" = $1).
223
491
  maxAtomicAmount: 1_000_000n,
224
492
  })
225
493
 
226
494
  const response = await fetchWithPayment("https://api.example.com/paid-thing")
227
495
  ```
228
496
 
229
- Request bodies must be replayable: pass them via the `init` argument as a
230
- string, `URLSearchParams`, Blob, ArrayBuffer, or typed array — a `Request`
231
- object carrying a body (or any stream) throws `X402PaymentError` instead of
232
- paying.
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.
233
522
 
234
- Payment failures surface as `X402PaymentError` or a subclass documenting its
235
- recovery path; an `ApiError` the loop does not absorb while skipping unpayable
236
- candidates, a create-phase `TimeoutError`, and a `"not-submitted"`
237
- `IntentSubmitError` propagate unchanged. For x402 `TimeoutError` recovery,
238
- follow the `TimeoutError` guidance in Errors above. Two subclasses deserve care:
239
- `X402ApprovalPendingError` means the payment is parked for human approval —
240
- re-run the same request after approval; `X402RetryFailedError` and
241
- `X402SubmitInterruptedError` mean money may have already moved — follow the
242
- recovery steps in the error message instead of paying again.
523
+ </details>
243
524
 
244
- ## Paying MPP challenges
525
+ ### Pay MPP challenges
245
526
 
246
- Install mppx and its compatible viem version alongside the SDK. Catena supports
247
- the `evm/charge` and `usdc/charge` wire pairs for native USDC on Base and Base
248
- Sepolia:
527
+ Install the optional peers with the SDK:
249
528
 
250
529
  ```sh
251
- npm install @catena/sdk mppx@0.9.0 viem@^2.54.0
530
+ npm install @catena/sdk mppx@^0.9.0 viem@^2.54.0
252
531
  ```
253
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
+
254
538
  ```ts
255
539
  import { createCatenaClient } from "@catena/sdk"
256
- import { wrapFetchWithMppPayment } from "@catena/sdk/mpp"
540
+ import {
541
+ MppCounterpartyNotFoundError,
542
+ wrapFetchWithMppPayment,
543
+ } from "@catena/sdk/mpp"
257
544
 
258
- const client = createCatenaClient()
545
+ const client = createCatenaClient({ privateKeyHex })
259
546
  const fetchWithPayment = wrapFetchWithMppPayment(client, {
260
547
  accountId: walletAccountId,
261
- // Refuse a price above 1 USDC before creating an intent.
262
548
  maxAtomicAmount: 1_000_000n,
263
- onPayment: (receipt) => {
264
- recordPayment(receipt)
265
- },
266
549
  })
267
550
 
268
551
  const response = await fetchWithPayment("https://api.example.com/paid-thing")
269
552
  ```
270
553
 
271
- The managed wrapper passes ordinary responses and undecodable 402s through
272
- untouched. For an eligible challenge, mppx parses and orders the candidates,
273
- chooses `Authorization` or `Payment-Authorization`, and attaches the credential.
274
- The wrapper tries at most the first five supported candidates and moves to the
275
- next only when Catena returns `mpp_challenge_not_payable`,
276
- `mpp_network_mismatch`, or `mpp_counterparty_rail_not_found`. It creates at most
277
- one credential and makes exactly one paid retry.
278
-
279
- The payment is bound to the response's final canonical URL. A cross-origin
280
- redirect is rejected before an intent is created. The credential-bearing retry
281
- preserves the caller's redirect mode and delegates redirect handling to the
282
- configured Fetch implementation, consistent with the x402 wrapper. Request
283
- bodies must be replayable: use a string, `URLSearchParams`, Blob, ArrayBuffer,
284
- or typed array in the `init` argument; a body-bearing `Request`,
285
- `ReadableStream`, or raw `FormData` is refused before payment. The wrapper does
286
- not pre-verify an optional request digest—the seller verifies it when accepting
287
- the credential.
288
-
289
- `onPayment` runs once after Catena completes and validates the credential, but
290
- before the paid retry. Its `MppPaymentReceipt` contains the intent ID, validated
291
- method and terms, and canonical resource URL; it never contains the credential.
292
- If the callback, retry, or a second 402 fails, `MppRetryFailedError.receipt`
293
- identifies the completed intent so the caller does not pay twice.
294
-
295
- Recovery errors are explicit: retry the original request after resolving
296
- `MppApprovalPendingError`; treat `MppPaymentDeclinedError` as terminal; fund one
297
- of `MppNetworkMismatchError.requiredNetworks`; and add the rail named by
298
- `MppCounterpartyNotFoundError`. For `MppSubmitInterruptedError`, first reconcile
299
- `intentId` with `client.getIntent(...)`, because submission may have succeeded.
300
- A create-phase `TimeoutError`, non-fallback `ApiError`, and `IntentSubmitError`
301
- with outcome `"not-submitted"` propagate unchanged.
302
-
303
- ### Custom mppx integration
304
-
305
- Use the lower-level Catena methods when the host needs its own candidate policy,
306
- retry count, event hooks, or transport behavior:
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:
307
585
 
308
586
  ```ts
309
587
  import { createCatenaClient } from "@catena/sdk"
310
588
  import { catena } from "@catena/sdk/mpp"
311
589
  import { Mppx } from "mppx/client"
312
590
 
313
- const client = createCatenaClient()
591
+ const client = createCatenaClient({ privateKeyHex })
592
+
314
593
  const mppx = Mppx.create({
315
594
  methods: [
316
595
  catena({
@@ -326,155 +605,307 @@ const mppx = Mppx.create({
326
605
  const response = await mppx.fetch("https://api.example.com/paid-thing")
327
606
  ```
328
607
 
329
- `catena.charge(...)` is an equivalent alias for `catena(...)`. mppx parses and
330
- selects challenges, chooses `Authorization` or `Payment-Authorization`, retries
331
- the request, and runs its response hooks. The Catena method submits the selected
332
- challenge through the normal policy and approval lifecycle, then returns the
333
- serialized credential to mppx.
334
-
335
- By default, `mppx@0.9.0` allows up to three automatic payment attempts per
336
- fetch. If the seller keeps returning payable challenges with fresh IDs, one
337
- fetch can produce multiple payment authorizations that may be redeemed
338
- separately. Each attempt still goes through Catena policy and approval checks;
339
- these checks do not guarantee one payment per fetch.
340
-
341
- Set `maxAtomicAmount` when creating the Catena methods to refuse an individual
342
- challenge above that price before creating an intent. The value uses atomic USDC
343
- units (6 decimals, so `1_000_000n` is 1 USDC). The server's policy limits still
344
- apply. This ceiling is checked separately for every challenge and does not limit
345
- the number of attempts.
346
-
347
- To allow only one automatic payment attempt per fetch, set
348
- `maxPaymentRetries: 1` in `Mppx.create(...)`. This stops automatic negotiation
349
- of fresh challenges after that attempt, but does not prevent duplicate purchases
350
- across separate fetch calls.
351
-
352
- With `mppx@0.9.0`, pass the HTTP method and body in the fetch `init` argument,
353
- not only inside a `Request` object. mppx rebuilds the paid retry from `init`, so
354
- a method or body stored only in `Request` can be lost: a POST may retry as a
355
- bodiless GET, and even a bodiless DELETE may retry as GET. For example:
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 }`:
356
652
 
357
- ```ts
358
- const response = await mppx.fetch("https://api.example.com/paid-thing", {
359
- method: "POST",
360
- headers: { "Content-Type": "application/json" },
361
- body: JSON.stringify({ query: "example" }),
362
- })
653
+ ```sh
654
+ npm install @catena/sdk viem@^2.21
363
655
  ```
364
656
 
365
- The body must also be reusable and byte-stable: every attempt must send the same
366
- bytes, as with the JSON string above. Raw `FormData` can generate a new
367
- multipart boundary each time it is sent, so identical fields can still fail a
368
- seller's request-body digest check. Serialize multipart bodies once, then reuse
369
- the resulting bytes and matching `Content-Type` on every attempt. Do not rely on
370
- `ReadableStream` bodies being replayed: the first send consumes the stream, and
371
- the paid retry can fail after authorization. Buffer the body before the first
372
- request instead; this uses memory and sacrifices streaming uploads.
373
-
374
- The method relays a challenge digest unchanged; it does not read or hash the
375
- HTTP request body. The seller verifies any body binding when it accepts the
376
- credential. Unsupported methods, intents, currencies, networks, and credential
377
- types are rejected before a Catena intent is submitted.
378
-
379
- Additional selection requirements apply: the UTC challenge expiry must end in
380
- `Z`, use no more than 3 fractional-second digits, and leave at least 5 seconds
381
- and no more than 1 hour. The optional credential header must be omitted or be
382
- exactly `Payment-Authorization`. An optional digest must use
383
- `sha-256=:<base64>:` or the mppx 0.9 spelling `sha-256=<base64>`, with a
384
- canonical, padded standard-base64 SHA-256 value. Optional `opaque` data must be
385
- nonempty, unpadded base64url. Addresses must be lowercase or have a valid EIP-55
386
- checksum. Request `description` and `externalId` text must contain valid Unicode
387
- without unpaired surrogates. When `maxAtomicAmount` is configured, the request
388
- amount must not exceed it.
389
-
390
- When Catena declines a challenge during selection, mppx can report
391
- `No method found for challenges` even when it lists `evm.charge` or
392
- `usdc.charge` as available. Check these requirements as well as the supported
393
- payment types when diagnosing that error.
394
-
395
- An intent result that does not yield a usable credential throws
396
- `MppPaymentError`, which exposes `intentId`, `status`, `reasons`, and
397
- `expiresAt`. A pending payment needs human approval. Inspect an in-flight intent
398
- with `client.getIntent(error.intentId)`. After approval, re-run the original
399
- paid request so its fresh challenge can consume the approved grant; polling
400
- reports the status but never advances an approved MPP payment. Blocked and
401
- failed payments include the server's reasons in the thrown error.
402
-
403
- Submission can also throw `IntentSubmitError` from `@catena/sdk`. An `outcome`
404
- of `"unknown"` means the server may already have signed an authorization. Poll
405
- `client.getIntent(error.intentId)` to determine the outcome before making
406
- another payment attempt.
407
-
408
- An HTTP failure (including another 402), network error, or later
409
- `MppPaymentError` does not prove that earlier authorizations were unused. An
410
- `MppPaymentError` describes only its own intent; earlier attempts in the same
411
- fetch may already have produced redeemable credentials. Before retrying the
412
- original request, including after approval, reconcile all payment attempts, not
413
- just the intent named in the last error. Use `client.getIntent(intentId)` for
414
- known intents; for MPP, `completed` means an authorization was produced, not
415
- proof of settlement or delivery of the purchased resource. If earlier outcomes
416
- are unclear, reconcile with the operator and seller before making another
417
- payment attempt. Do not automatically retry an ambiguous payment.
418
-
419
- ## Using the wallet as a viem account
420
-
421
- A Catena wallet is custodial: your credential authenticates requests and
422
- co-signs intents, and the wallet's own key never leaves the custodian. So the
423
- account `@catena/sdk/viem` returns signs exactly one thing — x402 EIP-3009
424
- `TransferWithAuthorization` typed data for USDC on Base or Base Sepolia, routed
425
- through a policy-checked payment intent. That is the payload x402 client
426
- libraries build, which makes the account a drop-in signer for tooling that knows
427
- nothing about Catena:
428
-
429
657
  ```ts
430
658
  import { createCatenaClient } from "@catena/sdk"
431
659
  import { createCatenaAccount } from "@catena/sdk/viem"
432
660
 
433
- const client = createCatenaClient()
661
+ const client = createCatenaClient({ privateKeyHex })
434
662
  const account = await createCatenaAccount(client, {
435
663
  accountId: walletAccountId,
436
- // Must match the network the wallet account is configured for; defaults to
437
- // "base". A testnet wallet needs "base-sepolia" here.
438
664
  network: "base",
439
665
  })
440
-
441
- // Hand `account` to any x402 client that accepts a viem account or
442
- // an { address, signTypedData } signer, e.g.:
443
- // wrapFetchWithPayment(fetch, clientWithScheme(account))
444
666
  ```
445
667
 
446
- The contract, in brief:
447
-
448
- - `signTypedData` accepts only `TransferWithAuthorization` for USDC on Base
449
- (8453) or Base Sepolia (84532). Anything else throws
450
- `UnsupportedTypedDataError` client-side, with a machine-readable `reason` —
451
- nothing is submitted.
452
- - The returned signature is verified to recover to the wallet address for the
453
- exact typed data you passed before it is returned; a mismatch throws
454
- `SignatureVerificationFailedError` instead of surfacing a bad signature. That
455
- check runs after the payment completed, so it belongs to the
456
- money-may-have-moved group below, not to the client-side refusals above.
457
- - `signMessage` and `signTransaction` throw `UnsupportedAccountCapabilityError`;
458
- there is no raw-hash `sign`.
459
- - A payment over a policy approval threshold throws `X402ApprovalPendingError`
460
- (the same class `@catena/sdk/x402` throws). Approve it in the Catena console,
461
- then let the tooling retry — a retry with a fresh nonce still consumes the
462
- approval.
463
- - A policy block or terminal failure throws `X402PaymentDeclinedError` with the
464
- server's reasons; request-level failures (for example a reused nonce)
465
- propagate as `ApiError` with a stable `code`.
466
- - Once the payment may have moved, every failure carries the intent id:
467
- `X402SubmitInterruptedError` (the submission was interrupted after the payment
468
- may have been claimed), `X402PaymentSignatureUnusableError` (it completed
469
- carrying a signature this SDK cannot use), `X402PaymentInFlightError` (still
470
- in flight — note that polling does not advance an approved x402 payment
471
- resting there; it waits for the paid request to be re-run), and
472
- `SignatureVerificationFailedError`. Reconcile with `getIntent(intentId)`
473
- instead of paying again. Note the shape difference: the intent's
474
- `data.paymentCredential.value` is the base64 x402 envelope used as the
475
- `PAYMENT-SIGNATURE` header, whereas `signTypedData` returns the inner hex
476
- signature decoded out of it — passing the envelope to a viem-based signer path
477
- will fail on shape.
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.
478
909
 
479
910
  ## License
480
911