-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathSimple7702Account.ts
More file actions
1143 lines (1061 loc) · 42 KB
/
Copy pathSimple7702Account.ts
File metadata and controls
1143 lines (1061 loc) · 42 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 {decodeAbiParameters, hexlify, privateKeyToAddress, signHash} from "src/ethereUtils";
import {Bundler} from "src/Bundler";
import {BaseUserOperationDummyValues, ENTRYPOINT_V8, ENTRYPOINT_V9} from "src/constants";
import {AbstractionKitError} from "src/errors";
import {invokeSigner, pickScheme} from "src/signer/negotiate";
import type {SignContext, ExternalSigner, SigningScheme, TypedData} from "src/signer/types";
import {JsonRpcNode, type Transport} from "src/transport";
import type {
GasOption,
JsonRpcResult,
PolygonChain,
StateOverrideSet,
UserOperationV8,
UserOperationV9,
} from "src/types";
import {
type Authorization7702Hex,
bigintToHex,
createAndSignEip7702RawTransaction,
createRevokeDelegationAuthorization,
} from "src/utils7702";
import {
createCallData,
createUserOperationHash,
fetchAccountNonce,
getFunctionSelector,
getUserOperationEip712DataV8V9,
getUserOperationEip712HashV8V9,
handlefetchGasPrice,
sendJsonRpcRequest,
} from "../../utils";
import {SendUseroperationResponse} from "../SendUseroperationResponse";
import {SmartAccount} from "../SmartAccount";
/**
* A minimal transaction object for EIP-7702 simple accounts.
* Represents a single call with a target address, ETH value, and calldata.
*/
export interface SimpleMetaTransaction {
/** Target contract or EOA address */
to: string;
/** Amount of native token (in wei) to send with the call */
value: bigint;
/** ABI-encoded calldata, or "0x" for plain ETH transfers */
data: string;
}
/**
* Optional overrides for UserOperation fields when calling
* {@link BaseSimple7702Account.baseCreateUserOperation}.
* Any field left undefined will be auto-determined (nonce fetched from RPC,
* gas limits estimated via bundler, gas prices fetched from the network).
*/
export interface CreateUserOperationOverrides {
/** set the nonce instead of querying the current nonce from the rpc node */
nonce?: bigint;
/** set the callData instead of using the encoding of the provided Metatransactions*/
callData?: string;
/** set the callGasLimit instead of estimating gas using the bundler*/
callGasLimit?: bigint;
/** set the verificationGasLimit instead of estimating gas using the bundler*/
verificationGasLimit?: bigint;
/** set the preVerificationGas instead of estimating gas using the bundler*/
preVerificationGas?: bigint;
/** set the maxFeePerGas instead of querying the current gas price from the rpc node */
maxFeePerGas?: bigint;
/** set the maxPriorityFeePerGas instead of querying the current gas price from the rpc node */
maxPriorityFeePerGas?: bigint;
/** set the callGasLimitPercentageMultiplier instead of estimating gas using the bundler*/
callGasLimitPercentageMultiplier?: number;
/** set the verificationGasLimitPercentageMultiplier instead of estimating gas using the bundler*/
verificationGasLimitPercentageMultiplier?: number;
/** set the preVerificationGasPercentageMultiplier instead of estimating gas using the bundler*/
preVerificationGasPercentageMultiplier?: number;
/** set the maxFeePerGasPercentageMultiplier instead of querying the current gas price from the rpc node */
maxFeePerGasPercentageMultiplier?: number;
/** set the maxPriorityFeePerGasPercentageMultiplier instead of querying the current gas price from the rpc node */
maxPriorityFeePerGasPercentageMultiplier?: number;
/** pass some state overrides for gas estimation */
state_override_set?: StateOverrideSet;
/**
* Skip calling the bundler's gas estimation entirely. When true, the returned
* UserOperation still gets a dummy signature, but its gas limits come from the
* provided overrides (or stay at 0n). Useful when estimation is run separately
* — for example, by a paymaster sponsorship call that returns its own limits.
*/
skipGasEstimation?: boolean;
/** Override the dummy signature used during gas estimation */
dummySignature?: string;
/** Gas price level preference (e.g., slow, medium, fast) */
gasLevel?: GasOption;
/** Polygon chain identifier for fetching gas prices from Polygon Gas Station */
polygonGasStation?: PolygonChain;
/**
* EIP-7702 authorization fields. When provided, the UserOperation
* will include an authorization tuple that delegates the EOA to
* the account's delegatee contract. If address/nonce are omitted,
* defaults are used (delegateeAddress and fetched from RPC respectively).
*/
eip7702Auth?: {
chainId: bigint;
address?: string;
nonce?: bigint;
yParity?: string;
r?: string;
s?: string;
};
parallelPaymasterInitValues?: {
/** set the paymaster contract address */
paymaster: string;
/** set the paymaster verification gas limit */
paymasterVerificationGasLimit: bigint;
/** set the paymaster post-operation gas limit */
paymasterPostOpGasLimit: bigint;
/** set the paymaster data, only valid value is 0x22e325a297439656 */
paymasterData: string;
};
}
/**
* Abstract base class for EIP-7702 simple smart accounts.
* Provides shared logic for creating, signing, and sending UserOperations
* using the SimpleAccount execute/executeBatch interface. Subclasses
* (e.g., {@link Simple7702Account}, {@link Simple7702AccountV09}) bind
* a specific EntryPoint version and delegatee address.
*/
export class BaseSimple7702Account extends SmartAccount {
/** Function selector for `execute(address,uint256,bytes)` */
static readonly executorFunctionSelector = "0xb61d27f6"; //execute
/** ABI parameter types for the single-call `execute` function */
static readonly executorFunctionInputAbi: string[] = [
"address", //dest
"uint256", //value
"bytes", //func
];
/** Function selector for `executeBatch((address,uint256,bytes)[])` */
static readonly batchExecutorFunctionSelector = "0x34fcd5be"; //executeBatch
/** ABI parameter types for the batch `executeBatch` function */
static readonly batchExecutorFunctionInputAbi = ["(address,uint256,bytes)[]"];
/** Dummy ECDSA signature used during gas estimation */
static readonly dummySignature =
"0xd2614025fc173b86704caf37b2fb447f7618101a0d31f5f304c777024cef38a060a29ee43fcf0c46f9107d4f670b8a85c2c017a1fe9e4af891f24f0be6ba5d671c";
/** The EntryPoint contract address this account targets */
readonly entrypointAddress: string;
/** The EIP-7702 delegatee (implementation) contract address */
readonly delegateeAddress: string;
/**
* @param accountAddress - The EOA address that will be delegated via EIP-7702
* @param entrypointAddress - The EntryPoint contract address
* @param delegateeAddress - The EIP-7702 delegatee (implementation) contract address
*/
constructor(accountAddress: string, entrypointAddress: string, delegateeAddress: string) {
super(accountAddress);
this.entrypointAddress = entrypointAddress;
this.delegateeAddress = delegateeAddress;
}
/**
* Check if this EOA is delegated to the expected delegatee address via EIP-7702.
* Returns `true` only when delegated to `this.delegateeAddress`.
* Use `JsonRpcNode.getDelegatedAddress()` directly to get the raw delegatee address.
*
* @param providerRpc - Ethereum JSON-RPC node URL
* @returns `true` if delegated to the expected address, `false` otherwise
*/
public async isDelegatedToThisAccount(
providerRpc: string | Transport | JsonRpcNode,
): Promise<boolean> {
const address = await JsonRpcNode.from(providerRpc).getDelegatedAddress(this.accountAddress);
if (address === null) return false;
return address.toLowerCase() === this.delegateeAddress.toLowerCase();
}
/**
* Create a signed raw EIP-7702 transaction that revokes the delegation,
* restoring the EOA to a normal account. The transaction is type 0x04
* with a zero-address authorization.
*
* Cannot be done via UserOp — the authorization_list is processed before
* execution, removing the account's code mid-transaction.
*
* Authorization nonce defaults to txNonce + 1 because EIP-7702 increments
* the sender's transaction nonce before processing the authorization list.
*
* @param eoaPrivateKey - The EOA's private key (signs both auth and tx)
* @param providerRpc - JSON-RPC endpoint for nonce, gas price, chain ID
* @param overrides - Optional overrides for transaction fields
* @returns Signed raw transaction hex, ready for `eth_sendRawTransaction`
*/
public async createRevokeDelegationTransaction(
eoaPrivateKey: string,
providerRpc: string | Transport | JsonRpcNode,
overrides: {
nonce?: bigint;
authorizationNonce?: bigint;
maxFeePerGas?: bigint;
maxPriorityFeePerGas?: bigint;
gasLimit?: bigint;
chainId?: bigint;
} = {},
): Promise<string> {
// Verify the private key matches this account — otherwise the raw
// transaction's sender (recovered from the signature) would be a
// different EOA and the revoke would target the signer's delegation
const signerAddress = privateKeyToAddress(eoaPrivateKey);
if (signerAddress.toLowerCase() !== this.accountAddress.toLowerCase()) {
throw new AbstractionKitError(
"BAD_DATA",
`eoaPrivateKey does not match accountAddress (${this.accountAddress})`,
);
}
// Verify delegation state before revoking
const delegatedTo = await JsonRpcNode.from(providerRpc).getDelegatedAddress(this.accountAddress);
if (delegatedTo === null) {
throw new AbstractionKitError("BAD_DATA", "Account is not delegated — nothing to revoke");
}
if (delegatedTo.toLowerCase() !== this.delegateeAddress.toLowerCase()) {
throw new AbstractionKitError(
"BAD_DATA",
"Account is delegated to a different address (" +
delegatedTo +
"), not " +
this.delegateeAddress +
" — use the correct account class to revoke",
);
}
const results: {
nonce?: bigint;
maxFeePerGas?: bigint;
maxPriorityFeePerGas?: bigint;
chainId?: bigint;
} = {};
// Build parallel fetch list
const ops: Promise<void>[] = [];
if (overrides.nonce == null) {
ops.push(
sendJsonRpcRequest(providerRpc, "eth_getTransactionCount", [
this.accountAddress,
"latest",
]).then((v) => {
results.nonce = BigInt(v as string);
}),
);
}
if (overrides.maxFeePerGas == null || overrides.maxPriorityFeePerGas == null) {
ops.push(
handlefetchGasPrice(providerRpc, undefined).then(([fee, tip]) => {
results.maxFeePerGas = fee;
results.maxPriorityFeePerGas = tip;
}),
);
}
if (overrides.chainId == null) {
ops.push(
sendJsonRpcRequest(providerRpc, "eth_chainId", []).then((v) => {
results.chainId = BigInt(v as string);
}),
);
}
if (ops.length > 0) await Promise.all(ops);
const txNonce = overrides.nonce ?? results.nonce ?? 0n;
const maxFeePerGas = overrides.maxFeePerGas ?? results.maxFeePerGas ?? 0n;
const maxPriorityFeePerGas =
overrides.maxPriorityFeePerGas ?? results.maxPriorityFeePerGas ?? 0n;
const chainId = overrides.chainId ?? results.chainId ?? 0n;
// Authorization nonce = txNonce + 1 by default
// (tx nonce is incremented before authorization processing in EIP-7702)
const authNonce = overrides.authorizationNonce ?? txNonce + 1n;
// Create undelegation authorization (returns Authorization7702Hex)
const authHex = createRevokeDelegationAuthorization(chainId, authNonce, eoaPrivateKey);
// Convert Authorization7702Hex -> Authorization7702 for raw tx builder
const auth = {
chainId: BigInt(authHex.chainId),
address: authHex.address,
nonce: BigInt(authHex.nonce),
yParity: (BigInt(authHex.yParity) === 0n ? 0 : 1) as 0 | 1,
r: BigInt(authHex.r),
s: BigInt(authHex.s),
};
const gasLimit = overrides.gasLimit ?? 60_000n;
return createAndSignEip7702RawTransaction(
chainId,
txNonce,
maxPriorityFeePerGas,
maxFeePerGas,
gasLimit,
this.accountAddress,
0n,
"0x",
[],
[auth],
eoaPrivateKey,
);
}
/**
* Encode calldata for a single `execute(address,uint256,bytes)` call.
* @param to - Target contract or EOA address
* @param value - Amount of native token (in wei) to transfer
* @param data - ABI-encoded calldata for the target
* @returns Encoded calldata for the execute function
*/
public static createAccountCallData(to: string, value: bigint, data: string): string {
const executorFunctionInputParameters = [to, value, data];
const callData = createCallData(
BaseSimple7702Account.executorFunctionSelector,
BaseSimple7702Account.executorFunctionInputAbi,
executorFunctionInputParameters,
);
return callData;
}
/**
* Encode calldata for a single {@link SimpleMetaTransaction} using `execute`.
* @param metaTransaction - The transaction to encode
* @returns Encoded calldata for the execute function
*/
public static createAccountCallDataSingleTransaction(
metaTransaction: SimpleMetaTransaction,
): string {
const value = metaTransaction.value ?? 0;
const data = metaTransaction.data ?? "0x";
const executorFunctionCallData = BaseSimple7702Account.createAccountCallData(
metaTransaction.to,
value,
data,
);
return executorFunctionCallData;
}
/**
* Encode calldata for a batch of {@link SimpleMetaTransaction}s using `executeBatch`.
* @param transactions - Array of transactions to batch
* @returns Encoded calldata for the executeBatch function
*/
public static createAccountCallDataBatchTransactions(
transactions: SimpleMetaTransaction[],
): string {
const encodedTransactions = [
transactions.map((transaction) => [transaction.to, transaction.value, transaction.data]),
];
const callData = createCallData(
BaseSimple7702Account.batchExecutorFunctionSelector,
BaseSimple7702Account.batchExecutorFunctionInputAbi,
encodedTransactions,
);
return callData;
}
/**
* Build an unsigned UserOperation from one or more transactions.
* Determines nonce, fetches gas prices, estimates gas limits, and
* optionally includes EIP-7702 authorization. All auto-determined
* values can be overridden.
* @param transactions - One or more transactions to encode into callData
* @param providerRpc - JSON-RPC endpoint for nonce and gas price queries
* @param bundlerRpc - Bundler RPC endpoint for gas estimation
* @param overrides - Optional overrides for gas, nonce, and EIP-7702 auth fields
* @returns A promise resolving to an unsigned UserOperation (v8 or v9)
*/
protected async baseCreateUserOperation(
transactions: SimpleMetaTransaction[],
providerRpc?: string | Transport | JsonRpcNode,
bundlerRpc?: string | Transport | Bundler,
overrides: CreateUserOperationOverrides = {},
): Promise<UserOperationV8 | UserOperationV9> {
if (transactions.length < 1) {
throw new RangeError("There should be at least one transaction");
}
let nonce: bigint | null = null;
let nonceOp: Promise<bigint> | null = null;
if (overrides.nonce == null) {
if (providerRpc != null) {
nonceOp = fetchAccountNonce(providerRpc, this.entrypointAddress, this.accountAddress);
} else {
throw new AbstractionKitError(
"BAD_DATA",
"providerRpc can't be null if nonce is not overridden",
);
}
} else {
nonce = overrides.nonce;
}
if (typeof overrides.maxFeePerGas === "bigint" && overrides.maxFeePerGas < 0n) {
throw new RangeError("maxFeePerGas override can't be negative");
}
if (typeof overrides.maxPriorityFeePerGas === "bigint" && overrides.maxPriorityFeePerGas < 0n) {
throw new RangeError("maxPriorityFeePerGas override can't be negative");
}
let maxFeePerGas = BaseUserOperationDummyValues.maxFeePerGas;
let maxPriorityFeePerGas = BaseUserOperationDummyValues.maxPriorityFeePerGas;
let gasPriceOp: Promise<[bigint, bigint]> | null = null;
if (overrides.maxFeePerGas == null || overrides.maxPriorityFeePerGas == null) {
gasPriceOp = handlefetchGasPrice(
providerRpc,
overrides.polygonGasStation,
overrides.gasLevel,
);
}
let eip7702AuthChainId: bigint | null = null;
let eip7702AuthAddress: string | null = null;
let eip7702AuthNonce: bigint | null = null;
let skipEip7702Auth = false;
if (overrides.eip7702Auth != null) {
eip7702AuthChainId = overrides.eip7702Auth.chainId;
eip7702AuthAddress = overrides.eip7702Auth.address ?? this.delegateeAddress;
eip7702AuthNonce = overrides.eip7702Auth.nonce ?? null;
}
// When eip7702Auth is provided, check delegation status in parallel.
// Best-effort: if the check fails, proceed as if not delegated.
let delegationCheckOp: Promise<string | null> | null = null;
if (overrides.eip7702Auth != null && providerRpc != null) {
delegationCheckOp = JsonRpcNode.from(providerRpc)
.getDelegatedAddress(this.accountAddress)
.catch(() => null);
}
if (overrides.eip7702Auth != null && eip7702AuthNonce == null) {
//check for eip7702AuthNonce
let eip7702AuthNonceOp: Promise<JsonRpcResult>;
if (providerRpc != null) {
eip7702AuthNonceOp = sendJsonRpcRequest(providerRpc, "eth_getTransactionCount", [
this.accountAddress,
"latest",
]);
} else {
throw new AbstractionKitError(
"BAD_DATA",
"providerRpc can't be null if eoaDelegatorNonce " + "is not overridden",
);
}
// Build array of all parallel operations
const ops: Promise<unknown>[] = [eip7702AuthNonceOp];
if (nonceOp != null) ops.push(nonceOp);
if (gasPriceOp != null) ops.push(gasPriceOp);
if (delegationCheckOp != null) ops.push(delegationCheckOp);
const values = await Promise.all(ops);
let idx = 0;
eip7702AuthNonce = BigInt(values[idx++] as string);
if (nonceOp != null) nonce = values[idx++] as bigint;
if (gasPriceOp != null)
[maxFeePerGas, maxPriorityFeePerGas] = values[idx++] as [bigint, bigint];
if (delegationCheckOp != null) {
const delegatedTo = values[idx++] as string | null;
if (
delegatedTo != null &&
delegatedTo.toLowerCase() === (eip7702AuthAddress as string).toLowerCase()
) {
skipEip7702Auth = true;
}
}
} else if (overrides.eip7702Auth != null) {
// eip7702AuthNonce was provided, but still need delegation check + other ops
const ops: Promise<unknown>[] = [];
if (nonceOp != null) ops.push(nonceOp);
if (gasPriceOp != null) ops.push(gasPriceOp);
if (delegationCheckOp != null) ops.push(delegationCheckOp);
if (ops.length > 0) {
const values = await Promise.all(ops);
let idx = 0;
if (nonceOp != null) nonce = values[idx++] as bigint;
if (gasPriceOp != null)
[maxFeePerGas, maxPriorityFeePerGas] = values[idx++] as [bigint, bigint];
if (delegationCheckOp != null) {
const delegatedTo = values[idx++] as string | null;
if (
delegatedTo != null &&
delegatedTo.toLowerCase() === (eip7702AuthAddress as string).toLowerCase()
) {
skipEip7702Auth = true;
}
}
}
} else {
//don't check for eip7702AuthNonce
if (gasPriceOp != null && nonceOp != null) {
await Promise.all([nonceOp, gasPriceOp]).then((values) => {
nonce = values[0];
[maxFeePerGas, maxPriorityFeePerGas] = values[1];
});
} else if (gasPriceOp != null) {
[maxFeePerGas, maxPriorityFeePerGas] = await gasPriceOp;
} else if (nonceOp != null) {
nonce = await nonceOp;
}
}
maxFeePerGas =
overrides.maxFeePerGas ??
BigInt(
Math.floor(
Number(maxFeePerGas) * (((overrides.maxFeePerGasPercentageMultiplier ?? 0) + 100) / 100),
),
);
maxPriorityFeePerGas =
overrides.maxPriorityFeePerGas ??
BigInt(
Math.floor(
Number(maxPriorityFeePerGas) *
(((overrides.maxPriorityFeePerGasPercentageMultiplier ?? 0) + 100) / 100),
),
);
if (nonce == null) {
throw new RangeError("failed to determine nonce");
} else if (nonce < 0n) {
throw new RangeError("nonce can't be negative");
}
let callData = "0x" as string;
if (overrides.callData == null) {
if (transactions.length === 1) {
callData = BaseSimple7702Account.createAccountCallDataSingleTransaction(transactions[0]);
} else {
callData = BaseSimple7702Account.createAccountCallDataBatchTransactions(transactions);
}
} else {
callData = overrides.callData;
}
let userOperation: UserOperationV8 | UserOperationV9;
if (overrides.eip7702Auth != null && !skipEip7702Auth) {
const yParity = overrides.eip7702Auth.yParity ?? "0x0";
if (yParity !== "0x0" && yParity !== "0x00" && yParity !== "0x1" && yParity !== "0x01") {
throw new AbstractionKitError(
"BAD_DATA",
"invalid yParity value for eoaDelegatorSignature. " + "must be '0x0' or '0x1'",
);
}
const authorization: Authorization7702Hex = {
chainId: bigintToHex(eip7702AuthChainId as bigint),
address: eip7702AuthAddress as string,
nonce: bigintToHex(eip7702AuthNonce as bigint),
yParity: yParity,
r:
overrides.eip7702Auth.r ??
"0x4277ba564d2c138823415df0ec8e8f97f30825056d54ec5128a8b29ec2dd81b2",
s:
overrides.eip7702Auth.s ??
"0x1075a1bec7f59848cca899ece93075199cd2aabceb0654b9ae00b881a30044cd",
};
userOperation = {
...BaseUserOperationDummyValues,
sender: this.accountAddress,
nonce: nonce,
callData: callData,
maxFeePerGas: maxFeePerGas,
maxPriorityFeePerGas: maxPriorityFeePerGas,
factory: "0x7702",
factoryData: null,
paymaster: null,
paymasterVerificationGasLimit: null,
paymasterPostOpGasLimit: null,
paymasterData: null,
eip7702Auth: authorization,
};
} else {
userOperation = {
...BaseUserOperationDummyValues,
sender: this.accountAddress,
nonce: nonce,
callData: callData,
maxFeePerGas: maxFeePerGas,
maxPriorityFeePerGas: maxPriorityFeePerGas,
factory: null,
factoryData: null,
paymaster: null,
paymasterVerificationGasLimit: null,
paymasterPostOpGasLimit: null,
paymasterData: null,
eip7702Auth: null,
};
}
let preVerificationGas = BaseUserOperationDummyValues.preVerificationGas;
let verificationGasLimit = BaseUserOperationDummyValues.verificationGasLimit;
let callGasLimit = BaseUserOperationDummyValues.callGasLimit;
// Set the dummy signature on the user operation regardless of whether
// gas estimation runs below, so the returned op always has a valid
// placeholder signature (required by paymaster sponsorship calls).
userOperation.signature = overrides.dummySignature ?? BaseSimple7702Account.dummySignature;
const skipGasEstimation = overrides.skipGasEstimation ?? false;
// Apply v0.9 parallel paymaster placeholders unconditionally so the
// paymaster stub survives into signing/hashing regardless of whether
// gas estimation runs below. The UserOpHash must commit to these
// fields, so dropping them when skipGasEstimation is true or when
// gas limits are pre-specified would produce an invalid signature.
const parallelPaymasterInitValues = overrides.parallelPaymasterInitValues;
if (parallelPaymasterInitValues != null) {
if (this.entrypointAddress !== ENTRYPOINT_V9) {
throw new RangeError("parallelPaymasterInitValues only works with ep v0.9");
}
userOperation.paymaster = parallelPaymasterInitValues.paymaster;
userOperation.paymasterVerificationGasLimit =
parallelPaymasterInitValues.paymasterVerificationGasLimit;
userOperation.paymasterPostOpGasLimit = parallelPaymasterInitValues.paymasterPostOpGasLimit;
userOperation.paymasterData = parallelPaymasterInitValues.paymasterData;
}
if (
!skipGasEstimation &&
(overrides.preVerificationGas == null ||
overrides.verificationGasLimit == null ||
overrides.callGasLimit == null)
) {
if (bundlerRpc != null) {
userOperation.callGasLimit = 0n;
userOperation.verificationGasLimit = 0n;
userOperation.preVerificationGas = 0n;
const inputMaxFeePerGas = userOperation.maxFeePerGas;
const inputMaxPriorityFeePerGas = userOperation.maxPriorityFeePerGas;
userOperation.maxFeePerGas = 0n;
userOperation.maxPriorityFeePerGas = 0n;
const userOperationToEstimate = { ...userOperation };
[preVerificationGas, verificationGasLimit, callGasLimit] =
await this.baseEstimateUserOperationGas(userOperationToEstimate, bundlerRpc, {
stateOverrideSet: overrides.state_override_set,
});
// Compensate for ECDSA verification cost the bundler skips during
// `eth_estimateUserOperationGas`: estimation runs with a dummy
// signature whose signature path is short-circuited (the dummy
// doesn't recover to a real owner, so the bundler bypasses
// signature validation). ~55k gas is the on-chain ECRECOVER +
// signature decode cost that simulation never paid for.
verificationGasLimit += 55_000n;
userOperation.maxFeePerGas = inputMaxFeePerGas;
userOperation.maxPriorityFeePerGas = inputMaxPriorityFeePerGas;
} else {
throw new AbstractionKitError(
"BAD_DATA",
"bundlerRpc can't be null if preVerificationGas," +
"verificationGasLimit and callGasLimit are not overridden",
);
}
}
if (typeof overrides.preVerificationGas === "bigint" && overrides.preVerificationGas < 0n) {
throw new RangeError("preVerificationGas override can't be negative");
}
if (typeof overrides.verificationGasLimit === "bigint" && overrides.verificationGasLimit < 0n) {
throw new RangeError("verificationGasLimit override can't be negative");
}
if (typeof overrides.callGasLimit === "bigint" && overrides.callGasLimit < 0n) {
throw new RangeError("callGasLimit override can't be negative");
}
userOperation.preVerificationGas =
overrides.preVerificationGas ??
BigInt(
Math.floor(
Number(preVerificationGas) *
(((overrides.preVerificationGasPercentageMultiplier ?? 0) + 100) / 100),
),
);
userOperation.verificationGasLimit =
overrides.verificationGasLimit ??
BigInt(
Math.floor(
Number(verificationGasLimit) *
(((overrides.verificationGasLimitPercentageMultiplier ?? 0) + 100) / 100),
),
);
userOperation.callGasLimit =
overrides.callGasLimit ??
BigInt(
Math.floor(
Number(callGasLimit) * (((overrides.callGasLimitPercentageMultiplier ?? 0) + 100) / 100),
),
);
return userOperation;
}
/**
* Estimate gas limits for a UserOperation via the bundler.
* @param userOperation - The UserOperation to estimate gas for
* @param bundlerRpc - Bundler RPC endpoint for gas estimation
* @param overrides - Optional overrides
* @param overrides.stateOverrideSet - State overrides to apply during estimation
* @param overrides.dummySignature - Custom dummy ECDSA signature for estimation
* @returns A promise resolving to `[preVerificationGas, verificationGasLimit, callGasLimit]`
*/
protected async baseEstimateUserOperationGas(
userOperation: UserOperationV8 | UserOperationV9,
bundlerRpc: string | Transport | Bundler,
overrides: {
stateOverrideSet?: StateOverrideSet;
dummySignature?: string;
} = {},
): Promise<[bigint, bigint, bigint]> {
const bundler = Bundler.from(bundlerRpc);
// Estimate on a shallow copy so the caller's operation is never
// mutated, even when estimation throws.
const userOperationToEstimate = {
...userOperation,
signature: overrides.dummySignature ?? BaseSimple7702Account.dummySignature,
maxFeePerGas: 0n,
maxPriorityFeePerGas: 0n,
};
const estimation = await bundler.estimateUserOperationGas(
userOperationToEstimate,
this.entrypointAddress,
overrides.stateOverrideSet,
);
const preVerificationGas = BigInt(estimation.preVerificationGas);
const verificationGasLimit = BigInt(estimation.verificationGasLimit);
const callGasLimit = BigInt(estimation.callGasLimit);
return [preVerificationGas, verificationGasLimit, callGasLimit];
}
/**
* Sign a UserOperation with an EOA private key.
* Computes the UserOperation hash and produces an ECDSA signature.
* @param useroperation - The UserOperation to sign
* @param privateKey - Hex-encoded private key of the EOA signer
* @param chainId - Target chain ID
* @returns Hex-encoded ECDSA signature
*/
protected baseSignUserOperation(
useroperation: UserOperationV8 | UserOperationV9,
privateKey: string,
chainId: bigint,
): string {
const userOperationHash = createUserOperationHash(
useroperation,
this.entrypointAddress,
chainId,
);
return signHash(privateKey, userOperationHash).serialized;
}
/**
* Schemes Simple7702 accepts from a Signer. EntryPoint v0.8/v0.9 introduced
* an EIP-712 domain at the EntryPoint contract, and the userOpHash IS the
* EIP-712 digest of the PackedUserOperation under that domain — so signing
* the typed data and signing the raw hash produce signatures that verify
* against the same `userOpHash` (and recover to the same signer address).
* Deterministic-ECDSA signers (ethers, viem, MetaMask) yield byte-identical
* bytes; signers that differ in `s` / `v` normalization still validate the
* same on-chain.
*
* `typedData` is listed first so JSON-RPC wallets that can only sign typed
* data work without a separate code path; `hash` remains a valid fallback
* for local-key signers.
*/
public static readonly ACCEPTED_SIGNING_SCHEMES: readonly SigningScheme[] = ["typedData", "hash"];
/**
* Build the EIP-712 typed data payload for a UserOperation under the
* EntryPoint v0.8 / v0.9 domain. Lower-level escape hatch for integrators
* driving `signTypedData` themselves with their own signing primitive
* (HSM, MPC, custom wallet abstraction). Most callers should pass an
* {@link ExternalSigner} to {@link signUserOperationWithSigner} instead, which
* builds this internally.
*
* The digest of the returned payload equals the UserOperation hash from
* {@link createUserOperationHash}, so a wallet calling
* `signTypedData(domain, types, message)` produces a signature that
* verifies against the same `userOpHash` as raw ECDSA over that hash.
* Deterministic-ECDSA signers yield byte-identical signatures; signers
* that differ in `s` / `v` normalization still validate the same on-chain.
*
* The base class defaults to EntryPoint v0.8; subclasses
* ({@link Simple7702AccountV09}) override with their own default.
*
* @param userOperation - Unsigned UserOperation to wrap
* @param chainId - Target chain ID (must match the chain that will validate
* the signature)
* @param overrides - Override the entrypoint address
* @returns EIP-712 {@link TypedData} payload ready for `signTypedData`
* @throws {AbstractionKitError} if the target EntryPoint is not v0.8 / v0.9.
*/
public static getUserOperationEip712Data(
userOperation: UserOperationV8 | UserOperationV9,
chainId: bigint,
overrides: { entrypointAddress?: string } = {},
): TypedData {
const entrypointAddress = overrides.entrypointAddress ?? ENTRYPOINT_V8;
return getUserOperationEip712DataV8V9(userOperation, entrypointAddress, chainId);
}
/**
* Compute the EIP-712 digest of a UserOperation under the EntryPoint
* v0.8 / v0.9 domain. For these EntryPoints this digest IS the
* `userOpHash` ({@link createUserOperationHash}); signing it with raw
* ECDSA or via `signTypedData` over the data from
* {@link getUserOperationEip712Data} produces a signature that validates
* against the same hash on-chain.
*
* @param userOperation - Unsigned UserOperation to hash
* @param chainId - Target chain ID
* @param overrides - Override the entrypoint address (defaults to EntryPoint v0.8)
* @returns The EIP-712 digest as a hex string
* @throws {AbstractionKitError} if the target EntryPoint is not v0.8 / v0.9.
*/
public static getUserOperationEip712Hash(
userOperation: UserOperationV8 | UserOperationV9,
chainId: bigint,
overrides: { entrypointAddress?: string } = {},
): string {
const entrypointAddress = overrides.entrypointAddress ?? ENTRYPOINT_V8;
return getUserOperationEip712HashV8V9(userOperation, entrypointAddress, chainId);
}
/**
* Sign a UserOperation with an {@link ExternalSigner}. The signer can implement
* either `signTypedData` (preferred — JSON-RPC wallets, viem `WalletClient`)
* or `signHash` (local keys, hardware wallets). Both schemes produce
* signatures that validate against the same `userOpHash` because the
* v0.8 / v0.9 userOpHash IS the EIP-712 digest of the PackedUserOperation
* (deterministic-ECDSA signers yield byte-identical bytes).
*
* Signers that implement neither method fail offline with an actionable
* error.
*/
protected async baseSignUserOperationWithSigner<T extends UserOperationV8 | UserOperationV9>(
useroperation: T,
signer: ExternalSigner,
chainId: bigint,
): Promise<string> {
const scheme = pickScheme(signer, BaseSimple7702Account.ACCEPTED_SIGNING_SCHEMES, {
accountName: "Simple7702 (EIP-712 typed data or raw ECDSA over userOpHash)",
signerIndex: 0,
});
const hash = createUserOperationHash(
useroperation,
this.entrypointAddress,
chainId,
) as `0x${string}`;
const context: SignContext<T> = {
userOperation: useroperation,
chainId,
entryPoint: this.entrypointAddress,
};
const typedData =
scheme === "typedData"
? BaseSimple7702Account.getUserOperationEip712Data(useroperation, chainId, {
entrypointAddress: this.entrypointAddress,
})
: undefined;
return invokeSigner(signer, scheme, { hash, typedData, context });
}
/**
* Submit a signed UserOperation to a bundler for on-chain inclusion.
* @param userOperation - The signed UserOperation to submit
* @param bundlerRpc - Bundler RPC endpoint
* @returns A {@link SendUseroperationResponse} that can be used to wait for inclusion
*/
protected async baseSendUserOperation(
userOperation: UserOperationV8 | UserOperationV9,
bundlerRpc: string | Transport | Bundler,
): Promise<SendUseroperationResponse> {
const bundler = Bundler.from(bundlerRpc);
const sendUserOperationRes = await bundler.sendUserOperation(
userOperation,
this.entrypointAddress,
);
return new SendUseroperationResponse(sendUserOperationRes, bundler, this.entrypointAddress);
}
/**
* Prepend a token `approve` call to existing calldata for a token paymaster.
* Instance wrapper for {@link BaseSimple7702Account.prependTokenPaymasterApproveToCallDataStatic}.
* @param callData - Existing encoded calldata (execute or executeBatch)
* @param tokenAddress - ERC-20 token contract to approve
* @param paymasterAddress - Paymaster address to approve as spender
* @param approveAmount - Token amount to approve
* @returns Re-encoded calldata with the approve transaction prepended as a batch
*/
public prependTokenPaymasterApproveToCallData(
callData: string,
tokenAddress: string,
paymasterAddress: string,
approveAmount: bigint,
): string {
return BaseSimple7702Account.prependTokenPaymasterApproveToCallDataStatic(
callData,
tokenAddress,
paymasterAddress,
approveAmount,
);
}
/**
* Prepend a token `approve` call to existing calldata for a token paymaster.
* Decodes the existing calldata, prepends an ERC-20 approve transaction,
* and re-encodes as a batch via `executeBatch`.
* @param callData - Existing encoded calldata (execute or executeBatch)
* @param tokenAddress - ERC-20 token contract to approve
* @param paymasterAddress - Paymaster address to approve as spender
* @param approveAmount - Token amount to approve
* @returns Re-encoded calldata with the approve transaction prepended as a batch
*/
public static prependTokenPaymasterApproveToCallDataStatic(
callData: string,
tokenAddress: string,
paymasterAddress: string,
approveAmount: bigint,
): string {
const approveFunctionSignature = "approve(address,uint256)";
const approveFunctionSelector = getFunctionSelector(approveFunctionSignature);
const approveCallData = createCallData(
approveFunctionSelector,
["address", "uint256"],
[paymasterAddress, approveAmount],
);
const approveMetatransaction: SimpleMetaTransaction = {
to: tokenAddress,
value: 0n,
data: approveCallData,
};
let decodedMetaTransactions: SimpleMetaTransaction[];
if (callData.startsWith(BaseSimple7702Account.batchExecutorFunctionSelector)) {
const decodedParamsArray = decodeAbiParameters<
[Array<[string, bigint, string | Uint8Array]>]
>(BaseSimple7702Account.batchExecutorFunctionInputAbi, `0x${callData.slice(10)}`)[0];
// decodeAbiParameters can return the "bytes" field as a Uint8Array;
// UTF-8 decoding would corrupt arbitrary calldata, so hex-encode it.
decodedMetaTransactions = decodedParamsArray.map((decodedParams) => ({
to: decodedParams[0],
value: BigInt(decodedParams[1]),
data:
typeof decodedParams[2] === "string"
? decodedParams[2]
: hexlify(decodedParams[2]),
}));
} else if (callData.startsWith(BaseSimple7702Account.executorFunctionSelector)) {
const decodedParams = decodeAbiParameters<[string, bigint, string | Uint8Array]>(
BaseSimple7702Account.executorFunctionInputAbi,
`0x${callData.slice(10)}`,
);
decodedMetaTransactions = [
{
to: decodedParams[0],
value: BigInt(decodedParams[1]),
data:
typeof decodedParams[2] === "string"
? decodedParams[2]
: hexlify(decodedParams[2]),
},
];
} else {
throw new AbstractionKitError(
"BAD_DATA",
"Invalid calldata, should start with " +
BaseSimple7702Account.batchExecutorFunctionSelector +
" or " +
BaseSimple7702Account.executorFunctionSelector,
{
context: {
callData: callData,
},