2

I have written a smart contract and within which I have declared a payable function where everyone could send their funds to the contract. Once they have transferred their funds, they would have the allowance to use some other features. However, now I want to write a solidity unit test for the script to test its functions when different accounts send funds through. I wanted to know whether there is any way to modify the msg.sender while executing functions of solidity unit testing. For instance, account 1 sends eth to contract, then account 2 needs to do the same.

1
  • 1
    Yes there is a way, use hardhat and etherjs. I’m sure there are many examples. U will need to use something called „connect“ so it will be something like this „contractInstanc.connect(<your signer account>).<the method you want to call>
    – Majd TL
    Sep 24, 2021 at 19:22

1 Answer 1

8
+100

As mentioned in the comments, common development frameworks (Hardhat, Truffle) provide you with multiple accounts. You can't spoof msg.sender in contracts, but you can change which account sends a transaction in the unit test.

This, of course, works easiest in your own local blockchains. Yes, you can import multiple accounts for public networks, but that's not how it's usually done.

With Hardhat, there are good examples in their documentation: https://hardhat.org/tutorial/testing-contracts.html#using-a-different-account . Hardhat gives each of those test accounts enough local Ether for any testing you want to do (1000 or so). To switch to use a different account, use the connect function, as shown in the examples.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.