I am wtiting test case using Foundry. I want to call a custom smart contract function that changes the state of the smart contract called from a EOA so the msg.sender
would be the EOA address. Here is my testing code:
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {console} from "forge-std/console.sol";
import {stdStorage, StdStorage, Test} from "forge-std/Test.sol";
import {Utils} from "./utils/Utils.sol";
import {MyERC20} from "../MyERC20.sol";
contract BaseSetup is MyERC20, DSTest {
Utils internal utils;
address payable[] internal users;
address internal alice;
address internal bob;
function setUp() public virtual {
utils = new Utils();
users = utils.createUsers(5);
alice = users[0];
vm.label(alice, "Alice");
bob = users[1];
vm.label(bob, "Bob");
}
function test() {
this.customFunction(); // want to call this function as Alice as the caller
}
}
So, in the code above, customFunction
is defined on the MyERC20
contract, and it changes the smart contract state. I want to call the function with different EOA accounts like alice
and bob
. Is it possible, and if so, what it the syntax for that?
CodePudding user response:
I would recommend using the prank
cheatcode in foundry for this.
It's pretty straight forward.
interface CheatCodes {
function prank(address) external;
}
contract Test is DSTest {
CheatCodes cheatCodes;
function setUp() public {
cheatCodes = CheatCodes(HEVM_ADDRESS);
}
function test() public {
// address(1337) is now the caller of customFunction
cheatCodes.prank(address(1337));
address(contract).customFunction();
}
}
This pranked caller will only persist for a single call. Then you will have to instantiate the caller again with the prank
cheatCode on future calls to the contract. Alternatively there is also a cheatCode called startPrank
which will allow the custom caller to persist until stopPrank
is called. Hope this helps!