@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
@@ -0,0 +1,498 @@
1
+ // ──────────────────────────────────────────────────────────────────────────
2
+ // AiFinPayAgent — unified, chain-opaque developer surface.
3
+ //
4
+ // Wraps the legacy chain-aware Agent (Solana keypair + native methods) and
5
+ // adds an EVM signer plus high-level call/openSession/balance/verify flows.
6
+ // Chain selection happens inside the SDK via the provider registry +
7
+ // cost-band heuristics.
8
+ //
9
+ // This is the Phase 1 skeleton. Methods marked `// TODO(phase-N)` will be
10
+ // wired up as the migration progresses (see Obsidian/22 - Migration Roadmap).
11
+ // ──────────────────────────────────────────────────────────────────────────
12
+ import nacl from "tweetnacl";
13
+ import bs58 from "bs58";
14
+ import { createPublicClient, createWalletClient, http, } from "viem";
15
+ import { privateKeyToAccount, generatePrivateKey, } from "viem/accounts";
16
+ import { polygon } from "viem/chains";
17
+ import { AiFinPayError, X402Error, } from "./errors.js";
18
+ import { Agent } from "./agent.js";
19
+ // ── B2BSplitter contract (deployed at 0xE34Fc0…8440 on Polygon mainnet) ──
20
+ const SPLITTER_PAY_MATIC_ABI = [
21
+ {
22
+ type: "function",
23
+ name: "payMatic",
24
+ stateMutability: "payable",
25
+ inputs: [
26
+ { type: "address", name: "merchant" },
27
+ { type: "address", name: "ipCreator" },
28
+ { type: "string", name: "orderId" },
29
+ ],
30
+ outputs: [],
31
+ },
32
+ ];
33
+ // ── Errors ─────────────────────────────────────────────────────────────────
34
+ export class ProviderUnknownError extends AiFinPayError {
35
+ }
36
+ export class WrongChainBalanceError extends AiFinPayError {
37
+ has;
38
+ needed;
39
+ constructor(has, needed, msg) {
40
+ super(msg);
41
+ this.has = has;
42
+ this.needed = needed;
43
+ }
44
+ }
45
+ export class InsufficientFundsError extends AiFinPayError {
46
+ needed_usd;
47
+ available_usd;
48
+ constructor(needed_usd, available_usd, msg) {
49
+ super(msg);
50
+ this.needed_usd = needed_usd;
51
+ this.available_usd = available_usd;
52
+ }
53
+ }
54
+ export class BudgetCapExceededError extends AiFinPayError {
55
+ kind;
56
+ constructor(kind, msg) {
57
+ super(msg);
58
+ this.kind = kind;
59
+ }
60
+ }
61
+ export class SettlementError extends AiFinPayError {
62
+ reason;
63
+ txHash;
64
+ constructor(reason, txHash) {
65
+ super(`Settlement failed: ${reason}${txHash ? ` (tx ${txHash})` : ""}`);
66
+ this.reason = reason;
67
+ this.txHash = txHash;
68
+ }
69
+ }
70
+ export class SessionExpiredError extends AiFinPayError {
71
+ session_id;
72
+ constructor(session_id) {
73
+ super(`Session ${session_id} expired or closed`);
74
+ this.session_id = session_id;
75
+ }
76
+ }
77
+ // ── Spend tracker (24h rolling) ────────────────────────────────────────────
78
+ class SpendTracker {
79
+ ring = [];
80
+ add(usd) {
81
+ const now = Date.now();
82
+ this.ring.push({ at: now, usd });
83
+ const cutoff = now - 24 * 3600 * 1000;
84
+ while (this.ring.length && this.ring[0].at < cutoff)
85
+ this.ring.shift();
86
+ }
87
+ total24h() {
88
+ return this.ring.reduce((s, e) => s + e.usd, 0);
89
+ }
90
+ }
91
+ // ── Main class ─────────────────────────────────────────────────────────────
92
+ const DEFAULT_REGISTRY_PATH = "/api/providers";
93
+ export class AiFinPayAgent {
94
+ inner; // existing Solana-flavoured agent
95
+ evmAccount;
96
+ registryUrl;
97
+ polygonRpc;
98
+ cachedRegistry;
99
+ budgetCaps;
100
+ spend24h = new SpendTracker();
101
+ telemetry;
102
+ _polygonPublic;
103
+ _polygonWallet;
104
+ constructor(inner, evmAccount, opts = {}) {
105
+ this.inner = inner;
106
+ this.evmAccount = evmAccount;
107
+ this.registryUrl = opts.registryUrl
108
+ ?? `${inner.baseUrl}${DEFAULT_REGISTRY_PATH}`;
109
+ this.budgetCaps = opts.budgetCaps ?? {};
110
+ this.telemetry = opts.telemetry !== false;
111
+ this.polygonRpc = opts.polygonRpc ?? "https://polygon.drpc.org";
112
+ }
113
+ // Lazy viem clients — only spun up when a Polygon flow runs.
114
+ polygonClients() {
115
+ if (!this._polygonPublic) {
116
+ this._polygonPublic = createPublicClient({
117
+ chain: polygon,
118
+ transport: http(this.polygonRpc),
119
+ });
120
+ }
121
+ if (!this._polygonWallet) {
122
+ this._polygonWallet = createWalletClient({
123
+ chain: polygon,
124
+ transport: http(this.polygonRpc),
125
+ account: this.evmAccount,
126
+ });
127
+ }
128
+ return { publicClient: this._polygonPublic, walletClient: this._polygonWallet };
129
+ }
130
+ // ── Constructors ─────────────────────────────────────────────────────────
131
+ /**
132
+ * Generate a fresh agent — new Solana keypair + new EVM keypair.
133
+ * Use `fromSeed()` to derive both from a single backup phrase instead.
134
+ */
135
+ static async new(opts = {}) {
136
+ const inner = Agent.new(opts);
137
+ const evmKey = opts.evmPrivateKey ?? generatePrivateKey();
138
+ const evmAccount = privateKeyToAccount(evmKey);
139
+ return new AiFinPayAgent(inner, evmAccount, opts);
140
+ }
141
+ /**
142
+ * Derive both keypairs from a single 32-byte hex seed. Same seed →
143
+ * deterministic Solana pubkey AND EVM address. One backup phrase, two
144
+ * chains.
145
+ *
146
+ * Solana key = nacl.sign.keyPair.fromSeed(seed)
147
+ * EVM key = keccak256(seed)[:32] (independent path; not BIP-44
148
+ * compatible — see design notes
149
+ * in 23 - Unified SDK Design).
150
+ *
151
+ * TODO(phase-1): replace with BIP-39/BIP-44 derivation
152
+ * m/44'/501'/0'/0' (Solana) + m/44'/60'/0'/0/0 (EVM) once the
153
+ * wallet-import audit recommendation lands.
154
+ */
155
+ static async fromSeed(seedHex, opts = {}) {
156
+ const seed = hexToBytes(seedHex.replace(/^0x/, ""));
157
+ if (seed.length !== 32) {
158
+ throw new AiFinPayError(`fromSeed: seed must be 32 bytes (64 hex chars)`);
159
+ }
160
+ const kp = nacl.sign.keyPair.fromSeed(seed);
161
+ const inner = Agent
162
+ ._ofKeyPair?.(kp, opts) ?? Agent.fromSecretB58(bs58.encode(kp.secretKey), opts);
163
+ // Derive EVM key from seed (independent, not BIP-44 — see TODO above)
164
+ const evmHex = ("0x" + bytesToHex(crypto32(seed)));
165
+ const evmAccount = privateKeyToAccount(evmHex);
166
+ return new AiFinPayAgent(inner, evmAccount, opts);
167
+ }
168
+ /**
169
+ * Legacy: load the Solana side from an existing keypair, then either
170
+ * generate a fresh EVM key or import one with `attachEvmKey`.
171
+ */
172
+ static async fromSolanaSecret(secretB58, opts = {}) {
173
+ const inner = Agent.fromSecretB58(secretB58, opts);
174
+ const evmKey = opts.evmPrivateKey ?? generatePrivateKey();
175
+ const evmAccount = privateKeyToAccount(evmKey);
176
+ return new AiFinPayAgent(inner, evmAccount, opts);
177
+ }
178
+ // ── Identity ────────────────────────────────────────────────────────────
179
+ get id() {
180
+ // Canonical: Solana pubkey for back-compat with the leaderboard / Seat PDA.
181
+ return this.inner.address;
182
+ }
183
+ get solanaAddress() { return this.inner.address; }
184
+ get evmAddress() { return this.evmAccount.address; }
185
+ // ── Registry ────────────────────────────────────────────────────────────
186
+ async fetchRegistry(force = false) {
187
+ if (this.cachedRegistry && !force)
188
+ return this.cachedRegistry;
189
+ const r = await fetch(this.registryUrl);
190
+ if (!r.ok) {
191
+ throw new AiFinPayError(`provider registry ${this.registryUrl} → ${r.status}`);
192
+ }
193
+ const j = (await r.json());
194
+ this.cachedRegistry = j.providers ?? [];
195
+ return this.cachedRegistry;
196
+ }
197
+ async resolveProvider(name) {
198
+ const reg = await this.fetchRegistry();
199
+ const hit = reg.find((p) => p.name === name);
200
+ if (!hit) {
201
+ throw new ProviderUnknownError(`Provider "${name}" not in registry ${this.registryUrl}`);
202
+ }
203
+ return hit;
204
+ }
205
+ // ── Budget caps ─────────────────────────────────────────────────────────
206
+ setBudget(caps) {
207
+ this.budgetCaps = caps;
208
+ }
209
+ checkBudget(costUsd) {
210
+ if (this.budgetCaps.per_call_usd !== undefined && costUsd > this.budgetCaps.per_call_usd) {
211
+ throw new BudgetCapExceededError("per_call", `cost $${costUsd} exceeds per-call cap $${this.budgetCaps.per_call_usd}`);
212
+ }
213
+ const after = this.spend24h.total24h() + costUsd;
214
+ if (this.budgetCaps.daily_usd !== undefined && after > this.budgetCaps.daily_usd) {
215
+ throw new BudgetCapExceededError("daily", `daily spend ${after.toFixed(4)} would exceed cap $${this.budgetCaps.daily_usd}`);
216
+ }
217
+ }
218
+ // ── Routing — chain selection ───────────────────────────────────────────
219
+ /**
220
+ * Chain selection heuristic — see Obsidian/23 - Unified SDK Design §Routing.
221
+ *
222
+ * 1. Explicit override always wins (subject to provider acceptance).
223
+ * 2. Cost ≤ $0.005 + Solana per-call live + Solana accepted → Solana
224
+ * (low gas wins for tiny calls).
225
+ * 3. Cost > $0.05 + Polygon accepted → Polygon
226
+ * (better finality for high-value calls).
227
+ * 4. Middle band → provider.preferred_chain.
228
+ * 5. Fallback → first accepted chain.
229
+ *
230
+ * Solana per-call is gated on the deploy of `b2b_pay_with_split` —
231
+ * until then `solana` selection raises in `call()`.
232
+ */
233
+ pickChain(provider, opts) {
234
+ const accepted = new Set(provider.accepted_chains);
235
+ // 1. Override.
236
+ if (opts.chain) {
237
+ if (!accepted.has(opts.chain)) {
238
+ throw new AiFinPayError(`Provider ${provider.name} does not accept ${opts.chain}; accepted: ${provider.accepted_chains.join(", ")}`);
239
+ }
240
+ return opts.chain;
241
+ }
242
+ const cost = opts.cost ?? provider.price_usd;
243
+ const solanaPerCallLive = process.env.AIFINPAY_SOLANA_PER_CALL === "live";
244
+ // 2. Tiny calls → Solana.
245
+ if (cost <= 0.005 && accepted.has("solana") && solanaPerCallLive) {
246
+ return "solana";
247
+ }
248
+ // 3. Big calls → Polygon for finality.
249
+ if (cost > 0.05 && accepted.has("polygon")) {
250
+ return "polygon";
251
+ }
252
+ // 4. Middle band → preferred.
253
+ if (accepted.has(provider.preferred_chain)) {
254
+ return provider.preferred_chain;
255
+ }
256
+ // 5. Fallback.
257
+ if (provider.accepted_chains[0])
258
+ return provider.accepted_chains[0];
259
+ throw new AiFinPayError(`Provider ${provider.name} declares no accepted_chains`);
260
+ }
261
+ // ── Verify (one-time on-chain registration) ─────────────────────────────
262
+ /**
263
+ * TODO(phase-4): mint AgentPassport on the cheapest chain available
264
+ * with the requested `stake_usd`. For now wires only the Solana side
265
+ * via the existing `reserveSeatInvoice` semantics.
266
+ */
267
+ async verify(_args) {
268
+ throw new AiFinPayError("verify() not implemented yet — see migration phase 4");
269
+ }
270
+ // ── Funding (deposit) ───────────────────────────────────────────────────
271
+ /**
272
+ * TODO(phase-1): pick a chain (preferred USDC on Polygon for stability;
273
+ * fallback Solana SOL). Return signed-tx instructions for the wallet.
274
+ */
275
+ async deposit(_usd, _opts) {
276
+ throw new AiFinPayError("deposit() not implemented yet — see migration phase 1.5");
277
+ }
278
+ // ── Call ────────────────────────────────────────────────────────────────
279
+ /**
280
+ * High-level paid call. Resolves the provider, picks a chain, builds the
281
+ * payment, sends to the bridge, retries with payment proof.
282
+ *
283
+ * Phase 1 implementation: Polygon per-call splitter via on-chain
284
+ * `B2BSplitter.payMatic()`. Solana per-call branch lights up after
285
+ * Phase 2 (b2b_pay_with_split deploy via Squads).
286
+ */
287
+ async call(opts) {
288
+ const provider = await this.resolveProvider(opts.provider);
289
+ const chain = this.pickChain(provider, opts);
290
+ const cost = opts.cost ?? provider.price_usd;
291
+ this.checkBudget(cost);
292
+ if (provider.mode === "session") {
293
+ throw new AiFinPayError(`Provider ${provider.name} requires session mode — use openSession() (phase-3 feature)`);
294
+ }
295
+ const url = opts.bridgeUrl ?? provider.bridge_url;
296
+ if (!url) {
297
+ throw new AiFinPayError(`Provider ${provider.name} has no bridge_url`);
298
+ }
299
+ if (chain === "solana") {
300
+ throw new AiFinPayError(`Solana per-call payment requires b2b_pay_with_split (phase-2). ` +
301
+ `Use chain: "polygon" override or wait for the Solana program upgrade.`);
302
+ }
303
+ const path = (() => {
304
+ if (provider.service_type === "search")
305
+ return "/search";
306
+ if (provider.service_type === "inference")
307
+ return "/chat/completions";
308
+ if (provider.service_type === "compute")
309
+ return "/run";
310
+ if (provider.service_type === "analytics")
311
+ return "/query";
312
+ return "/";
313
+ })();
314
+ const buildInit = (extraHeaders = {}) => ({
315
+ method: opts.method ?? "POST",
316
+ headers: { "content-type": "application/json", ...extraHeaders },
317
+ body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
318
+ signal: opts.signal,
319
+ });
320
+ // 1. Initial unauthenticated POST → expect 402 challenge from the bridge.
321
+ const fullUrl = url.replace(/\/$/, "") + path;
322
+ const initialResp = await this.inner.fetchImpl(fullUrl, buildInit());
323
+ if (initialResp.status !== 402) {
324
+ // Bridge didn't ask for payment — pass response through unchanged.
325
+ this.spend24h.add(cost);
326
+ if (this.telemetry)
327
+ this.reportTelemetry({ kind: "call", provider: provider.name, chain, cost, free: true });
328
+ return initialResp;
329
+ }
330
+ let challenge;
331
+ try {
332
+ challenge = (await initialResp.json());
333
+ }
334
+ catch (e) {
335
+ throw new X402Error(`bridge returned 402 with non-JSON body`);
336
+ }
337
+ if (!challenge.pay_matic) {
338
+ throw new X402Error(`bridge ${provider.name} returned 402 but no pay_matic block — only legacy AiFinPay/Coinbase facilitators not yet wired into AiFinPayAgent.call()`);
339
+ }
340
+ const pm = challenge.pay_matic;
341
+ // 2. Submit B2BSplitter.payMatic on Polygon mainnet.
342
+ const { publicClient, walletClient } = this.polygonClients();
343
+ const txHash = await walletClient.writeContract({
344
+ address: pm.splitter,
345
+ abi: SPLITTER_PAY_MATIC_ABI,
346
+ functionName: "payMatic",
347
+ args: [
348
+ pm.merchant_wallet,
349
+ "0x0000000000000000000000000000000000000000",
350
+ pm.order_id,
351
+ ],
352
+ value: BigInt(pm.total_wei),
353
+ chain: polygon,
354
+ account: this.evmAccount,
355
+ });
356
+ // 3. Wait for receipt (we only need inclusion for Polygon's 2s blocks).
357
+ const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
358
+ if (receipt.status !== "success") {
359
+ throw new AiFinPayError(`Polygon tx reverted: ${txHash}`);
360
+ }
361
+ // 4. Retry the bridge with payment proof.
362
+ const paidResp = await this.inner.fetchImpl(fullUrl, buildInit({
363
+ "x-tx-hash": txHash,
364
+ "x-order-id": pm.order_id,
365
+ }));
366
+ if (!paidResp.ok) {
367
+ const detail = await paidResp.text().catch(() => "<unreadable>");
368
+ throw new AiFinPayError(`Bridge retry failed ${paidResp.status} after on-chain payment ${txHash}: ${detail.slice(0, 300)}`);
369
+ }
370
+ this.spend24h.add(cost);
371
+ if (this.telemetry)
372
+ this.reportTelemetry({ kind: "call", provider: provider.name, chain, cost, tx: txHash });
373
+ return paidResp;
374
+ }
375
+ // ── Sessions ────────────────────────────────────────────────────────────
376
+ /**
377
+ * TODO(phase-3): open a metered budget session.
378
+ */
379
+ async openSession(_args) {
380
+ throw new AiFinPayError("openSession() not implemented yet — see migration phase 3");
381
+ }
382
+ // ── Balance ─────────────────────────────────────────────────────────────
383
+ /**
384
+ * Snapshot the agent's funds across both chains, USD-normalised.
385
+ *
386
+ * Phase 1.4: native MATIC + native SOL via RPC; ERC-20 / SPL token balances
387
+ * deferred (we don't yet need them for the unified `call()` flow which
388
+ * settles in MATIC). Pyth feeds are TODO; for now uses
389
+ * `AIFINPAY_MATIC_USD` and `AIFINPAY_SOL_USD` env, defaulting to 0.7 and 200.
390
+ */
391
+ async balance() {
392
+ const maticUsd = parseFloat(process.env.AIFINPAY_MATIC_USD ?? "0.70");
393
+ const solUsd = parseFloat(process.env.AIFINPAY_SOL_USD ?? "200");
394
+ const polygon = await this.fetchPolygonNative().catch(() => 0);
395
+ const solana = await this.fetchSolanaNative().catch(() => 0);
396
+ const polygonUsd = polygon * maticUsd;
397
+ const solanaUsd = solana * solUsd;
398
+ return {
399
+ agent_balance_usd: polygonUsd + solanaUsd,
400
+ chains: {
401
+ solana: { sol: solana, usdc: 0, msecco_balance: 0 },
402
+ polygon: { matic: polygon, usdc: 0, msecco_balance: 0 },
403
+ },
404
+ spend_24h_usd: this.spend24h.total24h(),
405
+ budget_caps: this.budgetCaps,
406
+ priced_at: Math.floor(Date.now() / 1000),
407
+ };
408
+ }
409
+ async fetchPolygonNative() {
410
+ const { publicClient } = this.polygonClients();
411
+ const wei = await publicClient.getBalance({
412
+ address: this.evmAccount.address,
413
+ });
414
+ return Number(wei) / 1e18;
415
+ }
416
+ async fetchSolanaNative() {
417
+ // Use raw JSON-RPC to avoid pulling @solana/web3.js as a dep.
418
+ const rpc = process.env.AIFINPAY_SOLANA_RPC || "https://api.mainnet.solana.com";
419
+ const r = await this.inner.fetchImpl(rpc, {
420
+ method: "POST",
421
+ headers: { "content-type": "application/json" },
422
+ body: JSON.stringify({
423
+ jsonrpc: "2.0",
424
+ id: 1,
425
+ method: "getBalance",
426
+ params: [this.solanaAddress],
427
+ }),
428
+ });
429
+ if (!r.ok)
430
+ return 0;
431
+ const j = (await r.json());
432
+ const lamports = j.result?.value ?? 0;
433
+ return lamports / 1e9;
434
+ }
435
+ // ── Reputation ──────────────────────────────────────────────────────────
436
+ /**
437
+ * TODO(phase-4 / phase-5): query operator backend reputation engine.
438
+ */
439
+ async reputation() {
440
+ return {
441
+ trust_score: 0,
442
+ spend_score: 0,
443
+ tenure_days: 0,
444
+ verified: false,
445
+ flags: [],
446
+ };
447
+ }
448
+ // ── Telemetry (opt-out) ─────────────────────────────────────────────────
449
+ reportTelemetry(payload) {
450
+ // Fire-and-forget. No body content, only metadata.
451
+ void this.inner.fetchImpl(`${this.inner.baseUrl}/api/telemetry`, {
452
+ method: "POST",
453
+ headers: { "content-type": "application/json" },
454
+ body: JSON.stringify({ agent_id: this.id, ...payload, ts: Date.now() }),
455
+ }).catch(() => { });
456
+ }
457
+ }
458
+ // ── Internal hex helpers (small, no extra deps) ────────────────────────────
459
+ function hexToBytes(hex) {
460
+ const out = new Uint8Array(hex.length / 2);
461
+ for (let i = 0; i < out.length; i++) {
462
+ out[i] = parseInt(hex.substr(i * 2, 2), 16);
463
+ }
464
+ return out;
465
+ }
466
+ function bytesToHex(b) {
467
+ let s = "";
468
+ for (let i = 0; i < b.length; i++)
469
+ s += b[i].toString(16).padStart(2, "0");
470
+ return s;
471
+ }
472
+ /**
473
+ * Derive a 32-byte EVM private key from a 32-byte seed using a domain-separated
474
+ * SHA-256 hash. Independent of the Solana keypair; same seed reproduces the
475
+ * same EVM key.
476
+ *
477
+ * Domain separator: "aifinpay:evm:v1\0" prevents accidental key collision with
478
+ * any other system that hashes this seed.
479
+ *
480
+ * TODO(phase-1): swap to a real BIP-44 path (`m/44'/60'/0'/0/0`) once we ship
481
+ * BIP-39 mnemonic support. This helper is stop-gap so the unified API can ship
482
+ * before audit-grade derivation lands.
483
+ */
484
+ function crypto32(seed) {
485
+ // Lazy require to avoid pulling node:crypto into bundlers that don't need it.
486
+ const c = globalThis.crypto;
487
+ if (c?.subtle) {
488
+ // Browser / modern Node — but subtle is async, and we're sync here.
489
+ // Fall through to the node:crypto path.
490
+ }
491
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
492
+ const nodeCrypto = require("node:crypto");
493
+ const h = nodeCrypto.createHash("sha256");
494
+ h.update("aifinpay:evm:v1\0");
495
+ h.update(seed);
496
+ return new Uint8Array(h.digest());
497
+ }
498
+ //# sourceMappingURL=unifiedAgent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unifiedAgent.js","sourceRoot":"","sources":["../src/unifiedAgent.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,2DAA2D;AAC3D,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,qEAAqE;AACrE,wBAAwB;AACxB,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,6EAA6E;AAC7E,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EACL,kBAAkB,EAClB,kBAAkB,EAClB,IAAI,GAGL,MAAM,MAAM,CAAC;AACd,OAAO,EACL,mBAAmB,EACnB,kBAAkB,GAEnB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,aAAa,EACb,SAAS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AAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAC5E,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;;;;;;;;GAWG;AACH,SAAS,QAAQ,CAAC,IAAgB;IAChC,8EAA8E;IAC9E,MAAM,CAAC,GAAI,UAAqD,CAAC,MAAM,CAAC;IACxE,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;QACd,oEAAoE;QACpE,wCAAwC;IAC1C,CAAC;IACD,iEAAiE;IACjE,MAAM,UAAU,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IAC1C,MAAM,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;IAC1C,CAAC,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;IAC9B,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACf,OAAO,IAAI,UAAU,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;AACpC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aifinpay/agent",
3
- "version": "0.1.0-alpha.1",
4
- "description": "Non-custodial x402 payment client for autonomous AI agents on AiFinPay (Solana + Polygon)",
3
+ "version": "0.3.0-alpha.0",
4
+ "description": "Unified agent-economy SDK for autonomous AI agents chain-opaque AiFinPayAgent surface (call/openSession/balance/verify) over Polygon and Solana execution environments.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -11,9 +11,14 @@
11
11
  "default": "./dist/index.js"
12
12
  }
13
13
  },
14
- "files": ["dist", "README.md", "LICENSE"],
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
15
19
  "scripts": {
16
20
  "build": "tsc -p tsconfig.json",
21
+ "test": "vitest run",
17
22
  "prepublishOnly": "npm run build"
18
23
  },
19
24
  "keywords": [
@@ -27,20 +32,22 @@
27
32
  ],
28
33
  "author": "CoinSecurities (SECCO) <contact@aifinpay.company>",
29
34
  "license": "MIT",
30
- "homepage": "https://aifinpay.company",
35
+ "homepage": "https://github.com/AiFinPay/sdk#readme",
31
36
  "repository": {
32
37
  "type": "git",
33
- "url": "git+https://github.com/enot3615/oracle-financial-hub-59.git",
34
- "directory": "sdk/node"
38
+ "url": "git+https://github.com/AiFinPay/sdk.git",
39
+ "directory": "node"
35
40
  },
36
- "bugs": "https://github.com/enot3615/oracle-financial-hub-59/issues",
41
+ "bugs": "https://github.com/AiFinPay/sdk/issues",
37
42
  "dependencies": {
38
43
  "bs58": "^6.0.0",
39
- "tweetnacl": "^1.0.3"
44
+ "tweetnacl": "^1.0.3",
45
+ "viem": "^2.21.0"
40
46
  },
41
47
  "devDependencies": {
42
48
  "@types/node": "^20.0.0",
43
- "typescript": "^5.4.0"
49
+ "typescript": "^5.4.0",
50
+ "vitest": "^4.1.5"
44
51
  },
45
52
  "engines": {
46
53
  "node": ">=18"