-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathSafeAccountV0_3_0.ts
More file actions
469 lines (444 loc) · 16.8 KB
/
Copy pathSafeAccountV0_3_0.ts
File metadata and controls
469 lines (444 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import type {Bundler} from "src/Bundler";
import {ENTRYPOINT_V7} from "src/constants";
import type {SignContext, Signer as AkSigner} from "src/signer/types";
import type {JsonRpcNode, Transport} from "src/transport";
import type {MetaTransaction, OnChainIdentifierParamsType, StateOverrideSet, UserOperationV7,} from "../../types";
import {SafeAccount} from "./SafeAccount";
import {SafeMultiChainSigAccountV1} from "./SafeMultiChainSigAccount";
import type {
CreateUserOperationV7Overrides,
InitCodeOverrides,
SafeAccountSingleton,
SafeSignatureOptions,
SafeUserOperationTypedDataDomain,
SafeUserOperationV7TypedMessageValue,
Signer,
SignerSignaturePair,
} from "./types";
/**
* Safe smart account implementation for EntryPoint v0.7.
* Provides methods to create, sign, and send ERC-4337 UserOperations
* using Safe's modular smart account architecture with the v0.7 EntryPoint.
*
* @example
* // Create a new account (not yet deployed on-chain)
* const smartAccount = SafeAccountV0_3_0.initializeNewAccount([ownerAddress]);
*
* // Or connect to an existing deployed account
* const smartAccount = new SafeAccountV0_3_0(existingAccountAddress);
*/
export class SafeAccountV0_3_0 extends SafeAccount {
static readonly DEFAULT_ENTRYPOINT_ADDRESS = ENTRYPOINT_V7;
static readonly DEFAULT_SAFE_4337_MODULE_ADDRESS = "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226";
static readonly DEFAULT_SAFE_MODULE_SETUP_ADDRESS = "0x2dd68b007B46fBe91B9A7c3EDa5A7a1063cB5b47";
/**
* Create a SafeAccountV0_3_0 instance for an existing deployed account.
* For new (undeployed) accounts, use the static `initializeNewAccount` method instead.
*
* @param accountAddress - The on-chain address of the Safe account
* @param overrides - Override default module, EntryPoint, and singleton addresses
*/
constructor(
accountAddress: string,
overrides: {
safe4337ModuleAddress?: string;
entrypointAddress?: string;
onChainIdentifierParams?: OnChainIdentifierParamsType;
onChainIdentifier?: string;
safeAccountSingleton?: SafeAccountSingleton;
} = {},
) {
const safe4337ModuleAddress =
overrides.safe4337ModuleAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_4337_MODULE_ADDRESS;
const entrypointAddress =
overrides.entrypointAddress ?? SafeAccountV0_3_0.DEFAULT_ENTRYPOINT_ADDRESS;
super(accountAddress, safe4337ModuleAddress, entrypointAddress, {
onChainIdentifierParams: overrides.onChainIdentifierParams,
onChainIdentifier: overrides.onChainIdentifier,
safeAccountSingleton: overrides.safeAccountSingleton,
});
}
/**
* Calculate the counterfactual account address from the initial owner signers.
* Does not deploy the account.
*
* @param owners - Array of owner signers (ECDSA addresses or WebAuthn public keys)
* @param overrides - Override default initialization values
* @returns The deterministic account address
*/
public static createAccountAddress(owners: Signer[], overrides: InitCodeOverrides = {}): string {
const [accountAddress, ,] = SafeAccount.createAccountAddressAndFactoryAddressAndData(
owners,
overrides,
overrides.safe4337ModuleAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_4337_MODULE_ADDRESS,
overrides.safeModuleSetupAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_MODULE_SETUP_ADDRESS,
);
return accountAddress;
}
/**
* Create and initialize a new SafeAccountV0_3_0 from its initial owners.
* The account address is deterministically computed but not yet deployed on-chain.
* The first UserOperation sent will deploy it automatically via factory data.
*
* Instantiates through `new this(...)`, so subclasses calling this
* factory (directly or via `super`) get an instance of the subclass,
* not a plain SafeAccountV0_3_0.
*
* @param owners - Array of owner signers (at least one required)
* @param overrides - Override default initialization values
* @returns An instance of the calling class with factory data set for deployment
*
* @example
* const smartAccount = SafeAccountV0_3_0.initializeNewAccount(["0xOwnerAddress"]);
*/
public static initializeNewAccount<T extends typeof SafeAccountV0_3_0>(
this: T,
owners: Signer[],
overrides: InitCodeOverrides = {},
): InstanceType<T> {
let isInitWebAuthn = false;
let x = 0n;
let y = 0n;
for (const owner of owners) {
if (typeof owner !== "string") {
if (isInitWebAuthn) {
throw new RangeError("Only one Webauthn signer is allowed during initialization");
}
if (owners.indexOf(owner) !== 0) {
throw new RangeError("Webauthn owner has to be the first owner for an init transaction.");
}
isInitWebAuthn = true;
x = owner.x;
y = owner.y;
}
}
const [accountAddress, factoryAddress, factoryData] =
SafeAccount.createAccountAddressAndFactoryAddressAndData(
owners,
overrides,
overrides.safe4337ModuleAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_4337_MODULE_ADDRESS,
overrides.safeModuleSetupAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_MODULE_SETUP_ADDRESS,
);
// biome-ignore lint/complexity/noThisInStatic: polymorphic factory; subclasses must get their own type back
const safe: SafeAccountV0_3_0 = new this(accountAddress, {
safe4337ModuleAddress: overrides.safe4337ModuleAddress,
entrypointAddress: overrides.entrypointAddress,
onChainIdentifierParams: overrides.onChainIdentifierParams,
onChainIdentifier: overrides.onChainIdentifier,
safeAccountSingleton: overrides.safeAccountSingleton,
});
safe.factoryAddress = factoryAddress;
safe.factoryData = factoryData;
if (isInitWebAuthn) {
safe.isInitWebAuthn = true;
safe.x = x;
safe.y = y;
}
return safe as InstanceType<T>;
}
/**
* Compute the EIP-712 hash of a UserOperation for Safe signature verification.
*
* @param useroperation - UserOperation to hash
* @param chainId - Target chain ID
* @param overrides - Override validAfter, validUntil, entrypoint, and module addresses
* @returns The EIP-712 hash as a hex string
*/
public static getUserOperationEip712Hash(
useroperation: UserOperationV7,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): string {
const validAfter = overrides.validAfter ?? 0n;
const validUntil = overrides.validUntil ?? 0n;
const entrypointAddress =
overrides.entrypointAddress ?? SafeAccountV0_3_0.DEFAULT_ENTRYPOINT_ADDRESS;
const safe4337ModuleAddress =
overrides.safe4337ModuleAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_4337_MODULE_ADDRESS;
return SafeAccount.getUserOperationEip712Hash(useroperation, chainId, {
validAfter,
validUntil,
entrypointAddress,
safe4337ModuleAddress,
});
}
/**
* Get the EIP-712 typed data components for a UserOperation.
* Useful for signing with external signers that need domain, types, and message separately.
*
* @param useroperation - UserOperation to get typed data for
* @param chainId - Target chain ID
* @param overrides - Override validAfter, validUntil, entrypoint, and module addresses
* @returns Object with domain, types, and messageValue for EIP-712 signing
*/
public static getUserOperationEip712Data(
useroperation: UserOperationV7,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): {
domain: SafeUserOperationTypedDataDomain;
types: Record<string, { name: string; type: string }[]>;
messageValue: SafeUserOperationV7TypedMessageValue;
} {
const validAfter = overrides.validAfter ?? 0n;
const validUntil = overrides.validUntil ?? 0n;
const entrypointAddress =
overrides.entrypointAddress ?? SafeAccountV0_3_0.DEFAULT_ENTRYPOINT_ADDRESS;
const safe4337ModuleAddress =
overrides.safe4337ModuleAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_4337_MODULE_ADDRESS;
return SafeAccount.getUserOperationEip712Data(useroperation, chainId, {
validAfter,
validUntil,
entrypointAddress,
safe4337ModuleAddress,
});
}
/**
* Build the Safe initializer calldata for the account setup transaction.
* Encodes the owners, threshold, module setup, and optional WebAuthn configuration.
*
* @param owners - Array of owner signers (ECDSA addresses or WebAuthn public keys)
* @param threshold - Number of required signatures for transaction approval
* @param overrides - Override default module, multisend, and WebAuthn addresses
* @returns The encoded initializer calldata hex string
*/
public static createInitializerCallData(
owners: Signer[],
threshold: number,
overrides: {
safe4337ModuleAddress?: string;
safeModuleSetupAddress?: string;
multisendContractAddress?: string;
webAuthnSharedSigner?: string;
eip7212WebAuthnPrecompileVerifierForSharedSigner?: string;
eip7212WebAuthnContractVerifierForSharedSigner?: string;
} = {},
): string {
const safe4337ModuleAddress =
overrides.safe4337ModuleAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_4337_MODULE_ADDRESS;
const safeModuleSetupAddress =
overrides.safeModuleSetupAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_MODULE_SETUP_ADDRESS;
return SafeAccount.createBaseInitializerCallData(
owners,
threshold,
safe4337ModuleAddress,
safeModuleSetupAddress,
overrides.multisendContractAddress,
overrides.webAuthnSharedSigner,
overrides.eip7212WebAuthnPrecompileVerifierForSharedSigner,
overrides.eip7212WebAuthnContractVerifierForSharedSigner,
);
}
/**
* Create the factory address and encoded factory data for deploying a new Safe account.
*
* @param owners - Array of owner signers (ECDSA addresses or WebAuthn public keys)
* @param overrides - Override default initialization values
* @returns A tuple of [factoryAddress, factoryData]
*/
public static createFactoryAddressAndData(
owners: Signer[],
overrides: InitCodeOverrides = {},
): [string, string] {
return SafeAccount.createFactoryAddressAndData(
owners,
overrides,
overrides.safe4337ModuleAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_4337_MODULE_ADDRESS,
overrides.safeModuleSetupAddress ?? SafeAccountV0_3_0.DEFAULT_SAFE_MODULE_SETUP_ADDRESS,
);
}
/**
* Create a complete UserOperation ready for signing.
* Automatically determines the nonce, fetches gas prices, estimates gas limits,
* and encodes the transactions into calldata. All values can be overridden.
*
* @param transactions - Array of MetaTransactions to execute
* @param providerRpc - Ethereum JSON-RPC node URL (for nonce and gas prices)
* @param bundlerRpc - Bundler RPC URL (for gas estimation)
* @param overrides - Override any auto-determined values
* @returns The unsigned UserOperation (UserOperationV7) ready to be signed
*
* @example
* const userOp = await smartAccount.createUserOperation(
* [{ to: recipientAddress, value: 1000000000000000n, data: "0x" }],
* nodeRpcUrl,
* bundlerRpcUrl,
* );
*/
public async createUserOperation(
transactions: MetaTransaction[],
providerRpc?: string | Transport | JsonRpcNode,
bundlerRpc?: string | Transport | Bundler,
overrides: CreateUserOperationV7Overrides = {},
): Promise<UserOperationV7> {
const [userOperation, factoryAddress, factoryData] =
await this.createBaseUserOperationAndFactoryAddressAndFactoryData(
transactions,
false,
providerRpc,
bundlerRpc,
overrides,
);
const userOperationV7: UserOperationV7 = {
...userOperation,
factory: factoryAddress,
factoryData,
paymaster: null,
paymasterVerificationGasLimit: null,
paymasterPostOpGasLimit: null,
paymasterData: null,
};
return userOperationV7;
}
/**
* Estimate gas limits for a UserOperation using the bundler.
*
* @param userOperation - The UserOperation to estimate gas for
* @param bundlerRpc - Bundler RPC URL
* @param overrides - State overrides, dummy signatures, and WebAuthn configuration
* @returns A tuple of [preVerificationGas, verificationGasLimit, callGasLimit]
*/
public async estimateUserOperationGas(
userOperation: UserOperationV7,
bundlerRpc: string | Transport | Bundler,
overrides: {
stateOverrideSet?: StateOverrideSet;
dummySignerSignaturePairs?: SignerSignaturePair[];
expectedSigners?: Signer[];
webAuthnSharedSigner?: string;
webAuthnSignerFactory?: string;
webAuthnSignerSingleton?: string;
webAuthnSignerProxyCreationCode?: string;
eip7212WebAuthnPrecompileVerifier?: string;
eip7212WebAuthnContractVerifier?: string;
} = {},
): Promise<[bigint, bigint, bigint]> {
return this.baseEstimateUserOperationGas(userOperation, bundlerRpc, overrides);
}
/**
* Sign a UserOperation using one or more private keys via EIP-712 typed data signing.
*
* @param useroperation - The UserOperation to sign
* @param privateKeys - Array of private keys for the signers
* @param chainId - The target chain ID
* @param options - {@link SafeSignatureOptions} — timing, multi-chain encoding, module address
* @returns The formatted signature string ready to set on the UserOperation
*
* @example
* const signature = smartAccount.signUserOperation(userOp, [privateKey], 1n);
* userOp.signature = signature;
*/
public signUserOperation(
useroperation: UserOperationV7,
privateKeys: string[],
chainId: bigint,
options: SafeSignatureOptions = {},
): string {
return SafeAccount.baseSignSingleUserOperation(
useroperation,
privateKeys,
chainId,
this.entrypointAddress,
this.safe4337ModuleAddress,
options,
);
}
/**
* Sign a UserOperation with one or more {@link ExternalSigner} instances
* (viem, ethers, hardware wallets, MPC, HSMs). Each signer declares its
* capabilities (`signHash`, `signTypedData`, or both) and the account picks
* the best match; incompatible signers fail offline with an actionable error.
*
* For a raw private-key string, use the sync {@link signUserOperation}
* instead or wrap with `fromPrivateKey(pk)`. Prebuilt adapters: `fromViem`,
* `fromEthersWallet`, `fromViemWalletClient`, `fromPrivateKey`.
*
* @example
* import { fromViem } from "abstractionkit";
* import { privateKeyToAccount } from "viem/accounts";
*
* const signer = fromViem(privateKeyToAccount(pk));
* userOp.signature = await account.signUserOperationWithSigners(userOp, [signer], chainId);
*
* @param useroperation - UserOperation to sign
* @param signers - one ExternalSigner per owner (any order)
* @param chainId - target chain ID
* @param options - {@link SafeSignatureOptions} — timing, multi-chain encoding, module address
* @returns Promise resolving to the formatted signature string
*/
public signUserOperationWithSigners(
useroperation: UserOperationV7,
signers: ReadonlyArray<AkSigner>,
chainId: bigint,
options: SafeSignatureOptions = {}
): Promise<string> {
const context: SignContext<UserOperationV7> = {
userOperation: useroperation,
chainId,
entryPoint: this.entrypointAddress,
};
return SafeAccount.baseSignUserOperationWithSigners(useroperation, signers, chainId, {
entrypointAddress: this.entrypointAddress,
safe4337ModuleAddress: this.safe4337ModuleAddress,
context,
options,
});
}
/**
* Create the MetaTransactions that migrate this DEPLOYED Safe from EntryPoint
* v0.7 (this account's `Safe4337Module`) to EntryPoint v0.9
* (`SafeMultiChainSigAccountV1`'s `Safe4337MultiChainSignatureModule`).
*
* The returned batch must be sent as a UserOperation FROM THIS v0.7 account
* (it is validated/executed by the v0.7 module on the v0.7 EntryPoint). After
* it lands, attach the same account address to `SafeMultiChainSigAccountV1` to
* operate on EntryPoint v0.9. Both modules are stateless, so no storage
* clearing is required. See {@link createModuleMigrationMetaTransactions}.
*
* @param nodeRpcUrl - The JSON-RPC API url for the target chain
* @param overrides - override the source/target module addresses or module lookup
* @returns a promise of [disableV07, enableV09, setFallbackHandler] MetaTransactions
*/
public async createMigrateToSafeMultiChainSigAccountV1MetaTransactions(
nodeRpcUrl: string | Transport | JsonRpcNode,
overrides: {
safeV07ModuleAddress?: string;
safeV09ModuleAddress?: string;
prevModuleAddress?: string;
modulesStart?: string;
modulesPageSize?: bigint;
skipPreflight?: boolean;
} = {},
): Promise<MetaTransaction[]> {
const moduleV07Address = overrides.safeV07ModuleAddress ?? this.safe4337ModuleAddress;
const moduleV09Address =
overrides.safeV09ModuleAddress ??
SafeMultiChainSigAccountV1.DEFAULT_SAFE_4337_MODULE_ADDRESS;
return this.createModuleMigrationMetaTransactions(
nodeRpcUrl,
moduleV07Address,
moduleV09Address,
{
prevModuleAddress: overrides.prevModuleAddress,
modulesStart: overrides.modulesStart,
modulesPageSize: overrides.modulesPageSize,
skipPreflight: overrides.skipPreflight,
},
);
}
}
/**
* Alias for {@link SafeAccountV0_3_0} representing Safe v1.4.1 singleton with module v0.3.0.
* Uses the same defaults and behavior as SafeAccountV0_3_0.
*/
export class SafeAccountV1_4_1_M_0_3_0 extends SafeAccountV0_3_0 {}