-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathkernel.ts
504 lines (468 loc) · 15.1 KB
/
kernel.ts
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
import hre from "hardhat";
import {
encodeAbiParameters,
encodeFunctionData,
encodePacked,
getAbiItem,
getContract,
getFunctionSelector,
hexToBigInt,
keccak256,
pad,
parseAbiParameters,
parseEther,
toHex,
walletActions,
zeroAddress,
} from "viem";
import {AccountConfig, AccountDataV06} from "../accounts";
import {KERNEL_ARTIFACTS} from "../artifacts/kernel";
import {getEntryPointV06} from "../utils/entryPoint";
import {getUnsignedUserOp} from "../utils/userOp";
async function accountFixture(): Promise<AccountDataV06> {
const [walletClient] = await hre.viem.getWalletClients();
const publicClient = await hre.viem.getPublicClient();
const testClient = (await hre.viem.getTestClient()).extend(walletActions);
for (const {address, bytecode} of Object.values(KERNEL_ARTIFACTS)) {
await hre.network.provider.send("hardhat_setCode", [address, bytecode]);
}
await hre.network.provider.send("evm_setNextBlockTimestamp", [2_000_000_000]); // Set the time to 2 billion
const kernelFactory = getContract({
address: KERNEL_ARTIFACTS.KernelFactory.address,
abi: KERNEL_ARTIFACTS.KernelFactory.abi,
publicClient,
walletClient,
});
const dummySig =
"0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c";
await testClient.impersonateAccount({address: zeroAddress});
await hre.network.provider.send("hardhat_setBalance", [
zeroAddress,
toHex(parseEther("10000")),
]);
await testClient.writeContract({
address: KERNEL_ARTIFACTS.KernelFactory.address,
abi: KERNEL_ARTIFACTS.KernelFactory.abi,
functionName: "setImplementation",
args: [KERNEL_ARTIFACTS.Kernel.address, true],
account: zeroAddress,
});
await testClient.stopImpersonatingAccount({address: zeroAddress});
const permissionAbi = parseAbiParameters([
"Permission permission",
"struct Permission { address target; uint256 valueLimit; bytes4 sig; ParamRule[] rules; uint8 operation; }",
"struct ParamRule { uint256 offset; uint8 condition; bytes32 param; }",
]);
const validUntil = Number(hexToBigInt("0x7d2b7500")); // 2_100_000_000
const validAfter = Number(hexToBigInt("0x713fb300")); // 1_900_000_000
const keyDataHolder = {
permissionObjects: null as any[] | null,
permissionHashes: null as `0x${string}`[] | null,
};
const initializeBytecode = (owner: `0x${string}`) =>
encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "initialize",
}),
],
args: [
KERNEL_ARTIFACTS.KernelECDSAValidator.address,
encodePacked(["address"], [owner]),
],
});
const entryPoint = getEntryPointV06({publicClient, walletClient});
return {
entryPoint,
createAccount: async (salt, ownerAddress) => {
return await kernelFactory.write.createAccount([
KERNEL_ARTIFACTS.Kernel.address,
initializeBytecode(ownerAddress),
salt,
]);
},
getAccountAddress: async (salt, ownerAddress) => {
return await kernelFactory.read.getAccountAddress([
initializeBytecode(ownerAddress),
salt,
]);
},
getOwnerSignature: async (owner, userOp, entryPoint) => {
const userOpHash = await entryPoint.read.getUserOpHash([userOp]);
const signature = await owner.signMessage({
message: {raw: userOpHash},
});
return encodePacked(["bytes4", "bytes"], ["0x00000000", signature]);
},
encodeUserOpExecute: (to, value, data) => {
return encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "execute",
}),
],
args: [to, value, data, 0], // Operation.CALL = 0
});
},
encodeRuntimeExecute: async (to, value, data) => {
return encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "execute",
}),
],
args: [to, value, data, 0], // Operation.CALL = 0
});
},
getDummySignature: (_userOp) => {
return encodePacked(["bytes4", "bytes"], ["0x00000000", dummySig]);
},
getInitCode: (salt, ownerAddress) => {
return encodePacked(
["address", "bytes"],
[
kernelFactory.address,
encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.KernelFactory.abi,
name: "createAccount",
}),
],
args: [
KERNEL_ARTIFACTS.Kernel.address,
initializeBytecode(ownerAddress),
salt,
],
}),
],
);
},
installSessionKeyPlugin: async (accountAddr, owner) => {
const sessionKeyValidator = getContract({
address: KERNEL_ARTIFACTS.KernelSessionKeyValidator.address,
abi: KERNEL_ARTIFACTS.KernelSessionKeyValidator.abi,
publicClient,
walletClient: owner,
});
const executeSelector = getFunctionSelector(
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "execute",
}),
);
const userOp = getUnsignedUserOp({
sender: accountAddr,
nonce: 0n,
initCode: "0x" as `0x${string}`,
callData: encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "execute",
}),
],
args: [zeroAddress, 0n, executeSelector, 0], // calling "execute" on the zero address
}),
getDummySignature: (userOp) => `0x`,
});
const userOpHash = await entryPoint.read.getUserOpHash([userOp]);
const validUntil = Number(hexToBigInt("0x7d2b7500")); // 2_100_000_000
const validAfter = Number(hexToBigInt("0x713fb300")); // 1_900_000_000
const permissionEncoding = encodeAbiParameters(permissionAbi, [
{
valueLimit: 0n,
target: zeroAddress,
sig: executeSelector,
rules: [],
operation: 0,
},
]);
const leafHash = keccak256(permissionEncoding);
const sessionKey = owner; // re-use the owner as an initial session key, will get added later
const merkleRoot = leafHash; // Tree of size 1
const enableDataInstallValidator = encodePacked(
["address", "bytes32", "uint48", "uint48", "address"],
[
sessionKey.account.address, // session key
merkleRoot, // merkle root
validAfter, // validafter
validUntil, // validuntil
zeroAddress, // paymaster
],
);
const validatorData = encodePacked(
["uint48", "uint48", "address"],
[
validAfter,
validUntil,
KERNEL_ARTIFACTS.KernelSessionKeyValidator.address,
],
);
const enableSig = await owner.signTypedData({
domain: {
name: "Kernel",
version: "0.2.1",
chainId: 31337,
verifyingContract: accountAddr,
},
types: {
ValidatorApproved: [
{name: "sig", type: "bytes4"},
{name: "validatorData", type: "uint256"},
{name: "executor", type: "address"},
{name: "enableData", type: "bytes"},
],
},
primaryType: "ValidatorApproved",
message: {
sig: executeSelector,
validatorData: hexToBigInt(validatorData),
executor: zeroAddress,
enableData: enableDataInstallValidator,
},
});
// await sessionKeyValidator.write.enable([
// enableDataInstallValidator])
/**
* userop sig structure:
*
* 0:4 - mode 0x00000002 for JIT
* 4:10 - validAfter
* 10:16 - validUntil
* 16:36 - validator addr
* 36:56 - executor (accountAddr)
* 56:88 - enableDataLen (a)
* 88:88+a - enableData
* 88+a:110+a - enableSigLen (b)
* 110+a:110+a+b - enableSig (c)
* 110+a+b: - userOpSig
*/
userOp.signature = encodePacked(
[
"bytes4", // Mode
"uint48", // validAfter (validator)
"uint48", // validUntil (validator)
"address", // validator
"address", // executor
"uint256", // enableDataLen
"bytes", // enableData
"uint256", // enableSigLen
"bytes", // enableSig
// start of validator-specific signature
"address", // session key
"bytes", // uo hash session key signature
"bytes", // Permission used (including merkle proof)
],
[
"0x00000002",
validAfter,
validUntil,
KERNEL_ARTIFACTS.KernelSessionKeyValidator.address,
zeroAddress, // executor
BigInt((enableDataInstallValidator.length - 2) / 2), // enableDataLen
enableDataInstallValidator,
BigInt(65),
enableSig,
sessionKey.account.address,
await sessionKey.signMessage({
message: {raw: userOpHash},
}),
encodeAbiParameters(
[...permissionAbi, {name: "proof", type: "bytes32[]"}],
[
{
valueLimit: 0n,
target: zeroAddress,
sig: executeSelector,
rules: [],
operation: 0,
},
[],
],
),
],
);
// console.log("is installed: ", await sessionKeyValidator.read.sessionData([sessionKey.account.address, accountAddr]));
await entryPoint.write.handleOps([[userOp], owner.account.address]);
// console.log("is installed: ", await sessionKeyValidator.read.sessionData([sessionKey.account.address, accountAddr]));
},
addSessionKeyCalldata: (key, target, tokens, spendLimit, account) => {
// for erc20 transfers
const permissionObject1 = {
valueLimit: 0n,
target: tokens[0].address, // only support the first token for now
sig: "0xa9059cbb" as `0x${string}`, // transfer(address,uint256)
rules: [
{
offset: BigInt(32), // offset of amount
condition: 4, // LESS_THAN_OR_EQUAL
param: pad(toHex(spendLimit), {size: 32, dir: "left"}),
},
],
operation: 0,
};
// for native transfers
const permissionObject2 = {
valueLimit: parseEther("0.5"),
target,
sig: "0x00000000" as `0x${string}`,
rules: [],
operation: 0,
};
const permissionEncoding1 = encodeAbiParameters(permissionAbi, [
permissionObject1,
]);
const permissionEncoding2 = encodeAbiParameters(permissionAbi, [
permissionObject2,
]);
// NOTE: this only works if the hash of the first permission object is less than the hash of the second permission object.
keyDataHolder.permissionObjects = [permissionObject1, permissionObject2];
keyDataHolder.permissionHashes = [
keccak256(permissionEncoding1),
keccak256(permissionEncoding2),
];
const merkleRoot = keccak256(
encodePacked(
["bytes32", "bytes32"],
[
keyDataHolder.permissionHashes[0],
keyDataHolder.permissionHashes[1],
],
),
);
return encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "execute",
}),
],
args: [
KERNEL_ARTIFACTS.KernelSessionKeyValidator.address,
0n,
encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.KernelSessionKeyValidator.abi,
name: "enable",
}),
],
args: [
encodePacked(
[
"address", // sessionKey
"bytes32", // merkleRoot
"uint48", // validAfter
"uint48", // validUntil
"address", // paymaster
],
[key, merkleRoot, validAfter, validUntil, zeroAddress],
),
],
}),
0, // Operation.CALL = 0
],
});
},
useSessionKeyERC20TransferCalldata: (token, key, to, amount) => {
return encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "execute",
}),
],
args: [
token.address,
0n,
encodeFunctionData({
abi: [
getAbiItem({
abi: token.abi,
name: "transfer",
}),
],
args: [to, amount],
}),
0, // Operation.CALL = 0
],
});
},
useSessionKeyNativeTokenTransferCalldata: (key, to, amount) => {
return encodeFunctionData({
abi: [
getAbiItem({
abi: KERNEL_ARTIFACTS.Kernel.abi,
name: "execute",
}),
],
args: [
to,
amount,
"0x00000000", // data, needs to be the zero selector for the session key permission
0, // Operation.CALL = 0
],
});
},
getSessionKeySignature: async (key, userOp, entryPoint) => {
// for now, assume it is the session key used to perform the erc-20 transfer
const userOpHash = await entryPoint.read.getUserOpHash([userOp]);
const keySignature = await key.signMessage({
message: {raw: userOpHash},
});
if (userOp.callData.slice(330, 338) === "a9059cbb") {
// calling "transfer" on an erc-20 token
return encodePacked(
[
"bytes4", // mode
"address", // session key
"bytes", // uo hash session key signature
"bytes", // Permission used (including merkle proof)
],
[
"0x00000001",
key.account.address,
keySignature,
encodeAbiParameters(
[...permissionAbi, {name: "proof", type: "bytes32[]"}],
[
keyDataHolder.permissionObjects![0],
[keyDataHolder.permissionHashes![1]],
],
),
],
);
} else {
// This is the native transfer test
return encodePacked(
[
"bytes4", // mode
"address", // session key
"bytes", // uo hash session key signature
"bytes", // Permission used (including merkle proof)
],
[
"0x00000001",
key.account.address,
keySignature,
encodeAbiParameters(
[...permissionAbi, {name: "proof", type: "bytes32[]"}],
[
keyDataHolder.permissionObjects![1],
[keyDataHolder.permissionHashes![0]],
],
),
],
);
}
},
};
}
export const kernel: AccountConfig = {
name: "Kernel v2.1",
accountFixture,
};