nirium-pollar-adapter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # nirium-pollar-adapter
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.
4
+
5
+ Both surfaces are **software-only and non-custodial**, and both are **live on Stellar mainnet**.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install nirium-pollar-adapter
11
+ # peer: @pollar/core
12
+ ```
13
+
14
+ ## Quickstart
15
+
16
+ ```ts
17
+ import { PollarClient } from "@pollar/core";
18
+ import { createPollarSigner, createNiriumAdapter } from "nirium-pollar-adapter";
19
+
20
+ const pollar = new PollarClient({ apiKey: "pub_mainnet_…" });
21
+ await pollar.login({ provider: "google" });
22
+
23
+ const nirium = createNiriumAdapter({
24
+ signer: createPollarSigner(pollar),
25
+ network: "stellar:pubnet",
26
+ });
27
+
28
+ // A normal fetch. The 402, the signature and the retry happen underneath.
29
+ const res = await nirium.x402Fetch(
30
+ "https://nirium-agent-mainnet.fly.dev/api/v1/premium/signals",
31
+ );
32
+ const data = await res.json();
33
+ ```
34
+
35
+ The user pays **$0.02 USDC** and signs nothing else — network fees are sponsored by the x402 facilitator, so the wallet does not need XLM for gas.
36
+
37
+ ### Status: waiting on one Pollar method
38
+
39
+ `createPollarSigner` needs `signAuthEntry` on `PollarClient`. Pollar already declares it on its `WalletAdapter` interface (Freighter and Albedo implement it), but it is not yet exposed on the client for embedded/passkey wallets. Until it ships, `createPollarSigner` throws an explanatory error and you can pass any other SEP-43 signer.
40
+
41
+ Check at runtime before enabling a pay button:
42
+
43
+ ```ts
44
+ import { canSignX402 } from "nirium-pollar-adapter";
45
+ <button disabled={!canSignX402(pollar)}>Pay $0.02</button>
46
+ ```
47
+
48
+ ## Verify it end-to-end today
49
+
50
+ The signer is pluggable, so you can prove the whole path works with a plain Stellar keypair — no Pollar required:
51
+
52
+ ```bash
53
+ NIRIUM_DEMO_SECRET=S… node examples/pay-with-keypair.mjs
54
+ ```
55
+
56
+ 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).
57
+
58
+ Swapping to a Pollar wallet is one line:
59
+
60
+ ```diff
61
+ - const signer = createEd25519Signer(secret, network);
62
+ + const signer = createPollarSigner(pollarClient);
63
+ ```
64
+
65
+ ## API
66
+
67
+ ### `createNiriumAdapter(config)`
68
+
69
+ | Option | Default | |
70
+ |---|---|---|
71
+ | `signer` | — | SEP-43 signer. Only `address` and `signAuthEntry` are required |
72
+ | `network` | `stellar:testnet` | `stellar:testnet` or `stellar:pubnet` |
73
+ | `agentBaseUrl` | box for the network | Nirium agent base URL |
74
+ | `rpcUrl` | public RPC for the network | Soroban RPC |
75
+ | `fetchImpl` | global `fetch` | for tests or runtimes without global fetch |
76
+
77
+ Returns:
78
+
79
+ - **`x402Fetch(url, init?)`** — fetch that pays on `402` and retries. Passes through untouched on `200`.
80
+ - **`getPremiumSignals()`** — typed shortcut to the agent's paid signals endpoint.
81
+ - **`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.
82
+ - **`getCetesRate()`** — public reference rate, no key required.
83
+
84
+ ### `createPollarSigner(pollarClient, opts?)`
85
+
86
+ Wraps a Pollar client as a SEP-43 `ClientStellarSigner`. Detection is at runtime, so it starts working the moment Pollar ships `signAuthEntry` — no version bump needed on your side.
87
+
88
+ ## Scope
89
+
90
+ | | |
91
+ |---|---|
92
+ | x402 Settlement | ✅ mainnet |
93
+ | Audit Trail (IPFS) | ✅ mainnet |
94
+ | Treasury / rebalance vault | audit-gated — testnet only |
95
+ | MPP session channels | audit-gated — testnet only |
96
+
97
+ Nirium never holds customer funds. The user's signature is the authorization; regulated partners execute any financial settlement.
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1,73 @@
1
+ import type { SignAuthEntry, SignTransaction } from "@stellar/stellar-sdk/contract";
2
+ export type StellarNetwork = "stellar:testnet" | "stellar:pubnet";
3
+ /**
4
+ * Signer SEP-43 que consume x402. `signTransaction` es opcional para clientes;
5
+ * lo único indispensable es `signAuthEntry`. Sirve igual para cuentas G y C.
6
+ */
7
+ export interface ClientStellarSigner {
8
+ address: string;
9
+ signAuthEntry: SignAuthEntry;
10
+ signTransaction?: SignTransaction;
11
+ }
12
+ /**
13
+ * Superficie mínima que necesitamos del cliente de Pollar. Se declara por
14
+ * duck-typing a propósito: @pollar/core sigue moviéndose y no queremos atarnos
15
+ * a una versión concreta.
16
+ */
17
+ export interface PollarLikeClient {
18
+ address?: string;
19
+ walletAddress?: string;
20
+ getAuthState?: () => {
21
+ walletAddress?: string;
22
+ address?: string;
23
+ } | undefined;
24
+ /** SEP-43. Aún no expuesto públicamente por Pollar — ver nota abajo. */
25
+ signAuthEntry?: SignAuthEntry;
26
+ signTransaction?: SignTransaction;
27
+ signTx?: (unsignedXdr: string) => Promise<unknown>;
28
+ }
29
+ export interface PollarSignerOptions {
30
+ /** Fuerza la dirección del pagador si el cliente aún no la expone. */
31
+ address?: string;
32
+ }
33
+ /**
34
+ * Envuelve un cliente de Pollar como signer SEP-43 para x402.
35
+ *
36
+ * El día que Pollar exponga `signAuthEntry` esto funciona sin cambios: la
37
+ * detección es en tiempo de ejecución, no en tiempo de compilación.
38
+ */
39
+ export declare function createPollarSigner(pollar: PollarLikeClient, opts?: PollarSignerOptions): ClientStellarSigner;
40
+ /** ¿Este signer ya puede pagar? Útil para deshabilitar el botón en la UI. */
41
+ export declare function canSignX402(pollar: PollarLikeClient): boolean;
42
+ export interface NiriumAdapterConfig {
43
+ /** Signer SEP-43 — normalmente createPollarSigner(pollarClient). */
44
+ signer: ClientStellarSigner;
45
+ /** CAIP-2. Default: stellar:testnet. */
46
+ network?: StellarNetwork;
47
+ /** Base URL del agente. Default: el box de la red elegida. */
48
+ agentBaseUrl?: string;
49
+ /** Soroban RPC. Default: público de la red elegida. */
50
+ rpcUrl?: string;
51
+ /** fetch a envolver (para tests o runtimes sin fetch global). */
52
+ fetchImpl?: typeof fetch;
53
+ }
54
+ export interface AuditAnchorInput {
55
+ /** sha-256 hex (64 chars), con o sin prefijo "sha-256:". */
56
+ hash?: string;
57
+ /** JSON pequeño (≤8KB). No metas datos personales: IPFS no se borra. */
58
+ record?: Record<string, unknown>;
59
+ txHash?: string;
60
+ tag?: string;
61
+ }
62
+ export declare function createNiriumAdapter(config: NiriumAdapterConfig): {
63
+ network: StellarNetwork;
64
+ agentBaseUrl: string;
65
+ address: string;
66
+ x402Fetch: (url: string, init?: RequestInit) => Promise<Response>;
67
+ getPremiumSignals: () => Promise<unknown>;
68
+ anchorAuditRecord: (input: AuditAnchorInput) => Promise<{
69
+ cid: string;
70
+ } & Record<string, unknown>>;
71
+ getCetesRate: () => Promise<number | null>;
72
+ };
73
+ export type NiriumAdapter = ReturnType<typeof createNiriumAdapter>;
package/dist/index.js ADDED
@@ -0,0 +1,164 @@
1
+ // ───────────────────────────────────────────────────────────────────────────
2
+ // nirium-pollar-adapter
3
+ //
4
+ // Adapter de Nirium para el SDK de Pollar. Expone los nodos software-only de
5
+ // Nirium (x402 Settlement + Audit Trail) a una app que ya usa Pollar para el
6
+ // onboarding, sin que la app maneje llaves ni entienda x402.
7
+ //
8
+ // import { PollarClient } from "@pollar/core";
9
+ // import { createPollarSigner, createNiriumAdapter } from "nirium-pollar-adapter";
10
+ //
11
+ // const pollar = new PollarClient({ apiKey });
12
+ // const nirium = createNiriumAdapter({
13
+ // signer: createPollarSigner(pollar),
14
+ // network: "stellar:pubnet",
15
+ // });
16
+ //
17
+ // // Un fetch normal. El 402, la firma y el reintento pasan por debajo.
18
+ // const res = await nirium.x402Fetch("https://nirium-agent-mainnet.fly.dev/api/v1/premium/signals");
19
+ // const data = await res.json();
20
+ //
21
+ // POR QUÉ ASÍ: x402 v2 NO es "manda una transferencia y enseña el hash". El
22
+ // cliente firma un *auth entry* de Soroban (SEP-43), lo manda en el header
23
+ // X-PAYMENT, y el facilitador verifica y liquida — patrocinando los fees
24
+ // (`areFeesSponsored: true` en el 402 de Nirium). Por eso aquí no armamos
25
+ // transacciones a mano: delegamos en @x402/fetch, igual que el SDK oficial.
26
+ //
27
+ // ALCANCE (regla de mainnet): x402 y Audit Trail son software-only y
28
+ // non-custodial → viven en mainnet hoy. El vault/rebalance y las sesiones MPP
29
+ // sostienen fondos de terceros → siguen audit-gated. Ver NiriumMainnet.md.
30
+ // ───────────────────────────────────────────────────────────────────────────
31
+ import { x402Client as X402ClientClass, wrapFetchWithPayment } from "@x402/fetch";
32
+ import { ExactStellarScheme } from "@x402/stellar/exact/client";
33
+ const DEFAULTS = {
34
+ network: "stellar:testnet",
35
+ testnetAgent: "https://nirium-agent.fly.dev",
36
+ pubnetAgent: "https://nirium-agent-mainnet.fly.dev",
37
+ testnetRpc: "https://soroban-testnet.stellar.org",
38
+ // El SDF no corre RPC público de mainnet: soroban.stellar.org NO existe.
39
+ pubnetRpc: "https://soroban-rpc.mainnet.stellar.gateway.fm",
40
+ };
41
+ const isPubnet = (n) => n === "stellar:pubnet";
42
+ const MISSING_SIGN_AUTH_ENTRY = "El cliente de Pollar no expone signAuthEntry(). x402 necesita firmar un auth " +
43
+ "entry de Soroban (SEP-43: signAuthEntry(authEntryXdr, { networkPassphrase, address })), " +
44
+ "no una transacción completa — signTx() no sirve para esto.\n\n" +
45
+ "Pollar YA firma auth entries por dentro para cuentas C (passkey); falta " +
46
+ "exponerlo en la API pública, igual que hace Freighter. Pedido abierto al " +
47
+ "equipo de Pollar. Mientras tanto puedes pasar tu propio signer a " +
48
+ "createNiriumAdapter({ signer }).";
49
+ /**
50
+ * Envuelve un cliente de Pollar como signer SEP-43 para x402.
51
+ *
52
+ * El día que Pollar exponga `signAuthEntry` esto funciona sin cambios: la
53
+ * detección es en tiempo de ejecución, no en tiempo de compilación.
54
+ */
55
+ export function createPollarSigner(pollar, opts = {}) {
56
+ const resolveAddress = () => {
57
+ const authState = pollar.getAuthState?.();
58
+ const address = opts.address ??
59
+ pollar.address ??
60
+ pollar.walletAddress ??
61
+ authState?.walletAddress ??
62
+ authState?.address;
63
+ if (!address) {
64
+ throw new Error("No hay wallet conectada en Pollar. Llama a login() antes de pagar, o " +
65
+ "pasa { address } a createPollarSigner().");
66
+ }
67
+ return address;
68
+ };
69
+ const signAuthEntry = async (authEntry, signOpts) => {
70
+ if (typeof pollar.signAuthEntry !== "function") {
71
+ throw new Error(MISSING_SIGN_AUTH_ENTRY);
72
+ }
73
+ return pollar.signAuthEntry(authEntry, {
74
+ address: resolveAddress(),
75
+ ...signOpts,
76
+ });
77
+ };
78
+ const signer = {
79
+ get address() {
80
+ return resolveAddress();
81
+ },
82
+ signAuthEntry,
83
+ };
84
+ // signTransaction es opcional para clientes x402; solo lo pasamos si existe.
85
+ if (typeof pollar.signTransaction === "function") {
86
+ signer.signTransaction = pollar.signTransaction.bind(pollar);
87
+ }
88
+ return signer;
89
+ }
90
+ /** ¿Este signer ya puede pagar? Útil para deshabilitar el botón en la UI. */
91
+ export function canSignX402(pollar) {
92
+ return typeof pollar.signAuthEntry === "function";
93
+ }
94
+ export function createNiriumAdapter(config) {
95
+ const network = config.network ?? DEFAULTS.network;
96
+ const agentBaseUrl = (config.agentBaseUrl ??
97
+ (isPubnet(network) ? DEFAULTS.pubnetAgent : DEFAULTS.testnetAgent)).replace(/\/$/, "");
98
+ const rpcUrl = config.rpcUrl ?? (isPubnet(network) ? DEFAULTS.pubnetRpc : DEFAULTS.testnetRpc);
99
+ const baseFetch = config.fetchImpl ?? fetch;
100
+ // El cliente x402 negocia el 402, firma el auth entry y reintenta solo.
101
+ const x402 = new X402ClientClass().register("stellar:*", new ExactStellarScheme(config.signer, { url: rpcUrl }));
102
+ const paidFetch = wrapFetchWithPayment(baseFetch, x402);
103
+ /**
104
+ * fetch con pago automático. Si el recurso responde 402, se paga y se
105
+ * reintenta; si responde 200, pasa directo. Los fees los patrocina el
106
+ * facilitador — la wallet del usuario no necesita XLM para el gas.
107
+ */
108
+ async function x402Fetch(url, init) {
109
+ return paidFetch(url, init);
110
+ }
111
+ /** Atajo tipado a los endpoints premium del agente. */
112
+ async function getPremiumSignals() {
113
+ const res = await x402Fetch(`${agentBaseUrl}/api/v1/premium/signals`);
114
+ if (!res.ok)
115
+ throw new Error(`premium/signals respondió HTTP ${res.status}`);
116
+ return res.json();
117
+ }
118
+ /**
119
+ * Ancla evidencia en IPFS (Audit Trail Node). Software-only: no firma, no
120
+ * mueve fondos, funciona en mainnet hoy. Se anclan HASHES, no PII.
121
+ */
122
+ async function anchorAuditRecord(input) {
123
+ const res = await baseFetch(`${agentBaseUrl}/api/audit/log`, {
124
+ method: "POST",
125
+ headers: { "content-type": "application/json" },
126
+ body: JSON.stringify({
127
+ ...input,
128
+ network: isPubnet(network) ? "mainnet" : "testnet",
129
+ }),
130
+ });
131
+ if (!res.ok) {
132
+ throw new Error(`audit/log respondió HTTP ${res.status}: ${await res.text()}`);
133
+ }
134
+ return res.json();
135
+ }
136
+ /**
137
+ * Tasa CETES de referencia (lectura pública, sin key ni pago).
138
+ * Sale de /api/tickers, que la publica en ambos boxes — /api/loop/status no
139
+ * sirve en mainnet porque ahí el loop autónomo está apagado.
140
+ */
141
+ async function getCetesRate() {
142
+ try {
143
+ const res = await baseFetch(`${agentBaseUrl}/api/tickers`, { cache: "no-store" });
144
+ const data = await res.json();
145
+ const rate = data?.market?.cetesRate;
146
+ return typeof rate === "number" ? rate : null;
147
+ }
148
+ catch {
149
+ return null;
150
+ }
151
+ }
152
+ return {
153
+ network,
154
+ agentBaseUrl,
155
+ address: config.signer.address,
156
+ // Settlement (x402) — mainnet
157
+ x402Fetch,
158
+ getPremiumSignals,
159
+ // Audit Trail — mainnet
160
+ anchorAuditRecord,
161
+ // Lecturas públicas
162
+ getCetesRate,
163
+ };
164
+ }
@@ -0,0 +1,49 @@
1
+ // ───────────────────────────────────────────────────────────────────────────
2
+ // Ejemplo: pagar un endpoint x402 de Nirium con una llave Stellar cualquiera.
3
+ //
4
+ // Sirve para verificar el adapter END-TO-END sin depender de Pollar: el signer
5
+ // es enchufable, así que aquí usamos un signer ed25519 estándar. El día que
6
+ // Pollar exponga signAuthEntry, se cambia UNA línea:
7
+ //
8
+ // - const signer = createEd25519Signer(secret, network);
9
+ // + const signer = createPollarSigner(pollarClient);
10
+ //
11
+ // Uso:
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
+ //
15
+ // OJO: contra stellar:pubnet esto gasta USDC REAL (0.02 por llamada a signals).
16
+ // ───────────────────────────────────────────────────────────────────────────
17
+
18
+ import { createEd25519Signer } from "@x402/stellar";
19
+ import { createNiriumAdapter } from "../dist/index.js";
20
+
21
+ const secret = process.env.NIRIUM_DEMO_SECRET;
22
+ if (!secret) {
23
+ console.error("Falta NIRIUM_DEMO_SECRET (llave secreta Stellar S...).");
24
+ process.exit(1);
25
+ }
26
+
27
+ const network = process.env.NIRIUM_NETWORK ?? "stellar:pubnet";
28
+ const signer = createEd25519Signer(secret, network);
29
+ const nirium = createNiriumAdapter({ signer, network });
30
+
31
+ console.log(`red : ${network}`);
32
+ console.log(`pagador : ${signer.address}`);
33
+ console.log(`agente : ${nirium.agentBaseUrl}`);
34
+
35
+ // 1) x402 — el 402, la firma del auth entry y el reintento pasan por debajo.
36
+ console.log("\n[1/2] pagando /api/v1/premium/signals (0.02 USDC)…");
37
+ const signals = await nirium.getPremiumSignals();
38
+ console.log(" OK — respuesta:", JSON.stringify(signals).slice(0, 220));
39
+
40
+ // 2) Audit Trail — software-only, sin firma ni pago.
41
+ console.log("\n[2/2] anclando evidencia en IPFS…");
42
+ const anchor = await nirium.anchorAuditRecord({
43
+ record: { source: "pollar-adapter-example", paidResource: "premium/signals", at: new Date().toISOString() },
44
+ tag: "adapter-e2e",
45
+ });
46
+ console.log(" OK — CID:", anchor.cid ?? JSON.stringify(anchor).slice(0, 200));
47
+
48
+ const rate = await nirium.getCetesRate();
49
+ console.log("\ntasa CETES de referencia:", rate ?? "n/d");
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "nirium-pollar-adapter",
3
+ "version": "0.1.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.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": ["dist", "examples"],
9
+ "scripts": {
10
+ "build": "tsc -p tsconfig.json",
11
+ "typecheck": "tsc -p tsconfig.json --noEmit"
12
+ },
13
+ "dependencies": {
14
+ "@stellar/stellar-sdk": "^14.0.0",
15
+ "@x402/core": "2.17.0",
16
+ "@x402/fetch": "2.17.0",
17
+ "@x402/stellar": "2.17.0"
18
+ },
19
+ "peerDependencies": {
20
+ "@pollar/core": "*"
21
+ },
22
+ "keywords": ["nirium", "pollar", "stellar", "soroban", "x402", "adapter"],
23
+ "license": "MIT"
24
+ }