nirium-pollar-adapter 0.2.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.
Files changed (3) hide show
  1. package/README.md +54 -1
  2. package/dist/index.js +127 -9
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -71,6 +71,13 @@ Swapping to a Pollar wallet is one line:
71
71
  + const signer = createPollarSigner(pollarClient);
72
72
  ```
73
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
+
74
81
  ## API
75
82
 
76
83
  ### `createNiriumAdapter(config)`
@@ -92,7 +99,53 @@ Returns:
92
99
 
93
100
  ### `createPollarSigner(pollarClient, opts?)`
94
101
 
95
- 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.
96
149
 
97
150
  ## Scope
98
151
 
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 { rpc } from "@stellar/stellar-sdk";
33
+ import { Address, rpc, xdr } from "@stellar/stellar-sdk";
34
34
  const DEFAULTS = {
35
35
  network: "stellar:testnet",
36
36
  testnetAgent: "https://nirium-agent.fly.dev",
@@ -43,6 +43,80 @@ const isPubnet = (n) => n === "stellar:pubnet";
43
43
  const MISSING_SIGN_AUTH_ENTRY = "El cliente de Pollar no expone signAuthEntry(). Está disponible desde " +
44
44
  "@pollar/core 0.11 — actualiza el paquete. Mientras tanto puedes pasar tu " +
45
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
+ }
46
120
  /**
47
121
  * Envuelve un cliente de Pollar como signer SEP-43 para x402.
48
122
  *
@@ -71,16 +145,29 @@ export function createPollarSigner(pollar, opts = {}) {
71
145
  }
72
146
  return address;
73
147
  };
74
- const signAuthEntry = async (authEntry) => {
148
+ const signAuthEntry = async (payload) => {
75
149
  if (typeof pollar.signAuthEntry !== "function") {
76
150
  throw new Error(MISSING_SIGN_AUTH_ENTRY);
77
151
  }
78
152
  const signerAddress = resolveAddress();
79
- rpcServer ??= new rpc.Server(rpcUrl);
80
- const { sequence } = await rpcServer.getLatestLedger();
81
- const outcome = await pollar.signAuthEntry(authEntry, {
82
- validUntilLedger: sequence + validityLedgers,
83
- });
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 });
84
171
  if ("status" in outcome && outcome.status === "error") {
85
172
  throw new Error(`Pollar rechazó la firma del auth entry: ${outcome.details ?? "sin detalle"}`);
86
173
  }
@@ -88,7 +175,23 @@ export function createPollarSigner(pollar, opts = {}) {
88
175
  if (!signedAuthEntry) {
89
176
  throw new Error("Pollar no devolvió signedAuthEntry.");
90
177
  }
91
- return { signedAuthEntry, signerAddress };
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
+ };
92
195
  };
93
196
  const signer = {
94
197
  get address() {
@@ -121,7 +224,22 @@ export function createNiriumAdapter(config) {
121
224
  * facilitador — la wallet del usuario no necesita XLM para el gas.
122
225
  */
123
226
  async function x402Fetch(url, init) {
124
- 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
+ }
125
243
  }
126
244
  /** Atajo tipado a los endpoints premium del agente. */
127
245
  async function getPremiumSignals() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nirium-pollar-adapter",
3
- "version": "0.2.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",
@@ -23,5 +23,6 @@
23
23
  "@pollar/core": { "optional": true }
24
24
  },
25
25
  "keywords": ["nirium", "pollar", "stellar", "soroban", "x402", "adapter"],
26
+ "homepage": "https://nirium.xyz",
26
27
  "license": "MIT"
27
28
  }