Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: add support for overriding the initCode for an account #197

Merged
merged 2 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
**/dist/*
examples/alchemy-daapp/*
site/.vitepress/cache/**/*
62 changes: 41 additions & 21 deletions packages/core/src/account/__tests__/simple.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Address } from "viem";
import { polygonMumbai, type Chain } from "viem/chains";
import { polygonMumbai, sepolia, type Chain } from "viem/chains";
import { describe, it } from "vitest";
import { getDefaultSimpleAccountFactoryAddress } from "../../index.js";
import { SmartAccountProvider } from "../../provider/base.js";
Expand Down Expand Up @@ -102,29 +102,49 @@ describe("Account Simple Tests", () => {
]"
`);
});
});

const givenConnectedProvider = ({
owner,
chain,
}: {
owner: SmartAccountSigner;
chain: Chain;
}) =>
new SmartAccountProvider({
rpcProvider: `${chain.rpcUrls.alchemy.http[0]}/${"test"}`,
chain,
}).connect((provider) => {
it("should correctly use the account init code override", async () => {
const account = new SimpleSmartContractAccount({
chain,
owner,
factoryAddress: getDefaultSimpleAccountFactoryAddress(chain),
rpcClient: provider,
chain: sepolia,
avasisht23 marked this conversation as resolved.
Show resolved Hide resolved
owner: owner,
factoryAddress: getDefaultSimpleAccountFactoryAddress(sepolia),
rpcClient: `${sepolia.rpcUrls.alchemy.http[0]}/${"test"}`,
// override the account address here so we don't have to resolve the address from the entrypoint
accountAddress: "0x1234567890123456789012345678901234567890",
avasisht23 marked this conversation as resolved.
Show resolved Hide resolved
initCode: "0xdeadbeef",
});

account.getAddress = vi.fn(
async () => "0xb856DBD4fA1A79a46D426f537455e7d3E79ab7c4"
);
// @ts-expect-error this object is protected
vi.spyOn(account.rpcProvider, "getBytecode").mockImplementation(() => {
return Promise.resolve("0x");
});

return account;
const initCode = await account.getInitCode();
expect(initCode).toMatchInlineSnapshot('"0xdeadbeef"');
});

const givenConnectedProvider = ({
owner,
chain,
}: {
owner: SmartAccountSigner;
chain: Chain;
}) =>
new SmartAccountProvider({
rpcProvider: `${chain.rpcUrls.alchemy.http[0]}/${"test"}`,
chain,
}).connect((provider) => {
const account = new SimpleSmartContractAccount({
chain,
owner,
factoryAddress: getDefaultSimpleAccountFactoryAddress(chain),
rpcClient: provider,
});

account.getAddress = vi.fn(
async () => "0xb856DBD4fA1A79a46D426f537455e7d3E79ab7c4"
);

return account;
});
});
67 changes: 37 additions & 30 deletions packages/core/src/account/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export abstract class BaseSmartContractAccount<
protected factoryAddress: Address;
protected deploymentState: DeploymentState = DeploymentState.UNDEFINED;
protected accountAddress?: Address;
protected accountInitCode?: Hex;
protected owner: SmartAccountSigner | undefined;
protected entryPoint: GetContractReturnType<
typeof EntryPointAbi,
Expand All @@ -51,8 +52,9 @@ export abstract class BaseSmartContractAccount<
| PublicErc4337Client<TTransport>
| PublicErc4337Client<HttpTransport>;

constructor(params: BaseSmartAccountParams<TTransport>) {
createBaseSmartAccountParamsSchema<TTransport>().parse(params);
constructor(params_: BaseSmartAccountParams<TTransport>) {
avasisht23 marked this conversation as resolved.
Show resolved Hide resolved
const params =
createBaseSmartAccountParamsSchema<TTransport>().parse(params_);

this.entryPointAddress =
params.entryPointAddress ?? getDefaultEntryPointAddress(params.chain);
Expand Down Expand Up @@ -95,6 +97,7 @@ export abstract class BaseSmartContractAccount<
this.accountAddress = params.accountAddress;
this.factoryAddress = params.factoryAddress;
this.owner = params.owner;
this.accountInitCode = params.initCode;

this.entryPoint = getContract({
address: this.entryPointAddress,
Expand Down Expand Up @@ -138,7 +141,7 @@ export abstract class BaseSmartContractAccount<

/**
* this should return the init code that will be used to create an account if one does not exist.
* Usually this is the concatenation of the account's factory address and the abi encoded function data of the account factory's `createAccount` method.
* This is the concatenation of the account's factory address and the abi encoded function data of the account factory's `createAccount` method.
*/
protected abstract getAccountInitCode(): Promise<Hash>;

Expand Down Expand Up @@ -189,29 +192,6 @@ export abstract class BaseSmartContractAccount<
return this.create6492Signature(isDeployed, signature);
}

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

const [factoryAddress, factoryCalldata] =
await this.parseFactoryAddressFromAccountInitCode();

Logger.debug(
`[BaseSmartContractAccount](create6492Signature)\
factoryAddress: ${factoryAddress}, factoryCalldata: ${factoryCalldata}`
);

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

/**
* Not all contracts support batch execution.
* If your contract does, this method should encode a list of
Expand All @@ -227,6 +207,7 @@ export abstract class BaseSmartContractAccount<
}
// #endregion optional-methods

// Extra implementations
async getNonce(): Promise<bigint> {
if (!(await this.isAccountDeployed())) {
return 0n;
Expand All @@ -250,12 +231,12 @@ export abstract class BaseSmartContractAccount<
this.deploymentState = DeploymentState.NOT_DEPLOYED;
}

return this.getAccountInitCode();
return this._getAccountInitCode();
}

async getAddress(): Promise<Address> {
if (!this.accountAddress) {
const initCode = await this.getAccountInitCode();
const initCode = await this._getAccountInitCode();
Logger.debug(
"[BaseSmartContractAccount](getAddress) initCode: ",
initCode
Expand Down Expand Up @@ -291,7 +272,6 @@ export abstract class BaseSmartContractAccount<
return this.entryPointAddress;
}

// Extra implementations
async isAccountDeployed(): Promise<boolean> {
return (await this.getDeploymentState()) === DeploymentState.DEPLOYED;
}
Expand All @@ -316,9 +296,36 @@ export abstract class BaseSmartContractAccount<
protected async parseFactoryAddressFromAccountInitCode(): Promise<
[Address, Hex]
> {
const initCode = await this.getAccountInitCode();
const initCode = await this._getAccountInitCode();
const factoryAddress = `0x${initCode.substring(2, 42)}` as Address;
const factoryCalldata = `0x${initCode.substring(42)}` as Hex;
return [factoryAddress, factoryCalldata];
}

private async _getAccountInitCode(): Promise<Hash> {
avasisht23 marked this conversation as resolved.
Show resolved Hide resolved
return this.accountInitCode ?? this.getAccountInitCode();
}

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

const [factoryAddress, factoryCalldata] =
await this.parseFactoryAddressFromAccountInitCode();

Logger.debug(
`[BaseSmartContractAccount](create6492Signature)\
factoryAddress: ${factoryAddress}, factoryCalldata: ${factoryCalldata}`
);

return wrapSignatureWith6492({
factoryAddress,
factoryCalldata,
signature,
});
}
}
11 changes: 9 additions & 2 deletions packages/core/src/account/schema.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Address } from "abitype/zod";
import type { Transport } from "viem";
import { isHex, type Transport } from "viem";
import z from "zod";
import { createPublicErc4337ClientSchema } from "../client/schema.js";
import type { SupportedTransports } from "../client/types";
Expand All @@ -18,5 +18,12 @@ export const createBaseSmartAccountParamsSchema = <
owner: SignerSchema.optional(),
entryPointAddress: Address.optional(),
chain: ChainSchema,
accountAddress: Address.optional(),
accountAddress: Address.optional().describe(
"Optional override for the account address."
),
initCode: z
.string()
.refine(isHex, "initCode must be a valid hex.")
.optional()
.describe("Optional override for the account init code."),
});
Loading