@catena/sdk 0.0.0-bootstrap.0 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright (c) 2025-2026 Catena Labs, Inc.
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md CHANGED
@@ -1,4 +1,481 @@
1
1
  # @catena/sdk
2
2
 
3
- Bootstrap placeholder. Use @catena/sdk@latest once the CI-published release is
4
- available.
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.
6
+
7
+ ## Status
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.
12
+
13
+ ```sh
14
+ npm install @catena/sdk
15
+ ```
16
+
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.
46
+
47
+ ```ts
48
+ import { createCatenaClient } from "@catena/sdk"
49
+
50
+ const client = createCatenaClient({
51
+ privateKeyHex: privateKeyFromSecretManager,
52
+ })
53
+ ```
54
+
55
+ ```ts
56
+ import { generateP256Keypair } from "@catena/sdk/keypair"
57
+
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.
61
+ ```
62
+
63
+ ## Quickstart
64
+
65
+ ```ts
66
+ import { createCatenaClient } from "@catena/sdk"
67
+
68
+ // CATENA_SECRET_KEY contains the linked P-256 private key.
69
+ const client = createCatenaClient()
70
+
71
+ const { accounts } = await client.listAccounts()
72
+ const { counterparties } = await client.listCounterparties()
73
+
74
+ await client.submitIntent({
75
+ action: {
76
+ type: "create_counterparty",
77
+ name: "Acme Vendor",
78
+ email: "billing@acme.test",
79
+ },
80
+ })
81
+
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.
84
+
85
+ await client.submitIntent({
86
+ action: {
87
+ type: "request_counterparty_details",
88
+ counterpartyId: counterparties[0].id,
89
+ methods: { bank: true, wallet: false },
90
+ },
91
+ })
92
+
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.
96
+
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")!
102
+
103
+ const intent = await client.submitIntent({
104
+ action: {
105
+ 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",
110
+ },
111
+ })
112
+ ```
113
+
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:
153
+
154
+ ```ts
155
+ const client = createCatenaClient({
156
+ timeout: 30_000,
157
+ })
158
+ ```
159
+
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.
212
+
213
+ ```ts
214
+ import { createCatenaClient } from "@catena/sdk"
215
+ import { wrapFetchWithX402Payment } from "@catena/sdk/x402"
216
+
217
+ const client = createCatenaClient()
218
+
219
+ const fetchWithPayment = wrapFetchWithX402Payment(client, {
220
+ // Wallet account the payments draw from.
221
+ accountId: walletAccountId,
222
+ // Refuse challenges above this price, in atomic USDC units ("1000000" = $1).
223
+ maxAtomicAmount: 1_000_000n,
224
+ })
225
+
226
+ const response = await fetchWithPayment("https://api.example.com/paid-thing")
227
+ ```
228
+
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.
233
+
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.
243
+
244
+ ## Paying MPP challenges
245
+
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:
249
+
250
+ ```sh
251
+ npm install @catena/sdk mppx@0.9.0 viem@^2.54.0
252
+ ```
253
+
254
+ ```ts
255
+ import { createCatenaClient } from "@catena/sdk"
256
+ import { wrapFetchWithMppPayment } from "@catena/sdk/mpp"
257
+
258
+ const client = createCatenaClient()
259
+ const fetchWithPayment = wrapFetchWithMppPayment(client, {
260
+ accountId: walletAccountId,
261
+ // Refuse a price above 1 USDC before creating an intent.
262
+ maxAtomicAmount: 1_000_000n,
263
+ onPayment: (receipt) => {
264
+ recordPayment(receipt)
265
+ },
266
+ })
267
+
268
+ const response = await fetchWithPayment("https://api.example.com/paid-thing")
269
+ ```
270
+
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:
307
+
308
+ ```ts
309
+ import { createCatenaClient } from "@catena/sdk"
310
+ import { catena } from "@catena/sdk/mpp"
311
+ import { Mppx } from "mppx/client"
312
+
313
+ const client = createCatenaClient()
314
+ const mppx = Mppx.create({
315
+ methods: [
316
+ catena({
317
+ client,
318
+ accountId: walletAccountId,
319
+ maxAtomicAmount: 1_000_000n,
320
+ }),
321
+ ],
322
+ maxPaymentRetries: 1,
323
+ polyfill: false,
324
+ })
325
+
326
+ const response = await mppx.fetch("https://api.example.com/paid-thing")
327
+ ```
328
+
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:
356
+
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
+ })
363
+ ```
364
+
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
+ ```ts
430
+ import { createCatenaClient } from "@catena/sdk"
431
+ import { createCatenaAccount } from "@catena/sdk/viem"
432
+
433
+ const client = createCatenaClient()
434
+ const account = await createCatenaAccount(client, {
435
+ 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
+ network: "base",
439
+ })
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
+ ```
445
+
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.
478
+
479
+ ## License
480
+
481
+ [Apache-2.0](./LICENSE)