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(cheats): deployCodeTo #401

Merged
merged 3 commits into from
Jun 25, 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
16 changes: 16 additions & 0 deletions src/StdCheats.sol
Original file line number Diff line number Diff line change
Expand Up @@ -697,4 +697,20 @@ abstract contract StdCheats is StdCheatsSafe {
// update owner
stdstore.target(token).sig(0x6352211e).with_key(id).checked_write(to);
}

function deployCodeTo(string memory what, address where) internal virtual {
deployCodeTo(what, "", 0, where);
}

function deployCodeTo(string memory what, bytes memory args, address where) internal virtual {
deployCodeTo(what, args, 0, where);
}

function deployCodeTo(string memory what, bytes memory args, uint256 value, address where) internal virtual {
bytes memory creationCode = vm.getCode(what);
vm.etch(where, abi.encodePacked(creationCode, args));
(bool success, bytes memory runtimeBytecode) = where.call{value: value}("");
require(success, "StdCheats deployCodeTo(string,bytes,uint256,address): Failed to create runtime bytecode.");
vm.etch(where, runtimeBytecode);
}
}
39 changes: 39 additions & 0 deletions test/StdCheats.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,33 @@ contract StdCheatsTest is Test {
&& addr != 0x4e59b44847b379578588920cA78FbF26c0B4956C
);
}

function testCannotDeployCodeTo() external {
vm.expectRevert("StdCheats deployCodeTo(string,bytes,uint256,address): Failed to create runtime bytecode.");
this._revertDeployCodeTo();
}

function _revertDeployCodeTo() external {
deployCodeTo("StdCheats.t.sol:RevertingContract", address(0));
}

function testDeployCodeTo() external {
address arbitraryAddress = makeAddr("arbitraryAddress");

deployCodeTo(
"StdCheats.t.sol:MockContractWithConstructorArgs",
abi.encode(uint256(6), true, bytes20(arbitraryAddress)),
1 ether,
arbitraryAddress
);

MockContractWithConstructorArgs ct = MockContractWithConstructorArgs(arbitraryAddress);

assertEq(arbitraryAddress.balance, 1 ether);
assertEq(ct.x(), 6);
assertTrue(ct.y());
assertEq(ct.z(), bytes20(arbitraryAddress));
}
}

contract StdCheatsMock is StdCheats {
Expand Down Expand Up @@ -505,3 +532,15 @@ contract RevertingContract {
revert();
}
}

contract MockContractWithConstructorArgs {
uint256 public immutable x;
bool public y;
bytes20 public z;

constructor(uint256 _x, bool _y, bytes20 _z) payable {
x = _x;
y = _y;
z = _z;
}
}