Tutorial Waffle Hello world con hardhat ed ethers
In questo tutorial di Waffle, impareremo come configurare un semplice progetto di smart contract "Hello World" usando hardhat e ethers.js. Quindi impareremo come aggiungere una nuova funzionalità allo smart contract e come testarla con Waffle.
Iniziamo creando un nuovo progetto:
yarn inito
npm inite installando i pacchetti necessari:
yarn add -D hardhat @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chaio
npm install -D hardhat @nomiclabs/hardhat-ethers ethers @nomiclabs/hardhat-waffle ethereum-waffle chaiIl prossimo passaggio consiste nel creare un progetto hardhat di esempio eseguendo 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.jsQuitMostra tuttoSeleziona Create a sample project
La struttura del nostro progetto sarà simile a:
1MyWaffleProject2├── contracts3│ └── Greeter.sol4├── node_modules5├── scripts6│ └── sample-script.js7├── test8│ └── sample-test.js9├── .gitattributes10├── .gitignore11├── hardhat.config.js12└── package.jsonMostra tuttoOra parliamo di alcuni di questi file:
- Greeter.sol - il nostro Smart Contract scritto in 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}Mostra tuttoIl nostro smart contract è divisibile in tre parti:
- costruttore - posizione in cui dichiariamo una variabile di tipo di stringa chiamata
greeting, - funzione greet - funzione che restituirà
greetingquando chiamata, - 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!")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})Mostra tuttoIl 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 changedFinora 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!")45 await greeter.deployed()6 await expect(greeter.setGreeting("")).to.be.revertedWith(7 "Greeting should not be empty"8 )9})Mostra tuttoSembra 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 failingMostra tuttoImplementiamo questa funzionalità nel nostro smart contract:
1require(bytes(_greeting).length > 0, "Il saluto non dovrebbe esser vuoto");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}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.