@dexterai/x402 5.0.0 → 5.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/README.md
CHANGED
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
<h1 align="center">@dexterai/x402</h1>
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
|
-
<strong>Give your agent a spending limit it
|
|
8
|
+
<strong>Give your agent a spending limit it cannot exceed — without ever giving up your wallet.</strong>
|
|
9
9
|
</p>
|
|
10
10
|
|
|
11
11
|
<p align="center">
|
|
12
|
-
Open a tab, set a cap, and your agent pays as it works,
|
|
12
|
+
Open a tab, set a cap, and your agent pays as it works. No signature per charge, no escrow, no custodian. Your USDC stays in your own wallet the entire time, and the seller is still guaranteed payment.
|
|
13
13
|
</p>
|
|
14
14
|
|
|
15
15
|
<p align="center">
|
|
@@ -25,189 +25,121 @@
|
|
|
25
25
|
|
|
26
26
|
---
|
|
27
27
|
|
|
28
|
-
##
|
|
28
|
+
## The problem
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
An agent that pays for things needs money it can reach without you in the loop for every charge. The two usual ways to give it that each cost you something you shouldn't have to give up.
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
- **Prefund an escrow** and your money leaves your wallet to sit with a custodian before you've bought anything. Your balance is on the table, and you've paid a stranger in advance.
|
|
33
|
+
- **Hand it a spending delegate** and you keep custody — but you can also pull the funds mid-charge, so the seller can be left unpaid. Serious sellers decline it.
|
|
33
34
|
|
|
34
|
-
The
|
|
35
|
+
## The tab
|
|
35
36
|
|
|
36
|
-
|
|
37
|
+
A **tab** keeps both halves. You open one against your own wallet with a single passkey tap and set a cap. Your agent spends against that cap call by call, with no signature on each charge. The money never leaves your wallet — and while the tab is open, the Solana program blocks you from pulling it out from under what the agent has already run up. The seller gets paid when they settle, automatically.
|
|
37
38
|
|
|
38
|
-
|
|
39
|
+
The cap is enforced at consensus by an on-chain program — not by this library, and not by Dexter. The closest familiar shape is an auth-and-capture card hold, except the hold lives on-chain instead of inside a processor, and no one ever takes your money.
|
|
39
40
|
|
|
40
|
-
```
|
|
41
|
-
|
|
41
|
+
```ts
|
|
42
|
+
import { payUrlWithTab } from '@dexterai/x402/tab';
|
|
43
|
+
|
|
44
|
+
const tabs = new Map(); // one open tab per seller, reused across calls
|
|
45
|
+
const { result, tab } = await payUrlWithTab(
|
|
46
|
+
'https://api.example.com/paid/infer',
|
|
47
|
+
{ method: 'GET' },
|
|
48
|
+
{ vault, perUnitCap: '0.01', totalCap: '1.00', tabs },
|
|
49
|
+
);
|
|
50
|
+
// ...the agent keeps calling; every call reuses the same tab, with no new prompt...
|
|
51
|
+
await tab?.close(); // one on-chain settle pays the seller for everything
|
|
42
52
|
```
|
|
43
53
|
|
|
44
|
-
|
|
54
|
+
That's the whole loop: one tap to open, unlimited calls under the cap, one settle to close. The seller's address comes off the wire from the URL's own `402` challenge — never from your code. The `vault` is built once from your passkey-rooted wallet; see [Setup](#setup).
|
|
45
55
|
|
|
46
|
-
|
|
56
|
+
---
|
|
47
57
|
|
|
48
|
-
##
|
|
58
|
+
## Why you can trust it
|
|
49
59
|
|
|
50
|
-
|
|
60
|
+
"Unruggable" has to be earned, so here is what backs it. Every property below is enforced by the on-chain program, not by this SDK and not by Dexter.
|
|
51
61
|
|
|
52
|
-
|
|
53
|
-
|
|
62
|
+
- **Non-custodial.** Your USDC never leaves your wallet. The program holds no funds — it records bindings and gates withdrawals. There is no escrow account and no custodian to fail.
|
|
63
|
+
- **The cap is consensus-enforced.** The limit is checked by the Solana program at consensus, not by this library. Read the program and verify it yourself: [`Hg3wRaydFtJhYrdvYrKECacpJYDsC9Px7yKmpncj2fhc`](https://solscan.io/account/Hg3wRaydFtJhYrdvYrKECacpJYDsC9Px7yKmpncj2fhc) on Solana mainnet.
|
|
64
|
+
- **Only your passkey moves money.** Withdrawals require a WebAuthn assertion verified by Solana's secp256r1 precompile. Neither the SDK nor the facilitator holds a key that can drain your wallet.
|
|
65
|
+
- **The seller is protected, surgically.** As the agent spends, accrued charges crystallize on-chain into a reservation sized to exactly what's been spent — never the whole wallet. The buyer keeps spending or withdrawing the rest of their balance freely, the seller is guaranteed what they're owed, and if a seller ever goes silent the buyer reclaims the abandoned reservation after a fixed grace period. No one's funds can be frozen indefinitely.
|
|
66
|
+
- **Live on mainnet, pre-audit, and we say so.** Tabs settle on Solana mainnet today; an external audit is funded and in flight. The report and any findings publish in the [`dexter-vault`](https://github.com/Dexter-DAO/dexter-vault) program repo. Responsible disclosure: branch@dexter.cash.
|
|
54
67
|
|
|
55
|
-
|
|
56
|
-
connection, // your Solana Connection (any RPC)
|
|
57
|
-
swigAddress, // the vault's Swig state account, from enrollment
|
|
58
|
-
vaultPda, // the vault's gate PDA, from enrollment
|
|
59
|
-
passkeySigner, // signOperation signer — browser: vault's DexterApiBrowserPasskeySigner; server agent: passkeySignerFromP256Keypair(kp)
|
|
60
|
-
feePayer, // lamport fee payer (a Signer)
|
|
61
|
-
});
|
|
62
|
-
```
|
|
68
|
+
The full threat model and trust assumptions live in the program's [`SECURITY.md`](https://github.com/Dexter-DAO/dexter-vault).
|
|
63
69
|
|
|
64
|
-
|
|
70
|
+
---
|
|
65
71
|
|
|
66
|
-
|
|
67
|
-
import { payUrlWithTab } from '@dexterai/x402/tab';
|
|
72
|
+
## Setup
|
|
68
73
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
{ vault, perUnitCap: '0.01', totalCap: '1.00', tabs },
|
|
74
|
-
);
|
|
75
|
-
// ...more payUrlWithTab calls reuse the same tab via `tabs`...
|
|
76
|
-
await tab?.close(); // one on-chain settle for everything the agent spent
|
|
74
|
+
Install the SDK alongside `@dexterai/vault` — it's a peer dependency, so your app and the tab adapter share one vault instance:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
npm install @dexterai/x402 @dexterai/vault
|
|
77
78
|
```
|
|
78
79
|
|
|
79
|
-
|
|
80
|
+
Build a `vault` adapter once, from the wallet addresses you receive when you enroll at [dexter.cash](https://dexter.cash), plus your passkey signer:
|
|
80
81
|
|
|
81
82
|
```ts
|
|
82
|
-
import {
|
|
83
|
+
import { createSolanaVaultAdapter } from '@dexterai/x402/tab/adapters/solana';
|
|
83
84
|
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
|
|
85
|
+
const vault = createSolanaVaultAdapter({
|
|
86
|
+
connection, // your Solana Connection (any RPC)
|
|
87
|
+
swigAddress, // the vault's Swig state account, from enrollment
|
|
88
|
+
vaultPda, // the vault's gate PDA, from enrollment
|
|
89
|
+
passkeySigner, // browser: vault's DexterApiBrowserPasskeySigner · agent: passkeySignerFromP256Keypair(kp)
|
|
90
|
+
feePayer, // lamport fee payer (a Signer)
|
|
91
|
+
});
|
|
89
92
|
```
|
|
90
93
|
|
|
91
|
-
|
|
94
|
+
That `vault` drives [the tab loop above](#the-tab). To inspect a seller's price before you spend, `resolveTabTerms(url)` reads the terms without paying — for consent screens, directories, or an agent that plans ahead.
|
|
95
|
+
|
|
96
|
+
---
|
|
92
97
|
|
|
93
|
-
|
|
98
|
+
## Get paid (sellers)
|
|
94
99
|
|
|
95
|
-
|
|
100
|
+
You get paid for exactly what you serve, and you hold no key. As an agent spends against its tab, charges crystallize on-chain into a reservation against the buyer's wallet; one settle at close pays your address for everything metered. One middleware advertises both a tab and a one-shot price in a single `402`, so tab-native agents and one-shot callers pay at the same rate.
|
|
96
101
|
|
|
97
102
|
```ts
|
|
98
103
|
import { tabOrExactMiddleware, requireTab, openSse } from '@dexterai/x402/tab/seller';
|
|
99
104
|
import type { X402Request } from '@dexterai/x402/server';
|
|
100
105
|
|
|
101
106
|
app.get('/paid/tick',
|
|
102
|
-
tabOrExactMiddleware({ connection, sellerPubkey, network: 'solana:
|
|
107
|
+
tabOrExactMiddleware({ connection, sellerPubkey, network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', perUnit: '0.01' }),
|
|
103
108
|
async (req, res) => {
|
|
104
|
-
if ((req as X402Request).x402) { res.json({ data: '...'
|
|
105
|
-
const
|
|
106
|
-
const meter = openSse(res, { tab, perUnit: '0.01' });
|
|
109
|
+
if ((req as X402Request).x402) { res.json({ data: '...' }); return; } // one-shot caller, already paid
|
|
110
|
+
const meter = openSse(res, { tab: requireTab(req), perUnit: '0.01' }); // tab caller
|
|
107
111
|
await meter.charge(1); // demand a fresh voucher; throws if the cap is exceeded
|
|
108
112
|
meter.send(JSON.stringify({ data: '...' }));
|
|
109
|
-
await meter.end(); //
|
|
113
|
+
await meter.end(); // always await — persists the final delivered amount
|
|
110
114
|
});
|
|
111
115
|
```
|
|
112
116
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
---
|
|
116
|
-
|
|
117
|
-
## How it works
|
|
118
|
-
|
|
119
|
-
Three nouns and one actor.
|
|
120
|
-
|
|
121
|
-
- **Vault:** your money, held in your own wallet and locked by your passkey. The program never takes custody.
|
|
122
|
-
- **Tab:** a capped spending limit you open against your vault, for one agent and one counterparty. The agent draws against it; the vault enforces the cap.
|
|
123
|
-
- **Passkey:** your key. You tap it to set up the vault and to open or approve a tab. Nothing else can authorize a withdrawal.
|
|
124
|
-
- **Your agent:** who you open the tab for.
|
|
125
|
-
|
|
126
|
-
A tab opens with one passkey tap, the agent spends against it with no further prompts, and one on-chain settle pays the seller and closes it. Each charge the agent makes is off-chain, so it costs no gas and no signature. As charges accrue, the seller crystallizes them on-chain into the reservation that guarantees its payment — keyless and automatic, with no action and no signature from you.
|
|
127
|
-
|
|
128
|
-
---
|
|
129
|
-
|
|
130
|
-
## Why you can trust it
|
|
131
|
-
|
|
132
|
-
The word "unruggable" has to be earned, so here is what actually backs it. The properties below are enforced by the on-chain program, not by this SDK.
|
|
133
|
-
|
|
134
|
-
- **Non-custodial.** Your USDC stays in your own wallet. The program holds no funds; it records bindings and gates a withdrawal. There is no escrow account and no custodian to fail.
|
|
135
|
-
- **The cap is enforced on-chain.** The limit is checked by the Solana program at consensus, not by this library and not by Dexter. You can read the program and verify the cap yourself: [`Hg3wRaydFtJhYrdvYrKECacpJYDsC9Px7yKmpncj2fhc`](https://solscan.io/account/Hg3wRaydFtJhYrdvYrKECacpJYDsC9Px7yKmpncj2fhc) on Solana mainnet.
|
|
136
|
-
- **Only your passkey moves funds.** Withdrawals require a WebAuthn assertion verified by Solana's secp256r1 precompile. The SDK and the facilitator never hold a key that can drain your wallet.
|
|
137
|
-
- **The seller is protected, surgically.** As the agent spends, accrued charges crystallize on-chain into a reservation the buyer cannot withdraw out from under. The reservation is exactly the amount accrued — not the whole wallet — so the buyer keeps spending or withdrawing the rest of their balance freely while the tab stays open. The seller is guaranteed the accrued amount; the buyer is never locked out of funds they haven't committed. If a seller ever goes silent, the buyer recovers an abandoned reservation themselves after a fixed grace period; nobody's funds can be frozen indefinitely.
|
|
138
|
-
- **Live on Solana mainnet.** Tabs settle on mainnet today. We can demonstrate the program rejecting a forged passkey from a clone: see the [`dexter-vault`](https://github.com/Dexter-DAO/dexter-vault) program repo.
|
|
139
|
-
- **Pre-audit, and we say so.** Not yet externally audited; funding is in flight. The report and any findings publish in the program repo. Responsible disclosure: branch@dexter.cash.
|
|
140
|
-
|
|
141
|
-
The full threat model and trust assumptions live in the program's [`SECURITY.md`](https://github.com/Dexter-DAO/dexter-vault).
|
|
117
|
+
Want a tab-only endpoint, or to compose the pieces yourself? The full seller surface is in [REFERENCE.md](./REFERENCE.md#sellers).
|
|
142
118
|
|
|
143
119
|
---
|
|
144
120
|
|
|
145
|
-
##
|
|
121
|
+
## Hosted approval (partners)
|
|
146
122
|
|
|
147
123
|
When a partner's app opens a tab for a user, the approval runs on one Dexter-hosted consent screen, deep-linked from the partner's app. The user sees the counterparty, the cap, and the expiry, taps their passkey once, and control returns to the app. The partner builds no approval UI and never handles a passkey.
|
|
148
124
|
|
|
149
|
-
The screen is hosted
|
|
150
|
-
|
|
151
|
-
---
|
|
152
|
-
|
|
153
|
-
## One-shot payments
|
|
154
|
-
|
|
155
|
-
When a charge is a single discrete purchase rather than metered consumption, pay it one-shot. x402 is HTTP's payment protocol: a server returns `402 Payment Required` describing what it wants paid, the client signs and retries, and the resource comes back. USDC on Solana and the major EVM chains, behind one API.
|
|
156
|
-
|
|
157
|
-
```typescript
|
|
158
|
-
import { payAndFetch, createKeypairWallet, createEvmKeypairWallet } from '@dexterai/x402/client';
|
|
159
|
-
|
|
160
|
-
const solana = await createKeypairWallet(process.env.SOLANA_PRIVATE_KEY);
|
|
161
|
-
const evm = await createEvmKeypairWallet(process.env.EVM_PRIVATE_KEY); // requires: npm install viem
|
|
162
|
-
|
|
163
|
-
const result = await payAndFetch(
|
|
164
|
-
'https://api.example.com/protected',
|
|
165
|
-
{ method: 'GET' },
|
|
166
|
-
{ solana, evm },
|
|
167
|
-
{},
|
|
168
|
-
);
|
|
169
|
-
|
|
170
|
-
if (result.ok && result.paid) {
|
|
171
|
-
const data = await result.response.json();
|
|
172
|
-
console.log(`Paid ${result.amountPaid} on ${result.network.bare}, tx ${result.txSignature}`);
|
|
173
|
-
} else if (result.ok && !result.paid) {
|
|
174
|
-
const data = await result.response.json(); // endpoint didn't demand payment; passed through
|
|
175
|
-
} else {
|
|
176
|
-
console.error(result.reason, result.detail);
|
|
177
|
-
}
|
|
178
|
-
```
|
|
179
|
-
|
|
180
|
-
`payAndFetch` handles x402 v1 and v2 transparently and returns a discriminated `PayResult`: `ok` splits into `paid: true | false`, so a free 200 is distinguishable from a paid one, and expected failures don't throw.
|
|
181
|
-
|
|
182
|
-
Protect an endpoint with `x402Middleware`; the handler runs only after payment settles. In React, `useX402Payment` takes wallets from `@solana/wallet-adapter-react` or `wagmi` and returns a `fetch` that pays automatically. Read a settled receipt off any paid response with `getPaymentReceipt(response)`.
|
|
183
|
-
|
|
184
|
-
```typescript
|
|
185
|
-
import { x402Middleware } from '@dexterai/x402/server';
|
|
186
|
-
|
|
187
|
-
app.get('/api/protected',
|
|
188
|
-
x402Middleware({ payTo: 'YourReceivingAddress', amount: '0.01', network: 'eip155:8453' }),
|
|
189
|
-
(req, res) => res.json({ data: 'protected content' }),
|
|
190
|
-
);
|
|
191
|
-
```
|
|
125
|
+
The screen is hosted for a structural reason, not a stylistic one: the vault's passkey can only sign on Dexter's own origin, so a user cannot be phished into approving on a look-alike page. The safety is a property of *where the key signs*. Flow and routing: [docs.dexter.cash](https://docs.dexter.cash).
|
|
192
126
|
|
|
193
127
|
---
|
|
194
128
|
|
|
195
129
|
## Also in this package
|
|
196
130
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
- **Batch settlement (EVM).** Prepay an escrow once, make many discrete paid calls against it with off-chain vouchers, and settle in a handful of transactions to amortize gas. EVM only. `openBatchChannel` / `createBatchSettlementSeller`.
|
|
200
|
-
- **Discovery (bazaar).** Make any `x402Middleware`-protected route discoverable through the official x402 bazaar spec, so agents find it by capability. `bazaarExtension()`.
|
|
201
|
-
- **Sponsored access.** When an agent pays through Dexter's facilitator, a matched recommendation can ride along in the receipt; the agent's model may act on it. `sponsoredAccess: true`.
|
|
202
|
-
- **Auto-listing.** Endpoints paid through the facilitator are auto-discovered, named, and quality-tested, then surfaced in `x402_search` across MCP clients. No registration step.
|
|
131
|
+
Tabs are the headline. The same install carries the rest of the x402 surface — each documented in full in [REFERENCE.md](./REFERENCE.md).
|
|
203
132
|
|
|
204
|
-
|
|
133
|
+
- **One-shot payments** — a single discrete purchase over HTTP `402`, USDC on Solana and the major EVM chains. `payAndFetch` (client), `x402Middleware` (server), `useX402Payment` (React).
|
|
134
|
+
- **Batch settlement (EVM)** — prepay an escrow once, make many paid calls with off-chain vouchers, settle in a handful of transactions to amortize gas. `openBatchChannel`.
|
|
135
|
+
- **Discovery** — make any protected route findable by capability through the x402 bazaar spec. `bazaarExtension()`.
|
|
136
|
+
- **Sponsored access & auto-listing** — endpoints paid through Dexter's facilitator are auto-discovered, named, quality-tested, and surfaced in `x402_search` across MCP clients, with no registration step.
|
|
205
137
|
|
|
206
138
|
---
|
|
207
139
|
|
|
208
140
|
## Supported networks
|
|
209
141
|
|
|
210
|
-
|
|
142
|
+
Tabs are Solana. One-shot and batch settlement span Solana and the major EVM chains; USDC on every chain. Full live list: [Dexter facilitator](https://x402.dexter.cash/supported).
|
|
211
143
|
|
|
212
144
|
| Network | CAIP-2 | Status |
|
|
213
145
|
|---------|--------|--------|
|
|
@@ -220,137 +152,13 @@ All networks supported by the [Dexter facilitator](https://x402.dexter.cash/supp
|
|
|
220
152
|
| BSC | `eip155:56` | Production |
|
|
221
153
|
| SKALE Base | `eip155:1187947933` | Production (zero gas) |
|
|
222
154
|
|
|
223
|
-
Testnets: Solana Devnet/Testnet, Base Sepolia, SKALE Base Sepolia. Multi-chain endpoints accept any chain in the list; the buyer picks. Pass `network` as an array to `x402Middleware`, with a `payTo` map for per-chain receivers.
|
|
224
|
-
|
|
225
155
|
---
|
|
226
156
|
|
|
227
|
-
##
|
|
228
|
-
|
|
229
|
-
### Package exports
|
|
230
|
-
|
|
231
|
-
```typescript
|
|
232
|
-
// Tabs (Solana): buyer
|
|
233
|
-
import { payUrlWithTab, resolveTabTerms, resolveTabOffer } from '@dexterai/x402/tab';
|
|
234
|
-
|
|
235
|
-
// Tabs (Solana): seller
|
|
236
|
-
import { tabChallengeMiddleware, tabMiddleware, tabOrExactMiddleware, requireTab, openSse } from '@dexterai/x402/tab/seller';
|
|
237
|
-
|
|
238
|
-
// One-shot client
|
|
239
|
-
import { payAndFetch, createKeypairWallet, createEvmKeypairWallet, getPaymentReceipt } from '@dexterai/x402/client';
|
|
240
|
-
|
|
241
|
-
// React
|
|
242
|
-
import { useX402Payment } from '@dexterai/x402/react';
|
|
243
|
-
|
|
244
|
-
// Server middleware + discovery
|
|
245
|
-
import { x402Middleware, bazaarExtension, declareDiscoveryExtension, createX402Server } from '@dexterai/x402/server';
|
|
246
|
-
|
|
247
|
-
// Batch settlement
|
|
248
|
-
import { openBatchChannel, resumeBatchChannel } from '@dexterai/x402/batch-settlement';
|
|
249
|
-
import { createBatchSettlementSeller } from '@dexterai/x402/batch-settlement/seller';
|
|
250
|
-
|
|
251
|
-
// Adapters (advanced) + utilities
|
|
252
|
-
import { createSolanaAdapter, createEvmAdapter } from '@dexterai/x402/adapters';
|
|
253
|
-
import { toAtomicUnits, fromAtomicUnits } from '@dexterai/x402/utils';
|
|
254
|
-
```
|
|
255
|
-
|
|
256
|
-
### `payUrlWithTab(url, init, opts) → Promise<{ result, tab }>`
|
|
257
|
-
|
|
258
|
-
Opens (or reuses) a lock-protected tab to the seller discovered from the URL's `402` challenge, and pays. `opts`: `{ vault, perUnitCap, totalCap, tabs }`. Reuse one `tabs` map across calls to keep a single open tab per seller; `tab.close()` settles everything spent in one transaction.
|
|
259
|
-
|
|
260
|
-
### `resolveTabTerms(url) → Promise<TabResolution>`
|
|
261
|
-
|
|
262
|
-
Reads a URL's tab terms without paying. Returns `{ kind: 'terms', terms: { counterparty, perRequest, network, settlement } }`, or a non-terms kind when the URL offers no tab.
|
|
263
|
-
|
|
264
|
-
### `payAndFetch(url, init, wallets, opts) → Promise<PayResult>`
|
|
265
|
-
|
|
266
|
-
| Argument | Type | Description |
|
|
267
|
-
|---|---|---|
|
|
268
|
-
| `url` | `string` | Endpoint to fetch |
|
|
269
|
-
| `init` | `RequestInit` | Standard fetch init. Body must be a string. |
|
|
270
|
-
| `wallets` | `WalletSet` | `{ solana?, evm? }`. The SDK picks the chain by what the merchant accepts and what you can pay |
|
|
271
|
-
| `opts` | `PayAndFetchOptions` | `maxAmountAtomic`, `timeoutMs`, `solanaRpcUrl` |
|
|
272
|
-
|
|
273
|
-
`PayResult` is a discriminated union. Narrow on `ok`, then on `paid`:
|
|
274
|
-
|
|
275
|
-
```typescript
|
|
276
|
-
if (result.ok && result.paid) {
|
|
277
|
-
result.response; result.amountPaid; result.network; result.txSignature;
|
|
278
|
-
} else if (result.ok && !result.paid) {
|
|
279
|
-
result.response; // merchant didn't demand payment; pass-through
|
|
280
|
-
} else {
|
|
281
|
-
result.reason; // 'merchant_rejected' | 'settlement_failed' | 'timeout' | ...
|
|
282
|
-
result.detail;
|
|
283
|
-
}
|
|
284
|
-
```
|
|
285
|
-
|
|
286
|
-
### `x402Middleware(config)`
|
|
287
|
-
|
|
288
|
-
| Option | Type | Required | Description |
|
|
289
|
-
|---|---|---|---|
|
|
290
|
-
| `payTo` | `string \| { 'solana:*'?, 'eip155:*'?, [caip2]? }` | Yes | Receiver address; map for per-chain receivers |
|
|
291
|
-
| `amount` | `string` | Yes | USD amount, e.g., `'0.01'` |
|
|
292
|
-
| `network` | `string \| string[]` | No | CAIP-2 network(s). Default: Solana mainnet |
|
|
293
|
-
| `scheme` | `'exact' \| 'batch-settlement'` | No | `'batch-settlement'` mounts as a batch-settlement seller |
|
|
294
|
-
| `extensions` | `ResourceServerExtension[]` | No | E.g., `[bazaarExtension()]` |
|
|
295
|
-
| `sponsoredAccess` | `boolean \| { inject?, onMatch? }` | No | Instinct ad-network recommendation injection |
|
|
296
|
-
| `facilitatorUrl` | `string` | No | Override facilitator (default: `x402.dexter.cash`) |
|
|
297
|
-
|
|
298
|
-
### Batch settlement
|
|
299
|
-
|
|
300
|
-
```ts
|
|
301
|
-
import { openBatchChannel } from '@dexterai/x402/batch-settlement';
|
|
302
|
-
|
|
303
|
-
const escrow = await openBatchChannel({ wallet: evmWallet, network: 'eip155:8453', deposit: '0.30' });
|
|
304
|
-
await escrow.fetch('https://api.example.com/v1/data');
|
|
305
|
-
console.log(escrow.state); // { deposited: '0.3', spent: '0.16', remaining: '0.14' }
|
|
306
|
-
await escrow.close();
|
|
307
|
-
```
|
|
308
|
-
|
|
309
|
-
State auto-persists and resumes with `resumeBatchChannel({ wallet, network, salt })`. If the seller never settles, reclaim unspent escrow with `forceWithdraw()` then `finalizeWithdraw()`. The seller mounts `createBatchSettlementSeller(config)` as an Express handler; Dexter operates the authorizer, so the seller manages no signing key. Returns a handler with `.stop()`, `.closeAll()`, `.closeChannel(id)`.
|
|
310
|
-
|
|
311
|
-
### Discovery, sponsored access
|
|
312
|
-
|
|
313
|
-
`bazaarExtension()` plus `declareDiscoveryExtension(config)` attach a spec-compliant `extensions.bazaar` block to a route's 402; extensions are opt-in and failure-isolated, so the payment path is never affected. `sponsoredAccess` injects `_x402_sponsored` into responses; read it with `getSponsoredRecommendations(response)`. Campaign creation is x402-gated at `x402ads.io`.
|
|
314
|
-
|
|
315
|
-
### Migrating to 5.0.0 (breaking)
|
|
316
|
-
|
|
317
|
-
Two changes, both about packaging and the passkey signer — the payment path itself is unchanged.
|
|
318
|
-
|
|
319
|
-
1. **`@dexterai/vault` is now a peer dependency** (`>=0.19`), not bundled. The tab adapter and your app share ONE vault instance, so there are no duplicate copies and no `instanceof`/type mismatches across packages. Install it alongside: `npm install @dexterai/x402 @dexterai/vault`.
|
|
320
|
-
2. **The passkey signer contract is `signOperation(operationMessage)`**, replacing the old `sign(challenge)`. The adapter now hands the signer the RAW operation message and the signer hashes it internally (`challenge = sha256(op)`, the on-chain `webauthn.rs` law). If you wrote a custom signer against `sign(challenge)`, rename the method to `signOperation` and delete your pre-hash — pass the message straight through. Vault's `DexterApiBrowserPasskeySigner` (browser) and this package's `passkeySignerFromP256Keypair` (node/agent) already conform.
|
|
321
|
-
|
|
322
|
-
To pin the old surface, stay on `@dexterai/x402@^4`.
|
|
323
|
-
|
|
324
|
-
### Removed in v4.0.0 (migration)
|
|
325
|
-
|
|
326
|
-
The v1-era helpers were removed in `4.0.0`. The payment engine is unchanged — the canonical entrypoints have done their jobs since 3.x:
|
|
327
|
-
|
|
328
|
-
| Removed | Use instead |
|
|
329
|
-
| --- | --- |
|
|
330
|
-
| `createX402Client(...).fetch(url)` | `payAndFetch(url, init, wallets)` (client) |
|
|
331
|
-
| `wrapFetch(fetch, opts)` | `payAndFetch` (client) — or pass your `WalletSet` directly |
|
|
332
|
-
| `x402AccessPass`, `x402BrowserSupport` | `x402Middleware` (server) |
|
|
333
|
-
| `createDynamicPricing`, `formatPricing` | compute the price per request in your handler, pass it to `x402Middleware` |
|
|
334
|
-
| `createTokenPricing`, `countTokens`, `MODEL_REGISTRY` + model getters | gone — these wrapped a hardcoded Jan-2026 OpenAI snapshot that goes stale; price requests with your model provider's live API and pass the amount to `x402Middleware` |
|
|
335
|
-
| `stripePayTo` | a `PayToProvider` map on `x402Middleware` |
|
|
336
|
-
| `useAccessPass` (react) | `useX402Payment` (react) |
|
|
337
|
-
|
|
338
|
-
`payAndFetch` speaks both x402 v1 and v2 and returns a discriminated `PayResult`, so it covers everything the old clients did. **EVM one-shot pay-per-call is unchanged** — `payAndFetch` is the EVM path until Tabs reaches EVM. To pin the old surface, stay on `@dexterai/x402@^3`.
|
|
339
|
-
|
|
340
|
-
---
|
|
341
|
-
|
|
342
|
-
## Development
|
|
343
|
-
|
|
344
|
-
```bash
|
|
345
|
-
npm run build # ESM + CJS
|
|
346
|
-
npm run dev # Watch mode
|
|
347
|
-
npm run typecheck
|
|
348
|
-
npm test # 364 vitest tests
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
## License
|
|
157
|
+
## More
|
|
352
158
|
|
|
353
|
-
|
|
159
|
+
- **[REFERENCE.md](./REFERENCE.md)** — every export, option table, and example: tabs, one-shot, batch settlement, discovery.
|
|
160
|
+
- **Upgrading?** `5.0.0` makes `@dexterai/vault` a peer dependency (`>=0.19`) and unifies the passkey signer on `signOperation`. Migration from v4/v3: [REFERENCE.md](./REFERENCE.md#migration).
|
|
161
|
+
- **License** — MIT, see [LICENSE](./LICENSE).
|
|
354
162
|
|
|
355
163
|
---
|
|
356
164
|
|
package/REFERENCE.md
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
# @dexterai/x402 — Reference
|
|
2
|
+
|
|
3
|
+
The full API surface. For what the SDK *is* and why, start with the [README](./README.md).
|
|
4
|
+
|
|
5
|
+
- [Package exports](#package-exports)
|
|
6
|
+
- [Tabs (buyer)](#tabs-buyer)
|
|
7
|
+
- [Sellers](#sellers)
|
|
8
|
+
- [One-shot payments](#one-shot-payments)
|
|
9
|
+
- [Server middleware](#server-middleware)
|
|
10
|
+
- [Batch settlement (EVM)](#batch-settlement-evm)
|
|
11
|
+
- [Discovery & sponsored access](#discovery--sponsored-access)
|
|
12
|
+
- [Migration](#migration)
|
|
13
|
+
- [Development](#development)
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Package exports
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
// Tabs (Solana): buyer
|
|
21
|
+
import { payUrlWithTab, resolveTabTerms, resolveTabOffer } from '@dexterai/x402/tab';
|
|
22
|
+
import { createSolanaVaultAdapter, passkeySignerFromP256Keypair } from '@dexterai/x402/tab/adapters/solana';
|
|
23
|
+
|
|
24
|
+
// Tabs (Solana): seller
|
|
25
|
+
import { tabChallengeMiddleware, tabMiddleware, tabOrExactMiddleware, requireTab, openSse } from '@dexterai/x402/tab/seller';
|
|
26
|
+
|
|
27
|
+
// One-shot client
|
|
28
|
+
import { payAndFetch, createKeypairWallet, createEvmKeypairWallet, getPaymentReceipt } from '@dexterai/x402/client';
|
|
29
|
+
|
|
30
|
+
// React
|
|
31
|
+
import { useX402Payment } from '@dexterai/x402/react';
|
|
32
|
+
|
|
33
|
+
// Server middleware + discovery
|
|
34
|
+
import { x402Middleware, bazaarExtension, declareDiscoveryExtension, createX402Server } from '@dexterai/x402/server';
|
|
35
|
+
|
|
36
|
+
// Batch settlement
|
|
37
|
+
import { openBatchChannel, resumeBatchChannel } from '@dexterai/x402/batch-settlement';
|
|
38
|
+
import { createBatchSettlementSeller } from '@dexterai/x402/batch-settlement/seller';
|
|
39
|
+
|
|
40
|
+
// Adapters (advanced) + utilities
|
|
41
|
+
import { createSolanaAdapter, createEvmAdapter } from '@dexterai/x402/adapters';
|
|
42
|
+
import { toAtomicUnits, fromAtomicUnits } from '@dexterai/x402/utils';
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
> `@dexterai/vault` is a **peer dependency** (`>=0.19`): install it alongside `@dexterai/x402` so the tab adapter and your app share ONE vault instance. The passkey signer the adapter consumes is vault's canonical `signOperation(operationMessage)` — the same type your app builds, with no bridge shim.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Tabs (buyer)
|
|
50
|
+
|
|
51
|
+
### `payUrlWithTab(url, init, opts) → Promise<{ result, tab }>`
|
|
52
|
+
|
|
53
|
+
Opens (or reuses) a lock-protected tab to the seller discovered from the URL's `402` challenge, and pays. `opts`: `{ vault, perUnitCap, totalCap, tabs }`. Reuse one `tabs` map across calls to keep a single open tab per seller; `tab.close()` settles everything spent in one transaction.
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { payUrlWithTab } from '@dexterai/x402/tab';
|
|
57
|
+
|
|
58
|
+
const tabs = new Map();
|
|
59
|
+
const { result, tab } = await payUrlWithTab(
|
|
60
|
+
'https://api.example.com/paid/infer',
|
|
61
|
+
{ method: 'GET' },
|
|
62
|
+
{ vault, perUnitCap: '0.01', totalCap: '1.00', tabs },
|
|
63
|
+
);
|
|
64
|
+
await tab?.close();
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### `resolveTabTerms(url) → Promise<TabResolution>`
|
|
68
|
+
|
|
69
|
+
Reads a URL's tab terms without paying. Returns `{ kind: 'terms', terms: { counterparty, perRequest, network, settlement } }`, or a non-terms kind when the URL offers no tab.
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { resolveTabTerms } from '@dexterai/x402/tab';
|
|
73
|
+
|
|
74
|
+
const resolved = await resolveTabTerms('https://api.example.com/paid/tick');
|
|
75
|
+
if (resolved.kind === 'terms') {
|
|
76
|
+
console.log(resolved.terms.counterparty, resolved.terms.perRequest.human);
|
|
77
|
+
// settlement: { custody: 'non-custodial', protection: 'lock', settleOn: 'close' }
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### `createSolanaVaultAdapter(options)`
|
|
82
|
+
|
|
83
|
+
Builds the `vault` adapter the buyer calls drive through.
|
|
84
|
+
|
|
85
|
+
| Option | Type | Description |
|
|
86
|
+
|---|---|---|
|
|
87
|
+
| `connection` | `Connection` | Your Solana `Connection` (any RPC) |
|
|
88
|
+
| `swigAddress` | `string` | The vault's Swig state account, from enrollment |
|
|
89
|
+
| `vaultPda` | `string` | The vault's gate PDA, from enrollment |
|
|
90
|
+
| `passkeySigner` | `PasskeySignerWithPublicKey` | A `signOperation(operationMessage)` signer (see below) |
|
|
91
|
+
| `feePayer` | `Signer` | Lamport fee payer |
|
|
92
|
+
|
|
93
|
+
The `passkeySigner` is vault 0.19's canonical shape: `{ credentialId, publicKey, signOperation(operationMessage) }`. The signer hashes the operation message internally (`challenge = sha256(op)`, the on-chain `webauthn.rs` law) and the adapter owns only the precompile assembly.
|
|
94
|
+
|
|
95
|
+
- **Browser:** vault's `DexterApiBrowserPasskeySigner` — drops in with no shim.
|
|
96
|
+
- **CLI / server agent:** `passkeySignerFromP256Keypair(kp)` from `@dexterai/x402/tab/adapters/solana`, wrapping a locally-held P-256 keypair.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Sellers
|
|
101
|
+
|
|
102
|
+
`tabOrExactMiddleware` is the recommended default: one middleware that advertises a tab and a one-shot price in a single 402 challenge, so agents pay by tab and one-shot callers pay exact, at the same price.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { tabOrExactMiddleware, requireTab, openSse } from '@dexterai/x402/tab/seller';
|
|
106
|
+
import type { X402Request } from '@dexterai/x402/server';
|
|
107
|
+
|
|
108
|
+
app.get('/paid/tick',
|
|
109
|
+
tabOrExactMiddleware({ connection, sellerPubkey, network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', perUnit: '0.01' }),
|
|
110
|
+
async (req, res) => {
|
|
111
|
+
if ((req as X402Request).x402) { res.json({ data: '...', paidVia: 'exact' }); return; } // exact rail
|
|
112
|
+
const tab = requireTab(req); // tab rail
|
|
113
|
+
const meter = openSse(res, { tab, perUnit: '0.01' });
|
|
114
|
+
await meter.charge(1); // demand a fresh voucher; throws if the cap is exceeded
|
|
115
|
+
meter.send(JSON.stringify({ data: '...' }));
|
|
116
|
+
await meter.end(); // ALWAYS await — persists the final delivered amount
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
For a tab-only endpoint, compose the two middlewares directly: `tabChallengeMiddleware` (answers voucher-less requests with the standard x402 challenge, so any agent can discover you) before `tabMiddleware` (verifies the per-charge vouchers). Both are exported from `@dexterai/x402/tab/seller`.
|
|
121
|
+
|
|
122
|
+
How the protection works: as the agent spends, accrued charges crystallize on-chain into a reservation against the buyer's wallet — sized to exactly what's accrued, not the whole wallet — so the buyer can't withdraw out from under your charges. One on-chain settle at close pays your `sellerPubkey` for everything metered; you hold no key and sign nothing.
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## One-shot payments
|
|
127
|
+
|
|
128
|
+
When a charge is a single discrete purchase rather than metered consumption, pay it one-shot. x402 is HTTP's payment protocol: a server returns `402 Payment Required` describing what it wants paid, the client signs and retries, and the resource comes back. USDC on Solana and the major EVM chains, behind one API.
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
import { payAndFetch, createKeypairWallet, createEvmKeypairWallet } from '@dexterai/x402/client';
|
|
132
|
+
|
|
133
|
+
const solana = await createKeypairWallet(process.env.SOLANA_PRIVATE_KEY);
|
|
134
|
+
const evm = await createEvmKeypairWallet(process.env.EVM_PRIVATE_KEY); // requires: npm install viem
|
|
135
|
+
|
|
136
|
+
const result = await payAndFetch(
|
|
137
|
+
'https://api.example.com/protected',
|
|
138
|
+
{ method: 'GET' },
|
|
139
|
+
{ solana, evm },
|
|
140
|
+
{},
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
if (result.ok && result.paid) {
|
|
144
|
+
const data = await result.response.json();
|
|
145
|
+
console.log(`Paid ${result.amountPaid} on ${result.network.bare}, tx ${result.txSignature}`);
|
|
146
|
+
} else if (result.ok && !result.paid) {
|
|
147
|
+
const data = await result.response.json(); // endpoint didn't demand payment; passed through
|
|
148
|
+
} else {
|
|
149
|
+
console.error(result.reason, result.detail);
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`payAndFetch` handles x402 v1 and v2 transparently and returns a discriminated `PayResult`: `ok` splits into `paid: true | false`, so a free 200 is distinguishable from a paid one, and expected failures don't throw.
|
|
154
|
+
|
|
155
|
+
### `payAndFetch(url, init, wallets, opts) → Promise<PayResult>`
|
|
156
|
+
|
|
157
|
+
| Argument | Type | Description |
|
|
158
|
+
|---|---|---|
|
|
159
|
+
| `url` | `string` | Endpoint to fetch |
|
|
160
|
+
| `init` | `RequestInit` | Standard fetch init. Body must be a string. |
|
|
161
|
+
| `wallets` | `WalletSet` | `{ solana?, evm? }`. The SDK picks the chain by what the merchant accepts and what you can pay |
|
|
162
|
+
| `opts` | `PayAndFetchOptions` | `maxAmountAtomic`, `timeoutMs`, `solanaRpcUrl` |
|
|
163
|
+
|
|
164
|
+
`PayResult` is a discriminated union. Narrow on `ok`, then on `paid`:
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
if (result.ok && result.paid) {
|
|
168
|
+
result.response; result.amountPaid; result.network; result.txSignature;
|
|
169
|
+
} else if (result.ok && !result.paid) {
|
|
170
|
+
result.response; // merchant didn't demand payment; pass-through
|
|
171
|
+
} else {
|
|
172
|
+
result.reason; // 'merchant_rejected' | 'settlement_failed' | 'timeout' | ...
|
|
173
|
+
result.detail;
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
In React, `useX402Payment` takes wallets from `@solana/wallet-adapter-react` or `wagmi` and returns a `fetch` that pays automatically. Read a settled receipt off any paid response with `getPaymentReceipt(response)`.
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## Server middleware
|
|
182
|
+
|
|
183
|
+
Protect an endpoint with `x402Middleware`; the handler runs only after payment settles.
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
import { x402Middleware } from '@dexterai/x402/server';
|
|
187
|
+
|
|
188
|
+
app.get('/api/protected',
|
|
189
|
+
x402Middleware({ payTo: 'YourReceivingAddress', amount: '0.01', network: 'eip155:8453' }),
|
|
190
|
+
(req, res) => res.json({ data: 'protected content' }),
|
|
191
|
+
);
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### `x402Middleware(config)`
|
|
195
|
+
|
|
196
|
+
| Option | Type | Required | Description |
|
|
197
|
+
|---|---|---|---|
|
|
198
|
+
| `payTo` | `string \| { 'solana:*'?, 'eip155:*'?, [caip2]? }` | Yes | Receiver address; map for per-chain receivers |
|
|
199
|
+
| `amount` | `string` | Yes | USD amount, e.g., `'0.01'` |
|
|
200
|
+
| `network` | `string \| string[]` | No | CAIP-2 network(s). Default: Solana mainnet |
|
|
201
|
+
| `scheme` | `'exact' \| 'batch-settlement'` | No | `'batch-settlement'` mounts as a batch-settlement seller |
|
|
202
|
+
| `extensions` | `ResourceServerExtension[]` | No | E.g., `[bazaarExtension()]` |
|
|
203
|
+
| `sponsoredAccess` | `boolean \| { inject?, onMatch? }` | No | Instinct ad-network recommendation injection |
|
|
204
|
+
| `facilitatorUrl` | `string` | No | Override facilitator (default: `x402.dexter.cash`) |
|
|
205
|
+
|
|
206
|
+
Multi-chain endpoints accept any chain the buyer can pay; pass `network` as an array with a `payTo` map for per-chain receivers. Testnets supported: Solana Devnet/Testnet, Base Sepolia, SKALE Base Sepolia.
|
|
207
|
+
|
|
208
|
+
---
|
|
209
|
+
|
|
210
|
+
## Batch settlement (EVM)
|
|
211
|
+
|
|
212
|
+
Prepay an escrow once, make many discrete paid calls against it with off-chain vouchers, and settle in a handful of transactions to amortize gas. EVM only.
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
import { openBatchChannel } from '@dexterai/x402/batch-settlement';
|
|
216
|
+
|
|
217
|
+
const escrow = await openBatchChannel({ wallet: evmWallet, network: 'eip155:8453', deposit: '0.30' });
|
|
218
|
+
await escrow.fetch('https://api.example.com/v1/data');
|
|
219
|
+
console.log(escrow.state); // { deposited: '0.3', spent: '0.16', remaining: '0.14' }
|
|
220
|
+
await escrow.close();
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
State auto-persists and resumes with `resumeBatchChannel({ wallet, network, salt })`. If the seller never settles, reclaim unspent escrow with `forceWithdraw()` then `finalizeWithdraw()`. The seller mounts `createBatchSettlementSeller(config)` as an Express handler; Dexter operates the authorizer, so the seller manages no signing key. The returned handler exposes `.stop()`, `.closeAll()`, `.closeChannel(id)`.
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## Discovery & sponsored access
|
|
228
|
+
|
|
229
|
+
`bazaarExtension()` plus `declareDiscoveryExtension(config)` attach a spec-compliant `extensions.bazaar` block to a route's 402; extensions are opt-in and failure-isolated, so the payment path is never affected.
|
|
230
|
+
|
|
231
|
+
`sponsoredAccess` injects `_x402_sponsored` into responses; read it with `getSponsoredRecommendations(response)`. When an agent pays through Dexter's facilitator, a matched recommendation can ride along in the receipt and the agent's model may act on it. Campaign creation is x402-gated at `x402ads.io`.
|
|
232
|
+
|
|
233
|
+
Endpoints paid through the facilitator are auto-discovered, named, and quality-tested, then surfaced in `x402_search` across MCP clients — no registration step.
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## Migration
|
|
238
|
+
|
|
239
|
+
### Migrating to 5.0.0 (breaking)
|
|
240
|
+
|
|
241
|
+
Two changes, both about packaging and the passkey signer — the payment path itself is unchanged.
|
|
242
|
+
|
|
243
|
+
1. **`@dexterai/vault` is now a peer dependency** (`>=0.19`), not bundled. The tab adapter and your app share ONE vault instance, so there are no duplicate copies and no `instanceof`/type mismatches across packages. Install it alongside: `npm install @dexterai/x402 @dexterai/vault`.
|
|
244
|
+
2. **The passkey signer contract is `signOperation(operationMessage)`**, replacing the old `sign(challenge)`. The adapter now hands the signer the RAW operation message and the signer hashes it internally (`challenge = sha256(op)`, the on-chain `webauthn.rs` law). If you wrote a custom signer against `sign(challenge)`, rename the method to `signOperation` and delete your pre-hash — pass the message straight through. Vault's `DexterApiBrowserPasskeySigner` (browser) and this package's `passkeySignerFromP256Keypair` (node/agent) already conform.
|
|
245
|
+
|
|
246
|
+
To pin the old surface, stay on `@dexterai/x402@^4`.
|
|
247
|
+
|
|
248
|
+
### Removed in v4.0.0
|
|
249
|
+
|
|
250
|
+
The v1-era helpers were removed in `4.0.0`. The payment engine is unchanged — the canonical entrypoints have done their jobs since 3.x:
|
|
251
|
+
|
|
252
|
+
| Removed | Use instead |
|
|
253
|
+
| --- | --- |
|
|
254
|
+
| `createX402Client(...).fetch(url)` | `payAndFetch(url, init, wallets)` (client) |
|
|
255
|
+
| `wrapFetch(fetch, opts)` | `payAndFetch` (client) — or pass your `WalletSet` directly |
|
|
256
|
+
| `x402AccessPass`, `x402BrowserSupport` | `x402Middleware` (server) |
|
|
257
|
+
| `createDynamicPricing`, `formatPricing` | compute the price per request in your handler, pass it to `x402Middleware` |
|
|
258
|
+
| `createTokenPricing`, `countTokens`, `MODEL_REGISTRY` + model getters | gone — these wrapped a hardcoded Jan-2026 OpenAI snapshot that goes stale; price requests with your model provider's live API and pass the amount to `x402Middleware` |
|
|
259
|
+
| `stripePayTo` | a `PayToProvider` map on `x402Middleware` |
|
|
260
|
+
| `useAccessPass` (react) | `useX402Payment` (react) |
|
|
261
|
+
|
|
262
|
+
`payAndFetch` speaks both x402 v1 and v2 and returns a discriminated `PayResult`, so it covers everything the old clients did. **EVM one-shot pay-per-call is unchanged** — `payAndFetch` is the EVM path until Tabs reaches EVM.
|
|
263
|
+
|
|
264
|
+
---
|
|
265
|
+
|
|
266
|
+
## Development
|
|
267
|
+
|
|
268
|
+
```bash
|
|
269
|
+
npm run build # ESM + CJS
|
|
270
|
+
npm run dev # Watch mode
|
|
271
|
+
npm run typecheck
|
|
272
|
+
npm test # vitest
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
MIT. See [LICENSE](./LICENSE).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var W=Object.create;var P=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var G=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},I=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of L(t))!z.call(e,r)&&r!==n&&P(e,r,{get:()=>t[r],enumerable:!(i=H(t,r))||i.enumerable});return e};var C=(e,t,n)=>(n=e!=null?W(F(e)):{},I(t||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),j=e=>I(P({},"__esModule",{value:!0}),e);var ie={};G(ie,{buildAdapterRegisterInstruction:()=>J,createSolanaVaultAdapter:()=>Z,deriveChannelId:()=>M,passkeySignerFromP256Keypair:()=>_});module.exports=j(ie);var o=require("@solana/web3.js");var y=require("@dexterai/vault/instructions"),b=require("@dexterai/vault/precompile"),m=require("@dexterai/vault/constants");var s=require("@dexterai/vault/messages");var x=C(require("tweetnacl"),1);var B=require("@noble/hashes/sha256");function R(){let e=x.default.sign.keyPair();return{publicKey:e.publicKey,privateKey:e.secretKey}}function D(e,t,n){return{publicKey:e.publicKey,privateKey:e.privateKey,scope:t,registration:n}}function V(e,t,n){if(n.length!==32)throw new Error(`channelIdBytes must be 32 bytes, got ${n.length}`);let i=BigInt(t.cumulativeAmount),r=BigInt(e.scope.maxAmountAtomic);if(i>r)throw new Error(`voucher cumulative ${i} exceeds session cap ${r}`);let a=Math.floor(Date.now()/1e3);if(a>=e.scope.expiresAtUnix)throw new Error(`session expired at ${e.scope.expiresAtUnix}, now ${a}`);let c=(0,s.voucherPayloadMessage)({channelId:n,cumulativeAmount:i,sequenceNumber:t.sequenceNumber}),l=x.default.sign.detached(c,e.privateKey);return{payload:t,sessionPublicKey:e.publicKey,sessionRegistration:e.registration,sessionSignature:l}}function K(e){if(!/^\d+$/.test(e))throw new Error(`atomic amount must be a non-negative integer string, got "${e}"`);return BigInt(e)}function M(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e.nonce,!0);let n=new TextEncoder().encode(e.sellerUrl),i=B.sha256.create();return i.update(e.vaultPda.toBytes()),i.update(n),i.update(t),i.digest()}var u=require("@dexterai/vault/session"),U=require("@noble/hashes/sha256");var T=require("@noble/curves/p256"),g=require("@noble/hashes/sha256"),N="dexter.cash";function q(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function X(e,t=`https://${N}`){let i={type:"webauthn.get",challenge:q(e),origin:t,crossOrigin:!1};return new TextEncoder().encode(JSON.stringify(i))}function Y(e=1){let t=(0,g.sha256)(new TextEncoder().encode(N)),n=new Uint8Array(37);return n.set(t,0),n[32]=5,new DataView(n.buffer).setUint32(33,e,!1),n}function Q(e,t){let n=X(t),i=Y(1),r=new Uint8Array(i.length+32);r.set(i,0),r.set((0,g.sha256)(n),i.length);let a=(0,g.sha256)(r);return{signature:T.p256.sign(a,e.privateKey,{lowS:!0}).toCompactRawBytes(),clientDataJSON:n,authenticatorData:i}}function _(e){return{credentialId:new Uint8Array(0),publicKey:e.publicKey,signOperation:async t=>Q(e,(0,g.sha256)(t))}}function J(e){return(0,y.buildRegisterSessionKeyInstruction)({vaultPda:e.vaultPda,sessionPubkey:e.sessionPubkey,maxAmount:e.maxAmount,maxRevolvingCapacity:e.maxRevolvingCapacity,expiresAt:e.expiresAt,allowedCounterparty:e.allowedCounterparty,nonce:e.nonce,swigAddress:e.swigAddress,vaultUsdcAta:e.vaultUsdcAta,clientDataJSON:e.clientDataJSON,authenticatorData:e.authenticatorData,payer:e.payer,siblingSessionPdas:e.siblingSessionPdas})}var k=class{network="solana:mainnet";swigAddress;vaultPda;connection;vaultPdaKey;passkey;feePayer;confirmOptions;constructor(t){this.connection=t.connection,this.swigAddress=typeof t.swigAddress=="string"?t.swigAddress:t.swigAddress.toBase58(),this.vaultPdaKey=typeof t.vaultPda=="string"?new o.PublicKey(t.vaultPda):t.vaultPda,this.vaultPda=this.vaultPdaKey.toBase58(),this.passkey=t.passkeySigner,this.feePayer=t.feePayer,this.confirmOptions=t.confirmOptions??{commitment:"confirmed"}}async authorizeSession(t){let n=new o.PublicKey(t.allowedCounterparty),i=K(t.revolvingCapacityAtomic??t.maxAmountAtomic),r=R(),a=ee(),c=(0,s.sessionRegisterMessage)({programId:m.DEXTER_VAULT_PROGRAM_ID,vaultPda:this.vaultPdaKey,sessionPubkey:r.publicKey,maxAmount:K(t.maxAmountAtomic),maxRevolvingCapacity:i,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:n,nonce:a}),{signature:l,clientDataJSON:d,authenticatorData:h}=await this.passkey.signOperation(c),S=E(h,(0,U.sha256)(d)),p=(0,b.buildSecp256r1VerifyInstruction)(this.passkey.publicKey,l,S),A=(0,u.sessionPdasOf)(await(0,u.fetchVaultSessionAccounts)(this.connection,this.vaultPdaKey)),w=await(0,u.resolveVaultUsdcAta)(this.connection,new o.PublicKey(this.swigAddress)),v=J({vaultPda:this.vaultPdaKey,swigAddress:new o.PublicKey(this.swigAddress),sessionPubkey:r.publicKey,maxAmount:K(t.maxAmountAtomic),maxRevolvingCapacity:i,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:n,nonce:a,clientDataJSON:d,authenticatorData:h,payer:this.feePayer.publicKey,siblingSessionPdas:A,vaultUsdcAta:w}),f=new o.Transaction().add(p,v);f.feePayer=this.feePayer.publicKey;let{blockhash:O}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);f.recentBlockhash=O,f.sign(this.feePayer);let $=await this.connection.sendRawTransaction(f.serialize(),{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});return await this.connection.confirmTransaction({signature:$,blockhash:O,lastValidBlockHeight:(await this.connection.getLatestBlockhash(this.confirmOptions.commitment)).lastValidBlockHeight},this.confirmOptions.commitment),await(0,u.waitForSession)(this.connection,this.vaultPdaKey,n,{expectedSessionPubkey:r.publicKey,timeoutMs:2e4}),D(r,t,c)}async signWithSession(t,n){let i=await te(n.channelId);return V(t,n,i)}async signOpenTab(t,n){return t.registration}async signCloseTab(t,n,i){let r=(0,s.sessionRevokeMessage)({programId:m.DEXTER_VAULT_PROGRAM_ID,vaultPda:this.vaultPdaKey,sessionPubkey:t.publicKey}),{signature:a,clientDataJSON:c,authenticatorData:l}=await this.passkey.signOperation(r),d=E(l,(0,U.sha256)(c)),h=(0,b.buildSecp256r1VerifyInstruction)(this.passkey.publicKey,a,d),S=(0,y.buildRevokeSessionKeyInstruction)({vaultPda:this.vaultPdaKey,allowedCounterparty:new o.PublicKey(t.scope.allowedCounterparty),clientDataJSON:c,authenticatorData:l}),p=new o.Transaction().add(h,S);p.feePayer=this.feePayer.publicKey;let{blockhash:A,lastValidBlockHeight:w}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);p.recentBlockhash=A,p.sign(this.feePayer);let v=await this.connection.sendRawTransaction(p.serialize(),{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});return await this.connection.confirmTransaction({signature:v,blockhash:A,lastValidBlockHeight:w},this.confirmOptions.commitment),r}};function Z(e){return new k(e)}function E(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function ee(){return Math.floor(Math.random()*4294967295)>>>0}async function te(e){if(/^[0-9a-f]{64}$/i.test(e))return ne(e);let{sha256:t}=await import("@noble/hashes/sha256");return t(new TextEncoder().encode(e))}function ne(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(n*2,2),16);return t}0&&(module.exports={buildAdapterRegisterInstruction,createSolanaVaultAdapter,deriveChannelId,passkeySignerFromP256Keypair});
|
|
@@ -112,6 +112,11 @@ interface AdapterRegisterIxParams {
|
|
|
112
112
|
payer: PublicKey;
|
|
113
113
|
/** V6: existing session PDAs for this vault — the overcommit aggregate gate. */
|
|
114
114
|
siblingSessionPdas: PublicKey[];
|
|
115
|
+
/** The vault swig-wallet's USDC ATA, or `null` for a credit-only vault whose
|
|
116
|
+
* ATA does not exist on-chain (own-USDC counted as 0). Resolve it through
|
|
117
|
+
* `@dexterai/vault`'s `resolveVaultUsdcAta` — the SINGLE source of truth for
|
|
118
|
+
* the derive-and-probe decision. The adapter no longer derives it locally. */
|
|
119
|
+
vaultUsdcAta: PublicKey | null;
|
|
115
120
|
}
|
|
116
121
|
declare function buildAdapterRegisterInstruction(p: AdapterRegisterIxParams): _solana_web3_js.TransactionInstruction;
|
|
117
122
|
/** Factory entry point. */
|
|
@@ -112,6 +112,11 @@ interface AdapterRegisterIxParams {
|
|
|
112
112
|
payer: PublicKey;
|
|
113
113
|
/** V6: existing session PDAs for this vault — the overcommit aggregate gate. */
|
|
114
114
|
siblingSessionPdas: PublicKey[];
|
|
115
|
+
/** The vault swig-wallet's USDC ATA, or `null` for a credit-only vault whose
|
|
116
|
+
* ATA does not exist on-chain (own-USDC counted as 0). Resolve it through
|
|
117
|
+
* `@dexterai/vault`'s `resolveVaultUsdcAta` — the SINGLE source of truth for
|
|
118
|
+
* the derive-and-probe decision. The adapter no longer derives it locally. */
|
|
119
|
+
vaultUsdcAta: PublicKey | null;
|
|
115
120
|
}
|
|
116
121
|
declare function buildAdapterRegisterInstruction(p: AdapterRegisterIxParams): _solana_web3_js.TransactionInstruction;
|
|
117
122
|
/** Factory entry point. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{PublicKey as u,Transaction as
|
|
1
|
+
import{PublicKey as u,Transaction as V}from"@solana/web3.js";import{buildRegisterSessionKeyInstruction as w,buildRevokeSessionKeyInstruction as v,deriveSwigWalletAddress as te}from"@dexterai/vault/instructions";import{buildSecp256r1VerifyInstruction as P}from"@dexterai/vault/precompile";import{DEXTER_VAULT_PROGRAM_ID as b,SECP256R1_PROGRAM_ID as re,INSTRUCTIONS_SYSVAR_ID as se}from"@dexterai/vault/constants";import{sessionRegisterMessage as x,sessionRevokeMessage as U,voucherPayloadMessage as k,buildVoucherMessage as ce}from"@dexterai/vault/messages";import O from"tweetnacl";import{sha256 as N}from"@noble/hashes/sha256";function I(){let e=O.sign.keyPair();return{publicKey:e.publicKey,privateKey:e.secretKey}}function C(e,t,n){return{publicKey:e.publicKey,privateKey:e.privateKey,scope:t,registration:n}}function R(e,t,n){if(n.length!==32)throw new Error(`channelIdBytes must be 32 bytes, got ${n.length}`);let i=BigInt(t.cumulativeAmount),r=BigInt(e.scope.maxAmountAtomic);if(i>r)throw new Error(`voucher cumulative ${i} exceeds session cap ${r}`);let s=Math.floor(Date.now()/1e3);if(s>=e.scope.expiresAtUnix)throw new Error(`session expired at ${e.scope.expiresAtUnix}, now ${s}`);let a=k({channelId:n,cumulativeAmount:i,sequenceNumber:t.sequenceNumber}),o=O.sign.detached(a,e.privateKey);return{payload:t,sessionPublicKey:e.publicKey,sessionRegistration:e.registration,sessionSignature:o}}function g(e){if(!/^\d+$/.test(e))throw new Error(`atomic amount must be a non-negative integer string, got "${e}"`);return BigInt(e)}function _(e){let t=new Uint8Array(8);new DataView(t.buffer).setBigUint64(0,e.nonce,!0);let n=new TextEncoder().encode(e.sellerUrl),i=N.create();return i.update(e.vaultPda.toBytes()),i.update(n),i.update(t),i.digest()}import{fetchVaultSessionAccounts as F,sessionPdasOf as z,waitForSession as G,resolveVaultUsdcAta as j}from"@dexterai/vault/session";import{sha256 as B}from"@noble/hashes/sha256";import{p256 as E}from"@noble/curves/p256";import{sha256 as d}from"@noble/hashes/sha256";var D="dexter.cash";function J(e){return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(e,t=`https://${D}`){let i={type:"webauthn.get",challenge:J(e),origin:t,crossOrigin:!1};return new TextEncoder().encode(JSON.stringify(i))}function W(e=1){let t=d(new TextEncoder().encode(D)),n=new Uint8Array(37);return n.set(t,0),n[32]=5,new DataView(n.buffer).setUint32(33,e,!1),n}function H(e,t){let n=$(t),i=W(1),r=new Uint8Array(i.length+32);r.set(i,0),r.set(d(n),i.length);let s=d(r);return{signature:E.sign(s,e.privateKey,{lowS:!0}).toCompactRawBytes(),clientDataJSON:n,authenticatorData:i}}function L(e){return{credentialId:new Uint8Array(0),publicKey:e.publicKey,signOperation:async t=>H(e,d(t))}}function q(e){return w({vaultPda:e.vaultPda,sessionPubkey:e.sessionPubkey,maxAmount:e.maxAmount,maxRevolvingCapacity:e.maxRevolvingCapacity,expiresAt:e.expiresAt,allowedCounterparty:e.allowedCounterparty,nonce:e.nonce,swigAddress:e.swigAddress,vaultUsdcAta:e.vaultUsdcAta,clientDataJSON:e.clientDataJSON,authenticatorData:e.authenticatorData,payer:e.payer,siblingSessionPdas:e.siblingSessionPdas})}var K=class{network="solana:mainnet";swigAddress;vaultPda;connection;vaultPdaKey;passkey;feePayer;confirmOptions;constructor(t){this.connection=t.connection,this.swigAddress=typeof t.swigAddress=="string"?t.swigAddress:t.swigAddress.toBase58(),this.vaultPdaKey=typeof t.vaultPda=="string"?new u(t.vaultPda):t.vaultPda,this.vaultPda=this.vaultPdaKey.toBase58(),this.passkey=t.passkeySigner,this.feePayer=t.feePayer,this.confirmOptions=t.confirmOptions??{commitment:"confirmed"}}async authorizeSession(t){let n=new u(t.allowedCounterparty),i=g(t.revolvingCapacityAtomic??t.maxAmountAtomic),r=I(),s=X(),a=x({programId:b,vaultPda:this.vaultPdaKey,sessionPubkey:r.publicKey,maxAmount:g(t.maxAmountAtomic),maxRevolvingCapacity:i,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:n,nonce:s}),{signature:o,clientDataJSON:l,authenticatorData:y}=await this.passkey.signOperation(a),h=M(y,B(l)),c=P(this.passkey.publicKey,o,h),p=z(await F(this.connection,this.vaultPdaKey)),A=await j(this.connection,new u(this.swigAddress)),f=q({vaultPda:this.vaultPdaKey,swigAddress:new u(this.swigAddress),sessionPubkey:r.publicKey,maxAmount:g(t.maxAmountAtomic),maxRevolvingCapacity:i,expiresAt:BigInt(t.expiresAtUnix),allowedCounterparty:n,nonce:s,clientDataJSON:l,authenticatorData:y,payer:this.feePayer.publicKey,siblingSessionPdas:p,vaultUsdcAta:A}),m=new V().add(c,f);m.feePayer=this.feePayer.publicKey;let{blockhash:S}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);m.recentBlockhash=S,m.sign(this.feePayer);let T=await this.connection.sendRawTransaction(m.serialize(),{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});return await this.connection.confirmTransaction({signature:T,blockhash:S,lastValidBlockHeight:(await this.connection.getLatestBlockhash(this.confirmOptions.commitment)).lastValidBlockHeight},this.confirmOptions.commitment),await G(this.connection,this.vaultPdaKey,n,{expectedSessionPubkey:r.publicKey,timeoutMs:2e4}),C(r,t,a)}async signWithSession(t,n){let i=await Y(n.channelId);return R(t,n,i)}async signOpenTab(t,n){return t.registration}async signCloseTab(t,n,i){let r=U({programId:b,vaultPda:this.vaultPdaKey,sessionPubkey:t.publicKey}),{signature:s,clientDataJSON:a,authenticatorData:o}=await this.passkey.signOperation(r),l=M(o,B(a)),y=P(this.passkey.publicKey,s,l),h=v({vaultPda:this.vaultPdaKey,allowedCounterparty:new u(t.scope.allowedCounterparty),clientDataJSON:a,authenticatorData:o}),c=new V().add(y,h);c.feePayer=this.feePayer.publicKey;let{blockhash:p,lastValidBlockHeight:A}=await this.connection.getLatestBlockhash(this.confirmOptions.commitment);c.recentBlockhash=p,c.sign(this.feePayer);let f=await this.connection.sendRawTransaction(c.serialize(),{skipPreflight:!1,preflightCommitment:this.confirmOptions.preflightCommitment??this.confirmOptions.commitment});return await this.connection.confirmTransaction({signature:f,blockhash:p,lastValidBlockHeight:A},this.confirmOptions.commitment),r}};function we(e){return new K(e)}function M(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function X(){return Math.floor(Math.random()*4294967295)>>>0}async function Y(e){if(/^[0-9a-f]{64}$/i.test(e))return Q(e);let{sha256:t}=await import("@noble/hashes/sha256");return t(new TextEncoder().encode(e))}function Q(e){let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(n*2,2),16);return t}export{q as buildAdapterRegisterInstruction,we as createSolanaVaultAdapter,_ as deriveChannelId,L as passkeySignerFromP256Keypair};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dexterai/x402",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.1.0",
|
|
4
4
|
"description": "Full-stack x402 SDK - add paid API monetization to any endpoint. Express middleware, React hooks, Access Pass, dynamic pricing. Solana, Base, Polygon, Arbitrum, Optimism, Avalanche, SKALE.",
|
|
5
5
|
"author": "Dexter",
|
|
6
6
|
"license": "MIT",
|
|
@@ -60,6 +60,7 @@
|
|
|
60
60
|
"files": [
|
|
61
61
|
"dist",
|
|
62
62
|
"README.md",
|
|
63
|
+
"REFERENCE.md",
|
|
63
64
|
"LICENSE",
|
|
64
65
|
"assets"
|
|
65
66
|
],
|
|
@@ -88,7 +89,7 @@
|
|
|
88
89
|
"tweetnacl": "^1.0.3"
|
|
89
90
|
},
|
|
90
91
|
"devDependencies": {
|
|
91
|
-
"@dexterai/vault": "^0.
|
|
92
|
+
"@dexterai/vault": "^0.20.0",
|
|
92
93
|
"@types/aws-lambda": "^8.10.161",
|
|
93
94
|
"@types/express": "^5.0.6",
|
|
94
95
|
"@types/node": "^22.10.0",
|
|
@@ -103,7 +104,7 @@
|
|
|
103
104
|
"vitest": "^2.1.8"
|
|
104
105
|
},
|
|
105
106
|
"peerDependencies": {
|
|
106
|
-
"@dexterai/vault": ">=0.
|
|
107
|
+
"@dexterai/vault": ">=0.20.0",
|
|
107
108
|
"@solana/wallet-adapter-base": "^0.9.0",
|
|
108
109
|
"react": "^18.0.0 || ^19.0.0",
|
|
109
110
|
"stripe": "^20.0.0",
|