Passer au contenu principal

Tutoriel pour "dire bonjour au monde" avec hardhat et ethers

wafflecontrats intelligentssoliditétesthardhatethers.js
Débutant
MiZiet
16 octobre 2020
4 minutes de lecture minute read

Dans ce tutoriel Waffle(opens in a new tab), nous apprendrons comment créer un simple contrat intelligent "Hello world", en utilisant hardhat(opens in a new tab) et ethers.js(opens in a new tab). Ensuite nous apprendrons conmment 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 l'installation des paquets nécessaires :

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 est la création d'un projet hardhat basique 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
👷 Bienvenue dans Hardhat v2.0.3 👷‍
? Que voulez vous faire ? …
❯ Create a sample project
Create an empty hardhat.config.js
Quit
Afficher tout

Sélectionnez Create a sample project

Notre structure de 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├── .gitattributs
10├── .gitignore
11├── hardhat.config.js
12└── package.json
Afficher tout

Maintenant, parlons 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
Copier

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

  1. constructeur - où nous déclarons une variable de type string appelée greeting,
  2. function greet - une fonction qui retournera la valeur greeting lorsqu'elle est appelée,
  3. function setGreeting - une fonction qui nous permet de changer la valeur 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
Copier

La prochaîne étape consiste à compiler notre contrat et à exécuter nos tests :

Les tests Waffle utilisent Mocha (un framework de test) avec Chai (une bibliothèque d'assertions). Tout ce que vous avez à faire est d'exécuter npx hardhat test et d'attendre que le message suivant apparaisse.

✓ Doit renvoyer le nouveau message de bienvenue une fois qu'il a changé

Tout semble bien pour l'instant, ajoutons une certaine complexité à notre projet

Imaginez une situation où quelqu'un ajoute une chaîne vide comme un salut. Ce ne serait pas un accueil chaleureux, n'est-ce pas ?
Veillons à ce que cela ne se produise pas :

Nous voulons utiliser la version de solidity revert lorsque quelqu'un passe une chaîne vide. Une bonne chose est que nous pouvons facilement tester cette fonctionnalité avec la correspondance 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 wait greeter.deployed()
6 await expect(greeter.setGreeting("")).to.be.revertedWith(
7 "Greeting should not be empty"
8 )
9})
Afficher tout
Copier

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");
Copier

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}
Copier

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 comment mettre en place un projet, ajouter un test et implémenter de nouvelles fonctionnalités.

Pour plus d'excellents correspondants chai pour tester vos contrats intelligents, consultez la documentation officielle de Waffle(opens in a new tab).

Dernière modification: @DylanCONIN(opens in a new tab), 15 août 2023

Ce tutoriel vous a été utile ?