Skip to content

Instantly share code, notes, and snippets.

@shogochiai
Created August 29, 2024 05:43
Show Gist options
  • Save shogochiai/b74cffd352de1720ecca55d7739839da to your computer and use it in GitHub Desktop.
Save shogochiai/b74cffd352de1720ecca55d7739839da to your computer and use it in GitHub Desktop.
An example of collocated fuzz test with meta contract. To get complex generated code, one can copy-paste this file to MC GPT and then test each validations by the unit tests.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Schema} from "bundle/main/storage/Schema.sol";
import {Storage} from "bundle/main/storage/Storage.sol";
import {MCTest} from "@devkit/Flattened.sol"; // MCTestをインポート
contract Borrow {
function borrow(uint256 amount) external {
Schema.GlobalState storage state = Storage.state();
uint256 collateral = state.collateralBalance[msg.sender];
uint256 maxBorrowable = collateral * 2 / 3;
require(amount <= maxBorrowable, "Insufficient collateral");
state.debtBalance[msg.sender] += amount;
}
// Getter functions for testing
function getCollateral(address user) external view returns (uint256) {
Schema.GlobalState storage state = Storage.state();
return state.collateralBalance[user];
}
function getDebt(address user) external view returns (uint256) {
Schema.GlobalState storage state = Storage.state();
return state.debtBalance[user];
}
}
contract BorrowTest is MCTest {
function setUp() public {
_use(Borrow.borrow.selector, address(new Borrow()));
}
function testBorrowWithStateFuzzing(uint256 x) public {
vm.assume(x > 1 ether && x < 1000 ether);
uint256 collateral = x;
vm.store(address(this), keccak256(abi.encode("collateralBalance", address(this))), bytes32(collateral));
uint256 maxBorrowable = collateral * 2 / 3;
vm.assume(maxBorrowable > 0);
uint256 borrowAmount = maxBorrowable / 2;
Borrow(address(this)).borrow(borrowAmount);
uint256 debt = Borrow(address(this)).getDebt(address(this));
assertEq(debt, borrowAmount, "Debt should be updated correctly");
uint256 requiredCollateral = debt * 150 / 100;
uint256 currentCollateral = Borrow(address(this)).getCollateral(address(this));
assertTrue(currentCollateral >= requiredCollateral, "Collateral should cover at least 150% of the debt");
}
function testBorrowWithLowCollateralRevert(uint256 x) public {
vm.assume(x > 1 ether && x < 10 ether);
uint256 collateral = x;
vm.store(address(this), keccak256(abi.encode("collateralBalance", address(this))), bytes32(collateral));
uint256 excessiveBorrowAmount = collateral * 4 / 3;
vm.expectRevert("Insufficient collateral");
Borrow(address(this)).borrow(excessiveBorrowAmount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment