nirium-pollar-adapter 0.5.0 → 0.6.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 CHANGED
@@ -1,16 +1,18 @@
1
1
  # nirium-pollar-adapter
2
2
 
3
- Nirium adapter for the [Pollar](https://pollar.xyz) SDK — let the wallet a user onboarded through Pollar pay for APIs (x402) and anchor tamper-proof evidence to IPFS, without your app touching keys or learning the x402 protocol.
3
+ Nirium adapter for the [Pollar](https://pollar.xyz) SDK. It lets the wallet a user onboarded through Pollar pay for APIs (x402) and anchor tamper-proof evidence to IPFS, without your app touching keys or learning the x402 protocol.
4
4
 
5
- Both surfaces are **software-only and non-custodial**, and both are **live on Stellar mainnet**.
5
+ Two things matter most here: **x402** pays per request, and `anchorOnTransactionSuccess()` (see [API](#api) below) anchors an Audit Trail receipt to IPFS for every Pollar transaction that reaches `success` - a verifiable, tamper-proof record of what happened, independent of this adapter's own output.
6
6
 
7
- Wraps [`nirium`](https://github.com/nirium-protocol/nirium), the TypeScript/Python SDK this adapter signs for — see that repo for the full API this exposes through a Pollar wallet instead of a raw keypair.
7
+ Both surfaces are **software-only and non-custodial**, and both are **live on Stellar mainnet**: the last x402 payment settled on [29 Sep 2026](https://stellar.expert/explorer/public/tx/b34630f6637d6773ad4f7378dac8690ae6d1809173ff9c9541d22165aeef5788) (a real USDC transfer on mainnet), and the last Audit Trail anchor is from 12 Nov 2026, checked live against the mainnet agent's `GET /api/reporting/summary?network=mainnet` at the time of writing (`anchors.lastAnchoredAt`).
8
+
9
+ Wraps [`nirium`](https://github.com/nirium-protocol/nirium), the TypeScript/Python SDK this adapter signs for. See that repo for the full API this exposes through a Pollar wallet instead of a raw keypair.
8
10
 
9
11
  ## Install
10
12
 
11
13
  ```bash
12
14
  npm install nirium-pollar-adapter
13
- # optional peer, only for createPollarSigner: @pollar/core >= 0.11
15
+ # optional peer, only for createPollarSigner: @pollar/core >=0.11.4 <0.13.0
14
16
  ```
15
17
 
16
18
  ## Quickstart
@@ -34,13 +36,13 @@ const res = await nirium.x402Fetch(
34
36
  const data = await res.json();
35
37
  ```
36
38
 
37
- The user pays **$0.05 USDC** and signs nothing else — network fees are sponsored by the x402 facilitator, so the wallet does not need XLM for gas.
39
+ The user pays **$0.05 USDC** and signs nothing else. The x402 facilitator sponsors the network fee, so the wallet does not need XLM for gas.
38
40
 
39
- ### Requires @pollar/core 0.11+
41
+ ### Requires @pollar/core 0.11.4+
40
42
 
41
- `createPollarSigner` calls `PollarClient.signAuthEntry`, available from `@pollar/core` 0.11. On older versions it throws an explanatory error, and you can still pass any other SEP-43 signer.
43
+ `createPollarSigner` calls `PollarClient.signAuthEntry`, available from `@pollar/core` 0.11. The peer range is `>=0.11.4 <0.13.0`; CI runs the contract test against 0.11.4; 0.12.0 was also run by hand on 2026-10-31. On older versions it throws an explanatory error, and you can still pass any other SEP-43 signer.
42
44
 
43
- The two sides speak different dialects and the adapter translates between them: x402 expects SEP-43 (`signAuthEntry(xdr, { networkPassphrase, address }) → { signedAuthEntry }`), Pollar expects `signAuthEntry(xdr, { validUntilLedger }) → { status, … }`. The adapter reads the network's latest ledger, sets the expiry, and normalises the outcome — you do not deal with any of it.
45
+ The two sides speak different dialects and the adapter translates between them: x402 expects SEP-43 (`signAuthEntry(xdr, { networkPassphrase, address }) → { signedAuthEntry }`), Pollar expects `signAuthEntry(xdr, { validUntilLedger }) → { status, … }`. The adapter reads the network's latest ledger, sets the expiry, and normalises the outcome. You do not deal with any of it.
44
46
 
45
47
  ```ts
46
48
  const signer = createPollarSigner(pollar, {
@@ -53,17 +55,25 @@ Check at runtime before enabling a pay button:
53
55
 
54
56
  ```ts
55
57
  import { canSignX402 } from "nirium-pollar-adapter";
56
- <button disabled={!canSignX402(pollar)}>Pay $0.02</button>
58
+ <button disabled={!canSignX402(pollar)}>Pay $0.05</button>
57
59
  ```
58
60
 
59
61
  ## Verify it end-to-end today
60
62
 
61
- The signer is pluggable, so you can prove the whole path works with a plain Stellar keypair — no Pollar required:
63
+ **Known issue:** [pollar-xyz/pollar-apps#36](https://github.com/pollar-xyz/pollar-apps/pull/36) fixes a real `XDR Read Error` that breaks payment in Pollar's own official Nirium demo today; still open as of this writing.
64
+
65
+ The signer is pluggable, so you can prove the whole path works with a plain Stellar keypair. No Pollar required - this defaults to testnet, no real money moves:
62
66
 
63
67
  ```bash
64
68
  NIRIUM_DEMO_SECRET=S… node examples/pay-with-keypair.mjs
65
69
  ```
66
70
 
71
+ Against mainnet (spends real USDC, $0.05 per call), opt in explicitly:
72
+
73
+ ```bash
74
+ NIRIUM_DEMO_SECRET=S… NIRIUM_NETWORK=stellar:pubnet node examples/pay-with-keypair.mjs
75
+ ```
76
+
67
77
  Verified on mainnet (27 Jul 2026): payment [`25ebaf9a…`](https://stellar.expert/explorer/public/tx/25ebaf9aa7e72c1c3edcc43a1c18aaa102c12eee42c57e02fed4fda79af6605d) settled, evidence anchored at [`QmZiwxidm…`](https://gateway.pinata.cloud/ipfs/QmZiwxidm7pcTqNufxzFyUc7qJrCRN2TKRNwcXkg7vUUwR).
68
78
 
69
79
  Swapping to a Pollar wallet is one line:
@@ -74,53 +84,57 @@ Swapping to a Pollar wallet is one line:
74
84
  ```
75
85
 
76
86
  **Verified with a real Pollar social login (our own test account, 5 Aug
77
- 2026):** a user who signed in with Google paid $0.02 USDC on mainnet —
78
- [`e4fa3df9…`](https://stellar.expert/explorer/public/tx/e4fa3df9cb225a4d7f64dd0082eb38218ada4b4af3378f288989a5d4b1116ed9)
79
- — holding **zero XLM** at any point. Pollar sponsors the account reserve and the
80
- trustline; the x402 facilitator sponsors the network fee and is the transaction
81
- source. The user never saw a key, a seed phrase or a gas prompt.
87
+ 2026):** a user who signed in with Google paid $0.02 USDC on mainnet
88
+ ([`e4fa3df9…`](https://stellar.expert/explorer/public/tx/e4fa3df9cb225a4d7f64dd0082eb38218ada4b4af3378f288989a5d4b1116ed9))
89
+ while holding **zero XLM** at every point. Pollar sponsors the account reserve
90
+ and the trustline. The x402 facilitator sponsors the network fee and is the
91
+ transaction source. The user never saw a key, a seed phrase or a gas prompt.
82
92
 
83
93
  Both proofs above paid `/premium/signals` ($0.02). Since 6-Aug-2026 that
84
- endpoint is **testnet only** — the mainnet agent box runs no autonomous loop,
94
+ endpoint is **testnet only**: the mainnet agent box runs no autonomous loop,
85
95
  so a capability guard now returns 501 before any charge. The example above
86
96
  pays `/premium/market` ($0.05) instead, which has no such guard and still
87
- settles on mainnet today; the two linked transactions remain real, they are
88
- just no longer reproducible verbatim with the current example.
97
+ settles on mainnet today. The two linked transactions remain real; they are
98
+ just no longer reproducible word for word with the current example.
89
99
 
90
100
  ## Deferred funding (Pollar "Deferred mode")
91
101
 
92
102
  If your Pollar app's **Dashboard → Treasury → Funding Mode** is set to
93
- **Deferred**, a wallet is created on-chain at login but its XLM reserve is
94
- not funded until your backend calls `POST /v1/wallets/activate`. This
95
- adapter did not call that endpoint until this version — the section above
96
- already shows why it usually does not need to: a wallet at 0 XLM can sign
97
- and settle a real x402 payment (Pollar sponsors the account reserve and the
98
- default trustline; the facilitator sponsors the network fee). Call
99
- `activateWallet()` when you *do* need the account's own reserve — receiving
100
- native XLM, holding subentries Pollar does not sponsor, or just to match
101
- what Pollar's dashboard considers "activated."
103
+ **Deferred**, Pollar does not create the account on-chain at login. Your
104
+ backend creates it by calling `POST /v3/wallets/fund`. Checked on testnet on
105
+ 2026-10-31: for a wallet that did not exist yet (Horizon returned 404), the
106
+ call returned 200 with `startingBalance: "0"`, and Horizon then showed the
107
+ account with 0 XLM and its reserves sponsored by Pollar. So "funding" here
108
+ means creating the account with sponsored reserves, not sending XLM to it.
109
+
110
+ You often do not need it for x402. A wallet at 0 XLM can sign and settle a
111
+ real x402 payment (see the section above: Pollar sponsors the reserve and
112
+ the default trustline, and the facilitator sponsors the network fee). Call
113
+ `activateWallet()` when your app needs the account to exist on-chain before
114
+ that first payment, or to match what Pollar's dashboard considers
115
+ "activated."
102
116
 
103
117
  ```ts
104
118
  import { activateWallet } from "nirium-pollar-adapter";
105
119
 
106
- // Server-side only (Next.js API route, Express handler, webhook) — never
107
- // call this from the browser, it requires the secret key.
120
+ // Server-side only (Next.js API route, Express handler, webhook). Never
121
+ // call this from the browser: it requires the secret key.
108
122
  const result = await activateWallet(wallet.address, {
109
123
  secretKey: process.env.POLLAR_SECRET_KEY!, // sec_testnet_… / sec_mainnet_…
110
124
  });
111
- // { activated: true, amount: "1.5" } — funded now
112
- // { activated: false } — was already funded; safe, not an error
125
+ // { activated: true, amount: "0" } - funded now (amount = Pollar's startingBalance)
126
+ // { activated: false } - account already exists on-chain; safe, not an error
113
127
  ```
114
128
 
115
- Calling it twice on an already-funded wallet does not throw — Pollar's own
129
+ Calling it twice on an already-funded wallet does not throw. Pollar's own
116
130
  docs call HTTP 409 "safe to ignore, treat as success," and `activateWallet`
117
131
  returns `{ activated: false }` rather than raising. Anything else throws
118
132
  `PollarActivationError` with the real `code` and HTTP `status` Pollar sent,
119
- rather than assuming a fixed meaning per status number — the two Pollar docs
120
- pages describing this endpoint disagree with each other on what several of
121
- the non-200/409 codes mean (402 vs. 403, 503 vs. 502 for what reads like the
122
- same failure), so this adapter surfaces what the server actually said
123
- instead of picking one doc to trust.
133
+ rather than assuming a fixed meaning per status number. The two Pollar docs
134
+ pages that describe this endpoint disagree on what several of the non-200/409
135
+ codes mean (402 vs. 403, 503 vs. 502 for what reads like the same failure),
136
+ so this adapter passes on what the server actually said instead of picking
137
+ one doc to trust.
124
138
 
125
139
  ## API
126
140
 
@@ -128,7 +142,7 @@ instead of picking one doc to trust.
128
142
 
129
143
  | Option | Default | |
130
144
  |---|---|---|
131
- | `signer` | — | SEP-43 signer. Only `address` and `signAuthEntry` are required |
145
+ | `signer` | - | SEP-43 signer. Only `address` and `signAuthEntry` are required |
132
146
  | `network` | `stellar:testnet` | `stellar:testnet` or `stellar:pubnet` |
133
147
  | `agentBaseUrl` | box for the network | Nirium agent base URL |
134
148
  | `rpcUrl` | public RPC for the network | Soroban RPC |
@@ -136,11 +150,11 @@ instead of picking one doc to trust.
136
150
 
137
151
  Returns:
138
152
 
139
- - **`x402Fetch(url, init?)`** — fetch that pays on `402` and retries. Passes through untouched on `200`.
140
- - **`getPremiumSignals()`** — typed shortcut to the agent's paid signals endpoint. **Testnet only**: signals come from the autonomous loop, which does not run on the mainnet box; there the endpoint returns 501 without charging.
141
- - **`getPremiumMarket()`** — typed shortcut to the agent's paid market-state endpoint ($0.05). Works and charges on **both** networks — no autonomous loop dependency.
142
- - **`anchorAuditRecord({ hash?, record?, txHash?, tag? })`** — anchors evidence to IPFS, returns the CID. No signature, no payment. Anchor **hashes, not personal data** — IPFS cannot be deleted.
143
- - **`getCetesRate()`** — public reference rate, no key required.
153
+ - **`x402Fetch(url, init?)`**: fetch that pays on `402` and retries. Passes through untouched on `200`.
154
+ - **`getPremiumSignals()`**: typed shortcut to the agent's paid signals endpoint. **Testnet only**: signals come from the autonomous loop, which does not run on the mainnet box; there the endpoint returns 501 without charging.
155
+ - **`getPremiumMarket()`**: typed shortcut to the agent's paid market-state endpoint ($0.05). Works and charges on **both** networks, with no dependency on the autonomous loop.
156
+ - **`anchorAuditRecord({ hash?, record?, txHash?, tag? })`**: anchors evidence to IPFS and returns the CID. No signature, no payment. Anchor **hashes, not personal data**: IPFS cannot be deleted.
157
+ - **`getCetesRate()`**: CETES rate as a number, no key required. It is **not a live reading**: today the agent serves a fixed value (5.57, read in June 2026 from app.etherfuse.com/b/cetes).
144
158
 
145
159
  ### `createPollarSigner(pollarClient, opts?)`
146
160
 
@@ -156,35 +170,54 @@ Wraps a Pollar client as a SEP-43 `ClientStellarSigner`.
156
170
  **`signAuthEntry` means two different things, and this is what translates them.**
157
171
 
158
172
  `stellar-sdk` (`AssembledTransaction.signAuthEntries` → `authorizeEntry`) hands
159
- the signer a **`HashIdPreimage`** — the thing about to be hashed — and expects
173
+ the signer a **`HashIdPreimage`** (the thing about to be hashed) and expects
160
174
  the **raw signature** back; it assembles the final entry itself. Pollar's
161
175
  `POST /tx/sign-auth-entry` expects the full **`SorobanAuthorizationEntry`** and
162
- returns the **signed entry**, because its backend validates the invocation tree
176
+ returns the **signed entry**, because its backend checks the invocation tree
163
177
  against your Auth Policy allowlist before signing, and a hash would tell it
164
178
  nothing. Both designs are right; they are just not the same one.
165
179
 
166
- Without translation Pollar answers `SOROBAN_AUTH_ENTRY_INVALID — "entryXdr is
180
+ Without translation Pollar answers `SOROBAN_AUTH_ENTRY_INVALID - "entryXdr is
167
181
  not a valid SorobanAuthorizationEntry"`, which reads like a corrupt XDR when the
168
- XDR is fine and merely of another type.
182
+ XDR is fine and simply of another type.
169
183
 
170
- The preimage carries nonce, expiry and invocation; the only thing the entry
171
- additionally needs is the signer address, which we have — so the reconstruction
172
- is exact and the hash Pollar signs is byte-identical to the one the SDK expects.
184
+ The preimage carries nonce, expiry and invocation. The only extra thing the
185
+ entry needs is the signer address, which we have, so the rebuilt entry is exact
186
+ and the hash Pollar signs is byte-identical to the one the SDK expects.
173
187
  The expiry is taken **from the preimage**, never from the clock: it lives inside
174
188
  the signed hash, so asking Pollar for a different one would yield a signature
175
189
  that does not validate.
176
190
 
177
191
  ### `activateWallet(publicKey, options)`
178
192
 
179
- Funds a Pollar wallet's on-chain XLM reserve (`POST /v1/wallets/activate`). **Server-side only.**
193
+ Creates a Pollar wallet's account on-chain with sponsored reserves, for apps in Deferred funding mode (`POST /v3/wallets/fund`). **Server-side only.**
180
194
 
181
195
  | Option | Default | |
182
196
  |---|---|---|
183
- | `secretKey` | — | `sec_testnet_…` / `sec_mainnet_…`. Never expose this client-side |
184
- | `baseUrl` | `https://api.pollar.xyz` | Pollar Server base URL |
197
+ | `secretKey` | - | `sec_testnet_…` / `sec_mainnet_…`. Never expose this client-side |
198
+ | `baseUrl` | `https://server.api.pollar.xyz` | Pollar Server base URL |
185
199
  | `fetchImpl` | global `fetch` | for tests or runtimes without global fetch |
186
200
 
187
- Returns `{ activated: boolean, amount?: string }`. Throws `PollarActivationError` (`.code`, `.status`) for anything other than success (200) or already-funded (409). Also throws a plain `Error` synchronously, before any network call, if `publicKey` is not a valid Stellar `G...` address.
201
+ Returns `{ activated: boolean, amount?: string, queued?: boolean }`. `amount` is the `startingBalance` Pollar reports (`"0"` in the testnet run above). `queued` is `true` on HTTP 202, for co-signed or self-custody wallets, where the user approves the request in their next session. Throws `PollarActivationError` (`.code`, `.status`) for anything other than success (200) or already-funded (409). Also throws a plain `Error` synchronously, before any network call, if `publicKey` is not a valid Stellar `G...` address.
202
+
203
+ ### `anchorOnTransactionSuccess(pollarClient, adapter, options?)`
204
+
205
+ Anchors an Audit Trail receipt each time a Pollar transaction reaches `success`. It listens to Pollar's `onTransactionStateChange`, which Pollar emits for custodial, external, passkey and co-signed wallets. It is **not** emitted for x402 payments, which this adapter anchors itself. Returns a function that stops listening.
206
+
207
+ ```ts
208
+ import { createNiriumAdapter, anchorOnTransactionSuccess } from "nirium-pollar-adapter";
209
+
210
+ const adapter = createNiriumAdapter({ signer });
211
+ const stop = anchorOnTransactionSuccess(pollar, adapter, {
212
+ onError: (err, hash) => console.error("anchor failed", hash, err),
213
+ });
214
+ ```
215
+
216
+ The receipt carries only `chain`, `network`, `hash` and `observedAt` (no app id), because what goes into IPFS is not deleted. Pollar replays the current state when you subscribe, so the function deduplicates by hash inside the process. It does not deduplicate across restarts: the same hash can be anchored twice. A failed anchor goes to `onError` and never throws into Pollar's listener; the hash can be retried when Pollar sends it again. Options: `chain` (default `"stellar"`), `tag` (default `"pollar-tx"`), `onError`.
217
+
218
+ Checked against `@pollar/core` 0.11.4 and 0.12.0 in the test suite.
219
+
220
+ **Live check, 2026-11-01, testnet.** `examples/spike-19/anchor-on-success.mjs` logs in to a Pollar testnet app, sends 1 XLM through `pollar.sendPayment`, and anchors the receipt. Transaction [`95717202...b7b`](https://horizon-testnet.stellar.org/transactions/95717202be514ed0ae6d59d88c5950d79ff94b40dad709a430691ad6c4449b7b) (successful, ledger 5506358, 1 payment op) produced Audit Trail receipt [`QmboKKkuwck3zvRx2bqnzUdDFkrEtc1VUHo6rrzm9nyBtD`](https://gateway.pinata.cloud/ipfs/QmboKKkuwck3zvRx2bqnzUdDFkrEtc1VUHo6rrzm9nyBtD). The record holds only `chain`, `network`, `hash` and `observedAt`, and `content_sha256` equals the sha-256 of that record as sent. This is a Nirium self-test on testnet, not third-party use.
188
221
 
189
222
  ### Paying from a browser
190
223
 
@@ -204,16 +237,30 @@ Pollar side: allowlist the USDC SAC with the `transfer` function under
204
237
  **Treasury → Auth Policy**. Until a contract is listed, every custodial signing
205
238
  request is rejected.
206
239
 
240
+ ## How this relates to Pollar's `AdapterFn` pattern
241
+
242
+ Pollar's own adapters (for example the Trustless Work one in its demo) follow the `AdapterFn` pattern from `@pollar/core`: each function returns `{ unsignedTransaction }`, the functions are registered on `PollarProvider` through `adapters={{ ... }}`, and the hook made by `createPollarAdapterHook` signs that transaction with the user's wallet and submits it to the network (`signAndSubmitTx`).
243
+
244
+ This package does not follow that pattern, on purpose. An x402 payment is not a transaction that gets submitted. The user signs a Soroban authorization entry, it travels to the seller in a header, and the x402 facilitator settles it. If an adapter returned it as `unsignedTransaction`, the hook would submit it to the network by itself. So `createNiriumAdapter` runs the payment itself (it negotiates the 402, signs through `createPollarSigner` and retries), and anchoring is a plain HTTP call.
245
+
246
+ In practice:
247
+
248
+ - You use `createNiriumAdapter` directly. It is not registered under `PollarProvider adapters`, and there is no `createPollarAdapterHook` hook for it.
249
+ - Nirium operations that do return an unsigned transaction (treasury, payouts) are not exposed here as `AdapterFn`s. They are invite-only on mainnet and outside the scope of this package.
250
+ - A registry-pattern version of the payment flow is not shipped. Whether one is possible depends on how an adapter could hand back a signed authorization entry instead of a transaction. That is an open design question, not a plan.
251
+
252
+ Checked on 2026-10-12 against the published `@pollar/core` 0.11.4 and `@pollar/react` 0.11.4 packages, not their docs. CI runs a contract test against the real `@pollar/core` 0.11.4 (`test/pollar-contract.test.mjs` and a compile-time check in `test/pollar-contract.types.ts`), so a change in the shape this package relies on fails the build.
253
+
207
254
  ## Scope
208
255
 
209
256
  | | |
210
257
  |---|---|
211
258
  | x402 Settlement | ✅ mainnet |
212
259
  | Audit Trail (IPFS) | ✅ mainnet |
213
- | Treasury vault (DeFindex, client-owned) — Nirium signs and executes | ✅ mainnet — invite-only during legal review |
214
- | Treasury vault — propose only, you sign | ✅ mainnet — public, no invite required (`POST /api/treasury/rebalance/propose`, not yet wrapped by this adapter) |
215
- | Nirium's own NiriumVault | audit-gated — testnet only |
216
- | MPP session channels | audit-gated — testnet only |
260
+ | Treasury vault (DeFindex, client-owned), Nirium signs and executes | ✅ mainnet, invite-only during legal review |
261
+ | Treasury vault, propose only, you sign | ✅ mainnet, public, no invite required (`POST /api/treasury/rebalance/propose`, not yet wrapped by this adapter) |
262
+ | Nirium's own NiriumVault | audit-gated, testnet only |
263
+ | MPP session channels | audit-gated, testnet only |
217
264
 
218
265
  Nirium never holds customer funds. The user's signature is the authorization; regulated partners execute any financial settlement.
219
266
 
package/dist/index.d.ts CHANGED
@@ -67,7 +67,7 @@ export declare function canSignX402(pollar: PollarLikeClient): boolean;
67
67
  export interface ActivateWalletOptions {
68
68
  /** Secret key de Pollar (sec_testnet_… / sec_mainnet_…). SOLO backend — nunca la mandes al navegador. */
69
69
  secretKey: string;
70
- /** Base URL del servidor de Pollar. Default: https://api.pollar.xyz. */
70
+ /** Base URL del servidor de Pollar. Default: https://server.api.pollar.xyz. */
71
71
  baseUrl?: string;
72
72
  /** fetch a envolver (para tests o runtimes sin fetch global). */
73
73
  fetchImpl?: typeof fetch;
@@ -77,6 +77,8 @@ export interface ActivateWalletResult {
77
77
  activated: boolean;
78
78
  /** Reserva de XLM fondeada, tal como la reporta Pollar. Solo viene cuando `activated` es `true` en esta llamada. */
79
79
  amount?: string;
80
+ /** `true` si Pollar encoló la petición (HTTP 202, wallet co-firmada o self-custody): el usuario la aprueba en su próxima sesión. */
81
+ queued?: boolean;
80
82
  }
81
83
  /** Pollar rechazó la activación con un código que no es "ya estaba activa". */
82
84
  export declare class PollarActivationError extends Error {
@@ -92,7 +94,7 @@ export declare class PollarActivationError extends Error {
92
94
  }
93
95
  /**
94
96
  * Fondea la reserva de XLM on-chain de una wallet de Pollar en modo Deferred
95
- * (`POST /v1/wallets/activate`). Llamar SOLO desde tu backend — la secret key
97
+ * (`POST /v3/wallets/fund`). Llamar SOLO desde tu backend — la secret key
96
98
  * nunca debe llegar al navegador.
97
99
  *
98
100
  * Cuándo llamarla: no hay un "evento de negocio" natural en un flujo x402 puro
@@ -136,3 +138,22 @@ export declare function createNiriumAdapter(config: NiriumAdapterConfig): {
136
138
  getCetesRate: () => Promise<number | null>;
137
139
  };
138
140
  export type NiriumAdapter = ReturnType<typeof createNiriumAdapter>;
141
+ /** Lo unico que se necesita del cliente de Pollar. */
142
+ export interface PollarTransactionEvents {
143
+ onTransactionStateChange?: (cb: (state: any) => void) => () => void;
144
+ }
145
+ export interface AnchorOnSuccessOptions {
146
+ /** Cadena que se escribe en el recibo. Default: "stellar". */
147
+ chain?: string;
148
+ /** Etiqueta del recibo en Audit Trail. Default: "pollar-tx". */
149
+ tag?: string;
150
+ /** Reloj, para pruebas. Default: Date.now. */
151
+ now?: () => number;
152
+ /** Se llama si el anclaje falla. El listener de Pollar nunca lanza. */
153
+ onError?: (error: unknown, hash: string) => void;
154
+ }
155
+ /**
156
+ * Ancla un recibo en Audit Trail cada vez que una transaccion de Pollar llega a
157
+ * `success`. Devuelve la funcion para dejar de escuchar.
158
+ */
159
+ export declare function anchorOnTransactionSuccess(pollar: PollarTransactionEvents, adapter: Pick<NiriumAdapter, "anchorAuditRecord" | "network">, options?: AnchorOnSuccessOptions): () => void;
package/dist/index.js CHANGED
@@ -226,7 +226,7 @@ export class PollarActivationError extends Error {
226
226
  }
227
227
  /**
228
228
  * Fondea la reserva de XLM on-chain de una wallet de Pollar en modo Deferred
229
- * (`POST /v1/wallets/activate`). Llamar SOLO desde tu backend — la secret key
229
+ * (`POST /v3/wallets/fund`). Llamar SOLO desde tu backend — la secret key
230
230
  * nunca debe llegar al navegador.
231
231
  *
232
232
  * Cuándo llamarla: no hay un "evento de negocio" natural en un flujo x402 puro
@@ -240,9 +240,9 @@ export async function activateWallet(publicKey, options) {
240
240
  if (!StrKey.isValidEd25519PublicKey(publicKey)) {
241
241
  throw new Error(`activateWallet: "${publicKey}" no es una dirección Stellar G... válida.`);
242
242
  }
243
- const baseUrl = (options.baseUrl ?? "https://api.pollar.xyz").replace(/\/+$/, "");
243
+ const baseUrl = (options.baseUrl ?? "https://server.api.pollar.xyz").replace(/\/+$/, "");
244
244
  const doFetch = options.fetchImpl ?? fetch;
245
- const res = await doFetch(`${baseUrl}/v1/wallets/activate`, {
245
+ const res = await doFetch(`${baseUrl}/v3/wallets/fund`, {
246
246
  method: "POST",
247
247
  headers: {
248
248
  "content-type": "application/json",
@@ -257,8 +257,12 @@ export async function activateWallet(publicKey, options) {
257
257
  catch {
258
258
  // Cuerpo vacío o no-JSON — se maneja abajo con el status solo.
259
259
  }
260
- if (res.status === 200 && body?.success) {
261
- return { activated: true, amount: body.content?.amount };
260
+ if (res.status === 200 && body?.success !== false) {
261
+ // Pollar v3 devuelve content.startingBalance (verificado en testnet 2026-10-31); `amount` era el nombre de v1.
262
+ return { activated: true, amount: body?.content?.startingBalance ?? body?.content?.amount };
263
+ }
264
+ if (res.status === 202) {
265
+ return { activated: false, queued: true };
262
266
  }
263
267
  if (res.status === 409) {
264
268
  return { activated: false };
@@ -371,3 +375,40 @@ export function createNiriumAdapter(config) {
371
375
  getCetesRate,
372
376
  };
373
377
  }
378
+ /**
379
+ * Ancla un recibo en Audit Trail cada vez que una transaccion de Pollar llega a
380
+ * `success`. Devuelve la funcion para dejar de escuchar.
381
+ */
382
+ export function anchorOnTransactionSuccess(pollar, adapter, options = {}) {
383
+ if (typeof pollar.onTransactionStateChange !== "function") {
384
+ throw new Error("anchorOnTransactionSuccess: este cliente de Pollar no tiene onTransactionStateChange.");
385
+ }
386
+ const seen = new Set();
387
+ const now = options.now ?? Date.now;
388
+ return pollar.onTransactionStateChange((state) => {
389
+ if (state?.step !== "success" || typeof state.hash !== "string" || !state.hash)
390
+ return;
391
+ const hash = state.hash;
392
+ if (seen.has(hash))
393
+ return;
394
+ seen.add(hash);
395
+ const record = {
396
+ chain: options.chain ?? "stellar",
397
+ network: isPubnet(adapter.network) ? "mainnet" : "testnet",
398
+ hash,
399
+ observedAt: new Date(now()).toISOString(),
400
+ };
401
+ Promise.resolve()
402
+ .then(() => adapter.anchorAuditRecord({ record, txHash: hash, tag: options.tag ?? "pollar-tx" }))
403
+ .catch((err) => {
404
+ // Si falla, se permite reintentar con el mismo hash cuando Pollar lo reenvie.
405
+ seen.delete(hash);
406
+ try {
407
+ options.onError?.(err, hash);
408
+ }
409
+ catch {
410
+ // un onError que lanza no debe romper el listener de Pollar
411
+ }
412
+ });
413
+ });
414
+ }
@@ -8,11 +8,16 @@
8
8
  // - const signer = createEd25519Signer(secret, network);
9
9
  // + const signer = createPollarSigner(pollarClient);
10
10
  //
11
- // Uso:
11
+ // Uso (default = testnet, seguro, sin gasto real):
12
12
  // NIRIUM_DEMO_SECRET=S... node examples/pay-with-keypair.mjs
13
- // NIRIUM_DEMO_SECRET=S... NIRIUM_NETWORK=stellar:testnet node examples/pay-with-keypair.mjs
14
13
  //
15
- // OJO: contra stellar:pubnet esto gasta USDC REAL (0.05 por llamada a market).
14
+ // Contra mainnet (gasta USDC REAL, 0.05 por llamada a market) — opt-in explícito:
15
+ // NIRIUM_DEMO_SECRET=S... NIRIUM_NETWORK=stellar:pubnet node examples/pay-with-keypair.mjs
16
+ //
17
+ // Update, 2026-10-24: el default de este archivo era "stellar:pubnet" —
18
+ // quien corriera el primer comando de uso tal cual, sin leer el resto del
19
+ // comentario, gastaba USDC real sin darse cuenta. El default ahora es
20
+ // testnet; pubnet pide la variable de entorno a propósito.
16
21
  //
17
22
  // Usa getPremiumMarket(), no getPremiumSignals(): desde el 6-ago-2026 el box
18
23
  // de mainnet responde 501 a /premium/signals ANTES de cobrar (no hay loop
@@ -29,7 +34,7 @@ if (!secret) {
29
34
  process.exit(1);
30
35
  }
31
36
 
32
- const network = process.env.NIRIUM_NETWORK ?? "stellar:pubnet";
37
+ const network = process.env.NIRIUM_NETWORK ?? "stellar:testnet";
33
38
  const signer = createEd25519Signer(secret, network);
34
39
  const nirium = createNiriumAdapter({ signer, network });
35
40
 
@@ -0,0 +1,168 @@
1
+ // Live check for anchorOnTransactionSuccess: one Pollar login, one real testnet
2
+ // payment, one Audit Trail receipt for it.
3
+ //
4
+ // What it does:
5
+ // 1. Logs in to a Pollar TESTNET app with an email code (you type the code).
6
+ // 2. Gives the Pollar wallet some testnet XLM from a throwaway key funded by
7
+ // friendbot (the throwaway key is never printed or saved).
8
+ // 3. Sends 1 XLM back through Pollar's own pipeline (pollar.sendPayment), which
9
+ // makes onTransactionStateChange report { step: "success", hash }.
10
+ // 4. anchorOnTransactionSuccess anchors { chain, network, hash, observedAt } in
11
+ // Audit Trail. The script prints the tx hash and the CID.
12
+ //
13
+ // Testnet only. The receipt is a Nirium self-test: never count it as third-party use.
14
+ //
15
+ // Env:
16
+ // POLLAR_PUBLISHABLE_KEY=pub_testnet_... (public key of a testnet Pollar app)
17
+ // POLLAR_LOGIN_EMAIL=you@example.com
18
+ // POLLAR_CODE_FILE=/path/to/file (optional; if unset, the code is asked in the terminal)
19
+ // POLLAR_ORIGIN=http://localhost:3000 (optional; must be an origin allowed in the Pollar
20
+ // app's settings, or session creation fails with ORIGIN_NOT_ALLOWED)
21
+ //
22
+ // Run from the repo root after `npm run build`:
23
+ // node examples/spike-19/anchor-on-success.mjs
24
+
25
+ import "./browser-polyfill.mjs";
26
+
27
+ import { PollarClient, createMemoryAdapter } from "@pollar/core";
28
+ import { Keypair, Horizon, TransactionBuilder, Operation, Asset, Networks, BASE_FEE } from "@stellar/stellar-sdk";
29
+ import { createPollarSigner, createNiriumAdapter, anchorOnTransactionSuccess } from "../../dist/index.js";
30
+ import { readFile, unlink } from "node:fs/promises";
31
+ import { createInterface } from "node:readline/promises";
32
+
33
+ const HORIZON = "https://horizon-testnet.stellar.org";
34
+
35
+ function waitForAuthStep(pollar, targetStep) {
36
+ return new Promise((resolve, reject) => {
37
+ const off = pollar.onAuthStateChange((state) => {
38
+ console.log("[auth]", state.step);
39
+ if (state.step === targetStep) {
40
+ off();
41
+ resolve(state);
42
+ } else if (state.step === "error") {
43
+ off();
44
+ reject(new Error(`Pollar auth error: ${state.message} [${state.errorCode}]`));
45
+ }
46
+ });
47
+ });
48
+ }
49
+
50
+ async function readCode() {
51
+ const file = process.env.POLLAR_CODE_FILE;
52
+ if (file) {
53
+ console.log(`Waiting for the 6-digit code in ${file} ...`);
54
+ const deadline = Date.now() + 5 * 60 * 1000;
55
+ while (Date.now() < deadline) {
56
+ try {
57
+ const raw = (await readFile(file, "utf8")).trim();
58
+ if (raw) {
59
+ await unlink(file).catch(() => {});
60
+ return raw;
61
+ }
62
+ } catch {}
63
+ await new Promise((r) => setTimeout(r, 2000));
64
+ }
65
+ throw new Error("Timed out waiting for the code file.");
66
+ }
67
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
68
+ const code = (await rl.question("6-digit code from your email: ")).trim();
69
+ rl.close();
70
+ return code;
71
+ }
72
+
73
+ async function giveTestnetXlm(address) {
74
+ const funder = Keypair.random();
75
+ const fb = await fetch(`https://friendbot.stellar.org?addr=${funder.publicKey()}`);
76
+ if (!fb.ok) throw new Error(`friendbot HTTP ${fb.status}`);
77
+ const server = new Horizon.Server(HORIZON);
78
+ const account = await server.loadAccount(funder.publicKey());
79
+ const exists = (await fetch(`${HORIZON}/accounts/${address}`)).status === 200;
80
+ const op = exists
81
+ ? Operation.payment({ destination: address, asset: Asset.native(), amount: "5" })
82
+ : Operation.createAccount({ destination: address, startingBalance: "5" });
83
+ const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: Networks.TESTNET })
84
+ .addOperation(op)
85
+ .setTimeout(60)
86
+ .build();
87
+ tx.sign(funder);
88
+ await server.submitTransaction(tx);
89
+ console.log(`Wallet ${exists ? "topped up with" : "created on-chain with"} 5 testnet XLM.`);
90
+ return funder.publicKey();
91
+ }
92
+
93
+ async function main() {
94
+ const apiKey = process.env.POLLAR_PUBLISHABLE_KEY;
95
+ const email = process.env.POLLAR_LOGIN_EMAIL;
96
+ if (!apiKey?.startsWith("pub_testnet_") || !email) {
97
+ console.error("Set POLLAR_PUBLISHABLE_KEY (pub_testnet_...) and POLLAR_LOGIN_EMAIL first.");
98
+ process.exit(1);
99
+ }
100
+
101
+ const pollar = new PollarClient({ apiKey, stellarNetwork: "testnet", storage: createMemoryAdapter() });
102
+ await pollar.ready();
103
+
104
+ const enteringEmail = waitForAuthStep(pollar, "entering_email");
105
+ pollar.beginEmailLogin();
106
+ await enteringEmail;
107
+ const enteringCode = waitForAuthStep(pollar, "entering_code");
108
+ pollar.sendEmailCode(email);
109
+ await enteringCode;
110
+ const authenticated = waitForAuthStep(pollar, "authenticated");
111
+ pollar.verifyEmailCode(await readCode());
112
+ await authenticated;
113
+
114
+ const signer = createPollarSigner(pollar, { network: "stellar:testnet" });
115
+ console.log("Pollar wallet:", signer.address);
116
+
117
+ const nirium = createNiriumAdapter({
118
+ signer,
119
+ network: "stellar:testnet",
120
+ agentBaseUrl: "https://nirium-agent.fly.dev",
121
+ });
122
+
123
+ // Wrap the anchor call only to capture its result for this check.
124
+ let resolveAnchor;
125
+ let rejectAnchor;
126
+ const anchored = new Promise((res, rej) => {
127
+ resolveAnchor = res;
128
+ rejectAnchor = rej;
129
+ });
130
+ const watched = {
131
+ network: nirium.network,
132
+ anchorAuditRecord: async (input) => {
133
+ console.log("Anchoring:", JSON.stringify(input));
134
+ const out = await nirium.anchorAuditRecord(input);
135
+ resolveAnchor(out);
136
+ return out;
137
+ },
138
+ };
139
+ const stop = anchorOnTransactionSuccess(pollar, watched, {
140
+ onError: (err, hash) => rejectAnchor(new Error(`anchor failed for ${hash}: ${err?.message ?? err}`)),
141
+ });
142
+
143
+ const funder = await giveTestnetXlm(signer.address);
144
+
145
+ console.log("Sending 1 XLM through Pollar ...");
146
+ const outcome = await pollar.sendPayment({
147
+ destination: funder,
148
+ amount: "1",
149
+ asset: { type: "native" },
150
+ });
151
+ console.log("sendPayment outcome:", outcome.status, outcome.hash ?? "");
152
+
153
+ const result = await Promise.race([
154
+ anchored,
155
+ new Promise((_, rej) => setTimeout(() => rej(new Error("No anchor within 60 s.")), 60000)),
156
+ ]);
157
+ stop();
158
+
159
+ console.log("\n=== RESULT ===");
160
+ console.log("tx hash:", outcome.hash);
161
+ console.log("check it:", `${HORIZON}/transactions/${outcome.hash}`);
162
+ console.log("anchor response:", JSON.stringify(result));
163
+ }
164
+
165
+ main().catch((e) => {
166
+ console.error("FAILED:", e?.message ?? e);
167
+ process.exit(1);
168
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-pollar-adapter",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Nirium adapter for the Pollar SDK — x402 pay-per-request and IPFS audit anchoring using the wallet a user onboarded through Pollar. Signs SEP-43 auth entries; the facilitator sponsors network fees. Includes Deferred-mode wallet activation (POST /v1/wallets/activate).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -9,19 +9,23 @@
9
9
  "dist",
10
10
  "examples"
11
11
  ],
12
+ "engines": {
13
+ "node": ">=22.12.0"
14
+ },
12
15
  "scripts": {
13
16
  "build": "tsc -p tsconfig.json",
14
- "typecheck": "tsc -p tsconfig.json --noEmit",
15
- "test": "npm run build && node --test test/*.test.mjs"
17
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.contract.json",
18
+ "test": "npm run build && node --test test/*.test.mjs",
19
+ "prepublishOnly": "npm run build"
16
20
  },
17
21
  "dependencies": {
18
- "@stellar/stellar-sdk": "^14.0.0",
19
- "@x402/core": "2.17.0",
20
- "@x402/fetch": "2.17.0",
21
- "@x402/stellar": "2.17.0"
22
+ "@stellar/stellar-sdk": "^16.4.1",
23
+ "@x402/core": "2.29.0",
24
+ "@x402/fetch": "2.29.0",
25
+ "@x402/stellar": "2.29.0"
22
26
  },
23
27
  "peerDependencies": {
24
- "@pollar/core": ">=0.11.0"
28
+ "@pollar/core": ">=0.11.4 <0.13.0"
25
29
  },
26
30
  "peerDependenciesMeta": {
27
31
  "@pollar/core": {
@@ -29,7 +33,8 @@
29
33
  }
30
34
  },
31
35
  "devDependencies": {
32
- "@types/node": "^20.19.0",
36
+ "@pollar/core": "0.12.0",
37
+ "@types/node": "^26.6.6",
33
38
  "typescript": "^5.7.0"
34
39
  },
35
40
  "keywords": [