Tutoriel Waffle « Hello world » avec Hardhat et Ethers
Dans ce tutoriel Waffleopens in a new tab, nous apprendrons à configurer un projet simple de contrat intelligent « Hello world », en utilisant Hardhatopens in a new tab et ethers.jsopens in a new tab. Ensuite, nous apprendrons comment ajouter une nouvelle fonctionnalité à notre contrat intelligent et comment la tester avec Waffle.
Commençons par créer un nouveau projet :
yarn initou
npm initet installez les paquets requis :
yarn add -D hardhat @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chaiou
npm install -D hardhat @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chaiL'étape suivante consiste à créer un projet d'exemple Hardhat en exécutant npx hardhat.
888 888 888 888 888888 888 888 888 888888 888 888 888 8888888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888888 888 "88b 888P" d88" 888 888 "88b "88b 888888 888 .d888888 888 888 888 888 888 .d888888 888888 888 888 888 888 Y88b 888 888 888 888 888 Y88b.888 888 "Y888888 888 "Y88888 888 888 "Y888888 "Y888👷 Welcome to Hardhat v2.0.3 👷? What do you want to do? …❯ Create a sample projectCreate an empty hardhat.config.jsQuitAfficher toutSélectionnez Create a sample project
La structure de notre projet devrait ressembler à ceci :
1MyWaffleProject2├── contracts3│ └── Greeter.sol4├── node_modules5├── scripts6│ └── sample-script.js7├── test8│ └── sample-test.js9├── .gitattributes10├── .gitignore11├── hardhat.config.js12└── package.jsonAfficher toutParlons maintenant de certains de ces fichiers :
- Greeter.sol - notre contrat intelligent écrit en Solidity ;
1contract Greeter {2string greeting;34constructor(string memory _greeting) public {5console.log("Deploying a Greeter with greeting:", _greeting);6greeting = _greeting;7}89function greet() public view returns (string memory) {10return greeting;11}1213function setGreeting(string memory _greeting) public {14console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);15greeting = _greeting;16}17}Afficher toutNotre contrat intelligent peut être divisé en trois parties :
- constructeur - où nous déclarons une variable de type
stringappeléegreeting, - fonction
greet- une fonction qui renverra la valeurgreetinglorsqu'elle est appelée, - fonction
setGreeting- une fonction qui nous permet de modifier la valeur degreeting.
- sample-test.js - notre fichier de tests
1describe("Greeter", function () {2 it("Should return the new greeting once it's changed", async function () {3 const Greeter = await ethers.getContractFactory("Greeter")4 const greeter = await Greeter.deploy("Hello, world!")56 await greeter.deployed()7 expect(await greeter.greet()).to.equal("Hello, world!")89 await greeter.setGreeting("Hola, mundo!")10 expect(await greeter.greet()).to.equal("Hola, mundo!")11 })12})Afficher toutL'étape suivante consiste à compiler notre contrat et à exécuter les tests :
Les tests Waffle utilisent Mocha (un framework de test) avec Chai (une bibliothèque d'assertions). Il vous suffit d'exécuter npx hardhat test et d'attendre que le message suivant s'affiche.
✓ Should return the new greeting once it's changedTout semble parfait jusqu'à présent. Ajoutons un peu de complexité à notre projet
Imaginez que quelqu'un ajoute une chaîne vide en guise de salut. Ce ne serait pas un salut très chaleureux, n'est-ce pas ?
Assurons-nous que cela ne se produise pas :
Nous voulons utiliser la fonction revert de Solidity lorsque quelqu'un transmet une chaîne de caractères vide. Heureusement, nous pouvons facilement tester cette fonctionnalité avec le matcher Chai de Waffle to.be.revertedWith().
1it("Should revert when passing an empty string", async () => {2 const Greeter = await ethers.getContractFactory("Greeter")3 const greeter = await Greeter.deploy("Hello, world!")45 await greeter.deployed()6 await expect(greeter.setGreeting("")).to.be.revertedWith(7 "Greeting should not be empty"8 )9})Afficher toutIl semblerait que notre nouveau test n'ait pas réussi :
Deploying a Greeter with greeting: Hello, world!Changing greeting from 'Hello, world!' to 'Hola, mundo!' ✓ Should return the new greeting once it's changed (1514ms)Deploying a Greeter with greeting: Hello, world!Changing greeting from 'Hello, world!' to '' 1) Should revert when passing an empty string 1 passing (2s) 1 failingAfficher toutImplémentons cette fonctionnalité dans notre contrat intelligent :
1require(bytes(_greeting).length > 0, "Greeting should not be empty");Maintenant, notre fonction setGreeting ressemble à ceci :
1function setGreeting(string memory _greeting) public {2require(bytes(_greeting).length > 0, "Greeting should not be empty");3console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);4greeting = _greeting;5}Exécutons les tests à nouveau :
✓ Should return the new greeting once it's changed (1467ms)✓ Should revert when passing an empty string (276ms)2 passing (2s)Félicitations ! Vous y êtes arrivé :)
Conclusion
Nous avons réalisé un projet simple avec Waffle, Hardhat et ethers.js. Nous avons appris à configurer un projet, à ajouter un test et à implémenter de nouvelles fonctionnalités.
Pour découvrir d'autres matchers Chai très utiles pour tester vos contrats intelligents, consultez la documentation officielle de Waffleopens in a new tab.
Dernière mise à jour de la page : 8 décembre 2023