What are the differences of Foundry vm.prank vs vm.broadcast
2 Answers
prank
sets msg.sender
to the address provided to it.
broadcast
actually creates transactions that can then be signed and sent on chain.
broadcast
can be used to deploy contracts inside of scripts, for example I can grab my private key from my .env
file and then deploy a contract with it.
contract NFTScript is Script {
function run() public {
vm.startBroadcast(vm.envUint("PRIVATE_KEY"));
NFT nft = new NFT("NonFun", "NFT");
console2.log(address(nft));
vm.stopBroadcast();
}
}
prank
can be used to ensure some tests pass, for example, any function that restricts the caller to a specific address.
function withdraw() public {
require(msg.sender == owner);
}
This test would pass a function call to withdraw
:
function testCall() public {
vm.prank(owner);
myContract.withdraw();
}
Meanwhile, this test would also pass:
function testBroadcast() public {
vm.startBroadcast(owner);
claim.withdraw();
vm.stopBroadcast();
}
-
But to call the withdraw function, isn't it required to be signed as well? Commented Sep 10, 2023 at 4:24
-
Which means that it's also possible for ``` vm.broadcast(owner) myContract.withdraw() ``` Commented Sep 10, 2023 at 4:25
-
@anonauditor Yes, you could also broadcast as the owner before calling withdraw and it would pass as well, I added another code snippet showing just that Commented Sep 10, 2023 at 15:55
vm.prank: Sets the next call's msg.sender to be the input address
vm.broadcast: Using the address that calls the test contract, has the next call (at this call depth only) create a transaction that can later be signed and sent onchain