nirium 0.15.0 → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +159 -37
- package/dist/index.d.ts +27 -0
- package/dist/index.js +78 -15
- package/dist/x402-policy.d.ts +178 -0
- package/dist/x402-policy.js +334 -0
- package/dist/x402-spend-cap.d.ts +65 -0
- package/dist/x402-spend-cap.js +129 -0
- package/dist/x402serve-smoke.test.js +10 -2
- package/package.json +12 -8
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Autonomous treasury and agentic-payments infrastructure for **Nirium Protocol** on Stellar/Soroban.
|
|
4
4
|
|
|
5
|
-
Nirium agents rebalance USDC ↔ CETES (tokenized Mexican T-bills via Etherfuse) 24/7 without human intervention. Built for developers who want to integrate autonomous treasury management, agentic payments
|
|
5
|
+
Nirium agents rebalance USDC ↔ CETES (tokenized Mexican T-bills via Etherfuse) 24/7 without human intervention. Built for developers who want to integrate autonomous treasury management, agentic payments with x402 (in both directions: paying for other APIs with `initX402()` and charging for your own with `x402Serve()`), an experimental MPP Charge client, and real-time market data into their applications.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
@@ -28,7 +28,7 @@ console.log('Agent alive:', alive);
|
|
|
28
28
|
const market = await agent.getMarket();
|
|
29
29
|
console.log('XLM Price:', market.xlmPrice);
|
|
30
30
|
|
|
31
|
-
// Trigger a demo strategy on Nirium's own shared testnet vault
|
|
31
|
+
// Trigger a demo strategy on Nirium's own shared testnet vault - a real,
|
|
32
32
|
// working transaction, not a simulation, but it moves Nirium's testnet
|
|
33
33
|
// funds, not yours. To rebalance YOUR OWN vault, see Treasury Rebalance below.
|
|
34
34
|
const result = await agent.execute('blend-yield', 'USDC', { amount: 5000 });
|
|
@@ -61,7 +61,7 @@ agent.subscribe((signal) => {
|
|
|
61
61
|
| Admin | `configureLLM()` |
|
|
62
62
|
| WebSocket | `subscribe()`, `onLog()`, `disconnect()` |
|
|
63
63
|
| x402 Payments | `initX402()`, `x402Fetch()` |
|
|
64
|
-
| MPP
|
|
64
|
+
| MPP Charge client (experimental, see below) | `initMpp()`, `mppFetch()` |
|
|
65
65
|
|
|
66
66
|
## Authentication
|
|
67
67
|
|
|
@@ -82,7 +82,7 @@ const agent = new Agent({
|
|
|
82
82
|
|
|
83
83
|
## Payment Protocols
|
|
84
84
|
|
|
85
|
-
### x402
|
|
85
|
+
### x402: Pay-Per-Request
|
|
86
86
|
```typescript
|
|
87
87
|
agent.initX402({
|
|
88
88
|
secretKey: 'S...', // Stellar secret key
|
|
@@ -93,19 +93,85 @@ const response = await agent.x402Fetch('https://nirium-agent.fly.dev/api/v1/prem
|
|
|
93
93
|
const data = await response.json();
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
-
|
|
96
|
+
#### Per-payment cap
|
|
97
|
+
|
|
98
|
+
`@x402/core` 2.23.0 and later refuse any payment above a default cap of **$1** per request (a default asset such as USDC), before anything is signed. `x402Fetch()` now says so with an `X402SpendCapError` instead of a generic error:
|
|
99
|
+
|
|
97
100
|
```typescript
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
101
|
+
import { X402SpendCapError } from 'nirium';
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
await agent.x402Fetch(url);
|
|
105
|
+
} catch (e) {
|
|
106
|
+
if (e instanceof X402SpendCapError) {
|
|
107
|
+
console.log(e.formattedAmount, e.cap, e.signerCalled); // '2 USDC' '$1' false
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The error carries `url`, `amount` (atomic units, the cheapest offer when the server lists several), `formattedAmount`, `asset`, `network` and `cap`, and `signerCalled` is always `false`: nothing was signed or sent. The cap is enforced by `@x402/core` and cannot be changed from `initX402()` yet. Other `spendControls` rejections (for example a non-default asset) still surface as the original error.
|
|
113
|
+
|
|
114
|
+
#### Pre-sign policy hook (experimental)
|
|
115
|
+
|
|
116
|
+
Pass `policy` to `initX402()` and every `x402Fetch()` asks your policy before anything is signed. The question is asked after the Stellar authorization is built, so the policy sees exactly what would be signed: amount, destination, asset, nonce, expiration ledger and network, decoded from the bytes.
|
|
117
|
+
|
|
118
|
+
**Experimental, new in 0.16.0.** The shape of `policy` (the context object, the outcomes, the records `onDecision` receives) can still change in a minor release before 1.0.0. Its scope is the agent-side cases that [#96](https://github.com/nirium-protocol/nirium/issues/96) groups as G1 (they come from the harness of @CodeDeityX), and nothing beyond them. What it does not cover is listed in the last paragraph of this section: code in the same process that holds the raw signer (L02 in that discussion), and pending-capacity reservation (L01: concurrent requests that observe the same remaining capacity). Neither is solved.
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
import { X402PolicyError } from 'nirium';
|
|
122
|
+
|
|
123
|
+
agent.initX402({
|
|
124
|
+
signer: walletSigner,
|
|
125
|
+
network: 'stellar:pubnet',
|
|
126
|
+
policy: {
|
|
127
|
+
evaluate: async (ctx) => {
|
|
128
|
+
const ok = BigInt(ctx.authorization.amount) <= myLimit;
|
|
129
|
+
return ok
|
|
130
|
+
? { decision: 'ALLOW', contextHash: ctx.contextHash, policyVersion: 'v7', expiresAt: Date.now() + 2_000 }
|
|
131
|
+
: { decision: 'DENY', reason: 'over limit' };
|
|
132
|
+
},
|
|
133
|
+
// Optional: the policy version in force right now.
|
|
134
|
+
currentVersion: async () => myPolicyStore.version(),
|
|
135
|
+
},
|
|
102
136
|
});
|
|
103
137
|
|
|
104
|
-
|
|
105
|
-
|
|
138
|
+
try {
|
|
139
|
+
await agent.x402Fetch(url);
|
|
140
|
+
} catch (e) {
|
|
141
|
+
if (e instanceof X402PolicyError) console.log(e.outcome); // DENY, WAIT, TIMEOUT, STALE, ...
|
|
142
|
+
}
|
|
106
143
|
```
|
|
107
144
|
|
|
108
|
-
|
|
145
|
+
Only an `ALLOW` that echoes this authorization's `contextHash`, and is still valid, reaches the signer. Everything else signs nothing: `DENY`, `WAIT`, an exception, no answer before the deadline (`timeoutMs`, default 5 s, never more than half the payment's `maxTimeoutSeconds`), a malformed answer, an `ALLOW` past its `expiresAt`, a signer whose address changed while the policy was being asked, or a clock (`now`) that does not return a finite number (`CLOCK_INVALID`). Without `policy`, `x402Fetch()` behaves exactly as before.
|
|
146
|
+
|
|
147
|
+
**Stale ALLOW.** With `currentVersion` set, it is read after the `ALLOW` and right before signing, and the `ALLOW` signs only if its `policyVersion` matches. A rejected, empty or late read signs nothing. This check is **not atomic with signing**: the version can change after it is read, or while the signer runs. It narrows the window to the synchronous step between the read and the signer call; it does not close it. `expiresAt` is checked again after the read.
|
|
148
|
+
|
|
149
|
+
**Receipts (`onDecision`).** A payment whose `ALLOW` is accepted produces an `ALLOWED` record. `ALLOWED` does **not** mean every check has passed: it is a notice, sent before the policy-version read and the final clock and identity checks. What follows it is either a refusal from those checks (`STALE`, `EXPIRED`, `TIMEOUT`, `CLOCK_INVALID`, `SIGNER_CHANGED`, ...) or the signer's result: `SIGNED` (the signer returned a signature) or `SIGNER_ERROR` (it rejected, threw, or returned no `signedAuthEntry`; its own error is rethrown untouched). `SIGNED` therefore means a signature exists. The observer cannot change the outcome. A synchronous throw from it is swallowed. If it returns a promise (or any thenable), that is not awaited, so it cannot delay a payment, and its rejection is swallowed so it never becomes an unhandled rejection. It runs before the final clock and identity checks, so what it changes there is detected.
|
|
150
|
+
|
|
151
|
+
**Rejected before the policy is consulted.** An authorization that is not a single `transfer(from, to, amount)` matching the selected payment requirements (asset, destination, amount, network, no sub-invocations, `from` equal to the signer) is refused without calling `evaluate`. A CAP-71 preimage must be bound to the signer's own address.
|
|
152
|
+
|
|
153
|
+
**Signature check.** The hook only checks that the signer returned a non-empty `signedAuthEntry`; it does not verify the signature itself. That check comes from `@stellar/stellar-sdk`: `authorizeEntry` verifies the signature against sha256 of the preimage before it enters the transaction (verified in 16.3.0, the version this package requires). A signature over different bytes, or by a different key, never reaches the merchant; a test in this package pins that.
|
|
154
|
+
|
|
155
|
+
**What this does not do.** It is a check on the agent side, not account-level enforcement: code in the same process that holds the raw signer can still call it directly (the L02 limit in #96; so can code that replaces its `signAuthEntry`, which is looked up at call time), and nothing on-chain enforces the policy. It does not solve pending-capacity reservation (L01 in #96: concurrent requests that observe the same remaining capacity): two calls evaluated at the same time can each fit a limit that together they exceed, and an aggregate cap has to be held by your policy. Discussed in [#96](https://github.com/nirium-protocol/nirium/issues/96), where @CodeDeityX laid out the agent-side cases this hook is built against.
|
|
156
|
+
|
|
157
|
+
### MPP Charge (experimental)
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
agent.initMpp({ secretKey: 'S...', mode: 'pull' }); // 'pull' (default) or 'push'
|
|
161
|
+
|
|
162
|
+
const response = await agent.mppFetch('https://your-mpp-server.example/resource');
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
`initMpp()` builds an MPP Charge client: the server answers `402` with a challenge, the client signs a USDC transfer on Stellar, and the server verifies and settles it. The network comes from the server's challenge, so `network` in the config is accepted but unused.
|
|
166
|
+
|
|
167
|
+
**Do not use it in production, and do not point it at Nirium's hosted endpoints yet.**
|
|
168
|
+
|
|
169
|
+
- The client works against a compliant MPP Charge server. We checked it against Nirium's own MPP middleware running locally against testnet, in `pull` and in `push` mode.
|
|
170
|
+
- When we tested on 1 October 2026, Nirium's hosted **testnet** endpoint (`/api/v1/mpp/*`) rejected MPP payments with `402 Verification Failed`, in `pull` and in `push` mode. We have **not tested the mainnet endpoint** (it would spend real USDC), so we cannot tell you it works there. We have not found the cause yet.
|
|
171
|
+
- In `push` mode the payment settles on-chain before the server verifies it, so a request the server rejects is **not refunded**.
|
|
172
|
+
- Until this is diagnosed, use x402 (`initX402()`) for paid endpoints. The `get_mpp_*` tools of the MCP server have the same limitation.
|
|
173
|
+
|
|
174
|
+
### x402Serve(): Charging Your Own API
|
|
109
175
|
|
|
110
176
|
`initX402()` above lets you *pay* for someone else's API. This is the other side: charging for yours.
|
|
111
177
|
|
|
@@ -113,19 +179,77 @@ const data = await response.json();
|
|
|
113
179
|
import { x402Serve } from 'nirium';
|
|
114
180
|
|
|
115
181
|
app.use('/premium', x402Serve({
|
|
116
|
-
payTo: 'G...', // your Stellar address
|
|
182
|
+
payTo: 'G...', // your Stellar address - where payments land
|
|
117
183
|
routes: { 'GET /signals': '$0.02' },
|
|
118
184
|
facilitatorApiKey: '...', // required on mainnet; OpenZeppelin Channels by default
|
|
119
185
|
}));
|
|
120
186
|
```
|
|
121
187
|
|
|
122
|
-
Runs on **your own server**, not Nirium's
|
|
188
|
+
Runs on **your own server**, not Nirium's - `x402Serve()` is a client-side function you call from your own code; Nirium doesn't operate, host, or route through anything here, is never in the payment path, and never sees your end users' requests.
|
|
189
|
+
|
|
190
|
+
**Known limitation:** by default `x402Serve()` does not protect against replay and does not rate-limit callers. It is turned on by passing `guard` (see below).
|
|
191
|
+
|
|
192
|
+
#### Replay and rate-limit guard (optional)
|
|
193
|
+
|
|
194
|
+
Without `guard`, `x402Serve()` verifies and settles the payment and does nothing else. It does not stop the same signed payment from being sent twice, and it does not limit how often one caller can hit a route. Pass `guard` to get both:
|
|
195
|
+
|
|
196
|
+
- **Replay guard:** each payment proof can be used once per method and route (`replayTtlMs`, 15 minutes by default). A second use gets `409 payment_replayed`. If the request does not end in a 2xx, the claim is released, so a normal retry still works. If the store is down, the replay check refuses the request (`503`) instead of letting it through.
|
|
197
|
+
- **Rate limit:** optional, per caller IP (`req.ip`; set Express `trust proxy` if you run behind a proxy). Past `max` requests in `windowMs` the caller gets `429 rate_limited` with a `Retry-After` header. If the store is down, rate limiting lets traffic through.
|
|
198
|
+
|
|
199
|
+
The guard needs a store with three methods (`X402GuardStore`: `claimOnce`, `release`, `slidingWindowHit`). Two options:
|
|
200
|
+
|
|
201
|
+
```typescript
|
|
202
|
+
import { x402Serve, createUpstashX402GuardStore, type X402GuardStore } from 'nirium';
|
|
203
|
+
|
|
204
|
+
// Option 1: Upstash (Redis over REST). Shared between several servers.
|
|
205
|
+
const store = createUpstashX402GuardStore({
|
|
206
|
+
url: process.env.UPSTASH_REDIS_REST_URL!,
|
|
207
|
+
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// Option 2: your own store. This one lives in memory, so it only works for a
|
|
211
|
+
// single process. For more than one server, back the same three methods with a shared store.
|
|
212
|
+
function createMemoryGuardStore(): X402GuardStore {
|
|
213
|
+
const claims = new Map<string, number>(); // key -> expires at
|
|
214
|
+
const hits = new Map<string, { t: number; member: string }[]>();
|
|
215
|
+
return {
|
|
216
|
+
async claimOnce(key, ttlMs) {
|
|
217
|
+
const now = Date.now();
|
|
218
|
+
if ((claims.get(key) ?? 0) > now) return false;
|
|
219
|
+
claims.set(key, now + ttlMs);
|
|
220
|
+
return true;
|
|
221
|
+
},
|
|
222
|
+
async release(key) { claims.delete(key); },
|
|
223
|
+
async slidingWindowHit(key, windowMs, member) {
|
|
224
|
+
const now = Date.now();
|
|
225
|
+
const list = (hits.get(key) ?? []).filter((h) => h.t > now - windowMs);
|
|
226
|
+
list.push({ t: now, member });
|
|
227
|
+
hits.set(key, list);
|
|
228
|
+
return list.length;
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
app.use('/premium', x402Serve({
|
|
234
|
+
payTo: 'G...',
|
|
235
|
+
routes: { 'GET /signals': '$0.02' },
|
|
236
|
+
facilitatorApiKey: '...',
|
|
237
|
+
guard: {
|
|
238
|
+
store, // or createMemoryGuardStore()
|
|
239
|
+
rateLimit: { max: 60, windowMs: 60_000 }, // optional
|
|
240
|
+
},
|
|
241
|
+
}));
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
No in-memory store ships with the package, and you do not need Upstash: any store that implements the three methods works. The design comes from a real production integration by Edgadafi ([Edgadafi/remesa-liquidez](https://github.com/Edgadafi/remesa-liquidez)); see [issue #91](https://github.com/nirium-protocol/nirium/issues/91). The code here is ours. Thanks, Edgadafi.
|
|
245
|
+
|
|
246
|
+
**Usage telemetry - opt-in, off by default:** set `NIRIUM_X402SERVE_TELEMETRY=true` to send a small, non-blocking usage ping to Nirium - your `payTo` address, a SHA-256 hash of your `facilitatorApiKey` (never the key itself), network, route/request counts, and this SDK's version. It never blocks, delays, or fails a payment if the ping fails, times out, or isn't sent at all. Disabled by default since v0.14.0 - it's the only channel that would otherwise connect Nirium to how a specific integrator is using this locally-run function, and that isn't a decision this package should make for you.
|
|
123
247
|
|
|
124
|
-
**
|
|
248
|
+
**Compliance is yours.** `x402Serve()` is a general-purpose library, not a service Nirium provides to your end users. You choose what to charge for, who your `payTo` is, and which jurisdiction you operate in - you remain solely responsible for complying with the financial, tax, and consumer-protection laws that apply to your own use of it.
|
|
125
249
|
|
|
126
|
-
|
|
250
|
+
### Resilient WebSocket client
|
|
127
251
|
|
|
128
|
-
|
|
252
|
+
`ResilientSignalClient` is a WebSocket client for `/ws/signals` that reconnects by itself with backoff, pings to detect dead connections, and drops duplicate signals. Create it with `{ url, token }`, call `connect()`, and listen with `onSignal()`, `onStatus()` and `onError()`; `close()` stops it.
|
|
129
253
|
|
|
130
254
|
### Endpoint Access Model
|
|
131
255
|
|
|
@@ -133,13 +257,13 @@ Runs on **your own server**, not Nirium's — `x402Serve()` is a client-side fun
|
|
|
133
257
|
|---|---|
|
|
134
258
|
| **Public** (no key) | `health`, `loop/status`, `execute-demo`, `signals/recent`, `skills` list |
|
|
135
259
|
| **Protected** (API key) | `execute`, `market`, `loop/start\|stop\|scan`, `subscriptions`, `skills/install`, `webhooks` |
|
|
136
|
-
| **WebSocket** (JWT) | `/ws/signals`
|
|
137
|
-
| **x402 Premium** | `/api/v1/premium/signals` ($0.02 USDC), `/api/v1/premium/market` ($0.05 USDC) |
|
|
138
|
-
| **MPP** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` |
|
|
260
|
+
| **WebSocket** (JWT) | `/ws/signals` - real-time signal stream |
|
|
261
|
+
| **x402 Premium** | `/api/v1/premium/signals` ($0.02 USDC), `/api/v1/premium/market` ($0.05 USDC). `/premium/signals` only exists on testnet: on mainnet it answers `501` (no signal source there) and does not charge. `/premium/market` is paid on both networks. |
|
|
262
|
+
| **MPP Charge** | `/api/v1/mpp/signals`, `/api/v1/mpp/market` (testnet endpoint rejected MPP payments when tested, mainnet untested, see [MPP Charge](#mpp-charge-experimental)) |
|
|
139
263
|
|
|
140
|
-
### x402 Metrics
|
|
264
|
+
### x402 Metrics: Observability Wrapper
|
|
141
265
|
|
|
142
|
-
Wrap your `x402Serve` handler with `x402Metrics` to get Prometheus-format counters, histograms, and revenue tracking
|
|
266
|
+
Wrap your `x402Serve` handler with `x402Metrics` to get Prometheus-format counters, histograms, and revenue tracking - no changes to your payment logic.
|
|
143
267
|
|
|
144
268
|
```typescript
|
|
145
269
|
import express from 'express';
|
|
@@ -207,7 +331,7 @@ x402_settlement_latency_seconds_sum{route="GET /signals"} 3.42
|
|
|
207
331
|
x402_settlement_latency_seconds_count{route="GET /signals"} 8
|
|
208
332
|
```
|
|
209
333
|
|
|
210
|
-
No payer addresses or PII are included in metrics output
|
|
334
|
+
No payer addresses or PII are included in metrics output - aggregates only.
|
|
211
335
|
|
|
212
336
|
## Payouts
|
|
213
337
|
|
|
@@ -216,7 +340,7 @@ Batch disbursement, non-custodial: the node builds an **unsigned** transaction,
|
|
|
216
340
|
```typescript
|
|
217
341
|
const run = await agent.createPayoutRun({
|
|
218
342
|
recipients: [{ wallet: 'GABC...', amount: '250.00' }],
|
|
219
|
-
acknowledgeTerms: true, // required on every network
|
|
343
|
+
acknowledgeTerms: true, // required on every network - 403 without it
|
|
220
344
|
});
|
|
221
345
|
|
|
222
346
|
const signedXdr = await signWithYourWallet(run.xdr);
|
|
@@ -224,23 +348,23 @@ const settled = await agent.submitPayout(run.runId, signedXdr);
|
|
|
224
348
|
console.log(settled.txHash, settled.cid); // on-chain hash + IPFS receipt
|
|
225
349
|
```
|
|
226
350
|
|
|
227
|
-
Licensed for **independent service payments only**
|
|
351
|
+
Licensed for **independent service payments only** - contractors, freelancers, B2B. Not for subordinate-employee salary. Read `getPayoutTerms()` before integrating; classifying recipients and meeting tax and labor obligations is the client's responsibility.
|
|
228
352
|
|
|
229
353
|
Mainnet is invite-only during early access and additionally requires `clientInfo`.
|
|
230
354
|
|
|
231
355
|
## Treasury Rebalance
|
|
232
356
|
|
|
233
|
-
Two ways to rebalance a DeFindex vault between idle cash and an invested strategy. Neither is a swap
|
|
357
|
+
Two ways to rebalance a DeFindex vault between idle cash and an invested strategy. Neither is a swap - the contract's `rebalance()` exposes exactly two instructions, `Unwind` and `Invest`, and neither accepts a destination address, so withdrawing anywhere but back into the vault itself is not expressible.
|
|
234
358
|
|
|
235
|
-
### Propose
|
|
359
|
+
### Propose: you review and sign, available to everyone today
|
|
236
360
|
|
|
237
|
-
The agent decides what it would do, using the same decision logic as the autonomous signer below, but it never signs. Public, no allowlist, no invite required
|
|
361
|
+
The agent decides what it would do, using the same decision logic as the autonomous signer below, but it never signs. Public, no allowlist, no invite required - works for any vault where you're already the on-chain rebalance manager.
|
|
238
362
|
|
|
239
363
|
```typescript
|
|
240
364
|
const proposal = await agent.proposeTreasuryRebalance({
|
|
241
365
|
vault: 'CABC...',
|
|
242
366
|
caller: 'GABC...', // must already be this vault's rebalanceManager on-chain
|
|
243
|
-
enterAt: 2.5, // your own mandate
|
|
367
|
+
enterAt: 2.5, // your own mandate - Nirium never supplies a default here
|
|
244
368
|
exitAt: 2.0,
|
|
245
369
|
});
|
|
246
370
|
|
|
@@ -252,13 +376,13 @@ if (proposal.instructions.length) {
|
|
|
252
376
|
}
|
|
253
377
|
```
|
|
254
378
|
|
|
255
|
-
### Autonomous
|
|
379
|
+
### Autonomous: Nirium signs, invite-only during legal review
|
|
256
380
|
|
|
257
|
-
`executeTreasuryRebalance()` has Nirium sign and submit with its own RebalanceManager key
|
|
381
|
+
`executeTreasuryRebalance()` has Nirium sign and submit with its own RebalanceManager key - full autonomy, no per-cycle approval. **This is invite-only while a specific legal question stays open**: whether executing on a client's behalf without taking custody still counts as regulated facilitation under Mexican law. It only runs against vaults explicitly allowlisted server-side; calling it against any other vault returns 403, and Nirium's mainnet infrastructure returns 501 for it entirely, since that box holds no signing key by design. Ask if you want autonomous execution today - otherwise, `proposeTreasuryRebalance()` above gives you the same decision-making with you as the one who signs.
|
|
258
382
|
|
|
259
383
|
## Audit Trail
|
|
260
384
|
|
|
261
|
-
Anchor evidence to IPFS and get back a CID
|
|
385
|
+
Anchor evidence to IPFS and get back a CID - an integrity seal, not notarization.
|
|
262
386
|
|
|
263
387
|
```typescript
|
|
264
388
|
const anchor = await agent.anchorAuditRecord({
|
|
@@ -272,17 +396,15 @@ Anchor a **hash** rather than the data itself: IPFS content cannot be deleted, s
|
|
|
272
396
|
|
|
273
397
|
## Requirements
|
|
274
398
|
|
|
275
|
-
- Node.js >=
|
|
399
|
+
- Node.js >= 22.12.0. `@stellar/stellar-sdk` 16 and `@x402/stellar` 2.28 declare `>=22.0.0`, but stellar-sdk 16 depends on `@noble/hashes` 2.x, which is ESM-only, and this package is published as CommonJS: `require('nirium')` only works without a flag from Node 22.12.0 (on 22.11 it throws `ERR_REQUIRE_ESM`)
|
|
276
400
|
- TypeScript >= 5.0
|
|
277
401
|
|
|
278
402
|
## Links
|
|
279
403
|
|
|
280
404
|
- [Documentation](https://nirium.xyz/docs)
|
|
281
405
|
- [Developer Sandbox](https://nirium.xyz/sandbox)
|
|
282
|
-
- [
|
|
283
|
-
- [MCP Server Integration](https://nirium.xyz/docs/mcp)
|
|
284
|
-
- [GitHub](https://github.com/nirium-protocol/nirium-sdk)
|
|
406
|
+
- [GitHub](https://github.com/nirium-protocol/nirium)
|
|
285
407
|
|
|
286
408
|
## License
|
|
287
409
|
|
|
288
|
-
Apache 2.0
|
|
410
|
+
Apache 2.0 - Nirium Protocol
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type X402GuardConfig } from './x402-guard';
|
|
2
|
+
import { type X402PolicyHook } from './x402-policy';
|
|
2
3
|
export interface AgentConfig {
|
|
3
4
|
apiKey: string;
|
|
4
5
|
baseUrl?: string;
|
|
@@ -10,6 +11,10 @@ export interface AgentConfig {
|
|
|
10
11
|
* SEP-43 signer. Only `address` and `signAuthEntry` are required — that is all
|
|
11
12
|
* x402 needs, and it is what browser wallets expose (Freighter, Stellar Wallets
|
|
12
13
|
* Kit, Pollar). Lets the SDK pay from a browser without ever holding a secret.
|
|
14
|
+
*
|
|
15
|
+
* Note: what `signAuthEntry` receives is the base64 `HashIdPreimage` of the
|
|
16
|
+
* Soroban authorization (the bytes whose sha256 gets signed), not the
|
|
17
|
+
* `SorobanAuthorizationEntry` itself.
|
|
13
18
|
* @see https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0043.md
|
|
14
19
|
*/
|
|
15
20
|
export interface X402Signer {
|
|
@@ -39,6 +44,13 @@ export interface X402Config {
|
|
|
39
44
|
network?: string;
|
|
40
45
|
/** Soroban RPC endpoint override (defaults per network) */
|
|
41
46
|
rpcUrl?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Pre-sign policy hook (#96). Runs after the Stellar authorization is
|
|
49
|
+
* built and before anything is signed; only an ALLOW bound to that exact
|
|
50
|
+
* authorization, and still valid, reaches the signer. Without it,
|
|
51
|
+
* x402Fetch behaves exactly as before. See X402PolicyHook.
|
|
52
|
+
*/
|
|
53
|
+
policy?: X402PolicyHook;
|
|
42
54
|
}
|
|
43
55
|
export interface MppConfig {
|
|
44
56
|
/**
|
|
@@ -542,6 +554,7 @@ export declare class Agent {
|
|
|
542
554
|
private logCallbacks;
|
|
543
555
|
private token;
|
|
544
556
|
private x402Client;
|
|
557
|
+
private x402Policy;
|
|
545
558
|
private mppClient;
|
|
546
559
|
constructor(config: AgentConfig);
|
|
547
560
|
private request;
|
|
@@ -840,11 +853,22 @@ export declare class Agent {
|
|
|
840
853
|
* Fetch a paid resource via x402 protocol.
|
|
841
854
|
* The client automatically handles 402 negotiation, auth-entry signing, and payment.
|
|
842
855
|
* Returns the Response object — call .json() or .text() for the payload.
|
|
856
|
+
*
|
|
857
|
+
* Throws `X402SpendCapError` when @x402/core refuses a payment for being above
|
|
858
|
+
* its per-payment cap (before anything is signed), and `X402PolicyError` when
|
|
859
|
+
* a `policy` refuses it.
|
|
843
860
|
*/
|
|
844
861
|
x402Fetch(url: string, init?: RequestInit): Promise<Response>;
|
|
862
|
+
private x402FetchWithPolicy;
|
|
845
863
|
/**
|
|
846
864
|
* Initialize the MPP Charge client for per-request Soroban SAC payments.
|
|
847
865
|
* Uses canonical @stellar/mpp charge mode with mppx.
|
|
866
|
+
*
|
|
867
|
+
* EXPERIMENTAL. The client works against a compliant MPP Charge server, but
|
|
868
|
+
* Nirium's hosted testnet `/api/v1/mpp/*` endpoint rejected MPP payments when
|
|
869
|
+
* tested on 2026-10-01 (`402 Verification Failed`), and in `push` mode the
|
|
870
|
+
* payment has already settled on-chain when that happens. The mainnet
|
|
871
|
+
* endpoint was not tested. Use `initX402()` for paid endpoints. See the README.
|
|
848
872
|
* In pull mode, the server assembles and broadcasts the transaction.
|
|
849
873
|
*
|
|
850
874
|
* @example
|
|
@@ -889,6 +913,9 @@ export interface X402ServeConfig {
|
|
|
889
913
|
guard?: X402GuardConfig;
|
|
890
914
|
}
|
|
891
915
|
export declare function x402Serve(config: X402ServeConfig): any;
|
|
916
|
+
export { X402PolicyError } from './x402-policy';
|
|
917
|
+
export { X402SpendCapError } from './x402-spend-cap';
|
|
918
|
+
export type { X402PolicyHook, X402PolicyContext, X402PolicyDecision, X402PolicyVerdict, X402PolicyOutcome, X402PolicyRecord, X402PaymentRequirementsView, } from './x402-policy';
|
|
892
919
|
export { x402Metrics } from './metrics';
|
|
893
920
|
export type { X402MetricsResult, MetricsSnapshot } from './metrics';
|
|
894
921
|
export type { X402GuardStore, X402GuardConfig, GuardRequest, GuardDenied } from './x402-guard';
|
package/dist/index.js
CHANGED
|
@@ -41,7 +41,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
41
41
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
42
42
|
};
|
|
43
43
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
44
|
-
exports.ResilientSignalClient = exports.createUpstashX402GuardStore = exports.x402Metrics = exports.Agent = void 0;
|
|
44
|
+
exports.ResilientSignalClient = exports.createUpstashX402GuardStore = exports.x402Metrics = exports.X402SpendCapError = exports.X402PolicyError = exports.Agent = void 0;
|
|
45
45
|
exports.x402Serve = x402Serve;
|
|
46
46
|
const ws_1 = __importDefault(require("ws"));
|
|
47
47
|
const node_crypto_1 = require("node:crypto");
|
|
@@ -51,8 +51,13 @@ const fetch_1 = require("@x402/fetch");
|
|
|
51
51
|
const stellar_1 = require("@x402/stellar");
|
|
52
52
|
// @ts-ignore
|
|
53
53
|
const client_1 = require("@x402/stellar/exact/client");
|
|
54
|
-
|
|
54
|
+
// @ts-ignore: ESM subpath imports (mismo patrón que los de @x402 de arriba)
|
|
55
|
+
const client_2 = require("mppx/client");
|
|
56
|
+
// @ts-ignore
|
|
57
|
+
const client_3 = require("@stellar/mpp/charge/client");
|
|
55
58
|
const x402_guard_1 = require("./x402-guard");
|
|
59
|
+
const x402_policy_1 = require("./x402-policy");
|
|
60
|
+
const x402_spend_cap_1 = require("./x402-spend-cap");
|
|
56
61
|
/** Build a `?a=1&b=2` suffix, dropping undefined values. Returns '' when empty. */
|
|
57
62
|
function queryString(params) {
|
|
58
63
|
if (!params)
|
|
@@ -101,6 +106,7 @@ class Agent {
|
|
|
101
106
|
logCallbacks = [];
|
|
102
107
|
token = null;
|
|
103
108
|
x402Client = null;
|
|
109
|
+
x402Policy = null;
|
|
104
110
|
mppClient = null;
|
|
105
111
|
constructor(config) {
|
|
106
112
|
this.apiKey = config.apiKey;
|
|
@@ -546,6 +552,8 @@ class Agent {
|
|
|
546
552
|
if (config.signer && config.secretKey) {
|
|
547
553
|
throw new Error('initX402 got both `secretKey` and `signer` — pass only one, so it is unambiguous which key signs.');
|
|
548
554
|
}
|
|
555
|
+
if (config.policy !== undefined)
|
|
556
|
+
(0, x402_policy_1.assertValidPolicyHook)(config.policy);
|
|
549
557
|
const signer = config.signer ?? stellar_1.createEd25519Signer(config.secretKey, network);
|
|
550
558
|
// Pubnet: el SDF NO corre RPC público de mainnet — soroban.stellar.org no
|
|
551
559
|
// existe. Default al RPC público de gateway.fm (mismo default que
|
|
@@ -553,24 +561,78 @@ class Agent {
|
|
|
553
561
|
const rpcUrl = config.rpcUrl || (network.includes('testnet')
|
|
554
562
|
? 'https://soroban-testnet.stellar.org'
|
|
555
563
|
: 'https://soroban-rpc.mainnet.stellar.gateway.fm');
|
|
556
|
-
|
|
557
|
-
|
|
564
|
+
if (config.policy) {
|
|
565
|
+
// Con policy el cliente se arma en cada x402Fetch: el signer de
|
|
566
|
+
// stellar-sdk no recibe la URL, y un closure por llamada ata URL,
|
|
567
|
+
// método y requisitos a ese pago sin estado compartido.
|
|
568
|
+
this.x402Policy = { base: signer, rpcUrl, policy: config.policy };
|
|
569
|
+
this.x402Client = null;
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
this.x402Policy = null;
|
|
573
|
+
const scheme = new client_1.ExactStellarScheme(signer, { url: rpcUrl });
|
|
574
|
+
const client = new fetch_1.x402Client().register('stellar:*', scheme);
|
|
575
|
+
// El cliente es uno solo; el fetch envuelto se arma en cada llamada
|
|
576
|
+
// (un closure barato) para que lo capturado de cada 402 sea de esa llamada.
|
|
577
|
+
this.x402Client = { client, scheme, baseFetch: fetch };
|
|
558
578
|
}
|
|
559
579
|
/**
|
|
560
580
|
* Fetch a paid resource via x402 protocol.
|
|
561
581
|
* The client automatically handles 402 negotiation, auth-entry signing, and payment.
|
|
562
582
|
* Returns the Response object — call .json() or .text() for the payload.
|
|
583
|
+
*
|
|
584
|
+
* Throws `X402SpendCapError` when @x402/core refuses a payment for being above
|
|
585
|
+
* its per-payment cap (before anything is signed), and `X402PolicyError` when
|
|
586
|
+
* a `policy` refuses it.
|
|
563
587
|
*/
|
|
564
588
|
async x402Fetch(url, init) {
|
|
589
|
+
if (this.x402Policy)
|
|
590
|
+
return this.x402FetchWithPolicy(this.x402Policy, url, init);
|
|
565
591
|
if (!this.x402Client) {
|
|
566
592
|
throw new Error('x402 client not initialized. Call agent.initX402() first.');
|
|
567
593
|
}
|
|
568
|
-
|
|
594
|
+
const { client, scheme, baseFetch } = this.x402Client;
|
|
595
|
+
const sink = {};
|
|
596
|
+
try {
|
|
597
|
+
return await (0, fetch_1.wrapFetchWithPayment)((0, x402_spend_cap_1.captureRequirements)(baseFetch, sink), client)(url, init);
|
|
598
|
+
}
|
|
599
|
+
catch (e) {
|
|
600
|
+
throw (0, x402_spend_cap_1.toSpendCapError)(e, url, sink.offered, scheme.findDefaultAsset?.bind(scheme)) ?? e;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
async x402FetchWithPolicy(cfg, url, init) {
|
|
604
|
+
const slot = {};
|
|
605
|
+
const gated = (0, x402_policy_1.createPolicyGatedSigner)(cfg.base, cfg.policy, () => ({ url, method: (init?.method ?? 'GET').toUpperCase(), requirements: slot.requirements }), (err) => { slot.error = err; });
|
|
606
|
+
const scheme = new client_1.ExactStellarScheme(gated, { url: cfg.rpcUrl });
|
|
607
|
+
const sink = {};
|
|
608
|
+
const client = new fetch_1.x402Client()
|
|
609
|
+
.register('stellar:*', scheme)
|
|
610
|
+
.onBeforePaymentCreation(async ({ selectedRequirements: r }) => {
|
|
611
|
+
slot.requirements = {
|
|
612
|
+
scheme: r.scheme, network: r.network, asset: r.asset,
|
|
613
|
+
payTo: r.payTo, amount: r.amount, maxTimeoutSeconds: r.maxTimeoutSeconds,
|
|
614
|
+
};
|
|
615
|
+
});
|
|
616
|
+
// NUNCA registrar onPaymentCreationFailure aquí: puede devolver un
|
|
617
|
+
// payload sin pasar por el signer, y el gate quedaría puenteado.
|
|
618
|
+
try {
|
|
619
|
+
return await (0, fetch_1.wrapFetchWithPayment)((0, x402_spend_cap_1.captureRequirements)(globalThis.fetch, sink), client)(url, init);
|
|
620
|
+
}
|
|
621
|
+
catch (e) {
|
|
622
|
+
// @x402/fetch reenvuelve el error y pierde la clase.
|
|
623
|
+
throw slot.error ?? (0, x402_spend_cap_1.toSpendCapError)(e, url, sink.offered, scheme.findDefaultAsset?.bind(scheme)) ?? e;
|
|
624
|
+
}
|
|
569
625
|
}
|
|
570
626
|
// ─── MPP Protocol (Charge Mode) ────────────────────────────
|
|
571
627
|
/**
|
|
572
628
|
* Initialize the MPP Charge client for per-request Soroban SAC payments.
|
|
573
629
|
* Uses canonical @stellar/mpp charge mode with mppx.
|
|
630
|
+
*
|
|
631
|
+
* EXPERIMENTAL. The client works against a compliant MPP Charge server, but
|
|
632
|
+
* Nirium's hosted testnet `/api/v1/mpp/*` endpoint rejected MPP payments when
|
|
633
|
+
* tested on 2026-10-01 (`402 Verification Failed`), and in `push` mode the
|
|
634
|
+
* payment has already settled on-chain when that happens. The mainnet
|
|
635
|
+
* endpoint was not tested. Use `initX402()` for paid endpoints. See the README.
|
|
574
636
|
* In pull mode, the server assembles and broadcasts the transaction.
|
|
575
637
|
*
|
|
576
638
|
* @example
|
|
@@ -580,17 +642,14 @@ class Agent {
|
|
|
580
642
|
* ```
|
|
581
643
|
*/
|
|
582
644
|
initMpp(config) {
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
},
|
|
591
|
-
},
|
|
645
|
+
// La red la dicta el reto 402 del servidor (methodDetails.network), no el cliente:
|
|
646
|
+
// `config.network` se acepta por compatibilidad pero ya no se usa.
|
|
647
|
+
// polyfill:false es obligatorio: sin él mppx reemplaza globalThis.fetch y
|
|
648
|
+
// pasaría a interceptar también los 402 de x402Fetch.
|
|
649
|
+
this.mppClient = client_2.Mppx.create({
|
|
650
|
+
methods: [client_3.stellar.charge({ secretKey: config.secretKey, mode: config.mode || 'pull' })],
|
|
651
|
+
polyfill: false,
|
|
592
652
|
});
|
|
593
|
-
this.mppClient = mppx;
|
|
594
653
|
}
|
|
595
654
|
/**
|
|
596
655
|
* Fetch a paid resource via MPP Charge protocol.
|
|
@@ -869,6 +928,10 @@ function x402Serve(config) {
|
|
|
869
928
|
// `.js` extension required even though the source is `.ts`: `module:
|
|
870
929
|
// ESNext` emits these specifiers verbatim, and Node's native ESM resolver
|
|
871
930
|
// (unlike a bundler) needs the real extension to find the compiled file.
|
|
931
|
+
var x402_policy_2 = require("./x402-policy");
|
|
932
|
+
Object.defineProperty(exports, "X402PolicyError", { enumerable: true, get: function () { return x402_policy_2.X402PolicyError; } });
|
|
933
|
+
var x402_spend_cap_2 = require("./x402-spend-cap");
|
|
934
|
+
Object.defineProperty(exports, "X402SpendCapError", { enumerable: true, get: function () { return x402_spend_cap_2.X402SpendCapError; } });
|
|
872
935
|
var metrics_1 = require("./metrics");
|
|
873
936
|
Object.defineProperty(exports, "x402Metrics", { enumerable: true, get: function () { return metrics_1.x402Metrics; } });
|
|
874
937
|
var x402_guard_upstash_1 = require("./x402-guard-upstash");
|