nirium-pollar-adapter 0.1.0 → 0.3.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 CHANGED
@@ -8,7 +8,7 @@ Both surfaces are **software-only and non-custodial**, and both are **live on St
8
8
 
9
9
  ```bash
10
10
  npm install nirium-pollar-adapter
11
- # peer: @pollar/core
11
+ # optional peer, only for createPollarSigner: @pollar/core >= 0.11
12
12
  ```
13
13
 
14
14
  ## Quickstart
@@ -34,9 +34,18 @@ const data = await res.json();
34
34
 
35
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
36
 
37
- ### Status: waiting on one Pollar method
37
+ ### Requires @pollar/core 0.11+
38
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.
39
+ `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.
40
+
41
+ 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.
42
+
43
+ ```ts
44
+ const signer = createPollarSigner(pollar, {
45
+ network: "stellar:pubnet",
46
+ validityLedgers: 120, // ~10 min, the default
47
+ });
48
+ ```
40
49
 
41
50
  Check at runtime before enabling a pay button:
42
51
 
@@ -62,6 +71,13 @@ Swapping to a Pollar wallet is one line:
62
71
  + const signer = createPollarSigner(pollarClient);
63
72
  ```
64
73
 
74
+ **Verified with a real Pollar social login (5 Aug 2026):** a user who signed in
75
+ with Google paid $0.02 USDC on mainnet —
76
+ [`e4fa3df9…`](https://stellar.expert/explorer/public/tx/e4fa3df9cb225a4d7f64dd0082eb38218ada4b4af3378f288989a5d4b1116ed9)
77
+ — holding **zero XLM** at any point. Pollar sponsors the account reserve and the
78
+ trustline; the x402 facilitator sponsors the network fee and is the transaction
79
+ source. The user never saw a key, a seed phrase or a gas prompt.
80
+
65
81
  ## API
66
82
 
67
83
  ### `createNiriumAdapter(config)`
@@ -83,7 +99,53 @@ Returns:
83
99
 
84
100
  ### `createPollarSigner(pollarClient, opts?)`
85
101
 
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.
102
+ Wraps a Pollar client as a SEP-43 `ClientStellarSigner`.
103
+
104
+ | Option | Default | |
105
+ |---|---|---|
106
+ | `address` | read from the client's auth state | payer address, if you already have it |
107
+ | `network` | `stellar:testnet` | used to read the latest ledger |
108
+ | `rpcUrl` | public RPC for the network | Soroban RPC |
109
+ | `validityLedgers` | `120` (~10 min) | only used when you hand it an entry directly |
110
+
111
+ **`signAuthEntry` means two different things, and this is what translates them.**
112
+
113
+ `stellar-sdk` (`AssembledTransaction.signAuthEntries` → `authorizeEntry`) hands
114
+ the signer a **`HashIdPreimage`** — the thing about to be hashed — and expects
115
+ the **raw signature** back; it assembles the final entry itself. Pollar's
116
+ `POST /tx/sign-auth-entry` expects the full **`SorobanAuthorizationEntry`** and
117
+ returns the **signed entry**, because its backend validates the invocation tree
118
+ against your Auth Policy allowlist before signing, and a hash would tell it
119
+ nothing. Both designs are right; they are just not the same one.
120
+
121
+ Without translation Pollar answers `SOROBAN_AUTH_ENTRY_INVALID — "entryXdr is
122
+ not a valid SorobanAuthorizationEntry"`, which reads like a corrupt XDR when the
123
+ XDR is fine and merely of another type.
124
+
125
+ The preimage carries nonce, expiry and invocation; the only thing the entry
126
+ additionally needs is the signer address, which we have — so the reconstruction
127
+ is exact and the hash Pollar signs is byte-identical to the one the SDK expects.
128
+ The expiry is taken **from the preimage**, never from the clock: it lives inside
129
+ the signed hash, so asking Pollar for a different one would yield a signature
130
+ that does not validate.
131
+
132
+ ### Paying from a browser
133
+
134
+ Three server-side settings are not optional, and all three fail with messages
135
+ that point somewhere else:
136
+
137
+ | Needed | Otherwise |
138
+ |---|---|
139
+ | `Access-Control-Expose-Headers: PAYMENT-REQUIRED` | JS cannot read the terms → *"Failed to parse payment requirements"*, which reads as a bad signature |
140
+ | `Access-Control-Allow-Headers: PAYMENT-SIGNATURE` | the paid retry never leaves the browser |
141
+ | `Access-Control-Allow-Headers: Access-Control-Expose-Headers` | `@x402/fetch` sets that response header **on the request**; without permission the preflight fails |
142
+
143
+ Client side, `connect-src` must list the resource server, the Soroban RPC and
144
+ `sdk.api.pollar.xyz`.
145
+
146
+ Pollar side: allowlist the USDC SAC with the `transfer` function under
147
+ **Treasury → Auth Policy**. Until a contract is listed, every custodial signing
148
+ request is rejected.
87
149
 
88
150
  ## Scope
89
151
 
package/dist/index.d.ts CHANGED
@@ -9,6 +9,17 @@ export interface ClientStellarSigner {
9
9
  signAuthEntry: SignAuthEntry;
10
10
  signTransaction?: SignTransaction;
11
11
  }
12
+ /** Lo que devuelve `PollarClient.signAuthEntry` (@pollar/core ≥ 0.11). */
13
+ export type PollarSignAuthEntryOutcome = {
14
+ status: "signed";
15
+ signedAuthEntry: string;
16
+ } | {
17
+ status: "error";
18
+ details?: string;
19
+ } | {
20
+ signedAuthEntry: string;
21
+ signerAddress?: string;
22
+ };
12
23
  /**
13
24
  * Superficie mínima que necesitamos del cliente de Pollar. Se declara por
14
25
  * duck-typing a propósito: @pollar/core sigue moviéndose y no queremos atarnos
@@ -17,24 +28,38 @@ export interface ClientStellarSigner {
17
28
  export interface PollarLikeClient {
18
29
  address?: string;
19
30
  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;
31
+ getAuthState?: () => any;
32
+ /**
33
+ * OJO: la firma de Pollar NO es la de SEP-43. Pide `validUntilLedger` (en vez
34
+ * de networkPassphrase/address) y responde un outcome con `status`.
35
+ */
36
+ signAuthEntry?: (entryXdr: string, options: {
37
+ validUntilLedger: number;
38
+ }) => Promise<PollarSignAuthEntryOutcome>;
26
39
  signTransaction?: SignTransaction;
27
40
  signTx?: (unsignedXdr: string) => Promise<unknown>;
28
41
  }
29
42
  export interface PollarSignerOptions {
30
43
  /** Fuerza la dirección del pagador si el cliente aún no la expone. */
31
44
  address?: string;
45
+ /** Red usada para leer el último ledger. Default: stellar:testnet. */
46
+ network?: StellarNetwork;
47
+ /** Soroban RPC para leer el último ledger. Default: el público de la red. */
48
+ rpcUrl?: string;
49
+ /**
50
+ * Ledgers que la firma sigue siendo válida. Default 120 (~10 min a 5 s por
51
+ * ledger) — con margen para la latencia del facilitador sin dejar una firma
52
+ * viva de más.
53
+ */
54
+ validityLedgers?: number;
32
55
  }
33
56
  /**
34
57
  * Envuelve un cliente de Pollar como signer SEP-43 para x402.
35
58
  *
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.
59
+ * Traduce entre los dos contratos: x402 pide SEP-43
60
+ * (`signAuthEntry(xdr, { networkPassphrase, address }) → { signedAuthEntry }`),
61
+ * y Pollar pide `signAuthEntry(xdr, { validUntilLedger }) → { status, … }`.
62
+ * El `validUntilLedger` se calcula leyendo el último ledger de la red.
38
63
  */
39
64
  export declare function createPollarSigner(pollar: PollarLikeClient, opts?: PollarSignerOptions): ClientStellarSigner;
40
65
  /** ¿Este signer ya puede pagar? Útil para deshabilitar el botón en la UI. */
package/dist/index.js CHANGED
@@ -30,6 +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
34
  const DEFAULTS = {
34
35
  network: "stellar:testnet",
35
36
  testnetAgent: "https://nirium-agent.fly.dev",
@@ -39,25 +40,103 @@ const DEFAULTS = {
39
40
  pubnetRpc: "https://soroban-rpc.mainnet.stellar.gateway.fm",
40
41
  };
41
42
  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 }).";
43
+ const MISSING_SIGN_AUTH_ENTRY = "El cliente de Pollar no expone signAuthEntry(). Está disponible desde " +
44
+ "@pollar/core 0.11 — actualiza el paquete. Mientras tanto puedes pasar tu " +
45
+ "propio signer a createNiriumAdapter({ signer }).";
46
+ // ── Los dos dialectos de "firmar un auth entry" ──────────────────────────────
47
+ //
48
+ // El mismo nombre, dos contratos incompatibles, y ninguno está mal:
49
+ //
50
+ // stellar-sdk (`AssembledTransaction.signAuthEntries` → `authorizeEntry`)
51
+ // manda el **HashIdPreimage** —lo que se va a hashear— y espera de vuelta
52
+ // la **firma cruda** en base64. Él arma el entry final.
53
+ //
54
+ // Pollar (`POST /tx/sign-auth-entry`)
55
+ // espera el **SorobanAuthorizationEntry** completo y devuelve el **entry
56
+ // ya firmado**, porque su backend valida el árbol de invocación contra el
57
+ // allowlist antes de firmar — y para eso necesita ver el entry, no un hash.
58
+ //
59
+ // Sin traducir, su backend responde `SOROBAN_AUTH_ENTRY_INVALID: entryXdr is
60
+ // not a valid SorobanAuthorizationEntry` — que se lee como "el XDR viene roto"
61
+ // cuando en realidad viene bien, solo que es de otro tipo.
62
+ //
63
+ // El preimage trae nonce, expiración e invocación; lo único que le falta al
64
+ // entry es la dirección del firmante, que sí tenemos. Así que la reconstrucción
65
+ // es exacta: el hash que Pollar firma es idéntico al que el SDK espera.
66
+ /** ¿Este base64 es un HashIdPreimage de autorización Soroban? */
67
+ function asSorobanAuthPreimage(b64) {
68
+ try {
69
+ const p = xdr.HashIdPreimage.fromXDR(b64, "base64");
70
+ return p.switch().name === "envelopeTypeSorobanAuthorization"
71
+ ? p.sorobanAuthorization()
72
+ : null;
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ /** Rearma el entry sin firmar que el preimage describe. */
79
+ function entryFromPreimage(pre, signerAddress) {
80
+ return new xdr.SorobanAuthorizationEntry({
81
+ credentials: xdr.SorobanCredentials.sorobanCredentialsAddress(new xdr.SorobanAddressCredentials({
82
+ address: Address.fromString(signerAddress).toScAddress(),
83
+ nonce: pre.nonce(),
84
+ signatureExpirationLedger: pre.signatureExpirationLedger(),
85
+ // Sin firmar: es justo lo que Pollar va a llenar.
86
+ signature: xdr.ScVal.scvVoid(),
87
+ })),
88
+ rootInvocation: pre.invocation(),
89
+ });
90
+ }
91
+ /**
92
+ * Saca los 64 bytes de la firma ed25519 del entry que devolvió Pollar.
93
+ * El campo `signature` es un ScVal y su forma depende de la cuenta: para una
94
+ * cuenta clásica es un vec con un mapa `{ public_key, signature }`, pero se
95
+ * aceptan también el mapa suelto y los bytes pelones para no romperse si
96
+ * cambian la envoltura.
97
+ */
98
+ function extractEd25519Signature(v) {
99
+ let node = v;
100
+ if (node.switch().name === "scvVec") {
101
+ const items = node.vec() ?? [];
102
+ if (items.length !== 1) {
103
+ throw new Error(`Pollar devolvió ${items.length} firmas en el auth entry; se esperaba 1.`);
104
+ }
105
+ node = items[0];
106
+ }
107
+ if (node.switch().name === "scvMap") {
108
+ for (const e of node.map() ?? []) {
109
+ const key = e.key();
110
+ if (key.switch().name === "scvSymbol" && key.sym().toString() === "signature") {
111
+ return e.val().bytes();
112
+ }
113
+ }
114
+ throw new Error("El auth entry firmado por Pollar no trae campo `signature`.");
115
+ }
116
+ if (node.switch().name === "scvBytes")
117
+ return node.bytes();
118
+ throw new Error(`Forma inesperada en la firma del auth entry de Pollar: ${node.switch().name}.`);
119
+ }
49
120
  /**
50
121
  * Envuelve un cliente de Pollar como signer SEP-43 para x402.
51
122
  *
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.
123
+ * Traduce entre los dos contratos: x402 pide SEP-43
124
+ * (`signAuthEntry(xdr, { networkPassphrase, address }) → { signedAuthEntry }`),
125
+ * y Pollar pide `signAuthEntry(xdr, { validUntilLedger }) → { status, … }`.
126
+ * El `validUntilLedger` se calcula leyendo el último ledger de la red.
54
127
  */
55
128
  export function createPollarSigner(pollar, opts = {}) {
129
+ const network = opts.network ?? DEFAULTS.network;
130
+ const rpcUrl = opts.rpcUrl ?? (isPubnet(network) ? DEFAULTS.pubnetRpc : DEFAULTS.testnetRpc);
131
+ const validityLedgers = opts.validityLedgers ?? 120;
132
+ let rpcServer = null;
56
133
  const resolveAddress = () => {
57
134
  const authState = pollar.getAuthState?.();
58
135
  const address = opts.address ??
59
136
  pollar.address ??
60
137
  pollar.walletAddress ??
138
+ // @pollar/core ≥ 0.11: la wallet vive en la sesión autenticada.
139
+ authState?.session?.wallet?.address ??
61
140
  authState?.walletAddress ??
62
141
  authState?.address;
63
142
  if (!address) {
@@ -66,14 +145,53 @@ export function createPollarSigner(pollar, opts = {}) {
66
145
  }
67
146
  return address;
68
147
  };
69
- const signAuthEntry = async (authEntry, signOpts) => {
148
+ const signAuthEntry = async (payload) => {
70
149
  if (typeof pollar.signAuthEntry !== "function") {
71
150
  throw new Error(MISSING_SIGN_AUTH_ENTRY);
72
151
  }
73
- return pollar.signAuthEntry(authEntry, {
74
- address: resolveAddress(),
75
- ...signOpts,
76
- });
152
+ const signerAddress = resolveAddress();
153
+ // El SDK de Stellar manda un preimage; un llamador directo puede mandar el
154
+ // entry. Se distinguen decodificando, no adivinando por el contenido.
155
+ const preimage = asSorobanAuthPreimage(payload);
156
+ let entryXdr;
157
+ let validUntilLedger;
158
+ if (preimage) {
159
+ entryXdr = entryFromPreimage(preimage, signerAddress).toXDR("base64");
160
+ // La expiración la fijó el SDK y viaja DENTRO del hash que se firma:
161
+ // pedirle a Pollar otra distinta produciría una firma que no valida.
162
+ validUntilLedger = preimage.signatureExpirationLedger();
163
+ }
164
+ else {
165
+ entryXdr = payload;
166
+ rpcServer ??= new rpc.Server(rpcUrl);
167
+ const { sequence } = await rpcServer.getLatestLedger();
168
+ validUntilLedger = sequence + validityLedgers;
169
+ }
170
+ const outcome = await pollar.signAuthEntry(entryXdr, { validUntilLedger });
171
+ if ("status" in outcome && outcome.status === "error") {
172
+ throw new Error(`Pollar rechazó la firma del auth entry: ${outcome.details ?? "sin detalle"}`);
173
+ }
174
+ const signedAuthEntry = outcome.signedAuthEntry;
175
+ if (!signedAuthEntry) {
176
+ throw new Error("Pollar no devolvió signedAuthEntry.");
177
+ }
178
+ // Camino directo (nos dieron un entry): se devuelve tal cual.
179
+ if (!preimage)
180
+ return { signedAuthEntry, signerAddress };
181
+ // Camino del SDK: hay que devolver la firma cruda, no el entry.
182
+ const signed = xdr.SorobanAuthorizationEntry.fromXDR(signedAuthEntry, "base64");
183
+ const creds = signed.credentials().address();
184
+ const usedLedger = creds.signatureExpirationLedger();
185
+ if (usedLedger !== validUntilLedger) {
186
+ // Si su backend recortó la ventana, firmó otro hash y la firma no valida.
187
+ // Vale más un error claro aquí que un `txBadAuth` diez pasos después.
188
+ throw new Error(`Pollar firmó con expiración ${usedLedger} en vez de ${validUntilLedger}; `
189
+ + "la firma no correspondería al pago. Sube el tope en Auth Policy → Signature validity.");
190
+ }
191
+ return {
192
+ signedAuthEntry: extractEd25519Signature(creds.signature()).toString("base64"),
193
+ signerAddress,
194
+ };
77
195
  };
78
196
  const signer = {
79
197
  get address() {
@@ -106,7 +224,22 @@ export function createNiriumAdapter(config) {
106
224
  * facilitador — la wallet del usuario no necesita XLM para el gas.
107
225
  */
108
226
  async function x402Fetch(url, init) {
109
- return paidFetch(url, init);
227
+ try {
228
+ return await paidFetch(url, init);
229
+ }
230
+ catch (e) {
231
+ // En el navegador un bloqueo de CSP, uno de CORS y un servicio caído dan
232
+ // el MISMO "Failed to fetch" sin decir a quién no se pudo llegar — y esa
233
+ // es justo la única pista que los distingue. Nombrar el host convierte
234
+ // media tarde de adivinanzas en una línea de configuración.
235
+ const msg = e instanceof Error ? e.message : String(e);
236
+ if (/failed to fetch|networkerror|load failed/i.test(msg)) {
237
+ throw new Error(`${msg} — el navegador no pudo alcanzar ${url}. Revisa connect-src del CSP, `
238
+ + "y que el servidor exponga PAYMENT-REQUIRED y acepte PAYMENT-SIGNATURE "
239
+ + "y Access-Control-Expose-Headers en su CORS.");
240
+ }
241
+ throw e;
242
+ }
110
243
  }
111
244
  /** Atajo tipado a los endpoints premium del agente. */
112
245
  async function getPremiumSignals() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-pollar-adapter",
3
- "version": "0.1.0",
3
+ "version": "0.3.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.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -17,8 +17,12 @@
17
17
  "@x402/stellar": "2.17.0"
18
18
  },
19
19
  "peerDependencies": {
20
- "@pollar/core": "*"
20
+ "@pollar/core": ">=0.11.0"
21
+ },
22
+ "peerDependenciesMeta": {
23
+ "@pollar/core": { "optional": true }
21
24
  },
22
25
  "keywords": ["nirium", "pollar", "stellar", "soroban", "x402", "adapter"],
26
+ "homepage": "https://nirium.xyz",
23
27
  "license": "MIT"
24
28
  }