-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathCalibur7702Account.ts
More file actions
1462 lines (1337 loc) · 52.8 KB
/
Copy pathCalibur7702Account.ts
File metadata and controls
1462 lines (1337 loc) · 52.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
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,
encodeAbiParameters,
hexlify,
keccak256,
privateKeyToAddress,
signHash,
} from "src/ethereUtils";
import {Bundler} from "src/Bundler";
import {
BaseUserOperationDummyValues,
CALIBUR_UNISWAP_V1_0_0_SINGLETON_ADDRESS,
ENTRYPOINT_V8,
ZeroAddress,
} from "src/constants";
import {AbstractionKitError} from "src/errors";
import type {PrependTokenPaymasterApproveAccount} from "src/paymaster/types";
import {invokeSigner, pickScheme} from "src/signer/negotiate";
import type {SignContext, Signer as AkSigner, SigningScheme, TypedData} from "src/signer/types";
import {JsonRpcNode, type Transport} from "src/transport";
import type {JsonRpcResult, 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";
import type {SimpleMetaTransaction} from "../simple/Simple7702Account";
import {
type CaliburCreateUserOperationOverrides,
type CaliburKey,
type CaliburKeySettings,
type CaliburKeySettingsResult,
CaliburKeyType,
type CaliburSignatureOverrides,
type WebAuthnSignatureData,
} from "./types";
const DEFAULT_SINGLETON_ADDRESS = CALIBUR_UNISWAP_V1_0_0_SINGLETON_ADDRESS;
/** Root key hash (bytes32 zero) — used for the EOA's own secp256k1 key */
const ROOT_KEY_HASH = "0x0000000000000000000000000000000000000000000000000000000000000000";
// Function selectors — computed from Calibur's actual Solidity interfaces:
// - executeUserOp is IAccountExecute.executeUserOp(PackedUserOperation,bytes32)
// The EntryPoint calls this; userOp.callData = selector + abi.encode(BatchedCall)
// - register takes Key struct: register((uint8,bytes))
// - update/revoke/invalidateNonce match standard signatures
/** executeUserOp selector — `executeUserOp((address,uint256,bytes,bytes,bytes32,uint256,bytes32,bytes,bytes),bytes32)` from IAccountExecute */
const EXECUTE_USER_OP_SELECTOR = "0x8dd7712f";
/** register((uint8,bytes)) — registers a Key struct */
const REGISTER_SELECTOR = "0x30b1fa3b";
/** update(bytes32,uint256) — updates key settings */
const UPDATE_SELECTOR = "0xa58bb84a";
/** revoke(bytes32) — revokes a key by hash */
const REVOKE_SELECTOR = "0xb75c7dc6";
/** invalidateNonce(uint256) — invalidates nonces */
const INVALIDATE_NONCE_SELECTOR = "0xb70e36f0";
// Read function selectors
/** isRegistered(bytes32) */
const IS_REGISTERED_SELECTOR = "0x27258b22";
/** getKeySettings(bytes32) — returns packed Settings (uint256) */
const GET_KEY_SETTINGS_SELECTOR = "0x0f3ebf6e";
/** getKey(bytes32) — returns Key struct (uint8,bytes) */
const GET_KEY_SELECTOR = "0x12aaac70";
/** keyCount() */
const KEY_COUNT_SELECTOR = "0xfac750e0";
/** keyAt(uint256) — returns Key struct */
const KEY_AT_SELECTOR = "0x4223b5c2";
/**
* EIP-7702 smart account implementation for the Calibur (Uniswap) singleton.
* Calibur turns an EOA into a smart account via EIP-7702 delegation, providing
* batched transactions, passkey signing, ERC-4337 support, and per-key hooks.
*
* Unlike Safe accounts, there is no factory or proxy — the EOA IS the account.
* All transactions go through `executeUserOp(bytes)` with `BatchedCall` encoding.
*
* @example
* ```typescript
* const account = new Calibur7702Account("0xMyEOA");
* const userOp = await account.createUserOperation(
* [{ to: "0xRecipient", value: 1000000000000000n, data: "0x" }],
* nodeRpc, bundlerRpc,
* { eip7702Auth: { chainId: 11155111n } }
* );
* userOp.signature = account.signUserOperation(userOp, privateKey, 11155111n);
* const response = await account.sendUserOperation(userOp, bundlerRpc);
* ```
*/
export class Calibur7702Account
extends SmartAccount
implements PrependTokenPaymasterApproveAccount
{
/** Function selector for `executeUserOp(bytes)` */
static readonly executorFunctionSelector = EXECUTE_USER_OP_SELECTOR;
/**
* Dummy ECDSA signature for gas estimation with root key signing.
* Format: `abi.encode(bytes32 keyHash, bytes sig, bytes hookData)`
*/
static readonly dummySignature: string = encodeAbiParameters(
["bytes32", "bytes", "bytes"],
[
ROOT_KEY_HASH,
"0xd2614025fc173b86704caf37b2fb447f7618101a0d31f5f304c777024cef38a060a29ee43fcf0c46f9107d4f670b8a85c2c017a1fe9e4af891f24f0be6ba5d671c",
"0x",
],
);
/**
* Create a dummy WebAuthn signature for gas estimation with passkey signing.
* The key hash must correspond to an actually registered key on the account,
* otherwise the contract's `validateUserOp` will revert with `KeyDoesNotExist`.
*
* @param keyHash - The key hash of a registered passkey (from {@link getKeyHash})
* @returns A dummy signature suitable for passing as `dummySignature` override
*/
public static createDummyWebAuthnSignature(keyHash: string): string {
const dummyClientDataJSON =
'{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}';
const challengeIndex = BigInt(dummyClientDataJSON.indexOf('"challenge":"'));
const typeIndex = BigInt(dummyClientDataJSON.indexOf('"type":"webauthn.get"'));
return encodeAbiParameters(
["bytes32", "bytes", "bytes"],
[
keyHash,
encodeAbiParameters(
["(bytes,string,uint256,uint256,uint256,uint256)"],
[
[
"0x49960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d97630500000000",
dummyClientDataJSON,
challengeIndex,
typeIndex,
BigInt("0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0"),
BigInt("0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0"),
],
],
),
"0x",
],
);
}
/**
* Wrap a raw ECDSA signature in Calibur's signature format:
* `abi.encode(bytes32 keyHash, bytes signature, bytes hookData)`.
*
* Use this when signing externally (e.g., with viem, hardware wallet, MPC)
* to avoid manually ABI-encoding the wrapped signature.
*
* @param keyHash - The key hash (use ROOT_KEY_HASH `0x00...00` for the EOA's root key)
* @param rawSignature - The raw ECDSA signature (65 bytes, hex-encoded)
* @param hookData - Optional hook data (default: "0x")
* @returns Hex-encoded wrapped signature ready for `userOp.signature`
*/
public static wrapSignature(keyHash: string, rawSignature: string, hookData = "0x"): string {
return encodeAbiParameters(["bytes32", "bytes", "bytes"], [keyHash, rawSignature, hookData]);
}
/**
* Format a raw EIP-712 signature (from `signTypedData` over the payload
* returned by {@link getUserOperationEip712Data}) into Calibur's
* `userOp.signature` layout. Provided for API parity with Safe's
* `formatEip712SingleSignatureToUseroperationSignature`.
*
* Under EntryPoint v0.8 / v0.9 the userOpHash IS the EIP-712 digest of
* the PackedUserOperation, so a raw-hash signature and a typed-data
* signature are byte-identical for deterministic-ECDSA signers; this
* method is therefore equivalent to {@link wrapSignature} with the same
* `keyHash` / `hookData`. The default `keyHash` is the root-key hash
* (`bytes32(0)`), which selects the EOA's own secp256k1 key.
*
* @param signature - Raw ECDSA signature (65 bytes, hex-encoded) from
* `signTypedData` over the payload from {@link getUserOperationEip712Data}
* @param overrides - Optional `keyHash` / `hookData` overrides
* @returns Hex-encoded wrapped signature ready for `userOp.signature`
*/
public static formatEip712SingleSignatureToUseroperationSignature(
signature: string,
overrides: CaliburSignatureOverrides = {},
): string {
const keyHash = overrides.keyHash ?? ROOT_KEY_HASH;
const hookData = overrides.hookData ?? "0x";
return Calibur7702Account.wrapSignature(keyHash, signature, hookData);
}
/** The EntryPoint contract address this account targets */
readonly entrypointAddress: string;
/** The Calibur singleton (delegatee) contract address */
readonly delegateeAddress: string;
/**
* Create a new Calibur7702Account instance for an existing EOA.
* @param accountAddress - The EOA address that will be (or already is) delegated via EIP-7702
* @param overrides - Optional overrides for entrypoint and delegatee addresses
* @param overrides.entrypointAddress - Custom EntryPoint address (defaults to EntryPoint v0.8)
* @param overrides.delegateeAddress - Custom Calibur singleton address
*/
constructor(
accountAddress: string,
overrides: {
entrypointAddress?: string;
delegateeAddress?: string;
} = {},
) {
super(accountAddress);
this.entrypointAddress = overrides.entrypointAddress ?? ENTRYPOINT_V8;
this.delegateeAddress = overrides.delegateeAddress ?? DEFAULT_SINGLETON_ADDRESS;
}
/**
* Compute the UserOperation hash for this account's EntryPoint.
* Convenience wrapper around the standalone `createUserOperationHash` that
* automatically uses this account's EntryPoint address.
*
* @param userOperation - The UserOperation to hash
* @param chainId - Target chain ID
* @returns The UserOperation hash as a hex string
*/
public getUserOperationHash(userOperation: UserOperationV8, chainId: bigint): string {
return createUserOperationHash(userOperation, this.entrypointAddress, chainId);
}
/**
* Build the EIP-712 typed data payload for a UserOperation under the
* EntryPoint v0.8 / v0.9 domain. Useful for wallets that can only sign
* typed data (`eth_signTypedData_v4`) — the digest of the returned payload
* equals the `userOpHash`, so a typed-data signature over it produces a
* wrapped Calibur signature that validates against the same hash on-chain.
*
* Intended for the secp256k1 key path (root key or any registered
* secondary secp256k1 key), since `eth_signTypedData_v4` only produces
* secp256k1 signatures. P-256 and WebAuthn-P256 keys sign with their
* own primitives — for those, use {@link getUserOperationEip712Hash}
* (the digest), which is the value-to-be-signed regardless of key type.
*
* @param userOperation - Unsigned UserOperation to wrap
* @param chainId - Target chain ID
* @param overrides - Override the entrypoint address (defaults to EntryPoint v0.8)
* @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`; the wrapped Calibur signature is verified against this
* hash on-chain.
*
* Universal across Calibur key types: secp256k1 and P-256 keys sign
* this digest directly, each with their own signing primitive.
*
* @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);
}
// ─── CallData Encoding ───────────────────────────────────────────────
/**
* Encode calldata for `executeUserOp(bytes)` with BatchedCall format.
* All transactions (even single ones) go through the same BatchedCall path.
*
* @param transactions - One or more transactions to encode
* @param revertOnFailure - Whether to revert the entire batch if any call fails (default: true)
* @returns Encoded calldata for the executeUserOp function
*/
public static createAccountCallData(
transactions: SimpleMetaTransaction[],
revertOnFailure = true,
): string {
const calls = transactions.map((tx) => [tx.to, tx.value, tx.data]);
// BatchedCall struct { Call[] calls; bool revertOnFailure; }
// Solidity's abi.decode(data, (BatchedCall)) expects a single struct/tuple
// parameter, which has an extra offset layer compared to two separate args.
const batchedCallEncoded = encodeAbiParameters(
["((address,uint256,bytes)[],bool)"],
[[calls, revertOnFailure]],
);
return EXECUTE_USER_OP_SELECTOR + batchedCallEncoded.slice(2);
}
// ─── UserOperation Lifecycle ─────────────────────────────────────────
/**
* Build an unsigned {@link UserOperationV8} 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 {@link UserOperationV8}
*/
public async createUserOperation(
transactions: SimpleMetaTransaction[],
providerRpc?: string | Transport | JsonRpcNode,
bundlerRpc?: string | Transport | Bundler,
overrides: CaliburCreateUserOperationOverrides = {},
): Promise<UserOperationV8> {
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;
if (overrides.eip7702Auth != null) {
eip7702AuthChainId = overrides.eip7702Auth.chainId;
eip7702AuthAddress = overrides.eip7702Auth.address ?? this.delegateeAddress;
eip7702AuthNonce = overrides.eip7702Auth.nonce ?? null;
}
// When eip7702Auth is provided, check if already delegated in parallel.
// If already delegated to the target, skip the authorization.
let skipEip7702Auth = false;
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) {
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",
);
}
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) {
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 {
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) {
callData = Calibur7702Account.createAccountCallData(
transactions,
overrides.revertOnFailure ?? true,
);
} else {
callData = overrides.callData;
}
const pmFields = overrides.paymasterFields;
let userOperation: UserOperationV8;
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: pmFields?.paymaster ?? null,
paymasterVerificationGasLimit: pmFields?.paymasterVerificationGasLimit ?? null,
paymasterPostOpGasLimit: pmFields?.paymasterPostOpGasLimit ?? null,
paymasterData: pmFields?.paymasterData ?? null,
eip7702Auth: authorization,
};
} else {
userOperation = {
...BaseUserOperationDummyValues,
sender: this.accountAddress,
nonce: nonce,
callData: callData,
maxFeePerGas: maxFeePerGas,
maxPriorityFeePerGas: maxPriorityFeePerGas,
factory: null,
factoryData: null,
paymaster: pmFields?.paymaster ?? null,
paymasterVerificationGasLimit: pmFields?.paymasterVerificationGasLimit ?? null,
paymasterPostOpGasLimit: pmFields?.paymasterPostOpGasLimit ?? null,
paymasterData: pmFields?.paymasterData ?? null,
eip7702Auth: null,
};
}
let preVerificationGas = BaseUserOperationDummyValues.preVerificationGas;
let verificationGasLimit = BaseUserOperationDummyValues.verificationGasLimit;
let callGasLimit = BaseUserOperationDummyValues.callGasLimit;
const skipGasEstimation = overrides.skipGasEstimation ?? false;
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: UserOperationV8 = { ...userOperation };
userOperationToEstimate.signature =
overrides.dummySignature ?? Calibur7702Account.dummySignature;
const bundler = Bundler.from(bundlerRpc);
const estimation = await bundler.estimateUserOperationGas(
userOperationToEstimate,
this.entrypointAddress,
overrides.state_override_set,
);
preVerificationGas = BigInt(estimation.preVerificationGas);
verificationGasLimit = BigInt(estimation.verificationGasLimit);
callGasLimit = BigInt(estimation.callGasLimit);
// Compensate for signature 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 key, so the bundler
// bypasses signature validation). ~55k gas covers the on-chain
// signature path that simulation never paid for, whether the
// real key is secp256k1 (ECRECOVER), P-256, or WebAuthn-P256.
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),
),
);
// Set the dummy signature so paymaster sponsorship calls can simulate
// validateUserOp (Calibur's signature decoder rejects empty signatures).
userOperation.signature = overrides.dummySignature ?? Calibur7702Account.dummySignature;
return userOperation;
}
/**
* Sign a UserOperation with a private key.
* Computes the UserOperation hash and wraps the ECDSA signature in
* Calibur's format: `abi.encode(keyHash, ecdsaSig, hookData)`.
*
* By default signs with the root key. To sign with a registered
* secondary key, pass its key hash via `overrides.keyHash`.
*
* @param userOperation - The UserOperation to sign
* @param privateKey - Hex-encoded private key
* @param chainId - Target chain ID
* @param overrides - Optional overrides (keyHash for secondary keys, hookData)
* @returns Hex-encoded wrapped signature
*
* @example
* // Sign with root key
* userOp.signature = account.signUserOperation(userOp, privateKey, chainId);
*
* // Sign with a registered secondary key
* userOp.signature = account.signUserOperation(userOp, privateKey, chainId, { keyHash });
*/
public signUserOperation(
userOperation: UserOperationV8,
privateKey: string,
chainId: bigint,
overrides: CaliburSignatureOverrides = {},
): string {
const userOperationHash = createUserOperationHash(
userOperation,
this.entrypointAddress,
chainId,
);
const keyHash = overrides.keyHash ?? ROOT_KEY_HASH;
const hookData = overrides.hookData ?? "0x";
const ecdsaSig = signHash(privateKey, userOperationHash).serialized;
return Calibur7702Account.wrapSignature(keyHash, ecdsaSig, hookData);
}
/**
* Schemes Calibur 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"];
/**
* Sign a UserOperation with an {@link AkSigner}. 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.
*/
public async signUserOperationWithSigner(
userOperation: UserOperationV8,
signer: AkSigner,
chainId: bigint,
overrides: CaliburSignatureOverrides = {},
): Promise<string> {
const scheme = pickScheme(signer, Calibur7702Account.ACCEPTED_SIGNING_SCHEMES, {
accountName: "Calibur (raw ECDSA over userOpHash)",
signerIndex: 0,
});
const hash = createUserOperationHash(
userOperation,
this.entrypointAddress,
chainId,
) as `0x${string}`;
const context: SignContext<UserOperationV8> = {
userOperation,
chainId,
entryPoint: this.entrypointAddress,
};
const typedData =
scheme === "typedData"
? Calibur7702Account.getUserOperationEip712Data(userOperation, chainId, {
entrypointAddress: this.entrypointAddress,
})
: undefined;
const signature = await invokeSigner(signer, scheme, { hash, typedData, context });
const keyHash = overrides.keyHash ?? ROOT_KEY_HASH;
const hookData = overrides.hookData ?? "0x";
return Calibur7702Account.wrapSignature(keyHash, signature, hookData);
}
/**
* Format a WebAuthn (passkey) assertion into Calibur's signature format.
* The challenge for the WebAuthn assertion should be `abi.encode(userOpHash)`.
*
* @param keyHash - The key hash of the registered passkey (from {@link getKeyHash})
* @param webAuthnAuth - WebAuthn assertion data from the browser
* @param overrides - Optional signature overrides (e.g., hookData)
* @returns Hex-encoded wrapped signature
*/
public formatWebAuthnSignature(
keyHash: string,
webAuthnAuth: WebAuthnSignatureData,
overrides: CaliburSignatureOverrides = {},
): string {
const hookData = overrides.hookData ?? "0x";
// Encode as a struct/tuple — Calibur decodes with:
// abi.decode(signature, (WebAuthn.WebAuthnAuth))
// which expects struct-wrapped encoding (extra offset for dynamic tuple).
const webAuthnEncoded = encodeAbiParameters(
["(bytes,string,uint256,uint256,uint256,uint256)"],
[
[
webAuthnAuth.authenticatorData,
webAuthnAuth.clientDataJSON,
webAuthnAuth.challengeIndex,
webAuthnAuth.typeIndex,
webAuthnAuth.r,
webAuthnAuth.s,
],
],
);
return encodeAbiParameters(["bytes32", "bytes", "bytes"], [keyHash, webAuthnEncoded, hookData]);
}
/**
* 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
*/
public async sendUserOperation(
userOperation: UserOperationV8,
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);
}
// ─── Key Helpers (static) ────────────────────────────────────────────
/**
* Create a secp256k1 key descriptor from an Ethereum address.
* @param address - The Ethereum address (EOA public address)
* @returns A {@link CaliburKey} with type Secp256k1
*/
public static createSecp256k1Key(address: string): CaliburKey {
return {
keyType: CaliburKeyType.Secp256k1,
publicKey: encodeAbiParameters(["address"], [address]),
};
}
/**
* Create a WebAuthn P-256 key descriptor from public key coordinates.
* @param x - The x coordinate of the P-256 public key
* @param y - The y coordinate of the P-256 public key
* @returns A {@link CaliburKey} with type WebAuthnP256
*/
public static createWebAuthnP256Key(x: bigint, y: bigint): CaliburKey {
return {
keyType: CaliburKeyType.WebAuthnP256,
publicKey: encodeAbiParameters(["uint256", "uint256"], [x, y]),
};
}
/**
* Create a raw P-256 key descriptor from public key coordinates.
* @param x - The x coordinate of the P-256 public key
* @param y - The y coordinate of the P-256 public key
* @returns A {@link CaliburKey} with type P256
*/
public static createP256Key(x: bigint, y: bigint): CaliburKey {
return {
keyType: CaliburKeyType.P256,
publicKey: encodeAbiParameters(["uint256", "uint256"], [x, y]),
};
}
/**
* Compute the key hash for a Calibur key.
* Uses double hashing: `keccak256(abi.encode(uint8 keyType, bytes32 keccak256(publicKey)))`.
*
* @param key - The key to hash
* @returns The key hash as a bytes32 hex string
*/
public static getKeyHash(key: CaliburKey): string {
const innerHash = keccak256(key.publicKey);
const encoded = encodeAbiParameters(["uint8", "bytes32"], [key.keyType, innerHash]);
return keccak256(encoded);
}
/**
* Pack key settings into a single uint256 value.
* Layout: `(isAdmin << 200) | (expiration << 160) | hook`
*
* @param settings - The key settings to pack
* @returns The packed settings as a bigint
*/
public static packKeySettings(settings: CaliburKeySettings): bigint {
const hook = BigInt(settings.hook ?? ZeroAddress);
const expiration = BigInt(settings.expiration ?? 0);
const isAdmin = settings.isAdmin ? 1n : 0n;
if (expiration < 0n || expiration >= 1n << 40n) {
// the on-chain field is uint40; an oversized value (e.g. a millisecond
// timestamp) would bleed into the isAdmin bit at position 200
throw new RangeError(
"expiration must be a unix timestamp in seconds that fits in 40 bits, " +
`got ${expiration}. Did you pass milliseconds instead of seconds?`,
);
}
if (hook < 0n || hook >= 1n << 160n) {
throw new RangeError("hook must be a valid 20-byte address.");
}
return (isAdmin << 200n) | (expiration << 160n) | hook;
}
/**
* Unpack a uint256 settings value into a {@link CaliburKeySettingsResult} object.
*
* @param packed - The packed settings value
* @returns Parsed key settings with all fields populated
*/
public static unpackKeySettings(packed: bigint): CaliburKeySettingsResult {
const hook = `0x${(packed & ((1n << 160n) - 1n)).toString(16).padStart(40, "0")}`;
const expiration = Number((packed >> 160n) & ((1n << 40n) - 1n));
const isAdmin = ((packed >> 200n) & 1n) === 1n;
return { hook, expiration, isAdmin };
}
// ─── Key Management (static, return SimpleMetaTransaction) ───────────
/**
* Create meta-transactions to register a new key on the Calibur account.
* Returns **two transactions**: `[register, update]`. Both must be included
* in the same UserOperation.
*
* **Safety guardrail:** This method never sets `isAdmin: true` regardless
* of input settings. Developers who need admin keys must encode calldata themselves.
*
* @param key - The key to register
* @param settings - Optional key settings (isAdmin is always forced to false)
* @returns A tuple of exactly two {@link SimpleMetaTransaction}s: [registerTx, updateTx].
* Both must be included in the same UserOperation.
*/
public static createRegisterKeyMetaTransactions(
key: CaliburKey,
settings: CaliburKeySettings = {},
): [SimpleMetaTransaction, SimpleMetaTransaction] {
if (settings.isAdmin === true) {
throw new AbstractionKitError(
"BAD_DATA",
"createRegisterKeyMetaTransactions does not allow setting " +
"isAdmin to true. Encode the calldata manually for admin keys.",
);
}
// Register: register((uint8 keyType, bytes publicKey))
const registerCallData =
REGISTER_SELECTOR +
encodeAbiParameters(["(uint8,bytes)"], [[key.keyType, key.publicKey]]).slice(2);
// Update: update(bytes32 keyHash, uint256 packedSettings)
const safeSettings: CaliburKeySettings = {
...settings,
isAdmin: false,
};
const keyHash = Calibur7702Account.getKeyHash(key);
const packedSettings = Calibur7702Account.packKeySettings(safeSettings);
const updateCallData =
UPDATE_SELECTOR + encodeAbiParameters(["bytes32", "uint256"], [keyHash, packedSettings]).slice(2);
return [
{ to: ZeroAddress, value: 0n, data: registerCallData },
{ to: ZeroAddress, value: 0n, data: updateCallData },
] as [SimpleMetaTransaction, SimpleMetaTransaction];
}
/**
* Create a meta-transaction to revoke a key from the Calibur account.
*
* @param keyHash - The key hash to revoke
* @returns A {@link SimpleMetaTransaction} that calls `revoke(bytes32)`
*/
public static createRevokeKeyMetaTransaction(keyHash: string): SimpleMetaTransaction {
const callData = REVOKE_SELECTOR + encodeAbiParameters(["bytes32"], [keyHash]).slice(2);
return { to: ZeroAddress, value: 0n, data: callData };
}
/**
* Create meta-transactions to revoke ALL registered keys on this account.
* Queries the on-chain key list and returns one `revoke(bytes32)` call per key.
*
* **Recommended before revoking EIP-7702 delegation** to prevent stale keys
* from becoming active again if the EOA re-delegates later.
*
* @param providerRpc - JSON-RPC endpoint to query registered keys
* @returns Array of {@link SimpleMetaTransaction}s — one revoke call per key.
* Empty array if no keys are registered.
*
* @example
* ```typescript
* // Step 1: Revoke all keys (send as UserOp)
* const revokeTxs = await account.createRevokeAllKeysMetaTransactions(providerRpc);
* if (revokeTxs.length > 0) {
* const userOp = await account.createUserOperation(revokeTxs, providerRpc, bundlerRpc);
* userOp.signature = account.signUserOperation(userOp, privateKey, chainId);
* const response = await account.sendUserOperation(userOp, bundlerRpc);
* await response.included();
* }
*
* // Step 2: Revoke delegation
* const rawTx = await account.createRevokeDelegationRawTransaction(chainId, privateKey, providerRpc);
* ```
*/
public async createRevokeAllKeysMetaTransactions(
providerRpc: string | Transport | JsonRpcNode,
): Promise<SimpleMetaTransaction[]> {
const keys = await this.getKeys(providerRpc);
return keys.map((key) => {
const keyHash = Calibur7702Account.getKeyHash(key);
return Calibur7702Account.createRevokeKeyMetaTransaction(keyHash);
});
}
/**
* Create a signed raw transaction that revokes EIP-7702 delegation,
* restoring this account to a plain EOA.
*
* **Recommended flow:** Call {@link createRevokeAllKeysMetaTransactions} first
* and send the cleanup UserOp, then call this method to revoke delegation.