@agether/sdk 2.6.1 → 2.8.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 (37) hide show
  1. package/README.md +39 -27
  2. package/dist/cli.js +54 -36
  3. package/dist/index.d.mts +43 -14
  4. package/dist/index.d.ts +43 -14
  5. package/dist/index.js +65 -32
  6. package/dist/index.mjs +62 -32
  7. package/package.json +2 -2
  8. package/dist/cli.d.ts +0 -27
  9. package/dist/cli.d.ts.map +0 -1
  10. package/dist/clients/AgentIdentityClient.d.ts +0 -188
  11. package/dist/clients/AgentIdentityClient.d.ts.map +0 -1
  12. package/dist/clients/AgentIdentityClient.js +0 -337
  13. package/dist/clients/AgetherClient.d.ts +0 -74
  14. package/dist/clients/AgetherClient.d.ts.map +0 -1
  15. package/dist/clients/AgetherClient.js +0 -172
  16. package/dist/clients/MorphoClient.d.ts +0 -482
  17. package/dist/clients/MorphoClient.d.ts.map +0 -1
  18. package/dist/clients/MorphoClient.js +0 -1717
  19. package/dist/clients/ScoringClient.d.ts +0 -89
  20. package/dist/clients/ScoringClient.d.ts.map +0 -1
  21. package/dist/clients/ScoringClient.js +0 -93
  22. package/dist/clients/X402Client.d.ts +0 -168
  23. package/dist/clients/X402Client.d.ts.map +0 -1
  24. package/dist/clients/X402Client.js +0 -378
  25. package/dist/index.d.ts.map +0 -1
  26. package/dist/types/index.d.ts +0 -132
  27. package/dist/types/index.d.ts.map +0 -1
  28. package/dist/types/index.js +0 -46
  29. package/dist/utils/abis.d.ts +0 -29
  30. package/dist/utils/abis.d.ts.map +0 -1
  31. package/dist/utils/abis.js +0 -139
  32. package/dist/utils/config.d.ts +0 -36
  33. package/dist/utils/config.d.ts.map +0 -1
  34. package/dist/utils/config.js +0 -168
  35. package/dist/utils/format.d.ts +0 -44
  36. package/dist/utils/format.d.ts.map +0 -1
  37. package/dist/utils/format.js +0 -75
@@ -1,378 +0,0 @@
1
- /**
2
- * x402 HTTP Client — Make paid API calls via the x402 protocol (v2)
3
- *
4
- * Built on top of the official @x402/fetch + @x402/evm SDK.
5
- * https://docs.x402.org/getting-started/quickstart-for-buyers
6
- *
7
- * Flow:
8
- * 1. Client → Resource Server (normal request)
9
- * 2. Resource Server → 402 with PAYMENT-REQUIRED header (base64 JSON)
10
- * 3. @x402/fetch auto-picks PaymentRequirements, signs EIP-3009 via EVM scheme
11
- * 4. Client → Resource Server (retries with PAYMENT-SIGNATURE header)
12
- * 5. Resource Server → verifies via facilitator → settles → 200 + data
13
- *
14
- * Auto-Draw: When autoDraw is enabled and USDC balance is insufficient,
15
- * the client automatically borrows from Morpho Blue before paying.
16
- *
17
- * Spending Limits: Optional daily spending cap (dailySpendLimitUsdc) and
18
- * yield-limited spending (yieldLimitedSpending) to keep borrows within
19
- * theoretical collateral yield.
20
- *
21
- * Chain support: Base (8453), Base Sepolia (84532), Ethereum (1).
22
- */
23
- import { wrapFetchWithPayment } from '@x402/fetch';
24
- import { x402Client } from '@x402/core/client';
25
- import { registerExactEvmScheme } from '@x402/evm/exact/client';
26
- import { privateKeyToAccount, toAccount } from 'viem/accounts';
27
- // ──────────────────── Client ────────────────────
28
- export class X402Client {
29
- constructor(config) {
30
- this.config = config;
31
- // ── Step 1: Resolve base signer from privateKey or walletClient ──
32
- let baseSigner;
33
- if ('walletClient' in config && config.walletClient) {
34
- // External WalletClient mode (Privy, Turnkey, MetaMask, etc.)
35
- const wc = config.walletClient;
36
- const account = wc.account;
37
- if (!account) {
38
- throw new Error('X402Client: walletClient must have an attached account. ' +
39
- 'Pass an account when creating the WalletClient or use privateKey mode instead.');
40
- }
41
- this.address = account.address;
42
- // Adapt WalletClient to the signer interface expected by @x402/evm
43
- baseSigner = {
44
- address: account.address,
45
- signTypedData: (msg) => wc.signTypedData({
46
- account,
47
- domain: msg.domain,
48
- types: msg.types,
49
- primaryType: msg.primaryType,
50
- message: msg.message,
51
- }),
52
- };
53
- }
54
- else if ('privateKey' in config && config.privateKey) {
55
- // Private key mode (existing behavior — SDK manages wallet)
56
- const privateKey = config.privateKey.startsWith('0x')
57
- ? config.privateKey
58
- : `0x${config.privateKey}`;
59
- const account = privateKeyToAccount(privateKey);
60
- this.address = account.address;
61
- baseSigner = account;
62
- }
63
- else {
64
- throw new Error('X402Client: provide either privateKey or walletClient in config.');
65
- }
66
- // ── Step 2: Wrap signer for smart-wallet (AgentAccount) if accountAddress is set ──
67
- // When accountAddress is provided, EIP-3009 `from` must be the contract, and
68
- // the signature must be >65 bytes so the x402 facilitator routes through USDC's
69
- // `bytes signature` overload of transferWithAuthorization — triggering EIP-1271
70
- // `isValidSignature` on the AgentAccount contract.
71
- let signer;
72
- if (config.accountAddress) {
73
- const accountAddr = config.accountAddress;
74
- const inner = baseSigner;
75
- signer = toAccount({
76
- address: accountAddr,
77
- async signMessage({ message }) {
78
- if ('signMessage' in inner && typeof inner.signMessage === 'function') {
79
- return inner.signMessage({ message });
80
- }
81
- throw new Error('signMessage not supported by underlying signer');
82
- },
83
- async signTransaction(tx) {
84
- if ('signTransaction' in inner && typeof inner.signTransaction === 'function') {
85
- return inner.signTransaction(tx);
86
- }
87
- throw new Error('signTransaction not supported by underlying signer');
88
- },
89
- async signTypedData(typedData) {
90
- const sig = await inner.signTypedData(typedData);
91
- // For Safe7579: prepend validator module address so isValidSignature
92
- // routes through Safe7579 → validator.isValidSignatureWithSender()
93
- if (config.validatorModule) {
94
- const validatorHex = config.validatorModule.replace('0x', '').toLowerCase();
95
- const sigHex = sig.replace('0x', '');
96
- return `0x${validatorHex}${sigHex}`;
97
- }
98
- // Fallback: append 00 to trigger EIP-1271 via >65 byte sig
99
- return `${sig}00`;
100
- },
101
- });
102
- this.address = accountAddr;
103
- }
104
- else {
105
- signer = baseSigner;
106
- }
107
- // Create x402 client and register EVM scheme (handles EIP-3009 signing)
108
- const client = new x402Client();
109
- registerExactEvmScheme(client, { signer });
110
- // Wrap native fetch with automatic 402 payment handling
111
- this.paidFetch = wrapFetchWithPayment(fetch, client);
112
- // Initialize spending tracker
113
- const today = new Date().toISOString().split('T')[0];
114
- const dailyLimit = config.dailySpendLimitUsdc
115
- ? BigInt(Math.round(parseFloat(config.dailySpendLimitUsdc) * 1e6))
116
- : 0n;
117
- this._spendingTracker = { date: today, totalBorrowed: 0n, dailyLimit };
118
- }
119
- async get(url, opts) {
120
- return this.request(url, { ...opts, method: 'GET' });
121
- }
122
- async post(url, body, opts) {
123
- return this.request(url, {
124
- ...opts,
125
- method: 'POST',
126
- body: body ? JSON.stringify(body) : undefined,
127
- headers: { 'Content-Type': 'application/json', ...opts?.headers },
128
- });
129
- }
130
- getAddress() {
131
- return this.address;
132
- }
133
- /** Get the current spending tracker state */
134
- getSpendingTracker() {
135
- this._resetTrackerIfNewDay();
136
- return { ...this._spendingTracker };
137
- }
138
- /** Get remaining daily spending allowance in USDC (human-readable) */
139
- getRemainingDailyAllowance() {
140
- this._resetTrackerIfNewDay();
141
- if (this._spendingTracker.dailyLimit === 0n)
142
- return 'unlimited';
143
- const remaining = this._spendingTracker.dailyLimit - this._spendingTracker.totalBorrowed;
144
- return (Number(remaining > 0n ? remaining : 0n) / 1e6).toFixed(2);
145
- }
146
- /**
147
- * Pay with auto-draw: Make an x402 request with automatic Morpho borrowing.
148
- *
149
- * Flow:
150
- * 1. Check USDC balance on AgentAccount
151
- * 2. Probe the URL to discover payment amount (if 402)
152
- * 3. If insufficient USDC, calculate deficit
153
- * 4. Check spending limit
154
- * 5. Borrow from Morpho via MorphoClient
155
- * 6. Proceed with x402 payment
156
- */
157
- async payWithAutoDraw(url, opts) {
158
- const { morphoClient, ...fetchOpts } = opts || {};
159
- // If auto-draw is not enabled or no morphoClient, fall back to normal request
160
- if (!this.config.autoDraw || !morphoClient) {
161
- return this.request(url, fetchOpts);
162
- }
163
- try {
164
- // Step 1: Check current USDC balance on AgentAccount
165
- const usdcBalance = await morphoClient.getUsdcBalance();
166
- console.log(` [auto-draw] AgentAccount USDC balance: ${(Number(usdcBalance) / 1e6).toFixed(2)}`);
167
- // Step 2: Probe the URL to discover payment amount
168
- const paymentAmount = await this._probePaymentAmount(url, fetchOpts);
169
- if (paymentAmount !== null) {
170
- console.log(` [auto-draw] Payment required: ${(Number(paymentAmount) / 1e6).toFixed(6)} USDC`);
171
- // Step 3: Check if we need to borrow
172
- const bufferStr = this.config.autoDrawBuffer || '0.5';
173
- const buffer = BigInt(Math.round(parseFloat(bufferStr) * 1e6));
174
- const needed = paymentAmount + buffer;
175
- if (usdcBalance < needed) {
176
- const deficit = needed - usdcBalance;
177
- console.log(` [auto-draw] Insufficient balance. Need to borrow ${(Number(deficit) / 1e6).toFixed(2)} USDC`);
178
- // Step 4: Check spending limits
179
- const limitCheck = await this._checkSpendingLimit(deficit, morphoClient);
180
- if (!limitCheck.allowed) {
181
- return {
182
- success: false,
183
- error: `Auto-draw blocked: ${limitCheck.reason}`,
184
- };
185
- }
186
- // Step 5: Check if borrowing is possible (collateral check)
187
- const maxBorrowable = await morphoClient.getMaxBorrowable();
188
- if (maxBorrowable.total < deficit) {
189
- return {
190
- success: false,
191
- error: `Auto-draw failed: insufficient collateral. Need ${(Number(deficit) / 1e6).toFixed(2)} USDC but can only borrow ${(Number(maxBorrowable.total) / 1e6).toFixed(2)} USDC more.`,
192
- };
193
- }
194
- // Step 6: Borrow the deficit
195
- const borrowAmount = (Number(deficit) / 1e6).toFixed(6);
196
- console.log(` [auto-draw] Borrowing ${borrowAmount} USDC from Morpho...`);
197
- const borrowResult = await morphoClient.borrow(borrowAmount);
198
- console.log(` [auto-draw] Borrow tx: ${borrowResult.tx}`);
199
- // Track spending
200
- this._trackSpending(deficit);
201
- // Step 7: Now proceed with the x402 payment
202
- const result = await this.request(url, fetchOpts);
203
- return {
204
- ...result,
205
- autoDrawInfo: {
206
- borrowed: borrowAmount,
207
- borrowTx: borrowResult.tx,
208
- reason: `USDC balance insufficient (had ${(Number(usdcBalance) / 1e6).toFixed(2)}, needed ${(Number(needed) / 1e6).toFixed(2)})`,
209
- },
210
- };
211
- }
212
- }
213
- // Balance sufficient or couldn't determine amount — proceed normally
214
- return this.request(url, fetchOpts);
215
- }
216
- catch (error) {
217
- // If auto-draw fails, still try the normal request
218
- console.log(` [auto-draw] Auto-draw check failed: ${error instanceof Error ? error.message : String(error)}. Proceeding with normal request.`);
219
- return this.request(url, fetchOpts);
220
- }
221
- }
222
- // ──────────── Core request — @x402/fetch handles 402 automatically ────────────
223
- async request(url, options) {
224
- try {
225
- console.log(` [x402] ${options?.method || 'GET'} ${url}`);
226
- const response = await this.paidFetch(url, {
227
- ...options,
228
- headers: {
229
- ...options?.headers,
230
- 'X-Agent-Id': this.config.agentId || '',
231
- },
232
- });
233
- if (response.ok) {
234
- const data = await response.json();
235
- // Check for settlement response header
236
- const paymentResponse = response.headers.get('PAYMENT-RESPONSE');
237
- let txHash;
238
- if (paymentResponse) {
239
- try {
240
- const settlement = JSON.parse(Buffer.from(paymentResponse, 'base64').toString('utf-8'));
241
- txHash = settlement.transaction;
242
- }
243
- catch (e) {
244
- console.warn('[agether] x402 payment response parse failed:', e instanceof Error ? e.message : e);
245
- }
246
- }
247
- return {
248
- success: true,
249
- data,
250
- ...(txHash ? {
251
- paymentInfo: {
252
- amount: '',
253
- asset: 'USDC',
254
- network: 'eip155:8453',
255
- txHash,
256
- },
257
- } : {}),
258
- };
259
- }
260
- // If we get here, @x402/fetch already tried to pay but the server rejected
261
- const errBody = await response.text();
262
- return {
263
- success: false,
264
- error: `HTTP ${response.status}: ${errBody}`,
265
- };
266
- }
267
- catch (error) {
268
- return {
269
- success: false,
270
- error: `Request failed: ${error instanceof Error ? error.message : String(error)}`,
271
- };
272
- }
273
- }
274
- // ──────────── Auto-Draw Helpers ────────────
275
- /**
276
- * Probe a URL to discover payment requirements without paying.
277
- * Makes a request and parses the 402 PAYMENT-REQUIRED header.
278
- * @returns Payment amount in raw USDC units (6 decimals), or null if not a 402.
279
- */
280
- async _probePaymentAmount(url, options) {
281
- try {
282
- const response = await fetch(url, {
283
- ...options,
284
- headers: {
285
- ...options?.headers,
286
- 'X-Agent-Id': this.config.agentId || '',
287
- },
288
- });
289
- if (response.status !== 402)
290
- return null;
291
- // Parse PAYMENT-REQUIRED header (base64 JSON)
292
- const paymentHeader = response.headers.get('X-PAYMENT') || response.headers.get('PAYMENT-REQUIRED');
293
- if (!paymentHeader)
294
- return null;
295
- try {
296
- const decoded = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf-8'));
297
- const requirements = Array.isArray(decoded) ? decoded : decoded.accepts || [decoded];
298
- if (requirements.length > 0) {
299
- const amount = requirements[0].maxAmountRequired || requirements[0].amount;
300
- if (amount) {
301
- return BigInt(amount);
302
- }
303
- }
304
- }
305
- catch (e) {
306
- console.warn('[agether] x402 payment header parse failed:', e instanceof Error ? e.message : e);
307
- }
308
- return null;
309
- }
310
- catch (e) {
311
- console.warn('[agether] x402 getPaymentRequired failed:', e instanceof Error ? e.message : e);
312
- return null;
313
- }
314
- }
315
- /** Reset spending tracker if it's a new day */
316
- _resetTrackerIfNewDay() {
317
- const today = new Date().toISOString().split('T')[0];
318
- if (this._spendingTracker.date !== today) {
319
- this._spendingTracker = {
320
- date: today,
321
- totalBorrowed: 0n,
322
- dailyLimit: this._spendingTracker.dailyLimit,
323
- };
324
- }
325
- }
326
- /** Track a new spending amount */
327
- _trackSpending(amount) {
328
- this._resetTrackerIfNewDay();
329
- this._spendingTracker.totalBorrowed += amount;
330
- }
331
- /**
332
- * Check if a borrow amount is within spending limits.
333
- * Considers both fixed daily limits and yield-limited spending.
334
- */
335
- async _checkSpendingLimit(amount, morphoClient) {
336
- this._resetTrackerIfNewDay();
337
- // If yield-limited spending is enabled, calculate dynamic limit
338
- if (this.config.yieldLimitedSpending) {
339
- try {
340
- const status = await morphoClient.getStatus();
341
- let totalDailyYieldUsdc = 0;
342
- for (const pos of status.positions) {
343
- if (parseFloat(pos.collateral) > 0) {
344
- try {
345
- const estimate = await morphoClient.getYieldEstimate(pos.collateralToken, pos.collateral, 1);
346
- totalDailyYieldUsdc += estimate.estimatedYieldUsd;
347
- }
348
- catch (e) {
349
- console.warn(`[agether] yield calc failed for ${pos.collateralToken}:`, e instanceof Error ? e.message : e);
350
- }
351
- }
352
- }
353
- const yieldLimit = BigInt(Math.round(totalDailyYieldUsdc * 1e6));
354
- const newTotal = this._spendingTracker.totalBorrowed + amount;
355
- if (yieldLimit > 0n && newTotal > yieldLimit) {
356
- return {
357
- allowed: false,
358
- reason: `Yield-limited spending exceeded. Daily yield cap: $${(Number(yieldLimit) / 1e6).toFixed(2)}, already spent: $${(Number(this._spendingTracker.totalBorrowed) / 1e6).toFixed(2)}, requested: $${(Number(amount) / 1e6).toFixed(2)}`,
359
- };
360
- }
361
- }
362
- catch (e) {
363
- console.warn('[agether] yield-limited spending check failed, falling through to fixed limit:', e instanceof Error ? e.message : e);
364
- }
365
- }
366
- // Check fixed daily limit
367
- if (this._spendingTracker.dailyLimit > 0n) {
368
- const newTotal = this._spendingTracker.totalBorrowed + amount;
369
- if (newTotal > this._spendingTracker.dailyLimit) {
370
- return {
371
- allowed: false,
372
- reason: `Daily spending limit exceeded. Limit: $${(Number(this._spendingTracker.dailyLimit) / 1e6).toFixed(2)}, already spent: $${(Number(this._spendingTracker.totalBorrowed) / 1e6).toFixed(2)}, requested: $${(Number(amount) / 1e6).toFixed(2)}`,
373
- };
374
- }
375
- }
376
- return { allowed: true };
377
- }
378
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,YAAY,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAEpE,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,YAAY,EACV,aAAa,EACb,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,sBAAsB,EACtB,WAAW,EACX,cAAc,EACd,UAAU,EACV,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,YAAY,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,YAAY,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAEhF,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,YAAY,EAAE,iBAAiB,EAAE,UAAU,EAAE,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAI9H,cAAc,SAAS,CAAC;AAIxB,OAAO,EACL,UAAU,EACV,WAAW,EACX,SAAS,EACT,aAAa,EACb,SAAS,EACT,kBAAkB,EAClB,aAAa,EACb,eAAe,EACf,SAAS,EACT,SAAS,GACV,MAAM,gBAAgB,CAAC;AAIxB,OAAO,EACL,qBAAqB,EAErB,wBAAwB,EACxB,kCAAkC,EAClC,4BAA4B,EAC5B,uBAAuB,EAEvB,sBAAsB,EACtB,mBAAmB,EACnB,6BAA6B,EAC7B,oBAAoB,EACpB,oBAAoB,EAEpB,uBAAuB,EACvB,eAAe,EACf,SAAS,EACT,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,cAAc,CAAC;AAItB,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC"}
@@ -1,132 +0,0 @@
1
- /**
2
- * Agether SDK Types
3
- *
4
- * Architecture (v2 — Safe + Safe7579):
5
- * - Agent registers via ERC-8004 → gets agentId
6
- * - Agether4337Factory creates Safe proxy with Safe7579 adapter per agent
7
- * - Agether8004ValidationModule: ownership + KYA gate + module lock (single 7579 validator)
8
- * - AgetherHookMultiplexer: admin-managed hook chain
9
- * - All execution via ERC-4337 UserOps through EntryPoint v0.7
10
- * - Agether8004Scorer: oracle-based credit scoring
11
- * - Morpho Blue: direct overcollateralized lending (agents interact via UserOps)
12
- * - x402: HTTP payment protocol for scoring API
13
- */
14
- export declare enum ChainId {
15
- Ethereum = 1,
16
- Base = 8453,
17
- BaseSepolia = 84532,
18
- Sepolia = 11155111,
19
- Hardhat = 31337
20
- }
21
- /** Morpho Blue MarketParams struct */
22
- export interface MorphoMarketParams {
23
- loanToken: string;
24
- collateralToken: string;
25
- oracle: string;
26
- irm: string;
27
- lltv: bigint;
28
- }
29
- /** Morpho Blue onchain position for an account */
30
- export interface MorphoPosition {
31
- supplyShares: bigint;
32
- borrowShares: bigint;
33
- collateral: bigint;
34
- }
35
- /** Morpho market info (from GraphQL API or onchain) */
36
- export interface MorphoMarketInfo {
37
- uniqueKey: string;
38
- loanAsset: {
39
- address: string;
40
- symbol: string;
41
- decimals: number;
42
- };
43
- collateralAsset: {
44
- address: string;
45
- symbol: string;
46
- decimals: number;
47
- };
48
- oracle: string;
49
- irm: string;
50
- lltv: bigint;
51
- totalSupplyAssets: bigint;
52
- totalBorrowAssets: bigint;
53
- utilization: number;
54
- }
55
- /** Onchain score attestation from Agether8004Scorer contract */
56
- export interface ScoreAttestation {
57
- score: bigint;
58
- timestamp: bigint;
59
- signer: string;
60
- }
61
- /** Score result from backend scoring API */
62
- export interface ScoreResult {
63
- agentId: string;
64
- score: number;
65
- timestamp: number;
66
- breakdown: {
67
- kyaBonus: number;
68
- accountBonus: number;
69
- balanceBonus: number;
70
- historyBonus: number;
71
- baseScore: number;
72
- };
73
- txHash?: string;
74
- }
75
- export interface TransactionResult {
76
- txHash: string;
77
- blockNumber: number;
78
- status: 'success' | 'failed';
79
- gasUsed: bigint;
80
- }
81
- export interface X402PaymentRequest {
82
- service: string;
83
- amount: bigint;
84
- asset: string;
85
- chain: ChainId;
86
- recipient: string;
87
- }
88
- export interface X402PaymentResult {
89
- paymentId: string;
90
- txHash: string;
91
- amount: bigint;
92
- chain: ChainId;
93
- status: 'pending' | 'confirmed' | 'failed';
94
- }
95
- export interface AgetherConfig {
96
- chainId: ChainId;
97
- rpcUrl: string;
98
- contracts: ContractAddresses;
99
- scoringEndpoint?: string;
100
- kyaEndpoint?: string;
101
- }
102
- export interface ContractAddresses {
103
- safeSingleton: string;
104
- safeProxyFactory: string;
105
- safe7579: string;
106
- entryPoint: string;
107
- agether4337Factory: string;
108
- agether7579Bootstrap: string;
109
- erc8004ValidationModule: string;
110
- agetherHookMultiplexer: string;
111
- validationRegistry: string;
112
- agether8004Scorer: string;
113
- timelockController: string;
114
- identityRegistry: string;
115
- usdc: string;
116
- morphoBlue: string;
117
- }
118
- export declare class AgetherError extends Error {
119
- code: string;
120
- details?: Record<string, unknown> | undefined;
121
- constructor(message: string, code: string, details?: Record<string, unknown> | undefined);
122
- }
123
- export declare class InsufficientBalanceError extends AgetherError {
124
- constructor(available: bigint, required: bigint);
125
- }
126
- export declare class ScoringRejectedError extends AgetherError {
127
- constructor(riskScore: number, reason?: string);
128
- }
129
- export declare class AgentNotApprovedError extends AgetherError {
130
- constructor(agentId: bigint);
131
- }
132
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,oBAAY,OAAO;IACjB,QAAQ,IAAI;IACZ,IAAI,OAAO;IACX,WAAW,QAAQ;IACnB,OAAO,WAAW;IAClB,OAAO,QAAQ;CAChB;AAID,sCAAsC;AACtC,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;CACd;AAED,kDAAkD;AAClD,MAAM,WAAW,cAAc;IAC7B,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;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AAE,OAAO,CAAC,YAAA;CAK3C;AAED,qBAAa,wBAAyB,SAAQ,YAAY;gBAC5C,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM;CAOhD;AAED,qBAAa,oBAAqB,SAAQ,YAAY;gBACxC,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;CAO/C;AAED,qBAAa,qBAAsB,SAAQ,YAAY;gBACzC,OAAO,EAAE,MAAM;CAO5B"}
@@ -1,46 +0,0 @@
1
- /**
2
- * Agether SDK Types
3
- *
4
- * Architecture (v2 — Safe + Safe7579):
5
- * - Agent registers via ERC-8004 → gets agentId
6
- * - Agether4337Factory creates Safe proxy with Safe7579 adapter per agent
7
- * - Agether8004ValidationModule: ownership + KYA gate + module lock (single 7579 validator)
8
- * - AgetherHookMultiplexer: admin-managed hook chain
9
- * - All execution via ERC-4337 UserOps through EntryPoint v0.7
10
- * - Agether8004Scorer: oracle-based credit scoring
11
- * - Morpho Blue: direct overcollateralized lending (agents interact via UserOps)
12
- * - x402: HTTP payment protocol for scoring API
13
- */
14
- // ============ Enums ============
15
- export var ChainId;
16
- (function (ChainId) {
17
- ChainId[ChainId["Ethereum"] = 1] = "Ethereum";
18
- ChainId[ChainId["Base"] = 8453] = "Base";
19
- ChainId[ChainId["BaseSepolia"] = 84532] = "BaseSepolia";
20
- ChainId[ChainId["Sepolia"] = 11155111] = "Sepolia";
21
- ChainId[ChainId["Hardhat"] = 31337] = "Hardhat";
22
- })(ChainId || (ChainId = {}));
23
- // ============ Error Types ============
24
- export class AgetherError extends Error {
25
- constructor(message, code, details) {
26
- super(message);
27
- this.code = code;
28
- this.details = details;
29
- this.name = 'AgetherError';
30
- }
31
- }
32
- export class InsufficientBalanceError extends AgetherError {
33
- constructor(available, required) {
34
- super(`Insufficient balance: available ${available}, required ${required}`, 'INSUFFICIENT_BALANCE', { available: available.toString(), required: required.toString() });
35
- }
36
- }
37
- export class ScoringRejectedError extends AgetherError {
38
- constructor(riskScore, reason) {
39
- super(`Scoring rejected: risk score ${riskScore}${reason ? `, ${reason}` : ''}`, 'SCORING_REJECTED', { riskScore, reason });
40
- }
41
- }
42
- export class AgentNotApprovedError extends AgetherError {
43
- constructor(agentId) {
44
- super(`Agent ${agentId} is not KYA-approved. Submit code for validation first.`, 'AGENT_NOT_APPROVED', { agentId: agentId.toString() });
45
- }
46
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * Contract ABIs (minimal for SDK)
3
- *
4
- * Architecture (v2 — Safe + Safe7579):
5
- * - Agether4337Factory (deploys Safe proxies with modules)
6
- * - Agether8004ValidationModule (ownership + KYA + module lock)
7
- * - AgetherHookMultiplexer (admin-managed hooks)
8
- * - Agether8004Scorer (oracle-based credit scores)
9
- * - ValidationRegistry (KYA code validation)
10
- * - ERC-8004 IdentityRegistry
11
- * - Morpho Blue (direct overcollateralized lending)
12
- * - EntryPoint v0.7 (ERC-4337 UserOp submission)
13
- */
14
- export declare const IDENTITY_REGISTRY_ABI: string[];
15
- export declare const AGETHER_4337_FACTORY_ABI: string[];
16
- export declare const SAFE_AGENT_FACTORY_ABI: string[];
17
- export declare const ACCOUNT_FACTORY_ABI: string[];
18
- export declare const AGETHER_8004_VALIDATION_MODULE_ABI: string[];
19
- export declare const ERC8004_VALIDATION_MODULE_ABI: string[];
20
- export declare const AGETHER_HOOK_MULTIPLEXER_ABI: string[];
21
- export declare const HOOK_MULTIPLEXER_ABI: string[];
22
- export declare const AGETHER_8004_SCORER_ABI: string[];
23
- export declare const AGENT_REPUTATION_ABI: string[];
24
- export declare const VALIDATION_REGISTRY_ABI: string[];
25
- export declare const MORPHO_BLUE_ABI: string[];
26
- export declare const ERC20_ABI: string[];
27
- export declare const ENTRYPOINT_V07_ABI: string[];
28
- export declare const SAFE7579_ACCOUNT_ABI: string[];
29
- //# sourceMappingURL=abis.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"abis.d.ts","sourceRoot":"","sources":["../../src/utils/abis.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,eAAO,MAAM,qBAAqB,UAOjC,CAAC;AAIF,eAAO,MAAM,wBAAwB,UAepC,CAAC;AAGF,eAAO,MAAM,sBAAsB,UAA2B,CAAC;AAC/D,eAAO,MAAM,mBAAmB,UAA2B,CAAC;AAI5D,eAAO,MAAM,kCAAkC,UAU9C,CAAC;AAGF,eAAO,MAAM,6BAA6B,UAAqC,CAAC;AAIhF,eAAO,MAAM,4BAA4B,UAMxC,CAAC;AAGF,eAAO,MAAM,oBAAoB,UAA+B,CAAC;AAIjE,eAAO,MAAM,uBAAuB,UASnC,CAAC;AAGF,eAAO,MAAM,oBAAoB,UAA0B,CAAC;AAI5D,eAAO,MAAM,uBAAuB,UAKnC,CAAC;AAIF,eAAO,MAAM,eAAe,UAoB3B,CAAC;AAIF,eAAO,MAAM,SAAS,UASrB,CAAC;AAIF,eAAO,MAAM,kBAAkB,UAQ9B,CAAC;AAIF,eAAO,MAAM,oBAAoB,UAQhC,CAAC"}