diff --git a/build-all.sh b/build-all.sh index 0854ab45..cbe44ceb 100644 --- a/build-all.sh +++ b/build-all.sh @@ -7,7 +7,7 @@ NC='\033[0m' # No Color # Define the list of directories containing package.json files that should be built. # Assuming that all packages are directly under the 'packages' and 'plugins' directories. -DIRECTORIES=("packages/*" "plugins/*" "wallet") +DIRECTORIES=("packages/*" "plugins/*") # Arrays to keep track of build statuses SUCCEEDED=() diff --git a/bun.lockb b/bun.lockb index f53da3be..ea7a390b 100755 Binary files a/bun.lockb and b/bun.lockb differ diff --git a/package.json b/package.json index b5a5af9b..a2885d29 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,5 @@ { - "workspaces": [ - "packages/*", - "templates/*", - "plugins/*", - "wallet", - "walletconnect" - ], + "workspaces": ["packages/*", "templates/*", "plugins/*"], "private": true, "author": "ZeroDev", "type": "module", diff --git a/packages/presets/.gitignore b/packages/presets/.gitignore deleted file mode 100644 index 468f82a1..00000000 --- a/packages/presets/.gitignore +++ /dev/null @@ -1,175 +0,0 @@ -# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore - -# Logs - -logs -_.log -npm-debug.log_ -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -.pnpm-debug.log* - -# Caches - -.cache - -# Diagnostic reports (https://nodejs.org/api/report.html) - -report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json - -# Runtime data - -pids -_.pid -_.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover - -lib-cov - -# Coverage directory used by tools like istanbul - -coverage -*.lcov - -# nyc test coverage - -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) - -.grunt - -# Bower dependency directory (https://bower.io/) - -bower_components - -# node-waf configuration - -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) - -build/Release - -# Dependency directories - -node_modules/ -jspm_packages/ - -# Snowpack dependency directory (https://snowpack.dev/) - -web_modules/ - -# TypeScript cache - -*.tsbuildinfo - -# Optional npm cache directory - -.npm - -# Optional eslint cache - -.eslintcache - -# Optional stylelint cache - -.stylelintcache - -# Microbundle cache - -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history - -.node_repl_history - -# Output of 'npm pack' - -*.tgz - -# Yarn Integrity file - -.yarn-integrity - -# dotenv environment variable files - -.env -.env.development.local -.env.test.local -.env.production.local -.env.local - -# parcel-bundler cache (https://parceljs.org/) - -.parcel-cache - -# Next.js build output - -.next -out - -# Nuxt.js build / generate output - -.nuxt -dist - -# Gatsby files - -# Comment in the public line in if your project uses Gatsby and not Next.js - -# https://nextjs.org/blog/next-9-1#public-directory-support - -# public - -# vuepress build output - -.vuepress/dist - -# vuepress v2.x temp and cache directory - -.temp - -# Docusaurus cache and generated files - -.docusaurus - -# Serverless directories - -.serverless/ - -# FuseBox cache - -.fusebox/ - -# DynamoDB Local files - -.dynamodb/ - -# TernJS port file - -.tern-port - -# Stores VSCode versions used for testing VSCode extensions - -.vscode-test - -# yarn v2 - -.yarn/cache -.yarn/unplugged -.yarn/build-state.yml -.yarn/install-state.gz -.pnp.* - -# IntelliJ based IDEs -.idea - -# Finder (MacOS) folder config -.DS_Store diff --git a/packages/presets/CHANGELOG.md b/packages/presets/CHANGELOG.md deleted file mode 100644 index 22fcb6fe..00000000 --- a/packages/presets/CHANGELOG.md +++ /dev/null @@ -1,37 +0,0 @@ -# @zerodev/presets - -## 5.3.3 - -### Patch Changes - -- Patch for latest permissionless 0.1.45 support - -## 5.3.2 - -### Patch Changes - -- Pinned permissionless version >=0.1.18 <=0.1.29 - -## 5.3.1 - -### Patch Changes - -- Update viem to 2.16.3 - -## 5.3.0 - -### Minor Changes - -- Kernel v3.1 released. And kernel versioning update. Added kernelVersion param in the interface. - -## 5.3.0-alpha-0 - -### Minor Changes - -- Integrated Kernel v3.1 and added kernelVersion param in account and plugins interface - -## 5.2.2 - -### Patch Changes - -- Update permissionless@0.1.18 diff --git a/packages/presets/package.json b/packages/presets/package.json deleted file mode 100644 index a769b85d..00000000 --- a/packages/presets/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@zerodev/presets", - "version": "5.3.3", - "author": "ZeroDev", - "main": "./_cjs/index.js", - "module": "./_esm/index.js", - "types": "./_types/index.d.ts", - "typings": "./_types/index.d.ts", - "type": "module", - "devDependencies": { - "bun-types": "latest" - }, - "exports": { - ".": { - "types": "./_types/zerodev/index.d.ts", - "import": "./_esm/zerodev/index.js", - "default": "./_cjs/zerodev/index.js" - }, - "./zerodev": { - "types": "./_types/zerodev/index.d.ts", - "import": "./_esm/zerodev/index.js", - "default": "./_cjs/zerodev/index.js" - } - }, - "license": "MIT", - "files": [ - "_esm", - "_cjs", - "_types", - "./**/*.ts", - "!_esm/**/*.tsbuildinfo", - "!_cjs/**/*.tsbuildinfo", - "!_types/**/*.tsbuildinfo", - "!.env", - "!./**/*.test.ts", - "!.changeset" - ], - "scripts": { - "build": "bun run clean && bun run build:cjs && bun run build:esm && bun run build:types", - "build:cjs": "tsc --project ./tsconfig.build.json --module commonjs --outDir ./_cjs --removeComments --verbatimModuleSyntax false && printf '{\"type\":\"commonjs\"}' > ./_cjs/package.json", - "build:esm": "tsc --project ./tsconfig.build.json --module es2015 --outDir ./_esm && printf '{\"type\": \"module\",\"sideEffects\":false}' > ./_esm/package.json", - "build:types": "tsc --project ./tsconfig.build.json --module esnext --declarationDir ./_types --emitDeclarationOnly --declaration --declarationMap", - "clean": "rimraf _esm _cjs _types", - "changeset": "changeset", - "changeset:release": "bun run build && changeset publish", - "changeset:version": "changeset version && bun install --lockfile-only", - "format": "biome format . --write", - "lint": "biome check .", - "lint:fix": "bun run lint --apply" - }, - "peerDependencies": { - "typescript": "~5.3.0", - "@zerodev/sdk": "^5.2.1", - "@zerodev/ecdsa-validator": "^5.2.1", - "permissionless": ">=0.1.44 <=0.1.45", - "viem": ">=2.16.3 <2.18.0" - } -} diff --git a/packages/presets/tsconfig.build.json b/packages/presets/tsconfig.build.json deleted file mode 100644 index bc982798..00000000 --- a/packages/presets/tsconfig.build.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "../../templates/typescript/tsconfig.build.json", - "include": ["./"], - "exclude": ["./**/*.test.ts", "./**/*.test-d.ts", "./**/*.bench.ts"], - "compilerOptions": { - "moduleResolution": "node", - "sourceMap": true, - "rootDir": "./", - "baseUrl": "./", - } -} diff --git a/packages/presets/zerodev/index.ts b/packages/presets/zerodev/index.ts deleted file mode 100644 index 34b366f3..00000000 --- a/packages/presets/zerodev/index.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { signerToEcdsaValidator } from "@zerodev/ecdsa-validator" -import type { KernelAccountClient, KernelSmartAccount } from "@zerodev/sdk" -import type { SponsorUserOperationParameters } from "@zerodev/sdk" -import { - createKernelAccount, - createKernelAccountClient, - createZeroDevPaymasterClient -} from "@zerodev/sdk" -import type { GetKernelVersion } from "@zerodev/sdk/types" -import type { SmartAccountSigner } from "permissionless/accounts" -import type { EntryPoint } from "permissionless/types" -import type { Address, Chain, HttpTransport } from "viem" -import { http, createPublicClient, isAddress } from "viem" - -export type Provider = "STACKUP" | "PIMLICO" | "ALCHEMY" | "GELATO" - -const getZeroDevBundlerRPC = ( - projectId: string, - provider?: Provider -): string => { - let rpc = `https://rpc.zerodev.app/api/v2/bundler/${projectId}` - if (provider) { - rpc += `?bundlerProvider=${provider}` - } - return rpc -} - -const getZeroDevPaymasterRPC = ( - projectId: string, - provider?: Provider -): string => { - let rpc = `https://rpc.zerodev.app/api/v2/paymaster/${projectId}` - if (provider) { - rpc += `?paymasterProvider=${provider}` - } - return rpc -} - -// An enum type called "PAYMASTER" with the following values: -// - "NONE" -// - "SPONSOR" -// - "ERC20", which should wrap a string -export type ERC20Paymaster = Address -export type PaymasterType = "NONE" | "SPONSOR" | ERC20Paymaster - -function isERC20(value: PaymasterType): value is ERC20Paymaster { - return isAddress(value) -} - -// biome-ignore lint/suspicious/noExplicitAny: -function isValidPaymasterType(value: any): value is PaymasterType { - return value === "NONE" || value === "SPONSOR" || isERC20(value) -} - -export async function createEcdsaKernelAccountClient< - entryPoint extends EntryPoint, - TChain extends Chain | undefined = Chain | undefined, - TSource extends string = "custom", - TAddress extends Address = Address ->({ - chain, - projectId, - signer, - provider, - index, - paymaster = "SPONSOR", - entryPointAddress, - kernelVersion -}: { - chain: TChain - projectId: string - signer: SmartAccountSigner - paymaster: PaymasterType - entryPointAddress: entryPoint - kernelVersion: GetKernelVersion - provider?: Provider - index?: bigint -}): Promise< - KernelAccountClient< - entryPoint, - HttpTransport, - TChain, - KernelSmartAccount - > -> { - const publicClient = createPublicClient({ - transport: http(getZeroDevBundlerRPC(projectId, provider)), - chain - }) - - const ecdsaValidator = await signerToEcdsaValidator(publicClient, { - signer, - entryPoint: entryPointAddress, - kernelVersion - }) - - const account = await createKernelAccount(publicClient, { - plugins: { - sudo: ecdsaValidator - }, - index, - entryPoint: entryPointAddress, - kernelVersion - }) - - if (!isValidPaymasterType(paymaster)) { - throw new Error("Invalid paymaster type") - } - - const zerodevPaymaster = createZeroDevPaymasterClient({ - chain: chain, - transport: http(getZeroDevPaymasterRPC(projectId, provider)), - entryPoint: entryPointAddress - }) - - const kernelClient = createKernelAccountClient({ - account, - chain, - entryPoint: entryPointAddress, - bundlerTransport: http(getZeroDevBundlerRPC(projectId, provider)), - middleware: - paymaster !== "NONE" - ? { - sponsorUserOperation: async ({ userOperation }) => { - const _userOperation = - userOperation as SponsorUserOperationParameters["userOperation"] - if (isERC20(paymaster)) { - return zerodevPaymaster.sponsorUserOperation({ - userOperation: _userOperation, - entryPoint: entryPointAddress, - gasToken: paymaster - }) - } - return zerodevPaymaster.sponsorUserOperation({ - userOperation: _userOperation, - entryPoint: entryPointAddress - }) - } - } - : undefined - }) - - return kernelClient as unknown as KernelAccountClient< - entryPoint, - HttpTransport, - TChain, - KernelSmartAccount - > -} diff --git a/wallet/CHANGELOG.md b/wallet/CHANGELOG.md deleted file mode 100644 index 2d09f8fe..00000000 --- a/wallet/CHANGELOG.md +++ /dev/null @@ -1,75 +0,0 @@ -# @zerodev/wallet - -## 0.1.5 - -### Patch Changes - -- Patch for latest permissionless 0.1.45 support -- Updated dependencies - - @zerodev/permissions@5.4.6 - - @zerodev/passkey-validator@5.4.2 - - @zerodev/sdk@5.3.14 - - @zerodev/ecdsa-validator@5.3.3 - -## 0.1.4 - -### Patch Changes - -- fix: policy parsing in grantPermission - -## 0.1.3 - -### Patch Changes - -- chore: upgrade passkey validator - -## 0.1.1 - -### Patch Changes - -- fix: handle getCallsStatus - -## 0.1.0 - -### Minor Changes - -- Update viem to 2.16.3 and use sdk5.3.2 - -### Patch Changes - -- Updated dependencies - - @zerodev/permissions@5.3.1 - - @zerodev/passkey-validator@5.3.3 - - @zerodev/sdk@5.3.2 - - @zerodev/ecdsa-validator@5.3.1 - -## 0.0.10 - -### Patch Changes - -- fix: update @zerodev/passkey-validator@5.2.8 - -## 0.0.9 - -### Patch Changes - -- Lock dependency version - -## 0.0.9 - -### Patch Changes - -- Add support for entrypoint v0.6 to KernelEIP1193Provider - -## 0.0.8 - -### Patch Changes - -- fix: switch chain if not in conifg - -## 0.0.7 - -### Patch Changes - -- Add 7677 paymaster support in KernelEIP1193Provider -- Add all policies in @zerodev/permission@5.2.9 diff --git a/wallet/KernelEIP1193Provider.ts b/wallet/KernelEIP1193Provider.ts deleted file mode 100644 index 8b2d4069..00000000 --- a/wallet/KernelEIP1193Provider.ts +++ /dev/null @@ -1,613 +0,0 @@ -import { EventEmitter } from "events" -import { - deserializePermissionAccount, - serializePermissionAccount, - toPermissionValidator -} from "@zerodev/permissions" -import { toECDSASigner } from "@zerodev/permissions/signers" -import type { KernelAccountClient, KernelSmartAccount } from "@zerodev/sdk" -import { createKernelAccount, createKernelAccountClient } from "@zerodev/sdk" -import type { SponsorUserOperationReturnType } from "@zerodev/sdk/actions" -import { createZeroDevPaymasterClient } from "@zerodev/sdk/clients" -import { - type BundlerClient, - ENTRYPOINT_ADDRESS_V06, - ENTRYPOINT_ADDRESS_V07, - type EstimateUserOperationGasReturnType, - bundlerActions -} from "permissionless" -import { - type GetPaymasterDataParameters, - type GetPaymasterDataReturnType, - type GetPaymasterStubDataReturnType, - paymasterActionsEip7677 -} from "permissionless/experimental" -import type { - ENTRYPOINT_ADDRESS_V06_TYPE, - ENTRYPOINT_ADDRESS_V07_TYPE, - EntryPoint, - GetEntryPointVersion, - UserOperation -} from "permissionless/types" -import type { - Chain, - Client, - EIP1193Parameters, - EIP1193RequestFn, - Hash, - PublicActions, - PublicRpcSchema, - SendTransactionParameters, - Transport -} from "viem" -import { http, type Hex, isHex, toHex } from "viem" -import { generatePrivateKey, privateKeyToAccount } from "viem/accounts" -import type { - GetCallsParams, - GetCallsResult, - GrantPermissionsParams, - PaymasterServiceCapability, - SendCallsParams, - SendCallsResult, - SessionType -} from "./types" -import { getPolicies, validatePermissions } from "./utils/permissions" -import { KernelLocalStorage } from "./utils/storage" - -const WALLET_CAPABILITIES_STORAGE_KEY = "WALLET_CAPABILITIES" -const WALLET_PERMISSION_STORAGE_KEY = "WALLET_PERMISSION" - -export class KernelEIP1193Provider< - entryPoint extends EntryPoint -> extends EventEmitter { - private readonly storage = new KernelLocalStorage("ZDWALLET") - private kernelClient: KernelAccountClient< - entryPoint, - Transport, - Chain, - KernelSmartAccount - > - private bundlerClient: BundlerClient - - constructor( - kernelClient: KernelAccountClient< - entryPoint, - Transport, - Chain, - KernelSmartAccount - > - ) { - super() - if ( - typeof kernelClient.account !== "object" || - typeof kernelClient.chain !== "object" - ) { - throw new Error("invalid kernel client") - } - this.kernelClient = kernelClient as KernelAccountClient< - entryPoint, - Transport, - Chain, - KernelSmartAccount - > - - const permissions = - kernelClient.account.entryPoint === ENTRYPOINT_ADDRESS_V07 - ? { - supported: true, - permissionTypes: [ - "sudo", - "contract-call", - "rate-limit", - "gas-limit", - "signature" - ] - } - : { - supported: false - } - - const capabilities = { - [kernelClient.account.address]: { - [toHex(kernelClient.chain.id)]: { - atomicBatch: { - supported: true - }, - paymasterService: { - supported: true - }, - permissions - } - } - } - this.storeItemToStorage(WALLET_CAPABILITIES_STORAGE_KEY, capabilities) - this.bundlerClient = kernelClient.extend( - bundlerActions(kernelClient.account.entryPoint) - ) - } - - getChainId() { - return this.handleGetChainId() - } - - async request({ - method, - params = [] - }: EIP1193Parameters): ReturnType { - switch (method) { - case "eth_chainId": - return this.handleGetChainId() - case "eth_requestAccounts": - return this.handleEthRequestAccounts() - case "eth_accounts": - return this.handleEthAccounts() - case "eth_sendTransaction": - return this.handleEthSendTransaction(params) - case "eth_sign": - return this.handleEthSign(params as [string, string]) - case "personal_sign": - return this.handlePersonalSign(params as [string, string]) - case "eth_signTypedData": - case "eth_signTypedData_v4": - return this.handleEthSignTypedDataV4(params as [string, string]) - case "wallet_getCapabilities": - return this.handleWalletCapabilities() - case "wallet_sendCalls": - return this.handleWalletSendcalls(params as [SendCallsParams]) - case "wallet_getCallsStatus": - return this.handleWalletGetCallStatus( - params as [GetCallsParams] - ) - case "wallet_grantPermissions": - return this.handleWalletGrantPermissions( - params as [GrantPermissionsParams] - ) - case "wallet_switchEthereumChain": - return this.handleSwitchEthereumChain() - default: - return this.kernelClient.transport.request({ method, params }) - } - } - - private handleGetChainId() { - return this.kernelClient.chain.id - } - - private async handleEthRequestAccounts(): Promise { - if (!this.kernelClient.account) { - return [] - } - return [this.kernelClient.account.address] - } - - private async handleEthAccounts(): Promise { - if (!this.kernelClient.account) { - return [] - } - return [this.kernelClient.account.address] - } - - private async handleEthSendTransaction(params: unknown): Promise { - const [tx] = params as [SendTransactionParameters] - return this.kernelClient.sendTransaction(tx) - } - - private async handleEthSign(params: [string, string]): Promise { - if (!this.kernelClient?.account) { - throw new Error("account not connected!") - } - const [address, message] = params - if ( - address.toLowerCase() !== - this.kernelClient.account.address.toLowerCase() - ) { - throw new Error( - "cannot sign for address that is not the current account" - ) - } - - return this.kernelClient.signMessage({ - message, - account: this.kernelClient.account - }) - } - - private async handlePersonalSign( - params: [string, string] - ): Promise { - if (!this.kernelClient?.account) { - throw new Error("account not connected!") - } - const [message, address] = params - if ( - address.toLowerCase() !== - this.kernelClient.account.address.toLowerCase() - ) { - throw new Error( - "cannot sign for address that is not the current account" - ) - } - - return this.kernelClient.signMessage({ - message, - account: this.kernelClient.account - }) - } - - private async handleEthSignTypedDataV4( - params: [string, string] - ): Promise { - if (!this.kernelClient?.account) { - throw new Error("account not connected!") - } - const [address, typedDataJSON] = params - const typedData = JSON.parse(typedDataJSON) - if ( - address.toLowerCase() !== - this.kernelClient.account.address.toLowerCase() - ) { - throw new Error( - "cannot sign for address that is not the current account" - ) - } - - return this.kernelClient.signTypedData({ - account: this.kernelClient.account, - domain: typedData.domain, - types: typedData.types, - message: typedData.message, - primaryType: typedData.primaryType - }) - } - - private async handleSwitchEthereumChain() { - throw new Error("Not implemented.") - } - - private async handleWalletSendcalls( - params: [SendCallsParams] - ): Promise { - const accountAddress = this.kernelClient.account.address - const accountChainId = this.kernelClient.chain.id - - const { calls, capabilities, from, chainId } = params[0] - if (from !== accountAddress) { - throw new Error("invalid account address") - } - if (Number(chainId) !== accountChainId) { - throw new Error("invalid chain id") - } - if ( - this.kernelClient.account.entryPoint !== ENTRYPOINT_ADDRESS_V07 && - capabilities?.permissions - ) { - throw new Error("Permissions not supported with kernel v2") - } - - let kernelAccountClient: KernelAccountClient< - entryPoint, - Transport, - Chain, - KernelSmartAccount - > - const permission = this.getItemFromStorage( - WALLET_PERMISSION_STORAGE_KEY - ) as SessionType - const paymasterService = await this.getPaymasterService( - capabilities?.paymasterService, - this.kernelClient.chain - ) - - const sessionId = capabilities?.permissions?.sessionId - const session = permission?.[accountAddress]?.[ - toHex(accountChainId) - ]?.find((session) => session.sessionId === sessionId) - if (session && this.kernelClient?.account?.client) { - const sessionSigner = await toECDSASigner({ - signer: privateKeyToAccount(session.signerPrivateKey) - }) - const sessionKeyAccount = (await deserializePermissionAccount( - this.kernelClient.account.client as Client< - Transport, - Chain, - undefined, - PublicRpcSchema, - PublicActions - >, - this.kernelClient.account.entryPoint, - this.kernelClient.account.kernelVersion, - session.approval, - sessionSigner - )) as unknown as KernelSmartAccount - - const kernelClient = createKernelAccountClient({ - account: sessionKeyAccount, - chain: this.kernelClient.chain, - entryPoint: this.kernelClient.account.entryPoint, - bundlerTransport: http(this.kernelClient.transport.url), - middleware: { - sponsorUserOperation: paymasterService - } - }) - - kernelAccountClient = kernelClient - } else { - kernelAccountClient = createKernelAccountClient({ - account: this.kernelClient.account, - chain: this.kernelClient.chain, - entryPoint: this.kernelClient.account.entryPoint, - bundlerTransport: http(this.kernelClient.transport.url), - middleware: { - sponsorUserOperation: paymasterService - } - }) - } - - const encodedeCall = await kernelAccountClient.account.encodeCallData( - calls.map((call) => ({ - to: call.to ?? kernelAccountClient.account.address, - value: call.value ? BigInt(call.value) : 0n, - data: call.data ?? "0x" - })) - ) - - return await kernelAccountClient.sendUserOperation({ - userOperation: { - callData: encodedeCall - } - }) - } - - private handleWalletCapabilities() { - const capabilities = this.getItemFromStorage( - WALLET_CAPABILITIES_STORAGE_KEY - // biome-ignore lint/suspicious/noExplicitAny: - ) as Record | undefined - - return capabilities - ? capabilities[this.kernelClient.account.address] - : {} - } - - private async handleWalletGetCallStatus( - params: [GetCallsParams] - ): Promise { - const userOpHash = params[0] - - if (!isHex(userOpHash)) { - throw new Error( - "Invalid params for wallet_getCallStatus: not a hex string" - ) - } - const result = await this.bundlerClient.getUserOperationReceipt({ - hash: userOpHash as Hex - }) - if (!result?.success) { - return { - status: "PENDING" - } - } - return { - status: "CONFIRMED", - receipts: [ - { - logs: result.logs.map((log) => ({ - address: log.address, - data: log.data, - topics: log.topics - })), - status: result.success ? "0x1" : "0x0", - blockHash: result.receipt.blockHash, - blockNumber: toHex(result.receipt.blockNumber), - gasUsed: toHex(result.receipt.gasUsed), - transactionHash: result.receipt.transactionHash - } - ] - } - } - - private async handleWalletGrantPermissions( - params: [GrantPermissionsParams] - ) { - if (this.kernelClient.account.entryPoint !== ENTRYPOINT_ADDRESS_V07) { - throw new Error("Permissions not supported with kernel v2") - } - const capabilities = - this.handleWalletCapabilities()[toHex(this.kernelClient.chain.id)] - .permissions.permissionTypes - - validatePermissions(params[0], capabilities) - const policies = getPolicies(params[0]) - const permissions = params[0].permissions - - // signer - const sessionPrivateKey = generatePrivateKey() - const sessionKeySigner = toECDSASigner({ - signer: privateKeyToAccount(sessionPrivateKey) - }) - - const client = this.kernelClient.account.client as Client< - Transport, - Chain | undefined, - undefined, - PublicRpcSchema, - PublicActions - > - - const permissionValidator = await toPermissionValidator(client, { - entryPoint: this.kernelClient.account.entryPoint, - kernelVersion: this.kernelClient.account.kernelVersion, - signer: sessionKeySigner, - policies: policies - }) - - const sudoValidator = - this.kernelClient.account.kernelPluginManager.sudoValidator - const sessionKeyAccount = await createKernelAccount(client, { - entryPoint: this.kernelClient.account.entryPoint, - kernelVersion: this.kernelClient.account.kernelVersion, - plugins: { - sudo: sudoValidator, - regular: permissionValidator - } - }) - const enabledSignature = - await sessionKeyAccount.kernelPluginManager.getPluginEnableSignature( - sessionKeyAccount.address - ) - const sessionKeyAccountWithSig = await createKernelAccount(client, { - entryPoint: this.kernelClient.account.entryPoint, - kernelVersion: this.kernelClient.account.kernelVersion, - plugins: { - sudo: sudoValidator, - regular: permissionValidator, - pluginEnableSignature: enabledSignature - } - }) - - const createdPermissions = - this.getItemFromStorage(WALLET_PERMISSION_STORAGE_KEY) || {} - const newPermission = { - sessionId: permissionValidator.getIdentifier(), - entryPoint: this.kernelClient.account.entryPoint, - signerPrivateKey: sessionPrivateKey, - approval: await serializePermissionAccount(sessionKeyAccountWithSig) - } - - const address = this.kernelClient.account.address - const chainId = toHex(this.kernelClient.chain.id) - - const mergedPermissions: SessionType = { ...createdPermissions } - - if (!mergedPermissions[address]) { - mergedPermissions[address] = {} - } - - if (!mergedPermissions[address][chainId]) { - mergedPermissions[address][chainId] = [] - } - - mergedPermissions[address][chainId].push(newPermission) - this.storeItemToStorage( - WALLET_PERMISSION_STORAGE_KEY, - mergedPermissions - ) - return { - grantedPermissions: permissions.map((permission) => ({ - type: permission.type, - data: permission.data, - policies: permission.policies - })), - expiry: params[0].expiry, - permissionsContext: permissionValidator.getIdentifier() - } - } - - private async getPaymasterService( - paymaster: PaymasterServiceCapability | undefined, - chain: Chain - ) { - if (!paymaster?.url) return undefined - - // verifying paymaster - return async ({ - userOperation, - entryPoint - }: { - userOperation: UserOperation> - entryPoint: entryPoint - }) => { - const paymasterClient = createZeroDevPaymasterClient({ - chain: chain, - entryPoint: entryPoint, - transport: http(paymaster.url) - }) - const paymasterEip7677Client = paymasterClient.extend( - paymasterActionsEip7677(entryPoint) - ) - - // 1. get stub data from paymasterService - const stubData = await paymasterEip7677Client.getPaymasterStubData({ - userOperation: userOperation, - chain: chain - }) - const stubUserOperation = { - ...userOperation, - ...stubData - } - const hexStubUserOperation = Object.fromEntries( - Object.entries(stubUserOperation).map(([key, value]) => { - if (typeof value === "bigint") return [key, toHex(value)] - return [key, value] - }) - ) - - // 2. estimate userOp gas - const gas = (await this.kernelClient.request({ - method: "eth_estimateUserOperationGas", - // biome-ignore lint/suspicious/noExplicitAny: - params: [hexStubUserOperation as any, entryPoint] - })) as EstimateUserOperationGasReturnType - - const userOperationWithGas = { - ...stubUserOperation, - callGasLimit: gas.callGasLimit, - verificationGasLimit: gas.verificationGasLimit, - preVerificationGas: gas.preVerificationGas - } as GetPaymasterDataParameters["userOperation"] - - // 3. get paymaster data - const paymasterData = await paymasterEip7677Client.getPaymasterData( - { - userOperation: userOperationWithGas, - chain: chain - } - ) - - if (entryPoint === ENTRYPOINT_ADDRESS_V06) { - const paymasterDataV06 = - paymasterData as GetPaymasterDataReturnType - return { - callGasLimit: BigInt(gas.callGasLimit), - verificationGasLimit: BigInt(gas.verificationGasLimit), - preVerificationGas: BigInt(gas.preVerificationGas), - paymasterAndData: paymasterDataV06?.paymasterAndData, - maxFeePerGas: BigInt(userOperation.maxFeePerGas), - maxPriorityFeePerGas: BigInt( - userOperation.maxPriorityFeePerGas - ) - } as SponsorUserOperationReturnType - } - const stubDataV07 = - stubData as GetPaymasterStubDataReturnType - const paymasterDataV07 = - paymasterData as GetPaymasterDataReturnType - - return { - callGasLimit: BigInt(gas.callGasLimit), - verificationGasLimit: BigInt(gas.verificationGasLimit), - preVerificationGas: BigInt(gas.preVerificationGas), - paymaster: paymasterDataV07.paymaster, - paymasterData: paymasterDataV07.paymasterData, - paymasterVerificationGasLimit: - stubDataV07.paymasterVerificationGasLimit && - BigInt(stubDataV07.paymasterVerificationGasLimit), - paymasterPostOpGasLimit: - stubDataV07?.paymasterPostOpGasLimit && - BigInt(stubDataV07.paymasterPostOpGasLimit), - maxFeePerGas: BigInt(userOperation.maxFeePerGas), - maxPriorityFeePerGas: BigInt(userOperation.maxPriorityFeePerGas) - } as SponsorUserOperationReturnType - } - // TODO: other paymaster services - } - - private getItemFromStorage(key: string): T | undefined { - const item = this.storage.getItem(key) - return item ? JSON.parse(item) : undefined - } - - private storeItemToStorage(key: string, item: T) { - this.storage.setItem(key, JSON.stringify(item)) - } -} diff --git a/wallet/connectors/passkeyConnector.ts b/wallet/connectors/passkeyConnector.ts deleted file mode 100644 index 31dddd04..00000000 --- a/wallet/connectors/passkeyConnector.ts +++ /dev/null @@ -1,314 +0,0 @@ -import { - ChainNotConfiguredError, - type Connector, - createConnector -} from "@wagmi/core" -import { - PasskeyValidatorContractVersion, - WebAuthnMode, - toPasskeyValidator, - toWebAuthnKey -} from "@zerodev/passkey-validator" -import { - type KernelValidator, - createKernelAccount, - createKernelAccountClient -} from "@zerodev/sdk" -import type { EntryPoint } from "permissionless/types" -import { - http, - type AddEthereumChainParameter, - type Chain, - type ProviderRpcError, - SwitchChainError, - UserRejectedRequestError, - createPublicClient, - getAddress, - numberToHex -} from "viem" -import { - KernelEIP1193Provider, - type KernelEIP1193Provider as KernelEIP1193ProviderType -} from "../KernelEIP1193Provider" -import type { ZeroDevVersion } from "../types" -import { ZERODEV_BUNDLER_URL, ZERODEV_PASSKEY_URL } from "../utils/constants" -import { getZerodevSigner, setZerodevSigner } from "../utils/passkey" -import { - getEntryPointFromZeroDevVersion, - getKernelVersionFromZeroDevVersion -} from "../utils/provider" - -passkeyConnector.type = "passkeyConnector" as const -export function passkeyConnector( - projectId: string, - chain: Chain, - version: ZeroDevVersion, - appName?: string -) { - const passkeyName = appName ?? "ZeroDev Passkey Wallet" - - type Provider = KernelEIP1193ProviderType | undefined - let walletProvider: Provider | undefined - - let accountsChanged: Connector["onAccountsChanged"] | undefined - let chainChanged: Connector["onChainChanged"] | undefined - let disconnect: Connector["onDisconnect"] | undefined - - return createConnector((config) => ({ - id: "zerodevPasskeySDK", - name: "Passkey", - supportsSimulation: true, - type: passkeyConnector.type, - - async connect({ chainId } = {}) { - try { - if (chainId && chain.id !== chainId) { - throw new Error( - `Incorrect chain Id: ${chainId} should be ${chain.id}` - ) - } - - const provider = await this.getProvider() - if (provider) { - const accounts = ( - (await provider.request({ - method: "eth_requestAccounts" - })) as string[] - ).map((x) => getAddress(x)) - if (!accountsChanged) { - accountsChanged = this.onAccountsChanged.bind(this) - provider.on("accountsChanged", accountsChanged) - } - if (!chainChanged) { - chainChanged = this.onChainChanged.bind(this) - provider.on("chainChanged", chainChanged) - } - if (!disconnect) { - disconnect = this.onDisconnect.bind(this) - provider.on("disconnect", disconnect) - } - return { accounts, chainId: chain.id } - } - - const entryPoint = getEntryPointFromZeroDevVersion(version) - const kernelVersion = - getKernelVersionFromZeroDevVersion(version) - const passkeySigner = getZerodevSigner() - - const publicClient = createPublicClient({ - chain, - transport: http() - }) - const mode = passkeySigner - ? WebAuthnMode.Login - : WebAuthnMode.Register - const webAuthnKey = await toWebAuthnKey({ - passkeyName: passkeyName, - passkeyServerUrl: `${ZERODEV_PASSKEY_URL}/${projectId}`, - mode, - passkeyServerHeaders: {} - }) - - const passkeyValidator = await toPasskeyValidator( - publicClient, - { - webAuthnKey, - entryPoint: entryPoint, - kernelVersion, - validatorContractVersion: - PasskeyValidatorContractVersion.V0_0_2 - } - ) - const passkeyData = ( - passkeyValidator as KernelValidator< - EntryPoint, - "WebAuthnValidator" - > & { - getSerializedData: () => string - } - ).getSerializedData() - setZerodevSigner(passkeyData, true) - - const kernelAccount = await createKernelAccount(publicClient, { - entryPoint: entryPoint, - kernelVersion, - plugins: { - sudo: passkeyValidator - } - }) - const kernelClient = createKernelAccountClient({ - account: kernelAccount, - chain, - entryPoint: entryPoint, - bundlerTransport: http( - `${ZERODEV_BUNDLER_URL}/${projectId}` - ) - }) - walletProvider = new KernelEIP1193Provider(kernelClient) - - return { accounts: [kernelAccount.address], chainId: chain.id } - } catch (error) { - if ( - /(user closed modal|accounts received is empty|user denied account)/i.test( - (error as Error).message - ) - ) - throw new UserRejectedRequestError(error as Error) - throw error - } - }, - - async disconnect() { - const provider = await this.getProvider() - if (accountsChanged) { - provider?.removeListener("accountsChanged", accountsChanged) - accountsChanged = undefined - } - if (chainChanged) { - provider?.removeListener("chainChanged", chainChanged) - chainChanged = undefined - } - if (disconnect) { - provider?.removeListener("disconnect", disconnect) - disconnect = undefined - } - walletProvider = undefined - const serializedData = getZerodevSigner() - if (serializedData) { - setZerodevSigner(serializedData.signer, false) - } - }, - - async getAccounts() { - const provider = await this.getProvider() - if (!provider) return [] - - return ( - (await provider.request({ - method: "eth_accounts" - })) as string[] - ).map((x) => getAddress(x)) - }, - - async getChainId() { - const provider = await this.getProvider() - if (!provider) return chain.id - - const chainId = await provider.request({ method: "eth_chainId" }) - return Number(chainId as number) - }, - - async getProvider() { - return walletProvider - }, - - async isAuthorized() { - try { - const accounts = await this.getAccounts() - return !!accounts.length - } catch { - return false - } - }, - - async switchChain({ addEthereumChainParameter, chainId }) { - const chain = config.chains.find((chain) => chain.id === chainId) - if (!chain) - throw new SwitchChainError(new ChainNotConfiguredError()) - - const provider = await this.getProvider() - if (!provider) - throw new SwitchChainError(new Error("Not Connected")) - - try { - await provider.request({ - method: "wallet_switchEthereumChain", - params: [{ chainId: numberToHex(chain.id) }] - }) - return chain - } catch (error) { - // Indicates chain is not added to provider - if ((error as ProviderRpcError).code === 4902) { - try { - let blockExplorerUrls: string[] - if (addEthereumChainParameter?.blockExplorerUrls) - blockExplorerUrls = - addEthereumChainParameter.blockExplorerUrls - else - blockExplorerUrls = chain.blockExplorers?.default - .url - ? [chain.blockExplorers?.default.url] - : [] - - let rpcUrls: readonly string[] - if (addEthereumChainParameter?.rpcUrls?.length) - rpcUrls = addEthereumChainParameter.rpcUrls - else rpcUrls = [chain.rpcUrls.default?.http[0] ?? ""] - - const addEthereumChain = { - blockExplorerUrls, - chainId: numberToHex(chainId), - chainName: - addEthereumChainParameter?.chainName ?? - chain.name, - iconUrls: addEthereumChainParameter?.iconUrls, - nativeCurrency: - addEthereumChainParameter?.nativeCurrency ?? - chain.nativeCurrency, - rpcUrls - } satisfies AddEthereumChainParameter - - await provider.request({ - method: "wallet_addEthereumChain", - params: [addEthereumChain] - }) - - return chain - } catch (error) { - throw new UserRejectedRequestError(error as Error) - } - } - - throw new SwitchChainError(error as Error) - } - }, - - onAccountsChanged(accounts) { - if (accounts.length === 0) this.onDisconnect() - else - config.emitter.emit("change", { - accounts: accounts.map((x) => getAddress(x)) - }) - }, - - onChainChanged(chain) { - const chainId = Number(chain) - config.emitter.emit("change", { chainId }) - }, - - async onDisconnect(_error) { - config.emitter.emit("disconnect") - - const provider = await this.getProvider() - if (!provider) return - - if (accountsChanged) { - provider.removeListener("accountsChanged", accountsChanged) - accountsChanged = undefined - } - if (chainChanged) { - provider.removeListener("chainChanged", chainChanged) - chainChanged = undefined - } - if (disconnect) { - provider.removeListener("disconnect", disconnect) - disconnect = undefined - } - walletProvider = undefined - const serializedData = getZerodevSigner() - if (serializedData) { - setZerodevSigner(serializedData.signer, false) - } - } - })) -} diff --git a/wallet/index.ts b/wallet/index.ts deleted file mode 100644 index 15736555..00000000 --- a/wallet/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export { - KernelEIP1193Provider, - type KernelEIP1193Provider as KernelEIP1193ProviderType -} from "./KernelEIP1193Provider.js" - -export { wrapSmartWallet } from "./wrapSmartWallet.js" - -export { passkeyConnector } from "./connectors/passkeyConnector.js" diff --git a/wallet/package.json b/wallet/package.json deleted file mode 100644 index f82d44ef..00000000 --- a/wallet/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "@zerodev/wallet", - "version": "0.1.5", - "author": "ZeroDev", - "main": "./_cjs/index.js", - "module": "./_esm/index.js", - "types": "./_types/index.d.ts", - "typings": "./_types/index.d.ts", - "type": "module", - "sideEffects": false, - "license": "MIT", - "files": [ - "_esm", - "_cjs", - "_types", - "./**/*.ts", - "!_esm/**/*.tsbuildinfo", - "!_cjs/**/*.tsbuildinfo", - "!_types/**/*.tsbuildinfo", - "!.env", - "!./**/*.test.ts", - "!.changeset" - ], - "scripts": { - "build": "bun run clean && bun run build:cjs && bun run build:esm && bun run build:types", - "build:cjs": "tsc --project ./tsconfig.build.json --module commonjs --outDir ./_cjs --removeComments --verbatimModuleSyntax false && printf '{\"type\":\"commonjs\"}' > ./_cjs/package.json", - "build:esm": "tsc --project ./tsconfig.build.json --module es2020 --outDir ./_esm && printf '{\"type\": \"module\",\"sideEffects\":false}' > ./_esm/package.json", - "build:types": "tsc --project ./tsconfig.build.json --module esnext --declarationDir ./_types --emitDeclarationOnly --declaration --declarationMap", - "clean": "rimraf _esm _cjs _types", - "changeset": "changeset", - "changeset:release": "bun run build && changeset publish", - "changeset:version": "changeset version && bun install --lockfile-only", - "format": "biome format . --write", - "lint": "biome check .", - "lint:fix": "bun run lint --apply" - }, - "dependencies": { - "@zerodev/ecdsa-validator": "^5.3.3", - "@zerodev/passkey-validator": "^5.4.2", - "@zerodev/permissions": "^5.4.6", - "@zerodev/sdk": "^5.3.14" - }, - "peerDependencies": { - "wagmi": "^2.9.0", - "viem": ">=2.16.3 <2.18.0", - "permissionless": ">=0.1.44 <=0.1.45" - } -} diff --git a/wallet/tsconfig.build.json b/wallet/tsconfig.build.json deleted file mode 100644 index dc3c8e62..00000000 --- a/wallet/tsconfig.build.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "../templates/typescript/tsconfig.build.json", - "include": ["./"], - "exclude": ["./**/*.test.ts", "./**/*.test-d.ts", "./**/*.bench.ts"], - "compilerOptions": { - "moduleResolution": "node", - "sourceMap": true, - "rootDir": "./", - "baseUrl": "./" - } -} diff --git a/wallet/types/index.ts b/wallet/types/index.ts deleted file mode 100644 index e3052da7..00000000 --- a/wallet/types/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -export type { - Permission, - PaymasterServiceCapability, - SendCallsParams, - SendCallsResult, - GetCallsParams, - GetCallsResult, - ShowCallsParams, - GrantPermissionsParams, - GrantPermissionsResult, - SessionType, - ZeroDevVersion -} from "./provider.js" diff --git a/wallet/types/policy.ts b/wallet/types/policy.ts deleted file mode 100644 index 0f939271..00000000 --- a/wallet/types/policy.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { OneOf } from "viem" - -/** @internal */ -export type GasLimitPolicy = { - type: "gas-limit" - data: { - /** Gas limit (in wei). */ - limit: uint256 - } -} - -/** @internal */ -export type RateLimitPolicy = { - type: "rate-limit" - data: { - /** Number of times during each interval. */ - count: number - /** Interval (in seconds). */ - interval: number - } -} - -export type Policy = OneOf< - GasLimitPolicy | RateLimitPolicy -> diff --git a/wallet/types/provider.ts b/wallet/types/provider.ts deleted file mode 100644 index 88ea1e85..00000000 --- a/wallet/types/provider.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { EntryPoint } from "permissionless/types" -import type { Address, Hex } from "viem" -import type { Policy } from "./policy" - -export type PaymasterServiceCapability = { - url: string -} - -// wallet_sendCalls -export type SendCallsParams = { - version: string - chainId: `0x${string}` // Hex chain id - from: `0x${string}` - calls: { - to?: `0x${string}` | undefined - data?: `0x${string}` | undefined - value?: `0x${string}` | undefined // Hex value - }[] - // biome-ignore lint/suspicious/noExplicitAny: - capabilities?: Record | undefined -} - -export type SendCallsResult = string - -// wallet_getCallStatus -export type GetCallsParams = string - -export type GetCallsResult = { - status: "PENDING" | "CONFIRMED" - receipts?: { - logs: { - address: `0x${string}` - data: `0x${string}` - topics: `0x${string}`[] - }[] - status: `0x${string}` // Hex 1 or 0 for success or failure, respectively - blockHash: `0x${string}` - blockNumber: `0x${string}` - gasUsed: `0x${string}` - transactionHash: `0x${string}` - }[] -} - -// wallet_showCallsStatus -export type ShowCallsParams = string - -// wallet_issuePermissions -export type Permission = { - type: string - // biome-ignore lint/suspicious/noExplicitAny: - data: Record - required: boolean - policies: Policy[] -} - -export type GrantPermissionsParams = { - permissions: Permission[] - expiry: number -} - -export type GrantPermissionsResult = { - sessionId: string -} - -export type SessionType = { - [address: Address]: { - [chainId: Hex]: { - sessionId: Hex - entryPoint: EntryPoint - signerPrivateKey: Hex - approval: string - }[] - } -} - -export type ZeroDevVersion = "v2" | "v3" | "v3.1" diff --git a/wallet/utils/constants.ts b/wallet/utils/constants.ts deleted file mode 100644 index ff39d700..00000000 --- a/wallet/utils/constants.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const ZERODEV_PASSKEY_URL = "https://passkeys.zerodev.app/api/v3" - -export const ZERODEV_BUNDLER_URL = "https://rpc.zerodev.app/api/v2/bundler" diff --git a/wallet/utils/passkey.ts b/wallet/utils/passkey.ts deleted file mode 100644 index 471eeed1..00000000 --- a/wallet/utils/passkey.ts +++ /dev/null @@ -1,35 +0,0 @@ -export type ZeroDevWalletSigner = { - isConnected: boolean - signer: string -} - -export const getZerodevSigner = (): ZeroDevWalletSigner | null => { - if (typeof window === "undefined") return null - const signer = window.localStorage.getItem("zerodev_wallet_signer") - if (!signer) return null - - try { - const parsedSigner = JSON.parse(signer) - if ( - parsedSigner && - typeof parsedSigner === "object" && - "isConnected" in parsedSigner && - "signer" in parsedSigner - ) { - return parsedSigner as ZeroDevWalletSigner - } - return null - } catch (err) { - return null - } -} - -export const setZerodevSigner = (signer: string, isConnected: boolean) => { - if (typeof window === "undefined") return - - window.localStorage.setItem( - "zerodev_wallet_signer", - JSON.stringify({ signer, isConnected }) - ) - return -} diff --git a/wallet/utils/permissions.ts b/wallet/utils/permissions.ts deleted file mode 100644 index 9a6d84db..00000000 --- a/wallet/utils/permissions.ts +++ /dev/null @@ -1,103 +0,0 @@ -import type { Policy } from "@zerodev/permissions" -import { - CallPolicyVersion, - type SignatureCallerPolicyParams, - toCallPolicy, - toGasPolicy, - toRateLimitPolicy, - toSignatureCallerPolicy, - toSudoPolicy, - toTimestampPolicy -} from "@zerodev/permissions/policies" -import { type Address, toHex } from "viem" -import type { GrantPermissionsParams, Permission, SessionType } from "../types" - -export const validatePermissions = ( - permissionsParams: GrantPermissionsParams, - supportedPolicies: string[] -) => { - // check expiry - if (permissionsParams.expiry < Math.floor(Date.now() / 1000)) { - throw new Error( - `Invalid expiry ${permissionsParams.expiry} for permissions` - ) - } - - // check policies are supported - for (const permission of permissionsParams.permissions) { - if (!supportedPolicies.includes(permission.type)) { - throw new Error(`Unsupported policy ${permission.type}`) - } - } -} - -export const getPermissionPoliciy = (permission: Permission): Policy[] => { - const policies: Policy[] = [] - switch (permission.type) { - case "sudo": - policies.push(toSudoPolicy({})) - break - case "contract-call": - policies.push( - toCallPolicy({ - ...permission.data, - policyVersion: CallPolicyVersion.V0_0_4 - }) - ) - break - case "signature": - policies.push( - toSignatureCallerPolicy( - permission.data as SignatureCallerPolicyParams - ) - ) - break - default: - break - } - for (const policy of permission.policies) { - switch (policy.type) { - case "gas-limit": - policies.push( - toGasPolicy({ - allowed: policy.data.limit - }) - ) - break - case "rate-limit": - policies.push(toRateLimitPolicy(policy.data)) - break - default: - break - } - } - return policies -} - -export const getPolicies = ( - permissionsParams: GrantPermissionsParams -): Policy[] => { - const policies = permissionsParams.permissions - .flatMap((permission) => getPermissionPoliciy(permission)) - .concat([ - toTimestampPolicy({ - validAfter: Math.floor(new Date().valueOf() / 1000), - validUntil: permissionsParams.expiry - }) - ]) - return policies -} - -export const isSessionValid = ( - sessionId: `0x${string}` | undefined, - permission: SessionType | undefined, - address: Address, - chainId: number -): boolean => { - if (!sessionId || !permission) return false - - const selectedPermission = permission[address]?.[toHex(chainId)] - if (!selectedPermission) return false - - return !!selectedPermission.find((p) => p.sessionId === sessionId) -} diff --git a/wallet/utils/provider.ts b/wallet/utils/provider.ts deleted file mode 100644 index 3a690e1a..00000000 --- a/wallet/utils/provider.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { KERNEL_V2_4, KERNEL_V3_0, KERNEL_V3_1 } from "@zerodev/sdk/constants" -import { ENTRYPOINT_ADDRESS_V06, ENTRYPOINT_ADDRESS_V07 } from "permissionless" -import type { ZeroDevVersion } from "../types" - -export const getEntryPointFromZeroDevVersion = (version: ZeroDevVersion) => { - if (version === "v3") { - return ENTRYPOINT_ADDRESS_V07 - } - return ENTRYPOINT_ADDRESS_V06 -} - -export const getKernelVersionFromZeroDevVersion = (version: ZeroDevVersion) => { - if (version === "v3") { - return KERNEL_V3_0 - } else if (version === "v3.1") { - return KERNEL_V3_1 - } - return KERNEL_V2_4 -} diff --git a/wallet/utils/storage.ts b/wallet/utils/storage.ts deleted file mode 100644 index fc36de50..00000000 --- a/wallet/utils/storage.ts +++ /dev/null @@ -1,19 +0,0 @@ -export class KernelLocalStorage { - constructor(private scope: "ZDWALLET") {} - - public getItem(key: string): string | null { - return localStorage.getItem(this.scopedKey(key)) - } - - public setItem(key: string, value: string): void { - localStorage.setItem(this.scopedKey(key), value) - } - - public removeItem(key: string): void { - localStorage.removeItem(this.scopedKey(key)) - } - - scopedKey(key: string): string { - return `${this.scope}:${key}` - } -} diff --git a/wallet/wrapSmartWallet.ts b/wallet/wrapSmartWallet.ts deleted file mode 100644 index 928aedd2..00000000 --- a/wallet/wrapSmartWallet.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { signerToEcdsaValidator } from "@zerodev/ecdsa-validator" -import { createKernelAccount, createKernelAccountClient } from "@zerodev/sdk" -import { walletClientToSmartAccountSigner } from "permissionless" -import type { EntryPoint } from "permissionless/types" -import { - http, - type Account, - type Chain, - type Transport, - type WalletClient, - createClient, - createPublicClient, - custom, - walletActions -} from "viem" -import type { CreateConnectorFn } from "wagmi" -import { - KernelEIP1193Provider, - type KernelEIP1193Provider as KernelEIP1193ProviderType -} from "./KernelEIP1193Provider" -import type { ZeroDevVersion } from "./types" -import { - getEntryPointFromZeroDevVersion, - getKernelVersionFromZeroDevVersion -} from "./utils/provider" - -export const wrapSmartWallet = ( - walletFunction: CreateConnectorFn, - projectId: string, - version: ZeroDevVersion -): CreateConnectorFn => { - // biome-ignore lint/suspicious/noExplicitAny: - return (config: any) => { - const entryPoint = getEntryPointFromZeroDevVersion(version) - const kernelVersion = getKernelVersionFromZeroDevVersion(version) - const wallet = walletFunction(config) - let kernelProvider: KernelEIP1193ProviderType | null - - return new Proxy(wallet, { - set(target, prop, value, receiver) { - return Reflect.set(target, prop, value, receiver) - }, - get(target, prop, receiver) { - const source = Reflect.get(target, prop, receiver) - if (prop === "connect") { - // biome-ignore lint/suspicious/noExplicitAny: - return async (params: any) => { - await target.connect(params) - const chainId = await target.getChainId() - const chain: Chain = config.chains.find( - // biome-ignore lint/suspicious/noExplicitAny: - (c: any) => c.id === chainId - ) - if (!chain) { - await target.switchChain?.({ - chainId: config.chains[0].id - }) - } - const connetedChain = chain ?? config.chains[0] - - const provider = await target.getProvider() - const accounts = await target.getAccounts() - - const walletClient = createClient({ - account: accounts[0], - chain: connetedChain, - name: "Connector Client", - transport: (opts) => - // biome-ignore lint/suspicious/noExplicitAny: - custom(provider as any)({ - ...opts, - retryCount: 0 - }) - }).extend(walletActions) as WalletClient< - Transport, - Chain, - Account - > - - const publicClient = createPublicClient({ - chain: connetedChain, - transport: http( - `https://rpc.zerodev.app/api/v2/bundler/${projectId}` - ) - }) - const ecdsaValidator = await signerToEcdsaValidator( - publicClient, - { - entryPoint: entryPoint, - kernelVersion, - signer: walletClientToSmartAccountSigner( - walletClient - ) - } - ) - const kernelAccount = await createKernelAccount( - publicClient, - { - entryPoint: entryPoint, - kernelVersion, - plugins: { - sudo: ecdsaValidator - } - } - ) - const kernelClient = createKernelAccountClient({ - account: kernelAccount, - chain: connetedChain, - entryPoint: entryPoint, - bundlerTransport: http( - `https://rpc.zerodev.app/api/v2/bundler/${projectId}` - ) - }) - kernelProvider = new KernelEIP1193Provider(kernelClient) - - return { - accounts: [kernelAccount.address], - chainId: connetedChain.id - } - } - } - - if (prop === "getProvider") { - return async () => { - if (kernelProvider) { - return kernelProvider - } - return target.getProvider() - } - } - - if (prop === "disconnect") { - return async () => { - await target.disconnect() - kernelProvider = null - return - } - } - - return source - } - }) - } -} diff --git a/walletconnect/CHANGELOG.md b/walletconnect/CHANGELOG.md deleted file mode 100644 index 1517262d..00000000 --- a/walletconnect/CHANGELOG.md +++ /dev/null @@ -1,23 +0,0 @@ -# @zerodev/walletconnect - -## 0.0.6 - -### Patch Changes - -- Patch for latest permissionless 0.1.45 support -- Updated dependencies - - @zerodev/wallet@0.1.5 - -## 0.0.5 - -### Patch Changes - -- Update viem to 2.16.3 -- Updated dependencies - - @zerodev/wallet@0.1.0 - -## 0.0.4 - -### Changed - -- Updated @zerodev/wallet version to 0.0.10 diff --git a/walletconnect/bun.lockb b/walletconnect/bun.lockb deleted file mode 100755 index cb7cf702..00000000 Binary files a/walletconnect/bun.lockb and /dev/null differ diff --git a/walletconnect/index.ts b/walletconnect/index.ts deleted file mode 100644 index cd0a7a15..00000000 --- a/walletconnect/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { default as WalletConnectWallet } from "./src/WalletConnectWallet.js" -export { default as WalletConnectKernelService } from "./src/WalletConnectKernelService.js" diff --git a/walletconnect/package.json b/walletconnect/package.json deleted file mode 100644 index 3dee318f..00000000 --- a/walletconnect/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "@zerodev/walletconnect", - "version": "0.0.6", - "author": "ZeroDev", - "main": "./_cjs/index.js", - "module": "./_esm/index.js", - "types": "./_types/index.d.ts", - "typings": "./_types/index.d.ts", - "type": "module", - "sideEffects": false, - "license": "MIT", - "files": [ - "_esm", - "_cjs", - "_types", - "./**/*.ts", - "!_esm/**/*.tsbuildinfo", - "!_cjs/**/*.tsbuildinfo", - "!_types/**/*.tsbuildinfo", - "!.env", - "!./**/*.test.ts", - "!.changeset" - ], - "scripts": { - "build": "bun run clean && bun run build:cjs && bun run build:esm && bun run build:types", - "build:cjs": "tsc --project ./tsconfig.build.json --module commonjs --outDir ./_cjs --removeComments --verbatimModuleSyntax false && printf '{\"type\":\"commonjs\"}' > ./_cjs/package.json", - "build:esm": "tsc --project ./tsconfig.build.json --module es2020 --outDir ./_esm && printf '{\"type\": \"module\",\"sideEffects\":false}' > ./_esm/package.json", - "build:types": "tsc --project ./tsconfig.build.json --module esnext --declarationDir ./_types --emitDeclarationOnly --declaration --declarationMap", - "clean": "rimraf _esm _cjs _types", - "changeset": "changeset", - "changeset:release": "bun run build && changeset publish", - "changeset:version": "changeset version && bun install --lockfile-only", - "format": "biome format . --write", - "lint": "biome check .", - "lint:fix": "bun run lint --apply" - }, - "dependencies": { - "@walletconnect/core": "^2.13.1", - "@walletconnect/encoding": "^1.0.2", - "@walletconnect/jsonrpc-utils": "^1.0.8", - "@walletconnect/types": "^2.13.1", - "@walletconnect/web3wallet": "^1.12.1", - "@zerodev/wallet": "^0.1.5", - "lodash": "^4.17.21" - }, - "peerDependencies": { - "viem": ">=2.16.3 <2.18.0", - "permissionless": ">=0.1.44 <=0.1.45" - }, - "devDependencies": { - "@types/lodash": "^4.17.4" - } -} diff --git a/walletconnect/src/WalletConnectKernelService.ts b/walletconnect/src/WalletConnectKernelService.ts deleted file mode 100644 index 593a504d..00000000 --- a/walletconnect/src/WalletConnectKernelService.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { hexToUtf8 } from "@walletconnect/encoding" -import { formatJsonRpcError } from "@walletconnect/jsonrpc-utils" -import type { SessionTypes } from "@walletconnect/types" -import { getSdkError } from "@walletconnect/utils" -import type { Web3WalletTypes } from "@walletconnect/web3wallet" -import type { KernelAccountClient, KernelSmartAccount } from "@zerodev/sdk" -import { KernelEIP1193Provider } from "@zerodev/wallet" -import type { EntryPoint } from "permissionless/types" -import type { Chain, Transport } from "viem" -import WalletConnectWallet from "./WalletConnectWallet" -import { stripEip155Prefix } from "./constants" - -class WalletConnectKernelService { - private wcWallet: WalletConnectWallet | undefined - private kernelProvider: KernelEIP1193Provider | undefined - - constructor() { - this.wcWallet = new WalletConnectWallet() - } - - async init({ - walletConnectProjectId, - walletConnectMetadata, - kernelClient, - kernelProvider - }: { - walletConnectProjectId: string - // biome-ignore lint/suspicious/noExplicitAny: - walletConnectMetadata: any - kernelClient?: KernelAccountClient< - EntryPoint, - Transport, - Chain, - KernelSmartAccount - > - kernelProvider?: KernelEIP1193Provider - }) { - if (!this.wcWallet) return - if (!kernelClient && !kernelProvider) { - throw new Error("Kernel client or provider must be provided") - } - await this.wcWallet.init({ - projectId: walletConnectProjectId, - metadata: walletConnectMetadata - }) - if (kernelProvider) { - this.kernelProvider = kernelProvider - } else if (kernelClient) { - this.kernelProvider = new KernelEIP1193Provider(kernelClient) - } - } - - async connect(uri: string) { - if (!this.wcWallet) return - if (uri && !uri.startsWith("wc:")) { - throw new Error("Invalid pairing code") - } - await this.wcWallet.connect(uri) - } - - async disconnect(session: SessionTypes.Struct) { - if (!this.wcWallet) return - await this.wcWallet.disconnectSession(session) - } - - onSessionRequest( - handler: (request: Web3WalletTypes.SessionRequest) => void - ) { - if (!this.wcWallet) return - this.wcWallet.onRequest(handler) - } - - onSessionProposal( - handler: (proposal: Web3WalletTypes.SessionProposal) => void - ) { - if (!this.wcWallet) return - this.wcWallet.onSessionPropose(handler) - } - - onSessionAdd(handler: () => void) { - if (!this.wcWallet) return - this.wcWallet.onSessionAdd(handler) - } - - onSessionDelete(handler: () => void) { - if (!this.wcWallet) return - this.wcWallet.onSessionDelete(handler) - } - - async approveSessionProposal( - proposal: Web3WalletTypes.SessionProposal, - chainId: string, - address: string - ) { - if (!this.wcWallet) return - await this.wcWallet.approveSession(proposal, chainId, address) - } - - async rejectSessionProposal(proposal: Web3WalletTypes.SessionProposal) { - if (!this.wcWallet) return - await this.wcWallet.rejectSession(proposal) - } - - async approveSessionRequest( - request: Web3WalletTypes.SessionRequest, - chainId: string - ) { - if (!this.wcWallet) return - - const { topic } = request - const session = this.wcWallet - .getActiveSessions() - .find((s) => s.topic === topic) - const requestChainId = stripEip155Prefix(request.params.chainId) - - const getResponse = () => { - // Get error if wrong chain - if ( - !session || - Number.parseInt(requestChainId) !== Number.parseInt(chainId) - ) { - const error = getSdkError("UNSUPPORTED_CHAINS") - return formatJsonRpcError(request.id, error) - } - return this.handleKernelRequest(request) - } - - try { - const response = await getResponse() - - // Send response to WalletConnect - await this.wcWallet.sendSessionResponse(topic, response) - } catch (e) { - const errorResponse = formatJsonRpcError(request.id, { - code: 5000, - message: (e as Error)?.message - }) - await this.wcWallet.sendSessionResponse(topic, errorResponse) - } - } - - async rejectSessionRequest(request: Web3WalletTypes.SessionRequest) { - if (!this.wcWallet) return - - const { topic, id } = request - const errorResponse = formatJsonRpcError(id, { - code: 5000, - message: "User Rejected" - }) - await this.wcWallet.sendSessionResponse(topic, errorResponse) - } - - getActiveSessions() { - if (!this.wcWallet) return - return this.wcWallet.getActiveSessions() - } - - async handleKernelRequest(event: Web3WalletTypes.SessionRequest) { - if (!this.kernelProvider) { - throw new Error("Kernel provider not initialized") - } - - const { params, id } = event - const { request } = params - if (request.method === "personal_sign") { - const requestParamsMessage = request.params[0] - - const message = hexToUtf8(requestParamsMessage) - const signedMessage = await this.kernelProvider.request({ - ...request, - params: [message, request.params[1]] - }) - - return { id, result: signedMessage, jsonrpc: "2.0" } - } - - if (request.method === "eth_sign") { - const requestParamsMessage = request.params[1] - - const message = hexToUtf8(requestParamsMessage) - const signedMessage = await this.kernelProvider.request({ - ...request, - params: [request.params[0], message] - }) - - return { id, result: signedMessage, jsonrpc: "2.0" } - } - - const result = await this.kernelProvider.request(request) - return { - jsonrpc: "2.0", - id: id, - result - } - } -} - -export default WalletConnectKernelService diff --git a/walletconnect/src/WalletConnectWallet.ts b/walletconnect/src/WalletConnectWallet.ts deleted file mode 100644 index 8b86fc5b..00000000 --- a/walletconnect/src/WalletConnectWallet.ts +++ /dev/null @@ -1,326 +0,0 @@ -import { Core } from "@walletconnect/core" -import type { JsonRpcResponse } from "@walletconnect/jsonrpc-utils" -import type { CoreTypes, SessionTypes } from "@walletconnect/types" -import { buildApprovedNamespaces, getSdkError } from "@walletconnect/utils" -import { Web3Wallet } from "@walletconnect/web3wallet" -import type Web3WalletType from "@walletconnect/web3wallet" -import type { Web3WalletTypes } from "@walletconnect/web3wallet" -import { uniq } from "lodash" -import { - EIP155, - KERNEL_COMPATIBLE_EVENTS, - KERNEL_COMPATIBLE_METHODS -} from "./constants" -import { getEip155ChainId, stripEip155Prefix } from "./utils" - -const SESSION_ADD_EVENT = "session_add" as Web3WalletTypes.Event // Workaround: WalletConnect doesn't emit session_add event -const SESSION_REJECT_EVENT = "session_reject" as Web3WalletTypes.Event // Workaround: WalletConnect doesn't emit session_reject event - -class WalletConnectWallet { - private web3Wallet: Web3WalletType | null = null - - public async init({ - projectId, - metadata - }: { - projectId: string - metadata: CoreTypes.Metadata - }) { - if (this.web3Wallet) return - - const core = new Core({ - projectId - }) - - const web3wallet = await Web3Wallet.init({ - core, - metadata - }) - - this.web3Wallet = web3wallet - } - - /** - * Subscribe to session proposals - */ - public onSessionPropose( - handler: (e: Web3WalletTypes.SessionProposal) => void - ) { - // Subscribe to the session proposal event - this.web3Wallet?.on("session_proposal", handler) - - // Return the unsubscribe function - return () => { - this.web3Wallet?.off("session_proposal", handler) - } - } - - public async approveSession( - proposal: Web3WalletTypes.SessionProposal, - currentChainId: string, - kernelAddress: string - ) { - if (!this.web3Wallet) throw new Error("WalletConnect not initialized") - - const namespaces = this.getNamespaces( - proposal, - currentChainId, - kernelAddress - ) - - // Approve the session proposal - const session = await this.web3Wallet.approveSession({ - id: proposal.id, - namespaces - }) - - const updatedNamespaces = { - ...session.namespaces, - ...this.getNamespaces(proposal, currentChainId, kernelAddress, true) - } - - await this.web3Wallet.updateSession({ - topic: session.topic, - namespaces: updatedNamespaces - }) - - await this.chainChanged(session.topic, currentChainId) - - // Workaround: WalletConnect doesn't have a session_add event - // and we want to update our state inside the useWalletConnectSessions hook - this.web3Wallet?.events.emit(SESSION_ADD_EVENT, session) - - // Return updated session as it may have changed - return ( - this.getActiveSessions().find( - ({ topic }) => topic === session.topic - ) ?? session - ) - } - - private getNamespaces( - proposal: Web3WalletTypes.SessionProposal, - currentChainId: string, - kernelAddress: string, - optional = false - ) { - const requiredChains = - proposal.params.requiredNamespaces[EIP155]?.chains || [] - const optionalChains = - proposal.params.optionalNamespaces[EIP155]?.chains || [] - - const supportedChainIds = [currentChainId].concat( - requiredChains.map(stripEip155Prefix), - optional ? optionalChains.map(stripEip155Prefix) : [] - ) - - const eip155ChainIds = supportedChainIds.map(getEip155ChainId) - const eip155Accounts = eip155ChainIds.map( - (eip155ChainId) => `${eip155ChainId}:${kernelAddress}` - ) - - // Don't include optionalNamespaces methods/events - const methods = uniq( - (proposal.params.requiredNamespaces[EIP155]?.methods || []).concat( - KERNEL_COMPATIBLE_METHODS - ) - ) - const events = uniq( - (proposal.params.requiredNamespaces[EIP155]?.events || []).concat( - KERNEL_COMPATIBLE_EVENTS - ) - ) - - return buildApprovedNamespaces({ - proposal: proposal.params, - supportedNamespaces: { - [EIP155]: { - chains: eip155ChainIds, - accounts: eip155Accounts, - methods, - events - } - } - }) - } - - public async chainChanged(topic: string, chainId: string) { - const eipChainId = getEip155ChainId(chainId) - - return this.web3Wallet?.emitSessionEvent({ - topic, - event: { - name: "chainChanged", - data: Number(chainId) - }, - chainId: eipChainId - }) - } - - /** - * Get active sessions - */ - public getActiveSessions(): SessionTypes.Struct[] { - const sessionsMap = this.web3Wallet?.getActiveSessions() || {} - return Object.values(sessionsMap) - } - - /** - * Connect using a wc-URI - */ - public async connect(uri: string) { - if (!this.web3Wallet) throw new Error("WalletConnect not initialized") - return this.web3Wallet.pair({ uri }) - } - - public async rejectSession(proposal: Web3WalletTypes.SessionProposal) { - if (!this.web3Wallet) throw new Error("WalletConnect not initialized") - - await this.web3Wallet.rejectSession({ - id: proposal.id, - reason: getSdkError("USER_REJECTED") - }) - - // Workaround: WalletConnect doesn't have a session_reject event - this.web3Wallet?.events.emit(SESSION_REJECT_EVENT, proposal) - } - - /** - * Subscribe to requests - */ - public onRequest(handler: (event: Web3WalletTypes.SessionRequest) => void) { - this.web3Wallet?.on("session_request", handler) - - return () => { - this.web3Wallet?.off("session_request", handler) - } - } - - /** - * Send a response to a request - */ - public async sendSessionResponse( - topic: string, - response: JsonRpcResponse - ) { - if (!this.web3Wallet) throw new Error("WalletConnect not initialized") - - return await this.web3Wallet.respondSessionRequest({ topic, response }) - } - - /** - * Disconnect a session - */ - public async disconnectSession(session: SessionTypes.Struct) { - if (!this.web3Wallet) throw new Error("WalletConnect not initialized") - - await this.web3Wallet.disconnectSession({ - topic: session.topic, - reason: getSdkError("USER_DISCONNECTED") - }) - - // Workaround: WalletConnect doesn't emit session_delete event when disconnecting from the wallet side - // and we want to update the state inside the useWalletConnectSessions hook - this.web3Wallet.events.emit("session_delete", session) - } - - /** - * Subscribe to session delete - */ - public onSessionDelete = ( - handler: (session: SessionTypes.Struct) => void - ) => { - // @ts-expect-error - custom event payload - this.web3Wallet?.on("session_delete", handler) - - return () => { - // @ts-expect-error - custom event payload - this.web3Wallet?.off("session_delete", handler) - } - } - - /** - * Subscribe to session add - */ - public onSessionAdd = (handler: (e: SessionTypes.Struct) => void) => { - // @ts-expect-error - custom event payload - this.web3Wallet?.on(SESSION_ADD_EVENT, handler) - - return () => { - // @ts-expect-error - custom event payload - this.web3Wallet?.off(SESSION_ADD_EVENT, handler) - } - } - - private async updateSession( - session: SessionTypes.Struct, - chainId: string, - address: string - ) { - if (!this.web3Wallet) throw new Error("WalletConnect not initialized") - - const currentEip155ChainIds = session.namespaces[EIP155]?.chains || [] - const currentEip155Accounts = session.namespaces[EIP155]?.accounts || [] - - const newEip155ChainId = getEip155ChainId(chainId) - const newEip155Account = `${newEip155ChainId}:${address}` - - const isUnsupportedChain = - !currentEip155ChainIds.includes(newEip155ChainId) - const isNewSession = !currentEip155Accounts.includes(newEip155Account) - - // Switching to unsupported chain - if (isUnsupportedChain) { - return this.disconnectSession(session) - } - - // Add new account to the session namespace - if (isNewSession) { - const namespaces: SessionTypes.Namespaces = { - [EIP155]: { - ...session.namespaces[EIP155], - chains: currentEip155ChainIds, - accounts: [newEip155Account, ...currentEip155Accounts] - } - } - - await this.web3Wallet.updateSession({ - topic: session.topic, - namespaces - }) - } - - // Switch to the new chain - await this.chainChanged(session.topic, chainId) - - // Switch to the new account - await this.accountsChanged(session.topic, chainId, address) - } - - public async accountsChanged( - topic: string, - chainId: string, - address: string - ) { - const eipChainId = getEip155ChainId(chainId) - - return this.web3Wallet?.emitSessionEvent({ - topic, - event: { - name: "accountsChanged", - data: [address] - }, - chainId: eipChainId - }) - } - - public async updateSessions(chainId: string, address: string) { - // If updating sessions disconnects multiple due to an unsupported chain, - // we need to wait for the previous session to disconnect before the next - for await (const session of this.getActiveSessions()) { - await this.updateSession(session, chainId, address) - } - } -} - -export default WalletConnectWallet diff --git a/walletconnect/src/constants.ts b/walletconnect/src/constants.ts deleted file mode 100644 index c3e8a7f2..00000000 --- a/walletconnect/src/constants.ts +++ /dev/null @@ -1,35 +0,0 @@ -export const EIP155 = "eip155" as const - -export const KERNEL_COMPATIBLE_METHODS = [ - "eth_accounts", - "eth_chainId", - "personal_sign", - "eth_sign", - "eth_signTypedData", - "eth_signTypedData_v4", - "eth_sendTransaction", - "eth_blockNumber", - "eth_getBalance", - "eth_getCode", - "eth_getTransactionCount", - "eth_getStorageAt", - "eth_getBlockByNumber", - "eth_getBlockByHash", - "eth_getTransactionByHash", - "eth_getTransactionReceipt", - "eth_estimateGas", - "eth_call", - "eth_getLogs", - "eth_gasPrice", - "wallet_getCapabilities", - "wallet_sendCalls", - "wallet_getCallStatus", - "wallet_issuePermissions", - "wallet_switchEthereumChain" -] - -export const KERNEL_COMPATIBLE_EVENTS = ["chainChanged", "accountsChanged"] - -export const stripEip155Prefix = (eip155Address: string): string => { - return eip155Address.split(":").pop() ?? "" -} diff --git a/walletconnect/src/utils.ts b/walletconnect/src/utils.ts deleted file mode 100644 index 1e643a1e..00000000 --- a/walletconnect/src/utils.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { ProposalTypes, SessionTypes } from "@walletconnect/types" -import { EIP155 } from "./constants" - -export const stripEip155Prefix = (eip155Address: string): string => { - return eip155Address.split(":").pop() ?? "" -} - -export const getEip155ChainId = (chainId: string): string => { - return `${EIP155}:${chainId}` -} - -export const asError = (thrown: unknown): Error => { - if (thrown instanceof Error) { - return thrown - } - - let message: string - - if (typeof thrown === "string") { - message = thrown - } else { - try { - message = JSON.stringify(thrown) - } catch { - message = String(thrown) - } - } - - return new Error(message) -} - -enum Errors { - WRONG_CHAIN = "%%dappName%% made a request on a different chain than the one you are connected to" -} - -export const getWrongChainError = (dappName: string): Error => { - const message = Errors.WRONG_CHAIN.replace("%%dappName%%", dappName) - return new Error(message) -} - -export const getPeerName = ( - peer: SessionTypes.Struct["peer"] | ProposalTypes.Struct["proposer"] -): string => { - return peer.metadata?.name || peer.metadata?.url || "" -} diff --git a/walletconnect/tsconfig.build.json b/walletconnect/tsconfig.build.json deleted file mode 100644 index 0ced61c7..00000000 --- a/walletconnect/tsconfig.build.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../templates/typescript/tsconfig.build.json", - "include": ["./"], - "exclude": ["./**/*.test.ts", "./**/*.test-d.ts", "./**/*.bench.ts"], - "compilerOptions": { - "moduleResolution": "node", - "sourceMap": true, - "rootDir": "./", - "baseUrl": "./", - "allowSyntheticDefaultImports": true - } -}