Vai al contenuto principale

Tutorial Waffle Hello world con hardhat ed ethers

wafflesmart contractSoliditytesthardhatethers.js
Principiante
MiZiet
16 ottobre 2020
4 minuti letti minute read

In questo tutorial di Waffle(opens in a new tab), impareremo come configurare un semplice progetto di smart contract "Hello World" usando hardhat(opens in a new tab) e ethers.js(opens in a new tab). Quindi impareremo come aggiungere una nuova funzionalità allo smart contract e come testarla con Waffle.

Iniziamo creando un nuovo progetto:

yarn init

o

npm init

e installando i pacchetti necessari:

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

o

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

Il prossimo passaggio consiste nel creare un progetto hardhat di esempio eseguendo 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
Mostra tutto

Seleziona Create a sample project

La struttura del nostro progetto sarà simile a:

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
Mostra tutto

Ora parliamo di alcuni di questi file:

  • Greeter.sol - il nostro Smart Contract scritto in 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}
Mostra tutto
Copia

Il nostro smart contract è divisibile in tre parti:

  1. costruttore - posizione in cui dichiariamo una variabile di tipo di stringa chiamata greeting,
  2. funzione greet - funzione che restituirà greeting quando chiamata,
  3. funzione setGreeting - funzione che ci consente di cambiare il valore di greeting.
  • sample-test.js - file per il test
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})
Mostra tutto
Copia

Il prossimo passaggio consiste nel compilare il contratto ed eseguire test:

I test di Waffle usano Mocha (un framework di test) con Chai (una libreria di asserzione). È sufficiente eseguire npx hardhat test e attendere che compaia il messaggio seguente.

✓ Should return the new greeting once it's changed

Finora tutto bene, adesso aggiungiamo un po' di complessità al nostro progetto

Immagina una situazione in cui qualcuno aggiunge una stringa vuota come formula di saluto. Non sarebbe un bel saluto, vero?
Assicuriamoci che non succeda:

Vogliamo usare revert di Solidity quando qualcuno passa una stringa vuota. Un aspetto positivo è che possiamo facilmente testare questa funzionalità con il matcher chai di 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})
Mostra tutto
Copia

Sembra che il nostro nuovo test non sia riuscito:

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
Mostra tutto

Implementiamo questa funzionalità nel nostro smart contract:

1require(bytes(_greeting).length > 0, "Il saluto non dovrebbe esser vuoto");
Copia

Ora, la nostra funzione setGreeting somiglia a:

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

Eseguiamo di nuovo i test:

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

Congratulazioni! Ce l'hai fatta :)

Conclusioni

Abbiamo realizzato un semplice progetto con Waffle, Hardhat ed ethers.js. Abbiamo imparato come configurare un progetto, aggiungere un test e implementare nuove funzionalità.

Per informazioni su altri utili matcher chai per testare gli smart contract, consulta la documentazione ufficiale di Waffle(opens in a new tab).

Ultima modifica: @Herbie_23(opens in a new tab), 15 agosto 2023

Questo tutorial è stato utile?