You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
14 Hrs
29 Min
20 Seg

Entorno de desarrollo con Hardhat

16/27
Resources

There are several development environments that you can use for the development of smart contracts. Possibly the most popular these days in the Ethereum community is Hardhat.

Contract development and deployment with Hardhat

Hardhat is a development environment that will allow us to work through the entire lifecycle of a smart contract on EVM-based networks. From the environment configuration, contract development, contract testing, debugging, compilation, up to the deployment stage on the blockchain.

Hardhat is based on Javascript, so all your previous knowledge in the language and in technologies such as NPM will be of great help to develop any project.

Installing Hardhat

The first step to use Hardhat is to install the framework on your computer. For this, you will need to create a new project with the help of NPM and install Hardhat as a dependency.

npm init -y npm install hardhat npm install @nomicfoundation/hardhat-toolbox

Remember that you will need to have your NodeJS-based development environment ready on your computer to use NPM. While contracts are developed with Solidity, you will need the help of Javascript to create, test and deploy your contract.

Creating and configuring a project with Hardhat

Once you have your base project created with npm, the npx hardhat command will start a new project with the base Hardhat settings inside it.

You will see a new file called hardhat.config.js, which we will modify later for the deployment of the contract on the blockchain.

With Hardhat initialized, it's time to create your first contract with this framework. To do this, create a directory called contracts with the .sol file that makes up your smart contract. For the next contract, the file is named Counter.sol:

````js // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.1 <0.8.19;

contract Counter { uint counter;

constructor(uint _counter) { counter = _counter; } function getCounter() public view returns (uint) { return counter; } function increment() public { counter++; }

} ```

Unit test development in Hardhat

One of the essential parts of smart contract development is your unit tests. Having a good set of tests to ensure the proper functioning of your contract is critical.

Inside your project, create a directory called test with a file called counter.js where we will write the tests for the Counter.sol contract. We will make use of the ether.js library, which is already built into Hardhat. You will also need to install Chai which we will use to evaluate the test results.

``` const { expect } = require('chai') const { ethers } = require('hardhat')

describe('Counter Contract', () => { it('Should increment the counter', async () => { const Counter = await ethers.getContractFactory('Counter') const counter = await Counter.deploy(0) await counter.increment() const updateCounter = await counter.getCounter()

   expect(updateCounter).to.equal(1) })

}) ```

In these lines of test code, written with JavaScript, we are creating a unit test that first captures the Counter.sol contract. Instantiate it and execute the increment() function. Then, we capture the current value of the counter and corroborate that the same is one.

Finally, with the command npx hardhat test, you will execute the tests and you will see the results by console. In this way, you can now test the logic of your contract, without the need to deploy it on the blockchain and without commissions.

Preparation for contract deployment

When you are sure that your contract is finalized, with a good test set that proves it works correctly, it's time to automate the deployment of your contract with Hardhat.

Start by creating a directory called scripts with a file called deploy.js. Here we will write, also using Javascript, a script that automates the deployment of the contract on the blockchain.

``` const { ethers } = require("hardhat");

async function main(){ const [deployer] = await ethers.getSigner(); console.log("Deployer",deployer);

const Counter = await ethers.getContractFactory('Counter'); const counter = await Counter.deploy(0); console.log ("Counter Contract Addres",counter.address);

} main() .then(() => process.exit(0)) .catch( (error) => { console.error(error); process.exit(1); }); ````.

It's time to go back to the hardhat.config.js configuration. Here, we will configure the Ethereum network to which we want to deploy the contract, along with the necessary information for this.

``` require("@nomicfoundation/hardhat-toolbox");

/* @type import('hardhat/config').HardhatUserConfig / module.exports = { solidity: "0.8.18", networks: { goerli: { url: 'PROVIDER_URL', accounts: [ 'METAMASK_PRIVATE_KEY' ] } } } } }; ````

For this example, we will deploy the contract in Goerli. Hardhat will allow you to deploy contracts on Sepolia or any other EVM-based network.

Note that you will need two very important and sensitive pieces of information, the private key of your wallet that will pay for the contract deployment fee. Make sure you have sufficient funds, in this case, in Goerli. You will also need a URL pointing to an Ethereum node.

Metamask will allow you to easily export the private key, not to mention once again the importance of securing this information well. On the other hand, as it is challenging to set up your own Ethereum node, services like Infura or Alchemy will give you a URL to connect to their nodes quickly.

If you have everything configured correctly, the next step will be to deploy the contract. But we'll see that in the next class.

Conclusion

You've seen throughout this class how important and useful it is to work with development environments like Hardhat. We have been able to develop a contract, test it and have everything ready for later deployment. You will also have noticed the importance of Javascript, although you don't really need much knowledge in the language, just the basics.

Let's go for the last step and deploy that contract with Hardhat.


Contributed by: Kevin Fiorentino (Platzi Contributor).

Contributions 9

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

  • Instalación de Hardhat
  1. Desde hardhat. org descargamos la herramienta
  2. Creamos un proyecto con npm init
  3. Nos aseguramos que se haya creado el package.json
  4. npm install --save-dev @nomicfoundation/hardhat-toolbox
  5. Configuramos hardhat. Para esto usamos npx hardhat
  6. Seleccionar Create an empty hardhat.config.js
  7. Nos aseguramos que se haya creado el hardhat.config.js
  • Una vez que la configuración de Hardhat esta lista vamos a VSCode.
  1. Creamos un nuevo folder llamado Contracts
  2. Dentro de esta carpeta creamos Counter.sol
  3. Escribimos el contrato (o copiamos el que escribimos en Remix en la clase anterior)
  • Pruebas unitarias
  1. Creamos un folder llamado Test
  2. Creamos dentro un archivo counter.js (ya que utilizaremos JavaScript)
  3. Vamos a utilizar la herramienta chai para escribir los testcases.
  4. Para poder instanciar un smart contract dentro de JavaScript vamos a utilizar ethers.js
  • Despliegue
  1. Creamos folder Scripts
  2. Creamos dentro de Scripts el archivo deploy.js
  • Actualizar config de hardhat para indicar la red de goerli y las llaves privadas

Dejo mis apuntes, más el codigo de la clase.

Goerli no me funcionó y en el faucet me recomendaba usar Sepolia así que seguí exactamente el paso a paso pero cambiando todo por Sepolia y funcionó.

Para hacerlo basta:

  • Usar seplia en metamask como red de prueba (test network)
  • Crear la app en Alchemy con Sepolia y obtener la URL para luego usarla en hardhat.config.js
  • En hardhat.config.js declarar que se usa Sepolia en vez de Goerli osea usar el comando
require("@nomicfoundation/hardhat-toolbox");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  solidity: "0.8.18",
  networks: {
    sepolia: {
      url:' obtenida de alchemy usando app en sepolia',
      accounts:[
        "AAAABBBBCCCC"
      ]
    }
  }
};
  • en la línea de comandos “–network sepolia”

Les comparto el código:

// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.7;

contract Counter {
  uint counter;

  constructor(uint _counter) {
    counter = _counter;
  }

  function getCounter() public view returns(uint) {
    return counter;
  }

  function increment() public {
    counter ++;
  }
}

Codigo de deploy.js

<code> 
const { ethers} = require("hardhat");

async function main(){
    const [deployer] = await ethers.getSigner();
    console.log("Deployer",deployer);

    const Counter = await ethers.getContractFactory('Counter');
    const counter = await Counter.deploy(0);

    console.log ("Counter Contract Addres",counter.address);

}
main()
    .then(() => process.exit(0))
    .catch( (error) => {
        console.error(error);
        process.exit(1); 
    });
npm init -y
npm install --save-dev hardhat
npm install --save-dev @nomicfoundation/hardhat-toolbox

Edita el archivo hardhat.config.js y agrega el código:

require(”@nomicfoundation/hardhat-toolbox”);

Edita tu contrato Counter.sol (carpeta contracts) en tu editor preferido (aquí usamos VSCode) y luego puedes compilarlo con:

npx hardhat compile

puedes ejecutar tu test con:

npx hardhat test

Si vas a usar la network de Sepolia entonces:

{
//TU CODIGO ...
  networks: {
    sepolia: {
      url: `TU_URL}`,
      accounts: [SEPOLIA_PRIVATE_KEY]
    }
  }

No me aparecen los colores en Counter.sol

En el archivo deploy.js, no desestructurar el resultado de ethers.getSigner() dado que ya no es iterable.
De lo contrario tendrás el error:

TypeError: (intermediate value) is not iterable
at main (/Users/Eber/Documents/3.Learning/1.blockchain/ethereum/counterContract/scripts/deploy.js:4:22)

.

Código completo

const { ethers } = require("hardhat");

async function main() {
  const deployer = await ethers.getSigner();
  console.log("Deployer", deployer);

  const Counter = await ethers.getContractFactory('Counter');
  const counter = await Counter.deploy(0);

  console.log("Counter Contract Address", counter.address);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });