@alchemy/aa-core
Version:
viem based SDK that enables interactions with ERC-4337 Smart Accounts. ABIs are based off the definitions generated in @account-abstraction/contracts
96 lines • 4.43 kB
JavaScript
import { custom, } from "viem";
import { z } from "zod";
import { AccountNotFoundError } from "../errors/account.js";
import { ChainNotFoundError } from "../errors/client.js";
import { middlewareActions } from "../middleware/actions.js";
import { createBundlerClient } from "./bundlerClient.js";
import {} from "./decorators/bundlerClient.js";
import { smartAccountClientActions, } from "./decorators/smartAccountClient.js";
import { SmartAccountClientOptsSchema } from "./schema.js";
export function createSmartAccountClient(config) {
const { key = "account", name = "account provider", transport, type = "SmartAccountClient", ...params } = config;
const client = createBundlerClient({
...params,
key,
name,
type: "SmartAccountClient",
transport: (opts) => {
const rpcTransport = transport(opts);
return custom({
async request({ method, params }) {
switch (method) {
case "eth_accounts": {
if (!client.account) {
throw new AccountNotFoundError();
}
return [client.account.address];
}
case "eth_sendTransaction":
if (!client.account) {
throw new AccountNotFoundError();
}
if (!client.chain) {
throw new ChainNotFoundError();
}
const [tx] = params;
return client.sendTransaction({
...tx,
account: client.account,
chain: client.chain,
});
case "eth_sign":
if (!client.account) {
throw new AccountNotFoundError();
}
const [address, data] = params;
if (address !== client.account.address) {
throw new Error("cannot sign for address that is not the current account");
}
return client.signMessage(data);
case "personal_sign": {
if (!client.account) {
throw new AccountNotFoundError();
}
const [data, address] = params;
if (address !== client.account.address) {
throw new Error("cannot sign for address that is not the current account");
}
return client.signMessage(data);
}
case "eth_signTypedData_v4": {
if (!client.account) {
throw new AccountNotFoundError();
}
const [address, dataParams] = params;
if (address !== client.account.address) {
throw new Error("cannot sign for address that is not the current account");
}
return client.signTypedData(dataParams);
}
case "eth_chainId":
if (!opts.chain) {
throw new ChainNotFoundError();
}
return opts.chain.id;
default:
return rpcTransport.request({ method, params });
}
},
})(opts);
},
})
.extend(() => ({
...SmartAccountClientOptsSchema.parse(config.opts ?? {}),
}))
.extend(middlewareActions(config))
.extend(smartAccountClientActions);
return { ...client, type };
}
export function createSmartAccountClientFromExisting(config) {
return createSmartAccountClient({
...config,
chain: config.client.chain,
transport: custom(config.client),
});
}
//# sourceMappingURL=smartAccountClient.js.map