-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathSafeAccount.ts
More file actions
3546 lines (3316 loc) · 125 KB
/
Copy pathSafeAccount.ts
File metadata and controls
3546 lines (3316 loc) · 125 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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
concat,
dataLength,
decodeAbiParameters,
encodeAbiParameters,
getAddress,
hashTypedData,
hexlify,
keccak256,
privateKeyToAddress,
signHash,
solidityPacked,
solidityPackedKeccak256,
toUtf8Bytes,
} from "src/ethereUtils";
import {Bundler} from "src/Bundler";
import {AbstractionKitError, ensureError} from "src/errors";
import {SafeAccountFactory} from "src/factory/SafeAccountFactory";
import {invokeSigner, pickScheme} from "src/signer/negotiate";
import type {ExternalSigner, SigningScheme, TypedData} from "src/signer/types";
import {JsonRpcNode, type Transport} from "src/transport";
import {
BaseUserOperationDummyValues,
EIP712_SAFE_OPERATION_PRIMARY_TYPE,
EIP712_SAFE_OPERATION_V6_TYPE,
EIP712_SAFE_OPERATION_V7_TYPE,
ENTRYPOINT_V6,
ENTRYPOINT_V7,
ENTRYPOINT_V9,
SAFE_FALLBACK_HANDLER_STORAGE_SLOT,
Safe_L2_V1_4_1,
ZeroAddress,
} from "../../constants";
import {
type AbiInputValue,
type BaseUserOperation,
type MetaTransaction,
type OnChainIdentifierParamsType,
Operation,
type StateOverrideSet,
type TenderlySimulationResult,
type UserOperationV6,
type UserOperationV7,
type UserOperationV9,
} from "../../types";
import {createCallData, fetchAccountNonce, getFunctionSelector, handlefetchGasPrice,} from "../../utils";
import {
simulateSenderCallDataWithTenderly,
simulateSenderCallDataWithTenderlyAndCreateShareLink,
} from "../../utilsTenderly";
import {SendUseroperationResponse} from "../SendUseroperationResponse";
import {SmartAccount} from "../SmartAccount";
import {decodeMultiSendCallData, encodeMultiSendCallData} from "./multisend";
import {
getSafeMessageEip712Data,
type SafeMessageTypedDataDomain,
type SafeMessageTypedMessageValue,
} from "./safeMessage";
import {
type BaseInitOverrides,
type CreateBaseUserOperationOverrides,
EOADummySignerSignaturePair,
type SafeAccountSingleton,
SafeModuleExecutorFunctionSelector,
type SafeSignatureOptions,
type SafeUserOperationTypedDataDomain,
type SafeUserOperationV6TypedMessageValue,
type SafeUserOperationV7TypedMessageValue,
type SafeUserOperationV9TypedMessageValue,
type Signer,
type SignerSignaturePair,
WebauthnDummySignerSignaturePair,
type WebauthnPublicKey,
type WebauthnSignatureData,
type WebAuthnSignatureOverrides,
} from "./types";
/**
* Base implementation shared by all Safe-account variants.
*
* Provides the core logic for Safe ERC-4337 accounts: counterfactual address
* derivation, initializer/factory-data encoding, EIP-712 UserOperation signing,
* multi-signer aggregation (ECDSA + WebAuthn), module enable/disable helpers,
* and UserOperation construction. Versioned subclasses
* ({@link SafeAccountV0_2_0}, {@link SafeAccountV0_3_0},
* {@link SafeAccountV1_5_0_M_0_3_0}) bind this class to a specific EntryPoint
* and Safe singleton, and expose version-typed wrappers.
*
* Instantiate directly only for an already-deployed account; use a subclass's
* static `initializeNewAccount` to produce a counterfactual account + factory
* data for first-time deployment.
*/
export class SafeAccount extends SmartAccount {
static readonly DEFAULT_WEB_AUTHN_SHARED_SIGNER: string =
"0xfD90FAd33ee8b58f32c00aceEad1358e4AFC23f9";
static readonly DEFAULT_WEB_AUTHN_SIGNER_SINGLETON: string =
"0x270D7E4a57E6322f336261f3EaE2BADe72E68d72";
static readonly DEFAULT_WEB_AUTHN_SIGNER_FACTORY: string =
"0xF7488fFbe67327ac9f37D5F722d83Fc900852Fbf";
// EIP-7212 contract verifier used in the verifier proxy CREATE2 salt and
// installed as the shared signer's contract verifier at init time.
// Defaults to FCL P256 because that's what Safe Passkey module v0.2.0
// shipped — newer modules (v0.2.1+, v1.5.0_M_0.3.0) override with Daimo.
// FCL has known non-security-critical bugs and is being phased out
// upstream now that EIP-7951 (precompile) supersedes it.
static readonly DEFAULT_WEB_AUTHN_CONTRACT_VERIFIER: string =
"0x445a0683e494ea0c5AF3E83c5159fBE47Cf9e765";
static readonly DEFAULT_WEB_AUTHN_PRECOMPILE: string =
"0x0000000000000000000000000000000000000000"; //zero address means no precompile
static readonly DEFAULT_WEB_AUTHN_SIGNER_PROXY_CREATION_CODE: string =
"0x61010060405234801561001157600080fd5b506040516101ee3803806101ee83398101604081905261003091610058565b6001600160a01b0390931660805260a09190915260c0526001600160b01b031660e0526100bc565b6000806000806080858703121561006e57600080fd5b84516001600160a01b038116811461008557600080fd5b60208601516040870151606088015192965090945092506001600160b01b03811681146100b157600080fd5b939692955090935050565b60805160a05160c05160e05160ff6100ef60003960006008015260006031015260006059015260006080015260ff6000f3fe608060408190527f00000000000000000000000000000000000000000000000000000000000000003660b681018290527f000000000000000000000000000000000000000000000000000000000000000060a082018190527f00000000000000000000000000000000000000000000000000000000000000008285018190527f00000000000000000000000000000000000000000000000000000000000000009490939192600082376000806056360183885af490503d6000803e8060c3573d6000fd5b503d6000f3fea2646970667358221220ddd9bb059ba7a6497d560ca97aadf4dbf0476f578378554a50d41c6bb654beae64736f6c63430008180033";
static readonly DEFAULT_MULTISEND_CONTRACT_ADDRESS = "0x38869bf66a61cF6bDB996A6aE40D5853Fd43B526";
static readonly initializerFunctionSelector: string = "0xb63e800d";
static readonly initializerFunctionInputAbi: string[] = [
"address[]",
"uint256",
"address",
"bytes",
"address",
"address",
"uint256",
"address",
];
static readonly DEFAULT_EXECUTOR_FUCNTION_SELECTOR =
SafeModuleExecutorFunctionSelector.executeUserOpWithErrorString;
static readonly executorFunctionInputAbi: string[] = [
"address", //to
"uint256", //value
"bytes", //data
"uint8", //operation
];
protected isInitWebAuthn: boolean;
protected x: bigint | null = null;
protected y: bigint | null = null;
readonly safeAccountSingleton: SafeAccountSingleton;
readonly entrypointAddress: string;
readonly safe4337ModuleAddress: string;
protected factoryAddress: string | null;
protected factoryData: string | null;
readonly onChainIdentifier: string | null;
/**
* @param accountAddress - On-chain address of the Safe account
* @param safe4337ModuleAddress - Address of the Safe 4337 module the account delegates to
* @param entrypointAddress - Target EntryPoint address (v0.6 / v0.7 / v0.9)
* @param overrides - Optional on-chain-identifier configuration and custom singleton
* @param overrides.onChainIdentifierParams - Attribution params for analytics (mutually exclusive with `onChainIdentifier`)
* @param overrides.onChainIdentifier - Pre-computed 32-byte identifier hex (no 0x prefix or with 0x)
* @param overrides.safeAccountSingleton - Override Safe singleton address + init hash (defaults to Safe L2 v1.4.1)
*/
constructor(
accountAddress: string,
safe4337ModuleAddress: string,
entrypointAddress: string,
overrides: {
onChainIdentifierParams?: OnChainIdentifierParamsType;
onChainIdentifier?: string;
safeAccountSingleton?: SafeAccountSingleton;
} = {},
) {
super(accountAddress);
this.entrypointAddress = entrypointAddress;
this.safe4337ModuleAddress = safe4337ModuleAddress;
this.factoryAddress = null;
this.factoryData = null;
this.isInitWebAuthn = false;
if (overrides.onChainIdentifierParams != null && overrides.onChainIdentifier != null) {
throw new RangeError("can't override both onChainIdentifier and onChainIdentifierParams");
} else if (overrides.onChainIdentifierParams != null) {
this.onChainIdentifier = generateOnChainIdentifier(
overrides.onChainIdentifierParams.project,
overrides.onChainIdentifierParams.platform,
overrides.onChainIdentifierParams.tool,
overrides.onChainIdentifierParams.toolVersion,
);
} else if (overrides.onChainIdentifier != null) {
let onChainIdentifier = overrides.onChainIdentifier;
if (onChainIdentifier.startsWith("0x")) {
onChainIdentifier = onChainIdentifier.slice(2);
}
if (onChainIdentifier.length !== 64) {
throw new RangeError("onChainIdentifier length must be 64.");
}
this.onChainIdentifier = onChainIdentifier;
} else {
this.onChainIdentifier = null;
}
this.safeAccountSingleton = overrides.safeAccountSingleton ?? Safe_L2_V1_4_1;
}
/**
* calculate proxy/account address using initializer call data
* @param initializerCallData from createBaseInitializerCallData
* @param overrides - overrides for the default values
* @param overrides.c2Nonce - create2 nonce to generate different sender addresses from the same owners
* defaults to zero
* @param overrides.safeFactoryAddress - safeFactoryAddress, defaults to
* SafeAccountFactory.DEFAULT_FACTORY_ADDRESS
* @param overrides.singletonInitHash - a hash that includes the singleton address and the proxy bytecode
* keccak256(solidityPacked(["bytes", "bytes"], [proxyByteCode, abiCoder.encode(["uint256"], [singletonAddress])]))
* defaults to SafeAccount.safeAccountSingleton.singletonInitHash
* @returns proxy/account address
*/
public static createProxyAddress(
initializerCallData: string,
overrides: {
c2Nonce?: bigint;
safeFactoryAddress?: string;
singletonInitHash?: string;
} = {},
): string {
const c2Nonce = overrides.c2Nonce ?? 0n;
if (c2Nonce < 0n) {
throw new RangeError("c2Nonce can't be negative");
}
const safeFactoryAddress =
overrides.safeFactoryAddress ?? SafeAccountFactory.DEFAULT_FACTORY_ADDRESS;
const singletonInitHash = overrides.singletonInitHash ?? Safe_L2_V1_4_1.singletonInitHash;
const salt = keccak256(
solidityPacked(["bytes32", "uint256"], [keccak256(initializerCallData), c2Nonce]),
);
const proxyAdd = solidityPackedKeccak256(
["bytes1", "address", "bytes32", "bytes32"],
["0xff", safeFactoryAddress, salt, singletonInitHash],
).slice(-40);
return getAddress(`0x${proxyAdd}`); //to checksummed
}
/**
* Check whether a Safe account is already deployed at the given address.
*
* Use this to decide between connecting to an existing account
* (`new SafeAccountV0_3_0(address)`) and initializing a new one
* (`SafeAccountV0_3_0.initializeNewAccount(owners)`). Once an account is
* deployed, the factory data carried by `initializeNewAccount` is no
* longer needed and including it would waste gas.
*
* Note: this only checks whether bytecode exists at `accountAddress`, not
* whether the deployed code is actually a Safe or whether its on-chain
* configuration matches a given set of owners.
*
* @param accountAddress - the Safe account address to check
* @param nodeRpcUrl - Ethereum JSON-RPC node URL
* @returns `true` if bytecode is deployed at `accountAddress`, `false` otherwise
*
* @example
* ```ts
* const account = (await SafeAccountV0_3_0.isDeployed(addr, rpc))
* ? new SafeAccountV0_3_0(addr)
* : SafeAccountV0_3_0.initializeNewAccount(owners);
* ```
*/
public static async isDeployed(
accountAddress: string,
nodeRpcUrl: string | Transport | JsonRpcNode,
): Promise<boolean> {
const code = await JsonRpcNode.from(nodeRpcUrl).getCode(accountAddress, "latest");
return code.length > 2;
}
/**
* encode calldata for a single MetaTransaction to be executed by Safe account
* @param metaTransaction - metaTransaction to create calldata for
* @param overrides - overrides for the default values
* @param overrides.safeModuleExecutorFunctionSelector - select the
* executor function, either "executeUserOpWithErrorString" or "executeUserOp"
* defaults to "executeUserOpWithErrorString"
* @returns calldata
*/
public static createAccountCallDataSingleTransaction(
metaTransaction: MetaTransaction,
overrides: {
safeModuleExecutorFunctionSelector?: SafeModuleExecutorFunctionSelector;
} = {},
): string {
const value = metaTransaction.value ?? 0;
const data = metaTransaction.data ?? "0x";
const operation = metaTransaction.operation ?? Operation.Call;
const safeModuleExecutorFunctionSelector =
overrides.safeModuleExecutorFunctionSelector ??
SafeAccount.DEFAULT_EXECUTOR_FUCNTION_SELECTOR;
const executorFunctionCallData = SafeAccount.createAccountCallData(
metaTransaction.to,
value,
data,
operation,
{
safeModuleExecutorFunctionSelector,
},
);
return executorFunctionCallData;
}
/**
* encode calldata for a list of MetaTransactions to be executed by Safe account
* @param metaTransaction - metaTransaction to create calldata for
* @param overrides - overrides for the default values
* @param overrides.safeModuleExecutorFunctionSelector - select the
* executor function, either "executeUserOpWithErrorString" or "executeUserOp"
* defaults to "executeUserOpWithErrorString"
* @param overrides.multisendContractAddress - defaults to
* SafeAccount.DEFAULT_MULTISEND_CONTRACT_ADDRESS
* @returns calldata
*/
public static createAccountCallDataBatchTransactions(
metaTransactions: MetaTransaction[],
overrides: {
safeModuleExecutorFunctionSelector?: SafeModuleExecutorFunctionSelector;
multisendContractAddress?: string;
} = {},
): string {
if (metaTransactions.length < 1) {
throw new RangeError("There should be at least one metaTransaction");
}
const safeModuleExecutorFunctionSelector =
overrides.safeModuleExecutorFunctionSelector ??
SafeAccount.DEFAULT_EXECUTOR_FUCNTION_SELECTOR;
const multisendContractAddress =
overrides.multisendContractAddress ?? SafeAccount.DEFAULT_MULTISEND_CONTRACT_ADDRESS;
const multiData = encodeMultiSendCallData(metaTransactions);
const mutisendSelector = "0x8d80ff0a";
const multiSendCallData = createCallData(mutisendSelector, ["bytes"], [multiData]);
const executorFunctionCallData = SafeAccount.createAccountCallData(
multisendContractAddress,
0n,
multiSendCallData,
Operation.Delegate,
{
safeModuleExecutorFunctionSelector,
},
);
return executorFunctionCallData;
}
/**
* encode calldata to be executed by Safe account
* @param to - target address
* @param value - amount of native token to transfer to target address
* @param data - calldata
* @param operation - either call or delegate call
* @param overrides - overrides for the default values
* @param overrides.safeModuleExecutorFunctionSelector - select the
* executor function, either "executeUserOpWithErrorString" or "executeUserOp"
* defaults to "executeUserOpWithErrorString"
* @returns callData
*/
public static createAccountCallData(
to: string,
value: bigint,
data: string,
operation: Operation,
overrides: {
safeModuleExecutorFunctionSelector?: SafeModuleExecutorFunctionSelector;
} = {},
): string {
const safeModuleExecutorFunctionSelector =
overrides.safeModuleExecutorFunctionSelector ??
SafeAccount.DEFAULT_EXECUTOR_FUCNTION_SELECTOR;
const executorFunctionInputParameters = [to, value, data, operation];
const callData = createCallData(
safeModuleExecutorFunctionSelector,
SafeAccount.executorFunctionInputAbi,
executorFunctionInputParameters,
);
return callData;
}
/**
* decode calldata to a Metatransaction
* @param callData - calldata to decode
* @returns [MetaTransaction, SafeModuleExecutorFunctionSelector]
*/
public static decodeAccountCallData(
callData: string,
): [MetaTransaction, SafeModuleExecutorFunctionSelector] {
let safeModuleExecutorFunctionSelector: SafeModuleExecutorFunctionSelector | null = null;
if (callData.startsWith(SafeModuleExecutorFunctionSelector.executeUserOpWithErrorString)) {
safeModuleExecutorFunctionSelector =
SafeModuleExecutorFunctionSelector.executeUserOpWithErrorString;
} else if (callData.startsWith(SafeModuleExecutorFunctionSelector.executeUserOp)) {
safeModuleExecutorFunctionSelector = SafeModuleExecutorFunctionSelector.executeUserOp;
}
if (safeModuleExecutorFunctionSelector != null) {
const params = `0x${callData.slice(10)}`;
const decodedParams = decodeAbiParameters<[string, bigint, string | Uint8Array, bigint]>(
[
"address", //to
"uint256", //value
"bytes", //data
"uint8", //operation"
],
params,
);
// decodeAbiParameters returns the "bytes" field as either a hex
// string or a Uint8Array. UTF-8 decoding the bytes would corrupt
// any non-text payload (function selectors, addresses, multisend
// blobs); hex-encode instead so the calldata round-trips.
const accountCallDataString: string =
typeof decodedParams[2] === "string" ? decodedParams[2] : hexlify(decodedParams[2]);
return [
{
to: decodedParams[0],
value: BigInt(decodedParams[1]),
data: accountCallDataString,
operation: Number(decodedParams[3]),
},
safeModuleExecutorFunctionSelector,
];
} else {
throw new AbstractionKitError(
"BAD_DATA",
"Invalid calldata, should start with " +
SafeModuleExecutorFunctionSelector.executeUserOpWithErrorString +
" or " +
SafeModuleExecutorFunctionSelector.executeUserOp,
{
context: {
callData: callData,
},
},
);
}
}
/**
* adds a token approve call to the call data for a token paymaster
* @param callData - calldata to be added to, if after decoding it is not
* a multisend transaction, it will be encoded as a multisend transaction
* @param tokenAddress - token to add approve for
* @param paymasterAddress - paymaster to add approve for
* @param approveAmount - amount to add approve for
* @param overrides - overrides for the default values
* @param overrides.multisendContractAddress - defaults to
* SafeAccount.DEFAULT_MULTISEND_CONTRACT_ADDRESS
* @returns callData
*/
public static prependTokenPaymasterApproveToCallDataStatic(
callData: string,
tokenAddress: string,
paymasterAddress: string,
approveAmount: bigint,
overrides: {
multisendContractAddress?: string;
} = {},
): string {
const multisendContractAddress =
overrides.multisendContractAddress ?? SafeAccount.DEFAULT_MULTISEND_CONTRACT_ADDRESS;
const [metaTransaction, safeModuleExecutorFunctionSelector] =
SafeAccount.decodeAccountCallData(callData);
const approveFunctionSignature = "approve(address,uint256)";
const approveFunctionSelector = getFunctionSelector(approveFunctionSignature);
const approveCallData = createCallData(
approveFunctionSelector,
["address", "uint256"],
[paymasterAddress, approveAmount],
);
const approveMetatransaction: MetaTransaction = {
to: tokenAddress,
value: 0n,
data: approveCallData,
operation: Operation.Call,
};
const encodedApproveMetatransaction = encodeMultiSendCallData([approveMetatransaction]);
let multiSendCallDataParams = "";
const mutisendSelector = "0x8d80ff0a";
if (metaTransaction.data.startsWith(mutisendSelector)) {
//multisend
const decodedCalldata = decodeMultiSendCallData(metaTransaction.data);
multiSendCallDataParams = encodedApproveMetatransaction + decodedCalldata.slice(2);
} else {
const encodedCallDataMetaTransaction = encodeMultiSendCallData([metaTransaction]);
multiSendCallDataParams =
encodedApproveMetatransaction + encodedCallDataMetaTransaction.slice(2);
}
const multiSendCallData = createCallData(
mutisendSelector,
["bytes"],
[multiSendCallDataParams],
);
const executorFunctionCallData = SafeAccount.createAccountCallData(
multisendContractAddress,
0n,
multiSendCallData,
Operation.Delegate,
{
safeModuleExecutorFunctionSelector,
},
);
return executorFunctionCallData;
}
/**
* @deprecated
* format a list of eip712 signatures to a useroperation signature
* @param signersAddresses - signers public addresses
* @param signatures - list of eip712 signatures
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @returns signature
*/
public static formatEip712SignaturesToUseroperationSignature(
signersAddresses: string[],
signatures: string[],
overrides: {
validAfter?: bigint;
validUntil?: bigint;
isMultiChainSignature?: boolean;
merkleProof?: string;
} = {},
): string {
if (signersAddresses.length !== signatures.length) {
throw new RangeError("signersAddresses and signatures arrays should be the same length");
}
const signersSignatures: SignerSignaturePair[] = [];
signersAddresses.forEach((signer, index) => {
signersSignatures.push({
signer: signer.toLowerCase(),
signature: signatures[index],
});
});
return SafeAccount.formatSignaturesToUseroperationSignature(signersSignatures, {
validAfter: overrides.validAfter,
validUntil: overrides.validUntil,
isMultiChainSignature: overrides.isMultiChainSignature,
multiChainMerkleProof: overrides.merkleProof,
});
}
/**
* Get the EIP-712 typed data for this account's configured EntryPoint and
* Safe 4337 module. Prefer this instance method for manual signing so
* custom constructor overrides are carried through automatically.
*
* @param useroperation - UserOperation to get typed data for
* @param chainId - target chain ID
* @param overrides - optional validity window and explicit address overrides
* @returns Object with domain, types, and messageValue for EIP-712 signing
*/
public getUserOperationEip712Data(
useroperation: UserOperationV6 | UserOperationV7 | UserOperationV9,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): {
domain: SafeUserOperationTypedDataDomain;
types: Record<string, { name: string; type: string }[]>;
messageValue:
| SafeUserOperationV6TypedMessageValue
| SafeUserOperationV7TypedMessageValue
| SafeUserOperationV9TypedMessageValue;
} {
return SafeAccount.getUserOperationEip712Data(useroperation, chainId, {
...overrides,
entrypointAddress: overrides.entrypointAddress ?? this.entrypointAddress,
safe4337ModuleAddress: overrides.safe4337ModuleAddress ?? this.safe4337ModuleAddress,
});
}
/**
* Hash the EIP-712 typed data for this account's configured EntryPoint and
* Safe 4337 module. Prefer this instance method for manual signing so
* custom constructor overrides are carried through automatically.
*
* @param useroperation - UserOperation to hash
* @param chainId - target chain ID
* @param overrides - optional validity window and explicit address overrides
* @returns EIP-712 digest as a hex string
*/
public getUserOperationEip712Hash(
useroperation: UserOperationV6 | UserOperationV7 | UserOperationV9,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): string {
const data = this.getUserOperationEip712Data(useroperation, chainId, overrides);
return hashTypedData(data.domain, data.types, data.messageValue);
}
/**
* Format signer/signature pairs for this account's signature encoding.
* Prefer this instance method for manual signing so account-level module
* context is applied automatically.
*
* @param signerSignaturePairs - signer/signature pairs to encode
* @param options - optional validity window, multi-chain, module, and WebAuthn encoding overrides
* @returns formatted UserOperation signature
*/
public formatUserOperationSignature(
signerSignaturePairs: SignerSignaturePair[],
options: SafeSignatureOptions & WebAuthnSignatureOverrides = {},
): string {
return SafeAccount.formatSignaturesToUseroperationSignature(signerSignaturePairs, {
...options,
safe4337ModuleAddress: options.safe4337ModuleAddress ?? this.safe4337ModuleAddress,
});
}
/**
* create a v0.07 or v0.06 useroperation eip712 data
* @param useroperation - useroperation to hash
* @param chainId - target chain id
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @param overrides.entrypoint - target entrypoint
* @param overrides.safe4337ModuleAddress - target module address
* @returns useroperation hash
*/
protected static getUserOperationEip712Hash(
useroperation: UserOperationV6 | UserOperationV7 | UserOperationV9,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): string {
if ("initCode" in useroperation) {
return SafeAccount.getUserOperationEip712Hash_V6(useroperation, chainId, overrides);
} else {
if (overrides.entrypointAddress) {
if (overrides.entrypointAddress.toLowerCase() === ENTRYPOINT_V9.toLowerCase()) {
return SafeAccount.getUserOperationEip712Hash_V9(
useroperation as UserOperationV9,
chainId,
overrides,
);
} else {
return SafeAccount.getUserOperationEip712Hash_V7(useroperation, chainId, overrides);
}
} else {
return SafeAccount.getUserOperationEip712Hash_V7(useroperation, chainId, overrides);
}
}
}
/**
* create a v0.07 or v0.06 useroperation eip712 data
* @param useroperation - useroperation to hash
* @param chainId - target chain id
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @param overrides.entrypoint - target entrypoint
* @param overrides.safe4337ModuleAddress - target module address
* @returns an object containing the typed data domain, type and typed data vales
* object needed for hashing and signing
*/
protected static getUserOperationEip712Data(
useroperation: UserOperationV6 | UserOperationV7 | UserOperationV9,
chainId: bigint,
overrides?: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
},
): {
domain: SafeUserOperationTypedDataDomain;
types: Record<string, { name: string; type: string }[]>;
messageValue:
| SafeUserOperationV6TypedMessageValue
| SafeUserOperationV7TypedMessageValue
| SafeUserOperationV9TypedMessageValue;
} {
if ("initCode" in useroperation) {
const data = SafeAccount.getUserOperationEip712Data_V6(useroperation, chainId, overrides);
return {
domain: data.domain,
types: data.types,
messageValue: data.messageValue,
};
} else {
let data:
| ReturnType<typeof SafeAccount.getUserOperationEip712Data_V7>
| ReturnType<typeof SafeAccount.getUserOperationEip712Data_V9>;
if (overrides?.entrypointAddress) {
if (overrides.entrypointAddress.toLowerCase() === ENTRYPOINT_V9.toLowerCase()) {
data = SafeAccount.getUserOperationEip712Data_V9(
useroperation as UserOperationV9,
chainId,
overrides,
);
} else {
data = SafeAccount.getUserOperationEip712Data_V7(useroperation, chainId, overrides);
}
} else {
data = SafeAccount.getUserOperationEip712Data_V7(useroperation, chainId, overrides);
}
return {
domain: data.domain,
types: data.types,
messageValue: data.messageValue,
};
}
}
/**
* create a v0.06 useroperation eip712 data
* @param useroperation - useroperation to hash
* @param chainId - target chain id
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @param overrides.entrypoint - target entrypoint
* defaults to ENTRYPOINT_V6
* @param overrides.safe4337ModuleAddress - defaults to "0xa581c4A4DB7175302464fF3C06380BC3270b4037"
* @returns an object containing the typed data domain, type and typed data vales
* object needed for hashing and signing
*/
public static getUserOperationEip712Data_V6(
useroperation: UserOperationV6,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): {
domain: SafeUserOperationTypedDataDomain;
types: Record<string, { name: string; type: string }[]>;
messageValue: SafeUserOperationV6TypedMessageValue;
} {
const validAfter = overrides.validAfter ?? 0n;
const validUntil = overrides.validUntil ?? 0n;
const entrypointAddress = overrides.entrypointAddress ?? ENTRYPOINT_V6;
const safe4337ModuleAddress =
overrides.safe4337ModuleAddress ?? "0xa581c4A4DB7175302464fF3C06380BC3270b4037";
const messageValue: SafeUserOperationV6TypedMessageValue = {
safe: useroperation.sender,
nonce: useroperation.nonce,
initCode: useroperation.initCode,
callData: useroperation.callData,
callGasLimit: useroperation.callGasLimit,
verificationGasLimit: useroperation.verificationGasLimit,
preVerificationGas: useroperation.preVerificationGas,
maxFeePerGas: useroperation.maxFeePerGas,
maxPriorityFeePerGas: useroperation.maxPriorityFeePerGas,
paymasterAndData: useroperation.paymasterAndData,
validAfter: validAfter,
validUntil: validUntil,
entryPoint: entrypointAddress,
};
const domain: SafeUserOperationTypedDataDomain = {
chainId: Number(chainId),
verifyingContract: safe4337ModuleAddress,
};
return {
domain,
types: EIP712_SAFE_OPERATION_V6_TYPE,
messageValue,
};
}
/**
* create a v0.06 useroperation eip712 data
* @param useroperation - useroperation to hash
* @param chainId - target chain id
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @param overrides.entrypoint - target entrypoint
* defaults to ENTRYPOINT_V6
* @param overrides.safe4337ModuleAddress - defaults to "0xa581c4A4DB7175302464fF3C06380BC3270b4037"
* @returns useroperation hash
*/
public static getUserOperationEip712Hash_V6(
useroperation: UserOperationV6,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): string {
const data = SafeAccount.getUserOperationEip712Data_V6(useroperation, chainId, overrides);
return hashTypedData(data.domain, data.types, data.messageValue);
}
private static baseGetUserOperationEip712DataV7V8V9(
useroperation: UserOperationV7,
chainId: bigint,
entrypointAddress: string,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
safe4337ModuleAddress?: string;
is_v9?: boolean;
} = {},
): {
domain: SafeUserOperationTypedDataDomain;
types: Record<string, { name: string; type: string }[]>;
messageValue: SafeUserOperationV6TypedMessageValue;
} {
const validAfter = overrides.validAfter ?? 0n;
const validUntil = overrides.validUntil ?? 0n;
const safe4337ModuleAddress =
overrides.safe4337ModuleAddress ?? "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226";
let initCode = "0x";
if (useroperation.factory != null) {
initCode = useroperation.factory;
if (useroperation.factoryData != null) {
initCode += useroperation.factoryData.slice(2);
}
}
let paymasterAndData = "0x";
if (useroperation.paymaster != null) {
paymasterAndData = useroperation.paymaster;
if (useroperation.paymasterVerificationGasLimit != null) {
paymasterAndData += encodeAbiParameters(
["uint128"],
[useroperation.paymasterVerificationGasLimit],
).slice(34);
}
if (useroperation.paymasterPostOpGasLimit != null) {
paymasterAndData += encodeAbiParameters(
["uint128"],
[useroperation.paymasterPostOpGasLimit],
).slice(34);
}
if (useroperation.paymasterData != null) {
const PAYMASTER_SIG_MAGIC = "22e325a297439656";
if (
overrides.is_v9 &&
useroperation.paymasterData.toLowerCase().endsWith(PAYMASTER_SIG_MAGIC)
) {
const sigLenHex = useroperation.paymasterData.slice(
useroperation.paymasterData.length - 16 - 4,
useroperation.paymasterData.length - 16,
);
const sigLen = parseInt(sigLenHex, 16);
const prefixEnd = useroperation.paymasterData.length - 16 - 4 - sigLen * 2;
paymasterAndData +=
useroperation.paymasterData.slice(0, prefixEnd).replaceAll("0x", "") +
PAYMASTER_SIG_MAGIC;
} else {
paymasterAndData += useroperation.paymasterData.slice(2);
}
}
}
const messageValue: SafeUserOperationV7TypedMessageValue = {
safe: useroperation.sender,
nonce: useroperation.nonce,
initCode: initCode,
callData: useroperation.callData,
verificationGasLimit: useroperation.verificationGasLimit,
callGasLimit: useroperation.callGasLimit,
preVerificationGas: useroperation.preVerificationGas,
maxPriorityFeePerGas: useroperation.maxPriorityFeePerGas,
maxFeePerGas: useroperation.maxFeePerGas,
paymasterAndData,
validAfter: validAfter,
validUntil: validUntil,
entryPoint: entrypointAddress,
};
const domain: SafeUserOperationTypedDataDomain = {
chainId: Number(chainId),
verifyingContract: safe4337ModuleAddress,
};
return {
domain,
types: EIP712_SAFE_OPERATION_V7_TYPE,
messageValue,
};
}
/**
* create a v0.07 useroperation eip712 hash
* @param useroperation - useroperation to hash
* @param chainId - target chain id
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @param overrides.entrypoint - target entrypoint
* defaults to ENTRYPOINT_V7
* @param overrides.safe4337ModuleAddress - defaults to "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226"
* @returns an object containing the typed data domain, type and typed data vales
* object needed for hashing and signing
*/
public static getUserOperationEip712Data_V7(
useroperation: UserOperationV7,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): {
domain: SafeUserOperationTypedDataDomain;
types: Record<string, { name: string; type: string }[]>;
messageValue: SafeUserOperationV6TypedMessageValue;
} {
return SafeAccount.baseGetUserOperationEip712DataV7V8V9(
useroperation,
chainId,
overrides.entrypointAddress ?? ENTRYPOINT_V7,
overrides,
);
}
/**
* create a v0.07 useroperation eip712 hash
* @param useroperation - useroperation to hash
* @param chainId - target chain id
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @param overrides.entrypoint - target entrypoint
* defaults to ENTRYPOINT_V7
* @param overrides.safe4337ModuleAddress - defaults to "0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226"
* @returns useroperation hash
*/
public static getUserOperationEip712Hash_V7(
useroperation: UserOperationV7,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): string {
const data = SafeAccount.getUserOperationEip712Data_V7(useroperation, chainId, overrides);
return hashTypedData(data.domain, data.types, data.messageValue);
}
/**
* create a v0.09 useroperation eip712 hash
* @param useroperation - useroperation to hash
* @param chainId - target chain id
* @param overrides - overrides for the default values
* @param overrides.validAfter - timestamp the signature will be valid after
* @param overrides.validUntil - timestamp the signature will be valid until
* @param overrides.entrypoint - target entrypoint
* defaults to ENTRYPOINT_V9
* @param overrides.safe4337ModuleAddress - defaults to "0xee8005d7e79f9a6829ea61A81Fc2A85055fB2a42"
* @returns an object containing the typed data domain, type and typed data vales
* object needed for hashing and signing
*/
public static getUserOperationEip712Data_V9(
useroperation: UserOperationV9,
chainId: bigint,
overrides: {
validAfter?: bigint;
validUntil?: bigint;
entrypointAddress?: string;
safe4337ModuleAddress?: string;
} = {},
): {
domain: SafeUserOperationTypedDataDomain;
types: Record<string, { name: string; type: string }[]>;
messageValue: SafeUserOperationV9TypedMessageValue;
} {
const safe4337ModuleAddress =
overrides.safe4337ModuleAddress ?? "0xee8005d7e79f9a6829ea61A81Fc2A85055fB2a42";
return SafeAccount.baseGetUserOperationEip712DataV7V8V9(
useroperation,