Skip to content

[SmartWallet] Expose new estimation functions for smart wallet transactions #1856

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

Merged
merged 3 commits into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
17 changes: 17 additions & 0 deletions .changeset/cuddly-kings-listen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"@thirdweb-dev/wallets": patch
---

Expose function to estimate SmartWallet transactions, handling pre and post deployment state

```ts
const cost = smartWallet.estimate(preparedTx);
const costBatch = smartWallet.estimateBatch(preparedTxs);
```

Also works with raw transactions

```ts
const cost = smartWallet.estimateRaw(rawTx);
const costBatch = smartWallet.estimateBatchRaw(rawTxs);
```
201 changes: 172 additions & 29 deletions packages/wallets/src/evm/connectors/smart-wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { ERC4337EthersSigner } from "./lib/erc4337-signer";
import { BigNumber, ethers, providers, utils } from "ethers";
import {
getChainProvider,
getGasPrice,
SignerPermissionsInput,
SignerWithPermissions,
SmartContract,
Expand All @@ -25,6 +26,8 @@ import {
} from "@thirdweb-dev/sdk";
import { AccountAPI } from "./lib/account";
import { AddressZero } from "@account-abstraction/utils";
import { TransactionDetailsForUserOp } from "./lib/transaction-details";
import { BatchData } from "./lib/base-api";

export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
protected config: SmartWalletConfig;
Expand Down Expand Up @@ -165,6 +168,8 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
return restrictions.approvedCallTargets.includes(transaction.getTarget());
}

/// PREPARED TRANSACTIONS

/**
* Send a single transaction without waiting for confirmations
* @param transactions
Expand Down Expand Up @@ -199,21 +204,14 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
throw new Error("Personal wallet not connected");
}
const signer = await this.getSigner();
const targets = transactions.map((tx) => tx.getTarget());
const data = transactions.map((tx) => tx.encode());
const values = await Promise.all(transactions.map((tx) => tx.getValue()));
const callData = await this.accountApi.encodeExecuteBatch(
targets,
values,
data,
);
const { tx, batchData } = await this.prepareBatchTx(transactions);
return await signer.sendTransaction(
{
to: await signer.getAddress(),
data: callData,
data: tx.encode(),
value: 0,
},
true, // batched tx flag
batchData,
);
}

Expand All @@ -232,6 +230,8 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
};
}

/// RAW TRANSACTIONS

async sendRaw(
transaction: utils.Deferrable<providers.TransactionRequest>,
): Promise<providers.TransactionResponse> {
Expand Down Expand Up @@ -259,26 +259,14 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
throw new Error("Personal wallet not connected");
}
const signer = await this.getSigner();
const resolvedTxs = await Promise.all(
transactions.map((transaction) =>
ethers.utils.resolveProperties(transaction),
),
);
const targets = resolvedTxs.map((tx) => tx.to || AddressZero);
const data = resolvedTxs.map((tx) => tx.data || "0x");
const values = resolvedTxs.map((tx) => tx.value || BigNumber.from(0));
const callData = await this.accountApi.encodeExecuteBatch(
targets,
values,
data,
);
const batch = await this.prepareBatchRaw(transactions);
return signer.sendTransaction(
{
to: await signer.getAddress(),
data: callData,
data: batch.tx.encode(),
value: 0,
},
true, // batched tx flag
batch.batchData, // batched tx flag
);
}

Expand All @@ -292,6 +280,67 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
};
}

/// ESTIMATION

async estimate(transaction: Transaction) {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
return this.estimateTx({
target: transaction.getTarget(),
data: transaction.encode(),
value: await transaction.getValue(),
});
}

async estimateRaw(
transaction: utils.Deferrable<providers.TransactionRequest>,
) {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
const tx = await ethers.utils.resolveProperties(transaction);
return this.estimateTx({
target: tx.to || AddressZero,
data: tx.data?.toString() || "",
value: tx.value || BigNumber.from(0),
});
}

async estimateBatch(transactions: Transaction<any>[]) {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
const { tx, batchData } = await this.prepareBatchTx(transactions);
return this.estimateTx(
{
target: tx.getTarget(),
data: tx.encode(),
value: await tx.getValue(),
},
batchData,
);
}

async estimateBatchRaw(
transactions: utils.Deferrable<providers.TransactionRequest>[],
) {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
const { tx, batchData } = await this.prepareBatchRaw(transactions);
return this.estimateTx(
{
target: tx.getTarget(),
data: tx.encode(),
value: await tx.getValue(),
},
batchData,
);
}

//// DEPLOYMENT

/**
* Manually deploy the smart wallet contract. If already deployed this will throw an error.
* Note that this is not necessary as the smart wallet will be deployed automatically on the first transaction the user makes.
Expand All @@ -301,16 +350,16 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
if (await this.accountApi.isAcountDeployed()) {
throw new Error("Smart wallet already deployed");
}
const signer = await this.getSigner();
const tx = await signer.sendTransaction(
{
to: await signer.getAddress(),
data: "0x",
},
true, // batched tx flag to avoid hitting the Router fallback method
{
targets: [],
data: [],
}, // batched tx flag to avoid hitting the Router fallback method
);
const receipt = await tx.wait();
return { receipt };
Expand All @@ -334,6 +383,8 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
}
}

//// PERMISSIONS

async grantPermissions(
target: string,
permissions: SignerPermissionsInput,
Expand Down Expand Up @@ -472,4 +523,96 @@ export class SmartWalletConnector extends Connector<SmartWalletConnectionArgs> {
},
};
}

/// PRIVATE METHODS

private async estimateTx(
tx: TransactionDetailsForUserOp,
batchData?: BatchData,
) {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
let deployGasLimit = BigNumber.from(0);
const [provider, isDeployed] = await Promise.all([
this.getProvider(),
this.isDeployed(),
]);
if (!isDeployed) {
deployGasLimit = await this.estimateDeploymentGasLimit();
}
const [{ callGasLimit: transactionGasLimit }, gasPrice] = await Promise.all(
[
this.accountApi.encodeUserOpCallDataAndGasLimit(tx, batchData),
getGasPrice(provider),
],
);
const transactionCost = transactionGasLimit.mul(gasPrice);
const deployCost = deployGasLimit.mul(gasPrice);
const totalCost = deployCost.add(transactionCost);

return {
ether: utils.formatEther(totalCost),
wei: totalCost,
details: {
deployGasLimit,
transactionGasLimit,
gasPrice,
transactionCost,
deployCost,
totalCost,
},
};
}

private async estimateDeploymentGasLimit() {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
const initCode = await this.accountApi.getInitCode();
const [initGas, verificationGasLimit] = await Promise.all([
this.accountApi.estimateCreationGas(initCode),
this.accountApi.getVerificationGasLimit(),
]);
return BigNumber.from(verificationGasLimit).add(initGas);
}

private async prepareBatchRaw(
transactions: ethers.utils.Deferrable<ethers.providers.TransactionRequest>[],
) {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
const resolvedTxs = await Promise.all(
transactions.map((transaction) =>
ethers.utils.resolveProperties(transaction),
),
);
const targets = resolvedTxs.map((tx) => tx.to || AddressZero);
const data = resolvedTxs.map((tx) => tx.data || "0x");
const values = resolvedTxs.map((tx) => tx.value || BigNumber.from(0));
return {
tx: await this.accountApi.prepareExecuteBatch(targets, values, data),
batchData: {
targets,
data,
},
};
}

private async prepareBatchTx(transactions: Transaction<any>[]) {
if (!this.accountApi) {
throw new Error("Personal wallet not connected");
}
const targets = transactions.map((tx) => tx.getTarget());
const data = transactions.map((tx) => tx.encode());
const values = await Promise.all(transactions.map((tx) => tx.getValue()));
return {
tx: await this.accountApi.prepareExecuteBatch(targets, values, data),
batchData: {
targets,
data,
},
};
}
}
25 changes: 12 additions & 13 deletions packages/wallets/src/evm/connectors/smart-wallet/lib/account.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { LOCAL_NODE_PKEY, SmartContract, ThirdwebSDK } from "@thirdweb-dev/sdk";
import {
LOCAL_NODE_PKEY,
SmartContract,
ThirdwebSDK,
Transaction,
} from "@thirdweb-dev/sdk";
import { BigNumberish, BigNumber, ethers, utils, BytesLike } from "ethers";
import { AccountApiParams } from "../types";
import { BaseAccountAPI } from "./base-api";
Expand Down Expand Up @@ -103,33 +108,27 @@ export class AccountAPI extends BaseAccountAPI {
return this.params.accountInfo.getNonce(accountContract);
}

async encodeExecute(
async prepareExecute(
target: string,
value: BigNumberish,
data: string,
): Promise<string> {
): Promise<Transaction<any>> {
const accountContract = await this.getAccountContract();
const tx = await this.params.accountInfo.execute(
return this.params.accountInfo.execute(
accountContract,
target,
value,
data,
);
return tx.encode();
}

async encodeExecuteBatch(
async prepareExecuteBatch(
targets: string[],
values: BigNumberish[],
datas: BytesLike[],
): Promise<string> {
): Promise<Transaction<any>> {
const accountContract = await this.getAccountContract();
const tx = accountContract.prepare("executeBatch", [
targets,
values,
datas,
]);
return tx.encode();
return accountContract.prepare("executeBatch", [targets, values, datas]);
}

async signUserOpHash(userOpHash: string): Promise<string> {
Expand Down
Loading