Here is an article based on the information provided:
Ethereum Hardhat does not detect custom errors from legacy contracts
When building and testing smart contracts on the Ethereum network with Hardhat, we often encounter issues with custom error handling. In this case, we are investigating a common issue that occurs when testing OpenZeppelin’s “TimelockController” contract.
The problem: Custom errors in legacy contracts
To use custom errors in your contracts, you need to import them from an external module (in this case, “Address.sol”) and then extend their functionality. However, Hardhat has a limitation when it comes to detecting these custom errors.
Specifically, the “TimelockController” contract imports “FailedCall” which is defined in the “Address.sol” module. Unfortunately, Hardhat does not detect these custom errors out of the box.
The solution: Create a separate error module
We can create a separate module that defines the user-defined error called “Failedcall”. {MSG = “Function could not be called up”; contract TimelockController is SafeToken {
// vorhandener Code …
Funktion Zeitsperre() öffentlich nurBesitzer {
versuchen {
// Versuch, die Timelock-Funktion aufzurufen
_timelock();
} catch (Fehler: Anruf fehlgeschlagen) {
// Behandeln Sie den benutzerdefinierten Fehler
console.log(“Timelock konnte nicht aufgerufen werden: “, error.msg);
}
}
Funktion _timelock() öffentlich nurBesitzer {
// Implementierung der Zeitsperrenlogik …
}
}
Testen mit Hardhat
Nachdem wir nun unser Modul „failedcall.sol“ definiert haben, können wir es importieren und den benutzerdefinierten Fehler in unserem Vertrag „TimelockController“ mit Hardhat testen.
Hier ist ein Beispiel, wie Sie dies tun könnten:
Javascript
// Hardhat-Konfiguration
const hre = erfordern(“Bauhelm”);
const TimelockContract = await hre.getContractFactory(“TimelockController”);
const timelockContract = await TimelockContract.deploy();
async function main() {
// deploy the contract
const timelockAddress = await timelockContract.address;
try {
// call the timelock function to test the custom error
await TimelockContract.timelock();
} catch (error: call failed) {
console.log(“Could not call timelock: “, error.msg);
}
}
“`
By creating a separate error module and extending it from our “TimelockController” contract, we were able to use custom errors in our test. This should help you resolve the issue of Hardhat not detecting these errors.
Hope this helps! Let me know if you have any questions or need further assistance.
بدون نظر