Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
ece50eb
add setup and rules about modules
teryanarmen Feb 10, 2023
2a99238
fix run script
teryanarmen Feb 10, 2023
6142597
use solc7.6 for fv
mmv08 Mar 31, 2023
2ce4faa
Merge branch 'main' of github.com:safe-global/safe-contracts into for…
mmv08 Mar 31, 2023
78fdf78
Mark assembly blocks as memory-safe
mmv08 Apr 6, 2023
c55691a
use solidity 0.8.19 for github action benchmark
mmv08 Apr 6, 2023
4d2284c
Update makefile
mmv08 Apr 11, 2023
2253f7e
fix the harness patch
mmv08 Apr 11, 2023
dc0cbf9
properties doc skeleton
mmv08 Apr 12, 2023
2524f74
properties notes
mmv08 Apr 20, 2023
6b03373
Merge branch 'main' of github.com:safe-global/safe-contracts into fea…
mmv08 Apr 27, 2023
ac6c56b
use 10m optimizer runs
mmv08 Apr 27, 2023
3ae2bde
Write calldata/return data to the memory allocated via the free memor…
mmv08 May 2, 2023
0c98fc0
memory-safe simulateAndRevert
mmv08 May 2, 2023
67d05a6
Merge branch 'main' of github.com:safe-global/safe-contracts into for…
mmv08 May 3, 2023
7a77545
Update CLA github action to v2.3.0
Uxio0 May 8, 2023
e8e9241
add certora workflow
mmv08 May 9, 2023
ed32c96
Fix changelog mention of createChainSpecificProxyWithNonce
frangio May 11, 2023
4b9c46f
Merge pull request #561 from frangio/changelog-fix
mmv08 May 11, 2023
1c29d23
fix script path
mmv08 May 10, 2023
c8932d4
use cvl2
mmv08 May 15, 2023
ad9b319
Merge pull request #560 from safe-global/formal-verification
mmv08 May 16, 2023
11e3459
Merge branch 'main' of github.com:safe-global/safe-contracts into fea…
mmv08 May 16, 2023
f8bd215
Remove gasleft in setupModules, add erc4337 compatibility test
mmv08 May 19, 2023
f77dfce
Fix typechecking in test files (#573)
mmv08 May 30, 2023
9cbdaa6
verify that guard can only be updated through setGuard
mmv08 May 17, 2023
1b25deb
Verify functions that may change the fallback handler address (#566)
mmv08 May 31, 2023
f37e0ed
Add an invariant for singleton address (#565)
mmv08 May 31, 2023
80ced58
Add an optimistic assumption about DELEGATECALL, update nonce monoton…
mmv08 May 31, 2023
13a5d89
Pump version to 1.4.1 (#579)
mmv08 May 31, 2023
36a07fe
Formal verification: native token balance updates (#582)
mmv08 Jun 15, 2023
1ed486b
Fix addresses for 1.4.1 in changelog (#590)
rmeissner Jun 15, 2023
7e46388
Fix certora CI action
mmv08 Jun 15, 2023
eec5ebc
Merge pull request #591 from safe-global/fix/certora-ci
mmv08 Jun 16, 2023
bf943f8
Formal verification: No message can be signed through the core contra…
mmv08 Jun 16, 2023
930478f
Merge branch 'main' of github.com:safe-global/safe-contracts into fea…
Jun 22, 2023
1a0d70c
fix munged patch
Jun 22, 2023
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
Prev Previous commit
Next Next commit
Remove gasleft in setupModules, add erc4337 compatibility test
  • Loading branch information
mmv08 committed May 26, 2023
commit f8bd2159b64392d5b594f4e056be258ade2fefab
5 changes: 5 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,8 @@ INFURA_KEY=""
# Used for custom network
NODE_URL=""
ETHERSCAN_API_KEY=""
# (Optional) Used to run ERC-4337 compatibility test. MNEMONIC is also required.
ERC4337_TEST_BUNDLER_URL=
ERC4337_TEST_NODE_URL=
ERC4337_TEST_SINGLETON_ADDRESS=
ERC4337_TEST_SAFE_FACTORY_ADDRESS=
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,29 @@ Usage
yarn
```

### Run all tests:
### Testing

To run the tests:

```bash
yarn build
yarn test
```

Optionally, if you want to run the ERC-4337 compatibility test, it uses a live bundler and node, so it contains some pre-requisites:

1. Define the environment variables:

```
ERC4337_TEST_BUNDLER_URL=
ERC4337_TEST_NODE_URL=
ERC4337_TEST_SINGLETON_ADDRESS=
ERC4337_TEST_SAFE_FACTORY_ADDRESS=
MNEMONIC=
```

2. Pre-fund the executor account derived from the mnemonic with some Native Token to cover the deployment of an ERC4337 module and the pre-fund of the Safe for the test operation.

### Deployments

A collection of the different Safe contract deployments and their addresses can be found in the [Safe deployments](https://github.com/safe-global/safe-deployments) repository.
Expand Down
2 changes: 1 addition & 1 deletion contracts/base/ModuleManager.sol
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ abstract contract ModuleManager is SelfAuthorized, Executor {
if (to != address(0)) {
require(isContract(to), "GS002");
// Setup has to complete successfully or transaction fails.
require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
require(execute(to, 0, data, Enum.Operation.DelegateCall, type(uint256).max), "GS000");
}
}

Expand Down
65 changes: 65 additions & 0 deletions contracts/test/4337/Test4337ModuleAndHandler.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
pragma abicoder v2;

import "../../libraries/SafeStorage.sol";

struct UserOperation {
address sender;
uint256 nonce;
bytes initCode;
bytes callData;
uint256 callGasLimit;
uint256 verificationGasLimit;
uint256 preVerificationGas;
uint256 maxFeePerGas;
uint256 maxPriorityFeePerGas;
bytes paymasterAndData;
bytes signature;
}

interface ISafe {
function execTransactionFromModule(address to, uint256 value, bytes memory data, uint8 operation) external returns (bool success);
}

/// @dev A Dummy 4337 Module/Handler for testing purposes
/// ⚠️ ⚠️ ⚠️ DO NOT USE IN PRODUCTION ⚠️ ⚠️ ⚠️
/// The module does not perform ANY validation, it just executes validateUserOp and execTransaction
/// to perform the opcode level compliance by the bundler.
contract Test4337ModuleAndHandler is SafeStorage {
address public immutable myAddress;
address public immutable entryPoint;

address internal constant SENTINEL_MODULES = address(0x1);

constructor(address entryPointAddress) {
entryPoint = entryPointAddress;
myAddress = address(this);
}

function validateUserOp(UserOperation calldata userOp, bytes32, uint256 missingAccountFunds) external returns (uint256 validationData) {
address payable safeAddress = payable(userOp.sender);
ISafe senderSafe = ISafe(safeAddress);

if (missingAccountFunds != 0) {
senderSafe.execTransactionFromModule(entryPoint, missingAccountFunds, "", 0);
}

return 0;
}

function execTransaction(address to, uint256 value, bytes calldata data) external payable {
address payable safeAddress = payable(msg.sender);
ISafe safe = ISafe(safeAddress);
require(safe.execTransactionFromModule(to, value, data, 0), "tx failed");
}

function enableMyself() public {
require(myAddress != address(this), "You need to DELEGATECALL, sir");

// Module cannot be added twice.
require(modules[myAddress] == address(0), "GS102");
modules[myAddress] = modules[SENTINEL_MODULES];
modules[SENTINEL_MODULES] = myAddress;
}
}
5 changes: 3 additions & 2 deletions hardhat.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import "@nomiclabs/hardhat-ethers";
import type { HardhatUserConfig, HttpNetworkUserConfig } from "hardhat/types";
import "@nomiclabs/hardhat-etherscan";
import "@nomiclabs/hardhat-waffle";
Expand Down Expand Up @@ -41,7 +42,7 @@ import { BigNumber } from "@ethersproject/bignumber";
import { DeterministicDeploymentInfo } from "hardhat-deploy/dist/types";

const primarySolidityVersion = SOLIDITY_VERSION || "0.7.6";
const soliditySettings = !!SOLIDITY_SETTINGS ? JSON.parse(SOLIDITY_SETTINGS) : undefined;
const soliditySettings = SOLIDITY_SETTINGS ? JSON.parse(SOLIDITY_SETTINGS) : undefined;

const deterministicDeployment = (network: string): DeterministicDeploymentInfo => {
const info = getSingletonFactoryInfo(parseInt(network));
Expand Down Expand Up @@ -132,7 +133,7 @@ const userConfig: HardhatUserConfig = {
},
};
if (NODE_URL) {
userConfig.networks!!.custom = {
userConfig.networks!.custom = {
...sharedNetworkConfig,
url: NODE_URL,
};
Expand Down
133 changes: 133 additions & 0 deletions test/integration/Safe.ERC4337.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import hre from "hardhat";
import { expect } from "chai";
import { AddressZero } from "@ethersproject/constants";
import { hexConcat } from "ethers/lib/utils";
import { getFactoryContract, getSafeSingletonContract } from "../utils/setup";
import { calculateProxyAddress } from "../../src/utils/proxies";

const ERC4337_TEST_ENV_VARIABLES_DEFINED =
typeof process.env.ERC4337_TEST_BUNDLER_URL !== "undefined" &&
typeof process.env.ERC4337_TEST_NODE_URL !== "undefined" &&
typeof process.env.ERC4337_TEST_SAFE_FACTORY_ADDRESS !== "undefined" &&
typeof process.env.ERC4337_TEST_SINGLETON_ADDRESS !== "undefined" &&
typeof process.env.MNEMONIC !== "undefined";

const itif = ERC4337_TEST_ENV_VARIABLES_DEFINED ? it : it.skip;
const SAFE_FACTORY_ADDRESS = process.env.ERC4337_TEST_SAFE_FACTORY_ADDRESS;
const SINGLETON_ADDRESS = process.env.ERC4337_TEST_SINGLETON_ADDRESS;
const BUNDLER_URL = process.env.ERC4337_TEST_BUNDLER_URL;
const NODE_URL = process.env.ERC4337_TEST_NODE_URL;
const MNEMONIC = process.env.MNEMONIC;

type UserOperation = {
sender: string;
nonce: string;
initCode: string;
callData: string;
callGasLimit: string;
verificationGasLimit: string;
preVerificationGas: string;
maxFeePerGas: string;
maxPriorityFeePerGas: string;
paymasterAndData: string;
signature: string;
};

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

describe("Safe.ERC4337", () => {
const setupTests = async () => {
const factory = await getFactoryContract();
const singleton = await getSafeSingletonContract();
const bundlerProvider = new hre.ethers.providers.JsonRpcProvider(BUNDLER_URL);
const provider = new hre.ethers.providers.JsonRpcProvider(NODE_URL);
const userWallet = hre.ethers.Wallet.fromMnemonic(MNEMONIC as string).connect(provider);

const entryPoints = await bundlerProvider.send("eth_supportedEntryPoints", []);
if (entryPoints.length === 0) {
throw new Error("No entry points found");
}

return {
factory: factory.attach(SAFE_FACTORY_ADDRESS).connect(userWallet),
singleton: singleton.attach(SINGLETON_ADDRESS).connect(provider),
bundlerProvider,
provider,
userWallet,
entryPoints,
};
};

/**
* This test verifies the ERC4337 based on gas estimation for a user operation
* The user operation deploys a Safe with the ERC4337 module and a handler
* and executes a transaction, thus verifying two things:
* 1. Deployment of the Safe with the ERC4337 module and handler is possible
* 2. Executing a transaction is possible
*/
itif("should pass the ERC4337 validation", async () => {
const { singleton, factory, provider, bundlerProvider, userWallet, entryPoints } = await setupTests();
const ENTRYPOINT_ADDRESS = entryPoints[0];

const erc4337ModuleAndHandlerFactory = (await hre.ethers.getContractFactory("Test4337ModuleAndHandler")).connect(userWallet);
const erc4337ModuleAndHandler = await erc4337ModuleAndHandlerFactory.deploy(ENTRYPOINT_ADDRESS);
// The bundler uses a different node, so we need to allow it sometime to sync
await sleep(10000);

const feeData = await provider.getFeeData();
const maxFeePerGas = feeData.maxFeePerGas.toHexString();

const maxPriorityFeePerGas = feeData.maxPriorityFeePerGas.toHexString();

const moduleInitializer = erc4337ModuleAndHandler.interface.encodeFunctionData("enableMyself", []);
const encodedInitializer = singleton.interface.encodeFunctionData("setup", [
[userWallet.address],
1,
erc4337ModuleAndHandler.address,
moduleInitializer,
erc4337ModuleAndHandler.address,
AddressZero,
0,
AddressZero,
]);
const deployedAddress = await calculateProxyAddress(factory, singleton.address, encodedInitializer, 73);

// The initCode contains 20 bytes of the factory address and the rest is the calldata to be forwarded
const initCode = hexConcat([
factory.address,
factory.interface.encodeFunctionData("createProxyWithNonce", [singleton.address, encodedInitializer, 73]),
]);
const userOpCallData = erc4337ModuleAndHandler.interface.encodeFunctionData("execTransaction", [userWallet.address, 0, 0]);

// Native tokens for the pre-fund 💸
await userWallet.sendTransaction({ to: deployedAddress, value: hre.ethers.utils.parseEther("0.001") });
// The bundler uses a different node, so we need to allow it sometime to sync
await sleep(10000);

const userOperation: UserOperation = {
sender: deployedAddress,
nonce: "0x0",
initCode,
callData: userOpCallData,
callGasLimit: "0x7A120",
verificationGasLimit: "0x7A120",
preVerificationGas: "0x186A0",
maxFeePerGas,
maxPriorityFeePerGas,
paymasterAndData: "0x",
signature: "0x",
};

const DEBUG_MESSAGE = `
Using entry point: ${ENTRYPOINT_ADDRESS}
Deployed Safe address: ${deployedAddress}
Module/Handler address: ${erc4337ModuleAndHandler.address}
User operation:
${JSON.stringify(userOperation, null, 2)}
`;
console.log(DEBUG_MESSAGE);

const estimatedGas = await bundlerProvider.send("eth_estimateUserOperationGas", [userOperation, ENTRYPOINT_ADDRESS]);
expect(estimatedGas).to.not.be.undefined;
});
});
12 changes: 12 additions & 0 deletions test/utils/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,18 @@ export const getSafeSingleton = async () => {
return Safe.attach(SafeDeployment.address);
};

export const getSafeSingletonContract = async () => {
const safeSingleton = await hre.ethers.getContractFactory(safeContractUnderTest());

return safeSingleton;
};

export const getFactoryContract = async () => {
const factory = await hre.ethers.getContractFactory("SafeProxyFactory");

return factory;
};

export const getFactory = async () => {
const FactoryDeployment = await deployments.get("SafeProxyFactory");
const Factory = await hre.ethers.getContractFactory("SafeProxyFactory");
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
"resolveJsonModule": true
},
"exclude": ["dist", "node_modules"],
"include": ["./src/index.ts", "./types"]
"include": ["./src/index.ts", "./types"],
"files": ["./hardhat.config.ts"]
}