Hardhat can be easily integrated with both Infura and Alchemy, which are popular RPC providers for Ethereum. This integration allows developers to deploy smart contracts and interact with the Ethereum network without running a full node. Below are the steps to set up Hardhat with Infura and Alchemy, along with sample code.

Setting Up Your Project

  • Ensure you have a Hardhat project set up. If you haven't done this yet, follow the steps in the previous section to create a new Hardhat project.

Installing Dependencies

  • Install the necessary dependencies for making HTTP requests:
npm install --save-dev @nomiclabs/hardhat-ethers ethers

Configuring Hardhat

  • Open the hardhat.config.js file and configure it to use Infura or Alchemy:
require("@nomiclabs/hardhat-ethers");

const INFURA_PROJECT_ID = "your_infura_project_id";
const ALCHEMY_API_KEY = "your_alchemy_api_key";
const PRIVATE_KEY = "your_wallet_private_key";

module.exports = {
solidity: "0.7.3",
networks: {
rinkeby: {
url: `https://rinkeby.infura.io/v3/${INFURA_PROJECT_ID}`,
accounts: [`0x${PRIVATE_KEY}`]
},
mainnet: {
url: `https://eth-mainnet.alchemyapi.io/v2/${ALCHEMY_API_KEY}`,
accounts: [`0x${PRIVATE_KEY}`]
}
}
};

Deploying a Smart Contract

  • Create a new file in the scripts directory named deploy.js with the following code:
async function main() {
const Greeter = await ethers.getContractFactory("Greeter");
const greeter = await Greeter.deploy("Hello, world!");

console.log("Greeter deployed to:", greeter.address);
}

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

Running the Deployment Script

  • To deploy your smart contract to the Rinkeby test network using Infura, run the following command:
npx hardhat run scripts/deploy.js --network rinkeby
  • To deploy to the Ethereum mainnet using Alchemy, use:
npx hardhat run scripts/deploy.js --network mainnet

Conclusion

By integrating Hardhat with Infura or Alchemy, you can easily deploy and interact with smart contracts on the Ethereum network without the need to run your own node. This setup streamlines the development process and allows for efficient testing and deployment.