Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/simulatecall-bytecode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': patch
---

`SimulateCall`: Changed the deployed call-simulator bytecode, which also changes its deployed address.
2 changes: 2 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ jobs:

slither:
runs-on: ubuntu-latest
env:
FOUNDRY_PROFILE: slither
steps:
- uses: actions/checkout@v7
- name: Set up environment
Expand Down
58 changes: 7 additions & 51 deletions contracts/utils/SimulateCall.sol
Original file line number Diff line number Diff line change
Expand Up @@ -37,60 +37,16 @@ library SimulateCall {
* capturing the return data.
*/
function getSimulator() internal returns (address instance) {
// [Simulator details]
// deployment prefix: 60315f8160095f39f3
// deployed bytecode: 60333611600a575f5ffd5b6034360360345f375f5f603436035f6014355f3560601c5af13d5f5f3e5f3d91602f57f35bfd
//
// offset | bytecode | opcode | stack
// -------|-------------|----------------|--------
// 0x0000 | 6033 | push1 0x33 | 0x33
// 0x0002 | 36 | calldatasize | cds 0x33
// 0x0003 | 11 | gt | (cds>0x33)
// 0x0004 | 600a | push1 0x0a | 0x0a (cds>0x33)
// 0x0006 | 57 | jumpi |
// 0x0007 | 5f | push0 | 0
// 0x0008 | 5f | push0 | 0 0
// 0x0009 | fd | revert |
// 0x000a | 5b | jumpdest |
// 0x000b | 6034 | push1 0x34 | 0x34
// 0x000d | 36 | calldatasize | cds 0x34
// 0x000e | 03 | sub | (cds-0x34)
// 0x000f | 6034 | push1 0x34 | 0x34 (cds-0x34)
// 0x0011 | 5f | push0 | 0 0x34 (cds-0x34)
// 0x0012 | 37 | calldatacopy |
// 0x0013 | 5f | push0 | 0
// 0x0014 | 5f | push0 | 0 0
// 0x0015 | 6034 | push1 0x34 | 0x34 0 0
// 0x0017 | 36 | calldatasize | cds 0x34 0 0
// 0x0018 | 03 | sub | (cds-0x34) 0 0
// 0x0019 | 5f | push0 | 0 (cds-0x34) 0 0
// 0x001a | 6014 | push1 0x14 | 0x14 0 (cds-0x34) 0 0
// 0x001c | 35 | calldataload | cd[0x14] 0 (cds-0x34) 0 0
// 0x001d | 5f | push0 | 0 cd[0x14] 0 (cds-0x34) 0 0
// 0x001e | 35 | calldataload | cd[0] cd[0x14] 0 (cds-0x34) 0 0
// 0x001f | 6060 | push1 0x60 | 0x60 cd[0] cd[0x14] 0 (cds-0x34) 0 0
// 0x0021 | 1c | shr | target cd[0x14] 0 (cds-0x34) 0 0
// 0x0022 | 5a | gas | gas target cd[0x14] 0 (cds-0x34) 0 0
// 0x0023 | f1 | call | suc
// 0x0024 | 3d | returndatasize | rds suc
// 0x0025 | 5f | push0 | 0 rds suc
// 0x0026 | 5f | push0 | 0 0 rds suc
// 0x0027 | 3e | returndatacopy | suc
// 0x0028 | 5f | push0 | 0 suc
// 0x0029 | 3d | returndatasize | rds 0 suc
// 0x002a | 91 | swap2 | suc 0 rds
// 0x002b | 602f | push1 0x2f | 0x2f suc 0 rds
// 0x002d | 57 | jumpi | 0 rds
// 0x002e | f3 | return |
// 0x002f | 5b | jumpdest | 0 rds
// 0x0030 | fd | revert |
// Bytecode compiled from contracts/utils/SimulateCall.yul.
// deployment prefix: 0x602580600a5f395ff3fe
// deployed bytecode: 0x5f803660331901806034833781601435813560601c5af13d5f803e6021573d5ff35b3d5ffd
assembly ("memory-safe") {
let fmp := mload(0x40)

// build initcode at FMP
mstore(add(fmp, 0x20), 0x5f375f5f603436035f6014355f3560601c5af13d5f5f3e5f3d91602f57f35bfd)
mstore(fmp, 0x60315f8160095f39f360333611600a575f5ffd5b603436036034)
let initcodehash := keccak256(add(fmp, 0x06), 0x3a)
mstore(add(fmp, 0x20), 0x1901806034833781601435813560601c5af13d5f803e6021573d5ff35b3d5ffd)
mstore(fmp, 0x602580600a5f395ff3fe5f80366033)
let initcodehash := keccak256(add(fmp, 0x11), 0x2f)

// compute create2 address
mstore(0x40, initcodehash)
Expand All @@ -101,7 +57,7 @@ library SimulateCall {

// if simulator not yet deployed, deploy it
if iszero(extcodesize(instance)) {
if iszero(create2(0, add(fmp, 0x06), 0x3a, 0)) {
if iszero(create2(0, add(fmp, 0x11), 0x2f, 0)) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
Expand Down
28 changes: 28 additions & 0 deletions contracts/utils/SimulateCall.yul
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// SPDX-License-Identifier: MIT

/// @dev Call simulator deployed via CREATE2 and delegatecalled by {SimulateCall}.
object "SimulationRelayer" {
/// @dev Constructor: returns the runtime object as the deployed code.
code {
datacopy(0, dataoffset("runtime"), datasize("runtime"))
return(0, datasize("runtime"))
}
object "runtime" {
/// @dev Runs the target call and inverts the result.
/// - Reverts on success (undoing state).
/// - Returns on failure.
/// Calldata layout: target[0x00:0x14] | value[0x14:0x34] | data[0x34:]
///
/// WARNING: Behavior is undefined if the calldata is shorter than 0x34 bytes. In that case, the length
/// computation underflows and the `calldatacopy` attempts to expand memory to an unreasonable size,
/// which in practice runs out of gas.
code {
let len := sub(calldatasize(), 0x34)
calldatacopy(0x00, 0x34, len)
let success := call(gas(), shr(0x60, calldataload(0x00)), calldataload(0x14), 0x00, len, 0x00, 0x00)
returndatacopy(0x00, 0x00, returndatasize())
if success { revert(0x00, returndatasize()) }
/* else */ { return(0x00, returndatasize()) }
Comment thread
Amxx marked this conversation as resolved.
Resolved
}
}
}
3 changes: 3 additions & 0 deletions foundry.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ out = 'out'
libs = ['node_modules', 'lib']
cache_path = 'cache_forge'

[profile.slither]
skip = ['*.yul']

[lint]
lint_on_build = false
exclude_lints = ["mixed-case-function", "asm-keccak256", "screaming-snake-case-immutable", "incorrect-shift", "mixed-case-variable"]
Expand Down
2 changes: 2 additions & 0 deletions hardhat.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import hardhatDocgen from './hardhat/hardhat-solidity-docgen/plugin.ts';
import hardhatExposed from './hardhat/hardhat-exposed/plugin.ts';
import hardhatTranspiler from './hardhat/hardhat-transpiler/plugin.ts';
import hardhatOzContractsHelpers from './hardhat/hardhat-oz-contracts-helpers/plugin.ts';
import hardhatYul from './hardhat/hardhat-yul/plugin.ts';
import './hardhat/async-test-sanity.ts';

// Parameters
Expand Down Expand Up @@ -41,6 +42,7 @@ export default defineConfig({
hardhatExposed,
hardhatTranspiler,
hardhatOzContractsHelpers,
hardhatYul,
],
paths: {
sources: argv.src,
Expand Down
59 changes: 59 additions & 0 deletions hardhat/hardhat-yul/hook-handlers/solidity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { SolidityHooks } from 'hardhat/types/hooks';
import fs from 'node:fs';
import path from 'node:path';
import { compileYul } from '../internal/compile.ts';

const isYul = (file: string) => file.endsWith('.yul');

// Hardhat only discovers `.sol` files. This hook compiles the `.yul` files found in the sources directories (or
// explicitly passed to `hardhat build`) alongside them, and emits regular artifacts at `artifacts/<sourceName>/`.
export default async (): Promise<Partial<SolidityHooks>> => ({
build: async (context, rootFilePaths, options, next) => {
// Yul files are removed from the roots, so the Solidity build system doesn't try to parse them.
const result = await next(
context,
rootFilePaths.filter(file => !isYul(file)),
options,
);

if (context.solidity.isSuccessfulBuildResult(result) && options?.scope !== 'tests') {
const { root, artifacts, sources } = context.config.paths;

// Discover all Yul files in the sources directories and the root file paths.
// Add any Yul files explicitly passed to the build via rootFilePaths.
const yulFiles = new Set([
...sources.solidity
.filter(dir => fs.existsSync(dir))
.flatMap(dir =>
fs
.readdirSync(dir, { recursive: true, encoding: 'utf8' })
.filter(isYul)
.map(file => path.join(dir, file)),
),
...rootFilePaths.filter(isYul),
]);

for (const file of yulFiles) {
const sourceName = path.relative(root, file).split(path.sep).join('/');
const outDir = path.join(artifacts, sourceName);
fs.mkdirSync(outDir, { recursive: true });
for (const { contractName, buildInfoId, bytecode, deployedBytecode } of await compileYul(context, sourceName)) {
const artifact = {
_format: 'hh3-artifact-1',
contractName,
sourceName,
abi: [],
bytecode,
linkReferences: {},
deployedBytecode,
deployedLinkReferences: {},
buildInfoId,
};
fs.writeFileSync(path.join(outDir, `${contractName}.json`), `${JSON.stringify(artifact, null, 2)}\n`);
}
}
}

return result;
},
});
58 changes: 58 additions & 0 deletions hardhat/hardhat-yul/internal/compile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { HookContext } from 'hardhat/types/hooks';
import type { SolidityBuildInfo } from 'hardhat/types/solidity';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import path from 'node:path';

export interface YulContract {
contractName: string;
buildInfoId: string;
bytecode: string;
deployedBytecode: string;
}

// Compile a Yul source with the solc resolved by Hardhat (courtesy from the Hardhat team).
export async function compileYul(context: HookContext, sourceName: string): Promise<YulContract[]> {
const { version, settings } = context.config.solidity.profiles.default.compilers[0];

const input = {
language: 'Yul',
sources: {
[sourceName]: { content: await readFile(path.join(context.config.paths.root, sourceName), 'utf8') },
},
settings: {
optimizer: settings.optimizer,
evmVersion: settings.evmVersion,
outputSelection: { '*': { '*': ['evm.bytecode.object', 'evm.deployedBytecode.object'] } },
},
};

// Hardhat requires every artifact to reference a build info, with an id of the form `solc-<major>_<minor>_<patch>-<hex>`
// (the solc version is parsed from it). No build info file is written: only the id is needed.
const buildInfoId = `solc-${version.replaceAll('.', '_')}-${createHash('sha256').update(JSON.stringify(input)).digest('hex')}`;

// `context.solidity.compileBuildInfo` downloads (or reuses from cache) the requested solc version
const output = await context.solidity.compileBuildInfo(
{ solcVersion: version, input } as unknown as SolidityBuildInfo,
{
quiet: true,
},
);

const errors = output.errors?.filter(e => e.severity === 'error') ?? [];
if (errors.length > 0) {
throw new Error(errors.map(e => e.formattedMessage).join('\n'));
}

return Object.entries(output.contracts?.[sourceName] ?? {}).map(([contractName, { evm }]) => {
if (!evm?.bytecode?.object || !evm?.deployedBytecode?.object) {
throw new Error(`No bytecode produced for ${sourceName}:${contractName}`);
}
return {
contractName,
buildInfoId,
bytecode: `0x${evm.bytecode.object}`,
deployedBytecode: `0x${evm.deployedBytecode.object}`,
};
});
}
10 changes: 10 additions & 0 deletions hardhat/hardhat-yul/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { HardhatPlugin } from 'hardhat/types/plugins';

const hardhatYulPlugin: HardhatPlugin = {
id: 'hardhat-yul',
hookHandlers: {
solidity: () => import('./hook-handlers/solidity.ts'),
},
};

export default hardhatYulPlugin;
21 changes: 9 additions & 12 deletions test/utils/SimulatedCall.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { network } from 'hardhat';
import { artifacts, network } from 'hardhat';
import { expect } from 'chai';

const {
Expand All @@ -12,23 +12,15 @@ async function fixture() {
const [receiver, other] = await ethers.getSigners();

const mock = await ethers.deployContract('$SimulateCall');
const simulator = ethers.getCreate2Address(
mock.target,
ethers.ZeroHash,
ethers.keccak256(
ethers.concat([
'0x60315f8160095f39f3',
'0x60333611600a575f5ffd5b6034360360345f375f5f603436035f6014355f3560601c5af13d5f5f3e5f3d91602f57f35bfd',
]),
),
);
const artifact = await artifacts.readArtifact('contracts/utils/SimulateCall.yul:SimulationRelayer');
const simulator = ethers.getCreate2Address(mock.target, ethers.ZeroHash, ethers.keccak256(artifact.bytecode));

const target = await ethers.deployContract('$CallReceiverMock');

// fund the mock contract (for tests that use value)
await other.sendTransaction({ to: mock, value });

return { mock, target, receiver, other, simulator };
return { mock, target, receiver, other, artifact, simulator };
}

describe('SimulateCall', function () {
Expand All @@ -48,6 +40,11 @@ describe('SimulateCall', function () {
await expect(this.mock.$getSimulator()).to.emit(this.mock, 'return$getSimulator').withArgs(this.simulator);
});

it('deploys the embedded simulator bytecode', async function () {
await this.mock.$getSimulator();
await expect(ethers.provider.getCode(this.simulator)).to.eventually.equal(this.artifact.deployedBytecode);
});

describe('simulated call', function () {
it('target success', async function () {
const txPromise = this.mock.$simulateCall(
Expand Down
Loading