repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,479 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeAbiParameters, + encodeFunctionData, + toHex, + zeroAddress +} from "viem" +import { + getChainId, + readContract, + signMessage as _signMessage +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import type { EntryPoint, Prettify } from "../../types" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import type { SmartAccount } from "../types" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccountSigner +} from "../types" +import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi" +import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants" +import { encodeCallData } from "./utils/encodeCallData" +import { getInitMSAData } from "./utils/getInitMSAData" +import { getNonceKeyWithEncoding } from "./utils/getNonceKey" +import { signMessage } from "./utils/signMessage" +import { signTypedData } from "./utils/signTypedData" + +export type EtherspotSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain> + +/** + * The account creation ABI for a modular etherspot smart account + */ +const createAccountAbi = [ + { + inputs: [ + { + internalType: "bytes32", + name: "salt", + type: "bytes32" + }, + { + internalType: "bytes", + name: "initCode", + type: "bytes" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "payable", + type: "function" + } +] as const + +type KERNEL_ADDRESSES = { + ecdsaValidatorAddress: Address + accountLogicAddress: Address + factoryAddress: Address + metaFactoryAddress: Address + bootstrapAddress: Address +} + +/** + * Get default addresses for Etherspot Smart Account based on chainId + * @param chainId + * @param ecdsaValidatorAddress + * @param accountLogicAddress + * @param factoryAddress + * @param metaFactoryAddress + */ +const getDefaultAddresses = ( + chainId: number, + { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }: Partial<KERNEL_ADDRESSES> +): KERNEL_ADDRESSES => { + const addresses = Networks[chainId] + const ecdsaValidatorAddress = + _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator + const accountLogicAddress = + _accountLogicAddress ?? addresses.modularEtherspotWallet + const factoryAddress = + _factoryAddress ?? addresses.modularEtherspotWalletFactory + const metaFactoryAddress = + _metaFactoryAddress ?? + addresses?.modularEtherspotWalletFactory ?? + zeroAddress + const bootstrapAddress = addresses.bootstrap ?? zeroAddress + + return { + ecdsaValidatorAddress, + accountLogicAddress, + factoryAddress, + metaFactoryAddress, + bootstrapAddress + }
I see only `ecdsaValidatorAddress, metaFactoryAddress, bootstrapAddress` are being used, what is the reason for other addresses to be returned?
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,479 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeAbiParameters, + encodeFunctionData, + toHex, + zeroAddress +} from "viem" +import { + getChainId, + readContract, + signMessage as _signMessage +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import type { EntryPoint, Prettify } from "../../types" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import type { SmartAccount } from "../types" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccountSigner +} from "../types" +import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi" +import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants" +import { encodeCallData } from "./utils/encodeCallData" +import { getInitMSAData } from "./utils/getInitMSAData" +import { getNonceKeyWithEncoding } from "./utils/getNonceKey" +import { signMessage } from "./utils/signMessage" +import { signTypedData } from "./utils/signTypedData" + +export type EtherspotSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain> + +/** + * The account creation ABI for a modular etherspot smart account + */ +const createAccountAbi = [ + { + inputs: [ + { + internalType: "bytes32", + name: "salt", + type: "bytes32" + }, + { + internalType: "bytes", + name: "initCode", + type: "bytes" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "payable", + type: "function" + } +] as const + +type KERNEL_ADDRESSES = { + ecdsaValidatorAddress: Address + accountLogicAddress: Address + factoryAddress: Address + metaFactoryAddress: Address + bootstrapAddress: Address +} + +/** + * Get default addresses for Etherspot Smart Account based on chainId + * @param chainId + * @param ecdsaValidatorAddress + * @param accountLogicAddress + * @param factoryAddress + * @param metaFactoryAddress + */ +const getDefaultAddresses = ( + chainId: number, + { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }: Partial<KERNEL_ADDRESSES> +): KERNEL_ADDRESSES => { + const addresses = Networks[chainId] + const ecdsaValidatorAddress = + _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator + const accountLogicAddress = + _accountLogicAddress ?? addresses.modularEtherspotWallet + const factoryAddress = + _factoryAddress ?? addresses.modularEtherspotWalletFactory + const metaFactoryAddress = + _metaFactoryAddress ?? + addresses?.modularEtherspotWalletFactory ?? + zeroAddress + const bootstrapAddress = addresses.bootstrap ?? zeroAddress + + return { + ecdsaValidatorAddress, + accountLogicAddress, + factoryAddress, + metaFactoryAddress, + bootstrapAddress + } +} + +export const getEcdsaRootIdentifier = (validatorAddress: Address) => { + return concatHex([VALIDATOR_TYPE.VALIDATOR, validatorAddress]) +} + +/** + * Get the initialization data for a etherspot smart account + * @param entryPoint + * @param owner + * @param ecdsaValidatorAddress + */ +const getInitialisationData = <entryPoint extends EntryPoint>({ + entryPoint: entryPointAddress, + owner, + ecdsaValidatorAddress, + bootstrapAddress +}: { + entryPoint: entryPoint + owner: Address + ecdsaValidatorAddress: Address + bootstrapAddress: Address +}) => { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + if (entryPointVersion === "v0.6") { + throw new Error("Only EntryPoint 0.7 is supported") + } + + const initMSAData = getInitMSAData(ecdsaValidatorAddress) + + const initCode = encodeAbiParameters( + [{ type: "address" }, { type: "address" }, { type: "bytes" }], + [owner, bootstrapAddress, initMSAData] + ) + + return initCode +} + +/** + * Get the account initialization code for a etherspot smart account + * @param entryPoint + * @param owner + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async <entryPoint extends EntryPoint>({ + entryPoint: entryPointAddress, + owner, + index, + ecdsaValidatorAddress, + bootstrapAddress +}: { + entryPoint: entryPoint + owner: Address + index: bigint + ecdsaValidatorAddress: Address + bootstrapAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the account initialization data + const initialisationData = getInitialisationData({ + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + owner, + bootstrapAddress + }) + + return encodeFunctionData({ + abi: createAccountAbi, + functionName: "createAccount", + args: [toHex(index, { size: 32 }), initialisationData] + }) +} + +/** + * Check the validity of an existing account address, or fetch the pre-deterministic account address for a etherspot smart wallet + * @param client + * @param owner + * @param entryPoint + * @param ecdsaValidatorAddress + * @param initCodeProvider + * @param deployedAccountAddress + * @param factoryAddress + */ +const getAccountAddress = async < + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + owner, + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + bootstrapAddress, + factoryAddress, + index +}: { + client: Client<TTransport, TChain> + owner: Address + factoryAddress: Address + entryPoint: entryPoint + ecdsaValidatorAddress: Address + bootstrapAddress: Address + index: bigint +}): Promise<Address> => { + const factoryData = getInitialisationData({ + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + owner, + bootstrapAddress + }) + + return await readContract(client, { + address: factoryAddress, + abi: EtherspotWalletFactoryAbi, + functionName: "getAddress", + args: [toHex(index, { size: 32 }), factoryData] + }) +} + +export type SignerToEtherspotSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = Prettify<{ + signer: SmartAccountSigner<TSource, TAddress> + entryPoint: entryPoint + address?: Address + index?: bigint + factoryAddress?: Address + metaFactoryAddress?: Address + accountLogicAddress?: Address + ecdsaValidatorAddress?: Address + deployedAccountAddress?: Address +}> +/** + * Build a etherspot smart account from a private key, that use the ECDSA signer behind the scene + * @param client + * @param privateKey + * @param entryPoint + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + * @param deployedAccountAddress + */ +export async function signerToEtherspotSmartAccount< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TSource extends string = string, + TAddress extends Address = Address +>( + client: Client<TTransport, TChain, undefined>, + { + signer, + address, + entryPoint: entryPointAddress, + index = BigInt(0), + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress, + accountLogicAddress: _accountLogicAddress, + ecdsaValidatorAddress: _ecdsaValidatorAddress + }: SignerToEtherspotSmartAccountParameters<entryPoint, TSource, TAddress> +): Promise<EtherspotSmartAccount<entryPoint, TTransport, TChain>> { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + if (entryPointVersion === "v0.6") { + throw new Error("Only EntryPoint 0.7 is supported") + } + + const chainID = await getChainId(client) + const { ecdsaValidatorAddress, metaFactoryAddress, bootstrapAddress } = + getDefaultAddresses(chainID, { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }) + + // Get the private key related account + const viemSigner: LocalAccount = { + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } as LocalAccount + + // Helper to generate the init code for the smart account + const generateInitCode = () => + getAccountInitCode({ + entryPoint: entryPointAddress, + owner: viemSigner.address, + index, + ecdsaValidatorAddress, + bootstrapAddress + }) + + // Fetch account address and chain id + const [accountAddress, chainId] = await Promise.all([ + address ?? + getAccountAddress<entryPoint, TTransport, TChain>({ + client, + entryPoint: entryPointAddress, + owner: viemSigner.address, + ecdsaValidatorAddress, + factoryAddress: metaFactoryAddress, + bootstrapAddress, + index + }), + client.chain?.id ?? getChainId(client)
I think we can reuse the chainId variable you created above to minimize the api requests.
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,479 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeAbiParameters, + encodeFunctionData, + toHex, + zeroAddress +} from "viem" +import { + getChainId, + readContract, + signMessage as _signMessage +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import type { EntryPoint, Prettify } from "../../types" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import type { SmartAccount } from "../types" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccountSigner +} from "../types" +import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi" +import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants" +import { encodeCallData } from "./utils/encodeCallData" +import { getInitMSAData } from "./utils/getInitMSAData" +import { getNonceKeyWithEncoding } from "./utils/getNonceKey" +import { signMessage } from "./utils/signMessage" +import { signTypedData } from "./utils/signTypedData" + +export type EtherspotSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain> + +/** + * The account creation ABI for a modular etherspot smart account + */ +const createAccountAbi = [ + { + inputs: [ + { + internalType: "bytes32", + name: "salt", + type: "bytes32" + }, + { + internalType: "bytes", + name: "initCode", + type: "bytes" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "payable", + type: "function" + } +] as const + +type KERNEL_ADDRESSES = { + ecdsaValidatorAddress: Address + accountLogicAddress: Address + factoryAddress: Address + metaFactoryAddress: Address + bootstrapAddress: Address +} + +/** + * Get default addresses for Etherspot Smart Account based on chainId + * @param chainId + * @param ecdsaValidatorAddress + * @param accountLogicAddress + * @param factoryAddress + * @param metaFactoryAddress + */ +const getDefaultAddresses = ( + chainId: number, + { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }: Partial<KERNEL_ADDRESSES> +): KERNEL_ADDRESSES => { + const addresses = Networks[chainId] + const ecdsaValidatorAddress = + _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator + const accountLogicAddress = + _accountLogicAddress ?? addresses.modularEtherspotWallet + const factoryAddress = + _factoryAddress ?? addresses.modularEtherspotWalletFactory + const metaFactoryAddress = + _metaFactoryAddress ?? + addresses?.modularEtherspotWalletFactory ?? + zeroAddress + const bootstrapAddress = addresses.bootstrap ?? zeroAddress + + return { + ecdsaValidatorAddress, + accountLogicAddress, + factoryAddress, + metaFactoryAddress, + bootstrapAddress + } +} + +export const getEcdsaRootIdentifier = (validatorAddress: Address) => { + return concatHex([VALIDATOR_TYPE.VALIDATOR, validatorAddress])
The function name says `root` identifier but we are returning type `validator`. I see there is `VALIDATOR_TYPE.ROOT` also. Can we change the name.
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,479 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeAbiParameters, + encodeFunctionData, + toHex, + zeroAddress +} from "viem" +import { + getChainId, + readContract, + signMessage as _signMessage +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import type { EntryPoint, Prettify } from "../../types" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import type { SmartAccount } from "../types" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccountSigner +} from "../types" +import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi" +import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants" +import { encodeCallData } from "./utils/encodeCallData" +import { getInitMSAData } from "./utils/getInitMSAData" +import { getNonceKeyWithEncoding } from "./utils/getNonceKey" +import { signMessage } from "./utils/signMessage" +import { signTypedData } from "./utils/signTypedData" + +export type EtherspotSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain> + +/** + * The account creation ABI for a modular etherspot smart account + */ +const createAccountAbi = [ + { + inputs: [ + { + internalType: "bytes32", + name: "salt", + type: "bytes32" + }, + { + internalType: "bytes", + name: "initCode", + type: "bytes" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "payable", + type: "function" + } +] as const + +type KERNEL_ADDRESSES = { + ecdsaValidatorAddress: Address + accountLogicAddress: Address + factoryAddress: Address + metaFactoryAddress: Address + bootstrapAddress: Address +} + +/** + * Get default addresses for Etherspot Smart Account based on chainId + * @param chainId + * @param ecdsaValidatorAddress + * @param accountLogicAddress + * @param factoryAddress + * @param metaFactoryAddress + */ +const getDefaultAddresses = ( + chainId: number, + { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }: Partial<KERNEL_ADDRESSES> +): KERNEL_ADDRESSES => { + const addresses = Networks[chainId] + const ecdsaValidatorAddress = + _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator + const accountLogicAddress = + _accountLogicAddress ?? addresses.modularEtherspotWallet + const factoryAddress = + _factoryAddress ?? addresses.modularEtherspotWalletFactory + const metaFactoryAddress = + _metaFactoryAddress ?? + addresses?.modularEtherspotWalletFactory ?? + zeroAddress + const bootstrapAddress = addresses.bootstrap ?? zeroAddress + + return { + ecdsaValidatorAddress, + accountLogicAddress, + factoryAddress, + metaFactoryAddress, + bootstrapAddress + } +} + +export const getEcdsaRootIdentifier = (validatorAddress: Address) => { + return concatHex([VALIDATOR_TYPE.VALIDATOR, validatorAddress]) +} + +/** + * Get the initialization data for a etherspot smart account + * @param entryPoint + * @param owner + * @param ecdsaValidatorAddress + */ +const getInitialisationData = <entryPoint extends EntryPoint>({ + entryPoint: entryPointAddress, + owner, + ecdsaValidatorAddress, + bootstrapAddress +}: { + entryPoint: entryPoint + owner: Address + ecdsaValidatorAddress: Address + bootstrapAddress: Address +}) => { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + if (entryPointVersion === "v0.6") { + throw new Error("Only EntryPoint 0.7 is supported") + } + + const initMSAData = getInitMSAData(ecdsaValidatorAddress) + + const initCode = encodeAbiParameters( + [{ type: "address" }, { type: "address" }, { type: "bytes" }], + [owner, bootstrapAddress, initMSAData] + ) + + return initCode +} + +/** + * Get the account initialization code for a etherspot smart account + * @param entryPoint + * @param owner + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async <entryPoint extends EntryPoint>({ + entryPoint: entryPointAddress, + owner, + index, + ecdsaValidatorAddress, + bootstrapAddress +}: { + entryPoint: entryPoint + owner: Address + index: bigint + ecdsaValidatorAddress: Address + bootstrapAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the account initialization data + const initialisationData = getInitialisationData({ + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + owner, + bootstrapAddress + }) + + return encodeFunctionData({ + abi: createAccountAbi, + functionName: "createAccount", + args: [toHex(index, { size: 32 }), initialisationData] + }) +} + +/** + * Check the validity of an existing account address, or fetch the pre-deterministic account address for a etherspot smart wallet + * @param client + * @param owner + * @param entryPoint + * @param ecdsaValidatorAddress + * @param initCodeProvider + * @param deployedAccountAddress + * @param factoryAddress + */ +const getAccountAddress = async < + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + owner, + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + bootstrapAddress, + factoryAddress, + index +}: { + client: Client<TTransport, TChain> + owner: Address + factoryAddress: Address + entryPoint: entryPoint + ecdsaValidatorAddress: Address + bootstrapAddress: Address + index: bigint +}): Promise<Address> => { + const factoryData = getInitialisationData({ + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + owner, + bootstrapAddress + }) + + return await readContract(client, { + address: factoryAddress, + abi: EtherspotWalletFactoryAbi, + functionName: "getAddress", + args: [toHex(index, { size: 32 }), factoryData] + }) +} + +export type SignerToEtherspotSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = Prettify<{ + signer: SmartAccountSigner<TSource, TAddress> + entryPoint: entryPoint + address?: Address + index?: bigint + factoryAddress?: Address + metaFactoryAddress?: Address + accountLogicAddress?: Address + ecdsaValidatorAddress?: Address + deployedAccountAddress?: Address +}> +/** + * Build a etherspot smart account from a private key, that use the ECDSA signer behind the scene + * @param client + * @param privateKey + * @param entryPoint + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + * @param deployedAccountAddress + */ +export async function signerToEtherspotSmartAccount< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TSource extends string = string, + TAddress extends Address = Address +>( + client: Client<TTransport, TChain, undefined>, + { + signer, + address, + entryPoint: entryPointAddress, + index = BigInt(0), + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress, + accountLogicAddress: _accountLogicAddress, + ecdsaValidatorAddress: _ecdsaValidatorAddress + }: SignerToEtherspotSmartAccountParameters<entryPoint, TSource, TAddress> +): Promise<EtherspotSmartAccount<entryPoint, TTransport, TChain>> { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + if (entryPointVersion === "v0.6") { + throw new Error("Only EntryPoint 0.7 is supported") + } + + const chainID = await getChainId(client) + const { ecdsaValidatorAddress, metaFactoryAddress, bootstrapAddress } = + getDefaultAddresses(chainID, { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }) + + // Get the private key related account + const viemSigner: LocalAccount = { + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } as LocalAccount + + // Helper to generate the init code for the smart account + const generateInitCode = () => + getAccountInitCode({ + entryPoint: entryPointAddress, + owner: viemSigner.address, + index, + ecdsaValidatorAddress, + bootstrapAddress + }) + + // Fetch account address and chain id + const [accountAddress, chainId] = await Promise.all([ + address ?? + getAccountAddress<entryPoint, TTransport, TChain>({ + client, + entryPoint: entryPointAddress, + owner: viemSigner.address, + ecdsaValidatorAddress, + factoryAddress: metaFactoryAddress, + bootstrapAddress, + index + }), + client.chain?.id ?? getChainId(client) + ]) + + if (!accountAddress) throw new Error("Account address not found") + + let smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + return toSmartAccount({ + address: accountAddress, + async signMessage({ message }) { + const signature = await signMessage(client, { + account: viemSigner, + message, + accountAddress, + chainId + }) + + return concatHex([ + getEcdsaRootIdentifier(ecdsaValidatorAddress), + 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>) { + const signature = await signTypedData< + TTypedData, + TPrimaryType, + TChain, + undefined + >(client, { + account: viemSigner, + ...typedData, + accountAddress, + chainId + }) + + return concatHex([ + getEcdsaRootIdentifier(ecdsaValidatorAddress), + signature + ]) + }, + client: client, + publicKey: accountAddress, + entryPoint: entryPointAddress, + source: "etherspotSmartAccount", + + // Get the nonce of the smart account + async getNonce() { + const key = getNonceKeyWithEncoding( + ecdsaValidatorAddress + // @dev specify the custom nonceKey here when integrating the said feature + /*, nonceKey */ + ) + return getAccountNonce(client, { + sender: accountAddress, + entryPoint: entryPointAddress, + key + }) + }, + + // Sign a user operation + async signUserOperation(userOperation) { + const hash = getUserOperationHash({ + userOperation: { + ...userOperation, + signature: "0x" + }, + entryPoint: entryPointAddress, + chainId: chainId + }) + const signature = await _signMessage(client, { + account: viemSigner, + message: { raw: hash } + }) + + return signature + }, + + // Encode the init code + async getInitCode() { + if (smartAccountDeployed) return "0x" + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return "0x" + + const _factoryAddress = metaFactoryAddress + return concatHex([_factoryAddress, await generateInitCode()]) + }, + + async getFactory() { + if (smartAccountDeployed) return undefined + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return undefined + + return metaFactoryAddress + }, + + async getFactoryData() { + if (smartAccountDeployed) return undefined + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return undefined + + return generateInitCode() + }, + + // Encode the deploy call data + async encodeDeployCallData(_) { + throw new Error("Simple account doesn't support account deployment")
We will have to change the error here to `Etherspot smart account doesn't support account deployment`. Though if you do have a default create2 proxy you can encode the transaction using that.
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,479 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeAbiParameters, + encodeFunctionData, + toHex, + zeroAddress +} from "viem" +import { + getChainId, + readContract, + signMessage as _signMessage +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import type { EntryPoint, Prettify } from "../../types" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import type { SmartAccount } from "../types" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccountSigner +} from "../types" +import { EtherspotWalletFactoryAbi } from "./abi/EtherspotWalletFactoryAbi" +import { DUMMY_ECDSA_SIGNATURE, Networks, VALIDATOR_TYPE } from "./constants" +import { encodeCallData } from "./utils/encodeCallData" +import { getInitMSAData } from "./utils/getInitMSAData" +import { getNonceKeyWithEncoding } from "./utils/getNonceKey" +import { signMessage } from "./utils/signMessage" +import { signTypedData } from "./utils/signTypedData" + +export type EtherspotSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "etherspotSmartAccount", transport, chain> + +/** + * The account creation ABI for a modular etherspot smart account + */ +const createAccountAbi = [ + { + inputs: [ + { + internalType: "bytes32", + name: "salt", + type: "bytes32" + }, + { + internalType: "bytes", + name: "initCode", + type: "bytes" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + stateMutability: "payable", + type: "function" + } +] as const + +type KERNEL_ADDRESSES = { + ecdsaValidatorAddress: Address + accountLogicAddress: Address + factoryAddress: Address + metaFactoryAddress: Address + bootstrapAddress: Address +} + +/** + * Get default addresses for Etherspot Smart Account based on chainId + * @param chainId + * @param ecdsaValidatorAddress + * @param accountLogicAddress + * @param factoryAddress + * @param metaFactoryAddress + */ +const getDefaultAddresses = ( + chainId: number, + { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }: Partial<KERNEL_ADDRESSES> +): KERNEL_ADDRESSES => { + const addresses = Networks[chainId] + const ecdsaValidatorAddress = + _ecdsaValidatorAddress ?? addresses.multipleOwnerECDSAValidator + const accountLogicAddress = + _accountLogicAddress ?? addresses.modularEtherspotWallet + const factoryAddress = + _factoryAddress ?? addresses.modularEtherspotWalletFactory + const metaFactoryAddress = + _metaFactoryAddress ?? + addresses?.modularEtherspotWalletFactory ?? + zeroAddress + const bootstrapAddress = addresses.bootstrap ?? zeroAddress + + return { + ecdsaValidatorAddress, + accountLogicAddress, + factoryAddress, + metaFactoryAddress, + bootstrapAddress + } +} + +export const getEcdsaRootIdentifier = (validatorAddress: Address) => { + return concatHex([VALIDATOR_TYPE.VALIDATOR, validatorAddress]) +} + +/** + * Get the initialization data for a etherspot smart account + * @param entryPoint + * @param owner + * @param ecdsaValidatorAddress + */ +const getInitialisationData = <entryPoint extends EntryPoint>({ + entryPoint: entryPointAddress, + owner, + ecdsaValidatorAddress, + bootstrapAddress +}: { + entryPoint: entryPoint + owner: Address + ecdsaValidatorAddress: Address + bootstrapAddress: Address +}) => { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + if (entryPointVersion === "v0.6") { + throw new Error("Only EntryPoint 0.7 is supported") + } + + const initMSAData = getInitMSAData(ecdsaValidatorAddress) + + const initCode = encodeAbiParameters( + [{ type: "address" }, { type: "address" }, { type: "bytes" }], + [owner, bootstrapAddress, initMSAData] + ) + + return initCode +} + +/** + * Get the account initialization code for a etherspot smart account + * @param entryPoint + * @param owner + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async <entryPoint extends EntryPoint>({ + entryPoint: entryPointAddress, + owner, + index, + ecdsaValidatorAddress, + bootstrapAddress +}: { + entryPoint: entryPoint + owner: Address + index: bigint + ecdsaValidatorAddress: Address + bootstrapAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the account initialization data + const initialisationData = getInitialisationData({ + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + owner, + bootstrapAddress + }) + + return encodeFunctionData({ + abi: createAccountAbi, + functionName: "createAccount", + args: [toHex(index, { size: 32 }), initialisationData] + }) +} + +/** + * Check the validity of an existing account address, or fetch the pre-deterministic account address for a etherspot smart wallet + * @param client + * @param owner + * @param entryPoint + * @param ecdsaValidatorAddress + * @param initCodeProvider + * @param deployedAccountAddress + * @param factoryAddress + */ +const getAccountAddress = async < + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + owner, + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + bootstrapAddress, + factoryAddress, + index +}: { + client: Client<TTransport, TChain> + owner: Address + factoryAddress: Address + entryPoint: entryPoint + ecdsaValidatorAddress: Address + bootstrapAddress: Address + index: bigint +}): Promise<Address> => { + const factoryData = getInitialisationData({ + entryPoint: entryPointAddress, + ecdsaValidatorAddress, + owner, + bootstrapAddress + }) + + return await readContract(client, { + address: factoryAddress, + abi: EtherspotWalletFactoryAbi, + functionName: "getAddress", + args: [toHex(index, { size: 32 }), factoryData] + }) +} + +export type SignerToEtherspotSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = Prettify<{ + signer: SmartAccountSigner<TSource, TAddress> + entryPoint: entryPoint + address?: Address + index?: bigint + factoryAddress?: Address + metaFactoryAddress?: Address + accountLogicAddress?: Address + ecdsaValidatorAddress?: Address + deployedAccountAddress?: Address +}> +/** + * Build a etherspot smart account from a private key, that use the ECDSA signer behind the scene + * @param client + * @param privateKey + * @param entryPoint + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + * @param deployedAccountAddress + */ +export async function signerToEtherspotSmartAccount< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TSource extends string = string, + TAddress extends Address = Address +>( + client: Client<TTransport, TChain, undefined>, + { + signer, + address, + entryPoint: entryPointAddress, + index = BigInt(0), + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress, + accountLogicAddress: _accountLogicAddress, + ecdsaValidatorAddress: _ecdsaValidatorAddress + }: SignerToEtherspotSmartAccountParameters<entryPoint, TSource, TAddress> +): Promise<EtherspotSmartAccount<entryPoint, TTransport, TChain>> { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + if (entryPointVersion === "v0.6") { + throw new Error("Only EntryPoint 0.7 is supported") + } + + const chainID = await getChainId(client) + const { ecdsaValidatorAddress, metaFactoryAddress, bootstrapAddress } = + getDefaultAddresses(chainID, { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }) + + // Get the private key related account + const viemSigner: LocalAccount = { + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } as LocalAccount + + // Helper to generate the init code for the smart account + const generateInitCode = () => + getAccountInitCode({ + entryPoint: entryPointAddress, + owner: viemSigner.address, + index, + ecdsaValidatorAddress, + bootstrapAddress + }) + + // Fetch account address and chain id + const [accountAddress, chainId] = await Promise.all([ + address ?? + getAccountAddress<entryPoint, TTransport, TChain>({ + client, + entryPoint: entryPointAddress, + owner: viemSigner.address, + ecdsaValidatorAddress, + factoryAddress: metaFactoryAddress, + bootstrapAddress, + index + }), + client.chain?.id ?? getChainId(client) + ]) + + if (!accountAddress) throw new Error("Account address not found") + + let smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + return toSmartAccount({ + address: accountAddress, + async signMessage({ message }) { + const signature = await signMessage(client, { + account: viemSigner, + message, + accountAddress, + chainId + }) + + return concatHex([ + getEcdsaRootIdentifier(ecdsaValidatorAddress), + 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>) { + const signature = await signTypedData< + TTypedData, + TPrimaryType, + TChain, + undefined + >(client, { + account: viemSigner, + ...typedData, + accountAddress, + chainId + }) + + return concatHex([ + getEcdsaRootIdentifier(ecdsaValidatorAddress), + signature + ]) + }, + client: client, + publicKey: accountAddress, + entryPoint: entryPointAddress, + source: "etherspotSmartAccount", + + // Get the nonce of the smart account + async getNonce() { + const key = getNonceKeyWithEncoding( + ecdsaValidatorAddress + // @dev specify the custom nonceKey here when integrating the said feature + /*, nonceKey */ + ) + return getAccountNonce(client, { + sender: accountAddress, + entryPoint: entryPointAddress, + key + }) + }, + + // Sign a user operation + async signUserOperation(userOperation) { + const hash = getUserOperationHash({ + userOperation: { + ...userOperation, + signature: "0x" + }, + entryPoint: entryPointAddress, + chainId: chainId + }) + const signature = await _signMessage(client, { + account: viemSigner, + message: { raw: hash } + }) + + return signature + }, + + // Encode the init code + async getInitCode() { + if (smartAccountDeployed) return "0x" + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return "0x" + + const _factoryAddress = metaFactoryAddress + return concatHex([_factoryAddress, await generateInitCode()]) + }, + + async getFactory() { + if (smartAccountDeployed) return undefined + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return undefined + + return metaFactoryAddress + }, + + async getFactoryData() { + if (smartAccountDeployed) return undefined + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return undefined + + return generateInitCode() + }, + + // Encode the deploy call data + async encodeDeployCallData(_) { + throw new Error("Simple account doesn't support account deployment") + }, + + // Encode a call + async encodeCallData(_tx) {
Can you change `_tx -> tx`. We use `_` to denote unused variables.
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,89 @@ +import { + type Address, + type Hex, + concatHex, + encodeAbiParameters, + encodeFunctionData, + toHex +} from "viem" +import { EtherspotExecuteAbi } from "../abi/EtherspotExecuteAbi" +import { CALL_TYPE, EXEC_TYPE } from "../constants" +import { getExecMode } from "./getExecMode" + +export const encodeCallData = ( + _tx:
Can you change `_tx -> tx`. We use `_` to denote unused variables.
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,39 @@ +import { + type Account, + type Chain, + type Client, + type LocalAccount, + type SignMessageParameters, + type SignMessageReturnType, + type Transport, + hashMessage, + publicActions +} from "viem" +import { signMessage as _signMessage } from "viem/actions" +import { type WrapMessageHashParams, wrapMessageHash } from "./wrapMessageHash" + +export async function signMessage< + TChain extends Chain | undefined, + TAccount extends Account | undefined +>( + client: Client<Transport, TChain, TAccount>, + { + account: account_ = client.account, + message, + accountAddress + }: SignMessageParameters<TAccount> & WrapMessageHashParams +): Promise<SignMessageReturnType> {
can we make chainId an explicit parameter, since we do make a chain id call in the account, this will save an extra chain id call if client doens't have chain. Checkout `GetChainParameter<TChain, TChainOverride>` in https://github.com/pimlicolabs/permissionless.js/blob/main/packages/permissionless/experimental/eip7677/actions/getPaymasterData.ts#L100
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -0,0 +1,68 @@ +import { + type Account, + type Chain, + type Client, + type LocalAccount, + type SignTypedDataParameters, + type SignTypedDataReturnType, + type Transport, + type TypedData, + getTypesForEIP712Domain, + hashTypedData, + publicActions, + validateTypedData +} from "viem" + +import { + signMessage as _signMessage,
since there is no other `signMessage` we don't need to rename it.
permissionless.js
github_2023
typescript
214
pimlicolabs
plusminushalf
@@ -85,5 +91,8 @@ export { type PrivateKeyToSafeSmartAccountParameters, type SignerToEcdsaKernelSmartAccountParameters, type SignerToBiconomySmartAccountParameters, - type PrivateKeyToBiconomySmartAccountParameters + type PrivateKeyToBiconomySmartAccountParameters, + type EtherspotSmartAccount, + type SignerToEtherspotSmartAccountParameters,
can we also add `PrivateKeyToEtherspotSmartAccount` file
permissionless.js
github_2023
typescript
255
pimlicolabs
kristofgazso
@@ -0,0 +1,120 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type Transport, + encodeFunctionData, + getAddress +} from "viem" +import { getAction } from "viem/utils" +import type { SmartAccount } from "../../accounts/types" +import type { GetAccountParameter, Prettify } from "../../types/" +import type { EntryPoint } from "../../types/entrypoint" +import { parseAccount } from "../../utils/" +import { AccountOrClientNotFoundError } from "../../utils/signUserOperationHashWithECDSA" +import type { Middleware } from "../smartAccount/prepareUserOperationRequest" +import { sendUserOperation } from "../smartAccount/sendUserOperation" +import { type ModuleType, parseModuleTypeId } from "./supportsModule" + +export type UninstallModulesParameters< + TEntryPoint extends EntryPoint, + TSmartAccount extends SmartAccount<TEntryPoint> | undefined = + | SmartAccount<TEntryPoint> + | undefined +> = GetAccountParameter<TEntryPoint, TSmartAccount> & { + modules: [ + { + type: ModuleType + address: Address + context: Hex + } + ] + maxFeePerGas?: bigint + maxPriorityFeePerGas?: bigint + nonce?: bigint +} & Middleware<TEntryPoint> + +export async function uninstallModules< + TEntryPoint extends EntryPoint, + TSmartAccount extends SmartAccount<TEntryPoint> | undefined = + | SmartAccount<TEntryPoint> + | undefined, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>( + client: Client<TTransport, TChain, TSmartAccount>, + parameters: Prettify<UninstallModulesParameters<TEntryPoint, TSmartAccount>> +): Promise<Hex> { + const { + account: account_ = client.account, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + middleware, + modules + } = parameters + + if (!account_) { + throw new AccountOrClientNotFoundError({ + docsPath: "/docs/actions/wallet/sendTransaction" + }) + } + + const account = parseAccount(account_) as SmartAccount<TEntryPoint> + + const uninstallModulesCallData = await account.encodeCallData( + await Promise.all( + modules.map(({ type, address, context }) => ({ + to: account.address, + value: BigInt(0), + data: encodeFunctionData({ + abi: [ + { + name: "uninstallModule", + type: "function", + stateMutability: "nonpayable", + inputs: [ + { + type: "uint256", + name: "moduleTypeId" + }, + { + type: "address", + name: "module" + }, + { + type: "bytes", + name: "deInitData" + } + ], + outputs: [] + } + ], + functionName: "uninstallModule", + args: [ + parseModuleTypeId(type), + getAddress(address), + context + ] + }) + })) + ) + ) + + return getAction( + client, + sendUserOperation<TEntryPoint>, + "sendUserOperation" + )({ + userOperation: { + sender: account.address, + maxFeePerGas: maxFeePerGas || BigInt(0),
why default to 0?
permissionless.js
github_2023
typescript
207
pimlicolabs
plusminushalf
@@ -366,35 +441,13 @@ const main = async () => { address: kernelFactoryOwner }) - // ==== SETUP ALCHEMY LIGHT ACCOUNT CONTRACTS ==== // - const alchemyLightClientOwner = "0xDdF32240B4ca3184De7EC8f0D5Aba27dEc8B7A5C"
Why have we removed this?
permissionless.js
github_2023
typescript
207
pimlicolabs
plusminushalf
@@ -85,5 +93,6 @@ export { type PrivateKeyToSafeSmartAccountParameters, type SignerToEcdsaKernelSmartAccountParameters, type SignerToBiconomySmartAccountParameters, - type PrivateKeyToBiconomySmartAccountParameters + type PrivateKeyToBiconomySmartAccountParameters, + type SignerToTrustSmartAccountParameters
we should add `PrivateKeyToTrustSmartAccount` as well.
permissionless.js
github_2023
typescript
207
pimlicolabs
plusminushalf
@@ -0,0 +1,194 @@ +import { + type Address, + type Chain, + type Client, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex +} from "viem" +import { getChainId } from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" + +import { toSmartAccount } from "../toSmartAccount" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types" + +import type { EntryPoint, Prettify } from "../../types" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" + +import { encodeCallData } from "./utils/encodeCallData" +import { getAccountAddress } from "./utils/getAccountAddress" +import { getDummySignature } from "./utils/getDummySignature" +import { getFactoryData } from "./utils/getFactoryData" +import { signMessage } from "./utils/signMessage" +import { signTransaction } from "./utils/signTransaction" +import { signTypedData } from "./utils/signTypedData" +import { signUserOperation } from "./utils/signUserOperation" + +/** + * Default addresses for Trust Smart Account + */ +export const TRUST_ADDRESSES: { + Secp256k1VerificationFacetAddress: Address +} = { + Secp256k1VerificationFacetAddress: + "0x03F82FA254B123282542Efc2b477f30ADD2Ca111" +} + +export type TrustSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "TrustSmartAccount", transport, chain> + +export type SignerToTrustSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = Prettify<{
We don't need prettify here, it is mostly to simplify complex inferred objects.
permissionless.js
github_2023
typescript
207
pimlicolabs
plusminushalf
@@ -0,0 +1,234 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + hashMessage, + hashTypedData +} from "viem" +import { getChainId } from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" + +import { toSmartAccount } from "../toSmartAccount" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types" + +import type { EntryPoint } from "../../types" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" + +import { encodeCallData } from "./utils/encodeCallData" +import { getAccountAddress } from "./utils/getAccountAddress" +import { getDummySignature } from "./utils/getDummySignature" +import { getFactoryData } from "./utils/getFactoryData" +import { signTransaction } from "./utils/signTransaction" +import { signUserOperation } from "./utils/signUserOperation" + +async function _signTypedData< + TSource extends string = string, + TAddress extends Address = Address +>( + signer: SmartAccountSigner<TSource, TAddress>, + chainId: number, + accountAddress: Address, + hashedMessage: Hex +): Promise<Hex> { + return signer.signTypedData({ + domain: { + chainId: Number(chainId), + name: "Barz", + verifyingContract: accountAddress, + version: "v0.2.0" + }, + types: { + BarzMessage: [{ name: "message", type: "bytes" }] + }, + message: { + message: hashedMessage + }, + primaryType: "BarzMessage" + }) +} + +/** + * Default addresses for Trust Smart Account + */ +export const TRUST_ADDRESSES: { + Secp256k1VerificationFacetAddress: Address + factoryAddress: Address +} = { + Secp256k1VerificationFacetAddress: + "0x81b9E3689390C7e74cF526594A105Dea21a8cdD5", + factoryAddress: "0x729c310186a57833f622630a16d13f710b83272a" +} + +export type TrustSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "TrustSmartAccount", transport, chain> + +export type SignerToTrustSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = { + signer: SmartAccountSigner<TSource, TAddress> + factoryAddress?: Address + entryPoint: entryPoint + index?: bigint + address?: Address + secp256k1VerificationFacetAddress?: Address +} + +/** + * @description Creates an Trust Smart Account from a private key. + * + * @returns A Private Key Trust Smart Account. + */ +export async function signerToTrustSmartAccount< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TSource extends string = string, + TAddress extends Address = Address +>( + client: Client<TTransport, TChain, undefined>, + { + signer, + factoryAddress = TRUST_ADDRESSES.factoryAddress, + entryPoint: entryPointAddress, + index = 0n, + secp256k1VerificationFacetAddress = TRUST_ADDRESSES.Secp256k1VerificationFacetAddress, + address + }: SignerToTrustSmartAccountParameters<entryPoint, TSource, TAddress> +): Promise<TrustSmartAccount<entryPoint, TTransport, TChain>> { + const viemSigner: LocalAccount<string> = { + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } + + const [accountAddress, chainId] = await Promise.all([ + address ?? + getAccountAddress(client, { + factoryAddress, + secp256k1VerificationFacetAddress, + entryPoint: entryPointAddress, + bytes: viemSigner.publicKey, + owner: viemSigner.address, + index + }), + getChainId(client)
Can we check if client has the chain so `client.chain?.id ?? getChainId(client)`
permissionless.js
github_2023
typescript
207
pimlicolabs
plusminushalf
@@ -0,0 +1,55 @@ +import type { Account, Address } from "viem" +import { encodeFunctionData } from "viem" + +/** + * Wrapped this function to minimize the call to check if account is deployed + */ +export const getFactoryData = async ({ + account, + bytes, + index, + secp256k1VerificationFacetAddress +}: { + account: Account + bytes: `0x${string}` + index: bigint + secp256k1VerificationFacetAddress: Address +}) => { + if (!account.address) throw new Error("Owner account not found")
why do we need account? this check doesn't help anything.
permissionless.js
github_2023
others
221
pimlicolabs
plusminushalf
@@ -0,0 +1,5 @@ +--- +"permissionless": patch +--- + +fix: domain typing
Can we change to `Fixed domain not typed as TypedDataDomain`
permissionless.js
github_2023
typescript
221
pimlicolabs
plusminushalf
@@ -136,10 +137,9 @@ export async function signTypedData< const account = parseAccount(account_) const types = { - EIP712Domain: getTypesForEIP712Domain({ domain }), + EIP712Domain: getTypesForEIP712Domain(domain as {domain: TypedDataDomain}),
Shouldn't parameter still be ```typescript EIP712Domain: getTypesForEIP712Domain({domain} as {domain: TypedDataDomain}), ```
permissionless.js
github_2023
typescript
213
pimlicolabs
kristofgazso
@@ -113,12 +113,23 @@ export type SignerToSimpleSmartAccountParameters< TAddress extends Address = Address > = Prettify<{ signer: SmartAccountSigner<TSource, TAddress> - factoryAddress: Address + factoryAddress?: Address entryPoint: entryPoint index?: bigint address?: Address }> +const getDefaultAddresses = (
weird naming no? more like `getFactoryAddress`
permissionless.js
github_2023
typescript
205
pimlicolabs
pavlovdog
@@ -123,10 +115,11 @@ export const getUserOperationReceipt = async < blockNumber: BigInt(log.blockNumber), blockHash: log.blockHash, transactionHash: log.transactionHash, - logIndex: BigInt(log.logIndex), - transactionIndex: BigInt(log.transactionIndex), + logIndex: Number(log.logIndex), + transactionIndex: Number(log.transactionIndex), address: log.address, - topics: log.topics + topics: log.topics, + removed: log.removed
Why not return the log as it is?
permissionless.js
github_2023
typescript
188
pimlicolabs
plusminushalf
@@ -0,0 +1,439 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeFunctionData, + hashMessage, + hashTypedData +} from "viem" +import { getChainId, signMessage } from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import { getSenderAddress } from "../../actions/public/getSenderAddress" +import type { + ENTRYPOINT_ADDRESS_V06_TYPE, + ENTRYPOINT_ADDRESS_V07_TYPE, + Prettify +} from "../../types" +import type { EntryPoint } from "../../types/entrypoint" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types" + +export type LightSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "LightSmartAccount", transport, chain> + +const getAccountInitCode = async ( + owner: Address, + index = BigInt(0) +): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + return encodeFunctionData({ + abi: [ + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "uint256", + name: "salt", + type: "uint256" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "contract LightAccount", + name: "ret", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "function" + } + ], + functionName: "createAccount", + args: [owner, index] + }) +} + +const getAccountAddress = async < + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + factoryAddress, + entryPoint: entryPointAddress, + owner, + index = BigInt(0) +}: { + client: Client<TTransport, TChain> + factoryAddress: Address + owner: Address + entryPoint: entryPoint + index?: bigint +}): Promise<Address> => { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + const factoryData = await getAccountInitCode(owner, index) + + if (entryPointVersion === "v0.6") { + return getSenderAddress<ENTRYPOINT_ADDRESS_V06_TYPE>(client, { + initCode: concatHex([factoryAddress, factoryData]), + entryPoint: entryPointAddress as ENTRYPOINT_ADDRESS_V06_TYPE + }) + } + + // Get the sender address based on the init code + return getSenderAddress<ENTRYPOINT_ADDRESS_V07_TYPE>(client, { + factory: factoryAddress, + factoryData, + entryPoint: entryPointAddress as ENTRYPOINT_ADDRESS_V07_TYPE + }) +} + +export type LightVersion = "v1.1.0" | "v2.0.0" + +export type SignerToLightSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = Prettify<{ + signer: SmartAccountSigner<TSource, TAddress> + lightVersion: LightVersion + entryPoint: entryPoint + factoryAddress?: Address + index?: bigint + address?: Address +}> + +async function signWith1271WrapperV1< + TSource extends string = string, + TAddress extends Address = Address +>( + signer: SmartAccountSigner<TSource, TAddress>, + chainId: number, + accountAddress: Address, + hashedMessage: Hex +): Promise<Hex> { + return signer.signTypedData({ + domain: { + chainId: Number(chainId), + name: "LightAccount", + verifyingContract: accountAddress, + version: "1" + }, + types: { + LightAccountMessage: [{ name: "message", type: "bytes" }] + }, + message: { + message: hashedMessage + }, + primaryType: "LightAccountMessage" + }) +} + +const LIGHT_VERSION_TO_ADDRESSES_MAP: { + [key in LightVersion]: { + factoryAddress: Address + } +} = { + "v1.1.0": { + factoryAddress: "0x00004EC70002a32400f8ae005A26081065620D20" + }, + "v2.0.0": { + factoryAddress: "0x0000000000400CdFef5E2714E63d8040b700BC24" + } +} + +const getDefaultAddresses = ( + lightVersion: LightVersion, + { + factoryAddress: _factoryAddress + }: { + factoryAddress?: Address + } +) => { + const factoryAddress = + _factoryAddress ?? + LIGHT_VERSION_TO_ADDRESSES_MAP[lightVersion].factoryAddress + + return { + factoryAddress + } +} + +/** + * @description Creates an Light Account from a private key. + * + * @returns A Private Key Light Account. + */ +export async function signerToLightSmartAccount< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TSource extends string = string, + TAddress extends Address = Address +>( + client: Client<TTransport, TChain, undefined>, + { + signer, + address, + lightVersion, + entryPoint: entryPointAddress, + index = BigInt(0), + factoryAddress: _factoryAddress + }: SignerToLightSmartAccountParameters<entryPoint, TSource, TAddress> +): Promise<LightSmartAccount<entryPoint, TTransport, TChain>> { + const viemSigner: LocalAccount = { + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } as LocalAccount + + if (lightVersion === "v2.0.0") {
since lightVersion is a constant can we just accept 1.1.0?
permissionless.js
github_2023
typescript
188
pimlicolabs
plusminushalf
@@ -0,0 +1,439 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeFunctionData, + hashMessage, + hashTypedData +} from "viem" +import { getChainId, signMessage } from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import { getSenderAddress } from "../../actions/public/getSenderAddress" +import type { + ENTRYPOINT_ADDRESS_V06_TYPE, + ENTRYPOINT_ADDRESS_V07_TYPE, + Prettify +} from "../../types" +import type { EntryPoint } from "../../types/entrypoint" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types" + +export type LightSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "LightSmartAccount", transport, chain> + +const getAccountInitCode = async ( + owner: Address, + index = BigInt(0) +): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + return encodeFunctionData({ + abi: [ + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "uint256", + name: "salt", + type: "uint256" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "contract LightAccount", + name: "ret", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "function" + } + ], + functionName: "createAccount", + args: [owner, index] + }) +} + +const getAccountAddress = async < + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + factoryAddress, + entryPoint: entryPointAddress, + owner, + index = BigInt(0) +}: { + client: Client<TTransport, TChain> + factoryAddress: Address + owner: Address + entryPoint: entryPoint + index?: bigint +}): Promise<Address> => { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + const factoryData = await getAccountInitCode(owner, index) + + if (entryPointVersion === "v0.6") { + return getSenderAddress<ENTRYPOINT_ADDRESS_V06_TYPE>(client, { + initCode: concatHex([factoryAddress, factoryData]), + entryPoint: entryPointAddress as ENTRYPOINT_ADDRESS_V06_TYPE + }) + } + + // Get the sender address based on the init code + return getSenderAddress<ENTRYPOINT_ADDRESS_V07_TYPE>(client, { + factory: factoryAddress, + factoryData, + entryPoint: entryPointAddress as ENTRYPOINT_ADDRESS_V07_TYPE + }) +} + +export type LightVersion = "v1.1.0" | "v2.0.0" + +export type SignerToLightSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = Prettify<{ + signer: SmartAccountSigner<TSource, TAddress> + lightVersion: LightVersion + entryPoint: entryPoint + factoryAddress?: Address + index?: bigint + address?: Address +}> + +async function signWith1271WrapperV1< + TSource extends string = string, + TAddress extends Address = Address +>( + signer: SmartAccountSigner<TSource, TAddress>, + chainId: number, + accountAddress: Address, + hashedMessage: Hex +): Promise<Hex> { + return signer.signTypedData({ + domain: { + chainId: Number(chainId), + name: "LightAccount", + verifyingContract: accountAddress, + version: "1" + }, + types: { + LightAccountMessage: [{ name: "message", type: "bytes" }] + }, + message: { + message: hashedMessage + }, + primaryType: "LightAccountMessage" + }) +} + +const LIGHT_VERSION_TO_ADDRESSES_MAP: { + [key in LightVersion]: { + factoryAddress: Address + } +} = { + "v1.1.0": { + factoryAddress: "0x00004EC70002a32400f8ae005A26081065620D20" + }, + "v2.0.0": { + factoryAddress: "0x0000000000400CdFef5E2714E63d8040b700BC24" + } +} + +const getDefaultAddresses = ( + lightVersion: LightVersion, + { + factoryAddress: _factoryAddress + }: { + factoryAddress?: Address + } +) => { + const factoryAddress = + _factoryAddress ?? + LIGHT_VERSION_TO_ADDRESSES_MAP[lightVersion].factoryAddress + + return { + factoryAddress + } +} + +/** + * @description Creates an Light Account from a private key. + * + * @returns A Private Key Light Account. + */ +export async function signerToLightSmartAccount< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TSource extends string = string, + TAddress extends Address = Address +>( + client: Client<TTransport, TChain, undefined>, + { + signer, + address, + lightVersion, + entryPoint: entryPointAddress, + index = BigInt(0), + factoryAddress: _factoryAddress + }: SignerToLightSmartAccountParameters<entryPoint, TSource, TAddress> +): Promise<LightSmartAccount<entryPoint, TTransport, TChain>> { + const viemSigner: LocalAccount = { + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } as LocalAccount + + if (lightVersion === "v2.0.0") { + throw new Error( + "LightSmartAccount v2.0.0 is not supported yet due to the bug in the implementation contract" + ) + } + + const { factoryAddress } = getDefaultAddresses(lightVersion, { + factoryAddress: _factoryAddress + }) + + const [accountAddress, chainId] = await Promise.all([ + address ?? + getAccountAddress<entryPoint, TTransport, TChain>({ + client, + factoryAddress, + entryPoint: entryPointAddress, + owner: viemSigner.address, + index + }), + client.chain?.id ?? getChainId(client) + ]) + + if (!accountAddress) throw new Error("Account address not found") + + let smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + return toSmartAccount({ + address: accountAddress, + signMessage: async ({ message }) => { + return signWith1271WrapperV1<TSource, TAddress>( + signer, + chainId, + accountAddress, + hashMessage(message) + ) + }, + 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 signWith1271WrapperV1<TSource, TAddress>( + signer, + chainId, + accountAddress, + hashTypedData(typedData) + ) + }, + client: client, + publicKey: accountAddress, + entryPoint: entryPointAddress, + source: "LightSmartAccount", + async getNonce() { + return getAccountNonce(client, { + sender: accountAddress, + entryPoint: entryPointAddress + }) + }, + async signUserOperation(userOperation) { + return signMessage(client, { + account: viemSigner, + message: { + raw: getUserOperationHash({ + userOperation, + entryPoint: entryPointAddress, + chainId: chainId + }) + } + }) + }, + async getInitCode() { + if (smartAccountDeployed) return "0x" + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return "0x" + + return concatHex([ + factoryAddress, + await getAccountInitCode(viemSigner.address, index) + ]) + }, + async getFactory() { + if (smartAccountDeployed) return undefined + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + if (smartAccountDeployed) return undefined + return factoryAddress + }, + async getFactoryData() { + if (smartAccountDeployed) return undefined + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + if (smartAccountDeployed) return undefined + return getAccountInitCode(viemSigner.address, index) + }, + async encodeDeployCallData(_) { + throw new Error("Simple account doesn't support account deployment")
this might be light account here.
permissionless.js
github_2023
typescript
188
pimlicolabs
plusminushalf
@@ -0,0 +1,439 @@ +import { + type Address, + type Chain, + type Client, + type Hex, + type LocalAccount, + type Transport, + type TypedData, + type TypedDataDefinition, + concatHex, + encodeFunctionData, + hashMessage, + hashTypedData +} from "viem" +import { getChainId, signMessage } from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce" +import { getSenderAddress } from "../../actions/public/getSenderAddress" +import type { + ENTRYPOINT_ADDRESS_V06_TYPE, + ENTRYPOINT_ADDRESS_V07_TYPE, + Prettify +} from "../../types" +import type { EntryPoint } from "../../types/entrypoint" +import { getEntryPointVersion } from "../../utils" +import { getUserOperationHash } from "../../utils/getUserOperationHash" +import { isSmartAccountDeployed } from "../../utils/isSmartAccountDeployed" +import { toSmartAccount } from "../toSmartAccount" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types" + +export type LightSmartAccount< + entryPoint extends EntryPoint, + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<entryPoint, "LightSmartAccount", transport, chain> + +const getAccountInitCode = async ( + owner: Address, + index = BigInt(0) +): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + return encodeFunctionData({ + abi: [ + { + inputs: [ + { + internalType: "address", + name: "owner", + type: "address" + }, + { + internalType: "uint256", + name: "salt", + type: "uint256" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "contract LightAccount", + name: "ret", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "function" + } + ], + functionName: "createAccount", + args: [owner, index] + }) +} + +const getAccountAddress = async < + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + factoryAddress, + entryPoint: entryPointAddress, + owner, + index = BigInt(0) +}: { + client: Client<TTransport, TChain> + factoryAddress: Address + owner: Address + entryPoint: entryPoint + index?: bigint +}): Promise<Address> => { + const entryPointVersion = getEntryPointVersion(entryPointAddress) + + const factoryData = await getAccountInitCode(owner, index) + + if (entryPointVersion === "v0.6") { + return getSenderAddress<ENTRYPOINT_ADDRESS_V06_TYPE>(client, { + initCode: concatHex([factoryAddress, factoryData]), + entryPoint: entryPointAddress as ENTRYPOINT_ADDRESS_V06_TYPE + }) + } + + // Get the sender address based on the init code + return getSenderAddress<ENTRYPOINT_ADDRESS_V07_TYPE>(client, { + factory: factoryAddress, + factoryData, + entryPoint: entryPointAddress as ENTRYPOINT_ADDRESS_V07_TYPE + }) +} + +export type LightVersion = "v1.1.0" | "v2.0.0" + +export type SignerToLightSmartAccountParameters< + entryPoint extends EntryPoint, + TSource extends string = string, + TAddress extends Address = Address +> = Prettify<{ + signer: SmartAccountSigner<TSource, TAddress> + lightVersion: LightVersion + entryPoint: entryPoint + factoryAddress?: Address + index?: bigint + address?: Address +}> + +async function signWith1271WrapperV1< + TSource extends string = string, + TAddress extends Address = Address +>( + signer: SmartAccountSigner<TSource, TAddress>, + chainId: number, + accountAddress: Address, + hashedMessage: Hex +): Promise<Hex> { + return signer.signTypedData({ + domain: { + chainId: Number(chainId), + name: "LightAccount", + verifyingContract: accountAddress, + version: "1" + }, + types: { + LightAccountMessage: [{ name: "message", type: "bytes" }] + }, + message: { + message: hashedMessage + }, + primaryType: "LightAccountMessage" + }) +} + +const LIGHT_VERSION_TO_ADDRESSES_MAP: { + [key in LightVersion]: { + factoryAddress: Address + } +} = { + "v1.1.0": { + factoryAddress: "0x00004EC70002a32400f8ae005A26081065620D20" + }, + "v2.0.0": { + factoryAddress: "0x0000000000400CdFef5E2714E63d8040b700BC24" + } +} + +const getDefaultAddresses = ( + lightVersion: LightVersion, + { + factoryAddress: _factoryAddress + }: { + factoryAddress?: Address + } +) => { + const factoryAddress = + _factoryAddress ?? + LIGHT_VERSION_TO_ADDRESSES_MAP[lightVersion].factoryAddress + + return { + factoryAddress + } +} + +/** + * @description Creates an Light Account from a private key. + * + * @returns A Private Key Light Account. + */ +export async function signerToLightSmartAccount< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TSource extends string = string, + TAddress extends Address = Address +>( + client: Client<TTransport, TChain, undefined>, + { + signer, + address, + lightVersion, + entryPoint: entryPointAddress, + index = BigInt(0), + factoryAddress: _factoryAddress + }: SignerToLightSmartAccountParameters<entryPoint, TSource, TAddress> +): Promise<LightSmartAccount<entryPoint, TTransport, TChain>> { + const viemSigner: LocalAccount = { + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } as LocalAccount + + if (lightVersion === "v2.0.0") { + throw new Error( + "LightSmartAccount v2.0.0 is not supported yet due to the bug in the implementation contract" + ) + } + + const { factoryAddress } = getDefaultAddresses(lightVersion, { + factoryAddress: _factoryAddress + }) + + const [accountAddress, chainId] = await Promise.all([ + address ?? + getAccountAddress<entryPoint, TTransport, TChain>({ + client, + factoryAddress, + entryPoint: entryPointAddress, + owner: viemSigner.address, + index + }), + client.chain?.id ?? getChainId(client) + ]) + + if (!accountAddress) throw new Error("Account address not found") + + let smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + return toSmartAccount({ + address: accountAddress, + signMessage: async ({ message }) => { + return signWith1271WrapperV1<TSource, TAddress>( + signer, + chainId, + accountAddress, + hashMessage(message) + ) + }, + 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 signWith1271WrapperV1<TSource, TAddress>( + signer, + chainId, + accountAddress, + hashTypedData(typedData) + ) + }, + client: client, + publicKey: accountAddress, + entryPoint: entryPointAddress, + source: "LightSmartAccount", + async getNonce() { + return getAccountNonce(client, { + sender: accountAddress, + entryPoint: entryPointAddress + }) + }, + async signUserOperation(userOperation) { + return signMessage(client, { + account: viemSigner, + message: { + raw: getUserOperationHash({ + userOperation, + entryPoint: entryPointAddress, + chainId: chainId + }) + } + }) + }, + async getInitCode() { + if (smartAccountDeployed) return "0x" + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return "0x" + + return concatHex([ + factoryAddress, + await getAccountInitCode(viemSigner.address, index) + ]) + }, + async getFactory() { + if (smartAccountDeployed) return undefined + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + if (smartAccountDeployed) return undefined + return factoryAddress + }, + async getFactoryData() { + if (smartAccountDeployed) return undefined + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + if (smartAccountDeployed) return undefined + return getAccountInitCode(viemSigner.address, index) + }, + async encodeDeployCallData(_) { + throw new Error("Simple account doesn't support account deployment") + }, + async encodeCallData(args) { + if (Array.isArray(args)) { + const argsArray = args as { + to: Address + value: bigint + data: Hex + }[] + + if (getEntryPointVersion(entryPointAddress) === "v0.6") {
why is this dependent ion entryPoint version? both entryPoint version can call any of the wallet's execute implementation.
permissionless.js
github_2023
others
188
pimlicolabs
plusminushalf
@@ -0,0 +1,5 @@ +--- +"permissionless": minor +--- + +Add Alchemy's LightAccount support V1.1.0
`Add -> Added` we use past tense. `V1.1.0 -> v1.1.0`
permissionless.js
github_2023
typescript
181
pimlicolabs
plusminushalf
@@ -20,11 +20,14 @@ export type GetUserOperationReceiptParameters = { export type GetUserOperationReceiptReturnType = { userOpHash: Hash + entryPoint: Address sender: Address nonce: bigint + paymaster?: Address | undefined
I don't think we need undefined if we have used `?:`
permissionless.js
github_2023
typescript
174
pimlicolabs
plusminushalf
@@ -73,52 +89,175 @@ const createAccountAbi = [ } ] as const +export type KernelVersion = "0.2.2" | "0.3.0-beta" + /** - * Default addresses for kernel smart account + * Default addresses map for different kernel smart account versions */ -const KERNEL_ADDRESSES: { - ECDSA_VALIDATOR: Address - ACCOUNT_V2_2_LOGIC: Address - FACTORY_ADDRESS: Address +export const KERNEL_VERSION_TO_ADDRESSES_MAP: { + [key in KernelVersion]: { + ECDSA_VALIDATOR: Address + ACCOUNT_LOGIC: Address + FACTORY_ADDRESS: Address + META_FACTORY_ADDRESS?: Address + } } = { - ECDSA_VALIDATOR: "0xd9AB5096a832b9ce79914329DAEE236f8Eea0390", - ACCOUNT_V2_2_LOGIC: "0x0DA6a956B9488eD4dd761E59f52FDc6c8068E6B5", - FACTORY_ADDRESS: "0x5de4839a76cf55d0c90e2061ef4386d962E15ae3" + "0.2.2": { + ECDSA_VALIDATOR: "0xd9AB5096a832b9ce79914329DAEE236f8Eea0390", + ACCOUNT_LOGIC: "0x0DA6a956B9488eD4dd761E59f52FDc6c8068E6B5", + FACTORY_ADDRESS: "0x5de4839a76cf55d0c90e2061ef4386d962E15ae3" + }, + "0.3.0-beta": { + ECDSA_VALIDATOR: "0x8104e3Ad430EA6d354d013A6789fDFc71E671c43", + ACCOUNT_LOGIC: "0x94F097E1ebEB4ecA3AAE54cabb08905B239A7D27", + FACTORY_ADDRESS: "0x6723b44Abeec4E71eBE3232BD5B455805baDD22f", + META_FACTORY_ADDRESS: "0xd703aaE79538628d27099B8c4f621bE4CCd142d5" + } +} + +/** + * Get supported Kernel Smart Account version based on entryPoint + * @param entryPoint + */ +const getKernelVersion = (entryPoint: EntryPoint): KernelVersion => {
we can use entryPoint constant, also is the new version of kernel not usable with older entryPoint?
permissionless.js
github_2023
typescript
174
pimlicolabs
plusminushalf
@@ -210,6 +358,7 @@ export type SignerToEcdsaKernelSmartAccountParameters< address?: Address index?: bigint factoryAddress?: Address + metaFactoryAddress?: Address accountLogicAddress?: Address ecdsaValidatorAddress?: Address
should we have kernel version as a param?
permissionless.js
github_2023
typescript
174
pimlicolabs
plusminushalf
@@ -353,7 +535,11 @@ export async function signerToEcdsaKernelSmartAccount< if (smartAccountDeployed) return "0x" - return concatHex([factoryAddress, await generateInitCode()]) + const _factoryAddress = + entryPointVersion === "v0.6" + ? factoryAddress + : metaFactoryAddress
What is the difference between `metaFactoryAddress` and `factoryAddress` and why do we need two separate keys for it.
permissionless.js
github_2023
typescript
174
pimlicolabs
plusminushalf
@@ -0,0 +1,36 @@ +import { concatHex, maxUint16, pad, toHex } from "viem" +import { VALIDATOR_MODE, VALIDATOR_TYPE } from "../constants" +import { + KERNEL_VERSION_TO_ADDRESSES_MAP, + type KernelVersion +} from "../signerToEcdsaKernelSmartAccount" + +export const getNonceKeyWithEncoding = ( + accountVerion: KernelVersion, + nonceKey = 0n +) => { + if (accountVerion === "0.2.2") { + return nonceKey + } + + if (nonceKey > maxUint16) + throw new Error( + `nonce key must be equal or less than 2 bytes(maxUint16) for Kernel version ${accountVerion}` + ) + + const ecdsaValidatorAddress =
User might have passed a different ESDSA_VALIDATOR address in the `signerToEcdsaKernelSmartAccount` we might want to pass that down here.
permissionless.js
github_2023
typescript
174
pimlicolabs
plusminushalf
@@ -73,52 +89,175 @@ const createAccountAbi = [ } ] as const +export type KernelVersion = "0.2.2" | "0.3.0-beta" + /** - * Default addresses for kernel smart account + * Default addresses map for different kernel smart account versions */ -const KERNEL_ADDRESSES: { - ECDSA_VALIDATOR: Address - ACCOUNT_V2_2_LOGIC: Address - FACTORY_ADDRESS: Address +export const KERNEL_VERSION_TO_ADDRESSES_MAP: { + [key in KernelVersion]: { + ECDSA_VALIDATOR: Address + ACCOUNT_LOGIC: Address + FACTORY_ADDRESS: Address + META_FACTORY_ADDRESS?: Address + } } = { - ECDSA_VALIDATOR: "0xd9AB5096a832b9ce79914329DAEE236f8Eea0390", - ACCOUNT_V2_2_LOGIC: "0x0DA6a956B9488eD4dd761E59f52FDc6c8068E6B5", - FACTORY_ADDRESS: "0x5de4839a76cf55d0c90e2061ef4386d962E15ae3" + "0.2.2": { + ECDSA_VALIDATOR: "0xd9AB5096a832b9ce79914329DAEE236f8Eea0390", + ACCOUNT_LOGIC: "0x0DA6a956B9488eD4dd761E59f52FDc6c8068E6B5", + FACTORY_ADDRESS: "0x5de4839a76cf55d0c90e2061ef4386d962E15ae3" + }, + "0.3.0-beta": { + ECDSA_VALIDATOR: "0x8104e3Ad430EA6d354d013A6789fDFc71E671c43", + ACCOUNT_LOGIC: "0x94F097E1ebEB4ecA3AAE54cabb08905B239A7D27", + FACTORY_ADDRESS: "0x6723b44Abeec4E71eBE3232BD5B455805baDD22f", + META_FACTORY_ADDRESS: "0xd703aaE79538628d27099B8c4f621bE4CCd142d5" + } +} + +/** + * Get supported Kernel Smart Account version based on entryPoint + * @param entryPoint + */ +const getKernelVersion = (entryPoint: EntryPoint): KernelVersion => { + return entryPoint === "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789" + ? "0.2.2" + : "0.3.0-beta" +} + +type KERNEL_ADDRESSES = { + ecdsaValidatorAddress: Address + accountLogicAddress: Address + factoryAddress: Address + metaFactoryAddress: Address +} + +/** + * Get default addresses for Kernel Smart Account based on entryPoint or user input + * @param entryPointAddress + * @param ecdsaValidatorAddress + * @param accountLogicAddress + * @param factoryAddress + * @param metaFactoryAddress + */ +const getDefaultAddresses = <entryPoint extends EntryPoint>( + entryPointAddress: entryPoint, + { + ecdsaValidatorAddress: _ecdsaValidatorAddress, + accountLogicAddress: _accountLogicAddress, + factoryAddress: _factoryAddress, + metaFactoryAddress: _metaFactoryAddress + }: Partial<KERNEL_ADDRESSES> +): KERNEL_ADDRESSES => { + const kernelVersion = getKernelVersion(entryPointAddress) + const addresses = KERNEL_VERSION_TO_ADDRESSES_MAP[kernelVersion] + const ecdsaValidatorAddress = + _ecdsaValidatorAddress ?? addresses.ECDSA_VALIDATOR + const accountLogicAddress = _accountLogicAddress ?? addresses.ACCOUNT_LOGIC + const factoryAddress = _factoryAddress ?? addresses.FACTORY_ADDRESS + const metaFactoryAddress = + _metaFactoryAddress ?? addresses?.META_FACTORY_ADDRESS ?? zeroAddress // Meta Factory doesn't exists for Kernel v2.2 + + return { + ecdsaValidatorAddress, + accountLogicAddress, + factoryAddress, + metaFactoryAddress + } +} + +export const getEcdsaRootIdentifierForKernelV3 = () => {
this is hard coding the ECDSA_VALIDATOR address, but we hare taking this address as a param in `signerTo..*`. We should use that address as it also defaults to `KERNEL_VERSION_TO_ADDRESSES_MAP["0.3.0-beta"].ECDSA_VALIDATOR`
permissionless.js
github_2023
typescript
139
pimlicolabs
plusminushalf
@@ -78,20 +77,20 @@ export type SmartAccountClientConfig< */ export function createSmartAccountClient< - entryPoint extends EntryPoint, - TSmartAccount extends SmartAccount<entryPoint> | undefined = - | SmartAccount<entryPoint> + TEntryPoint extends EntryPoint = EntryPoint, + TSmartAccount extends SmartAccount<TEntryPoint> | undefined = + | SmartAccount<TEntryPoint> | undefined, TTransport extends Transport = Transport, TChain extends Chain | undefined = undefined >( parameters: SmartAccountClientConfig< - entryPoint, + TEntryPoint, TTransport, TChain, TSmartAccount > -): SmartAccountClient<entryPoint, TTransport, TChain, TSmartAccount> { +): SmartAccountClient<TEntryPoint, TTransport, TChain, TSmartAccount> {
Can we do use ```typescript TSmartAccount extends SmartAccount<infer TEntryPoint> ? TEntryPoint : never, ``` instead of `TEntryPoint`
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -242,7 +240,7 @@ export const getEoaWalletClient = () => { export const getEntryPoint = () => { if (!process.env.ENTRYPOINT_ADDRESS) throw new Error("ENTRYPOINT_ADDRESS environment variable not set") - return process.env.ENTRYPOINT_ADDRESS as Address + return ENTRYPOINT_ADDRESS_0_6
hmm throughout this PR would it not be better to name this ENTRYPOINT_ADDRESS_V06 / ENTRYPOINT_ADDRESS_V07 instead of ENTRYPOINT_ADDRESS_0_6/
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -122,14 +121,11 @@ const getAccountInitCode = async ({ }) // Build the account init code - return concatHex([ - factoryAddress, - encodeFunctionData({ - abi: createAccountAbi, - functionName: "deployCounterFactualAccount", - args: [ecdsaModuleAddress, ecdsaOwnershipInitData, index] - }) as Hex - ]) + return encodeFunctionData({
what is this change doing?
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -350,6 +367,32 @@ export async function signerToEcdsaKernelSmartAccount< if (smartAccountDeployed) return "0x" + return concatHex([factoryAddress, await generateInitCode()]) + }, + + async getFactory() { + if (smartAccountDeployed) return null + + smartAccountDeployed = await isSmartAccountDeployed( + client, + accountAddress + ) + + if (smartAccountDeployed) return null
why check twice?
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -59,13 +77,20 @@ export class InvalidEntryPointError extends BaseError { * // Return '0x7a88a206ba40b37a8c07a2b5688cf8b287318b63' */ export const getSenderAddress = async < + entryPoint extends EntryPoint, TTransport extends Transport = Transport, TChain extends Chain | undefined = Chain | undefined >( client: Client<TTransport, TChain>, - args: Prettify<GetSenderAddressParams> + args: Prettify<GetSenderAddressParams<entryPoint>> ): Promise<Address> => { - const { initCode, entryPoint } = args + const { initCode, entryPoint, factory, factoryData } = args + + if (!initCode && (!factory || !factoryData)) {
confusing
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -95,21 +130,125 @@ export async function prepareUserOperationRequest< } if (sponsorUserOperation) { - userOperation = await sponsorUserOperation({ + userOperation = (await sponsorUserOperation({ + userOperation, + entryPoint: account.entryPoint + } as { + userOperation: UserOperation<GetEntryPointVersion<entryPoint>> + entryPoint: entryPoint + })) as UserOperation<"0.6">
in these cases would it not be better for the typing to be v0.6 instead of 0.6?
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -95,21 +130,125 @@ export async function prepareUserOperationRequest< } if (sponsorUserOperation) { - userOperation = await sponsorUserOperation({ + userOperation = (await sponsorUserOperation({ + userOperation, + entryPoint: account.entryPoint + } as { + userOperation: UserOperation<GetEntryPointVersion<entryPoint>> + entryPoint: entryPoint + })) as UserOperation<"0.6"> + } else if ( + !userOperation.callGasLimit || + !userOperation.verificationGasLimit || + !userOperation.preVerificationGas + ) { + const gasParameters = await getAction(client, estimateUserOperationGas)( + { + userOperation, + entryPoint: account.entryPoint + } as { + userOperation: UserOperation<GetEntryPointVersion<entryPoint>> + entryPoint: entryPoint + }, + stateOverrides + ) + + userOperation.callGasLimit =
why not use |= ?
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -123,5 +262,39 @@ export async function prepareUserOperationRequest< userOperation.preVerificationGas || gasParameters.preVerificationGas } - return userOperation + return userOperation as PrepareUserOperationRequestReturnType<entryPoint> +} + +export async function prepareUserOperationRequest< + entryPoint extends EntryPoint, + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined, + TAccount extends SmartAccount<entryPoint> | undefined = + | SmartAccount<entryPoint> + | undefined +>( + client: Client<TTransport, TChain, TAccount>, + args: Prettify<PrepareUserOperationRequestParameters<entryPoint, TAccount>>, + stateOverrides?: StateOverrides +): Promise<Prettify<PrepareUserOperationRequestReturnType<entryPoint>>> { + const { account: account_ = client.account } = args + if (!account_) throw new AccountOrClientNotFoundError() + + const account = parseAccount(account_) as SmartAccount<entryPoint> + + const entryPointVersion = getEntryPointVersion(account.entryPoint) + + if (entryPointVersion === "0.6") { + return prepareUserOperationRequestEntryPointVersion0_6(
weird func naming no?
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -0,0 +1,15 @@ +import type { + ENTRYPOINT_ADDRESS_V06_TYPE, + ENTRYPOINT_ADDRESS_V07_TYPE +} from "../types" +import type { EntryPoint, GetEntryPointVersion } from "../types/entrypoint" + +export const ENTRYPOINT_ADDRESS_V06: ENTRYPOINT_ADDRESS_V06_TYPE = + "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789" +export const ENTRYPOINT_ADDRESS_V07: ENTRYPOINT_ADDRESS_V07_TYPE = + "0xA959db6F3798192dC21BdFa6C46B6AD8D1b7eDa3"
the address is not final yet right?
permissionless.js
github_2023
typescript
114
pimlicolabs
kristofgazso
@@ -18,14 +20,36 @@ export type GetRequiredPrefundReturnType = { * userOperation * }) */ -export const getRequiredPrefund = ({ - userOperation -}: GetRequiredPrefundReturnType): bigint => { - const multiplier = userOperation.paymasterAndData.length > 2 ? 3n : 1n +export const getRequiredPrefund = <entryPoint extends EntryPoint>({ + userOperation, + entryPoint: entryPointAddress +}: GetRequiredPrefundReturnType<entryPoint>): bigint => { + if (entryPointAddress === ENTRYPOINT_ADDRESS_V06) { + const userOperationVersion0_6 = userOperation as UserOperation<"0.6"> + const multiplier = + userOperationVersion0_6.paymasterAndData.length > 2 ? 3n : 1n + const requiredGas = + userOperationVersion0_6.callGasLimit + + userOperationVersion0_6.verificationGasLimit * multiplier + + userOperationVersion0_6.preVerificationGas + + return ( + BigInt(requiredGas) * BigInt(userOperationVersion0_6.maxFeePerGas) + ) + } + + const userOperationVersion0_7 = userOperation as UserOperation<"0.7">
-> userOperationVersionV07?
permissionless.js
github_2023
typescript
118
pimlicolabs
kristofgazso
@@ -172,11 +172,64 @@ describe("Safe Account", () => { const smartAccountClient = await getSmartAccountClient({ account: await getSignerToSafeSmartAccount() }) + const response = await smartAccountClient.sendTransaction({ to: zeroAddress, value: 0n, data: "0x" }) + + expectTypeOf(response).toBeString() + expect(response).toHaveLength(66) + expect(response).toMatch(/^0x[0-9a-fA-F]{64}$/) + + await new Promise((res) => { + setTimeout(res, 1000) + }) + await waitForNonceUpdate() + }, 1000000) + + test("safe Smart account client send transaction revert with string", async () => { + const smartAccountClient = await getSmartAccountClient({ + account: await getSignerToSafeSmartAccount() + }) + + const erc20Token = getContract({ + abi: [ + { + inputs: [ + { + internalType: "address", + name: "to", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + } + ], + name: "transfer", + outputs: [{ internalType: "bool", name: "", type: "bool" }], + stateMutability: "nonpayable", + type: "function" + } + ], + address: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", + client: { + public: await getPublicClient(), + wallet: smartAccountClient + } + }) + + const response = await erc20Token.write.transfer([zeroAddress, 10n]) + console.log(response)
log?
permissionless.js
github_2023
others
92
pimlicolabs
kristofgazso
@@ -23,20 +23,28 @@ "license": "MIT", "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 ./packages/permissionless/_cjs --removeComments --verbatimModuleSyntax false && printf '{\"type\":\"commonjs\"}' > ./packages/permissionless/_cjs/package.json", - "build:esm": "tsc --project ./tsconfig.build.json --module es2015 --outDir ./packages/permissionless/_esm && printf '{\"type\": \"module\",\"sideEffects\":false}' > ./packages/permissionless/_esm/package.json", - "build:types": "tsc --project ./tsconfig.build.json --module esnext --declarationDir ./packages/permissionless/_types --emitDeclarationOnly --declaration --declarationMap", + "build:wagmi": "bun run clean && bun run build:wagmi:cjs && bun run build:wagmi:esm && bun run build:wagmi:types",
why a separate build step?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SmartAccountAlreadyDeployed extends BaseError { + static message = /aa10/ + override name = "SmartAccountAlreadyDeployed" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeFailedOrOutOfGas extends BaseError { + static message = /aa13/ + override name = "InitCodeFailedOrOutOfGas" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeReturnedDifferentSmartAccountAddress extends BaseError { + static message = /aa14/ + override name = "InitCodeReturnedDifferentSmartAccountAddress" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySender extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySender" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountNotDeployed extends BaseError { + static message = /aa20/ + override name = "SmartAccountNotDeployed" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountDoNotHaveEnoughFunds extends BaseError {
Do -> Does Or actually why not call this smth like just: NotEnoughFunds
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SmartAccountAlreadyDeployed extends BaseError { + static message = /aa10/ + override name = "SmartAccountAlreadyDeployed" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeFailedOrOutOfGas extends BaseError { + static message = /aa13/ + override name = "InitCodeFailedOrOutOfGas" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeReturnedDifferentSmartAccountAddress extends BaseError { + static message = /aa14/ + override name = "InitCodeReturnedDifferentSmartAccountAddress" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySender extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySender" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountNotDeployed extends BaseError { + static message = /aa20/ + override name = "SmartAccountNotDeployed" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountDoNotHaveEnoughFunds extends BaseError { + static message = /aa21/ + override name = "SmartAccountDoNotHaveEnoughFunds" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`, + "", + "Possible solutions:", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre-fund. Consider leveraging functions like getRequiredPrefund.", + "• If you are looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountSignatureExpiredOrNotDue extends BaseError {
SmartAccountSignatureExpiredOrNotDue -> SignatureExpiredOrNotDue?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SmartAccountAlreadyDeployed extends BaseError { + static message = /aa10/ + override name = "SmartAccountAlreadyDeployed" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeFailedOrOutOfGas extends BaseError { + static message = /aa13/ + override name = "InitCodeFailedOrOutOfGas" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeReturnedDifferentSmartAccountAddress extends BaseError { + static message = /aa14/ + override name = "InitCodeReturnedDifferentSmartAccountAddress" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySender extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySender" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountNotDeployed extends BaseError { + static message = /aa20/ + override name = "SmartAccountNotDeployed" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountDoNotHaveEnoughFunds extends BaseError { + static message = /aa21/ + override name = "SmartAccountDoNotHaveEnoughFunds" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`, + "", + "Possible solutions:", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre-fund. Consider leveraging functions like getRequiredPrefund.", + "• If you are looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountSignatureExpiredOrNotDue extends BaseError { + static message = /aa21/ + override name = "SmartAccountDoNotHaveEnoughFunds" + constructor({ + cause, + docsPath + }: { + cause?: BaseError + docsPath?: string + }) { + super( + [ + "The signature used in the user operation is not valid, because it is outside of the time range it specified.", + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are looking to use time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountRevertedOrOutOfGasDuringValidation extends BaseError {
SmartAccountRevertedOrOutOfGasDuringValidation -> ValidationRevertedOrOutOfGas?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SmartAccountAlreadyDeployed extends BaseError { + static message = /aa10/ + override name = "SmartAccountAlreadyDeployed" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeFailedOrOutOfGas extends BaseError { + static message = /aa13/ + override name = "InitCodeFailedOrOutOfGas" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeReturnedDifferentSmartAccountAddress extends BaseError { + static message = /aa14/ + override name = "InitCodeReturnedDifferentSmartAccountAddress" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySender extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySender" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountNotDeployed extends BaseError { + static message = /aa20/ + override name = "SmartAccountNotDeployed" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountDoNotHaveEnoughFunds extends BaseError { + static message = /aa21/ + override name = "SmartAccountDoNotHaveEnoughFunds" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`, + "", + "Possible solutions:", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre-fund. Consider leveraging functions like getRequiredPrefund.", + "• If you are looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountSignatureExpiredOrNotDue extends BaseError { + static message = /aa21/ + override name = "SmartAccountDoNotHaveEnoughFunds" + constructor({ + cause, + docsPath + }: { + cause?: BaseError + docsPath?: string + }) { + super( + [ + "The signature used in the user operation is not valid, because it is outside of the time range it specified.", + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are looking to use time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountRevertedOrOutOfGasDuringValidation extends BaseError { + static message = /aa23/ + override name = "SmartAccountRevertedOrOutOfGasDuringValidation" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `The smart account ${sender} reverted or ran out of gas during the validation of the user operation.`, + "", + "Possible solutions:", + "• Verify that the verificationGasLimit is high enough to cover the validateUserOp function's gas costs.", + "• Make sure validateUserOp returns uint(1) for invalid signatures, and MUST NOT REVERT when the signature is invalid", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre fund. Consider leveraging functions like getRequiredPrefund.", + "• Verify that the validateUserOp function is implemented with the correct logic, and that the user operation is supposed to be valid.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountInvalidSignature extends BaseError {
SmartAccountInvalidSignature -> InvalidSignature?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SmartAccountAlreadyDeployed extends BaseError { + static message = /aa10/ + override name = "SmartAccountAlreadyDeployed" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeFailedOrOutOfGas extends BaseError { + static message = /aa13/ + override name = "InitCodeFailedOrOutOfGas" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeReturnedDifferentSmartAccountAddress extends BaseError { + static message = /aa14/ + override name = "InitCodeReturnedDifferentSmartAccountAddress" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySender extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySender" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountNotDeployed extends BaseError { + static message = /aa20/ + override name = "SmartAccountNotDeployed" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountDoNotHaveEnoughFunds extends BaseError { + static message = /aa21/ + override name = "SmartAccountDoNotHaveEnoughFunds" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`, + "", + "Possible solutions:", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre-fund. Consider leveraging functions like getRequiredPrefund.", + "• If you are looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountSignatureExpiredOrNotDue extends BaseError { + static message = /aa21/ + override name = "SmartAccountDoNotHaveEnoughFunds" + constructor({ + cause, + docsPath + }: { + cause?: BaseError + docsPath?: string + }) { + super( + [ + "The signature used in the user operation is not valid, because it is outside of the time range it specified.", + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are looking to use time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountRevertedOrOutOfGasDuringValidation extends BaseError { + static message = /aa23/ + override name = "SmartAccountRevertedOrOutOfGasDuringValidation" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `The smart account ${sender} reverted or ran out of gas during the validation of the user operation.`, + "", + "Possible solutions:", + "• Verify that the verificationGasLimit is high enough to cover the validateUserOp function's gas costs.", + "• Make sure validateUserOp returns uint(1) for invalid signatures, and MUST NOT REVERT when the signature is invalid", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre fund. Consider leveraging functions like getRequiredPrefund.", + "• Verify that the validateUserOp function is implemented with the correct logic, and that the user operation is supposed to be valid.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountInvalidSignature extends BaseError { + static message = /aa24/ + override name = "SmartAccountInvalidSignature" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `The smart account ${sender} signature is invalid.`, + "", + "Possible solutions:", + "• Verify that the user operation was correctly signed, and that the signature was correctly encoded in the signature field of the user operation.", + "• Most smart account implementations sign over the userOpHash. Make sure that the userOpHash is correctly computed. Consider leveraging functions like getUserOperationHash.", + "• Make sure you have selected the correct chainId and entryPointAddress when computing the userOpHash.", + "• Make sure the smart account signature verification function is correctly implemented.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountNonceInvalid extends BaseError {
SmartAccountNonceInvalid -> NonceInvalid?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,55 @@ +import { BaseError } from "viem" + +export class InvalidBeneficiaryAddressSetByBundler extends BaseError {
InvalidBeneficiaryAddressSetByBundler -> InvalidBeneficiaryAddress
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,107 @@ +import { BaseError } from "viem" + +export class VerificationGasLimitNotEnough extends BaseError { + static message = /aa4[01]/ + override name = "VerificationGasLimitNotEnough" + constructor({ + cause, + verificationGasLimit, + docsPath + }: { + cause?: BaseError + verificationGasLimit?: bigint + docsPath?: string + }) { + super( + [ + `Smart account and paymaster verification exceeded the verificationGasLimit ${verificationGasLimit} set for the user operation.`, + "", + "Possible solutions:", + "• Verify that the verificationGasLimit set for the user operation is high enough to cover the gas used during smart account and paymaster verification.", + "• If you are using the eth_estimateUserOperationGas or pm_sponsorUserOperation method from bundler provider like Pimlico to set user operation gas limits and the EntryPoint throws this error during submission, reach out to them.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class FundsLowerThanActualGasCost extends BaseError { + static message = /aa51/ + override name = "FundsLowerThanActualGasCost" + constructor({ + cause, + docsPath + }: { + cause?: BaseError + docsPath?: string + }) { + super( + [ + "The actual gas cost of the user operation ended up being higher than the funds paid by the smart account or the paymaster.", + "", + "Possible solutions:", + "• If you encounter this error, try increasing the verificationGasLimit set for the user operation.", + "• If you are using the eth_estimateUserOperationGas or pm_sponsorUserOperation method from bundler provider like Pimlico to set user operation gas limits and the EntryPoint throws this error during submission, reach out to them.",
I'd remove `like Pimlico`
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,235 @@ +import { BaseError, type Hex } from "viem" +import { getAddressFromInitCodeOrPaymasterAndData } from "../utils/index.js" + +export class PaymasterNotDeployed extends BaseError { + static message = /aa30/ + override name = "PaymasterNotDeployed" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} is not deployed.`, + "", + "Possible solutions:", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• Verify that the paymaster contract is deployed on the network you are using.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDepositTooLow extends BaseError { + static message = /aa31/ + override name = "PaymasterDepositTooLow" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} contract does not have enough funds deposited into the EntryPoint contract to cover the required funds for the user operation.`, + "", + "Possible solutions:", + "• If you are using your own paymaster contract, deposit more funds into the EntryPoint contract through the deposit() function of the paymaster contract.", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to useVerify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• If you are using a paymaster service like Pimlico, reach out to them.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterExpiredOrNotDue extends BaseError { + static message = /aa32/ + override name = "PaymasterExpiredOrNotDue" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster}'s data used in the paymasterAndData field of the user operation is not valid, because it is outside of the time range it specified.`, + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are using your own paymaster contract and using time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are using your own paymaster contract and not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "• If you are using a service, contact your service provider for their paymaster's validity.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidationRevertedOrNotEnoughGas extends BaseError {
PaymasterValidationRevertedOrNotEnoughGas -> PaymasterValidationRevertedOrOutOfGas
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SenderAlreadyDeployedError extends BaseError { + static message = /aa10/ + override name = "SenderAlreadyDeployedError" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeRevertedError extends BaseError { + static message = /aa13/ + override name = "InitCodeRevertedError" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderAddressMismatchError extends BaseError { + static message = /aa14/ + override name = "SenderAddressMismatchError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.",
Init code -> The initCode
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SenderAlreadyDeployedError extends BaseError { + static message = /aa10/ + override name = "SenderAlreadyDeployedError" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeRevertedError extends BaseError { + static message = /aa13/ + override name = "InitCodeRevertedError" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderAddressMismatchError extends BaseError { + static message = /aa14/ + override name = "SenderAddressMismatchError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySenderError extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySenderError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`,
Init code -> The initCode
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SenderAlreadyDeployedError extends BaseError { + static message = /aa10/ + override name = "SenderAlreadyDeployedError" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeRevertedError extends BaseError { + static message = /aa13/ + override name = "InitCodeRevertedError" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderAddressMismatchError extends BaseError { + static message = /aa14/ + override name = "SenderAddressMismatchError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySenderError extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySenderError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderNotDeployedError extends BaseError { + static message = /aa20/ + override name = "SenderNotDeployedError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountInsufficientFundsError extends BaseError { + static message = /aa21/ + override name = "SmartAccountInsufficientFundsError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`,
but -> and
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SenderAlreadyDeployedError extends BaseError { + static message = /aa10/ + override name = "SenderAlreadyDeployedError" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeRevertedError extends BaseError { + static message = /aa13/ + override name = "InitCodeRevertedError" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderAddressMismatchError extends BaseError { + static message = /aa14/ + override name = "SenderAddressMismatchError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySenderError extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySenderError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderNotDeployedError extends BaseError { + static message = /aa20/ + override name = "SenderNotDeployedError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountInsufficientFundsError extends BaseError { + static message = /aa21/ + override name = "SmartAccountInsufficientFundsError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`, + "", + "Possible solutions:", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre-fund. Consider leveraging functions like getRequiredPrefund.",
pre-fund -> prefund
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SenderAlreadyDeployedError extends BaseError { + static message = /aa10/ + override name = "SenderAlreadyDeployedError" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeRevertedError extends BaseError { + static message = /aa13/ + override name = "InitCodeRevertedError" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderAddressMismatchError extends BaseError { + static message = /aa14/ + override name = "SenderAddressMismatchError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySenderError extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySenderError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderNotDeployedError extends BaseError { + static message = /aa20/ + override name = "SenderNotDeployedError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountInsufficientFundsError extends BaseError { + static message = /aa21/ + override name = "SmartAccountInsufficientFundsError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`, + "", + "Possible solutions:", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre-fund. Consider leveraging functions like getRequiredPrefund.", + "• If you are looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderSignatureExpiredOrNotDue extends BaseError {
weren't we gonna change this to SmartAccountSignatureValidityPeriodError?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,306 @@ +import { type Address, BaseError } from "viem" + +export class SenderAlreadyDeployedError extends BaseError { + static message = /aa10/ + override name = "SenderAlreadyDeployedError" + constructor({ + cause, + sender, + docsPath + }: { cause?: BaseError; sender?: Address; docsPath?: string } = {}) { + super( + [ + `Smart account ${sender} is already deployed.`, + "", + "Possible solutions:", + `• Remove the initCode from the user operation and set it to "0x"`, + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeRevertedError extends BaseError { + static message = /aa13/ + override name = "InitCodeRevertedError" + constructor({ + cause, + docsPath + }: { cause?: BaseError; docsPath?: string } = {}) { + super( + [ + "EntryPoint failed to create the smart account with the initCode provided.", + "", + "Possible reasons:", + "• The initCode ran out of gas", + "• The initCode reverted during the account deployment process", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode is correct.", + "• Check whether the verificationGasLimit is sufficient for the initCode to complete without running out of gas.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderAddressMismatchError extends BaseError { + static message = /aa14/ + override name = "SenderAddressMismatchError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + "Init code returned a different smart account address than expected.", + `Expected: ${sender}`, + "", + "Possible reasons:", + "• Account deployed with the initCode provided does not match match the sender address provided", + "", + "Possible solutions:", + "• Verify that the sender address was generated deterministically from the initCode. (consider leveraging functions like getSenderAddress)", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode)", + "• Verify that the initCode is correct.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InitCodeDidNotDeploySenderError extends BaseError { + static message = /aa15/ + override name = "InitCodeDidNotDeploySenderError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Init code did not deploy the sender at the address ${sender}.`, + "", + "Possible reasons:", + "• The initCode factory is not creating an account.", + "• The initCode factory is creating an account, but is not implemented correctly as it is not deploying at the sender address", + "", + "Possible solutions:", + "• Verify that the factory address in the initCode is correct (the factory address is the first 20 bytes of the initCode).", + "• Verify that the initCode factory is implemented correctly. The factory must deploy the smart account at the sender address.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderNotDeployedError extends BaseError { + static message = /aa20/ + override name = "SenderNotDeployedError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `Smart account ${sender} is not deployed.`, + "", + "Possible reasons:", + "• An initCode was not specified, but the sender address (i.e. the smart account) is not deployed.", + "", + "Possible solutions:", + "• If this is the first transaction by this account, make sure the initCode is included in the user operation.", + "• If the smart account is already supposed to be deployed, verify that you have selected the correct sender address for the user operation.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountInsufficientFundsError extends BaseError { + static message = /aa21/ + override name = "SmartAccountInsufficientFundsError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `You are not using a paymaster, but the ${sender} address did not have enough native tokens to cover the gas costs associated with the user operation.`, + "", + "Possible solutions:", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre-fund. Consider leveraging functions like getRequiredPrefund.", + "• If you are looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SenderSignatureExpiredOrNotDue extends BaseError { + static message = /aa22/ + override name = "SenderSignatureExpiredOrNotDue" + constructor({ + cause, + docsPath + }: { + cause?: BaseError + docsPath?: string + }) { + super( + [ + "The signature used in the user operation is not valid, because it is outside of the time range it specified.", + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are looking to use time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class SmartAccountValidationRevertedError extends BaseError { + static message = /aa23/ + override name = "SmartAccountValidationRevertedError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `The smart account ${sender} reverted or ran out of gas during the validation of the user operation.`, + "", + "Possible solutions:", + "• Verify that the verificationGasLimit is high enough to cover the validateUserOp function's gas costs.", + "• Make sure validateUserOp returns uint(1) for invalid signatures, and MUST NOT REVERT when the signature is invalid", + "• If you are not using a paymaster, verify that the sender address has enough native tokens to cover the required pre fund. Consider leveraging functions like getRequiredPrefund.", + "• Verify that the validateUserOp function is implemented with the correct logic, and that the user operation is supposed to be valid.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InvalidSmartAccountSignatureError extends BaseError { + static message = /aa24/ + override name = "InvalidSmartAccountSignatureError" + constructor({ + cause, + sender, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + }) { + super( + [ + `The smart account ${sender} signature is invalid.`, + "", + "Possible solutions:", + "• Verify that the user operation was correctly signed, and that the signature was correctly encoded in the signature field of the user operation.", + "• Most smart account implementations sign over the userOpHash. Make sure that the userOpHash is correctly computed. Consider leveraging functions like getUserOperationHash.", + "• Make sure you have selected the correct chainId and entryPointAddress when computing the userOpHash.", + "• Make sure the smart account signature verification function is correctly implemented.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class InvalidSmartAccountNonceError extends BaseError { + static message = /aa25/ + override name = "InvalidSmartAccountNonceError" + constructor({ + cause, + sender, + nonce, + docsPath + }: { + cause?: BaseError + sender: Address + docsPath?: string + nonce: bigint + }) { + super( + [ + `The smart account ${sender} nonce is invalid.`, + `Nonce sent: ${nonce}`,
should we show the key and sequence separately too here?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,107 @@ +import { BaseError } from "viem" + +export class VerificationGasLimitTooLowError extends BaseError { + static message = /aa4[01]/ + override name = "VerificationGasLimitTooLowError" + constructor({ + cause, + verificationGasLimit, + docsPath + }: { + cause?: BaseError + verificationGasLimit?: bigint + docsPath?: string + }) { + super( + [ + `Smart account and paymaster verification exceeded the verificationGasLimit ${verificationGasLimit} set for the user operation.`,
Smart account -> The smart account
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,235 @@ +import { BaseError, type Hex } from "viem" +import { getAddressFromInitCodeOrPaymasterAndData } from "../utils/index.js" + +export class PaymasterNotDeployedError extends BaseError { + static message = /aa30/ + override name = "PaymasterNotDeployedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} is not deployed.`,
remove the colon?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,235 @@ +import { BaseError, type Hex } from "viem" +import { getAddressFromInitCodeOrPaymasterAndData } from "../utils/index.js" + +export class PaymasterNotDeployedError extends BaseError { + static message = /aa30/ + override name = "PaymasterNotDeployedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} is not deployed.`, + "", + "Possible solutions:", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• Verify that the paymaster contract is deployed on the network you are using.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDepositTooLowError extends BaseError { + static message = /aa31/ + override name = "PaymasterDepositTooLowError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} contract does not have enough funds deposited into the EntryPoint contract to cover the required funds for the user operation.`,
remove the colon?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,235 @@ +import { BaseError, type Hex } from "viem" +import { getAddressFromInitCodeOrPaymasterAndData } from "../utils/index.js" + +export class PaymasterNotDeployedError extends BaseError { + static message = /aa30/ + override name = "PaymasterNotDeployedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} is not deployed.`, + "", + "Possible solutions:", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• Verify that the paymaster contract is deployed on the network you are using.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDepositTooLowError extends BaseError { + static message = /aa31/ + override name = "PaymasterDepositTooLowError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} contract does not have enough funds deposited into the EntryPoint contract to cover the required funds for the user operation.`, + "", + "Possible solutions:", + "• If you are using your own paymaster contract, deposit more funds into the EntryPoint contract through the deposit() function of the paymaster contract.", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to useVerify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• If you are using a paymaster service, reach out to them.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidityPeriodError extends BaseError { + static message = /aa32/ + override name = "PaymasterValidityPeriodError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster}'s data used in the paymasterAndData field of the user operation is not valid, because it is outside of the time range it specified.`,
remove the colon?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,235 @@ +import { BaseError, type Hex } from "viem" +import { getAddressFromInitCodeOrPaymasterAndData } from "../utils/index.js" + +export class PaymasterNotDeployedError extends BaseError { + static message = /aa30/ + override name = "PaymasterNotDeployedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} is not deployed.`, + "", + "Possible solutions:", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• Verify that the paymaster contract is deployed on the network you are using.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDepositTooLowError extends BaseError { + static message = /aa31/ + override name = "PaymasterDepositTooLowError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} contract does not have enough funds deposited into the EntryPoint contract to cover the required funds for the user operation.`, + "", + "Possible solutions:", + "• If you are using your own paymaster contract, deposit more funds into the EntryPoint contract through the deposit() function of the paymaster contract.", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to useVerify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• If you are using a paymaster service, reach out to them.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidityPeriodError extends BaseError { + static message = /aa32/ + override name = "PaymasterValidityPeriodError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster}'s data used in the paymasterAndData field of the user operation is not valid, because it is outside of the time range it specified.`, + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are using your own paymaster contract and using time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are using your own paymaster contract and not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "• If you are using a service, contact your service provider for their paymaster's validity.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidationRevertedError extends BaseError { + static message = /aa33/ + override name = "PaymasterValidationRevertedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `The validatePaymasterUserOp function of the paymaster: ${paymaster} either reverted or ran out of gas.`,
remove the colon?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,235 @@ +import { BaseError, type Hex } from "viem" +import { getAddressFromInitCodeOrPaymasterAndData } from "../utils/index.js" + +export class PaymasterNotDeployedError extends BaseError { + static message = /aa30/ + override name = "PaymasterNotDeployedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} is not deployed.`, + "", + "Possible solutions:", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• Verify that the paymaster contract is deployed on the network you are using.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDepositTooLowError extends BaseError { + static message = /aa31/ + override name = "PaymasterDepositTooLowError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} contract does not have enough funds deposited into the EntryPoint contract to cover the required funds for the user operation.`, + "", + "Possible solutions:", + "• If you are using your own paymaster contract, deposit more funds into the EntryPoint contract through the deposit() function of the paymaster contract.", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to useVerify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• If you are using a paymaster service, reach out to them.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidityPeriodError extends BaseError { + static message = /aa32/ + override name = "PaymasterValidityPeriodError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster}'s data used in the paymasterAndData field of the user operation is not valid, because it is outside of the time range it specified.`, + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are using your own paymaster contract and using time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are using your own paymaster contract and not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "• If you are using a service, contact your service provider for their paymaster's validity.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidationRevertedError extends BaseError { + static message = /aa33/ + override name = "PaymasterValidationRevertedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `The validatePaymasterUserOp function of the paymaster: ${paymaster} either reverted or ran out of gas.`, + "", + "Possible solutions:", + "• Verify that the verificationGasLimit is high enough to cover the validatePaymasterUserOp function's gas costs.", + "• If you are using your own paymaster contract, verify that the validatePaymasterUserOp function is implemented with the correct logic, and that the user operation is supposed to be valid.", + "• If you are using a paymaster service, and the user operation is well formed with a high enough verificationGasLimit, reach out to them.", + "• If you are not looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is not set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDataRejectedError extends BaseError { + static message = /aa34/ + override name = "PaymasterDataRejectedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `The validatePaymasterUserOp function of the paymaster: ${paymaster} rejected paymasterAndData.`,
remove the colon?
permissionless.js
github_2023
typescript
92
pimlicolabs
kristofgazso
@@ -0,0 +1,235 @@ +import { BaseError, type Hex } from "viem" +import { getAddressFromInitCodeOrPaymasterAndData } from "../utils/index.js" + +export class PaymasterNotDeployedError extends BaseError { + static message = /aa30/ + override name = "PaymasterNotDeployedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} is not deployed.`, + "", + "Possible solutions:", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• Verify that the paymaster contract is deployed on the network you are using.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDepositTooLowError extends BaseError { + static message = /aa31/ + override name = "PaymasterDepositTooLowError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + } = {}) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster} contract does not have enough funds deposited into the EntryPoint contract to cover the required funds for the user operation.`, + "", + "Possible solutions:", + "• If you are using your own paymaster contract, deposit more funds into the EntryPoint contract through the deposit() function of the paymaster contract.", + "• Verify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to useVerify that the paymasterAndData field is correct, and that the first 20 bytes are the address of the paymaster contract you intend to use.", + "• If you are using a paymaster service, reach out to them.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidityPeriodError extends BaseError { + static message = /aa32/ + override name = "PaymasterValidityPeriodError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `Paymaster: ${paymaster}'s data used in the paymasterAndData field of the user operation is not valid, because it is outside of the time range it specified.`, + "", + "Possible reasons:", + "• This error occurs when the block.timestamp falls after the validUntil timestamp, or before the validAfter timestamp.", + "", + "Possible solutions:", + "• If you are using your own paymaster contract and using time-based signatures, verify that the validAfter and validUntil fields are set correctly and that the user operation is sent within the specified range.", + "• If you are using your own paymaster contract and not looking to use time-based signatures, verify that the validAfter and validUntil fields are set to 0.", + "• If you are using a service, contact your service provider for their paymaster's validity.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterValidationRevertedError extends BaseError { + static message = /aa33/ + override name = "PaymasterValidationRevertedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `The validatePaymasterUserOp function of the paymaster: ${paymaster} either reverted or ran out of gas.`, + "", + "Possible solutions:", + "• Verify that the verificationGasLimit is high enough to cover the validatePaymasterUserOp function's gas costs.", + "• If you are using your own paymaster contract, verify that the validatePaymasterUserOp function is implemented with the correct logic, and that the user operation is supposed to be valid.", + "• If you are using a paymaster service, and the user operation is well formed with a high enough verificationGasLimit, reach out to them.", + "• If you are not looking to use a paymaster to cover the gas fees, verify that the paymasterAndData field is not set.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterDataRejectedError extends BaseError { + static message = /aa34/ + override name = "PaymasterDataRejectedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `The validatePaymasterUserOp function of the paymaster: ${paymaster} rejected paymasterAndData.`, + "", + "Possible solutions:", + "• If you are using your own paymaster contract, verify that the user operation was correctly signed according to your implementation, and that the paymaster signature was correctly encoded in the paymasterAndData field of the user operation.", + "• If you are using a paymaster service, make sure you do not modify any of the fields of the user operation after the paymaster signs over it (except the signature field).", + "• If you are using a paymaster service and you have not modified any of the fields except the signature but you are still getting this error, reach out to them.", + "", + docsPath ? `Docs: ${docsPath}` : "" + ].join("\n"), + { + cause + } + ) + } +} + +export class PaymasterPostOpRevertedError extends BaseError { + static message = /aa50/ + override name = "PaymasterPostOpRevertedError" + constructor({ + cause, + paymasterAndData, + docsPath + }: { + cause?: BaseError + paymasterAndData?: Hex + docsPath?: string + }) { + const paymaster = paymasterAndData + ? getAddressFromInitCodeOrPaymasterAndData(paymasterAndData) + : "0x" + + super( + [ + `The postOp function of the paymaster: ${paymaster} reverted.`,
remove the colon?
permissionless.js
github_2023
typescript
47
pimlicolabs
plusminushalf
@@ -0,0 +1,151 @@ +/** + * The exeuctor abi, used to execute transactions on the Biconomy Modular Smart Account + */ +export const BiconomyExecuteAbi = [ + { + inputs: [ + { + internalType: "address", + name: "dest", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + }, + { + internalType: "bytes", + name: "func", + type: "bytes" + } + ], + name: "execute_ncC", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address", + name: "dest", + type: "address" + }, + { + internalType: "uint256", + name: "value", + type: "uint256" + }, + { + internalType: "bytes", + name: "func", + type: "bytes" + } + ], + name: "execute", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + internalType: "address[]", + name: "dest", + type: "address[]" + }, + { + internalType: "uint256[]", + name: "value", + type: "uint256[]" + }, + { + internalType: "bytes[]", + name: "func", + type: "bytes[]" + } + ], + name: "executeBatch",
I think we don't use this function of the abi, we can remove this.
permissionless.js
github_2023
typescript
47
pimlicolabs
plusminushalf
@@ -0,0 +1,389 @@ +import { + type Account, + type Address, + type Chain, + type Client, + type Hex, + type Transport, + concatHex, + encodeAbiParameters, + encodeFunctionData, + encodePacked, + getContractAddress, + hexToBigInt, + keccak256, + parseAbiParameters +} from "viem" +import { toAccount } from "viem/accounts" +import { + getBytecode, + getChainId, + signMessage, + signTypedData +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce.js" +// import { getSenderAddress } from "../../actions/public/getSenderAddress.js" +import { getUserOperationHash } from "../../utils/getUserOperationHash.js" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types.js" +import { + BiconomyExecuteAbi, + BiconomyInitAbi +} from "./abi/BiconomySmartAccountAbi.js" +// import Abis + +export type BiconomySmartAccount< + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<"biconomySmartAccount", transport, chain> + +/** + * The account creation ABI for Biconomy Smart Account (from the biconomy SmartAccountFactory) + */ + +const createAccountAbi = [ + { + inputs: [ + { + internalType: "address", + name: "moduleSetupContract", + type: "address" + }, + { + internalType: "bytes", + name: "moduleSetupData", + type: "bytes" + }, + { + internalType: "uint256", + name: "index", + type: "uint256" + } + ], + name: "deployCounterFactualAccount", + outputs: [ + { + internalType: "address", + name: "proxy", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "function" + } +] as const + +/** + * Default addresses for Biconomy Smart Account + */ +const BICONOMY_ADDRESSES: { + ECDSA_OWNERSHIP_REGISTRY_MODULE: Address + ACCOUNT_V2_0_LOGIC: Address + FACTORY_ADDRESS: Address + DEFAULT_FALLBACK_HANDLER_ADDRESS: Address +} = { + ECDSA_OWNERSHIP_REGISTRY_MODULE: + "0x0000001c5b32F37F5beA87BDD5374eB2aC54eA8e", + ACCOUNT_V2_0_LOGIC: "0x0000002512019Dafb59528B82CB92D3c5D2423aC", + FACTORY_ADDRESS: "0x000000a56Aaca3e9a4C479ea6b6CD0DbcB6634F5", + DEFAULT_FALLBACK_HANDLER_ADDRESS: + "0x0bBa6d96BD616BedC6BFaa341742FD43c60b83C1" +} + +const BICONOMY_PROXY_CREATION_CODE = + "0x6080346100aa57601f61012038819003918201601f19168301916001600160401b038311848410176100af578084926020946040528339810103126100aa57516001600160a01b0381168082036100aa5715610065573055604051605a90816100c68239f35b60405162461bcd60e51b815260206004820152601e60248201527f496e76616c696420696d706c656d656e746174696f6e206164647265737300006044820152606490fd5b600080fd5b634e487b7160e01b600052604160045260246000fdfe608060405230546000808092368280378136915af43d82803e156020573d90f35b3d90fdfea2646970667358221220a03b18dce0be0b4c9afe58a9eb85c35205e2cf087da098bbf1d23945bf89496064736f6c63430008110033" + +/** + * Get the account initialization code for Biconomy smart account with ECDSA as default authorization module + * @param owner + * @param index + * @param factoryAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async ({ + owner, + index, + factoryAddress, + ecdsaModuleAddress +}: { + owner: Address + index: bigint + factoryAddress: Address + ecdsaModuleAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the module setup data + const ecdsaOwnershipInitData = encodeFunctionData({ + abi: BiconomyInitAbi, + functionName: "initForSmartAccount", + args: [owner] + }) + + // Build the account init code + return concatHex([ + factoryAddress, + encodeFunctionData({ + abi: createAccountAbi, + functionName: "deployCounterFactualAccount", + args: [ecdsaModuleAddress, ecdsaOwnershipInitData, index] + }) as Hex + ]) +} + +const getAccountAddress = async < + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + factoryAddress, + accountLogicAddress, + fallbackHandlerAddress, + ecdsaModuleAddress, + entryPoint, + owner, + index = 0n +}: { + client: Client<TTransport, TChain> + factoryAddress: Address + accountLogicAddress: Address + fallbackHandlerAddress: Address + ecdsaModuleAddress: Address + owner: Address + entryPoint: Address + index?: bigint +}): Promise<Address> => { + // @ts-ignore + const unusedClient = client // Ignoring the error for now + // @ts-ignore + const unusedEntryPoint = entryPoint // Ignoring the error for now + // 1. + /*const initCode = await getAccountInitCode({owner, index, factoryAddress, ecdsaModuleAddress}) + + return getSenderAddress(client, { + initCode, + entryPoint + })*/ + + //2. + + // Build the module setup data + const ecdsaOwnershipInitData = encodeFunctionData({ + abi: BiconomyInitAbi, + functionName: "initForSmartAccount", + args: [owner] + }) + + // Build account init code + const initialisationData = encodeFunctionData({ + abi: BiconomyInitAbi, + functionName: "init", + args: [ + fallbackHandlerAddress, + ecdsaModuleAddress, + ecdsaOwnershipInitData + ] + }) + + const deploymentCode = encodePacked( + ["bytes", "uint256"], + [BICONOMY_PROXY_CREATION_CODE, hexToBigInt(accountLogicAddress)] + ) + + const salt = keccak256( + encodePacked( + ["bytes32", "uint256"], + [keccak256(encodePacked(["bytes"], [initialisationData])), index] + ) + ) + + return getContractAddress({ + from: factoryAddress, + salt, + bytecode: deploymentCode, + opcode: "CREATE2" + }) +} + +/** + * Build a Biconomy modular smart account from a private key, that use the ECDSA signer behind the scene + * @param client + * @param privateKey + * @param entryPoint + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaModuleAddress + */ +export async function signerToBiconomySmartAccount< + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>( + client: Client<TTransport, TChain>, + { + signer, + entryPoint, + index = 0n, + factoryAddress = BICONOMY_ADDRESSES.FACTORY_ADDRESS, + accountLogicAddress = BICONOMY_ADDRESSES.ACCOUNT_V2_0_LOGIC, + fallbackHandlerAddress = BICONOMY_ADDRESSES.DEFAULT_FALLBACK_HANDLER_ADDRESS, + ecdsaModuleAddress = BICONOMY_ADDRESSES.ECDSA_OWNERSHIP_REGISTRY_MODULE + }: { + signer: SmartAccountSigner
`SmartAccountSigner` now needs source & address;
permissionless.js
github_2023
typescript
47
pimlicolabs
plusminushalf
@@ -0,0 +1,389 @@ +import { + type Account, + type Address, + type Chain, + type Client, + type Hex, + type Transport, + concatHex, + encodeAbiParameters, + encodeFunctionData, + encodePacked, + getContractAddress, + hexToBigInt, + keccak256, + parseAbiParameters +} from "viem" +import { toAccount } from "viem/accounts" +import { + getBytecode, + getChainId, + signMessage, + signTypedData +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce.js" +// import { getSenderAddress } from "../../actions/public/getSenderAddress.js" +import { getUserOperationHash } from "../../utils/getUserOperationHash.js" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types.js" +import { + BiconomyExecuteAbi, + BiconomyInitAbi +} from "./abi/BiconomySmartAccountAbi.js" +// import Abis + +export type BiconomySmartAccount< + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<"biconomySmartAccount", transport, chain> + +/** + * The account creation ABI for Biconomy Smart Account (from the biconomy SmartAccountFactory) + */ + +const createAccountAbi = [ + { + inputs: [ + { + internalType: "address", + name: "moduleSetupContract", + type: "address" + }, + { + internalType: "bytes", + name: "moduleSetupData", + type: "bytes" + }, + { + internalType: "uint256", + name: "index", + type: "uint256" + } + ], + name: "deployCounterFactualAccount", + outputs: [ + { + internalType: "address", + name: "proxy", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "function" + } +] as const + +/** + * Default addresses for Biconomy Smart Account + */ +const BICONOMY_ADDRESSES: { + ECDSA_OWNERSHIP_REGISTRY_MODULE: Address + ACCOUNT_V2_0_LOGIC: Address + FACTORY_ADDRESS: Address + DEFAULT_FALLBACK_HANDLER_ADDRESS: Address +} = { + ECDSA_OWNERSHIP_REGISTRY_MODULE: + "0x0000001c5b32F37F5beA87BDD5374eB2aC54eA8e", + ACCOUNT_V2_0_LOGIC: "0x0000002512019Dafb59528B82CB92D3c5D2423aC", + FACTORY_ADDRESS: "0x000000a56Aaca3e9a4C479ea6b6CD0DbcB6634F5", + DEFAULT_FALLBACK_HANDLER_ADDRESS: + "0x0bBa6d96BD616BedC6BFaa341742FD43c60b83C1" +} + +const BICONOMY_PROXY_CREATION_CODE = + "0x6080346100aa57601f61012038819003918201601f19168301916001600160401b038311848410176100af578084926020946040528339810103126100aa57516001600160a01b0381168082036100aa5715610065573055604051605a90816100c68239f35b60405162461bcd60e51b815260206004820152601e60248201527f496e76616c696420696d706c656d656e746174696f6e206164647265737300006044820152606490fd5b600080fd5b634e487b7160e01b600052604160045260246000fdfe608060405230546000808092368280378136915af43d82803e156020573d90f35b3d90fdfea2646970667358221220a03b18dce0be0b4c9afe58a9eb85c35205e2cf087da098bbf1d23945bf89496064736f6c63430008110033" + +/** + * Get the account initialization code for Biconomy smart account with ECDSA as default authorization module + * @param owner + * @param index + * @param factoryAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async ({ + owner, + index, + factoryAddress, + ecdsaModuleAddress +}: { + owner: Address + index: bigint + factoryAddress: Address + ecdsaModuleAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the module setup data + const ecdsaOwnershipInitData = encodeFunctionData({ + abi: BiconomyInitAbi, + functionName: "initForSmartAccount", + args: [owner] + }) + + // Build the account init code + return concatHex([ + factoryAddress, + encodeFunctionData({ + abi: createAccountAbi, + functionName: "deployCounterFactualAccount", + args: [ecdsaModuleAddress, ecdsaOwnershipInitData, index] + }) as Hex + ]) +} + +const getAccountAddress = async < + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + factoryAddress, + accountLogicAddress, + fallbackHandlerAddress, + ecdsaModuleAddress, + entryPoint, + owner, + index = 0n +}: { + client: Client<TTransport, TChain> + factoryAddress: Address + accountLogicAddress: Address + fallbackHandlerAddress: Address + ecdsaModuleAddress: Address + owner: Address + entryPoint: Address + index?: bigint +}): Promise<Address> => { + // @ts-ignore
need to resolve this.
permissionless.js
github_2023
typescript
47
pimlicolabs
plusminushalf
@@ -0,0 +1,389 @@ +import { + type Account, + type Address, + type Chain, + type Client, + type Hex, + type Transport, + concatHex, + encodeAbiParameters, + encodeFunctionData, + encodePacked, + getContractAddress, + hexToBigInt, + keccak256, + parseAbiParameters +} from "viem" +import { toAccount } from "viem/accounts" +import { + getBytecode, + getChainId, + signMessage, + signTypedData +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce.js" +// import { getSenderAddress } from "../../actions/public/getSenderAddress.js" +import { getUserOperationHash } from "../../utils/getUserOperationHash.js" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types.js" +import { + BiconomyExecuteAbi, + BiconomyInitAbi +} from "./abi/BiconomySmartAccountAbi.js" +// import Abis + +export type BiconomySmartAccount< + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<"biconomySmartAccount", transport, chain> + +/** + * The account creation ABI for Biconomy Smart Account (from the biconomy SmartAccountFactory) + */ + +const createAccountAbi = [ + { + inputs: [ + { + internalType: "address", + name: "moduleSetupContract", + type: "address" + }, + { + internalType: "bytes", + name: "moduleSetupData", + type: "bytes" + }, + { + internalType: "uint256", + name: "index", + type: "uint256" + } + ], + name: "deployCounterFactualAccount", + outputs: [ + { + internalType: "address", + name: "proxy", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "function" + } +] as const + +/** + * Default addresses for Biconomy Smart Account + */ +const BICONOMY_ADDRESSES: { + ECDSA_OWNERSHIP_REGISTRY_MODULE: Address + ACCOUNT_V2_0_LOGIC: Address + FACTORY_ADDRESS: Address + DEFAULT_FALLBACK_HANDLER_ADDRESS: Address +} = { + ECDSA_OWNERSHIP_REGISTRY_MODULE: + "0x0000001c5b32F37F5beA87BDD5374eB2aC54eA8e", + ACCOUNT_V2_0_LOGIC: "0x0000002512019Dafb59528B82CB92D3c5D2423aC", + FACTORY_ADDRESS: "0x000000a56Aaca3e9a4C479ea6b6CD0DbcB6634F5", + DEFAULT_FALLBACK_HANDLER_ADDRESS: + "0x0bBa6d96BD616BedC6BFaa341742FD43c60b83C1" +} + +const BICONOMY_PROXY_CREATION_CODE = + "0x6080346100aa57601f61012038819003918201601f19168301916001600160401b038311848410176100af578084926020946040528339810103126100aa57516001600160a01b0381168082036100aa5715610065573055604051605a90816100c68239f35b60405162461bcd60e51b815260206004820152601e60248201527f496e76616c696420696d706c656d656e746174696f6e206164647265737300006044820152606490fd5b600080fd5b634e487b7160e01b600052604160045260246000fdfe608060405230546000808092368280378136915af43d82803e156020573d90f35b3d90fdfea2646970667358221220a03b18dce0be0b4c9afe58a9eb85c35205e2cf087da098bbf1d23945bf89496064736f6c63430008110033" + +/** + * Get the account initialization code for Biconomy smart account with ECDSA as default authorization module + * @param owner + * @param index + * @param factoryAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async ({ + owner, + index, + factoryAddress, + ecdsaModuleAddress +}: { + owner: Address + index: bigint + factoryAddress: Address + ecdsaModuleAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the module setup data + const ecdsaOwnershipInitData = encodeFunctionData({ + abi: BiconomyInitAbi, + functionName: "initForSmartAccount", + args: [owner] + }) + + // Build the account init code + return concatHex([ + factoryAddress, + encodeFunctionData({ + abi: createAccountAbi, + functionName: "deployCounterFactualAccount", + args: [ecdsaModuleAddress, ecdsaOwnershipInitData, index] + }) as Hex + ]) +} + +const getAccountAddress = async < + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + factoryAddress, + accountLogicAddress, + fallbackHandlerAddress, + ecdsaModuleAddress, + entryPoint, + owner, + index = 0n +}: { + client: Client<TTransport, TChain> + factoryAddress: Address + accountLogicAddress: Address + fallbackHandlerAddress: Address + ecdsaModuleAddress: Address + owner: Address + entryPoint: Address + index?: bigint +}): Promise<Address> => { + // @ts-ignore + const unusedClient = client // Ignoring the error for now + // @ts-ignore
this too
permissionless.js
github_2023
typescript
47
pimlicolabs
plusminushalf
@@ -0,0 +1,389 @@ +import { + type Account, + type Address, + type Chain, + type Client, + type Hex, + type Transport, + concatHex, + encodeAbiParameters, + encodeFunctionData, + encodePacked, + getContractAddress, + hexToBigInt, + keccak256, + parseAbiParameters +} from "viem" +import { toAccount } from "viem/accounts" +import { + getBytecode, + getChainId, + signMessage, + signTypedData +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce.js" +// import { getSenderAddress } from "../../actions/public/getSenderAddress.js" +import { getUserOperationHash } from "../../utils/getUserOperationHash.js" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccount, + type SmartAccountSigner +} from "../types.js" +import { + BiconomyExecuteAbi, + BiconomyInitAbi +} from "./abi/BiconomySmartAccountAbi.js" +// import Abis + +export type BiconomySmartAccount< + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<"biconomySmartAccount", transport, chain> + +/** + * The account creation ABI for Biconomy Smart Account (from the biconomy SmartAccountFactory) + */ + +const createAccountAbi = [ + { + inputs: [ + { + internalType: "address", + name: "moduleSetupContract", + type: "address" + }, + { + internalType: "bytes", + name: "moduleSetupData", + type: "bytes" + }, + { + internalType: "uint256", + name: "index", + type: "uint256" + } + ], + name: "deployCounterFactualAccount", + outputs: [ + { + internalType: "address", + name: "proxy", + type: "address" + } + ], + stateMutability: "nonpayable", + type: "function" + } +] as const + +/** + * Default addresses for Biconomy Smart Account + */ +const BICONOMY_ADDRESSES: { + ECDSA_OWNERSHIP_REGISTRY_MODULE: Address + ACCOUNT_V2_0_LOGIC: Address + FACTORY_ADDRESS: Address + DEFAULT_FALLBACK_HANDLER_ADDRESS: Address +} = { + ECDSA_OWNERSHIP_REGISTRY_MODULE: + "0x0000001c5b32F37F5beA87BDD5374eB2aC54eA8e", + ACCOUNT_V2_0_LOGIC: "0x0000002512019Dafb59528B82CB92D3c5D2423aC", + FACTORY_ADDRESS: "0x000000a56Aaca3e9a4C479ea6b6CD0DbcB6634F5", + DEFAULT_FALLBACK_HANDLER_ADDRESS: + "0x0bBa6d96BD616BedC6BFaa341742FD43c60b83C1" +} + +const BICONOMY_PROXY_CREATION_CODE = + "0x6080346100aa57601f61012038819003918201601f19168301916001600160401b038311848410176100af578084926020946040528339810103126100aa57516001600160a01b0381168082036100aa5715610065573055604051605a90816100c68239f35b60405162461bcd60e51b815260206004820152601e60248201527f496e76616c696420696d706c656d656e746174696f6e206164647265737300006044820152606490fd5b600080fd5b634e487b7160e01b600052604160045260246000fdfe608060405230546000808092368280378136915af43d82803e156020573d90f35b3d90fdfea2646970667358221220a03b18dce0be0b4c9afe58a9eb85c35205e2cf087da098bbf1d23945bf89496064736f6c63430008110033" + +/** + * Get the account initialization code for Biconomy smart account with ECDSA as default authorization module + * @param owner + * @param index + * @param factoryAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async ({ + owner, + index, + factoryAddress, + ecdsaModuleAddress +}: { + owner: Address + index: bigint + factoryAddress: Address + ecdsaModuleAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the module setup data + const ecdsaOwnershipInitData = encodeFunctionData({ + abi: BiconomyInitAbi, + functionName: "initForSmartAccount", + args: [owner] + }) + + // Build the account init code + return concatHex([ + factoryAddress, + encodeFunctionData({ + abi: createAccountAbi, + functionName: "deployCounterFactualAccount", + args: [ecdsaModuleAddress, ecdsaOwnershipInitData, index] + }) as Hex + ]) +} + +const getAccountAddress = async <
Can we not use: ```typescript const initCode = await getAccountInitCode(...) return getSenderAddress(client, { initCode, entryPoint }) ```
permissionless.js
github_2023
typescript
42
pimlicolabs
plusminushalf
@@ -0,0 +1,363 @@ +import { + type Account, + type Address, + type Chain, + type Client, + type Hex, + type Transport, + concatHex, + encodeFunctionData, + isAddressEqual +} from "viem" +import { toAccount } from "viem/accounts" +import { + getBytecode, + getChainId, + readContract, + signMessage, + signTypedData +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce.js" +import { getSenderAddress } from "../../actions/public/getSenderAddress.js" +import { getUserOperationHash } from "../../utils/getUserOperationHash.js" +import type { SmartAccount } from "../types.js" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccountSigner +} from "../types.js" +import { KernelExecuteAbi, KernelInitAbi } from "./abi/KernelAccountAbi.js" + +export type KernelEcdsaSmartAccount< + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<"kernelEcdsaSmartAccount", transport, chain> + +/** + * The account creation ABI for a kernel smart account (from the KernelFactory) + */ +const createAccountAbi = [ + { + inputs: [ + { + internalType: "address", + name: "_implementation", + type: "address" + }, + { + internalType: "bytes", + name: "_data", + type: "bytes" + }, + { + internalType: "uint256", + name: "_index", + type: "uint256" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "address", + name: "proxy", + type: "address" + } + ], + stateMutability: "payable", + type: "function" + } +] as const + +/** + * Default addresses for kernel smart account + */ +const KERNEL_ADDRESSES: { + ECDSA_VALIDATOR: Address + ACCOUNT_V2_2_LOGIC: Address + FACTORY_ADDRESS: Address +} = { + ECDSA_VALIDATOR: "0xd9AB5096a832b9ce79914329DAEE236f8Eea0390", + ACCOUNT_V2_2_LOGIC: "0x0DA6a956B9488eD4dd761E59f52FDc6c8068E6B5", + FACTORY_ADDRESS: "0x5de4839a76cf55d0c90e2061ef4386d962E15ae3" +} + +/** + * Get the account initialization code for a kernel smart account + * @param owner + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async ({ + owner, + index, + factoryAddress, + accountLogicAddress, + ecdsaValidatorAddress +}: { + owner: Address + index: bigint + factoryAddress: Address + accountLogicAddress: Address + ecdsaValidatorAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the account initialization data + const initialisationData = encodeFunctionData({ + abi: KernelInitAbi, + functionName: "initialize", + args: [ecdsaValidatorAddress, owner] + }) + + // Build the account init code + return concatHex([ + factoryAddress, + encodeFunctionData({ + abi: createAccountAbi, + functionName: "createAccount", + args: [accountLogicAddress, initialisationData, index] + }) as Hex + ]) +} + +/** + * Check the validity of an existing account address, or fetch the pre-deterministic account address for a kernel smart wallet + * @param client + * @param owner + * @param entryPoint + * @param ecdsaValidatorAddress + * @param initCodeProvider + * @param deployedAccountAddress + */ +const getAccountAddress = async < + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + owner, + entryPoint, + initCodeProvider, + ecdsaValidatorAddress, + deployedAccountAddress +}: { + client: Client<TTransport, TChain> + owner: Address + initCodeProvider: () => Promise<Hex> + entryPoint: Address + ecdsaValidatorAddress: Address + deployedAccountAddress?: Address +}): Promise<Address> => { + // If we got an already deployed account, ensure it's well deployed, and the validator & signer are correct + if (deployedAccountAddress !== undefined) { + // Get the owner of the deployed account, ensure it's the same as the owner given in params + const deployedAccountOwner = await readContract(client, { + address: ecdsaValidatorAddress, + abi: [ + { + inputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + name: "ecdsaValidatorStorage", + outputs: [ + { + internalType: "address", + name: "owner", + type: "address" + } + ], + stateMutability: "view", + type: "function" + } + ], + functionName: "ecdsaValidatorStorage", + args: [deployedAccountAddress] + }) + + // Ensure the address match + if (!isAddressEqual(deployedAccountOwner, owner)) { + throw new Error("Invalid owner for the already deployed account") + } + + // If ok, return the address + return deployedAccountAddress + } + + // Find the init code for this account + const initCode = await initCodeProvider() + + // Get the sender address based on the init code + return getSenderAddress(client, { + initCode, + entryPoint + }) +} + +/** + * Build a kernel smart account from a private key, that use the ECDSA signer behind the scene + * @param client + * @param privateKey + * @param entryPoint + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + * @param deployedAccountAddress + */ +export async function signerToEcdsaKernelSmartAccount< + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>( + client: Client<TTransport, TChain>, + { + signer, + entryPoint, + index = 0n, + factoryAddress = KERNEL_ADDRESSES.FACTORY_ADDRESS, + accountLogicAddress = KERNEL_ADDRESSES.ACCOUNT_V2_2_LOGIC, + ecdsaValidatorAddress = KERNEL_ADDRESSES.ECDSA_VALIDATOR, + deployedAccountAddress + }: { + signer: SmartAccountSigner + entryPoint: Address + index?: bigint + factoryAddress?: Address + accountLogicAddress?: Address + ecdsaValidatorAddress?: Address + deployedAccountAddress?: Address + } +): Promise<KernelEcdsaSmartAccount<TTransport, TChain>> { + // Get the private key related account + const viemSigner: Account = + signer.type === "local" + ? ({ + ...signer, + signTransaction: (_, __) => { + throw new SignTransactionNotSupportedBySmartAccount() + } + } as Account) + : (signer as Account) + + // Helper to generate the init code for the smart account + const generateInitCode = () => + getAccountInitCode({ + owner: viemSigner.address, + index, + factoryAddress, + accountLogicAddress, + ecdsaValidatorAddress + }) + + // Fetch account address and chain id + const [accountAddress, chainId] = await Promise.all([ + getAccountAddress<TTransport, TChain>({ + client, + entryPoint, + owner: viemSigner.address, + ecdsaValidatorAddress, + initCodeProvider: generateInitCode, + deployedAccountAddress + }), + getChainId(client) + ]) + + if (!accountAddress) throw new Error("Account address not found") + + // Build the EOA Signer + const account = toAccount({ + address: accountAddress, + async signMessage({ message }) { + return signMessage(client, { account: viemSigner, message }) + }, + async signTransaction(_, __) { + throw new SignTransactionNotSupportedBySmartAccount() + }, + async signTypedData(typedData) { + return signTypedData(client, { account: viemSigner, ...typedData }) + } + }) + + return { + ...account, + client: client, + publicKey: accountAddress, + entryPoint: entryPoint, + source: "kernelEcdsaSmartAccount", + + // Get the nonce of the smart account + async getNonce() { + return getAccountNonce(client, { + sender: accountAddress, + entryPoint: entryPoint + }) + }, + + // Sign a user operation + async signUserOperation(userOperation) { + const hash = getUserOperationHash({ + userOperation: { + ...userOperation, + signature: "0x" + }, + entryPoint: entryPoint, + chainId: chainId + }) + const signature = await signMessage(client, { + account: viemSigner, + message: { raw: hash } + }) + // Always use the sudo mode, since we will use external paymaster + return concatHex(["0x00000000", signature])
what do you mean by "since we will use external paymaster"? Will this impact others using this library?
permissionless.js
github_2023
typescript
42
pimlicolabs
plusminushalf
@@ -16,6 +16,11 @@ import { smartAccountActions } from "./decorators/smartAccount.js" +/** + * TODO: + * - Add docs + * - Fix typing, 'accounts' is required to signMessage, signTypedData, signTransaction, but not needed here, since account is embedded in the client
This is not needed, as in viem in `signTransaction` you can have a client without an account and attach the account to any of the above function calls separately.
permissionless.js
github_2023
typescript
42
pimlicolabs
plusminushalf
@@ -0,0 +1,363 @@ +import { + type Account, + type Address, + type Chain, + type Client, + type Hex, + type Transport, + concatHex, + encodeFunctionData, + isAddressEqual +} from "viem" +import { toAccount } from "viem/accounts" +import { + getBytecode, + getChainId, + readContract, + signMessage, + signTypedData +} from "viem/actions" +import { getAccountNonce } from "../../actions/public/getAccountNonce.js" +import { getSenderAddress } from "../../actions/public/getSenderAddress.js" +import { getUserOperationHash } from "../../utils/getUserOperationHash.js" +import type { SmartAccount } from "../types.js" +import { + SignTransactionNotSupportedBySmartAccount, + type SmartAccountSigner +} from "../types.js" +import { KernelExecuteAbi, KernelInitAbi } from "./abi/KernelAccountAbi.js" + +export type KernelEcdsaSmartAccount< + transport extends Transport = Transport, + chain extends Chain | undefined = Chain | undefined +> = SmartAccount<"kernelEcdsaSmartAccount", transport, chain> + +/** + * The account creation ABI for a kernel smart account (from the KernelFactory) + */ +const createAccountAbi = [ + { + inputs: [ + { + internalType: "address", + name: "_implementation", + type: "address" + }, + { + internalType: "bytes", + name: "_data", + type: "bytes" + }, + { + internalType: "uint256", + name: "_index", + type: "uint256" + } + ], + name: "createAccount", + outputs: [ + { + internalType: "address", + name: "proxy", + type: "address" + } + ], + stateMutability: "payable", + type: "function" + } +] as const + +/** + * Default addresses for kernel smart account + */ +const KERNEL_ADDRESSES: { + ECDSA_VALIDATOR: Address + ACCOUNT_V2_2_LOGIC: Address + FACTORY_ADDRESS: Address +} = { + ECDSA_VALIDATOR: "0xd9AB5096a832b9ce79914329DAEE236f8Eea0390", + ACCOUNT_V2_2_LOGIC: "0x0DA6a956B9488eD4dd761E59f52FDc6c8068E6B5", + FACTORY_ADDRESS: "0x5de4839a76cf55d0c90e2061ef4386d962E15ae3" +} + +/** + * Get the account initialization code for a kernel smart account + * @param owner + * @param index + * @param factoryAddress + * @param accountLogicAddress + * @param ecdsaValidatorAddress + */ +const getAccountInitCode = async ({ + owner, + index, + factoryAddress, + accountLogicAddress, + ecdsaValidatorAddress +}: { + owner: Address + index: bigint + factoryAddress: Address + accountLogicAddress: Address + ecdsaValidatorAddress: Address +}): Promise<Hex> => { + if (!owner) throw new Error("Owner account not found") + + // Build the account initialization data + const initialisationData = encodeFunctionData({ + abi: KernelInitAbi, + functionName: "initialize", + args: [ecdsaValidatorAddress, owner] + }) + + // Build the account init code + return concatHex([ + factoryAddress, + encodeFunctionData({ + abi: createAccountAbi, + functionName: "createAccount", + args: [accountLogicAddress, initialisationData, index] + }) as Hex + ]) +} + +/** + * Check the validity of an existing account address, or fetch the pre-deterministic account address for a kernel smart wallet + * @param client + * @param owner + * @param entryPoint + * @param ecdsaValidatorAddress + * @param initCodeProvider + * @param deployedAccountAddress + */ +const getAccountAddress = async < + TTransport extends Transport = Transport, + TChain extends Chain | undefined = Chain | undefined +>({ + client, + owner, + entryPoint, + initCodeProvider, + ecdsaValidatorAddress, + deployedAccountAddress +}: { + client: Client<TTransport, TChain> + owner: Address + initCodeProvider: () => Promise<Hex> + entryPoint: Address + ecdsaValidatorAddress: Address + deployedAccountAddress?: Address +}): Promise<Address> => { + // If we got an already deployed account, ensure it's well deployed, and the validator & signer are correct + if (deployedAccountAddress !== undefined) { + // Get the owner of the deployed account, ensure it's the same as the owner given in params + const deployedAccountOwner = await readContract(client, { + address: ecdsaValidatorAddress, + abi: [ + { + inputs: [ + { + internalType: "address", + name: "", + type: "address" + } + ], + name: "ecdsaValidatorStorage", + outputs: [ + { + internalType: "address", + name: "owner", + type: "address" + } + ], + stateMutability: "view", + type: "function" + } + ], + functionName: "ecdsaValidatorStorage", + args: [deployedAccountAddress] + }) + + // Ensure the address match + if (!isAddressEqual(deployedAccountOwner, owner)) { + throw new Error("Invalid owner for the already deployed account")
Can we define a custom error for this?
permissionless.js
github_2023
typescript
10
pimlicolabs
plusminushalf
@@ -44,8 +44,7 @@ export type GetUserOperationStatusReturnType = PimlicoUserOperationStatus /** * Returns the live gas prices that you can use to send a user operation. * - * - Docs: [TODO://add link] - * - Example: [TODO://add link] + * - Docs: https://docs.pimlico.io/permissionless/reference/pimlico-bundler-actions/getUserOperationGasPrice
<img width="529" alt="image" src="https://github.com/pimlicolabs/permissionless.js/assets/5251472/150e3e3f-95cf-4d8c-ac64-d8d53d2bc9c7"> We can use createPimlicoBundlerClient
permissionless.js
github_2023
typescript
10
pimlicolabs
plusminushalf
@@ -218,8 +213,7 @@ export type PimlicoPaymasterClientActions = { /** * Returns paymasterAndData & updated gas parameters required to sponsor a userOperation. * - * - Docs: [TODO://add link] - * - Example: [TODO://add link] + * https://docs.pimlico.io/permissionless/reference/pimlico-paymaster-actions/sponsorUserOperation
Can use `createPimlicoPaymasterClient`. <img width="620" alt="image" src="https://github.com/pimlicolabs/permissionless.js/assets/5251472/d2e2626f-a87e-44c6-85dc-d241791d9a70">
permissionless.js
github_2023
others
8
pimlicolabs
kristofgazso
@@ -42,7 +36,11 @@ "types": "./_types/clients/pimlico.d.ts", "import": "./_esm/clients/pimlico.js", "default": "./_cjs/clients/pimlico.js" - } + },"./utils": {
(nitpick) formatting
permissionless.js
github_2023
typescript
8
pimlicolabs
kristofgazso
@@ -0,0 +1,46 @@ +import { type Address, type Hex, encodeAbiParameters, keccak256 } from "viem" +import type { UserOperation } from "../types" + +function packUserOp(userOperation: UserOperation): Hex { + const hashedInitCode = keccak256(userOperation.initCode) + const hashedCallData = keccak256(userOperation.callData) + const hashedPaymasterAndData = keccak256(userOperation.paymasterAndData) + + return encodeAbiParameters( + [ + { type: "address" }, + { type: "uint256" }, + { type: "bytes32" }, + { type: "bytes32" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "bytes32" } + ], + [ + userOperation.sender as Address, + userOperation.nonce, + hashedInitCode, + hashedCallData, + userOperation.callGasLimit, + userOperation.verificationGasLimit, + userOperation.preVerificationGas, + userOperation.maxFeePerGas, + userOperation.maxPriorityFeePerGas, + hashedPaymasterAndData + ] + ) +} + +const getUserOperationHash = (userOperation: UserOperation, entryPointAddress: Address, chainId: bigint) => {
should these be positional or kwargs?
leptonic
github_2023
others
77
lpotthast
ydirson
@@ -30,33 +30,33 @@ js-sys = "0.3.68" leptos = "0.6.5" leptos_reactive = "0.6.5" leptos-tiptap = { version = "0.7.0", optional = true } -leptos-use = { version = "0.10.2", features = ["math"] } +leptos-use = { version = "0.12.0", features = ["math"] } icondata = { version = "0.3.0" } leptos_meta = { version = "0.6.5", features = [] } leptos_router = "0.6.5" serde = "1.0.196" serde-wasm-bindgen = "0.6.3" serde_json = "1.0.113" strum = { version = "0.26.1", features = ["derive"] } -time = { version = "0.3.34", features = [ - "wasm-bindgen", - "macros", - "serde", - "serde-well-known", +time = { version = "0.3.36", features = [ + "wasm-bindgen", + "macros", + "serde", + "serde-well-known", ] } tracing = "0.1.40" uuid = { version = "1.7.0", features = ["v4", "v7", "js", "serde"] } wasm-bindgen = "0.2.91" wasm-bindgen-futures = "0.4.41" # TODO: What of all below is really required? web-sys = { version = "0.3.68", features = [ - "DomRect", - "Event", - "EventTarget", - "ScrollIntoViewOptions", - "HtmlFormElement", - "HtmlInputElement", - "Storage", + "DomRect", + "Event", + "EventTarget", + "ScrollIntoViewOptions", + "HtmlFormElement", + "HtmlInputElement", + "Storage",
this and other indent changes just introduce noise
leptonic
github_2023
others
77
lpotthast
ydirson
@@ -30,33 +30,33 @@ js-sys = "0.3.68" leptos = "0.6.5" leptos_reactive = "0.6.5" leptos-tiptap = { version = "0.7.0", optional = true } -leptos-use = { version = "0.10.2", features = ["math"] } +leptos-use = { version = "0.12.0", features = ["math"] }
This is highly unrelated to the `time` issue - Leptonic even build fine with Rust 1.80 and `leptos-use` 0.10.10, though there are errors that do need handling, which may have an origin similar to that of the `time` create.
leptonic
github_2023
others
77
lpotthast
ydirson
@@ -30,33 +30,33 @@ js-sys = "0.3.68" leptos = "0.6.5" leptos_reactive = "0.6.5" leptos-tiptap = { version = "0.7.0", optional = true } -leptos-use = { version = "0.10.2", features = ["math"] } +leptos-use = { version = "0.12.0", features = ["math"] } icondata = { version = "0.3.0" } leptos_meta = { version = "0.6.5", features = [] } leptos_router = "0.6.5" serde = "1.0.196" serde-wasm-bindgen = "0.6.3" serde_json = "1.0.113" strum = { version = "0.26.1", features = ["derive"] } -time = { version = "0.3.34", features = [
And this is the version on `main`, which has no issue getting a fixed `time` crate - the problem is really the `=0.3.31` in the v0.5.0 release
leptonic
github_2023
others
16
lpotthast
paulvt
@@ -1,7 +1,7 @@ use std::fmt::{Display, Formatter}; use leptos::{ - leptos_dom::{Callable, Callback}, + Callable, Callback,
`Callable` and `Callback` are included in `leptos::*` by default now, so these can be removed (in this file and all the others)!
leptonic
github_2023
others
16
lpotthast
paulvt
@@ -1,7 +1,7 @@ use std::fmt::Display; use leptos::{ - leptos_dom::{Callable, Callback, StoredCallback}, + Callable, Callback, StoredValue,
The same holds for `StoredValue` 🙂
novel
github_2023
others
403
steven-tey
andrewdoro
@@ -200,4 +200,12 @@ div[data-youtube-video] > iframe { div[data-youtube-video] > iframe { max-height: 100px; } +} + +span[style] > strong { + color: inherit; +} + +mark[style] > strong { + color: inherit;
hey thanks for the change, it would be great if you can also add the changes to the prosemirror docs file
novel
github_2023
typescript
400
steven-tey
andrewdoro
@@ -28,7 +29,7 @@ const Command = Extension.create({ }, }); -const renderItems = () => { +const renderItems = (elementRef: RefObject<Element> | null = null) => {
I think you need to make the elementRef optional `elementRef?: RefObject<Element> | null = null` I just want to be sure that TS won't complain about missing argument when calling renderItems()
novel
github_2023
typescript
375
steven-tey
maks-ivanov
@@ -106,6 +112,16 @@ const starterKit = StarterKit.configure({ gapcursor: false, }); +const lowlight = createLowlight(common); +lowlight.register("html", html); +lowlight.register("css", css); +lowlight.register("js", js); +lowlight.register("ts", ts); + +const codeBlockLowlight = CodeBlockLowlight.configure({ + lowlight, +}); +
Nice, I've been looking at implementing this feature! I think this would need a way to specify languages via configuration, since this block basically just hardcodes these 4
novel
github_2023
typescript
361
steven-tey
haydenbleasel
@@ -38,7 +40,10 @@ const simpleExtensions = [ transformCopiedText: true, }), CustomKeymap, - DragAndDrop, + GlobalDragHandle.configure({ + scrollTreshold: 0,
Typo
novel
github_2023
typescript
350
steven-tey
andrewdoro
@@ -12,6 +12,17 @@ export interface DragHandleOptions { } function absoluteRect(node: Element) { const data = node.getBoundingClientRect(); + const modal = node.closest('[role="dialog"]');
should we also add something about this to the docs, I don't know if all people use this attr for their dialog`[role="dialog"]`. Wyt?
novel
github_2023
typescript
297
steven-tey
chrisp018
@@ -53,26 +55,94 @@ export async function POST(req: Request): Promise<Response> { } } - let { prompt } = await req.json(); + let { prompt, option } = await req.json(); - const response = await openai.chat.completions.create({ - model: process.env.NODE_ENV == "development" ? "llama2" : "gpt-3.5-turbo", - stream: true, - messages: [ + const messages = match(option) + .with("continue", () => [ { role: "system", content: "You are an AI writing assistant that continues existing text based on context from prior text. " + "Give more weight/priority to the later characters than the beginning ones. " + - "Limit your response to no more than 200 characters, but make sure to construct complete sentences.", - // we're disabling markdown for now until we can figure out a way to stream markdown text with proper formatting: https://github.com/steven-tey/novel/discussions/7 - // "Use Markdown formatting when appropriate.", + "Limit your response to no more than 200 characters, but make sure to construct complete sentences." + + "Use Markdown formatting when appropriate.", + }, + { + role: "user", + content: prompt, + }, + ]) + .with("improve", () => [ + { + role: "system", + content: + "You are an AI writing assistant that improves existing text. " + + "Limit your response to no more than 200 characters, but make sure to construct complete sentences." + + "Use Markdown formatting when appropriate.", + }, + { + role: "user", + content: prompt, + }, + ]) + .with("shorter", () => [ + { + role: "system", + content: + "You are an AI writing assistant that shortens existing text. " + + "Use Markdown formatting when appropriate.", + }, + { + role: "user", + content: prompt, + }, + ]) + .with("longer", () => [ + { + role: "system", + content: + "You are an AI writing assistant that lengthens existing text. " + + "Use Markdown formatting when appropriate.", + }, + { + role: "user", + content: prompt,
![image](https://github.com/steven-tey/novel/assets/45734348/cddd2ca0-acdd-405f-a915-de89a89896af) ![image](https://github.com/steven-tey/novel/assets/45734348/8599c6a4-0e29-4c94-82ab-ba9d277f66ed) Do you think we should add further information for content?, I just added simple expand sentence like this ```content: `The existing text is: ${prompt}`,``` The screenshot show improve abit
novel
github_2023
typescript
136
steven-tey
jeloi
@@ -0,0 +1,172 @@ +import StarterKit, { StarterKitOptions } from "@tiptap/starter-kit"; +import HorizontalRule from "@tiptap/extension-horizontal-rule"; +import TiptapLink from "@tiptap/extension-link"; +import TiptapImage from "@tiptap/extension-image"; +import Placeholder from "@tiptap/extension-placeholder"; +import TiptapUnderline from "@tiptap/extension-underline"; +import TextStyle from "@tiptap/extension-text-style"; +import { Color } from "@tiptap/extension-color"; +import TaskItem from "@tiptap/extension-task-item"; +import TaskList from "@tiptap/extension-task-list"; +import { Markdown } from "tiptap-markdown"; +import Highlight from "@tiptap/extension-highlight"; +import { InputRule } from "@tiptap/core"; +import UpdatedImage from "./updated-image"; +import CustomKeymap from "./custom-keymap"; +import DragAndDrop from "./drag-and-drop"; +import UploadImagesPlugin from "../plugins/upload-images"; + +export type DefaultExtensionsStylingOptions = { + starterKit: { + bulletList: string; + orderedList: string; + listItem: string; + blockquote: string; + codeBlock: string; + code: string; + dropcursor: StarterKitOptions["dropcursor"]; + gapcursor: StarterKitOptions["gapcursor"]; + }; + horizontalRule: string; + tipTapLink: string; + tipTapImage: string; + updatedImage: string; + taskList: string; + taskItem: string; +}; + +// export const stylingOptionsExtensions = + +export const createDefaultExensions = ({ + starterKit: { + bulletList, + orderedList, + listItem, + blockquote, + codeBlock, + code, + dropcursor, + gapcursor, + }, + horizontalRule, + taskItem, + taskList, + tipTapImage, + tipTapLink, + updatedImage, +}: DefaultExtensionsStylingOptions) => [ + StarterKit.configure({ + bulletList: { + HTMLAttributes: { + class: bulletList, + }, + }, + orderedList: { + HTMLAttributes: { + class: orderedList, + }, + }, + listItem: { + HTMLAttributes: { + class: listItem, + }, + }, + blockquote: { + HTMLAttributes: { + class: blockquote, + }, + }, + codeBlock: { + HTMLAttributes: { + class: codeBlock, + }, + }, + code: { + HTMLAttributes: { + class: code, + spellcheck: "false", + }, + }, + horizontalRule: false, + dropcursor: dropcursor, + gapcursor: gapcursor, + }), + // patch to fix horizontal rule bug: https://github.com/ueberdosis/tiptap/pull/3859#issuecomment-1536799740 + HorizontalRule.extend({ + addInputRules() { + return [ + new InputRule({ + find: /^(?:---|—-|___\s|\*\*\*\s)$/, + handler: ({ state, range }) => { + const attributes = {}; + + const { tr } = state; + const start = range.from; + let end = range.to; + + tr.insert(start - 1, this.type.create(attributes)).delete( + tr.mapping.map(start), + tr.mapping.map(end) + ); + }, + }), + ]; + }, + }).configure({ + HTMLAttributes: { + class: horizontalRule, + }, + }), + TiptapLink.configure({ + HTMLAttributes: { + class: tipTapLink, + }, + }), + TiptapImage.extend({ + addProseMirrorPlugins() { + return [UploadImagesPlugin()]; + }, + }).configure({ + allowBase64: true, + HTMLAttributes: { + class: tipTapImage, + }, + }), + UpdatedImage.configure({ + HTMLAttributes: { + class: updatedImage, + }, + }), + Placeholder.configure({ + placeholder: ({ node }) => { + if (node.type.name === "heading") { + return `Heading ${node.attrs.level}`; + } + return "Press '/' for commands, or '++' for AI autocomplete...";
could we make this a param thats passed in? alternative is to just supporting override extensions entirely to configure a custom one, but could be too heavy handed.
novel
github_2023
typescript
47
steven-tey
steven-tey
@@ -140,12 +141,13 @@ export default function Editor() { onClick={() => { editor?.chain().focus().run(); }} - className="relative min-h-[500px] w-full max-w-screen-lg border-stone-200 p-12 px-8 sm:mb-[calc(20vh)] sm:rounded-lg sm:border sm:px-12 sm:shadow-lg" + className=" min-h-[500px] w-full max-w-screen-lg border-stone-200 p-12 px-8 sm:mb-[calc(20vh)] sm:rounded-lg sm:border sm:px-12 sm:shadow-lg"
This breaks the Save Status component's positioning: ![CleanShot 2023-06-25 at 16 08 07](https://github.com/steven-tey/novel/assets/28986134/e9ba65f3-a9e8-4837-b0b7-218f170ca04a)
novel
github_2023
typescript
18
steven-tey
steven-tey
@@ -33,8 +35,10 @@ export const metadata: Metadata = { export default function RootLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> - <Toaster /> - <body className={cx(cal.variable, inter.variable)}>{children}</body> + <body className={cx(cal.variable, inter.variable)}> + {children} + <Toaster />
Perfect – this has actually been bugging me for a while haha so thank you!
novel
github_2023
others
161
steven-tey
MarkLyck
@@ -150,7 +150,7 @@ ul[data-type="taskList"] li[data-checked="true"] > div > p { } &:active { - background-color: var(--novel-stone-200); + background-color: var(--nnovel-stone-200);
Is this supposed to have two `n`'s?
novel
github_2023
typescript
93
steven-tey
jasonLaster
@@ -0,0 +1,83 @@ +import { defineConfig, devices } from '@playwright/test'; +import { devices as replayDevices } from "@replayio/playwright"; + + +/** + * Read environment variables from file. + * https://github.com/motdotla/dotenv + */ +// require('dotenv').config(); + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './tests', + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: 'html', + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + // baseURL: 'http://127.0.0.1:3000', + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: 'on-first-retry', + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + + // { + // name: 'firefox', + // use: { ...devices['Desktop Firefox'] }, + // }, + + // { + // name: 'webkit', + // use: { ...devices['Desktop Safari'] }, + // }, + + /* Test against mobile viewports. */ + // { + // name: 'Mobile Chrome', + // use: { ...devices['Pixel 5'] }, + // }, + // { + // name: 'Mobile Safari', + // use: { ...devices['iPhone 12'] }, + // }, + + /* Test against branded browsers. */ + // { + // name: 'Microsoft Edge', + // use: { ...devices['Desktop Edge'], channel: 'msedge' }, + // }, + // { + // name: 'Google Chrome', + // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, + // },
we probably should remove the comments
novel
github_2023
typescript
93
steven-tey
jasonLaster
@@ -0,0 +1,49 @@ +import { test, expect } from '@playwright/test'; + +test('editing the content should work', async ({ page }) => { + await page.goto('http://localhost:3000/'); + await expect(page.getByText("Hello World!")).toHaveCount(0) + + await page.getByRole('heading', { name: 'Introducing Novel' }).click(); + await page.keyboard.press('Enter'); + await page.keyboard.type('Hello World!'); + + await expect(page.getByText("Hello World!")).toHaveCount(1) +}); + +test('pressing `/` should open the slash menu', async ({ page }) => { + await page.goto('http://localhost:3000/'); + await expect(page.locator("#slash-command")).toHaveCount(0) + + await page.getByRole('heading', { name: 'Introducing Novel' }).click(); + await page.keyboard.press('Enter'); + await page.keyboard.press('/'); + + await expect(page.locator("#slash-command")).toHaveCount(1) +}); + +// test('Pressing ++ should trigger AI autocomplete', async ({ page }) => { +// await page.goto('http://localhost:3000/'); + +// await page.getByRole('heading', { name: 'Introducing Novel' }).click(); +// await page.keyboard.press('Enter'); +// await page.keyboard.type('My favorite snack is'); +// await page.keyboard.press('+'); +// await page.keyboard.press('+'); + +// // Add timeout here +// // Add assertion here +// });
comments...
novel
github_2023
others
93
steven-tey
jasonLaster
@@ -0,0 +1,38 @@ +name: Playwright Tests +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] +jobs: + test: + timeout-minutes: 60 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: 18 + - uses: pnpm/action-setup@v2 + with: + version: 7 + - name: Install dependencies + run: pnpm install + - name: Install Playwright Browsers + run: pnpm exec playwright install --with-deps + - run: pnpm build + - name: Run Playwright tests + run: pnpm exec playwright test --project replay-chromium --reporter=@replayio/playwright/reporter,line + - uses: actions/upload-artifact@v3 + if: always() + with: + name: playwright-report + path: playwright-report/ + retention-days: 30 + - name: Upload replays + if: ${{ always() }} + uses: replayio/action-upload@v0.5.1 + with: + # TODO: Replace with a secret before merging + # api-key: ${{ secrets.RECORD_REPLAY_API_KEY }} + api-key: rwk_it0M3XJ0w4NYjEZtc72dd3BHI4pQEoChgy5u1sLZUs9
lets do `public:true` so these replays are publicly available
novel
github_2023
typescript
62
steven-tey
steven-tey
@@ -7,6 +7,7 @@ import { Analytics } from "@vercel/analytics/react"; import { Metadata } from "next"; import Toaster from "./toaster"; import { ReactNode } from "react"; +import { cookies } from "next/dist/client/components/headers";
This should be `import { cookies } from 'next/headers'`
novel
github_2023
typescript
62
steven-tey
steven-tey
@@ -1,31 +1,43 @@ import Editor from "@/ui/editor"; +import { ThemeSwitcher } from "@/ui/editor/components/theme-switcher"; import Github from "@/ui/shared/github"; +import { cookies } from "next/dist/client/components/headers"; export default function Page() { + + const theme = cookies().get("theme")?.value === "dark" ? "dark" : "light" + return ( <> <a href="/deploy" target="_blank" - className="absolute bottom-5 left-5 max-h-fit rounded-lg p-2 transition-colors duration-200 hover:bg-stone-100 sm:bottom-auto sm:top-5" + className="absolute p-2 transition-colors duration-200 rounded-lg bottom-5 left-5 max-h-fit hover:bg-stone-100 sm:bottom-auto sm:top-5 dark:hover:bg-slate-800" > <svg width={22} viewBox="0 0 76 76" fill="none" xmlns="http://www.w3.org/2000/svg" + className="dark:text-white" > - <path d="M37.5274 0L75.0548 65H0L37.5274 0Z" fill="#000000" /> + <path d="M37.5274 0L75.0548 65H0L37.5274 0Z" fill="currentColor" /> </svg> </a> <a href="/github" target="_blank" - className="absolute bottom-5 right-5 max-h-fit rounded-lg p-2 transition-colors duration-200 hover:bg-stone-100 sm:bottom-auto sm:top-5" + className="absolute p-2 transition-colors duration-200 rounded-lg bottom-5 right-5 max-h-fit hover:bg-stone-100 sm:bottom-auto sm:top-5 dark:hover:bg-slate-800"
Can we standardize to use shades of `stone` instead of `slate` please? 🙏
Swift-Macros
github_2023
others
65
krzysztofzablocki
krzysztofzablocki
@@ -149,11 +149,12 @@ that implements the same interface as the protocol and keeps track of interactio - [Reuse Identifier](https://github.com/collisionspace/ReuseIdentifierMacro): A Reuse Identifier Macro that is useful in generation of a reuse id for your UICollectionViewCells and UITableViewCells - [SwiftMacros collection](https://github.com/ShenghaiWang/SwiftMacros): A practical collection of Swift Macros that help code correctly and smartly. - [ModifiedCopyMacro](https://github.com/WilhelmOks/ModifiedCopyMacro): A Swift macro for making inline copies of a struct by modifying a property. -- [DictionaryLiteralShorthandMacro](https://github.com/Dcard/DictionaryLiteralShorthandMacro): A Swfit macro for creating dictionary literals with keys as "string representations of corresponding variable names". +- [DictionaryLiteralShorthandMacro](https://github.com/Dcard/DictionaryLiteralShorthandMacro): A Swfit macro for creating dictionary literals w ith keys as "string representations of corresponding variable names".
shouldn't modify this :)
nestjs-resilience
github_2023
typescript
320
SocketSomeone
SocketSomeone
@@ -53,6 +57,18 @@ export class CircuitBreakerStrategy extends Strategy<CircuitBreakerOptions> { const failuresPercentage = () => (state.failuresCount / this.options.requestVolumeThreshold) * 100; + if (this.options.rollingWindowInMilliseconds) { + const rollingWindowHasExpired = () => + Date.now() >= + state.lastRequestTimeMs + this.options.rollingWindowInMilliseconds; + if (rollingWindowHasExpired()) { + state.failuresCount = 0; + state.succeedsCount = 0; + state.openedAt = 0; + state.lastRequestTimeMs = Date.now();
Why we set last request only when rolling window has expired not every request? If its has no meaning - will be merged
nestjs-resilience
github_2023
typescript
320
SocketSomeone
SocketSomeone
@@ -0,0 +1,57 @@ +import { CircuitBreakerStrategy, UseResilience } from '../../src';
You created new decorator spec, but test for circuit strategy already created, maybe use previous?
nestjs-resilience
github_2023
typescript
320
SocketSomeone
SocketSomeone
@@ -53,6 +57,18 @@ export class CircuitBreakerStrategy extends Strategy<CircuitBreakerOptions> { const failuresPercentage = () => (state.failuresCount / this.options.requestVolumeThreshold) * 100; + if (this.options.rollingWindowInMilliseconds) { + const rollingWindowHasExpired = () => + Date.now() >= + state.lastRequestTimeMs + this.options.rollingWindowInMilliseconds; + if (rollingWindowHasExpired()) { + state.failuresCount = 0; + state.succeedsCount = 0; + state.openedAt = 0; + } + } + state.lastRequestTimeMs = Date.now();
```suggestion } state.lastRequestTimeMs = Date.now(); ```
lm-human-preference-details
github_2023
python
19
vwxyzjn
lewtun
@@ -510,6 +514,37 @@ def train(args: Args): ) dataloader = DataLoader(dataset, batch_size=args.ppo.local_batch_size) policy, optimizer, dataloader = accelerator.prepare(policy, optimizer, dataloader) + if args.deepspeed: + import deepspeed + + deepspeed_states = AcceleratorState().deepspeed_plugin + deepspeed_states.deepspeed_config['train_micro_batch_size_per_gpu'] = args.ppo.local_micro_batch_size + deepspeed_states.deepspeed_config['checkpoint'] = {'use_node_local_storage': True} + off_load_device = "cpu"
Note that this will slow down your code significantly. I would allow the option to be set as an option that's inferred from the `accelerate` config as I did here: https://github.com/huggingface/trl/pull/758
lm-human-preference-details
github_2023
python
19
vwxyzjn
lewtun
@@ -510,6 +514,37 @@ def train(args: Args): ) dataloader = DataLoader(dataset, batch_size=args.ppo.local_batch_size) policy, optimizer, dataloader = accelerator.prepare(policy, optimizer, dataloader) + if args.deepspeed: + import deepspeed + + deepspeed_states = AcceleratorState().deepspeed_plugin + deepspeed_states.deepspeed_config['train_micro_batch_size_per_gpu'] = args.ppo.local_micro_batch_size + deepspeed_states.deepspeed_config['checkpoint'] = {'use_node_local_storage': True}
I think this flag is only needed if each node has a separate local filesystem. For the HFC case, you probably don't need it