nirium-pollar-adapter 0.5.0 → 0.6.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 +100 -57
- package/dist/index.d.ts +23 -2
- package/dist/index.js +46 -5
- package/examples/pay-with-keypair.mjs +9 -4
- package/examples/spike-19/anchor-on-success.mjs +168 -0
- package/package.json +14 -9
package/README.md
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
# nirium-pollar-adapter
|
|
2
2
|
|
|
3
|
-
Nirium adapter for the [Pollar](https://pollar.xyz) SDK
|
|
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
5
|
Both surfaces are **software-only and non-custodial**, and both are **live on Stellar mainnet**.
|
|
6
6
|
|
|
7
|
-
Wraps [`nirium`](https://github.com/nirium-protocol/nirium), the TypeScript/Python SDK this adapter signs for
|
|
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.
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
12
|
npm install nirium-pollar-adapter
|
|
13
|
-
# optional peer, only for createPollarSigner: @pollar/core >= 0.
|
|
13
|
+
# optional peer, only for createPollarSigner: @pollar/core >=0.11.4 <0.13.0
|
|
14
14
|
```
|
|
15
15
|
|
|
16
16
|
## Quickstart
|
|
@@ -34,13 +34,13 @@ const res = await nirium.x402Fetch(
|
|
|
34
34
|
const data = await res.json();
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
The user pays **$0.05 USDC** and signs nothing else
|
|
37
|
+
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
38
|
|
|
39
|
-
### Requires @pollar/core 0.11+
|
|
39
|
+
### Requires @pollar/core 0.11.4+
|
|
40
40
|
|
|
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.
|
|
41
|
+
`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
42
|
|
|
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
|
|
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.
|
|
44
44
|
|
|
45
45
|
```ts
|
|
46
46
|
const signer = createPollarSigner(pollar, {
|
|
@@ -53,17 +53,23 @@ Check at runtime before enabling a pay button:
|
|
|
53
53
|
|
|
54
54
|
```ts
|
|
55
55
|
import { canSignX402 } from "nirium-pollar-adapter";
|
|
56
|
-
<button disabled={!canSignX402(pollar)}>Pay $0.
|
|
56
|
+
<button disabled={!canSignX402(pollar)}>Pay $0.05</button>
|
|
57
57
|
```
|
|
58
58
|
|
|
59
59
|
## Verify it end-to-end today
|
|
60
60
|
|
|
61
|
-
The signer is pluggable, so you can prove the whole path works with a plain Stellar keypair
|
|
61
|
+
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
62
|
|
|
63
63
|
```bash
|
|
64
64
|
NIRIUM_DEMO_SECRET=S… node examples/pay-with-keypair.mjs
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
+
Against mainnet (spends real USDC, $0.05 per call), opt in explicitly:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
NIRIUM_DEMO_SECRET=S… NIRIUM_NETWORK=stellar:pubnet node examples/pay-with-keypair.mjs
|
|
71
|
+
```
|
|
72
|
+
|
|
67
73
|
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
74
|
|
|
69
75
|
Swapping to a Pollar wallet is one line:
|
|
@@ -74,53 +80,57 @@ Swapping to a Pollar wallet is one line:
|
|
|
74
80
|
```
|
|
75
81
|
|
|
76
82
|
**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
|
-
|
|
80
|
-
|
|
81
|
-
source. The user never saw a key, a seed phrase or a gas prompt.
|
|
83
|
+
2026):** a user who signed in with Google paid $0.02 USDC on mainnet
|
|
84
|
+
([`e4fa3df9…`](https://stellar.expert/explorer/public/tx/e4fa3df9cb225a4d7f64dd0082eb38218ada4b4af3378f288989a5d4b1116ed9))
|
|
85
|
+
while holding **zero XLM** at every point. Pollar sponsors the account reserve
|
|
86
|
+
and the trustline. The x402 facilitator sponsors the network fee and is the
|
|
87
|
+
transaction source. The user never saw a key, a seed phrase or a gas prompt.
|
|
82
88
|
|
|
83
89
|
Both proofs above paid `/premium/signals` ($0.02). Since 6-Aug-2026 that
|
|
84
|
-
endpoint is **testnet only
|
|
90
|
+
endpoint is **testnet only**: the mainnet agent box runs no autonomous loop,
|
|
85
91
|
so a capability guard now returns 501 before any charge. The example above
|
|
86
92
|
pays `/premium/market` ($0.05) instead, which has no such guard and still
|
|
87
|
-
settles on mainnet today
|
|
88
|
-
just no longer reproducible
|
|
93
|
+
settles on mainnet today. The two linked transactions remain real; they are
|
|
94
|
+
just no longer reproducible word for word with the current example.
|
|
89
95
|
|
|
90
96
|
## Deferred funding (Pollar "Deferred mode")
|
|
91
97
|
|
|
92
98
|
If your Pollar app's **Dashboard → Treasury → Funding Mode** is set to
|
|
93
|
-
**Deferred**,
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
99
|
+
**Deferred**, Pollar does not create the account on-chain at login. Your
|
|
100
|
+
backend creates it by calling `POST /v3/wallets/fund`. Checked on testnet on
|
|
101
|
+
2026-10-31: for a wallet that did not exist yet (Horizon returned 404), the
|
|
102
|
+
call returned 200 with `startingBalance: "0"`, and Horizon then showed the
|
|
103
|
+
account with 0 XLM and its reserves sponsored by Pollar. So "funding" here
|
|
104
|
+
means creating the account with sponsored reserves, not sending XLM to it.
|
|
105
|
+
|
|
106
|
+
You often do not need it for x402. A wallet at 0 XLM can sign and settle a
|
|
107
|
+
real x402 payment (see the section above: Pollar sponsors the reserve and
|
|
108
|
+
the default trustline, and the facilitator sponsors the network fee). Call
|
|
109
|
+
`activateWallet()` when your app needs the account to exist on-chain before
|
|
110
|
+
that first payment, or to match what Pollar's dashboard considers
|
|
111
|
+
"activated."
|
|
102
112
|
|
|
103
113
|
```ts
|
|
104
114
|
import { activateWallet } from "nirium-pollar-adapter";
|
|
105
115
|
|
|
106
|
-
// Server-side only (Next.js API route, Express handler, webhook)
|
|
107
|
-
// call this from the browser
|
|
116
|
+
// Server-side only (Next.js API route, Express handler, webhook). Never
|
|
117
|
+
// call this from the browser: it requires the secret key.
|
|
108
118
|
const result = await activateWallet(wallet.address, {
|
|
109
119
|
secretKey: process.env.POLLAR_SECRET_KEY!, // sec_testnet_… / sec_mainnet_…
|
|
110
120
|
});
|
|
111
|
-
// { activated: true, amount: "
|
|
112
|
-
// { activated: false }
|
|
121
|
+
// { activated: true, amount: "0" } - funded now (amount = Pollar's startingBalance)
|
|
122
|
+
// { activated: false } - account already exists on-chain; safe, not an error
|
|
113
123
|
```
|
|
114
124
|
|
|
115
|
-
Calling it twice on an already-funded wallet does not throw
|
|
125
|
+
Calling it twice on an already-funded wallet does not throw. Pollar's own
|
|
116
126
|
docs call HTTP 409 "safe to ignore, treat as success," and `activateWallet`
|
|
117
127
|
returns `{ activated: false }` rather than raising. Anything else throws
|
|
118
128
|
`PollarActivationError` with the real `code` and HTTP `status` Pollar sent,
|
|
119
|
-
rather than assuming a fixed meaning per status number
|
|
120
|
-
pages
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
129
|
+
rather than assuming a fixed meaning per status number. The two Pollar docs
|
|
130
|
+
pages that describe this endpoint disagree on what several of the non-200/409
|
|
131
|
+
codes mean (402 vs. 403, 503 vs. 502 for what reads like the same failure),
|
|
132
|
+
so this adapter passes on what the server actually said instead of picking
|
|
133
|
+
one doc to trust.
|
|
124
134
|
|
|
125
135
|
## API
|
|
126
136
|
|
|
@@ -128,7 +138,7 @@ instead of picking one doc to trust.
|
|
|
128
138
|
|
|
129
139
|
| Option | Default | |
|
|
130
140
|
|---|---|---|
|
|
131
|
-
| `signer` |
|
|
141
|
+
| `signer` | - | SEP-43 signer. Only `address` and `signAuthEntry` are required |
|
|
132
142
|
| `network` | `stellar:testnet` | `stellar:testnet` or `stellar:pubnet` |
|
|
133
143
|
| `agentBaseUrl` | box for the network | Nirium agent base URL |
|
|
134
144
|
| `rpcUrl` | public RPC for the network | Soroban RPC |
|
|
@@ -136,11 +146,11 @@ instead of picking one doc to trust.
|
|
|
136
146
|
|
|
137
147
|
Returns:
|
|
138
148
|
|
|
139
|
-
- **`x402Fetch(url, init?)
|
|
140
|
-
- **`getPremiumSignals()
|
|
141
|
-
- **`getPremiumMarket()
|
|
142
|
-
- **`anchorAuditRecord({ hash?, record?, txHash?, tag? })
|
|
143
|
-
- **`getCetesRate()
|
|
149
|
+
- **`x402Fetch(url, init?)`**: fetch that pays on `402` and retries. Passes through untouched on `200`.
|
|
150
|
+
- **`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.
|
|
151
|
+
- **`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.
|
|
152
|
+
- **`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.
|
|
153
|
+
- **`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
154
|
|
|
145
155
|
### `createPollarSigner(pollarClient, opts?)`
|
|
146
156
|
|
|
@@ -156,35 +166,54 @@ Wraps a Pollar client as a SEP-43 `ClientStellarSigner`.
|
|
|
156
166
|
**`signAuthEntry` means two different things, and this is what translates them.**
|
|
157
167
|
|
|
158
168
|
`stellar-sdk` (`AssembledTransaction.signAuthEntries` → `authorizeEntry`) hands
|
|
159
|
-
the signer a **`HashIdPreimage`**
|
|
169
|
+
the signer a **`HashIdPreimage`** (the thing about to be hashed) and expects
|
|
160
170
|
the **raw signature** back; it assembles the final entry itself. Pollar's
|
|
161
171
|
`POST /tx/sign-auth-entry` expects the full **`SorobanAuthorizationEntry`** and
|
|
162
|
-
returns the **signed entry**, because its backend
|
|
172
|
+
returns the **signed entry**, because its backend checks the invocation tree
|
|
163
173
|
against your Auth Policy allowlist before signing, and a hash would tell it
|
|
164
174
|
nothing. Both designs are right; they are just not the same one.
|
|
165
175
|
|
|
166
|
-
Without translation Pollar answers `SOROBAN_AUTH_ENTRY_INVALID
|
|
176
|
+
Without translation Pollar answers `SOROBAN_AUTH_ENTRY_INVALID - "entryXdr is
|
|
167
177
|
not a valid SorobanAuthorizationEntry"`, which reads like a corrupt XDR when the
|
|
168
|
-
XDR is fine and
|
|
178
|
+
XDR is fine and simply of another type.
|
|
169
179
|
|
|
170
|
-
The preimage carries nonce, expiry and invocation
|
|
171
|
-
|
|
172
|
-
|
|
180
|
+
The preimage carries nonce, expiry and invocation. The only extra thing the
|
|
181
|
+
entry needs is the signer address, which we have, so the rebuilt entry is exact
|
|
182
|
+
and the hash Pollar signs is byte-identical to the one the SDK expects.
|
|
173
183
|
The expiry is taken **from the preimage**, never from the clock: it lives inside
|
|
174
184
|
the signed hash, so asking Pollar for a different one would yield a signature
|
|
175
185
|
that does not validate.
|
|
176
186
|
|
|
177
187
|
### `activateWallet(publicKey, options)`
|
|
178
188
|
|
|
179
|
-
|
|
189
|
+
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
190
|
|
|
181
191
|
| Option | Default | |
|
|
182
192
|
|---|---|---|
|
|
183
|
-
| `secretKey` |
|
|
184
|
-
| `baseUrl` | `https://api.pollar.xyz` | Pollar Server base URL |
|
|
193
|
+
| `secretKey` | - | `sec_testnet_…` / `sec_mainnet_…`. Never expose this client-side |
|
|
194
|
+
| `baseUrl` | `https://server.api.pollar.xyz` | Pollar Server base URL |
|
|
185
195
|
| `fetchImpl` | global `fetch` | for tests or runtimes without global fetch |
|
|
186
196
|
|
|
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.
|
|
197
|
+
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.
|
|
198
|
+
|
|
199
|
+
### `anchorOnTransactionSuccess(pollarClient, adapter, options?)`
|
|
200
|
+
|
|
201
|
+
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.
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
import { createNiriumAdapter, anchorOnTransactionSuccess } from "nirium-pollar-adapter";
|
|
205
|
+
|
|
206
|
+
const adapter = createNiriumAdapter({ signer });
|
|
207
|
+
const stop = anchorOnTransactionSuccess(pollar, adapter, {
|
|
208
|
+
onError: (err, hash) => console.error("anchor failed", hash, err),
|
|
209
|
+
});
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
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`.
|
|
213
|
+
|
|
214
|
+
Checked against `@pollar/core` 0.11.4 and 0.12.0 in the test suite.
|
|
215
|
+
|
|
216
|
+
**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
217
|
|
|
189
218
|
### Paying from a browser
|
|
190
219
|
|
|
@@ -204,16 +233,30 @@ Pollar side: allowlist the USDC SAC with the `transfer` function under
|
|
|
204
233
|
**Treasury → Auth Policy**. Until a contract is listed, every custodial signing
|
|
205
234
|
request is rejected.
|
|
206
235
|
|
|
236
|
+
## How this relates to Pollar's `AdapterFn` pattern
|
|
237
|
+
|
|
238
|
+
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`).
|
|
239
|
+
|
|
240
|
+
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.
|
|
241
|
+
|
|
242
|
+
In practice:
|
|
243
|
+
|
|
244
|
+
- You use `createNiriumAdapter` directly. It is not registered under `PollarProvider adapters`, and there is no `createPollarAdapterHook` hook for it.
|
|
245
|
+
- 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.
|
|
246
|
+
- 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.
|
|
247
|
+
|
|
248
|
+
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.
|
|
249
|
+
|
|
207
250
|
## Scope
|
|
208
251
|
|
|
209
252
|
| | |
|
|
210
253
|
|---|---|
|
|
211
254
|
| x402 Settlement | ✅ mainnet |
|
|
212
255
|
| Audit Trail (IPFS) | ✅ mainnet |
|
|
213
|
-
| Treasury vault (DeFindex, client-owned)
|
|
214
|
-
| Treasury vault
|
|
215
|
-
| Nirium's own NiriumVault | audit-gated
|
|
216
|
-
| MPP session channels | audit-gated
|
|
256
|
+
| Treasury vault (DeFindex, client-owned), Nirium signs and executes | ✅ mainnet, invite-only during legal review |
|
|
257
|
+
| Treasury vault, propose only, you sign | ✅ mainnet, public, no invite required (`POST /api/treasury/rebalance/propose`, not yet wrapped by this adapter) |
|
|
258
|
+
| Nirium's own NiriumVault | audit-gated, testnet only |
|
|
259
|
+
| MPP session channels | audit-gated, testnet only |
|
|
217
260
|
|
|
218
261
|
Nirium never holds customer funds. The user's signature is the authorization; regulated partners execute any financial settlement.
|
|
219
262
|
|
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 /
|
|
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 /
|
|
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}/
|
|
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
|
-
|
|
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
|
-
//
|
|
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:
|
|
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.
|
|
3
|
+
"version": "0.6.0",
|
|
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": "^
|
|
19
|
-
"@x402/core": "2.
|
|
20
|
-
"@x402/fetch": "2.
|
|
21
|
-
"@x402/stellar": "2.
|
|
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
|
-
"@
|
|
36
|
+
"@pollar/core": "0.11.4",
|
|
37
|
+
"@types/node": "^26.6.5",
|
|
33
38
|
"typescript": "^5.7.0"
|
|
34
39
|
},
|
|
35
40
|
"keywords": [
|