Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support Kernel V1 #98

Merged
merged 11 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions packages/core/accounts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ export {
KERNEL_ADDRESSES,
EIP1271ABI
} from "./kernel/createKernelAccount.js"
export { createKernelV1Account } from "./kernel/v1/createKernelV1Account.js"
export { addressToEmptyAccount } from "./addressToEmptyAccount.js"
export * from "./utils/index.js"
9 changes: 1 addition & 8 deletions packages/core/accounts/kernel/createKernelAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import type {
} from "../../types/kernel.js"
import { getKernelVersion } from "../../utils.js"
import { wrapSignatureWith6492 } from "../utils/6492.js"
import { parseFactoryAddressAndCallDataFromAccountInitCode } from "../utils/index.js"
import {
isKernelPluginManager,
toKernelPluginManager
Expand Down Expand Up @@ -207,14 +208,6 @@ const getAccountAddress = async <
})
}

const parseFactoryAddressAndCallDataFromAccountInitCode = (
initCode: Hex
): [Address, Hex] => {
const factoryAddress = `0x${initCode.substring(2, 42)}` as Address
const factoryCalldata = `0x${initCode.substring(42)}` as Hex
return [factoryAddress, factoryCalldata]
}

/**
* Build a kernel smart account from a private key, that use the ECDSA signer behind the scene
* @param client
Expand Down
276 changes: 276 additions & 0 deletions packages/core/accounts/kernel/v1/createKernelV1Account.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
import {
getAccountNonce,
getSenderAddress,
getUserOperationHash
} from "permissionless"
import {
SignTransactionNotSupportedBySmartAccount,
type SmartAccountSigner
} from "permissionless/accounts"
import {
type Address,
type Chain,
type Client,
type Hash,
type Hex,
type LocalAccount,
type Transport,
type TypedData,
type TypedDataDefinition,
concatHex,
encodeFunctionData
} from "viem"
import { toAccount } from "viem/accounts"
import {
getBytecode,
getChainId,
signMessage,
signTypedData
} from "viem/actions"
import { type KernelEncodeCallDataArgs } from "../../../types/kernel.js"
import { wrapSignatureWith6492 } from "../../utils/6492.js"
import { parseFactoryAddressAndCallDataFromAccountInitCode } from "../../utils/index.js"
import { type KernelSmartAccount } from "../createKernelAccount.js"
import {
MULTISEND_ADDRESS,
encodeMultiSend,
multiSendAbi
} from "./multisend.js"

export type KernelV1SmartAccount<
transport extends Transport = Transport,
chain extends Chain | undefined = Chain | undefined
> = Omit<KernelSmartAccount<transport, chain>, "kernelPluginManager">

const createAccountAbi = [
{
inputs: [
{ internalType: "address", name: "_owner", type: "address" },
{ internalType: "uint256", name: "_index", type: "uint256" }
],
name: "createAccount",
outputs: [
{
internalType: "contract EIP1967Proxy",
name: "proxy",
type: "address"
}
],
stateMutability: "nonpayable",
type: "function"
}
]

const executeAndRevertAbi = [
{
inputs: [
{ internalType: "address", name: "to", type: "address" },
{ internalType: "uint256", name: "value", type: "uint256" },
{ internalType: "bytes", name: "data", type: "bytes" },
{ internalType: "enum Operation", name: "operation", type: "uint8" }
],
name: "executeAndRevert",
outputs: [],
stateMutability: "nonpayable",
type: "function"
}
]

const KERNEL_V1_ADDRESSES: {
FACTORY_ADDRESS: Address
ENTRYPOINT_V0_6: Address
} = {
FACTORY_ADDRESS: "0x4E4946298614FC299B50c947289F4aD0572CB9ce",
ENTRYPOINT_V0_6: "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789"
}

export async function createKernelV1Account<
TTransport extends Transport = Transport,
TChain extends Chain | undefined = Chain | undefined,
TSource extends string = string,
TAddress extends Address = Address
>(
client: Client<TTransport, TChain, undefined>,
{
signer,
entrypoint = KERNEL_V1_ADDRESSES.ENTRYPOINT_V0_6,
index = 0n
}: {
signer: SmartAccountSigner<TSource, TAddress>
entrypoint?: Address
index?: bigint
}
): Promise<KernelV1SmartAccount<TTransport, TChain>> {
if (entrypoint !== KERNEL_V1_ADDRESSES.ENTRYPOINT_V0_6) {
throw new Error("Only EntryPoint 0.6 is supported")
}

const viemSigner: LocalAccount = {
...signer,
signTransaction: (_, __) => {
throw new SignTransactionNotSupportedBySmartAccount()
}
} as LocalAccount

// Fetch chain id
const chainId = await getChainId(client)

const generateInitCode = async (): Promise<Hex> => {
return concatHex([
KERNEL_V1_ADDRESSES.FACTORY_ADDRESS,
encodeFunctionData({
abi: createAccountAbi,
functionName: "createAccount",
args: [signer.address, index]
})
]) as Hex
}

const initCode = await generateInitCode()
const accountAddress = await getSenderAddress(client, {
initCode,
entryPoint: entrypoint
})

if (!accountAddress) throw new Error("Account address not found")

const account = toAccount({
address: accountAddress,
async signMessage({ message }) {
const [isDeployed, signature] = await Promise.all([
isAccountDeployed(),
signer.signMessage({ message })
])
return create6492Signature(isDeployed, signature)
},
async signTransaction(_, __) {
throw new SignTransactionNotSupportedBySmartAccount()
},
async signTypedData<
const TTypedData extends TypedData | Record<string, unknown>,
TPrimaryType extends
| keyof TTypedData
| "EIP712Domain" = keyof TTypedData
>(typedData: TypedDataDefinition<TTypedData, TPrimaryType>) {
return signTypedData<TTypedData, TPrimaryType, TChain, undefined>(
client,
{
account: viemSigner,
...typedData
}
)
}
})

const isAccountDeployed = async (): Promise<boolean> => {
const contractCode = await getBytecode(client, {
address: accountAddress
})

return (contractCode?.length ?? 0) > 2
}

const create6492Signature = async (
isDeployed: boolean,
signature: Hash
): Promise<Hash> => {
if (isDeployed) {
return signature
}

const [factoryAddress, factoryCalldata] =
parseFactoryAddressAndCallDataFromAccountInitCode(
await generateInitCode()
)

return wrapSignatureWith6492({
factoryAddress,
factoryCalldata,
signature
})
}

return {
...account,
client: client,
publicKey: accountAddress,
entryPoint: entrypoint,
source: "kernelSmartAccount",
generateInitCode,
async getNonce() {
return getAccountNonce(client, {
sender: accountAddress,
entryPoint: entrypoint
})
},
async signUserOperation(userOperation) {
const hash = getUserOperationHash({
userOperation: {
...userOperation,
signature: "0x"
},
entryPoint: entrypoint,
chainId: chainId
})
const signature = await signMessage(client, {
account: viemSigner,
message: { raw: hash }
})
return signature
},
async getInitCode() {
if (await isAccountDeployed()) {
return "0x"
} else {
return generateInitCode()
}
},
async encodeCallData(_tx) {
const tx = _tx as KernelEncodeCallDataArgs

if (Array.isArray(tx)) {
// Encode a batched call using multiSend
const multiSendCallData = encodeFunctionData({
abi: multiSendAbi,
functionName: "multiSend",
args: [encodeMultiSend(tx)]
})

return encodeFunctionData({
abi: executeAndRevertAbi,
functionName: "executeAndRevert",
args: [MULTISEND_ADDRESS, 0n, multiSendCallData, 1n]
})
}

// Default to `call`
if (!tx.callType || tx.callType === "call") {
if (tx.to.toLowerCase() === accountAddress.toLowerCase()) {
return tx.data
}

return encodeFunctionData({
abi: executeAndRevertAbi,
functionName: "executeAndRevert",
args: [tx.to, tx.value || 0n, tx.data, 0n]
})
}

if (tx.callType === "delegatecall") {
return encodeFunctionData({
abi: executeAndRevertAbi,
functionName: "executeAndRevert",
args: [tx.to, tx.value || 0n, tx.data, 1n]
})
}

throw new Error("Invalid call type")
},
async encodeDeployCallData() {
return "0x"
},
async getDummySignature() {
return "0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c"
}
}
}
43 changes: 43 additions & 0 deletions packages/core/accounts/kernel/v1/multisend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { type Address, type Hex, encodePacked, toBytes } from "viem"
import {
type CallType,
type KernelEncodeCallDataArgs
} from "../../../types/index.js"

export const MULTISEND_ADDRESS = "0x8ae01fcf7c655655ff2c6ef907b8b4718ab4e17c"

export const multiSendAbi = [
{
type: "function",
name: "multiSend",
inputs: [{ type: "bytes", name: "transactions" }]
}
]

const encodeCall = (call: {
to: Address
value: bigint
data: Hex
callType: CallType | undefined
}): string => {
const data = toBytes(call.data)
const encoded = encodePacked(
["uint8", "address", "uint256", "uint256", "bytes"],
[
call.callType === "delegatecall" ? 1 : 0,
call.to,
call.value || 0n,
BigInt(data.length),
call.data
]
)
return encoded.slice(2)
}

export const encodeMultiSend = (calls: KernelEncodeCallDataArgs): Hex => {
if (!Array.isArray(calls)) {
throw new Error("Invalid multiSend calls, should use an array of calls")
}

return `0x${calls.map((call) => encodeCall(call)).join("")}`
}
9 changes: 9 additions & 0 deletions packages/core/accounts/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { toKernelPluginManager } from "./toKernelPluginManager.js"
export { toKernelPluginManager }

import type { Address, Hex } from "viem"
import { verifyEIP6492Signature } from "./6492.js"
export { verifyEIP6492Signature }

export const parseFactoryAddressAndCallDataFromAccountInitCode = (
initCode: Hex
): [Address, Hex] => {
const factoryAddress = `0x${initCode.substring(2, 42)}` as Address
const factoryCalldata = `0x${initCode.substring(42)}` as Hex
return [factoryAddress, factoryCalldata]
}
6 changes: 2 additions & 4 deletions packages/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export {
createKernelAccount,
createKernelV1Account,
type KernelSmartAccount,
KERNEL_ADDRESSES,
addressToEmptyAccount,
Expand Down Expand Up @@ -34,8 +35,5 @@ export { KernelFactoryAbi } from "./accounts/kernel/abi/KernelFactoryAbi.js"
export { TokenActionsAbi } from "./accounts/kernel/abi/TokenActionsAbi.js"
export * as constants from "./constants.js"
export * from "./utils.js"
export {
gasTokenAddresses,
type TokenSymbolsMap
} from "./gasTokenAddresses.js"
export { gasTokenAddresses, type TokenSymbolsMap } from "./gasTokenAddresses.js"
export { verifyEIP6492Signature } from "./accounts/utils/index.js"
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zerodev/sdk",
"version": "5.1.8",
"version": "5.1.9",
"author": "ZeroDev",
"main": "./_cjs/index.js",
"module": "./_esm/index.js",
Expand Down
Loading
Loading