nirium-pollar-adapter 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Nirium Protocol Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -4,6 +4,8 @@ Nirium adapter for the [Pollar](https://pollar.xyz) SDK — let the wallet a use
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 — see that repo for the full API this exposes through a Pollar wallet instead of a raw keypair.
8
+
7
9
  ## Install
8
10
 
9
11
  ```bash
@@ -85,6 +87,41 @@ pays `/premium/market` ($0.05) instead, which has no such guard and still
85
87
  settles on mainnet today; the two linked transactions remain real, they are
86
88
  just no longer reproducible verbatim with the current example.
87
89
 
90
+ ## Deferred funding (Pollar "Deferred mode")
91
+
92
+ 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."
102
+
103
+ ```ts
104
+ import { activateWallet } from "nirium-pollar-adapter";
105
+
106
+ // Server-side only (Next.js API route, Express handler, webhook) — never
107
+ // call this from the browser, it requires the secret key.
108
+ const result = await activateWallet(wallet.address, {
109
+ secretKey: process.env.POLLAR_SECRET_KEY!, // sec_testnet_… / sec_mainnet_…
110
+ });
111
+ // { activated: true, amount: "1.5" } — funded now
112
+ // { activated: false } — was already funded; safe, not an error
113
+ ```
114
+
115
+ Calling it twice on an already-funded wallet does not throw — Pollar's own
116
+ docs call HTTP 409 "safe to ignore, treat as success," and `activateWallet`
117
+ returns `{ activated: false }` rather than raising. Anything else throws
118
+ `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.
124
+
88
125
  ## API
89
126
 
90
127
  ### `createNiriumAdapter(config)`
@@ -137,6 +174,18 @@ The expiry is taken **from the preimage**, never from the clock: it lives inside
137
174
  the signed hash, so asking Pollar for a different one would yield a signature
138
175
  that does not validate.
139
176
 
177
+ ### `activateWallet(publicKey, options)`
178
+
179
+ Funds a Pollar wallet's on-chain XLM reserve (`POST /v1/wallets/activate`). **Server-side only.**
180
+
181
+ | Option | Default | |
182
+ |---|---|---|
183
+ | `secretKey` | — | `sec_testnet_…` / `sec_mainnet_…`. Never expose this client-side |
184
+ | `baseUrl` | `https://api.pollar.xyz` | Pollar Server base URL |
185
+ | `fetchImpl` | global `fetch` | for tests or runtimes without global fetch |
186
+
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.
188
+
140
189
  ### Paying from a browser
141
190
 
142
191
  Three server-side settings are not optional, and all three fail with messages
@@ -170,4 +219,4 @@ Nirium never holds customer funds. The user's signature is the authorization; re
170
219
 
171
220
  ## License
172
221
 
173
- MIT
222
+ Apache-2.0: see [LICENSE](./LICENSE).
package/dist/index.d.ts CHANGED
@@ -64,6 +64,45 @@ export interface PollarSignerOptions {
64
64
  export declare function createPollarSigner(pollar: PollarLikeClient, opts?: PollarSignerOptions): ClientStellarSigner;
65
65
  /** ¿Este signer ya puede pagar? Útil para deshabilitar el botón en la UI. */
66
66
  export declare function canSignX402(pollar: PollarLikeClient): boolean;
67
+ export interface ActivateWalletOptions {
68
+ /** Secret key de Pollar (sec_testnet_… / sec_mainnet_…). SOLO backend — nunca la mandes al navegador. */
69
+ secretKey: string;
70
+ /** Base URL del servidor de Pollar. Default: https://api.pollar.xyz. */
71
+ baseUrl?: string;
72
+ /** fetch a envolver (para tests o runtimes sin fetch global). */
73
+ fetchImpl?: typeof fetch;
74
+ }
75
+ export interface ActivateWalletResult {
76
+ /** `true` si esta llamada fondeó la reserva; `false` si ya estaba fondeada (idempotente, HTTP 409). */
77
+ activated: boolean;
78
+ /** Reserva de XLM fondeada, tal como la reporta Pollar. Solo viene cuando `activated` es `true` en esta llamada. */
79
+ amount?: string;
80
+ }
81
+ /** Pollar rechazó la activación con un código que no es "ya estaba activa". */
82
+ export declare class PollarActivationError extends Error {
83
+ /** El `code` que mandó Pollar (p.ej. "WALLET_NOT_FOUND", "FORBIDDEN"), o "UNKNOWN" si no vino. */
84
+ readonly code: string;
85
+ /** El status HTTP real de la respuesta. */
86
+ readonly status: number;
87
+ constructor(message: string,
88
+ /** El `code` que mandó Pollar (p.ej. "WALLET_NOT_FOUND", "FORBIDDEN"), o "UNKNOWN" si no vino. */
89
+ code: string,
90
+ /** El status HTTP real de la respuesta. */
91
+ status: number);
92
+ }
93
+ /**
94
+ * 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
96
+ * nunca debe llegar al navegador.
97
+ *
98
+ * Cuándo llamarla: no hay un "evento de negocio" natural en un flujo x402 puro
99
+ * como si lo hay en KYC — el disparador razonable es justo después del login,
100
+ * antes de mostrar el botón de pago, para que la primera petición del usuario
101
+ * no se tope con una cuenta a medio activar. Si tu app ya cobra sin problema
102
+ * con la wallet a 0 XLM (el caso común, ver la nota arriba), puedes no
103
+ * llamarla nunca; queda disponible para cuando sí la necesites.
104
+ */
105
+ export declare function activateWallet(publicKey: string, options: ActivateWalletOptions): Promise<ActivateWalletResult>;
67
106
  export interface NiriumAdapterConfig {
68
107
  /** Signer SEP-43 — normalmente createPollarSigner(pollarClient). */
69
108
  signer: ClientStellarSigner;
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@
30
30
  // ───────────────────────────────────────────────────────────────────────────
31
31
  import { x402Client as X402ClientClass, wrapFetchWithPayment } from "@x402/fetch";
32
32
  import { ExactStellarScheme } from "@x402/stellar/exact/client";
33
- import { Address, rpc, xdr } from "@stellar/stellar-sdk";
33
+ import { Address, StrKey, rpc, xdr } from "@stellar/stellar-sdk";
34
34
  const DEFAULTS = {
35
35
  network: "stellar:testnet",
36
36
  testnetAgent: "https://nirium-agent.fly.dev",
@@ -209,6 +209,62 @@ export function createPollarSigner(pollar, opts = {}) {
209
209
  export function canSignX402(pollar) {
210
210
  return typeof pollar.signAuthEntry === "function";
211
211
  }
212
+ /** Pollar rechazó la activación con un código que no es "ya estaba activa". */
213
+ export class PollarActivationError extends Error {
214
+ code;
215
+ status;
216
+ constructor(message,
217
+ /** El `code` que mandó Pollar (p.ej. "WALLET_NOT_FOUND", "FORBIDDEN"), o "UNKNOWN" si no vino. */
218
+ code,
219
+ /** El status HTTP real de la respuesta. */
220
+ status) {
221
+ super(message);
222
+ this.code = code;
223
+ this.status = status;
224
+ this.name = "PollarActivationError";
225
+ }
226
+ }
227
+ /**
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
230
+ * nunca debe llegar al navegador.
231
+ *
232
+ * Cuándo llamarla: no hay un "evento de negocio" natural en un flujo x402 puro
233
+ * como si lo hay en KYC — el disparador razonable es justo después del login,
234
+ * antes de mostrar el botón de pago, para que la primera petición del usuario
235
+ * no se tope con una cuenta a medio activar. Si tu app ya cobra sin problema
236
+ * con la wallet a 0 XLM (el caso común, ver la nota arriba), puedes no
237
+ * llamarla nunca; queda disponible para cuando sí la necesites.
238
+ */
239
+ export async function activateWallet(publicKey, options) {
240
+ if (!StrKey.isValidEd25519PublicKey(publicKey)) {
241
+ throw new Error(`activateWallet: "${publicKey}" no es una dirección Stellar G... válida.`);
242
+ }
243
+ const baseUrl = (options.baseUrl ?? "https://api.pollar.xyz").replace(/\/+$/, "");
244
+ const doFetch = options.fetchImpl ?? fetch;
245
+ const res = await doFetch(`${baseUrl}/v1/wallets/activate`, {
246
+ method: "POST",
247
+ headers: {
248
+ "content-type": "application/json",
249
+ "x-pollar-api-key": options.secretKey,
250
+ },
251
+ body: JSON.stringify({ publicKey }),
252
+ });
253
+ let body = {};
254
+ try {
255
+ body = await res.json();
256
+ }
257
+ catch {
258
+ // Cuerpo vacío o no-JSON — se maneja abajo con el status solo.
259
+ }
260
+ if (res.status === 200 && body?.success) {
261
+ return { activated: true, amount: body.content?.amount };
262
+ }
263
+ if (res.status === 409) {
264
+ return { activated: false };
265
+ }
266
+ throw new PollarActivationError(`Pollar rechazó la activación de ${publicKey}: HTTP ${res.status} ${body?.code ?? "(sin código)"}`, body?.code ?? "UNKNOWN", res.status);
267
+ }
212
268
  export function createNiriumAdapter(config) {
213
269
  const network = config.network ?? DEFAULTS.network;
214
270
  const agentBaseUrl = (config.agentBaseUrl ??
@@ -0,0 +1,46 @@
1
+ // Side-effect-only module. Must be the FIRST import in spike.mjs.
2
+ //
3
+ // @pollar/core computes `isBrowser = typeof window !== "undefined" && typeof
4
+ // localStorage !== "undefined"` as a module-level `var`, evaluated once when
5
+ // the module is first loaded — not re-checked per call. ES module `import`
6
+ // declarations are hoisted and all execute before the rest of a file's body,
7
+ // regardless of where `globalThis.window = ...` is textually written in that
8
+ // same file — so setting the globals inline above a static
9
+ // `import { PollarClient } from "@pollar/core"` has no effect: the import
10
+ // already ran first. A separate module, imported before @pollar/core (static
11
+ // imports run in the order they're written relative to each other), is what
12
+ // actually gets the globals in place before @pollar/core's module body runs.
13
+ // Pollar's publishable keys are domain-restricted: their backend checks the
14
+ // request's Origin header against an allowlist and returns 403
15
+ // ORIGIN_NOT_ALLOWED otherwise (confirmed against the real API below, not
16
+ // assumed). A real browser attaches Origin automatically on every
17
+ // cross-origin fetch; Node's fetch does not, and there's no PollarClient
18
+ // config knob to set it — so the fix has to be a global fetch monkey-patch
19
+ // that adds it only for calls to Pollar's own API host.
20
+ const ORIGIN = process.env.POLLAR_ORIGIN || "https://nirium.xyz";
21
+ const realFetch = globalThis.fetch;
22
+ globalThis.fetch = (input, init = {}) => {
23
+ const url = typeof input === "string" ? input : input?.url ?? String(input);
24
+ if (url.includes(".pollar.xyz")) {
25
+ const headers = new Headers(init.headers ?? (typeof input === "object" ? input.headers : undefined));
26
+ headers.set("Origin", ORIGIN);
27
+ init = { ...init, headers };
28
+ }
29
+ return realFetch(input, init);
30
+ };
31
+
32
+ globalThis.window = globalThis.window ?? {
33
+ // Used for the visibilitychange-driven token-refresh scheduler. A no-op
34
+ // is fine here — this script is a single short-lived run, not a long-lived
35
+ // tab that needs to catch up on missed background refreshes.
36
+ addEventListener: () => {},
37
+ removeEventListener: () => {},
38
+ };
39
+ if (typeof globalThis.localStorage === "undefined") {
40
+ const backing = new Map();
41
+ globalThis.localStorage = {
42
+ getItem: (k) => backing.get(k) ?? null,
43
+ setItem: (k, v) => void backing.set(k, String(v)),
44
+ removeItem: (k) => void backing.delete(k),
45
+ };
46
+ }
@@ -0,0 +1,146 @@
1
+ // Spike for pollar-apps#19 — "Nirium adapter: pay per API request with a
2
+ // Pollar account (x402) and ship demo.pollar.xyz/adapters/nirium".
3
+ //
4
+ // Blocking criterion from the issue: one Pollar social-login session,
5
+ // createPollarSigner() from nirium-pollar-adapter, one x402 request paid
6
+ // and settled against an x402-enabled endpoint, transaction hash captured.
7
+ //
8
+ // Rewritten against the REAL @pollar/core@0.11.2 API, verified against its
9
+ // .d.ts before writing a line of this: PollarClient's auth surface is
10
+ // event-driven (sendEmailCode/verifyEmailCode return void, not Promise) —
11
+ // state comes through onAuthStateChange(cb) as a discriminated union keyed
12
+ // by `step` (idle → sending_email → entering_code → verifying_email_code →
13
+ // authenticating → authenticated | error). The previous version of this
14
+ // script assumed a Promise-returning login()/verifyEmailCode() pair that
15
+ // does not exist in the installed SDK and would have hung or thrown.
16
+ //
17
+ // Still not fully scriptable: a human has to read the 6-digit code from
18
+ // their inbox. This version doesn't block on stdin (there's no live
19
+ // terminal attached when run in the background) — it polls a code file
20
+ // instead, so the OTP can be dropped in from a separate step once it
21
+ // arrives by email.
22
+ //
23
+ // Run with: node spike.mjs
24
+ //
25
+ // Env required (get PUB_KEY from https://dashboard.pollar.xyz → Build → API Keys):
26
+ // POLLAR_PUBLISHABLE_KEY=pub_testnet_...
27
+ // POLLAR_LOGIN_EMAIL=you@example.com
28
+ // POLLAR_CODE_FILE=/tmp/pollar-otp-code.txt (optional, this is the default)
29
+
30
+ // Must be the first import — see browser-polyfill.mjs for why this can't
31
+ // just be inline code above the @pollar/core import in this same file.
32
+ import "./browser-polyfill.mjs";
33
+
34
+ import { PollarClient, createMemoryAdapter } from "@pollar/core";
35
+ import { createPollarSigner, createNiriumAdapter } from "../../dist/index.js";
36
+ import { readFile, unlink } from "node:fs/promises";
37
+
38
+ const CODE_FILE = process.env.POLLAR_CODE_FILE || "/tmp/pollar-otp-code.txt";
39
+ const CODE_POLL_TIMEOUT_MS = 5 * 60 * 1000; // 5 min to relay the OTP
40
+ const CODE_POLL_INTERVAL_MS = 2000;
41
+
42
+ /** Resolve once the auth state reaches `targetStep`, reject on `step: 'error'`. */
43
+ function waitForAuthStep(pollar, targetStep) {
44
+ return new Promise((resolve, reject) => {
45
+ const unsubscribe = pollar.onAuthStateChange((state) => {
46
+ console.log("[auth state]", state.step);
47
+ if (state.step === targetStep) {
48
+ unsubscribe();
49
+ resolve(state);
50
+ } else if (state.step === "error") {
51
+ unsubscribe();
52
+ reject(new Error(`Pollar auth error (was expecting "${targetStep}"): ${state.message} [${state.errorCode}]`));
53
+ }
54
+ });
55
+ });
56
+ }
57
+
58
+ /** Poll CODE_FILE until it has content, then delete it so a stale code can't be reused. */
59
+ async function waitForCodeFile() {
60
+ console.log(`Waiting for the 6-digit code in ${CODE_FILE} (write it there once you have it)...`);
61
+ const deadline = Date.now() + CODE_POLL_TIMEOUT_MS;
62
+ while (Date.now() < deadline) {
63
+ try {
64
+ const raw = (await readFile(CODE_FILE, "utf8")).trim();
65
+ if (raw) {
66
+ await unlink(CODE_FILE).catch(() => {});
67
+ return raw;
68
+ }
69
+ } catch {
70
+ // File doesn't exist yet — keep polling.
71
+ }
72
+ await new Promise((r) => setTimeout(r, CODE_POLL_INTERVAL_MS));
73
+ }
74
+ throw new Error(`Timed out after ${CODE_POLL_TIMEOUT_MS}ms waiting for ${CODE_FILE}`);
75
+ }
76
+
77
+ async function main() {
78
+ const apiKey = process.env.POLLAR_PUBLISHABLE_KEY;
79
+ const email = process.env.POLLAR_LOGIN_EMAIL;
80
+ if (!apiKey || !email) {
81
+ console.error("Set POLLAR_PUBLISHABLE_KEY and POLLAR_LOGIN_EMAIL first.");
82
+ process.exit(1);
83
+ }
84
+
85
+ const pollar = new PollarClient({
86
+ apiKey,
87
+ stellarNetwork: "testnet",
88
+ storage: createMemoryAdapter(),
89
+ });
90
+
91
+ await pollar.ready();
92
+
93
+ // sendEmailCode() throws PollarFlowError unless the current step is
94
+ // 'entering_email' — that step only exists after beginEmailLogin() runs
95
+ // (idle -> creating_session -> entering_email). Skipping straight to
96
+ // sendEmailCode() is the second bug the server-side no-op guard was
97
+ // masking in the previous version of this script.
98
+ console.log("Starting email login...");
99
+ const enteringEmail = waitForAuthStep(pollar, "entering_email");
100
+ pollar.beginEmailLogin();
101
+ await enteringEmail;
102
+
103
+ console.log(`Sending OTP to ${email}...`);
104
+ const enteringCode = waitForAuthStep(pollar, "entering_code");
105
+ pollar.sendEmailCode(email);
106
+ await enteringCode;
107
+
108
+ const code = await waitForCodeFile();
109
+
110
+ console.log("Verifying code...");
111
+ const authenticated = waitForAuthStep(pollar, "authenticated");
112
+ pollar.verifyEmailCode(code);
113
+ const authState = await authenticated;
114
+ console.log("Authenticated. verified:", authState.verified);
115
+
116
+ const signer = createPollarSigner(pollar, { network: "stellar:testnet" });
117
+ console.log("Signer address:", signer.address);
118
+
119
+ const nirium = createNiriumAdapter({
120
+ signer,
121
+ network: "stellar:testnet",
122
+ agentBaseUrl: "https://nirium-agent.fly.dev",
123
+ });
124
+
125
+ console.log("Requesting /api/v1/premium/signals (expect 402, then auto-pay + retry)...");
126
+ // Using x402Fetch directly (not the getPremiumSignals() shortcut) so we can
127
+ // inspect the raw response headers — the settlement tx hash comes from
128
+ // @x402/express's own machinery, not from Nirium's code, and the exact
129
+ // header name isn't pinned down anywhere in this repo. Log everything and
130
+ // find it empirically rather than guessing a header key.
131
+ const res = await nirium.x402Fetch(`${nirium.agentBaseUrl}/api/v1/premium/signals`);
132
+ console.log("Response status:", res.status);
133
+ console.log("Response headers:");
134
+ for (const [key, value] of res.headers.entries()) {
135
+ console.log(` ${key}: ${value}`);
136
+ }
137
+ const body = await res.json();
138
+ console.log("Body:", body);
139
+
140
+ console.log("Done. Find the settlement tx hash in the headers above, verify it resolves on stellar.expert before including it in the PR.");
141
+ }
142
+
143
+ main().catch((err) => {
144
+ console.error("Spike failed:", err);
145
+ process.exit(1);
146
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nirium-pollar-adapter",
3
- "version": "0.4.1",
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.",
3
+ "version": "0.5.0",
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",
7
7
  "types": "dist/index.d.ts",
@@ -11,7 +11,8 @@
11
11
  ],
12
12
  "scripts": {
13
13
  "build": "tsc -p tsconfig.json",
14
- "typecheck": "tsc -p tsconfig.json --noEmit"
14
+ "typecheck": "tsc -p tsconfig.json --noEmit",
15
+ "test": "npm run build && node --test test/*.test.mjs"
15
16
  },
16
17
  "dependencies": {
17
18
  "@stellar/stellar-sdk": "^14.0.0",
@@ -27,6 +28,10 @@
27
28
  "optional": true
28
29
  }
29
30
  },
31
+ "devDependencies": {
32
+ "@types/node": "^20.19.0",
33
+ "typescript": "^5.7.0"
34
+ },
30
35
  "keywords": [
31
36
  "nirium",
32
37
  "pollar",
@@ -36,5 +41,12 @@
36
41
  "adapter"
37
42
  ],
38
43
  "homepage": "https://nirium.xyz",
39
- "license": "MIT"
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/nirium-protocol/nirium-pollar-adapter.git"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/nirium-protocol/nirium-pollar-adapter/issues"
50
+ },
51
+ "license": "Apache-2.0"
40
52
  }