@aifinpay/agent 0.1.0-alpha.1 → 0.3.0-alpha.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 (42) hide show
  1. package/README.md +6 -2
  2. package/dist/agent.d.ts +112 -0
  3. package/dist/agent.d.ts.map +1 -0
  4. package/dist/agent.js +312 -0
  5. package/dist/agent.js.map +1 -0
  6. package/dist/crypto.d.ts +3 -0
  7. package/dist/crypto.d.ts.map +1 -0
  8. package/dist/crypto.js +12 -0
  9. package/dist/crypto.js.map +1 -0
  10. package/dist/errors.d.ts +19 -0
  11. package/dist/errors.d.ts.map +1 -0
  12. package/dist/errors.js +22 -0
  13. package/dist/errors.js.map +1 -0
  14. package/dist/facilitators/aifinpay.d.ts +21 -0
  15. package/dist/facilitators/aifinpay.d.ts.map +1 -0
  16. package/dist/facilitators/aifinpay.js +76 -0
  17. package/dist/facilitators/aifinpay.js.map +1 -0
  18. package/dist/facilitators/base.d.ts +35 -0
  19. package/dist/facilitators/base.d.ts.map +1 -0
  20. package/dist/facilitators/base.js +2 -0
  21. package/dist/facilitators/base.js.map +1 -0
  22. package/dist/facilitators/coinbase.d.ts +20 -0
  23. package/dist/facilitators/coinbase.d.ts.map +1 -0
  24. package/dist/facilitators/coinbase.js +67 -0
  25. package/dist/facilitators/coinbase.js.map +1 -0
  26. package/dist/facilitators/detect.d.ts +9 -0
  27. package/dist/facilitators/detect.d.ts.map +1 -0
  28. package/dist/facilitators/detect.js +33 -0
  29. package/dist/facilitators/detect.js.map +1 -0
  30. package/dist/facilitators/index.d.ts +5 -0
  31. package/dist/facilitators/index.d.ts.map +1 -0
  32. package/dist/facilitators/index.js +4 -0
  33. package/dist/facilitators/index.js.map +1 -0
  34. package/dist/index.d.ts +28 -60
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +22 -197
  37. package/dist/index.js.map +1 -1
  38. package/dist/unifiedAgent.d.ts +222 -0
  39. package/dist/unifiedAgent.d.ts.map +1 -0
  40. package/dist/unifiedAgent.js +498 -0
  41. package/dist/unifiedAgent.js.map +1 -0
  42. package/package.json +16 -9
package/README.md CHANGED
@@ -10,9 +10,13 @@ the `x-signature` header to authenticate against AiFinPay-protected endpoints.
10
10
  ## Install
11
11
 
12
12
  ```bash
13
+ # alpha / prerelease (current)
14
+ npm install @aifinpay/agent@alpha
15
+ # or pnpm add @aifinpay/agent@alpha
16
+ # or yarn add @aifinpay/agent@alpha
17
+
18
+ # stable (when 1.0 ships)
13
19
  npm install @aifinpay/agent
14
- # or pnpm add @aifinpay/agent
15
- # or yarn add @aifinpay/agent
16
20
  ```
17
21
 
18
22
  ## Quick start
@@ -0,0 +1,112 @@
1
+ import type { PayOptions } from "./facilitators/base.js";
2
+ export interface Invoice {
3
+ amountUsd: number;
4
+ treasuryVault: string;
5
+ programId: string;
6
+ nonce: string;
7
+ raw: Record<string, unknown>;
8
+ }
9
+ export interface AgentOptions {
10
+ baseUrl?: string;
11
+ timeoutMs?: number;
12
+ fetchImpl?: typeof fetch;
13
+ }
14
+ export interface PayInit extends Omit<RequestInit, "method"> {
15
+ method?: string;
16
+ options?: PayOptions;
17
+ maxRetries?: number;
18
+ }
19
+ export declare class Agent {
20
+ readonly publicKey: Uint8Array;
21
+ readonly secretKey: Uint8Array;
22
+ readonly baseUrl: string;
23
+ readonly timeoutMs: number;
24
+ /** Internal — facilitators reach for this when they need to refetch from the backend. */
25
+ readonly fetchImpl: typeof fetch;
26
+ private constructor();
27
+ static new(opts?: AgentOptions): Agent;
28
+ /** Load from base58 secret (Solana style: 64 bytes = secret + public). */
29
+ static fromSecretB58(secretB58: string, opts?: AgentOptions): Agent;
30
+ /** Load from a Solana CLI ``solana-keygen`` JSON file path (Node only). */
31
+ static fromKeypairFile(path: string, opts?: AgentOptions): Promise<Agent>;
32
+ /** Solana base58 public key. */
33
+ get address(): string;
34
+ /** 64-byte base58 secret. Save this safely — server never sees it. */
35
+ get secretB58(): string;
36
+ manifesto(): Promise<Record<string, unknown>>;
37
+ wellKnown(): Promise<Record<string, unknown>>;
38
+ fetchNonce(): Promise<{
39
+ nonce: string;
40
+ expires_at: string;
41
+ }>;
42
+ /** Build a fresh AiFinPay-native x402 header set. */
43
+ authHeaders(): Promise<Record<string, string>>;
44
+ hasSeat(): Promise<boolean>;
45
+ waitForFunding({ minUsdCents, pollMs, timeoutMs, }?: {
46
+ minUsdCents?: number;
47
+ pollMs?: number;
48
+ timeoutMs?: number;
49
+ }): Promise<void>;
50
+ /**
51
+ * @deprecated since 0.3.0 — use `AiFinPayAgent.deposit(usd, { asset })`
52
+ * instead. The unified surface picks the chain and asset for you.
53
+ * Kept for back-compat; will not be removed before 1.0.0.
54
+ */
55
+ reserveSeatInvoice({ amountUsd, asset, }: {
56
+ amountUsd: number;
57
+ asset?: "SOL" | "USDC" | "USDT";
58
+ }): Promise<Invoice>;
59
+ /**
60
+ * Pure-view fee-on-top breakdown — no payment, no auth.
61
+ *
62
+ * Returns merchant amount, treasury fee, IP creator fee, and total —
63
+ * so the agent can decide whether to pay BEFORE building the tx.
64
+ *
65
+ * @deprecated since 0.3.0 — pricing is exposed through the provider
66
+ * registry consumed by `AiFinPayAgent.call()`. Direct on-chain quote
67
+ * is rarely needed anymore. Kept for back-compat through 1.0.0.
68
+ */
69
+ quoteSplit(args: {
70
+ chain: "solana" | "polygon";
71
+ merchantAmount: bigint | number | string;
72
+ }): Promise<Record<string, unknown>>;
73
+ /**
74
+ * @deprecated since 0.3.0 — use `AiFinPayAgent.call({ provider })`,
75
+ * which selects the chain, builds the tx, and submits it for you.
76
+ * Kept for back-compat through 1.0.0.
77
+ *
78
+ * Get the on-chain instructions for a fee-on-top split payment.
79
+ *
80
+ * The merchant receives `merchantAmount` units (lamports for Solana,
81
+ * wei for Polygon). Treasury fee + IP-creator fee are added ON TOP.
82
+ *
83
+ * The SDK does **not** submit the transaction — it's non-custodial.
84
+ * Caller uses the returned `args` + `accounts` (Solana) or
85
+ * `args` + `msg_value_wei` (Polygon) with a chain SDK of choice
86
+ * (`@solana/web3.js`, `viem`, `ethers`, …).
87
+ *
88
+ * Throws `FacilitatorNotImplementedError` if the corresponding splitter
89
+ * is not yet deployed on the requested chain (backend returns 503 with
90
+ * onboarding message).
91
+ */
92
+ payWithSplitInvoice(args: {
93
+ chain: "solana" | "polygon";
94
+ merchantWallet: string;
95
+ merchantAmount: bigint | number | string;
96
+ orderId: string;
97
+ feeRecipient?: string;
98
+ }): Promise<Record<string, unknown>>;
99
+ /**
100
+ * HTTP request that auto-handles x402 across multiple facilitators.
101
+ *
102
+ * First sends the request unauthenticated. On 402, detects which
103
+ * facilitator the server speaks (AiFinPay native, Coinbase x402, …),
104
+ * builds the appropriate auth payload, and retries.
105
+ */
106
+ pay(url: string, init?: PayInit): Promise<Response>;
107
+ request(method: string, url: string, init?: RequestInit): Promise<Response>;
108
+ get(url: string, init?: PayInit): Promise<Response>;
109
+ post(url: string, init?: PayInit): Promise<Response>;
110
+ private json;
111
+ }
112
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAMzD,MAAM,WAAW,OAAO;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC9B;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAC1B;AAED,MAAM,WAAW,OAAQ,SAAQ,IAAI,CAAC,WAAW,EAAE,QAAQ,CAAC;IAC1D,MAAM,CAAC,EAAE,MA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,CAAC,QAAQ,CAAC;YAM1C,IAAI;CA6BnB"}
package/dist/agent.js ADDED
@@ -0,0 +1,312 @@
1
+ import nacl from "tweetnacl";
2
+ import bs58 from "bs58";
3
+ import { sha256 } from "./crypto.js";
4
+ import { AiFinPayError, FundingTimeoutError, X402Error } from "./errors.js";
5
+ import { detectFacilitator } from "./facilitators/detect.js";
6
+ const DEFAULT_BASE_URL = "https://aifinpay.company";
7
+ const DEFAULT_TIMEOUT_MS = 30_000;
8
+ const SDK_UA = "aifinpay-agent-node/0.2.0";
9
+ export class Agent {
10
+ publicKey;
11
+ secretKey; // 64 bytes (secret + public)
12
+ baseUrl;
13
+ timeoutMs;
14
+ /** Internal — facilitators reach for this when they need to refetch from the backend. */
15
+ fetchImpl;
16
+ constructor(secretKey, publicKey, opts = {}) {
17
+ this.secretKey = secretKey;
18
+ this.publicKey = publicKey;
19
+ this.baseUrl = (opts.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
20
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
21
+ this.fetchImpl = opts.fetchImpl ?? globalThis.fetch;
22
+ if (!this.fetchImpl) {
23
+ throw new AiFinPayError("global fetch not available. Pass opts.fetchImpl or upgrade to Node 18+.");
24
+ }
25
+ }
26
+ // ── Constructors ───────────────────────────────────────────────────────
27
+ static new(opts = {}) {
28
+ const kp = nacl.sign.keyPair();
29
+ return new Agent(kp.secretKey, kp.publicKey, opts);
30
+ }
31
+ /** Load from base58 secret (Solana style: 64 bytes = secret + public). */
32
+ static fromSecretB58(secretB58, opts = {}) {
33
+ const raw = bs58.decode(secretB58);
34
+ let kp;
35
+ if (raw.length === 64) {
36
+ kp = nacl.sign.keyPair.fromSecretKey(raw);
37
+ }
38
+ else if (raw.length === 32) {
39
+ kp = nacl.sign.keyPair.fromSeed(raw);
40
+ }
41
+ else {
42
+ throw new AiFinPayError(`secret must decode to 32 or 64 bytes, got ${raw.length}`);
43
+ }
44
+ return new Agent(kp.secretKey, kp.publicKey, opts);
45
+ }
46
+ /** Load from a Solana CLI ``solana-keygen`` JSON file path (Node only). */
47
+ static async fromKeypairFile(path, opts = {}) {
48
+ const fs = await import("node:fs/promises");
49
+ const raw = await fs.readFile(path, "utf8");
50
+ const arr = JSON.parse(raw);
51
+ if (!Array.isArray(arr) || arr.length !== 64) {
52
+ throw new AiFinPayError(`${path}: expected 64-byte JSON array`);
53
+ }
54
+ const sk = Uint8Array.from(arr);
55
+ const kp = nacl.sign.keyPair.fromSecretKey(sk);
56
+ return new Agent(kp.secretKey, kp.publicKey, opts);
57
+ }
58
+ // ── Public properties ──────────────────────────────────────────────────
59
+ /** Solana base58 public key. */
60
+ get address() {
61
+ return bs58.encode(this.publicKey);
62
+ }
63
+ /** 64-byte base58 secret. Save this safely — server never sees it. */
64
+ get secretB58() {
65
+ return bs58.encode(this.secretKey);
66
+ }
67
+ // ── Discovery ──────────────────────────────────────────────────────────
68
+ async manifesto() {
69
+ return (await this.json("GET", "/manifesto.json"));
70
+ }
71
+ async wellKnown() {
72
+ return (await this.json("GET", "/.well-known/x402.json"));
73
+ }
74
+ // ── x402 auth (AiFinPay-native helpers, kept for backwards compat) ────
75
+ async fetchNonce() {
76
+ return this.json("GET", "/nonce");
77
+ }
78
+ /** Build a fresh AiFinPay-native x402 header set. */
79
+ async authHeaders() {
80
+ const { nonce } = await this.fetchNonce();
81
+ const msg = new TextEncoder().encode(`AiFinPay-x402:${nonce}:${this.address}`);
82
+ const digest = await sha256(msg);
83
+ const sig = nacl.sign.detached(digest, this.secretKey);
84
+ return {
85
+ "x-agent-pubkey": this.address,
86
+ "x-nonce": nonce,
87
+ "x-signature": bs58.encode(sig),
88
+ };
89
+ }
90
+ // ── Seat / funding ────────────────────────────────────────────────────
91
+ async hasSeat() {
92
+ const r = (await this.json("GET", `/api/seat/${this.address}`));
93
+ return Boolean(r.has_seat);
94
+ }
95
+ async waitForFunding({ minUsdCents = 100, pollMs = 5_000, timeoutMs = 600_000, } = {}) {
96
+ const deadline = Date.now() + timeoutMs;
97
+ while (Date.now() < deadline) {
98
+ const data = (await this.json("GET", "/api/leaderboard?merge=true"));
99
+ for (const entry of data.leaderboard || []) {
100
+ if (entry.pubkey === this.address) {
101
+ const cents = Math.round(parseFloat(entry.usd) * 100);
102
+ if (cents >= minUsdCents)
103
+ return;
104
+ }
105
+ }
106
+ await new Promise((res) => setTimeout(res, pollMs));
107
+ }
108
+ throw new FundingTimeoutError(`address ${this.address} never reached ${minUsdCents} cents on-chain`);
109
+ }
110
+ // ── Invoices ──────────────────────────────────────────────────────────
111
+ /**
112
+ * @deprecated since 0.3.0 — use `AiFinPayAgent.deposit(usd, { asset })`
113
+ * instead. The unified surface picks the chain and asset for you.
114
+ * Kept for back-compat; will not be removed before 1.0.0.
115
+ */
116
+ async reserveSeatInvoice({ amountUsd, asset = "USDC", }) {
117
+ const endpoint = asset === "SOL" ? "/api/invoice" : "/api/invoice-spl";
118
+ const payload = {
119
+ amount_usd: amountUsd,
120
+ agent_pubkey: this.address,
121
+ };
122
+ if (asset !== "SOL")
123
+ payload.asset = asset;
124
+ const data = (await this.json("POST", endpoint, payload));
125
+ return {
126
+ amountUsd,
127
+ treasuryVault: data.treasury_vault || "",
128
+ programId: data.program_id || "",
129
+ nonce: data.nonce || "",
130
+ raw: data,
131
+ };
132
+ }
133
+ // ── Fee-on-top split (b2b_pay_with_split / AiFinPaySplitter) ─────────
134
+ /**
135
+ * Pure-view fee-on-top breakdown — no payment, no auth.
136
+ *
137
+ * Returns merchant amount, treasury fee, IP creator fee, and total —
138
+ * so the agent can decide whether to pay BEFORE building the tx.
139
+ *
140
+ * @deprecated since 0.3.0 — pricing is exposed through the provider
141
+ * registry consumed by `AiFinPayAgent.call()`. Direct on-chain quote
142
+ * is rarely needed anymore. Kept for back-compat through 1.0.0.
143
+ */
144
+ async quoteSplit(args) {
145
+ const param = args.chain === "solana"
146
+ ? "merchant_amount_lamports"
147
+ : "merchant_amount_wei";
148
+ const url = new URL(`${this.baseUrl}/api/b2b/quote-split`);
149
+ url.searchParams.set(param, String(args.merchantAmount));
150
+ const r = await this.fetchImpl(url.toString(), {
151
+ headers: { accept: "application/json", "user-agent": SDK_UA },
152
+ });
153
+ if (!r.ok) {
154
+ throw new AiFinPayError(`GET /api/b2b/quote-split → ${r.status}`);
155
+ }
156
+ return (await r.json());
157
+ }
158
+ /**
159
+ * @deprecated since 0.3.0 — use `AiFinPayAgent.call({ provider })`,
160
+ * which selects the chain, builds the tx, and submits it for you.
161
+ * Kept for back-compat through 1.0.0.
162
+ *
163
+ * Get the on-chain instructions for a fee-on-top split payment.
164
+ *
165
+ * The merchant receives `merchantAmount` units (lamports for Solana,
166
+ * wei for Polygon). Treasury fee + IP-creator fee are added ON TOP.
167
+ *
168
+ * The SDK does **not** submit the transaction — it's non-custodial.
169
+ * Caller uses the returned `args` + `accounts` (Solana) or
170
+ * `args` + `msg_value_wei` (Polygon) with a chain SDK of choice
171
+ * (`@solana/web3.js`, `viem`, `ethers`, …).
172
+ *
173
+ * Throws `FacilitatorNotImplementedError` if the corresponding splitter
174
+ * is not yet deployed on the requested chain (backend returns 503 with
175
+ * onboarding message).
176
+ */
177
+ async payWithSplitInvoice(args) {
178
+ const { FacilitatorNotImplementedError } = await import("./errors.js");
179
+ if (!args.orderId || args.orderId.length > 64) {
180
+ throw new AiFinPayError("orderId required, max 64 chars");
181
+ }
182
+ const r = await this.fetchImpl(`${this.baseUrl}/api/b2b/pay-with-split`, {
183
+ method: "POST",
184
+ headers: {
185
+ accept: "application/json",
186
+ "content-type": "application/json",
187
+ "user-agent": SDK_UA,
188
+ },
189
+ body: JSON.stringify({
190
+ chain: args.chain,
191
+ agent_pubkey: this.address,
192
+ merchant_wallet: args.merchantWallet,
193
+ merchant_amount: String(args.merchantAmount),
194
+ order_id: args.orderId,
195
+ ...(args.feeRecipient ? { fee_recipient: args.feeRecipient } : {}),
196
+ }),
197
+ });
198
+ if (r.status === 503) {
199
+ let msg = "splitter not deployed";
200
+ try {
201
+ const body = (await r.json());
202
+ if (body.message)
203
+ msg = body.message;
204
+ }
205
+ catch {
206
+ /* ignore */
207
+ }
208
+ throw new FacilitatorNotImplementedError(msg);
209
+ }
210
+ if (!r.ok) {
211
+ throw new AiFinPayError(`POST /api/b2b/pay-with-split → ${r.status}`);
212
+ }
213
+ return (await r.json());
214
+ }
215
+ // ── Generic x402 — works against any supported facilitator ────────────
216
+ /**
217
+ * HTTP request that auto-handles x402 across multiple facilitators.
218
+ *
219
+ * First sends the request unauthenticated. On 402, detects which
220
+ * facilitator the server speaks (AiFinPay native, Coinbase x402, …),
221
+ * builds the appropriate auth payload, and retries.
222
+ */
223
+ async pay(url, init = {}) {
224
+ const { method = "GET", maxRetries = 1, options = {}, ...rest } = init;
225
+ const baseHeaders = mergeHeaders(rest.headers, options.extraHeaders);
226
+ const send = (m, headers, body) => this.fetchImpl(url, {
227
+ ...rest,
228
+ method: m,
229
+ headers,
230
+ body: body ?? rest.body,
231
+ });
232
+ let resp = await send(method, { ...baseHeaders, "user-agent": SDK_UA });
233
+ let attempt = 0;
234
+ while (resp.status === 402 && attempt < maxRetries) {
235
+ attempt += 1;
236
+ const facilitator = await detectFacilitator(resp, options.facilitator ?? "auto");
237
+ const auth = await facilitator.buildAuth(resp, this, options);
238
+ const merged = mergeHeaders(baseHeaders, auth.headers);
239
+ merged["user-agent"] = SDK_UA;
240
+ resp = await send(auth.method ?? method, merged, auth.body);
241
+ }
242
+ if (resp.status === 402) {
243
+ let challenge;
244
+ try {
245
+ challenge = JSON.stringify(await resp.clone().json());
246
+ }
247
+ catch {
248
+ challenge = (await resp.clone().text()).slice(0, 500);
249
+ }
250
+ throw new X402Error(`402 Payment Required after ${attempt} retry/retries. ` +
251
+ `Challenge: ${challenge}`);
252
+ }
253
+ return resp;
254
+ }
255
+ // ── Backwards-compat wrappers ────────────────────────────────────────
256
+ async request(method, url, init = {}) {
257
+ return this.pay(url, { ...init, method });
258
+ }
259
+ get(url, init = {}) {
260
+ return this.pay(url, { ...init, method: "GET" });
261
+ }
262
+ post(url, init = {}) {
263
+ return this.pay(url, { ...init, method: "POST" });
264
+ }
265
+ // ── Internal helpers ──────────────────────────────────────────────────
266
+ async json(method, path, body) {
267
+ const init = {
268
+ method,
269
+ headers: {
270
+ accept: "application/json",
271
+ "user-agent": SDK_UA,
272
+ ...(body ? { "content-type": "application/json" } : {}),
273
+ },
274
+ };
275
+ if (body)
276
+ init.body = JSON.stringify(body);
277
+ const ctrl = new AbortController();
278
+ const t = setTimeout(() => ctrl.abort(), this.timeoutMs);
279
+ try {
280
+ const r = await this.fetchImpl(this.baseUrl + path, {
281
+ ...init,
282
+ signal: ctrl.signal,
283
+ });
284
+ if (!r.ok) {
285
+ throw new AiFinPayError(`${method} ${path} → ${r.status}`);
286
+ }
287
+ return await r.json();
288
+ }
289
+ finally {
290
+ clearTimeout(t);
291
+ }
292
+ }
293
+ }
294
+ function mergeHeaders(...sources) {
295
+ const out = {};
296
+ for (const src of sources) {
297
+ if (!src)
298
+ continue;
299
+ if (src instanceof Headers) {
300
+ src.forEach((v, k) => (out[k] = v));
301
+ }
302
+ else if (Array.isArray(src)) {
303
+ for (const [k, v] of src)
304
+ out[k] = String(v);
305
+ }
306
+ else {
307
+ Object.assign(out, src);
308
+ }
309
+ }
310
+ return out;
311
+ }
312
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAG7D,MAAM,gBAAgB,GAAG,0BAA0B,CAAC;AACpD,MAAM,kBAAkB,GAAG,MAA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AAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACtC,CAAC;aAAM,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;YAC9B,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,GAAG;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QAC/C,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** Cross-runtime SHA-256 helper. */
2
+ export declare function sha256(bytes: Uint8Array): Promise<Uint8Array>;
3
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,wBAAsB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAYnE"}
package/dist/crypto.js ADDED
@@ -0,0 +1,12 @@
1
+ /** Cross-runtime SHA-256 helper. */
2
+ export async function sha256(bytes) {
3
+ if (typeof crypto !== "undefined" && crypto.subtle) {
4
+ // Force ArrayBuffer (not SharedArrayBuffer) for strict TS lib check
5
+ const data = new Uint8Array(bytes);
6
+ const buf = await crypto.subtle.digest("SHA-256", data.buffer);
7
+ return new Uint8Array(buf);
8
+ }
9
+ const { createHash } = await import("node:crypto");
10
+ return new Uint8Array(createHash("sha256").update(bytes).digest());
11
+ }
12
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../src/crypto.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,KAAiB;IAC5C,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QACnD,oEAAoE;QACpE,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;QACnC,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CACpC,SAAS,EACT,IAAI,CAAC,MAAqB,CAC3B,CAAC;QACF,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IACD,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC;IACnD,OAAO,IAAI,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;AACrE,CAAC"}
@@ -0,0 +1,19 @@
1
+ export declare class AiFinPayError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ export declare class X402Error extends AiFinPayError {
5
+ }
6
+ export declare class FundingTimeoutError extends AiFinPayError {
7
+ }
8
+ export declare class SeatNotFoundError extends AiFinPayError {
9
+ }
10
+ /** The 402 response did not match any known facilitator flavor. */
11
+ export declare class UnsupportedFacilitatorError extends X402Error {
12
+ }
13
+ /** Required payment exceeds the caller's maxAmountUsd budget. */
14
+ export declare class PaymentTooExpensiveError extends X402Error {
15
+ }
16
+ /** Detected a known facilitator we can't pay yet (e.g. EVM not wired). */
17
+ export declare class FacilitatorNotImplementedError extends X402Error {
18
+ }
19
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,aAAc,SAAQ,KAAK;gBAC1B,OAAO,EAAE,MAAM;CAI5B;AAED,qBAAa,SAAU,SAAQ,aAAa;CAAG;AAE/C,qBAAa,mBAAoB,SAAQ,aAAa;CAAG;AAEzD,qBAAa,iBAAkB,SAAQ,aAAa;CAAG;AAEvD,mEAAmE;AACnE,qBAAa,2BAA4B,SAAQ,SAAS;CAAG;AAE7D,iEAAiE;AACjE,qBAAa,wBAAyB,SAAQ,SAAS;CAAG;AAE1D,0EAA0E;AAC1E,qBAAa,8BAA+B,SAAQ,SAAS;CAAG"}
package/dist/errors.js ADDED
@@ -0,0 +1,22 @@
1
+ export class AiFinPayError extends Error {
2
+ constructor(message) {
3
+ super(message);
4
+ this.name = this.constructor.name;
5
+ }
6
+ }
7
+ export class X402Error extends AiFinPayError {
8
+ }
9
+ export class FundingTimeoutError extends AiFinPayError {
10
+ }
11
+ export class SeatNotFoundError extends AiFinPayError {
12
+ }
13
+ /** The 402 response did not match any known facilitator flavor. */
14
+ export class UnsupportedFacilitatorError extends X402Error {
15
+ }
16
+ /** Required payment exceeds the caller's maxAmountUsd budget. */
17
+ export class PaymentTooExpensiveError extends X402Error {
18
+ }
19
+ /** Detected a known facilitator we can't pay yet (e.g. EVM not wired). */
20
+ export class FacilitatorNotImplementedError extends X402Error {
21
+ }
22
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACpC,CAAC;CACF;AAED,MAAM,OAAO,SAAU,SAAQ,aAAa;CAAG;AAE/C,MAAM,OAAO,mBAAoB,SAAQ,aAAa;CAAG;AAEzD,MAAM,OAAO,iBAAkB,SAAQ,aAAa;CAAG;AAEvD,mEAAmE;AACnE,MAAM,OAAO,2BAA4B,SAAQ,SAAS;CAAG;AAE7D,iEAAiE;AACjE,MAAM,OAAO,wBAAyB,SAAQ,SAAS;CAAG;AAE1D,0EAA0E;AAC1E,MAAM,OAAO,8BAA+B,SAAQ,SAAS;CAAG"}
@@ -0,0 +1,21 @@
1
+ import type { Agent } from "../agent.js";
2
+ import type { AuthPayload, Facilitator, PayOptions } from "./base.js";
3
+ /**
4
+ * Native AiFinPay flavor.
5
+ *
6
+ * Wire format:
7
+ * - 402 carries a JSON body with `protocol: "AiFinPay vX"` and
8
+ * `agreement_hash`, `treasury_vault`, `x-nonce` …
9
+ * - Client retries with three headers:
10
+ * x-agent-pubkey, x-nonce, x-signature
11
+ * - Signature: Ed25519 over SHA-256("AiFinPay-x402:{nonce}:{pubkey}")
12
+ */
13
+ export declare class AiFinPayFacilitator implements Facilitator {
14
+ static readonly name = "aifinpay";
15
+ readonly name = "aifinpay";
16
+ static detect(resp: Response): Promise<boolean>;
17
+ buildAuth(resp: Response, agent: Agent, _opts: PayOptions): Promise<AuthPayload>;
18
+ private inbandNonce;
19
+ private fetchNonce;
20
+ }
21
+ //# sourceMappingURL=aifinpay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aifinpay.d.ts","sourceRoot":"","sources":["../../src/facilitators/aifinpay.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEtE;;;;;;;;;GASG;AACH,qBAAa,mBAAoB,YAAW,WAAW;IACrD,MAAM,CAAC,QAAQ,CAAC,IAAI,cAAc;IAClC,QAAQ,CAAC,IAAI,cAAc;WAEd,MAAM,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC;IAoB/C,SAAS,CACb,IAAI,EAAE,QAAQ,EACd,KAAK,EAAE,KAAK,EACZ,KAAK,EAAE,UAAU,GAChB,OAAO,CAAC,WAAW,CAAC;YAiBT,WAAW;YAaX,UAAU;CASzB"}
@@ -0,0 +1,76 @@
1
+ import nacl from "tweetnacl";
2
+ import bs58 from "bs58";
3
+ import { sha256 } from "../crypto.js";
4
+ /**
5
+ * Native AiFinPay flavor.
6
+ *
7
+ * Wire format:
8
+ * - 402 carries a JSON body with `protocol: "AiFinPay vX"` and
9
+ * `agreement_hash`, `treasury_vault`, `x-nonce` …
10
+ * - Client retries with three headers:
11
+ * x-agent-pubkey, x-nonce, x-signature
12
+ * - Signature: Ed25519 over SHA-256("AiFinPay-x402:{nonce}:{pubkey}")
13
+ */
14
+ export class AiFinPayFacilitator {
15
+ static name = "aifinpay";
16
+ name = "aifinpay";
17
+ static async detect(resp) {
18
+ if (resp.status !== 402)
19
+ return false;
20
+ let body;
21
+ try {
22
+ body = await resp.clone().json();
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ if (typeof body !== "object" || body === null)
28
+ return false;
29
+ const b = body;
30
+ if (typeof b.protocol === "string" && b.protocol.startsWith("AiFinPay")) {
31
+ return true;
32
+ }
33
+ // Fallback fingerprint when an upstream proxy strips `protocol`.
34
+ return (("agreement_hash" in b || "manifesto" in b) &&
35
+ ("treasury_vault" in b || "program_id" in b));
36
+ }
37
+ async buildAuth(resp, agent, _opts) {
38
+ const nonce = (await this.inbandNonce(resp)) || (await this.fetchNonce(agent));
39
+ const msg = new TextEncoder().encode(`AiFinPay-x402:${nonce}:${agent.address}`);
40
+ const digest = await sha256(msg);
41
+ const sig = nacl.sign.detached(digest, agent.secretKey);
42
+ return {
43
+ headers: {
44
+ "x-agent-pubkey": agent.address,
45
+ "x-nonce": nonce,
46
+ "x-signature": bs58.encode(sig),
47
+ },
48
+ };
49
+ }
50
+ async inbandNonce(resp) {
51
+ let body;
52
+ try {
53
+ body = await resp.clone().json();
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ if (typeof body !== "object" || body === null)
59
+ return null;
60
+ const b = body;
61
+ const candidate = b["x-nonce"] ?? b["nonce"];
62
+ return typeof candidate === "string" && candidate ? candidate : null;
63
+ }
64
+ async fetchNonce(agent) {
65
+ const r = await agent.fetchImpl(`${agent.baseUrl}/nonce`, {
66
+ headers: { accept: "application/json" },
67
+ });
68
+ if (!r.ok)
69
+ throw new Error(`/nonce → ${r.status}`);
70
+ const json = (await r.json());
71
+ if (!json.nonce)
72
+ throw new Error("/nonce: missing 'nonce' field");
73
+ return json.nonce;
74
+ }
75
+ }
76
+ //# sourceMappingURL=aifinpay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aifinpay.js","sourceRoot":"","sources":["../../src/facilitators/aifinpay.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAGtC;;;;;;;;;GASG;AACH,MAAM,OAAO,mBAAmB;IAC9B,MAAM,CAAU,IAAI,GAAG,UAAU,CAAC;IACzB,IAAI,GAAG,UAAU,CAAC;IAE3B,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,IAAc;QAChC,IAAI,IAAI,CAAC,MAAM,KAAK,GAAG;YAAE,OAAO,KAAK,CAAC;QACtC,IAAI,IAAa,CAAC;QAClB,IAAI,CAAC;YACH,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC;QACnC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC;QAC5D,MAAM,CAAC,GAAG,IAA+B,CAAC;QAC1C,IAAI,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YACxE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,iEAAiE;QACjE,OAAO,CACL,CAAC,gBAAgB,IAAI,CAAC,IAAI,WAAW,IAAI,CAAC,CAAC;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