@smartagentkit/sdk 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1354 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ALLOWLIST_HOOK_ABI: () => ALLOWLIST_HOOK_ABI,
24
+ DEPLOYMENTS: () => DEPLOYMENTS,
25
+ EMERGENCY_PAUSE_HOOK_ABI: () => EMERGENCY_PAUSE_HOOK_ABI,
26
+ ENTRYPOINT_V07: () => ENTRYPOINT_V07,
27
+ ExecutionError: () => ExecutionError,
28
+ HOOK_MULTIPLEXER_ABI: () => HOOK_MULTIPLEXER_ABI,
29
+ HOOK_MULTIPLEXER_ADDRESS: () => HOOK_MULTIPLEXER_ADDRESS,
30
+ HOOK_TYPE_GLOBAL: () => HOOK_TYPE_GLOBAL,
31
+ MODULE_ADDRESSES: () => MODULE_ADDRESSES,
32
+ MODULE_TYPE_EXECUTOR: () => MODULE_TYPE_EXECUTOR,
33
+ MODULE_TYPE_FALLBACK: () => MODULE_TYPE_FALLBACK,
34
+ MODULE_TYPE_HOOK: () => MODULE_TYPE_HOOK,
35
+ MODULE_TYPE_VALIDATOR: () => MODULE_TYPE_VALIDATOR,
36
+ NATIVE_TOKEN: () => NATIVE_TOKEN,
37
+ OWNABLE_VALIDATOR_ADDRESS: () => OWNABLE_VALIDATOR_ADDRESS,
38
+ PRESETS: () => PRESETS,
39
+ PolicyConfigError: () => PolicyConfigError,
40
+ RHINESTONE_ATTESTER: () => RHINESTONE_ATTESTER,
41
+ SAFE_7579_LAUNCHPAD: () => SAFE_7579_LAUNCHPAD,
42
+ SAFE_7579_MODULE: () => SAFE_7579_MODULE,
43
+ SMART_SESSIONS_ADDRESS: () => SMART_SESSIONS_ADDRESS,
44
+ SPENDING_LIMIT_HOOK_ABI: () => SPENDING_LIMIT_HOOK_ABI,
45
+ SessionError: () => SessionError,
46
+ SmartAgentKitClient: () => SmartAgentKitClient,
47
+ SmartAgentKitError: () => SmartAgentKitError,
48
+ SmartSessionMode: () => import_module_sdk2.SmartSessionMode,
49
+ SpendingLimitExceededError: () => SpendingLimitExceededError,
50
+ WINDOW_1_DAY: () => WINDOW_1_DAY,
51
+ WINDOW_1_HOUR: () => WINDOW_1_HOUR,
52
+ WINDOW_1_WEEK: () => WINDOW_1_WEEK,
53
+ WalletCreationError: () => WalletCreationError,
54
+ WalletPausedError: () => WalletPausedError,
55
+ buildSession: () => buildSession,
56
+ computePermissionId: () => computePermissionId,
57
+ encodeAllowlistInitData: () => encodeAllowlistInitData,
58
+ encodeEmergencyPauseInitData: () => encodeEmergencyPauseInitData,
59
+ encodeEnableSessionSignature: () => encodeEnableSessionSignature,
60
+ encodePolicyInitData: () => encodePolicyInitData,
61
+ encodeSpendingLimitInitData: () => encodeSpendingLimitInitData,
62
+ encodeUseSessionSignature: () => encodeUseSessionSignature,
63
+ getRemoveSessionAction: () => getRemoveAction,
64
+ getSmartSessionsModule: () => getSmartSessionsModule
65
+ });
66
+ module.exports = __toCommonJS(index_exports);
67
+
68
+ // src/client.ts
69
+ var import_viem4 = require("viem");
70
+ var import_accounts = require("viem/accounts");
71
+ var import_accounts2 = require("permissionless/accounts");
72
+ var import_clients = require("permissionless/clients");
73
+ var import_erc7579 = require("permissionless/actions/erc7579");
74
+ var import_module_sdk3 = require("@rhinestone/module-sdk");
75
+
76
+ // src/presets.ts
77
+ var import_viem = require("viem");
78
+
79
+ // src/constants.ts
80
+ var MODULE_TYPE_VALIDATOR = 1;
81
+ var MODULE_TYPE_EXECUTOR = 2;
82
+ var MODULE_TYPE_FALLBACK = 3;
83
+ var MODULE_TYPE_HOOK = 4;
84
+ var NATIVE_TOKEN = "0x0000000000000000000000000000000000000000";
85
+ var ENTRYPOINT_V07 = "0x0000000071727De22E5E9d8BAf0edAc6f37da032";
86
+ var SAFE_7579_MODULE = "0x7579EE8307284F293B1927136486880611F20002";
87
+ var SAFE_7579_LAUNCHPAD = "0x7579011aB74c46090561ea277Ba79D510c6C00ff";
88
+ var RHINESTONE_ATTESTER = "0x000000333034E9f539ce08819E12c1b8Cb29084d";
89
+ var ATTESTERS_THRESHOLD = 1;
90
+ var WINDOW_1_HOUR = 3600;
91
+ var WINDOW_1_DAY = 86400;
92
+ var WINDOW_1_WEEK = 604800;
93
+ var SPENDING_LIMIT_HOOK_ABI = [
94
+ {
95
+ name: "setSpendingLimit",
96
+ type: "function",
97
+ inputs: [
98
+ { name: "token", type: "address" },
99
+ { name: "limit", type: "uint256" },
100
+ { name: "windowDuration", type: "uint48" }
101
+ ],
102
+ outputs: [],
103
+ stateMutability: "nonpayable"
104
+ },
105
+ {
106
+ name: "removeSpendingLimit",
107
+ type: "function",
108
+ inputs: [{ name: "token", type: "address" }],
109
+ outputs: [],
110
+ stateMutability: "nonpayable"
111
+ },
112
+ {
113
+ name: "getRemainingAllowance",
114
+ type: "function",
115
+ inputs: [
116
+ { name: "account", type: "address" },
117
+ { name: "token", type: "address" }
118
+ ],
119
+ outputs: [{ name: "remaining", type: "uint256" }],
120
+ stateMutability: "view"
121
+ },
122
+ {
123
+ name: "configs",
124
+ type: "function",
125
+ inputs: [
126
+ { name: "account", type: "address" },
127
+ { name: "token", type: "address" }
128
+ ],
129
+ outputs: [
130
+ { name: "limit", type: "uint256" },
131
+ { name: "spent", type: "uint256" },
132
+ { name: "windowDuration", type: "uint48" },
133
+ { name: "windowStart", type: "uint48" }
134
+ ],
135
+ stateMutability: "view"
136
+ }
137
+ ];
138
+ var ALLOWLIST_HOOK_ABI = [
139
+ {
140
+ name: "addPermission",
141
+ type: "function",
142
+ inputs: [
143
+ { name: "target", type: "address" },
144
+ { name: "selector", type: "bytes4" }
145
+ ],
146
+ outputs: [],
147
+ stateMutability: "nonpayable"
148
+ },
149
+ {
150
+ name: "removePermission",
151
+ type: "function",
152
+ inputs: [
153
+ { name: "target", type: "address" },
154
+ { name: "selector", type: "bytes4" }
155
+ ],
156
+ outputs: [],
157
+ stateMutability: "nonpayable"
158
+ },
159
+ {
160
+ name: "setMode",
161
+ type: "function",
162
+ inputs: [{ name: "mode", type: "uint8" }],
163
+ outputs: [],
164
+ stateMutability: "nonpayable"
165
+ },
166
+ {
167
+ name: "isTargetAllowed",
168
+ type: "function",
169
+ inputs: [
170
+ { name: "account", type: "address" },
171
+ { name: "target", type: "address" },
172
+ { name: "selector", type: "bytes4" }
173
+ ],
174
+ outputs: [{ name: "", type: "bool" }],
175
+ stateMutability: "view"
176
+ }
177
+ ];
178
+ var EMERGENCY_PAUSE_HOOK_ABI = [
179
+ {
180
+ name: "pause",
181
+ type: "function",
182
+ inputs: [{ name: "account", type: "address" }],
183
+ outputs: [],
184
+ stateMutability: "nonpayable"
185
+ },
186
+ {
187
+ name: "unpause",
188
+ type: "function",
189
+ inputs: [{ name: "account", type: "address" }],
190
+ outputs: [],
191
+ stateMutability: "nonpayable"
192
+ },
193
+ {
194
+ name: "isPaused",
195
+ type: "function",
196
+ inputs: [{ name: "account", type: "address" }],
197
+ outputs: [{ name: "", type: "bool" }],
198
+ stateMutability: "view"
199
+ },
200
+ {
201
+ name: "setGuardian",
202
+ type: "function",
203
+ inputs: [{ name: "newGuardian", type: "address" }],
204
+ outputs: [],
205
+ stateMutability: "nonpayable"
206
+ },
207
+ {
208
+ name: "setAutoUnpauseTimeout",
209
+ type: "function",
210
+ inputs: [{ name: "timeout", type: "uint48" }],
211
+ outputs: [],
212
+ stateMutability: "nonpayable"
213
+ }
214
+ ];
215
+ var HOOK_MULTIPLEXER_ADDRESS = "0xF6782ed057F95f334D04F0Af1Af4D14fb84DE549";
216
+ var HOOK_TYPE_GLOBAL = 0;
217
+ var MODULE_ONINSTALL_ABI = [
218
+ {
219
+ name: "onInstall",
220
+ type: "function",
221
+ inputs: [{ name: "data", type: "bytes" }],
222
+ outputs: [],
223
+ stateMutability: "nonpayable"
224
+ }
225
+ ];
226
+ var SET_TRUSTED_FORWARDER_ABI = [
227
+ {
228
+ name: "setTrustedForwarder",
229
+ type: "function",
230
+ inputs: [{ name: "forwarder", type: "address" }],
231
+ outputs: [],
232
+ stateMutability: "nonpayable"
233
+ }
234
+ ];
235
+ var HOOK_MULTIPLEXER_ABI = [
236
+ {
237
+ name: "addHook",
238
+ type: "function",
239
+ inputs: [
240
+ { name: "hook", type: "address" },
241
+ { name: "hookType", type: "uint8" }
242
+ ],
243
+ outputs: [],
244
+ stateMutability: "nonpayable"
245
+ },
246
+ {
247
+ name: "removeHook",
248
+ type: "function",
249
+ inputs: [
250
+ { name: "hook", type: "address" },
251
+ { name: "hookType", type: "uint8" }
252
+ ],
253
+ outputs: [],
254
+ stateMutability: "nonpayable"
255
+ }
256
+ ];
257
+ var MODULE_ADDRESSES = {
258
+ // Will be populated after deployment
259
+ };
260
+
261
+ // src/presets.ts
262
+ var PRESETS = {
263
+ /**
264
+ * DeFi Trader preset:
265
+ * - Daily spending limit on ETH and stablecoins
266
+ * - Allowlist of approved DEX contracts
267
+ * - Emergency pause with owner as guardian
268
+ */
269
+ "defi-trader": (owner, params = {}) => [
270
+ {
271
+ type: "spending-limit",
272
+ limits: [
273
+ {
274
+ token: NATIVE_TOKEN,
275
+ limit: params.dailyEthLimit ?? (0, import_viem.parseEther)("1"),
276
+ window: WINDOW_1_DAY
277
+ },
278
+ ...params.stablecoinLimits ?? []
279
+ ]
280
+ },
281
+ // Only include allowlist if specific DEXes are provided;
282
+ // an empty allowlist in "allow" mode would block all transactions.
283
+ ...params.allowedDexes?.length ? [
284
+ {
285
+ type: "allowlist",
286
+ mode: "allow",
287
+ targets: params.allowedDexes.map((addr) => ({
288
+ address: addr,
289
+ selector: "0x00000000"
290
+ }))
291
+ }
292
+ ] : [],
293
+ {
294
+ type: "emergency-pause",
295
+ guardian: params.guardian ?? owner,
296
+ autoUnpauseAfter: WINDOW_1_DAY
297
+ }
298
+ ],
299
+ /**
300
+ * Treasury Agent preset:
301
+ * - Lower spending limits with longer windows
302
+ * - Emergency pause (manual only)
303
+ */
304
+ "treasury-agent": (owner, params = {}) => [
305
+ {
306
+ type: "spending-limit",
307
+ limits: [
308
+ {
309
+ token: NATIVE_TOKEN,
310
+ limit: params.weeklyEthLimit ?? (0, import_viem.parseEther)("5"),
311
+ window: WINDOW_1_WEEK
312
+ }
313
+ ]
314
+ },
315
+ {
316
+ type: "emergency-pause",
317
+ guardian: params.guardian ?? owner,
318
+ autoUnpauseAfter: 0
319
+ }
320
+ ],
321
+ /**
322
+ * Payment Agent preset:
323
+ * - Strict spending limits
324
+ * - Allowlist of approved recipients only
325
+ * - Emergency pause
326
+ */
327
+ "payment-agent": (owner, params = {}) => [
328
+ {
329
+ type: "spending-limit",
330
+ limits: [
331
+ {
332
+ token: NATIVE_TOKEN,
333
+ limit: params.dailyLimit ?? (0, import_viem.parseEther)("0.1"),
334
+ window: WINDOW_1_DAY
335
+ }
336
+ ]
337
+ },
338
+ // Only include allowlist if specific recipients are provided;
339
+ // an empty allowlist in "allow" mode would block all transactions.
340
+ ...params.approvedRecipients?.length ? [
341
+ {
342
+ type: "allowlist",
343
+ mode: "allow",
344
+ targets: params.approvedRecipients.map(
345
+ (addr) => ({
346
+ address: addr
347
+ })
348
+ )
349
+ }
350
+ ] : [],
351
+ {
352
+ type: "emergency-pause",
353
+ guardian: params.guardian ?? owner,
354
+ autoUnpauseAfter: 3600
355
+ }
356
+ ],
357
+ /**
358
+ * Minimal preset:
359
+ * - Just emergency pause
360
+ * - For agents that need maximum flexibility with a kill switch
361
+ */
362
+ minimal: (owner, params = {}) => [
363
+ {
364
+ type: "emergency-pause",
365
+ guardian: params.guardian ?? owner,
366
+ autoUnpauseAfter: 0
367
+ }
368
+ ]
369
+ };
370
+
371
+ // src/policies.ts
372
+ var import_viem2 = require("viem");
373
+
374
+ // src/errors.ts
375
+ var SmartAgentKitError = class extends Error {
376
+ constructor(message, options) {
377
+ super(message, options);
378
+ this.name = "SmartAgentKitError";
379
+ }
380
+ };
381
+ var WalletCreationError = class extends SmartAgentKitError {
382
+ constructor(message, cause) {
383
+ super(`Wallet creation failed: ${message}`, { cause });
384
+ this.name = "WalletCreationError";
385
+ }
386
+ };
387
+ var PolicyConfigError = class extends SmartAgentKitError {
388
+ constructor(message, cause) {
389
+ super(`Invalid policy configuration: ${message}`, { cause });
390
+ this.name = "PolicyConfigError";
391
+ }
392
+ };
393
+ var ExecutionError = class extends SmartAgentKitError {
394
+ constructor(message, cause) {
395
+ super(`Transaction execution failed: ${message}`, { cause });
396
+ this.name = "ExecutionError";
397
+ }
398
+ };
399
+ var SpendingLimitExceededError = class extends SmartAgentKitError {
400
+ constructor(token, attempted, remaining) {
401
+ super(
402
+ `Spending limit exceeded for ${token}: attempted ${attempted}, remaining ${remaining}`
403
+ );
404
+ this.token = token;
405
+ this.attempted = attempted;
406
+ this.remaining = remaining;
407
+ this.name = "SpendingLimitExceededError";
408
+ }
409
+ };
410
+ var WalletPausedError = class extends SmartAgentKitError {
411
+ constructor(walletAddress) {
412
+ super(`Wallet ${walletAddress} is currently paused`);
413
+ this.walletAddress = walletAddress;
414
+ this.name = "WalletPausedError";
415
+ }
416
+ };
417
+ var SessionError = class extends SmartAgentKitError {
418
+ constructor(message, cause) {
419
+ super(`Session error: ${message}`, { cause });
420
+ this.name = "SessionError";
421
+ }
422
+ };
423
+
424
+ // src/policies.ts
425
+ function encodePolicyInitData(policy, moduleAddresses, trustedForwarder = "0x0000000000000000000000000000000000000000") {
426
+ const zeroAddress = "0x0000000000000000000000000000000000000000";
427
+ switch (policy.type) {
428
+ case "spending-limit":
429
+ return {
430
+ moduleAddress: moduleAddresses?.spendingLimitHook ?? zeroAddress,
431
+ moduleType: MODULE_TYPE_HOOK,
432
+ initData: encodeSpendingLimitInitData(policy, trustedForwarder)
433
+ };
434
+ case "allowlist":
435
+ return {
436
+ moduleAddress: moduleAddresses?.allowlistHook ?? zeroAddress,
437
+ moduleType: MODULE_TYPE_HOOK,
438
+ initData: encodeAllowlistInitData(policy, trustedForwarder)
439
+ };
440
+ case "emergency-pause":
441
+ return {
442
+ moduleAddress: moduleAddresses?.emergencyPauseHook ?? zeroAddress,
443
+ moduleType: MODULE_TYPE_HOOK,
444
+ initData: encodeEmergencyPauseInitData(policy, trustedForwarder)
445
+ };
446
+ case "automation":
447
+ throw new PolicyConfigError(
448
+ "AutomationExecutor encoding is not yet implemented (Sprint 2)"
449
+ );
450
+ default: {
451
+ const _exhaustive = policy;
452
+ throw new PolicyConfigError(
453
+ `Unknown policy type: ${_exhaustive.type}`
454
+ );
455
+ }
456
+ }
457
+ }
458
+ function encodeSpendingLimitInitData(policy, trustedForwarder = "0x0000000000000000000000000000000000000000") {
459
+ if (policy.limits.length === 0) {
460
+ throw new PolicyConfigError("SpendingLimitPolicy must have at least one token limit");
461
+ }
462
+ const seenTokens = /* @__PURE__ */ new Set();
463
+ for (const limit of policy.limits) {
464
+ const tokenKey = limit.token.toLowerCase();
465
+ if (seenTokens.has(tokenKey)) {
466
+ throw new PolicyConfigError(
467
+ `Duplicate token address in limits: ${limit.token}. Only one limit per token is supported.`
468
+ );
469
+ }
470
+ seenTokens.add(tokenKey);
471
+ if (limit.limit <= 0n) {
472
+ throw new PolicyConfigError("Token limit must be greater than zero");
473
+ }
474
+ if (limit.window < 60) {
475
+ throw new PolicyConfigError("Window duration must be at least 60 seconds");
476
+ }
477
+ }
478
+ return (0, import_viem2.encodeAbiParameters)(
479
+ (0, import_viem2.parseAbiParameters)(
480
+ "address trustedForwarder, (address token, uint256 limit, uint48 windowDuration)[]"
481
+ ),
482
+ [
483
+ trustedForwarder,
484
+ policy.limits.map((l) => ({
485
+ token: l.token,
486
+ limit: l.limit,
487
+ windowDuration: l.window
488
+ }))
489
+ ]
490
+ );
491
+ }
492
+ function encodeAllowlistInitData(policy, trustedForwarder = "0x0000000000000000000000000000000000000000") {
493
+ if (policy.mode === "allow" && policy.targets.length === 0) {
494
+ throw new PolicyConfigError(
495
+ "AllowlistPolicy in 'allow' mode must have at least one target. An empty allowlist would block all transactions."
496
+ );
497
+ }
498
+ const mode = policy.mode === "allow" ? 0 : 1;
499
+ const wildcardSelector = "0x431e2cf5";
500
+ const protectedAddresses = policy.protectedAddresses ?? [];
501
+ if (protectedAddresses.length > 20) {
502
+ throw new PolicyConfigError(
503
+ "AllowlistPolicy protectedAddresses cannot exceed 20 entries (on-chain MAX_PROTECTED_ADDRESSES limit)"
504
+ );
505
+ }
506
+ return (0, import_viem2.encodeAbiParameters)(
507
+ (0, import_viem2.parseAbiParameters)(
508
+ "address trustedForwarder, uint8 mode, (address target, bytes4 selector)[], address[] protectedAddresses"
509
+ ),
510
+ [
511
+ trustedForwarder,
512
+ mode,
513
+ policy.targets.map((t) => ({
514
+ target: t.address,
515
+ selector: t.selector ?? wildcardSelector
516
+ })),
517
+ protectedAddresses
518
+ ]
519
+ );
520
+ }
521
+ function encodeEmergencyPauseInitData(policy, trustedForwarder = "0x0000000000000000000000000000000000000000") {
522
+ if (policy.guardian === "0x0000000000000000000000000000000000000000") {
523
+ throw new PolicyConfigError("Guardian address cannot be the zero address");
524
+ }
525
+ return (0, import_viem2.encodeAbiParameters)(
526
+ (0, import_viem2.parseAbiParameters)("address trustedForwarder, address guardian, uint48 autoUnpauseAfter"),
527
+ [trustedForwarder, policy.guardian, policy.autoUnpauseAfter ?? 0]
528
+ );
529
+ }
530
+
531
+ // src/deployments/base-sepolia.json
532
+ var base_sepolia_default = {
533
+ chainId: 84532,
534
+ entryPoint: "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
535
+ safe7579Module: "0x7579EE8307284F293B1927136486880611F20002",
536
+ safe7579Launchpad: "0x7579011aB74c46090561ea277Ba79D510c6C00ff",
537
+ rhinestoneAttester: "0x000000333034E9f539ce08819E12c1b8Cb29084d",
538
+ hookMultiPlexer: "0xF6782ed057F95f334D04F0Af1Af4D14fb84DE549",
539
+ spendingLimitHook: "0x0ea97ef2fc52700d1628110a8f411fefb0c0aa8b",
540
+ allowlistHook: "0x61a2100072d03f66de6f7dd0dfc2f7aa5c91e777",
541
+ emergencyPauseHook: "0xb8fdc9ee56cfb4077e132eff631b546fe6e79fec",
542
+ automationExecutor: "0x729c29b35c396b907ed118f00fbe4d4bcc3a7f46",
543
+ moduleSetupHelper: "0x4f1555baf4b3221c373094d47419596118828e41"
544
+ };
545
+
546
+ // src/deployments/sepolia.json
547
+ var sepolia_default = {
548
+ chainId: 11155111,
549
+ entryPoint: "0x0000000071727De22E5E9d8BAf0edAc6f37da032",
550
+ safe7579Module: "0x7579EE8307284F293B1927136486880611F20002",
551
+ safe7579Launchpad: "0x7579011aB74c46090561ea277Ba79D510c6C00ff",
552
+ rhinestoneAttester: "0x000000333034E9f539ce08819E12c1b8Cb29084d",
553
+ hookMultiPlexer: "",
554
+ spendingLimitHook: "",
555
+ allowlistHook: "",
556
+ emergencyPauseHook: "",
557
+ automationExecutor: "",
558
+ moduleSetupHelper: ""
559
+ };
560
+
561
+ // src/deployments.ts
562
+ var DEPLOYMENTS = {};
563
+ function loadDeployment(json) {
564
+ if (json.spendingLimitHook && json.spendingLimitHook !== "") {
565
+ DEPLOYMENTS[json.chainId] = {
566
+ spendingLimitHook: json.spendingLimitHook,
567
+ allowlistHook: json.allowlistHook,
568
+ emergencyPauseHook: json.emergencyPauseHook,
569
+ automationExecutor: json.automationExecutor || void 0
570
+ };
571
+ }
572
+ }
573
+ loadDeployment(base_sepolia_default);
574
+ loadDeployment(sepolia_default);
575
+
576
+ // src/sessions.ts
577
+ var import_viem3 = require("viem");
578
+ var import_module_sdk = require("@rhinestone/module-sdk");
579
+ var import_module_sdk2 = require("@rhinestone/module-sdk");
580
+ var SMART_SESSIONS_ADDRESS = "0x00000000002B0eCfbD0496EE71e01257dA0E37DE";
581
+ var OWNABLE_VALIDATOR_ADDRESS = "0x2483DA3A338895199E5e538530213157e931Bf06";
582
+ function buildSession(sessionKeyAddress, params, chainId, sessionValidatorAddress) {
583
+ const validatorAddress = sessionValidatorAddress ?? OWNABLE_VALIDATOR_ADDRESS;
584
+ const now = Math.floor(Date.now() / 1e3);
585
+ const sessionValidatorInitData = (0, import_viem3.encodeAbiParameters)(
586
+ (0, import_viem3.parseAbiParameters)("address"),
587
+ [sessionKeyAddress]
588
+ );
589
+ const userOpPolicies = [];
590
+ if (!params.expiresAt || params.expiresAt <= now) {
591
+ throw new SessionError("expiresAt must be in the future");
592
+ }
593
+ const timePolicy = (0, import_module_sdk.getTimeFramePolicy)({
594
+ validUntil: params.expiresAt,
595
+ validAfter: now
596
+ });
597
+ userOpPolicies.push({
598
+ policy: timePolicy.address,
599
+ initData: timePolicy.initData
600
+ });
601
+ if (params.spendingLimits && params.spendingLimits.length > 0) {
602
+ const spendingPolicy = (0, import_module_sdk.getSpendingLimitsPolicy)(
603
+ params.spendingLimits.map((l) => ({
604
+ token: l.token,
605
+ limit: l.limit
606
+ }))
607
+ );
608
+ userOpPolicies.push({
609
+ policy: spendingPolicy.address,
610
+ initData: spendingPolicy.initData
611
+ });
612
+ }
613
+ const actions = params.actions.map(
614
+ (action) => {
615
+ if (action.rules?.length) {
616
+ throw new SessionError(
617
+ "Per-action rules (SessionAction.rules) are not yet supported. Remove rules or wait for a future release."
618
+ );
619
+ }
620
+ return {
621
+ actionTarget: action.target,
622
+ actionTargetSelector: action.selector,
623
+ actionPolicies: []
624
+ };
625
+ }
626
+ );
627
+ if (actions.length === 0) {
628
+ throw new SessionError("Session must have at least one allowed action");
629
+ }
630
+ const randomBuf = new Uint8Array(32);
631
+ crypto.getRandomValues(randomBuf);
632
+ const salt = (0, import_viem3.keccak256)(
633
+ (0, import_viem3.concat)([sessionKeyAddress, (0, import_viem3.toHex)(randomBuf)])
634
+ );
635
+ return {
636
+ sessionValidator: validatorAddress,
637
+ sessionValidatorInitData,
638
+ salt,
639
+ userOpPolicies,
640
+ erc7739Policies: {
641
+ allowedERC7739Content: [],
642
+ erc1271Policies: []
643
+ },
644
+ actions,
645
+ permitERC4337Paymaster: true,
646
+ chainId
647
+ };
648
+ }
649
+ function getSmartSessionsModule(sessions) {
650
+ return (0, import_module_sdk.getSmartSessionsValidator)({
651
+ sessions,
652
+ useRegistry: true
653
+ });
654
+ }
655
+ function computePermissionId(session) {
656
+ return (0, import_module_sdk.getPermissionId)({ session });
657
+ }
658
+ async function getEnableDetails(sessions, account, publicClients, enableValidatorAddress) {
659
+ return (0, import_module_sdk.getEnableSessionDetails)({
660
+ sessions,
661
+ account: {
662
+ address: account.address,
663
+ type: account.type,
664
+ deployedOnChains: []
665
+ },
666
+ clients: publicClients,
667
+ enableValidatorAddress
668
+ });
669
+ }
670
+ function encodeUseSessionSignature(permissionId, signature) {
671
+ return (0, import_module_sdk.encodeSmartSessionSignature)({
672
+ mode: import_module_sdk.SmartSessionMode.USE,
673
+ permissionId,
674
+ signature
675
+ });
676
+ }
677
+ function encodeEnableSessionSignature(permissionId, signature, enableSessionData) {
678
+ return (0, import_module_sdk.encodeSmartSessionSignature)({
679
+ mode: import_module_sdk.SmartSessionMode.ENABLE,
680
+ permissionId,
681
+ signature,
682
+ enableSessionData
683
+ });
684
+ }
685
+ function getRemoveAction(permissionId) {
686
+ const action = (0, import_module_sdk.getRemoveSessionAction)({ permissionId });
687
+ const to = typeof action.target === "string" ? action.target : action.to;
688
+ if (!to) throw new SessionError("getRemoveSessionAction returned no target address");
689
+ let value;
690
+ if (typeof action.value === "bigint") {
691
+ value = action.value;
692
+ } else if (action.value != null) {
693
+ value = BigInt(String(action.value));
694
+ } else {
695
+ value = 0n;
696
+ }
697
+ const data = (typeof action.data === "string" ? action.data : action.callData) ?? "0x";
698
+ return { to, value, data };
699
+ }
700
+
701
+ // src/client.ts
702
+ function resolveAccount(key) {
703
+ if (typeof key === "string") {
704
+ return (0, import_accounts.privateKeyToAccount)(key);
705
+ }
706
+ return (0, import_accounts.mnemonicToAccount)(key.mnemonic, {
707
+ addressIndex: key.addressIndex ?? 0
708
+ });
709
+ }
710
+ var SmartAgentKitClient = class {
711
+ config;
712
+ publicClient;
713
+ walletClients;
714
+ sessions;
715
+ constructor(config) {
716
+ if (!config.moduleAddresses) {
717
+ const builtIn = DEPLOYMENTS[config.chain.id];
718
+ if (builtIn) {
719
+ config = { ...config, moduleAddresses: builtIn };
720
+ }
721
+ }
722
+ this.config = config;
723
+ this.publicClient = (0, import_viem4.createPublicClient)({
724
+ chain: config.chain,
725
+ transport: (0, import_viem4.http)(config.rpcUrl)
726
+ });
727
+ this.walletClients = /* @__PURE__ */ new Map();
728
+ this.sessions = /* @__PURE__ */ new Map();
729
+ }
730
+ // ─── Wallet Creation ──────────────────────────────────────────
731
+ /**
732
+ * Deploy a new policy-governed smart wallet for an AI agent.
733
+ *
734
+ * The wallet is a Safe smart account with ERC-7579 modules. A
735
+ * HookMultiPlexer is installed as the single hook, and sub-hooks
736
+ * (SpendingLimit, Allowlist, EmergencyPause) are routed through it.
737
+ *
738
+ * The deployment and policy initialization happen atomically in
739
+ * the first UserOperation.
740
+ */
741
+ async createWallet(params) {
742
+ try {
743
+ const policies = this.resolvePolicies(params);
744
+ const moduleAddresses = this.requireModuleAddresses(policies);
745
+ if (!params.ownerPrivateKey && !params.ownerMnemonic) {
746
+ throw new WalletCreationError(
747
+ "Provide either ownerPrivateKey or ownerMnemonic"
748
+ );
749
+ }
750
+ const ownerKey = params.ownerMnemonic ? { mnemonic: params.ownerMnemonic, addressIndex: params.addressIndex } : params.ownerPrivateKey;
751
+ const ownerAccount = resolveAccount(ownerKey);
752
+ if (ownerAccount.address.toLowerCase() !== params.owner.toLowerCase()) {
753
+ throw new WalletCreationError(
754
+ `Owner address mismatch: key derives ${ownerAccount.address} but params.owner is ${params.owner}`
755
+ );
756
+ }
757
+ const hookModule = (0, import_module_sdk3.getHookMultiPlexer)({
758
+ globalHooks: [],
759
+ valueHooks: [],
760
+ delegatecallHooks: [],
761
+ sigHooks: [],
762
+ targetHooks: []
763
+ });
764
+ const safeAccount = await (0, import_accounts2.toSafeSmartAccount)({
765
+ client: this.publicClient,
766
+ owners: [ownerAccount],
767
+ version: "1.4.1",
768
+ entryPoint: {
769
+ address: ENTRYPOINT_V07,
770
+ version: "0.7"
771
+ },
772
+ safe4337ModuleAddress: SAFE_7579_MODULE,
773
+ erc7579LaunchpadAddress: SAFE_7579_LAUNCHPAD,
774
+ hooks: [
775
+ {
776
+ address: hookModule.address,
777
+ context: hookModule.initData
778
+ }
779
+ ],
780
+ attesters: [RHINESTONE_ATTESTER],
781
+ attestersThreshold: ATTESTERS_THRESHOLD,
782
+ saltNonce: params.salt ?? 0n
783
+ });
784
+ const smartAccountClient = (0, import_clients.createSmartAccountClient)({
785
+ account: safeAccount,
786
+ chain: this.config.chain,
787
+ bundlerTransport: (0, import_viem4.http)(this.config.bundlerUrl),
788
+ client: this.publicClient
789
+ }).extend((0, import_erc7579.erc7579Actions)());
790
+ this.walletClients.set(safeAccount.address, smartAccountClient);
791
+ if (policies.length > 0 && moduleAddresses) {
792
+ await this.initializePolicies(
793
+ smartAccountClient,
794
+ policies,
795
+ moduleAddresses,
796
+ hookModule.address
797
+ );
798
+ }
799
+ return {
800
+ address: safeAccount.address,
801
+ owner: params.owner,
802
+ chain: this.config.chain,
803
+ isDeployed: policies.length > 0,
804
+ // Deployed if first UserOp was sent
805
+ policies: this.mapPoliciesToInstalled(policies, moduleAddresses),
806
+ sessions: []
807
+ };
808
+ } catch (error) {
809
+ if (error instanceof WalletCreationError) throw error;
810
+ throw new WalletCreationError(
811
+ error instanceof Error ? error.message : String(error),
812
+ error
813
+ );
814
+ }
815
+ }
816
+ /**
817
+ * Reconnect to an existing wallet for executing transactions.
818
+ * Accepts a private key or mnemonic credential.
819
+ */
820
+ async connectWallet(walletAddress, ownerKey) {
821
+ const ownerAccount = resolveAccount(ownerKey);
822
+ const safeAccount = await (0, import_accounts2.toSafeSmartAccount)({
823
+ client: this.publicClient,
824
+ owners: [ownerAccount],
825
+ version: "1.4.1",
826
+ entryPoint: {
827
+ address: ENTRYPOINT_V07,
828
+ version: "0.7"
829
+ },
830
+ safe4337ModuleAddress: SAFE_7579_MODULE,
831
+ erc7579LaunchpadAddress: SAFE_7579_LAUNCHPAD,
832
+ address: walletAddress,
833
+ attesters: [RHINESTONE_ATTESTER],
834
+ attestersThreshold: ATTESTERS_THRESHOLD
835
+ });
836
+ const smartAccountClient = (0, import_clients.createSmartAccountClient)({
837
+ account: safeAccount,
838
+ chain: this.config.chain,
839
+ bundlerTransport: (0, import_viem4.http)(this.config.bundlerUrl),
840
+ client: this.publicClient
841
+ }).extend((0, import_erc7579.erc7579Actions)());
842
+ this.walletClients.set(walletAddress, smartAccountClient);
843
+ }
844
+ async predictAddress(_owner, _salt) {
845
+ throw new Error("Not yet implemented \u2014 Sprint 3");
846
+ }
847
+ // ─── Policy Management ────────────────────────────────────────
848
+ async addPolicy(_wallet, _policy, _ownerPrivateKey) {
849
+ throw new Error("Not yet implemented \u2014 Sprint 3");
850
+ }
851
+ async removePolicy(_wallet, _moduleAddress, _ownerPrivateKey) {
852
+ throw new Error("Not yet implemented \u2014 Sprint 3");
853
+ }
854
+ async getPolicies(_walletAddress) {
855
+ throw new Error("Not yet implemented \u2014 Sprint 3");
856
+ }
857
+ // ─── Session Key Management ───────────────────────────────────
858
+ /**
859
+ * Create a session key for an AI agent.
860
+ *
861
+ * Generates a new ECDSA key pair and enables it as a session key on
862
+ * the smart account via Smart Sessions. The session is scoped to
863
+ * specific target contracts, function selectors, and time window.
864
+ *
865
+ * @returns The session key address, private key, and permission ID.
866
+ */
867
+ async createSession(wallet, params, ownerKey) {
868
+ const client = this.getWalletClient(wallet.address);
869
+ try {
870
+ const sessionPrivateKey = (0, import_accounts.generatePrivateKey)();
871
+ const sessionAccount = (0, import_accounts.privateKeyToAccount)(sessionPrivateKey);
872
+ const chainId = BigInt(this.config.chain.id);
873
+ const session = buildSession(
874
+ sessionAccount.address,
875
+ params,
876
+ chainId
877
+ );
878
+ const permissionId = computePermissionId(session);
879
+ const smartSessionsModule = getSmartSessionsModule();
880
+ try {
881
+ const isInstalled = await client.isModuleInstalled({
882
+ type: "validator",
883
+ address: smartSessionsModule.address,
884
+ context: "0x"
885
+ });
886
+ if (!isInstalled) {
887
+ await client.installModule({
888
+ type: "validator",
889
+ address: smartSessionsModule.address,
890
+ context: smartSessionsModule.initData
891
+ });
892
+ }
893
+ } catch {
894
+ await client.installModule({
895
+ type: "validator",
896
+ address: smartSessionsModule.address,
897
+ context: smartSessionsModule.initData
898
+ });
899
+ }
900
+ const enableDetails = await getEnableDetails(
901
+ [session],
902
+ { address: wallet.address, type: "safe" },
903
+ [this.publicClient]
904
+ );
905
+ const ownerAccount = resolveAccount(ownerKey);
906
+ const ownerSignature = await ownerAccount.signMessage({
907
+ message: { raw: enableDetails.permissionEnableHash }
908
+ });
909
+ const enableSig = encodeEnableSessionSignature(
910
+ enableDetails.permissionId,
911
+ ownerSignature,
912
+ enableDetails.enableSessionData
913
+ );
914
+ const walletSessions = this.sessions.get(wallet.address) ?? [];
915
+ walletSessions.push({
916
+ permissionId,
917
+ sessionKeyAddress: sessionAccount.address,
918
+ sessionKeyPrivateKey: sessionPrivateKey,
919
+ expiresAt: params.expiresAt,
920
+ actions: params.actions.map((a) => ({
921
+ target: a.target,
922
+ selector: a.selector
923
+ }))
924
+ });
925
+ this.sessions.set(wallet.address, walletSessions);
926
+ return {
927
+ sessionKey: sessionAccount.address,
928
+ privateKey: sessionPrivateKey,
929
+ permissionId
930
+ };
931
+ } catch (error) {
932
+ if (error instanceof SessionError) throw error;
933
+ throw new SessionError(
934
+ error instanceof Error ? error.message : String(error)
935
+ );
936
+ }
937
+ }
938
+ /**
939
+ * Revoke a session key, permanently disabling it.
940
+ */
941
+ async revokeSession(wallet, permissionId, _ownerKey) {
942
+ const client = this.getWalletClient(wallet.address);
943
+ try {
944
+ const removeAction = getRemoveAction(permissionId);
945
+ await client.sendTransaction({
946
+ calls: [removeAction]
947
+ });
948
+ const walletSessions = this.sessions.get(wallet.address) ?? [];
949
+ this.sessions.set(
950
+ wallet.address,
951
+ walletSessions.filter((s) => s.permissionId !== permissionId)
952
+ );
953
+ } catch (error) {
954
+ throw new SessionError(
955
+ error instanceof Error ? error.message : String(error)
956
+ );
957
+ }
958
+ }
959
+ /**
960
+ * Get active sessions for a wallet.
961
+ */
962
+ getActiveSessions(walletAddress) {
963
+ const now = Math.floor(Date.now() / 1e3);
964
+ const walletSessions = this.sessions.get(walletAddress) ?? [];
965
+ return walletSessions.filter((s) => s.expiresAt > now).map((s) => ({
966
+ sessionKey: s.sessionKeyAddress,
967
+ actions: s.actions.map((a) => ({ target: a.target, selector: a.selector })),
968
+ expiresAt: s.expiresAt,
969
+ isActive: true
970
+ }));
971
+ }
972
+ // ─── Transaction Execution ────────────────────────────────────
973
+ /**
974
+ * Execute a single transaction from the agent wallet.
975
+ * The transaction is submitted as a UserOperation through the bundler.
976
+ * Hooks (spending limits, allowlist, pause) are enforced on-chain.
977
+ */
978
+ async execute(wallet, params) {
979
+ const client = this.getWalletClient(wallet.address);
980
+ try {
981
+ const hash = await client.sendTransaction({
982
+ calls: [
983
+ {
984
+ to: params.target,
985
+ value: params.value ?? 0n,
986
+ data: params.data ?? "0x"
987
+ }
988
+ ]
989
+ });
990
+ return hash;
991
+ } catch (error) {
992
+ throw new ExecutionError(
993
+ error instanceof Error ? error.message : String(error),
994
+ error
995
+ );
996
+ }
997
+ }
998
+ /**
999
+ * Execute a batch of transactions atomically from the agent wallet.
1000
+ * All calls are encoded into a single UserOperation with batch mode.
1001
+ */
1002
+ async executeBatch(wallet, params) {
1003
+ const client = this.getWalletClient(wallet.address);
1004
+ try {
1005
+ const calls = params.calls.map((call) => ({
1006
+ to: call.target,
1007
+ value: call.value ?? 0n,
1008
+ data: call.data ?? "0x"
1009
+ }));
1010
+ const hash = await client.sendTransaction({
1011
+ calls
1012
+ });
1013
+ return hash;
1014
+ } catch (error) {
1015
+ throw new ExecutionError(
1016
+ error instanceof Error ? error.message : String(error),
1017
+ error
1018
+ );
1019
+ }
1020
+ }
1021
+ // ─── Query Functions ──────────────────────────────────────────
1022
+ /**
1023
+ * Get the remaining spending allowance for a token on a wallet.
1024
+ * Reads directly from the SpendingLimitHook contract.
1025
+ */
1026
+ async getRemainingAllowance(walletAddress, token) {
1027
+ const moduleAddresses = this.config.moduleAddresses;
1028
+ if (!moduleAddresses) {
1029
+ throw new PolicyConfigError(
1030
+ "moduleAddresses not configured \u2014 cannot query SpendingLimitHook"
1031
+ );
1032
+ }
1033
+ const result = await this.publicClient.readContract({
1034
+ address: moduleAddresses.spendingLimitHook,
1035
+ abi: SPENDING_LIMIT_HOOK_ABI,
1036
+ functionName: "getRemainingAllowance",
1037
+ args: [walletAddress, token]
1038
+ });
1039
+ return result;
1040
+ }
1041
+ /**
1042
+ * Check if a wallet is currently paused.
1043
+ * Reads directly from the EmergencyPauseHook contract.
1044
+ */
1045
+ async isPaused(walletAddress) {
1046
+ const moduleAddresses = this.config.moduleAddresses;
1047
+ if (!moduleAddresses) {
1048
+ throw new PolicyConfigError(
1049
+ "moduleAddresses not configured \u2014 cannot query EmergencyPauseHook"
1050
+ );
1051
+ }
1052
+ const result = await this.publicClient.readContract({
1053
+ address: moduleAddresses.emergencyPauseHook,
1054
+ abi: EMERGENCY_PAUSE_HOOK_ABI,
1055
+ functionName: "isPaused",
1056
+ args: [walletAddress]
1057
+ });
1058
+ return result;
1059
+ }
1060
+ /**
1061
+ * Get the native ETH balance of a wallet.
1062
+ */
1063
+ async getBalances(walletAddress) {
1064
+ const eth = await this.publicClient.getBalance({
1065
+ address: walletAddress
1066
+ });
1067
+ return { eth, tokens: [] };
1068
+ }
1069
+ // ─── Pause / Unpause (Guardian Actions) ───────────────────────
1070
+ /**
1071
+ * Pause a wallet. Must be called by the configured guardian.
1072
+ * This is NOT a UserOp — it's a direct call to the EmergencyPauseHook.
1073
+ */
1074
+ async pause(walletAddress, guardianKey) {
1075
+ const moduleAddresses = this.config.moduleAddresses;
1076
+ if (!moduleAddresses) {
1077
+ throw new PolicyConfigError("moduleAddresses not configured");
1078
+ }
1079
+ const guardian = resolveAccount(guardianKey);
1080
+ const { request } = await this.publicClient.simulateContract({
1081
+ account: guardian,
1082
+ address: moduleAddresses.emergencyPauseHook,
1083
+ abi: EMERGENCY_PAUSE_HOOK_ABI,
1084
+ functionName: "pause",
1085
+ args: [walletAddress]
1086
+ });
1087
+ const guardianClient = (0, import_viem4.createWalletClient)({
1088
+ account: guardian,
1089
+ chain: this.config.chain,
1090
+ transport: (0, import_viem4.http)(this.config.rpcUrl)
1091
+ });
1092
+ return guardianClient.writeContract(request);
1093
+ }
1094
+ /**
1095
+ * Unpause a wallet. Must be called by the configured guardian.
1096
+ */
1097
+ async unpause(walletAddress, guardianKey) {
1098
+ const moduleAddresses = this.config.moduleAddresses;
1099
+ if (!moduleAddresses) {
1100
+ throw new PolicyConfigError("moduleAddresses not configured");
1101
+ }
1102
+ const guardian = resolveAccount(guardianKey);
1103
+ const { request } = await this.publicClient.simulateContract({
1104
+ account: guardian,
1105
+ address: moduleAddresses.emergencyPauseHook,
1106
+ abi: EMERGENCY_PAUSE_HOOK_ABI,
1107
+ functionName: "unpause",
1108
+ args: [walletAddress]
1109
+ });
1110
+ const guardianClient = (0, import_viem4.createWalletClient)({
1111
+ account: guardian,
1112
+ chain: this.config.chain,
1113
+ transport: (0, import_viem4.http)(this.config.rpcUrl)
1114
+ });
1115
+ return guardianClient.writeContract(request);
1116
+ }
1117
+ // ─── Private Helpers ──────────────────────────────────────────
1118
+ resolvePolicies(params) {
1119
+ if (params.preset) {
1120
+ return PRESETS[params.preset](params.owner, params.presetParams);
1121
+ }
1122
+ return params.policies ?? [];
1123
+ }
1124
+ requireModuleAddresses(policies) {
1125
+ if (policies.length === 0) return void 0;
1126
+ const moduleAddresses = this.config.moduleAddresses;
1127
+ if (!moduleAddresses) {
1128
+ throw new WalletCreationError(
1129
+ "moduleAddresses must be configured when policies are specified. Provide the deployed hook contract addresses in SmartAgentKitConfig."
1130
+ );
1131
+ }
1132
+ for (const policy of policies) {
1133
+ switch (policy.type) {
1134
+ case "spending-limit":
1135
+ if (!moduleAddresses.spendingLimitHook) {
1136
+ throw new WalletCreationError(
1137
+ "spendingLimitHook address required for spending-limit policy"
1138
+ );
1139
+ }
1140
+ break;
1141
+ case "allowlist":
1142
+ if (!moduleAddresses.allowlistHook) {
1143
+ throw new WalletCreationError(
1144
+ "allowlistHook address required for allowlist policy"
1145
+ );
1146
+ }
1147
+ break;
1148
+ case "emergency-pause":
1149
+ if (!moduleAddresses.emergencyPauseHook) {
1150
+ throw new WalletCreationError(
1151
+ "emergencyPauseHook address required for emergency-pause policy"
1152
+ );
1153
+ }
1154
+ break;
1155
+ case "automation":
1156
+ throw new PolicyConfigError(
1157
+ "automation policies are not yet supported"
1158
+ );
1159
+ }
1160
+ }
1161
+ return moduleAddresses;
1162
+ }
1163
+ /**
1164
+ * Build and send the first UserOp that initializes all sub-hooks
1165
+ * and adds them to the HookMultiPlexer.
1166
+ *
1167
+ * This batch includes for each sub-hook:
1168
+ * 1. onInstall(initData) — initialize the sub-hook for this account
1169
+ * 2. setTrustedForwarder(hookMultiPlexer) — so sub-hooks resolve the
1170
+ * correct account when called through the multiplexer
1171
+ * 3. addHook(hookAddress, GLOBAL) on HookMultiPlexer — register the
1172
+ * sub-hook for all transactions
1173
+ */
1174
+ async initializePolicies(client, policies, moduleAddresses, hookMultiPlexerAddress) {
1175
+ const calls = [];
1176
+ for (const policy of policies) {
1177
+ switch (policy.type) {
1178
+ case "spending-limit": {
1179
+ const hookAddress = moduleAddresses.spendingLimitHook;
1180
+ const initData = encodeSpendingLimitInitData(policy);
1181
+ this.pushSubHookInitCalls(
1182
+ calls,
1183
+ hookAddress,
1184
+ initData,
1185
+ hookMultiPlexerAddress
1186
+ );
1187
+ break;
1188
+ }
1189
+ case "allowlist": {
1190
+ const hookAddress = moduleAddresses.allowlistHook;
1191
+ const initData = encodeAllowlistInitData(policy);
1192
+ this.pushSubHookInitCalls(
1193
+ calls,
1194
+ hookAddress,
1195
+ initData,
1196
+ hookMultiPlexerAddress
1197
+ );
1198
+ break;
1199
+ }
1200
+ case "emergency-pause": {
1201
+ const hookAddress = moduleAddresses.emergencyPauseHook;
1202
+ const initData = encodeEmergencyPauseInitData(policy);
1203
+ this.pushSubHookInitCalls(
1204
+ calls,
1205
+ hookAddress,
1206
+ initData,
1207
+ hookMultiPlexerAddress
1208
+ );
1209
+ break;
1210
+ }
1211
+ case "automation":
1212
+ break;
1213
+ }
1214
+ }
1215
+ if (calls.length === 0) return;
1216
+ await client.sendTransaction({
1217
+ calls
1218
+ });
1219
+ }
1220
+ /**
1221
+ * Push the 3 calls needed to initialize a sub-hook:
1222
+ * 1. onInstall(initData) on the sub-hook
1223
+ * 2. setTrustedForwarder(multiplexer) on the sub-hook
1224
+ * 3. addHook(hookAddr, GLOBAL) on the HookMultiPlexer
1225
+ */
1226
+ pushSubHookInitCalls(calls, hookAddress, initData, hookMultiPlexerAddress) {
1227
+ calls.push({
1228
+ to: hookAddress,
1229
+ value: 0n,
1230
+ data: (0, import_viem4.encodeFunctionData)({
1231
+ abi: MODULE_ONINSTALL_ABI,
1232
+ functionName: "onInstall",
1233
+ args: [initData]
1234
+ })
1235
+ });
1236
+ calls.push({
1237
+ to: hookAddress,
1238
+ value: 0n,
1239
+ data: (0, import_viem4.encodeFunctionData)({
1240
+ abi: SET_TRUSTED_FORWARDER_ABI,
1241
+ functionName: "setTrustedForwarder",
1242
+ args: [hookMultiPlexerAddress]
1243
+ })
1244
+ });
1245
+ calls.push({
1246
+ to: hookMultiPlexerAddress,
1247
+ value: 0n,
1248
+ data: (0, import_viem4.encodeFunctionData)({
1249
+ abi: HOOK_MULTIPLEXER_ABI,
1250
+ functionName: "addHook",
1251
+ args: [hookAddress, HOOK_TYPE_GLOBAL]
1252
+ })
1253
+ });
1254
+ }
1255
+ mapPoliciesToInstalled(policies, moduleAddresses) {
1256
+ if (!moduleAddresses) return [];
1257
+ return policies.map((policy) => {
1258
+ switch (policy.type) {
1259
+ case "spending-limit":
1260
+ return {
1261
+ moduleAddress: moduleAddresses.spendingLimitHook,
1262
+ moduleType: 4,
1263
+ name: "SpendingLimitHook",
1264
+ config: policy
1265
+ };
1266
+ case "allowlist":
1267
+ return {
1268
+ moduleAddress: moduleAddresses.allowlistHook,
1269
+ moduleType: 4,
1270
+ name: "AllowlistHook",
1271
+ config: policy
1272
+ };
1273
+ case "emergency-pause":
1274
+ return {
1275
+ moduleAddress: moduleAddresses.emergencyPauseHook,
1276
+ moduleType: 4,
1277
+ name: "EmergencyPauseHook",
1278
+ config: policy
1279
+ };
1280
+ case "automation":
1281
+ return {
1282
+ moduleAddress: moduleAddresses.automationExecutor ?? "0x0000000000000000000000000000000000000000",
1283
+ moduleType: 2,
1284
+ name: "AutomationExecutor",
1285
+ config: policy
1286
+ };
1287
+ default: {
1288
+ const _exhaustive = policy;
1289
+ return {
1290
+ moduleAddress: "0x0000000000000000000000000000000000000000",
1291
+ moduleType: 0,
1292
+ name: "Unknown",
1293
+ config: _exhaustive
1294
+ };
1295
+ }
1296
+ }
1297
+ });
1298
+ }
1299
+ getWalletClient(walletAddress) {
1300
+ const client = this.walletClients.get(walletAddress);
1301
+ if (!client) {
1302
+ throw new ExecutionError(
1303
+ `No client found for wallet ${walletAddress}. Call createWallet() or connectWallet() first.`
1304
+ );
1305
+ }
1306
+ return client;
1307
+ }
1308
+ };
1309
+ // Annotate the CommonJS export names for ESM import in node:
1310
+ 0 && (module.exports = {
1311
+ ALLOWLIST_HOOK_ABI,
1312
+ DEPLOYMENTS,
1313
+ EMERGENCY_PAUSE_HOOK_ABI,
1314
+ ENTRYPOINT_V07,
1315
+ ExecutionError,
1316
+ HOOK_MULTIPLEXER_ABI,
1317
+ HOOK_MULTIPLEXER_ADDRESS,
1318
+ HOOK_TYPE_GLOBAL,
1319
+ MODULE_ADDRESSES,
1320
+ MODULE_TYPE_EXECUTOR,
1321
+ MODULE_TYPE_FALLBACK,
1322
+ MODULE_TYPE_HOOK,
1323
+ MODULE_TYPE_VALIDATOR,
1324
+ NATIVE_TOKEN,
1325
+ OWNABLE_VALIDATOR_ADDRESS,
1326
+ PRESETS,
1327
+ PolicyConfigError,
1328
+ RHINESTONE_ATTESTER,
1329
+ SAFE_7579_LAUNCHPAD,
1330
+ SAFE_7579_MODULE,
1331
+ SMART_SESSIONS_ADDRESS,
1332
+ SPENDING_LIMIT_HOOK_ABI,
1333
+ SessionError,
1334
+ SmartAgentKitClient,
1335
+ SmartAgentKitError,
1336
+ SmartSessionMode,
1337
+ SpendingLimitExceededError,
1338
+ WINDOW_1_DAY,
1339
+ WINDOW_1_HOUR,
1340
+ WINDOW_1_WEEK,
1341
+ WalletCreationError,
1342
+ WalletPausedError,
1343
+ buildSession,
1344
+ computePermissionId,
1345
+ encodeAllowlistInitData,
1346
+ encodeEmergencyPauseInitData,
1347
+ encodeEnableSessionSignature,
1348
+ encodePolicyInitData,
1349
+ encodeSpendingLimitInitData,
1350
+ encodeUseSessionSignature,
1351
+ getRemoveSessionAction,
1352
+ getSmartSessionsModule
1353
+ });
1354
+ //# sourceMappingURL=index.js.map