Ethereum: Issue with tx.origin and msg.sender in Foundry test
Ethereum: Problem with tx. Origin
andMsg.Sender 'in the foundry test
As part of my current research on smart contracts, I was working on a test case for the Eternaut Level-4 contract (telephone) using the foundry. However, I encountered an unexpected problem that required troubleshooting.
The problem:
During the tests, I noticed that the fields "TX. Origin" and "Msg.sender" of my contract did not behave as planned. More specifically, these fields seemed to provide different values from what I expected.
The problem:
After examining the contract code and understanding how he interacts with the blockchain, I realized that there were two main problems at stake here:
- tx.origin
: The field tx.origin
contains the address of the account which launched the transaction (that is to say the sender). However, when using the Foundry test framework, this value is not always exact.
- Msg.sender
: The Msg.sender 'field contains the address of the account which called the contractual function (that is to say the recipient). This value may be different from "TX. Origin", especially if the transaction has been sent via a different account.
The solution:
To resolve this problem, I applied several modifications to my test code:
- Use "Sender" instead of "Origin" : in the Foundry test framework, it seems that "the sender" is the correct attribute to use when accessing the sender D 'A transaction.
- UseContractaddress ‘as withdrawn : If tx. Origin’ and
Msg.sender
are always different, I can resume the use of the contract address (contractaddress) as an alternative.
Here is an updated code extract demonstrating these modifications:
Javascript
Const {ethers} = require ("ethers");
// Test box for a telephone contract
Asynchronous function Testtephone () {
// Initialize the contract and the account
CONSTPONECONTRACT = NEW ETHERS.Contract (
"
Abi telephone,
Ethers.Wallet.FrombateKey (
"Your_private_key", // replace with your private key
))
));
// Create a transaction object
Const tx = {
De: Ethers.wallet.fromprivateKey ("Your_Private_Key"),
to: telephony.address, // correct address for this contract
Value: Ethers.utils.parsether ("1"), // Define the transaction value
Gasprice: 20n, // fix the price of gas (optional)
Gaslimit: 2000, // Set the maximum gas limit
Data: "0x", // Define the transaction data (empty in this case)
};
// Make the transaction
Const Result = Await TELEPHONECONTRACT.SENDTRANSAction (TX);
console.log (result);
}
// Run the test function
Testtelephone ();
` ‘
Conclusion:
By applying these modifications, I was able to solve the problem with “TX. Origin” and “Msg.sender” in my test for the telephone contract. Now that the values are correct, I can do with other tests and analyzes.
If you are faced with similar problems or if you have any questions about this solution, do not hesitate to ask!