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: eip-7702 support in aa-sdk/core, and sma7702 support in account-kit/smart-contracts #1287

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
2 changes: 1 addition & 1 deletion .vitest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"prool": "^0.0.15",
"tar": "^7.4.1",
"typescript-template": "*",
"viem": "2.20.0"
"viem": "2.22.6"
},
"dependencies": {
"@aa-sdk/core": "^4.0.0-alpha.8"
Expand Down
2 changes: 1 addition & 1 deletion aa-sdk/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"zod": "^3.22.4"
},
"peerDependencies": {
"viem": "^2.20.0"
"viem": "^2.22.6"
},
"repository": {
"type": "git",
Expand Down
69 changes: 39 additions & 30 deletions aa-sdk/core/src/account/smartContractAccount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,11 @@ export type ToSmartContractAccountParams<
getDummySignature: () => Hex | Promise<Hex>;
encodeExecute: (tx: AccountOp) => Promise<Hex>;
encodeBatchExecute?: (txs: AccountOp[]) => Promise<Hex>;
getNonce?: (nonceKey?: bigint) => Promise<bigint>;
// if not provided, will default to just using signMessage over the Hex
signUserOperationHash?: (uoHash: Hex) => Promise<Hex>;
encodeUpgradeToAndCall?: (params: UpgradeToAndCallParams) => Promise<Hex>;
getImplementationAddress?: () => Promise<NullAddress | Address>;
} & Omit<CustomSource, "signTransaction" | "address">;
// [!endregion ToSmartContractAccountParams]

Expand Down Expand Up @@ -260,6 +262,7 @@ export async function toSmartContractAccount<
source,
accountAddress,
getAccountInitCode,
getNonce,
signMessage,
signTypedData,
encodeBatchExecute,
Expand Down Expand Up @@ -339,11 +342,13 @@ export async function toSmartContractAccount(
getAccountInitCode,
signMessage,
signTypedData,
encodeBatchExecute,
encodeExecute,
encodeBatchExecute,
getNonce,
getDummySignature,
signUserOperationHash,
encodeUpgradeToAndCall,
getImplementationAddress,
} = params;

const client = createBundlerClient({
Expand Down Expand Up @@ -410,16 +415,18 @@ export async function toSmartContractAccount(
return initCode === "0x";
};

const getNonce = async (nonceKey = 0n): Promise<bigint> => {
if (!(await isAccountDeployed())) {
return 0n;
}

return entryPointContract.read.getNonce([
accountAddress_,
nonceKey,
]) as Promise<bigint>;
};
const getNonce_ =
getNonce ??
(async (nonceKey = 0n): Promise<bigint> => {
if (!(await isAccountDeployed())) {
return 0n;
}

return entryPointContract.read.getNonce([
accountAddress_,
nonceKey,
]) as Promise<bigint>;
});

const account = toAccount({
address: accountAddress_,
Expand Down Expand Up @@ -468,25 +475,27 @@ export async function toSmartContractAccount(
return create6492Signature(isDeployed, signature);
};

const getImplementationAddress = async (): Promise<NullAddress | Address> => {
const storage = await client.getStorageAt({
address: account.address,
// This is the default slot for the implementation address for Proxies
slot: "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
const getImplementationAddress_ =
getImplementationAddress ??
(async () => {
const storage = await client.getStorageAt({
address: account.address,
// This is the default slot for the implementation address for Proxies
slot: "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
});

if (storage == null) {
throw new FailedToGetStorageSlotError(
"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
"Proxy Implementation Address"
);
}

// The storage slot contains a full bytes32, but we want only the last 20 bytes.
// So, slice off the leading `0x` and the first 12 bytes (24 characters), leaving the last 20 bytes, then prefix with `0x`.
return `0x${storage.slice(26)}`;
});

if (storage == null) {
throw new FailedToGetStorageSlotError(
"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
"Proxy Implementation Address"
);
}

// The storage slot contains a full bytes32, but we want only the last 20 bytes.
// So, slice off the leading `0x` and the first 12 bytes (24 characters), leaving the last 20 bytes, then prefix with `0x`.
return `0x${storage.slice(26)}`;
};

if (entryPoint.version !== "0.6.0" && entryPoint.version !== "0.7.0") {
throw new InvalidEntryPointError(chain, entryPoint.version);
}
Expand All @@ -510,9 +519,9 @@ export async function toSmartContractAccount(
encodeUpgradeToAndCall: encodeUpgradeToAndCall_,
getEntryPoint: () => entryPoint,
isAccountDeployed,
getAccountNonce: getNonce,
getAccountNonce: getNonce_,
signMessageWith6492,
signTypedDataWith6492,
getImplementationAddress,
getImplementationAddress: getImplementationAddress_,
};
}
5 changes: 4 additions & 1 deletion aa-sdk/core/src/client/decorators/bundlerClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ export type BundlerActions = {
estimateUserOperationGas<
TEntryPointVersion extends EntryPointVersion = EntryPointVersion
>(
request: UserOperationRequest<TEntryPointVersion>,
request: Extract<
UserOperationRequest<TEntryPointVersion>,
{ authorizationContract?: Address }
>,
entryPoint: Address,
stateOverride?: StateOverride
): Promise<UserOperationEstimateGasResponse<TEntryPointVersion>>;
Expand Down
2 changes: 2 additions & 0 deletions aa-sdk/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ export {
} from "./errors/useroperation.js";
export { LogLevel, Logger } from "./logger.js";
export { middlewareActions } from "./middleware/actions.js";
export { default7702UserOpSigner } from "./middleware/defaults/7702signer.js";
export { default7702GasEstimator } from "./middleware/defaults/7702gasEstimator.js";
export { defaultFeeEstimator } from "./middleware/defaults/feeEstimator.js";
export { defaultGasEstimator } from "./middleware/defaults/gasEstimator.js";
export { defaultPaymasterAndData } from "./middleware/defaults/paymasterAndData.js";
Expand Down
44 changes: 44 additions & 0 deletions aa-sdk/core/src/middleware/defaults/7702gasEstimator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { AccountNotFoundError } from "../../errors/account.js";
import type { UserOperationStruct } from "../../types.js";
import type { ClientMiddlewareFn } from "../types";
import { defaultGasEstimator } from "./gasEstimator.js";

/**
* A middleware function to estimate the gas usage of a user operation with an optional custom gas estimator.
* This function is only compatible with accounts using EntryPoint v0.7.0.
*
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should add an @example block here as well and it should look like:

@example
```ts twoslash
....
```

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the twoslash piece will ensure that the code is valid when the docs site is built AND add the on hover interaction to the docs

* @param {ClientMiddlewareFn} [gasEstimator] An optional custom gas estimator function
* @returns {Function} A function that takes user operation structure and parameters, estimates gas usage, and returns the estimated user operation
*/
export const default7702GasEstimator: (
gasEstimator?: ClientMiddlewareFn
) => ClientMiddlewareFn =
(gasEstimator?: ClientMiddlewareFn) => async (struct, params) => {
const gasEstimator_ = gasEstimator ?? defaultGasEstimator(params.client);

const account = params.account ?? params.client.account;
if (!account) {
throw new AccountNotFoundError();
}

const entryPoint = account.getEntryPoint();
if (entryPoint.version !== "0.7.0") {
throw new Error(
"This middleware is only compatible with EntryPoint v0.7.0"
);
}

// todo: this is currently overloading the meaning of the getImplementationAddress method, replace with a dedicated method or clarify intention in docs
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

discussed offline, but I think it's a good idea to allow passing an optional override to toSmartContractAccount for this

That methods intention is meant to return the address at which the logic for the SCA lives and I think that holds here:

  • proxies point to a different address than the SCA address
  • no proxy accounts should probably return the address of the SCA itself?
  • 7702 returns the address containing the logic we're delegating to for the EOA

const implementationAddress = await account.getImplementationAddress();

// todo: do we need to omit this from estimation if the account is already 7702 delegated? Not omitting for now.

(struct as UserOperationStruct<"0.7.0">).authorizationContract =
implementationAddress;

const estimatedUO = await gasEstimator_(struct, params);

estimatedUO.authorizationContract = undefined; // Strip out authorizationContract after estimation.

return estimatedUO;
};
82 changes: 82 additions & 0 deletions aa-sdk/core/src/middleware/defaults/7702signer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { toHex } from "viem";
import { isSmartAccountWithSigner } from "../../account/smartContractAccount.js";
import { AccountNotFoundError } from "../../errors/account.js";
import { ChainNotFoundError } from "../../errors/client.js";
import type { ClientMiddlewareFn } from "../types";
import { defaultUserOpSigner } from "./userOpSigner.js";

/**
* Provides a default middleware function for signing user operations with a client account when using ERC-7702 to upgrade local accounts to smart accounts.
* If the SmartAccount doesn't support `signAuthorization`, then this just runs the provided `signUserOperation` middleware
*
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment here, needs an @example tag which has twoslash enabled

* @param {ClientMiddlewareFn} [userOpSigner] Optional user operation signer function
* @returns {Function} An async function that processes the user operation and returns the authorized operation with an authorization tuple if necessary
*/
export const default7702UserOpSigner: (
userOpSigner?: ClientMiddlewareFn
) => ClientMiddlewareFn =
(userOpSigner?: ClientMiddlewareFn) => async (struct, params) => {
const userOpSigner_ = userOpSigner ?? defaultUserOpSigner;

const uo = await userOpSigner_(struct, params);

const account = params.account ?? params.client.account;
const { client } = params;

if (!account || !isSmartAccountWithSigner(account)) {
throw new AccountNotFoundError();
}

const signer = account.getSigner();

if (!signer.signAuthorization) {
return uo;
}

if (!client.chain) {
throw new ChainNotFoundError();
}

const code = (await client.getCode({ address: account.address })) ?? "0x";
// TODO: this isn't the cleanest because now the account implementation HAS to know that it needs to return an impl address
// even if the account is not deployed
Comment on lines +41 to +42
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there anyway to make that clearer? If we add the optional parameter mentioned above, then we could update the docs on toSmartContractAccount to highlight what that address is for?

We could also update the jsdoc for this middleware as well to make it clear that the account MUST return something when calling getImplementationAddress

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is an issue on the semantic meaning of "getImplementationAddress" - there's ambiguity of what the function does:

  • does it get the current implementation address from the account's proxy? <-- what it is default-initialized to
  • does it get the intended implementation address for a proxy?
  • does it get the intended delegation address for 7702? <-- what this middleware expects user to overwrite it to

We could try to do something with the type system to attempt to assert that this middleware is only added to a client for which the account provided has the definition overwritten. But that sounds super messy, so I'm not particularly inclined to do it.

I think the real fix for this is to:

  • define the getImplementationAddress to mean getting the intended implementation address, agnostic to SCA / 7702-upgraded EOA
  • Move the "current proxy implementation getter" to a utility function / utility action on a public client


const implAddress = await account.getImplementationAddress();

const expectedCode = "0xef0100" + implAddress.slice(2);

if (code.toLowerCase() === expectedCode.toLowerCase()) {
return uo;
}

const accountNonce = await params.client.getTransactionCount({
address: account.address,
});

const {
r,
s,
v,
yParity = v ? v - 27n : undefined,
} = await signer.signAuthorization({
chainId: client.chain.id,
contractAddress: implAddress,
nonce: accountNonce,
});

if (yParity === undefined) {
throw new Error("Invalid signature: missing yParity or v");
}
Comment on lines +67 to +69
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like the responsibility of the signer probably no?


return {
...uo,
authorizationTuple: {
chainId: client.chain.id,
nonce: toHex(accountNonce), // deepHexlify doesn't encode number(0) correctly, it returns "0x"
address: implAddress,
r,
s,
yParity: toHex(yParity),
},
};
};
28 changes: 28 additions & 0 deletions aa-sdk/core/src/signer/local-account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
privateKeyToAccount,
} from "viem/accounts";
import type { SmartAccountSigner } from "./types.js";
import type { Authorization } from "viem/experimental";

/**
* Represents a local account signer and provides methods to sign messages and transactions, as well as static methods to create the signer from mnemonic or private key.
Expand Down Expand Up @@ -95,6 +96,33 @@ export class LocalAccountSigner<
return this.inner.signTypedData(params);
};

/**
* Signs an unsigned authorization using the provided private key account.
*
* @example
* ```ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can we add twoslash after the ts here?

At some point we'll want to do this for ALL examples retroactively as well, but that will cause too many build breaks I fear

* import { LocalAccountSigner } from "@aa-sdk/core";
* import { generatePrivateKey } from "viem";
*
* const signer = LocalAccountSigner.mnemonicToAccountSigner(generatePrivateKey());
* const signedAuthorization = await signer.signAuthorization({
* contractAddress: "0x1234123412341234123412341234123412341234",
* chainId: 1,
* nonce: 3,
* });
* ```
*
* @param {Authorization<number, false>} unsignedAuthorization - The unsigned authorization to be signed.
* @returns {Promise<Authorization<number, true>>} A promise that resolves to the signed authorization.
*/

signAuthorization(
this: LocalAccountSigner<PrivateKeyAccount>,
unsignedAuthorization: Authorization<number, false>
): Promise<Authorization<number, true>> {
return this.inner.experimental_signAuthorization(unsignedAuthorization);
}

/**
* Returns the address of the inner object in a specific hexadecimal format.
*
Expand Down
5 changes: 5 additions & 0 deletions aa-sdk/core/src/signer/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
TypedData,
TypedDataDefinition,
} from "viem";
import type { Authorization } from "viem/experimental";

// [!region SmartAccountAuthenticator]
/**
Expand Down Expand Up @@ -42,5 +43,9 @@ export interface SmartAccountSigner<Inner = any> {
>(
params: TypedDataDefinition<TTypedData, TPrimaryType>
) => Promise<Hex>;

signAuthorization?: (
unsignedAuthorization: Authorization<number, false>
) => Promise<Authorization<number, true>>;
}
// [!endregion SmartAccountSigner]
15 changes: 11 additions & 4 deletions aa-sdk/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type StateOverride,
type TransactionReceipt,
} from "viem";
import type { Authorization } from "viem/experimental";
import type { z } from "zod";
import type {
UserOperationFeeOptionsFieldSchema,
Expand Down Expand Up @@ -201,15 +202,20 @@ export interface UserOperationRequest_v7 {
}
// [!endregion UserOperationRequest_v7]

export type Eip7702ExtendedFields =
| { authorizationTuple?: Authorization; authorizationContract?: never }
| { authorizationTuple?: never; authorizationContract?: Address };

// [!region UserOperationRequest]
// Reference: https://eips.ethereum.org/EIPS/eip-4337#definitions
export type UserOperationRequest<
TEntryPointVersion extends EntryPointVersion = EntryPointVersion
> = TEntryPointVersion extends "0.6.0"
> = (TEntryPointVersion extends "0.6.0"
? UserOperationRequest_v6
: TEntryPointVersion extends "0.7.0"
? UserOperationRequest_v7
: never;
: never) &
Eip7702ExtendedFields;

// [!endregion UserOperationRequest]

Expand Down Expand Up @@ -347,9 +353,10 @@ export interface UserOperationStruct_v7 {
// [!region UserOperationStruct]
export type UserOperationStruct<
TEntryPointVersion extends EntryPointVersion = EntryPointVersion
> = TEntryPointVersion extends "0.6.0"
> = (TEntryPointVersion extends "0.6.0"
? UserOperationStruct_v6
: TEntryPointVersion extends "0.7.0"
? UserOperationStruct_v7
: never;
: never) &
Eip7702ExtendedFields;
// [!endregion UserOperationStruct]
Loading