Salt la conținutul principal

Waffle spune „Salut, lume”; tutorial cu Hardhat și eteri

wafflecontracte inteligentesoliditytestarehardhatethers.js
Începător
MiZiet
16 octombrie 2020
4 minute de citit minute read

În acest tutorial Waffle(opens in a new tab) veți învăța cum să configurați un proiect de contract inteligent simplu „Hello world”, utilizând hardhat(opens in a new tab) și ethers.js(opens in a new tab). Apoi veți învăța cum să adăugați o nouă funcționalitate la contractul dvs. inteligent și cum să îl testați cu Waffle.

Să începem creând un nou proiect:

yarn init

sau

npm init

și instalând pachetele necesare:

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

sau

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

Următorul pas este crearea unui exemplu de proiect hardhat executând 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
Afișează tot

Selectați Crearea unui exemplu de proiect

Structura proiectului nostru ar trebui să fie:

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
Afișează tot

Acum să vorbim despre unele dintre aceste fișiere:

  • Greeter.sol - contractul nostru inteligent scris în 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}
Afișează tot
Copiați

Contractul nostru inteligent poate fi împărțit în trei:

  1. „constructor” - unde declarăm o variabilă de tip string numită greeting,
  2. funcția „greet” -o funcție care va returna greeting atunci când este apelată,
  3. funcția „setGreeting” - o funcție care ne permite să schimbăm valoarea greeting.
  • sample-test.js - fișierul nostru de teste
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})
Afișează tot
Copiați

La pasul următor ne vom compila contractul și vom rula testele:

Testele Waffle folosesc Mocha (un framework de testare) cu Chai (o bibliotecă de afirmații). Trebuie doar să rulați testul npx hardhat și să așteptați să apară următorul mesaj.

✓ Should return the new greeting once it's changed

Lucrurile merg grozav până acum, haideți să facem proiectul puțin mai complex

Imaginați-vă cum ar fi ca cineva să adauge un string gol ca salut. Nu ar fi un salut călduros, nu?
Să avem grijă ca acest lucru să nu se întâmple:

Atunci când cineva transmite un string gol, trebuie să folosim funcția solidity revert. Este bine că putem testa cu ușurință această funcționalitate cu validatorul-matcher chai to.be.revertedWith() al lui Waffle.

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})
Afișează tot
Copiați

Se pare că nu a mers noul nostru test:

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
Afișează tot

Să implementăm această funcționalitate în contractul nostru inteligent:

1require(bytes(_greeting).length > 0, "Greeting should not be empty");
Copiați

Acum funcția noastră „setGreeting” arată astfel:

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}
Copiați

Să rulăm din nou testele:

✓ Should return the new greeting once it's changed (1467ms)
✓ Should revert when passing an empty string (276ms)
2 passing (2s)

Felicitări! Ați reușit :)

Concluzie

Am făcut un proiect simplu cu Waffle, Hardhat și ethers.js. Am învățat cum să configurăm un proiect, să adăugăm un test și să implementăm noi funcționalități.

Dacă doriți să vă testați contractele inteligente și cu alți validatori-matchers chai excelenți, consultați documentele oficiale Waffle(opens in a new tab).

Ultima modificare: @nicklcanada(opens in a new tab), 15 august 2023

A fost util acest tutorial?