@agether/sdk 1.6.0 → 1.6.2

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.
@@ -0,0 +1,333 @@
1
+ /**
2
+ * AgentIdentityClient - Integration with ag0 (ERC-8004)
3
+ *
4
+ * ERC-8004 Contract Addresses:
5
+ * - Sepolia IdentityRegistry: 0x8004A818BFB912233c491871b3d84c89A494BD9e
6
+ * - Sepolia ReputationRegistry: 0x8004B663056A597Dffe9eCcC1965A193B7388713
7
+ *
8
+ * SDKs:
9
+ * - TypeScript: https://github.com/agent0lab/agent0-ts
10
+ * - Python: https://github.com/agent0lab/agent0-py
11
+ *
12
+ * Docs: https://sdk.ag0.xyz/docs
13
+ */
14
+ import { ethers } from 'ethers';
15
+ // ERC-8004 ABI fragments
16
+ const ERC8004_IDENTITY_ABI = [
17
+ // Registration
18
+ 'function register() returns (uint256)',
19
+ 'function register(string agentURI) returns (uint256)',
20
+ 'function register(string agentURI, tuple(string key, bytes value)[] metadata) returns (uint256)',
21
+ // Management
22
+ 'function setAgentURI(uint256 agentId, string newURI)',
23
+ 'function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue)',
24
+ 'function getMetadata(uint256 agentId, string metadataKey) view returns (bytes)',
25
+ // ERC-721 standard
26
+ 'function ownerOf(uint256 tokenId) view returns (address)',
27
+ 'function balanceOf(address owner) view returns (uint256)',
28
+ 'function tokenURI(uint256 tokenId) view returns (string)',
29
+ 'function transferFrom(address from, address to, uint256 tokenId)',
30
+ 'function approve(address to, uint256 tokenId)',
31
+ 'function getApproved(uint256 tokenId) view returns (address)',
32
+ // Events
33
+ 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)',
34
+ ];
35
+ const ERC8004_REPUTATION_ABI = [
36
+ // Feedback
37
+ 'function giveFeedback(uint256 agentId, int128 value, uint8 valueDecimals, string tag1, string tag2, string endpoint, string feedbackURI, bytes32 feedbackHash)',
38
+ 'function revokeFeedback(uint256 agentId, uint64 feedbackIndex)',
39
+ // Queries
40
+ 'function readFeedback(uint256 agentId, address clientAddress, uint64 feedbackIndex) view returns (int128 value, uint8 valueDecimals, string tag1, string tag2, bool isRevoked)',
41
+ 'function getSummary(uint256 agentId, address[] clientAddresses, string tag1, string tag2) view returns (uint64 count, int128 summaryValue, uint8 summaryValueDecimals)',
42
+ 'function getClients(uint256 agentId) view returns (address[])',
43
+ 'function getLastIndex(uint256 agentId, address clientAddress) view returns (uint64)',
44
+ // Registry
45
+ 'function getIdentityRegistry() view returns (address)',
46
+ ];
47
+ // ERC-8004 Sepolia addresses
48
+ export const ERC8004_SEPOLIA = {
49
+ identityRegistry: '0x8004A818BFB912233c491871b3d84c89A494BD9e',
50
+ reputationRegistry: '0x8004B663056A597Dffe9eCcC1965A193B7388713',
51
+ };
52
+ export class AgentIdentityClient {
53
+ constructor(options) {
54
+ this.config = options.config;
55
+ this.signer = options.signer;
56
+ // Get registry addresses (prefer config, fallback to Sepolia)
57
+ const identityAddr = options.config.contracts?.identityRegistry || ERC8004_SEPOLIA.identityRegistry;
58
+ const reputationAddr = options.config.contracts?.reputationRegistry || ERC8004_SEPOLIA.reputationRegistry;
59
+ this.identityRegistry = new ethers.Contract(identityAddr, ERC8004_IDENTITY_ABI, this.signer);
60
+ this.reputationRegistry = new ethers.Contract(reputationAddr, ERC8004_REPUTATION_ABI, this.signer);
61
+ }
62
+ // ============ Identity Functions ============
63
+ /**
64
+ * Register a new agent (minimal - no metadata)
65
+ */
66
+ async register() {
67
+ const tx = await this.identityRegistry['register()']();
68
+ const receipt = await tx.wait();
69
+ const agentId = this.parseAgentIdFromReceipt(receipt);
70
+ return { agentId, txHash: receipt.hash };
71
+ }
72
+ /**
73
+ * Register agent with IPFS/HTTP URI to metadata JSON
74
+ * @param agentURI URI pointing to agent metadata (ipfs:// or https://)
75
+ */
76
+ async registerWithURI(agentURI) {
77
+ const tx = await this.identityRegistry['register(string)'](agentURI);
78
+ const receipt = await tx.wait();
79
+ const agentId = this.parseAgentIdFromReceipt(receipt);
80
+ return { agentId, txHash: receipt.hash };
81
+ }
82
+ /**
83
+ * Check if the signer already owns an ERC-8004 identity token.
84
+ * Returns true if balanceOf > 0, false otherwise.
85
+ * Note: Cannot determine the specific agentId without enumeration —
86
+ * use agether init <pk> --agent-id <id> if you know your agentId.
87
+ */
88
+ async hasExistingIdentity() {
89
+ try {
90
+ const address = await this.signer.getAddress();
91
+ const balance = await this.identityRegistry.balanceOf(address);
92
+ return balance > 0n;
93
+ }
94
+ catch {
95
+ return false;
96
+ }
97
+ }
98
+ /**
99
+ * Register only if no identity exists; otherwise throw.
100
+ * Prevents accidental double-registration.
101
+ */
102
+ async registerOrGet() {
103
+ const hasIdentity = await this.hasExistingIdentity();
104
+ if (hasIdentity) {
105
+ throw new Error('Wallet already owns an ERC-8004 identity. Use agether init <pk> --agent-id <id> to set it.');
106
+ }
107
+ const result = await this.register();
108
+ return { ...result, existing: false };
109
+ }
110
+ /**
111
+ * Register with URI only if no identity exists; otherwise throw.
112
+ * Prevents accidental double-registration.
113
+ */
114
+ async registerOrGetWithURI(agentURI) {
115
+ const hasIdentity = await this.hasExistingIdentity();
116
+ if (hasIdentity) {
117
+ throw new Error('Wallet already owns an ERC-8004 identity. Use agether init <pk> --agent-id <id> to set it.');
118
+ }
119
+ const result = await this.registerWithURI(agentURI);
120
+ return { ...result, existing: false };
121
+ }
122
+ /**
123
+ * Register agent with URI and on-chain metadata
124
+ */
125
+ async registerWithMetadata(agentURI, metadata) {
126
+ const metadataEntries = metadata.map(m => ({
127
+ key: m.key,
128
+ value: ethers.toUtf8Bytes(m.value),
129
+ }));
130
+ const tx = await this.identityRegistry['register(string,tuple(string,bytes)[])'](agentURI, metadataEntries);
131
+ const receipt = await tx.wait();
132
+ const agentId = this.parseAgentIdFromReceipt(receipt);
133
+ return { agentId, txHash: receipt.hash };
134
+ }
135
+ /**
136
+ * Get agent owner address
137
+ */
138
+ async getOwner(agentId) {
139
+ return await this.identityRegistry.ownerOf(agentId);
140
+ }
141
+ /**
142
+ * Get agent URI (metadata JSON location)
143
+ */
144
+ async getAgentURI(agentId) {
145
+ return await this.identityRegistry.tokenURI(agentId);
146
+ }
147
+ /**
148
+ * Update agent URI
149
+ */
150
+ async setAgentURI(agentId, newURI) {
151
+ const tx = await this.identityRegistry.setAgentURI(agentId, newURI);
152
+ const receipt = await tx.wait();
153
+ return receipt.hash;
154
+ }
155
+ /**
156
+ * Set on-chain metadata (key-value)
157
+ */
158
+ async setMetadata(agentId, key, value) {
159
+ const tx = await this.identityRegistry.setMetadata(agentId, key, ethers.toUtf8Bytes(value));
160
+ const receipt = await tx.wait();
161
+ return receipt.hash;
162
+ }
163
+ /**
164
+ * Get on-chain metadata
165
+ */
166
+ async getMetadata(agentId, key) {
167
+ const value = await this.identityRegistry.getMetadata(agentId, key);
168
+ return ethers.toUtf8String(value);
169
+ }
170
+ /**
171
+ * Transfer agent to new owner
172
+ */
173
+ async transfer(agentId, to) {
174
+ const from = await this.signer.getAddress();
175
+ const tx = await this.identityRegistry.transferFrom(from, to, agentId);
176
+ const receipt = await tx.wait();
177
+ return receipt.hash;
178
+ }
179
+ /**
180
+ * Fetch and parse agent metadata from URI
181
+ */
182
+ async fetchAgentMetadata(agentId) {
183
+ try {
184
+ const uri = await this.getAgentURI(agentId);
185
+ // Handle IPFS URIs
186
+ let fetchUrl = uri;
187
+ if (uri.startsWith('ipfs://')) {
188
+ const cid = uri.replace('ipfs://', '');
189
+ fetchUrl = `https://ipfs.io/ipfs/${cid}`;
190
+ }
191
+ const response = await fetch(fetchUrl);
192
+ if (!response.ok)
193
+ return null;
194
+ return await response.json();
195
+ }
196
+ catch {
197
+ return null;
198
+ }
199
+ }
200
+ // ============ Reputation Functions ============
201
+ /**
202
+ * Give feedback to an agent
203
+ */
204
+ async giveFeedback(input) {
205
+ const feedbackHash = ethers.keccak256(ethers.AbiCoder.defaultAbiCoder().encode(['uint256', 'int128', 'uint256'], [input.agentId, input.value, Date.now()]));
206
+ const tx = await this.reputationRegistry.giveFeedback(input.agentId, input.value, input.decimals || 0, input.tag1 || '', input.tag2 || '', input.endpoint || '', input.feedbackURI || '', feedbackHash);
207
+ const receipt = await tx.wait();
208
+ return receipt.hash;
209
+ }
210
+ /**
211
+ * Give positive feedback (shorthand)
212
+ */
213
+ async givePosisitiveFeedback(agentId, value = 100, tags = {}) {
214
+ return this.giveFeedback({
215
+ agentId,
216
+ value: Math.abs(value),
217
+ ...tags,
218
+ });
219
+ }
220
+ /**
221
+ * Give negative feedback (e.g., for defaults)
222
+ */
223
+ async giveNegativeFeedback(agentId, value = -100, tags = {}) {
224
+ return this.giveFeedback({
225
+ agentId,
226
+ value: -Math.abs(value),
227
+ ...tags,
228
+ });
229
+ }
230
+ /**
231
+ * Record credit default in reputation system
232
+ */
233
+ async recordCreditDefault(agentId, creditLineId) {
234
+ return this.giveFeedback({
235
+ agentId,
236
+ value: -100,
237
+ tag1: 'credit',
238
+ tag2: 'default',
239
+ feedbackURI: `agether://default/${creditLineId}`,
240
+ });
241
+ }
242
+ /**
243
+ * Get reputation summary for an agent
244
+ */
245
+ async getReputation(agentId, tag1 = '', tag2 = '') {
246
+ const clients = await this.reputationRegistry.getClients(agentId);
247
+ if (clients.length === 0) {
248
+ return {
249
+ count: 0,
250
+ totalValue: 0,
251
+ averageValue: 0,
252
+ clients: [],
253
+ };
254
+ }
255
+ const [count, summaryValue, decimals] = await this.reputationRegistry.getSummary(agentId, clients, tag1, tag2);
256
+ // Convert from fixed-point
257
+ const divisor = 10 ** Number(decimals);
258
+ const total = Number(summaryValue) / divisor;
259
+ return {
260
+ count: Number(count),
261
+ totalValue: total,
262
+ averageValue: Number(count) > 0 ? total / Number(count) : 0,
263
+ clients: clients.map((c) => c),
264
+ };
265
+ }
266
+ /**
267
+ * Check if agent has negative credit reputation
268
+ */
269
+ async hasNegativeCreditReputation(agentId) {
270
+ const rep = await this.getReputation(agentId, 'credit', '');
271
+ return rep.count > 0 && rep.averageValue < 0;
272
+ }
273
+ // ============ Agether Integration ============
274
+ /**
275
+ * Verify agent is eligible for Agether credit
276
+ * Checks:
277
+ * 1. Agent exists in ERC-8004 registry
278
+ * 2. Agent has no negative credit reputation
279
+ */
280
+ async verifyForCredit(agentId) {
281
+ // Check agent exists
282
+ let owner;
283
+ try {
284
+ owner = await this.getOwner(agentId);
285
+ }
286
+ catch {
287
+ return { eligible: false, reason: 'Agent not found in ERC-8004 registry' };
288
+ }
289
+ // Check credit reputation
290
+ const reputation = await this.getReputation(agentId, 'credit', '');
291
+ if (reputation.count > 0 && reputation.averageValue < 0) {
292
+ return {
293
+ eligible: false,
294
+ reason: 'Agent has negative credit reputation',
295
+ owner,
296
+ reputation,
297
+ };
298
+ }
299
+ return {
300
+ eligible: true,
301
+ owner,
302
+ reputation,
303
+ };
304
+ }
305
+ // ============ Helpers ============
306
+ parseAgentIdFromReceipt(receipt) {
307
+ // Find Transfer event (ERC-721)
308
+ for (const log of receipt.logs) {
309
+ try {
310
+ const parsed = this.identityRegistry.interface.parseLog({
311
+ topics: log.topics,
312
+ data: log.data,
313
+ });
314
+ if (parsed?.name === 'Transfer') {
315
+ return parsed.args[2]; // tokenId
316
+ }
317
+ }
318
+ catch {
319
+ continue;
320
+ }
321
+ }
322
+ return 0n;
323
+ }
324
+ /**
325
+ * Get contract addresses
326
+ */
327
+ getContractAddresses() {
328
+ return {
329
+ identity: this.identityRegistry.target,
330
+ reputation: this.reputationRegistry.target,
331
+ };
332
+ }
333
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * AgetherClient — Account management & identity for AI agents
3
+ *
4
+ * Flow:
5
+ * 1. Agent registers via ERC-8004 → gets agentId
6
+ * 2. AccountFactory.createAccount(agentId) → AgentAccount (KYA-gated smart wallet)
7
+ * 3. Use MorphoClient for lending, ScoringClient for scores, X402Client for payments
8
+ */
9
+ import { Signer } from 'ethers';
10
+ import { AgetherConfig, TransactionResult, ChainId } from '../types';
11
+ export interface AgetherClientOptions {
12
+ config: AgetherConfig;
13
+ signer: Signer;
14
+ agentId: bigint;
15
+ }
16
+ export declare class AgetherClient {
17
+ private config;
18
+ private signer;
19
+ private agentId;
20
+ private accountFactory;
21
+ private identityRegistry;
22
+ private validationRegistry;
23
+ private agentReputation;
24
+ private accountAddress?;
25
+ constructor(options: AgetherClientOptions);
26
+ static fromPrivateKey(privateKey: string, agentId: bigint, chainIdOrConfig: ChainId | AgetherConfig): AgetherClient;
27
+ createAccount(): Promise<string>;
28
+ getAccountAddress(): Promise<string>;
29
+ accountExists(): Promise<boolean>;
30
+ predictAddress(): Promise<string>;
31
+ getBalances(): Promise<{
32
+ eoa: {
33
+ eth: string;
34
+ usdc: string;
35
+ };
36
+ account?: {
37
+ address: string;
38
+ eth: string;
39
+ usdc: string;
40
+ };
41
+ }>;
42
+ fundAccount(usdcAmount: string): Promise<TransactionResult>;
43
+ withdrawUsdc(usdcAmount: string): Promise<TransactionResult>;
44
+ withdrawEth(ethAmount: string): Promise<TransactionResult>;
45
+ isKyaApproved(): Promise<boolean>;
46
+ identityExists(): Promise<boolean>;
47
+ getIdentityOwner(): Promise<string>;
48
+ getCreditScore(): Promise<bigint>;
49
+ isScoreFresh(): Promise<{
50
+ fresh: boolean;
51
+ age: bigint;
52
+ }>;
53
+ isEligible(minScore?: bigint): Promise<{
54
+ eligible: boolean;
55
+ currentScore: bigint;
56
+ }>;
57
+ get chainId(): ChainId;
58
+ get contracts(): import("..").ContractAddresses;
59
+ get currentAccountAddress(): string | undefined;
60
+ getSigner(): Signer;
61
+ getAgentId(): bigint;
62
+ }
63
+ //# sourceMappingURL=AgetherClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgetherClient.d.ts","sourceRoot":"","sources":["../../src/clients/AgetherClient.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAU,MAAM,EAAY,MAAM,QAAQ,CAAC;AAClD,OAAO,EACL,aAAa,EACb,iBAAiB,EAEjB,OAAO,EACR,MAAM,UAAU,CAAC;AAWlB,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,aAAa,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,OAAO,CAAS;IAExB,OAAO,CAAC,cAAc,CAAW;IACjC,OAAO,CAAC,gBAAgB,CAAW;IACnC,OAAO,CAAC,kBAAkB,CAAW;IACrC,OAAO,CAAC,eAAe,CAAW;IAElC,OAAO,CAAC,cAAc,CAAC,CAAS;gBAEpB,OAAO,EAAE,oBAAoB;IAgCzC,MAAM,CAAC,cAAc,CACnB,UAAU,EAAE,MAAM,EAClB,OAAO,EAAE,MAAM,EACf,eAAe,EAAE,OAAO,GAAG,aAAa,GACvC,aAAa;IAYV,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAoBhC,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC;IAUpC,aAAa,IAAI,OAAO,CAAC,OAAO,CAAC;IAIjC,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;IAMjC,WAAW,IAAI,OAAO,CAAC;QAC3B,GAAG,EAAE;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAA;SAAE,CAAC;QACnC,OAAO,CAAC,EAAE;YAAE,OAAO,EAAE,MAAM,CAAC;YAAC,GAAG,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAA;SAAE,CAAC;KAC1D,CAAC;IA0BI,WAAW,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAc3D,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAe5D,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAiB1D,aAAa,IAAI,OAAO,CAAC,OAAO,CAAC;IAIjC,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC;IASlC,gBAAgB,IAAI,OAAO,CAAC,MAAM,CAAC;IAMnC,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;IAIjC,YAAY,IAAI,OAAO,CAAC;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IAKxD,UAAU,CAAC,QAAQ,GAAE,MAAa,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,OAAO,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;IAO/F,IAAI,OAAO,IAAI,OAAO,CAAgC;IACtD,IAAI,SAAS,mCAAoC;IACjD,IAAI,qBAAqB,IAAI,MAAM,GAAG,SAAS,CAAgC;IAC/E,SAAS,IAAI,MAAM;IACnB,UAAU,IAAI,MAAM;CACrB"}
@@ -0,0 +1,171 @@
1
+ /**
2
+ * AgetherClient — Account management & identity for AI agents
3
+ *
4
+ * Flow:
5
+ * 1. Agent registers via ERC-8004 → gets agentId
6
+ * 2. AccountFactory.createAccount(agentId) → AgentAccount (KYA-gated smart wallet)
7
+ * 3. Use MorphoClient for lending, ScoringClient for scores, X402Client for payments
8
+ */
9
+ import { ethers, Contract } from 'ethers';
10
+ import { AgetherError, } from '../types';
11
+ import { ACCOUNT_FACTORY_ABI, AGENT_ACCOUNT_ABI, IDENTITY_REGISTRY_ABI, VALIDATION_REGISTRY_ABI, AGENT_REPUTATION_ABI, ERC20_ABI, } from '../utils/abis';
12
+ import { getDefaultConfig } from '../utils/config';
13
+ export class AgetherClient {
14
+ constructor(options) {
15
+ this.config = options.config;
16
+ this.signer = options.signer;
17
+ this.agentId = options.agentId;
18
+ const provider = options.signer.provider;
19
+ if (!provider)
20
+ throw new AgetherError('Signer must have a provider', 'NO_PROVIDER');
21
+ this.accountFactory = new Contract(options.config.contracts.accountFactory, ACCOUNT_FACTORY_ABI, options.signer);
22
+ this.identityRegistry = new Contract(options.config.contracts.identityRegistry, IDENTITY_REGISTRY_ABI, provider);
23
+ this.validationRegistry = new Contract(options.config.contracts.validationRegistry, VALIDATION_REGISTRY_ABI, provider);
24
+ this.agentReputation = new Contract(options.config.contracts.agentReputation, AGENT_REPUTATION_ABI, provider);
25
+ }
26
+ // Static Factory
27
+ static fromPrivateKey(privateKey, agentId, chainIdOrConfig) {
28
+ const config = typeof chainIdOrConfig === 'number'
29
+ ? getDefaultConfig(chainIdOrConfig)
30
+ : chainIdOrConfig;
31
+ const provider = new ethers.JsonRpcProvider(config.rpcUrl);
32
+ const signer = new ethers.Wallet(privateKey, provider);
33
+ return new AgetherClient({ config, signer, agentId });
34
+ }
35
+ // Account Management
36
+ async createAccount() {
37
+ const tx = await this.accountFactory.createAccount(this.agentId);
38
+ const receipt = await tx.wait();
39
+ const event = receipt.logs
40
+ .map((log) => {
41
+ try {
42
+ return this.accountFactory.interface.parseLog(log);
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ })
48
+ .find((e) => e?.name === 'AccountCreated');
49
+ if (event) {
50
+ this.accountAddress = event.args.account;
51
+ }
52
+ else {
53
+ this.accountAddress = await this.accountFactory.getAccount(this.agentId);
54
+ }
55
+ return this.accountAddress;
56
+ }
57
+ async getAccountAddress() {
58
+ if (this.accountAddress)
59
+ return this.accountAddress;
60
+ const addr = await this.accountFactory.getAccount(this.agentId);
61
+ if (addr === ethers.ZeroAddress) {
62
+ throw new AgetherError('No account found. Create one with createAccount().', 'NO_ACCOUNT');
63
+ }
64
+ this.accountAddress = addr;
65
+ return addr;
66
+ }
67
+ async accountExists() {
68
+ return this.accountFactory.accountExists(this.agentId);
69
+ }
70
+ async predictAddress() {
71
+ return this.accountFactory.predictAddress(this.agentId);
72
+ }
73
+ // Balances
74
+ async getBalances() {
75
+ const provider = this.signer.provider;
76
+ const eoaAddr = await this.signer.getAddress();
77
+ const usdc = new Contract(this.config.contracts.usdc, ERC20_ABI, provider);
78
+ const ethBal = await provider.getBalance(eoaAddr);
79
+ const usdcBal = await usdc.balanceOf(eoaAddr);
80
+ const result = {
81
+ eoa: { eth: ethers.formatEther(ethBal), usdc: ethers.formatUnits(usdcBal, 6) },
82
+ };
83
+ try {
84
+ const acctAddr = await this.getAccountAddress();
85
+ const acctEth = await provider.getBalance(acctAddr);
86
+ const acctUsdc = await usdc.balanceOf(acctAddr);
87
+ result.account = {
88
+ address: acctAddr,
89
+ eth: ethers.formatEther(acctEth),
90
+ usdc: ethers.formatUnits(acctUsdc, 6),
91
+ };
92
+ }
93
+ catch { /* no account */ }
94
+ return result;
95
+ }
96
+ async fundAccount(usdcAmount) {
97
+ const acctAddr = await this.getAccountAddress();
98
+ const usdc = new Contract(this.config.contracts.usdc, ERC20_ABI, this.signer);
99
+ const amount = ethers.parseUnits(usdcAmount, 6);
100
+ const tx = await usdc.transfer(acctAddr, amount);
101
+ const receipt = await tx.wait();
102
+ return {
103
+ txHash: receipt.hash,
104
+ blockNumber: receipt.blockNumber,
105
+ status: receipt.status === 1 ? 'success' : 'failed',
106
+ gasUsed: receipt.gasUsed,
107
+ };
108
+ }
109
+ async withdrawUsdc(usdcAmount) {
110
+ const acctAddr = await this.getAccountAddress();
111
+ const account = new Contract(acctAddr, AGENT_ACCOUNT_ABI, this.signer);
112
+ const amount = ethers.parseUnits(usdcAmount, 6);
113
+ const eoaAddr = await this.signer.getAddress();
114
+ const tx = await account.withdraw(this.config.contracts.usdc, amount, eoaAddr);
115
+ const receipt = await tx.wait();
116
+ return {
117
+ txHash: receipt.hash,
118
+ blockNumber: receipt.blockNumber,
119
+ status: receipt.status === 1 ? 'success' : 'failed',
120
+ gasUsed: receipt.gasUsed,
121
+ };
122
+ }
123
+ async withdrawEth(ethAmount) {
124
+ const acctAddr = await this.getAccountAddress();
125
+ const account = new Contract(acctAddr, AGENT_ACCOUNT_ABI, this.signer);
126
+ const amount = ethers.parseEther(ethAmount);
127
+ const eoaAddr = await this.signer.getAddress();
128
+ const tx = await account.withdrawETH(amount, eoaAddr);
129
+ const receipt = await tx.wait();
130
+ return {
131
+ txHash: receipt.hash,
132
+ blockNumber: receipt.blockNumber,
133
+ status: receipt.status === 1 ? 'success' : 'failed',
134
+ gasUsed: receipt.gasUsed,
135
+ };
136
+ }
137
+ // Identity & Validation
138
+ async isKyaApproved() {
139
+ return this.validationRegistry.isAgentCodeApproved(this.agentId);
140
+ }
141
+ async identityExists() {
142
+ try {
143
+ await this.identityRegistry.ownerOf(this.agentId);
144
+ return true;
145
+ }
146
+ catch {
147
+ return false;
148
+ }
149
+ }
150
+ async getIdentityOwner() {
151
+ return this.identityRegistry.ownerOf(this.agentId);
152
+ }
153
+ // Reputation
154
+ async getCreditScore() {
155
+ return this.agentReputation.getCreditScore(this.agentId);
156
+ }
157
+ async isScoreFresh() {
158
+ const [fresh, age] = await this.agentReputation.isScoreFresh(this.agentId);
159
+ return { fresh, age };
160
+ }
161
+ async isEligible(minScore = 500n) {
162
+ const [eligible, currentScore] = await this.agentReputation.isEligible(this.agentId, minScore);
163
+ return { eligible, currentScore };
164
+ }
165
+ // Getters
166
+ get chainId() { return this.config.chainId; }
167
+ get contracts() { return this.config.contracts; }
168
+ get currentAccountAddress() { return this.accountAddress; }
169
+ getSigner() { return this.signer; }
170
+ getAgentId() { return this.agentId; }
171
+ }