Passer au contenu principal

Tutoriel Waffle « Hello world » avec Hardhat et Ethers

Waffle
contrats intelligents
Solidity
test
Hardhat
ethers.js
Débutant
MiZiet
16 octobre 2020
4 minutes de lecture

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 init

ou

npm init

et installez les paquets requis :

yarn add -D hardhat @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chai

ou

npm install -D hardhat @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chai

L'étape suivante consiste à créer un projet d'exemple Hardhat en exécutant npx hardhat.

888 888 888 888 888
888 888 888 888 888
888 888 888 888 888
8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888
888 888 "88b 888P" d88" 888 888 "88b "88b 888
888 888 .d888888 888 888 888 888 888 .d888888 888
888 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 project
Create an empty hardhat.config.js
Quit
Afficher tout

Sélectionnez Create a sample project

La structure de notre projet devrait ressembler à ceci :

1MyWaffleProject
2├── contracts
3│ └── Greeter.sol
4├── node_modules
5├── scripts
6│ └── sample-script.js
7├── test
8│ └── sample-test.js
9├── .gitattributes
10├── .gitignore
11├── hardhat.config.js
12└── package.json
Afficher tout

Parlons maintenant de certains de ces fichiers :

  • Greeter.sol - notre contrat intelligent écrit en Solidity ;
1contract Greeter {
2string greeting;
3
4constructor(string memory _greeting) public {
5console.log("Deploying a Greeter with greeting:", _greeting);
6greeting = _greeting;
7}
8
9function greet() public view returns (string memory) {
10return greeting;
11}
12
13function setGreeting(string memory _greeting) public {
14console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
15greeting = _greeting;
16}
17}
Afficher tout

Notre contrat intelligent peut être divisé en trois parties :

  1. constructeur - où nous déclarons une variable de type string appelée greeting,
  2. fonction greet - une fonction qui renverra la valeur greeting lorsqu'elle est appelée,
  3. fonction setGreeting - une fonction qui nous permet de modifier la valeur de greeting.
  • 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!")
5
6 await greeter.deployed()
7 expect(await greeter.greet()).to.equal("Hello, world!")
8
9 await greeter.setGreeting("Hola, mundo!")
10 expect(await greeter.greet()).to.equal("Hola, mundo!")
11 })
12})
Afficher tout

L'é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 changed

Tout 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!")
4
5 await greeter.deployed()
6 await expect(greeter.setGreeting("")).to.be.revertedWith(
7 "Greeting should not be empty"
8 )
9})
Afficher tout

Il 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 failing
Afficher tout

Implé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

Ce tutoriel vous a été utile ?