@elizaos/plugin-wallet 2.0.0-beta.1

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 (200) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -0
  3. package/auto-enable.ts +76 -0
  4. package/dist/LpManagementService-BWrQ5-cO.mjs +353 -0
  5. package/dist/MockLpService-D_Apn4Fd.mjs +99 -0
  6. package/dist/aerodrome-CfnESC32.mjs +890 -0
  7. package/dist/chunk-hT5z_Zn9.mjs +35 -0
  8. package/dist/index.d.mts +34727 -0
  9. package/dist/index.mjs +21590 -0
  10. package/dist/lib/server-wallet-trade.d.mts +34 -0
  11. package/dist/lib/server-wallet-trade.mjs +306 -0
  12. package/dist/meteora-BPX39hZo.mjs +22640 -0
  13. package/dist/orca-Bybp1HXO.mjs +249 -0
  14. package/dist/pancakeswp-CkEXlXti.mjs +604 -0
  15. package/dist/plugin-ZO_MTyd0.mjs +529 -0
  16. package/dist/raydium-rfaM9yEf.mjs +539 -0
  17. package/dist/sdk/index.d.mts +32492 -0
  18. package/dist/sdk/index.mjs +6415 -0
  19. package/dist/types-D5252NZk.mjs +487 -0
  20. package/dist/uniswap-CReXgXVN.mjs +573 -0
  21. package/dist/wallet-action.d.mts +6 -0
  22. package/dist/wallet-action.mjs +820 -0
  23. package/package.json +152 -0
  24. package/src/actions/failure-codes.ts +79 -0
  25. package/src/actions/index.ts +1 -0
  26. package/src/analytics/birdeye/actions/wallet-search-address.ts +9 -0
  27. package/src/analytics/birdeye/birdeye-task.ts +175 -0
  28. package/src/analytics/birdeye/birdeye.ts +813 -0
  29. package/src/analytics/birdeye/constants.ts +74 -0
  30. package/src/analytics/birdeye/providers/agent-portfolio-provider.ts +18 -0
  31. package/src/analytics/birdeye/providers/market.ts +227 -0
  32. package/src/analytics/birdeye/providers/portfolio-factory.test.ts +138 -0
  33. package/src/analytics/birdeye/providers/portfolio-factory.ts +252 -0
  34. package/src/analytics/birdeye/providers/trending.ts +365 -0
  35. package/src/analytics/birdeye/providers/wallet.ts +14 -0
  36. package/src/analytics/birdeye/search-category.test.ts +207 -0
  37. package/src/analytics/birdeye/search-category.ts +506 -0
  38. package/src/analytics/birdeye/service.ts +992 -0
  39. package/src/analytics/birdeye/tasks/birdeye.ts +232 -0
  40. package/src/analytics/birdeye/types/api/common.ts +305 -0
  41. package/src/analytics/birdeye/types/api/defi.ts +220 -0
  42. package/src/analytics/birdeye/types/api/pair.ts +200 -0
  43. package/src/analytics/birdeye/types/api/search.ts +86 -0
  44. package/src/analytics/birdeye/types/api/token.ts +635 -0
  45. package/src/analytics/birdeye/types/api/trader.ts +76 -0
  46. package/src/analytics/birdeye/types/api/wallet.ts +181 -0
  47. package/src/analytics/birdeye/types/shared.ts +106 -0
  48. package/src/analytics/birdeye/utils.ts +700 -0
  49. package/src/analytics/dexscreener/errors.ts +28 -0
  50. package/src/analytics/dexscreener/index.ts +3 -0
  51. package/src/analytics/dexscreener/search-category.test.ts +49 -0
  52. package/src/analytics/dexscreener/search-category.ts +42 -0
  53. package/src/analytics/dexscreener/service.ts +595 -0
  54. package/src/analytics/dexscreener/types.ts +128 -0
  55. package/src/analytics/lpinfo/index.d.ts +7 -0
  56. package/src/analytics/lpinfo/index.ts +52 -0
  57. package/src/analytics/lpinfo/kamino/README.md +102 -0
  58. package/src/analytics/lpinfo/kamino/index.ts +24 -0
  59. package/src/analytics/lpinfo/kamino/providers/kaminoLiquidityProvider.ts +422 -0
  60. package/src/analytics/lpinfo/kamino/providers/kaminoPoolProvider.ts +365 -0
  61. package/src/analytics/lpinfo/kamino/providers/kaminoProvider.ts +496 -0
  62. package/src/analytics/lpinfo/kamino/services/kaminoLiquidityService.ts +1123 -0
  63. package/src/analytics/lpinfo/kamino/services/kaminoService.ts +758 -0
  64. package/src/analytics/lpinfo/steer/README.md +169 -0
  65. package/src/analytics/lpinfo/steer/index.ts +23 -0
  66. package/src/analytics/lpinfo/steer/providers/steerLiquidityProvider.ts +544 -0
  67. package/src/analytics/lpinfo/steer/services/steerLiquidityService.ts +1690 -0
  68. package/src/analytics/lpinfo/steer/steer-display-types.ts +99 -0
  69. package/src/analytics/news/index.ts +52 -0
  70. package/src/analytics/news/interfaces/types.ts +222 -0
  71. package/src/analytics/news/providers/defiNewsProvider.ts +734 -0
  72. package/src/analytics/news/services/newsDataService.ts +332 -0
  73. package/src/analytics/news/utils/formatters.ts +151 -0
  74. package/src/analytics/token-info/action.ts +240 -0
  75. package/src/analytics/token-info/index.ts +3 -0
  76. package/src/analytics/token-info/params.ts +215 -0
  77. package/src/analytics/token-info/providers.ts +681 -0
  78. package/src/analytics/token-info/service.ts +168 -0
  79. package/src/analytics/token-info/types.ts +74 -0
  80. package/src/audit/audit-log.ts +45 -0
  81. package/src/browser-shim/build-shim.ts +123 -0
  82. package/src/browser-shim/index.ts +5 -0
  83. package/src/browser-shim/shim.template.js +563 -0
  84. package/src/chains/evm/.github/workflows/npm-deploy.yml +112 -0
  85. package/src/chains/evm/LICENSE +21 -0
  86. package/src/chains/evm/README.md +106 -0
  87. package/src/chains/evm/actions/helpers.ts +147 -0
  88. package/src/chains/evm/actions/swap.ts +839 -0
  89. package/src/chains/evm/actions/transfer.ts +254 -0
  90. package/src/chains/evm/biome.json +61 -0
  91. package/src/chains/evm/bridge-router.ts +660 -0
  92. package/src/chains/evm/build.ts +89 -0
  93. package/src/chains/evm/chain-handler.ts +416 -0
  94. package/src/chains/evm/constants.ts +23 -0
  95. package/src/chains/evm/contracts/artifacts/OZGovernor.json +1707 -0
  96. package/src/chains/evm/contracts/artifacts/TimelockController.json +1007 -0
  97. package/src/chains/evm/contracts/artifacts/VoteToken.json +895 -0
  98. package/src/chains/evm/dex/aerodrome/index.ts +34 -0
  99. package/src/chains/evm/dex/aerodrome/services/AerodromeLpService.ts +558 -0
  100. package/src/chains/evm/dex/aerodrome/types.ts +318 -0
  101. package/src/chains/evm/dex/pancakeswp/index.ts +35 -0
  102. package/src/chains/evm/dex/pancakeswp/services/PancakeSwapV3LpService.ts +743 -0
  103. package/src/chains/evm/dex/pancakeswp/types.ts +65 -0
  104. package/src/chains/evm/dex/uniswap/index.ts +35 -0
  105. package/src/chains/evm/dex/uniswap/services/UniswapV3LpService.ts +759 -0
  106. package/src/chains/evm/dex/uniswap/types.ts +390 -0
  107. package/src/chains/evm/generated/specs/spec-helpers.ts +73 -0
  108. package/src/chains/evm/generated/specs/specs.ts +151 -0
  109. package/src/chains/evm/gov-router.ts +250 -0
  110. package/src/chains/evm/index.browser.ts +16 -0
  111. package/src/chains/evm/index.ts +31 -0
  112. package/src/chains/evm/prompts.ts +193 -0
  113. package/src/chains/evm/providers/get-balance.ts +123 -0
  114. package/src/chains/evm/providers/wallet.ts +715 -0
  115. package/src/chains/evm/routes/sign.ts +333 -0
  116. package/src/chains/evm/rpc-providers.ts +410 -0
  117. package/src/chains/evm/service.ts +140 -0
  118. package/src/chains/evm/templates/index.ts +10 -0
  119. package/src/chains/evm/types/index.ts +432 -0
  120. package/src/chains/evm/vitest.config.ts +18 -0
  121. package/src/chains/registry.ts +668 -0
  122. package/src/chains/solana/README.md +367 -0
  123. package/src/chains/wallet-action.ts +533 -0
  124. package/src/chains/wallet-router.test.ts +296 -0
  125. package/src/contracts.ts +65 -0
  126. package/src/core-augmentation.ts +10 -0
  127. package/src/index.ts +71 -0
  128. package/src/lib/server-wallet-trade.ts +192 -0
  129. package/src/lib/wallet-export-guard.ts +330 -0
  130. package/src/lp/actions/liquidity.ts +827 -0
  131. package/src/lp/e2e/real-token-tests.ts +428 -0
  132. package/src/lp/e2e/scenarios.ts +470 -0
  133. package/src/lp/e2e/test-utils.ts +145 -0
  134. package/src/lp/lp-manager-entry.ts +303 -0
  135. package/src/lp/services/ConcentratedLiquidityService.ts +120 -0
  136. package/src/lp/services/DexInteractionService.ts +226 -0
  137. package/src/lp/services/LpManagementService.test.ts +148 -0
  138. package/src/lp/services/LpManagementService.ts +632 -0
  139. package/src/lp/services/UserLpProfileService.ts +163 -0
  140. package/src/lp/services/VaultService.ts +153 -0
  141. package/src/lp/services/YieldOptimizationService.ts +344 -0
  142. package/src/lp/services/__tests__/MockLpService.ts +146 -0
  143. package/src/lp/tasks/LpAutoRebalanceTask.ts +117 -0
  144. package/src/lp/tasks/__tests__/LpAutoRebalanceTask.test.ts +370 -0
  145. package/src/lp/types.ts +582 -0
  146. package/src/lp/utils/solanaClient.ts +143 -0
  147. package/src/plugin.ts +125 -0
  148. package/src/policy/policy.ts +19 -0
  149. package/src/providers/canonical-provider.ts +27 -0
  150. package/src/providers/unified-wallet-provider.ts +79 -0
  151. package/src/register-routes.ts +11 -0
  152. package/src/routes/plugin.ts +47 -0
  153. package/src/routes/wallet-market-overview-route.ts +869 -0
  154. package/src/sdk/abi.ts +258 -0
  155. package/src/sdk/bridge/abis.ts +126 -0
  156. package/src/sdk/bridge/client.ts +518 -0
  157. package/src/sdk/bridge/index.ts +56 -0
  158. package/src/sdk/bridge/solana.ts +604 -0
  159. package/src/sdk/bridge/types.ts +202 -0
  160. package/src/sdk/convenience.ts +347 -0
  161. package/src/sdk/escrow/MutualStakeEscrow.ts +480 -0
  162. package/src/sdk/escrow/types.ts +64 -0
  163. package/src/sdk/escrow/verifiers.ts +73 -0
  164. package/src/sdk/identity/erc8004.ts +692 -0
  165. package/src/sdk/identity/reputation.ts +449 -0
  166. package/src/sdk/identity/uaid.ts +497 -0
  167. package/src/sdk/identity/validation.ts +372 -0
  168. package/src/sdk/index.ts +763 -0
  169. package/src/sdk/policy/SpendingPolicy.ts +260 -0
  170. package/src/sdk/policy/UptoBillingPolicy.ts +320 -0
  171. package/src/sdk/router/PaymentRouter.ts +215 -0
  172. package/src/sdk/router/index.ts +8 -0
  173. package/src/sdk/swap/SwapModule.ts +310 -0
  174. package/src/sdk/swap/abi.ts +117 -0
  175. package/src/sdk/swap/index.ts +34 -0
  176. package/src/sdk/swap/types.ts +135 -0
  177. package/src/sdk/tokens/decimals.ts +140 -0
  178. package/src/sdk/tokens/registry.ts +911 -0
  179. package/src/sdk/tokens/solana.ts +419 -0
  180. package/src/sdk/tokens/transfers.ts +327 -0
  181. package/src/sdk/types.ts +158 -0
  182. package/src/sdk/wallet-core.ts +115 -0
  183. package/src/sdk/x402/budget.ts +168 -0
  184. package/src/sdk/x402/chains/abstract/index.ts +280 -0
  185. package/src/sdk/x402/client.ts +320 -0
  186. package/src/sdk/x402/index.ts +46 -0
  187. package/src/sdk/x402/middleware.ts +92 -0
  188. package/src/sdk/x402/multi-asset.ts +144 -0
  189. package/src/sdk/x402/types.ts +156 -0
  190. package/src/services/wallet-backend-service.ts +328 -0
  191. package/src/types/wallet-router.ts +227 -0
  192. package/src/utils/intent-trajectory.ts +106 -0
  193. package/src/wallet/backend.ts +62 -0
  194. package/src/wallet/errors.ts +49 -0
  195. package/src/wallet/index.ts +27 -0
  196. package/src/wallet/local-eoa-backend.ts +201 -0
  197. package/src/wallet/pending.ts +60 -0
  198. package/src/wallet/select-backend.ts +47 -0
  199. package/src/wallet/steward-backend.ts +161 -0
  200. package/src/wallet-action.ts +1 -0
@@ -0,0 +1,763 @@
1
+ import type { JsonValue } from "@elizaos/core";
2
+ import {
3
+ type Address,
4
+ type Chain,
5
+ createPublicClient,
6
+ getContract,
7
+ type Hash,
8
+ type Hex,
9
+ http,
10
+ type WalletClient,
11
+ } from "viem";
12
+ import { arbitrum, base, baseSepolia, mainnet, polygon } from "viem/chains";
13
+ import { AgentAccountFactoryV2Abi, AgentAccountV2Abi } from "./abi.js";
14
+ import type {
15
+ ActivityEntry,
16
+ BatchTransfer,
17
+ BudgetForecast,
18
+ ExecuteResult,
19
+ PendingTx,
20
+ QueuedEvent,
21
+ WalletHealth,
22
+ } from "./types.js";
23
+ import {
24
+ NATIVE_TOKEN,
25
+ requireWalletAccount,
26
+ type AgentWallet as Wallet,
27
+ } from "./wallet-core.js";
28
+
29
+ export { AgentAccountFactoryV2Abi, AgentAccountV2Abi } from "./abi.js";
30
+ export type {
31
+ ActivityEntry,
32
+ AgentWalletConfig,
33
+ BatchTransfer,
34
+ BudgetForecast,
35
+ BudgetStatus,
36
+ ExecuteResult,
37
+ PendingTx,
38
+ QueuedEvent,
39
+ SpendPolicy,
40
+ WalletHealth,
41
+ } from "./types.js";
42
+ export {
43
+ agentTransferToken,
44
+ checkBudget,
45
+ createWallet,
46
+ NATIVE_TOKEN,
47
+ requireWalletAccount,
48
+ setSpendPolicy,
49
+ } from "./wallet-core.js";
50
+ export type {
51
+ X402ClientConfig,
52
+ X402PaymentPayload,
53
+ X402PaymentRequired,
54
+ X402PaymentRequirements,
55
+ X402ResourceInfo,
56
+ X402ServiceBudget,
57
+ X402SettlementResponse,
58
+ X402TransactionLog,
59
+ } from "./x402/index.js";
60
+ // [MAX-ADDED] x402 protocol support
61
+ export {
62
+ createX402Client,
63
+ createX402Fetch,
64
+ DEFAULT_SUPPORTED_NETWORKS,
65
+ USDC_ADDRESSES,
66
+ wrapWithX402,
67
+ X402BudgetExceededError,
68
+ X402BudgetTracker,
69
+ X402Client,
70
+ X402PaymentError,
71
+ } from "./x402/index.js";
72
+
73
+ const CHAINS: Record<string, Chain> = {
74
+ base,
75
+ "base-sepolia": baseSepolia,
76
+ ethereum: mainnet,
77
+ arbitrum,
78
+ polygon,
79
+ };
80
+
81
+ /**
82
+ * Execute a transaction as the agent. If within limits, executes immediately.
83
+ * If over limits, queues for owner approval and returns the pending tx ID.
84
+ */
85
+ export async function agentExecute(
86
+ wallet: Wallet,
87
+ params: { to: Address; value?: bigint; data?: Hex },
88
+ ): Promise<ExecuteResult> {
89
+ const value = params.value ?? 0n;
90
+ const data = params.data ?? "0x";
91
+
92
+ const hash = await wallet.contract.write.agentExecute(
93
+ [params.to, value, data],
94
+ {
95
+ value,
96
+ account: requireWalletAccount(wallet.walletClient),
97
+ chain: wallet.chain,
98
+ },
99
+ );
100
+
101
+ // Check the tx receipt for TransactionQueued vs TransactionExecuted events
102
+ const receipt = await wallet.publicClient.waitForTransactionReceipt({ hash });
103
+
104
+ // Event topic hash for AgentAccountV2 queue detection
105
+ const QUEUED_TOPIC =
106
+ "0x338e4b9b04df0b67a953d7ea6a7037128b8c6948e3d8c09a9d51a5f5be6c2284";
107
+
108
+ const walletAddr = wallet.address.toLowerCase();
109
+ const queuedLog = receipt.logs.find(
110
+ (log) =>
111
+ log.address.toLowerCase() === walletAddr &&
112
+ log.topics[0] === QUEUED_TOPIC,
113
+ );
114
+
115
+ const wasExecuted = !queuedLog;
116
+
117
+ return {
118
+ executed: wasExecuted,
119
+ txHash: hash,
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Get a pending transaction by ID.
125
+ */
126
+ export async function getPendingApprovals(
127
+ wallet: Wallet,
128
+ fromId: bigint = 0n,
129
+ toId?: bigint,
130
+ ): Promise<PendingTx[]> {
131
+ const maxId = toId ?? (await wallet.contract.read.pendingNonce());
132
+ const results: PendingTx[] = [];
133
+
134
+ for (let i = fromId; i < maxId; i++) {
135
+ const [to, value, token, amount, createdAt, executed, cancelled] =
136
+ await wallet.contract.read.getPending([i]);
137
+
138
+ if (!executed && !cancelled && createdAt > 0n) {
139
+ results.push({
140
+ txId: i,
141
+ to,
142
+ value,
143
+ data: "0x", // data not returned by getPending view
144
+ token,
145
+ amount,
146
+ createdAt: Number(createdAt),
147
+ executed,
148
+ cancelled,
149
+ });
150
+ }
151
+ }
152
+
153
+ return results;
154
+ }
155
+
156
+ /**
157
+ * Approve a pending transaction. Only callable by the NFT owner.
158
+ */
159
+ export async function approveTransaction(
160
+ wallet: Wallet,
161
+ txId: bigint,
162
+ ): Promise<Hash> {
163
+ return wallet.contract.write.approvePending([txId], {
164
+ account: requireWalletAccount(wallet.walletClient),
165
+ chain: wallet.chain,
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Cancel a pending transaction. Only callable by the NFT owner.
171
+ */
172
+ export async function cancelTransaction(
173
+ wallet: Wallet,
174
+ txId: bigint,
175
+ ): Promise<Hash> {
176
+ return wallet.contract.write.cancelPending([txId], {
177
+ account: requireWalletAccount(wallet.walletClient),
178
+ chain: wallet.chain,
179
+ });
180
+ }
181
+
182
+ /**
183
+ * Add or remove an operator (agent hot wallet).
184
+ */
185
+ export async function setOperator(
186
+ wallet: Wallet,
187
+ operator: Address,
188
+ authorized: boolean,
189
+ ): Promise<Hash> {
190
+ return wallet.contract.write.setOperator([operator, authorized], {
191
+ account: requireWalletAccount(wallet.walletClient),
192
+ chain: wallet.chain,
193
+ });
194
+ }
195
+
196
+ // ─── Factory: Deploy New Wallets ───
197
+
198
+ /**
199
+ * Deploy a new AgentAccountV2 wallet via the factory (CREATE2).
200
+ * Returns the deterministic wallet address.
201
+ */
202
+ export async function deployWallet(config: {
203
+ factoryAddress: Address;
204
+ tokenContract: Address;
205
+ tokenId: bigint;
206
+ chain: keyof typeof CHAINS;
207
+ rpcUrl?: string;
208
+ walletClient: WalletClient;
209
+ }): Promise<{ walletAddress: Address; txHash: Hash }> {
210
+ const chain = CHAINS[config.chain];
211
+ if (!chain) throw new Error(`Unsupported chain: ${config.chain}`);
212
+
213
+ const publicClient = createPublicClient({
214
+ chain,
215
+ transport: http(config.rpcUrl),
216
+ });
217
+
218
+ const factory = getContract({
219
+ address: config.factoryAddress,
220
+ abi: AgentAccountFactoryV2Abi,
221
+ client: { public: publicClient, wallet: config.walletClient },
222
+ });
223
+
224
+ // Get deterministic address first
225
+ const walletAddress = (await factory.read.getAddress([
226
+ config.tokenContract,
227
+ config.tokenId,
228
+ ])) as Address;
229
+
230
+ // Deploy
231
+ const txHash = await factory.write.createAccount(
232
+ [config.tokenContract, config.tokenId],
233
+ { account: requireWalletAccount(config.walletClient), chain },
234
+ );
235
+
236
+ return { walletAddress, txHash };
237
+ }
238
+
239
+ /**
240
+ * Compute the deterministic wallet address without deploying.
241
+ */
242
+ export async function getWalletAddress(config: {
243
+ factoryAddress: Address;
244
+ tokenContract: Address;
245
+ tokenId: bigint;
246
+ chain: string;
247
+ rpcUrl?: string;
248
+ }): Promise<Address> {
249
+ const chain = CHAINS[config.chain];
250
+ if (!chain) throw new Error(`Unsupported chain: ${config.chain}`);
251
+
252
+ const publicClient = createPublicClient({
253
+ chain,
254
+ transport: http(config.rpcUrl),
255
+ });
256
+
257
+ const factory = getContract({
258
+ address: config.factoryAddress,
259
+ abi: AgentAccountFactoryV2Abi,
260
+ client: publicClient,
261
+ });
262
+
263
+ return factory.read.getAddress([
264
+ config.tokenContract,
265
+ config.tokenId,
266
+ ]) as Promise<Address>;
267
+ }
268
+
269
+ // ─── [MAX-ADDED] Value-Add Features for Agent Customers ───
270
+
271
+ /**
272
+ * [MAX-ADDED] Budget forecast with period-aware remaining capacity.
273
+ * Why: Agents need to know not just "how much is left" but "when does budget reset"
274
+ * so they can plan spending across time windows and avoid unnecessary queuing.
275
+ */
276
+ export async function getBudgetForecast(
277
+ wallet: Wallet,
278
+ token: Address = NATIVE_TOKEN,
279
+ now?: number,
280
+ ): Promise<BudgetForecast> {
281
+ const [perTxLimit, remainingInPeriod] =
282
+ await wallet.contract.read.remainingBudget([token]);
283
+ const [_policyPerTx, periodLimit, periodLength, periodSpent, periodStart] =
284
+ await wallet.contract.read.spendPolicies([token]);
285
+
286
+ const currentTime = now ?? Math.floor(Date.now() / 1000);
287
+ const periodEnd = Number(periodStart) + Number(periodLength);
288
+ const secondsUntilReset = Math.max(0, periodEnd - currentTime);
289
+ const utilizationPercent =
290
+ periodLimit > 0n ? Number((periodSpent * 100n) / periodLimit) : 0;
291
+
292
+ return {
293
+ token,
294
+ perTxLimit,
295
+ remainingInPeriod,
296
+ periodLimit,
297
+ periodLength: Number(periodLength),
298
+ periodSpent,
299
+ periodStart: Number(periodStart),
300
+ secondsUntilReset,
301
+ utilizationPercent,
302
+ };
303
+ }
304
+
305
+ /**
306
+ * [MAX-ADDED] Wallet health check — diagnostic snapshot for agent self-monitoring.
307
+ * Why: Agents need a single-call way to verify their wallet is properly configured,
308
+ * check operator status, and monitor queue depth before executing transactions.
309
+ */
310
+ export async function getWalletHealth(
311
+ wallet: Wallet,
312
+ operatorsToCheck: Address[] = [],
313
+ tokensToCheck: Address[] = [NATIVE_TOKEN],
314
+ now?: number,
315
+ ): Promise<WalletHealth> {
316
+ // Read wallet identity
317
+ const [tokenContract, tokenId, operatorEpoch] = await Promise.all([
318
+ wallet.contract.read.tokenContract(),
319
+ wallet.contract.read.tokenId(),
320
+ wallet.contract.read.operatorEpoch(),
321
+ ]);
322
+
323
+ // Check operator status
324
+ const activeOperators = await Promise.all(
325
+ operatorsToCheck.map(async (addr) => ({
326
+ address: addr,
327
+ active: (await wallet.contract.read.isOperatorActive([addr])) as boolean,
328
+ })),
329
+ );
330
+
331
+ // Count pending queue depth
332
+ const pendingNonce = (await wallet.contract.read.pendingNonce()) as bigint;
333
+ let pendingQueueDepth = 0;
334
+ for (let i = 0n; i < pendingNonce; i++) {
335
+ const [, , , , createdAt, executed, cancelled] =
336
+ await wallet.contract.read.getPending([i]);
337
+ if (!executed && !cancelled && createdAt > 0n) pendingQueueDepth++;
338
+ }
339
+
340
+ // Budget forecasts for requested tokens
341
+ const budgets = await Promise.all(
342
+ tokensToCheck.map((t) => getBudgetForecast(wallet, t, now)),
343
+ );
344
+
345
+ return {
346
+ address: wallet.address,
347
+ tokenContract: tokenContract as Address,
348
+ tokenId: tokenId as bigint,
349
+ operatorEpoch: operatorEpoch as bigint,
350
+ activeOperators,
351
+ pendingQueueDepth,
352
+ budgets,
353
+ };
354
+ }
355
+
356
+ /**
357
+ * [MAX-ADDED] Batch agent token transfers — multiple transfers in sequential calls.
358
+ * Why: Agents often need to pay multiple recipients (tips, fees, splits). This helper
359
+ * reduces boilerplate and returns all tx hashes. Each is a separate on-chain tx
360
+ * (true batching would need a multicall contract, but this is the safe SDK-level helper).
361
+ */
362
+ export async function batchAgentTransfer(
363
+ wallet: Wallet,
364
+ transfers: BatchTransfer[],
365
+ ): Promise<Hash[]> {
366
+ const hashes: Hash[] = [];
367
+ for (const t of transfers) {
368
+ const hash = await wallet.contract.write.agentTransferToken(
369
+ [t.token, t.to, t.amount],
370
+ {
371
+ account: requireWalletAccount(wallet.walletClient),
372
+ chain: wallet.chain,
373
+ },
374
+ );
375
+ hashes.push(hash);
376
+ }
377
+ return hashes;
378
+ }
379
+
380
+ /**
381
+ * [MAX-ADDED] Activity history — query past wallet events for self-auditing.
382
+ * Why: Agents need to verify what happened on-chain (transfers, operator changes,
383
+ * policy updates) without relying on external indexers. This queries event logs directly.
384
+ */
385
+ export async function getActivityHistory(
386
+ wallet: Wallet,
387
+ options: { fromBlock?: bigint; toBlock?: bigint | "latest" } = {},
388
+ ): Promise<ActivityEntry[]> {
389
+ const fromBlock = options.fromBlock ?? 0n;
390
+ const toBlock = options.toBlock ?? ("latest" as const);
391
+
392
+ const eventConfigs = [
393
+ { eventName: "TransactionExecuted" as const, type: "execution" as const },
394
+ { eventName: "TransactionQueued" as const, type: "queued" as const },
395
+ { eventName: "TransactionApproved" as const, type: "approved" as const },
396
+ { eventName: "TransactionCancelled" as const, type: "cancelled" as const },
397
+ {
398
+ eventName: "SpendPolicyUpdated" as const,
399
+ type: "policy_update" as const,
400
+ },
401
+ { eventName: "OperatorUpdated" as const, type: "operator_update" as const },
402
+ ];
403
+
404
+ const allEntries: ActivityEntry[] = [];
405
+
406
+ for (const { eventName, type } of eventConfigs) {
407
+ const logs = await wallet.publicClient.getContractEvents({
408
+ address: wallet.address,
409
+ abi: AgentAccountV2Abi,
410
+ eventName,
411
+ fromBlock,
412
+ toBlock,
413
+ });
414
+
415
+ for (const log of logs) {
416
+ const rawArgs =
417
+ log && typeof log === "object" && "args" in log
418
+ ? (log as { args?: Record<string, JsonValue> }).args
419
+ : undefined;
420
+ allEntries.push({
421
+ type,
422
+ blockNumber: log.blockNumber ?? 0n,
423
+ transactionHash: log.transactionHash ?? ("0x" as Hash),
424
+ args: rawArgs ?? {},
425
+ });
426
+ }
427
+ }
428
+
429
+ // Sort by block number ascending
430
+ allEntries.sort((a, b) => Number(a.blockNumber - b.blockNumber));
431
+ return allEntries;
432
+ }
433
+
434
+ // ─── Event Listeners ───
435
+
436
+ /**
437
+ * Watch for TransactionQueued events (over-limit transactions needing approval).
438
+ * Returns an unwatch function.
439
+ */
440
+ export function onTransactionQueued(
441
+ wallet: Wallet,
442
+ callback: (event: QueuedEvent) => void,
443
+ ): () => void {
444
+ return wallet.publicClient.watchContractEvent({
445
+ address: wallet.address,
446
+ abi: AgentAccountV2Abi,
447
+ eventName: "TransactionQueued",
448
+ onLogs: (logs) => {
449
+ for (const log of logs) {
450
+ const args =
451
+ log && typeof log === "object" && "args" in log
452
+ ? (
453
+ log as {
454
+ args?: {
455
+ txId?: bigint;
456
+ to?: Address;
457
+ value?: bigint;
458
+ token?: Address;
459
+ amount?: bigint;
460
+ };
461
+ }
462
+ ).args
463
+ : undefined;
464
+ if (
465
+ !args ||
466
+ args.txId === undefined ||
467
+ args.to === undefined ||
468
+ args.value === undefined ||
469
+ args.token === undefined ||
470
+ args.amount === undefined ||
471
+ !log.transactionHash
472
+ ) {
473
+ continue;
474
+ }
475
+ callback({
476
+ txId: args.txId,
477
+ to: args.to,
478
+ value: args.value,
479
+ token: args.token,
480
+ amount: args.amount,
481
+ blockNumber: log.blockNumber,
482
+ transactionHash: log.transactionHash,
483
+ });
484
+ }
485
+ },
486
+ });
487
+ }
488
+
489
+ /**
490
+ * Watch for TransactionExecuted events.
491
+ */
492
+ export function onTransactionExecuted(
493
+ wallet: Wallet,
494
+ callback: (event: {
495
+ target: Address;
496
+ value: bigint;
497
+ executor: Address;
498
+ transactionHash: Hash;
499
+ }) => void,
500
+ ): () => void {
501
+ return wallet.publicClient.watchContractEvent({
502
+ address: wallet.address,
503
+ abi: AgentAccountV2Abi,
504
+ eventName: "TransactionExecuted",
505
+ onLogs: (logs) => {
506
+ for (const log of logs) {
507
+ const args =
508
+ log && typeof log === "object" && "args" in log
509
+ ? (
510
+ log as {
511
+ args?: {
512
+ target?: Address;
513
+ value?: bigint;
514
+ executor?: Address;
515
+ };
516
+ }
517
+ ).args
518
+ : undefined;
519
+ const transactionHash = log.transactionHash;
520
+ if (
521
+ !args ||
522
+ args.target === undefined ||
523
+ args.value === undefined ||
524
+ args.executor === undefined ||
525
+ !transactionHash
526
+ ) {
527
+ continue;
528
+ }
529
+ callback({
530
+ target: args.target,
531
+ value: args.value,
532
+ executor: args.executor,
533
+ transactionHash,
534
+ });
535
+ }
536
+ },
537
+ });
538
+ }
539
+
540
+ export type {
541
+ BridgeChain,
542
+ BridgeOptions,
543
+ BridgeResult,
544
+ BurnResult,
545
+ } from "./bridge/index.js";
546
+ // ─── CCTP V2 Cross-Chain Bridge ─────────────────────────────────────────────
547
+ export {
548
+ BRIDGE_CHAIN_IDS,
549
+ BridgeError,
550
+ BridgeModule,
551
+ CCTP_DOMAIN_IDS,
552
+ createBridge,
553
+ ERC20BridgeAbi,
554
+ FINALITY_THRESHOLD,
555
+ MESSAGE_TRANSMITTER_V2,
556
+ MessageTransmitterV2Abi,
557
+ TOKEN_MESSENGER_V2,
558
+ TokenMessengerV2Abi,
559
+ USDC_CONTRACT,
560
+ } from "./bridge/index.js";
561
+ export type {
562
+ AgentIdentity,
563
+ AgentModelMetadata,
564
+ AgentRegistrationFile,
565
+ AgentRegistrationRef,
566
+ AgentServiceEndpoint,
567
+ ERC8004ClientConfig,
568
+ MetadataEntry,
569
+ RegistrationResult,
570
+ SupportedChain,
571
+ SupportedTrustMechanism,
572
+ } from "./identity/erc8004.js";
573
+ // ─── ERC-8004: Trustless Agents — Identity Registry ─────────────────────────
574
+ export {
575
+ buildDataURI,
576
+ ERC8004Client,
577
+ ERC8004IdentityRegistryAbi,
578
+ formatAgentRegistry,
579
+ KNOWN_REGISTRY_ADDRESSES,
580
+ METADATA_KEYS,
581
+ parseDataURI,
582
+ REGISTRATION_FILE_TYPE,
583
+ resolveAgentURI,
584
+ validateRegistrationFile,
585
+ } from "./identity/erc8004.js";
586
+ export type {
587
+ AgentReputationSummary,
588
+ FeedbackEntry,
589
+ FeedbackFilters,
590
+ GiveFeedbackParams,
591
+ ReputationClientConfig,
592
+ RespondToFeedbackParams,
593
+ } from "./identity/reputation.js";
594
+ // ─── ERC-8004: Reputation Registry ─────────────────────────────────────────
595
+ export {
596
+ ReputationClient,
597
+ ReputationRegistryAbi,
598
+ } from "./identity/reputation.js";
599
+ export type {
600
+ ParsedUAID,
601
+ RegisterUAIDParams,
602
+ UAIDProtocol,
603
+ UAIDResolution,
604
+ UAIDResolverConfig,
605
+ UniversalAgentIdentity,
606
+ } from "./identity/uaid.js";
607
+ // ─── UAID: Cross-Chain Identity Resolution (HOL Registry Broker) ────────────
608
+ export { UAIDResolver } from "./identity/uaid.js";
609
+ export type {
610
+ RequestValidationParams,
611
+ RespondToValidationParams,
612
+ ValidationClientConfig,
613
+ ValidationStatus,
614
+ ValidationSummary,
615
+ } from "./identity/validation.js";
616
+ // ─── ERC-8004: Validation Registry ─────────────────────────────────────────
617
+ export {
618
+ ValidationClient,
619
+ ValidationRegistryAbi,
620
+ } from "./identity/validation.js";
621
+ export type {
622
+ SwapModuleConfig,
623
+ SwapOptions,
624
+ SwapQuote,
625
+ SwapResult,
626
+ UniswapFeeTier,
627
+ } from "./swap/index.js";
628
+ // ─── SwapModule — Uniswap V3 token swap aggregator ──────────────────────────
629
+ export {
630
+ applySlippage,
631
+ attachSwap,
632
+ BASE_TOKENS,
633
+ calcDeadline,
634
+ calcProtocolFee,
635
+ DEFAULT_SLIPPAGE_BPS,
636
+ ERC20Abi,
637
+ PROTOCOL_FEE_BPS,
638
+ PROTOCOL_FEE_COLLECTOR,
639
+ SwapModule,
640
+ UniswapV3QuoterV2Abi,
641
+ UniswapV3RouterAbi,
642
+ } from "./swap/index.js";
643
+
644
+ // x402 already exported above from original index.ts
645
+
646
+ // ─── Convenience: env-variable-driven wallet bootstrap ──────────────────────
647
+ export {
648
+ setPolicyFromEnv,
649
+ walletFromEnv,
650
+ x402FromEnv,
651
+ } from "./convenience.js";
652
+ // ─── Mutual Stake Escrow ─────────────────────────────────────────────────────
653
+ export { MutualStakeEscrow } from "./escrow/MutualStakeEscrow.js";
654
+ export type {
655
+ CreateEscrowParams,
656
+ EscrowCreated,
657
+ EscrowDetails,
658
+ TxResult as EscrowTxResult,
659
+ } from "./escrow/types.js";
660
+ export { TaskStatus } from "./escrow/types.js";
661
+ export {
662
+ encodeHashVerifierData,
663
+ encodeOptimisticVerifierData,
664
+ resolveVerifierAddress,
665
+ VERIFIER_ADDRESSES,
666
+ } from "./escrow/verifiers.js";
667
+ export type {
668
+ AuditEntry,
669
+ DraftEntry,
670
+ PaymentIntent,
671
+ PolicyResult,
672
+ PolicyStatus,
673
+ SpendingPolicyConfig,
674
+ } from "./policy/SpendingPolicy.js";
675
+ // ─── SpendingPolicy — Programmable spending guardrails ───────────────────────
676
+ export { SpendingPolicy } from "./policy/SpendingPolicy.js";
677
+ export type {
678
+ UptoAuthorizationRecord,
679
+ UptoAuthorizationRequest,
680
+ UptoAuthorizationStatus,
681
+ UptoBillingSnapshot,
682
+ UptoSettlementOptions,
683
+ UptoSettlementRecord,
684
+ WalletLedgerDelta,
685
+ } from "./policy/UptoBillingPolicy.js";
686
+ // ─── UptoBillingPolicy — x402 usage-based settlement accounting ─────────────
687
+ export { UptoBillingPolicy } from "./policy/UptoBillingPolicy.js";
688
+
689
+ // ─── v6: Multi-Token Support ─────────────────────────────────────────────────
690
+
691
+ export type {
692
+ PaymentContext,
693
+ PaymentRail,
694
+ RailConfig,
695
+ RailStatus,
696
+ RoutingDecision,
697
+ } from "./router/index.js";
698
+ // ─── Payment Router ───────────────────────────────────────────────────────────
699
+ export { PaymentRouter } from "./router/index.js";
700
+ export type { TokenInfo } from "./tokens/decimals.js";
701
+ // Token decimal normalization
702
+ export {
703
+ formatBalance,
704
+ parseAmount,
705
+ toHuman,
706
+ toRaw,
707
+ } from "./tokens/decimals.js";
708
+ export type { AddTokenParams, TokenEntry } from "./tokens/registry.js";
709
+ // TokenRegistry — pre-populated multi-chain token address registry
710
+ export {
711
+ ARBITRUM_REGISTRY,
712
+ AVALANCHE_REGISTRY,
713
+ BASE_REGISTRY,
714
+ BASE_SEPOLIA_REGISTRY,
715
+ ETHEREUM_REGISTRY,
716
+ getGlobalRegistry,
717
+ getNativeToken,
718
+ LINEA_REGISTRY,
719
+ OPTIMISM_REGISTRY,
720
+ POLYGON_REGISTRY,
721
+ SONIC_REGISTRY,
722
+ TokenRegistry,
723
+ UNICHAIN_REGISTRY,
724
+ WORLDCHAIN_REGISTRY,
725
+ } from "./tokens/registry.js";
726
+ export type {
727
+ SolanaTokenInfo,
728
+ SolanaTokenSymbol,
729
+ SolanaTxResult,
730
+ SolanaWalletConfig,
731
+ SolBalanceResult,
732
+ SplBalanceResult,
733
+ } from "./tokens/solana.js";
734
+ // Solana SPL token support (optional peer dependency: @solana/web3.js)
735
+ export {
736
+ createSolanaWallet,
737
+ SOLANA_TOKEN_DECIMALS,
738
+ SOLANA_TOKENS,
739
+ SolanaWallet,
740
+ } from "./tokens/solana.js";
741
+ export type {
742
+ NativeBalanceResult,
743
+ TokenBalanceResult,
744
+ TransferContext,
745
+ TransferOptions,
746
+ } from "./tokens/transfers.js";
747
+ // Multi-token EVM transfers (direct EOA/hot-wallet operations)
748
+ export {
749
+ encodeERC20Transfer,
750
+ getBalances,
751
+ getNativeBalance,
752
+ getTokenBalance,
753
+ sendNative,
754
+ sendToken,
755
+ } from "./tokens/transfers.js";
756
+ // x402 multi-asset resolution (v6 additions)
757
+ export {
758
+ buildSupportedAssets,
759
+ isStablecoin,
760
+ parseNetworkChainId,
761
+ resolveAssetAddress,
762
+ resolveAssetDecimals,
763
+ } from "./x402/multi-asset.js";