Deploying a Contract
To deploy the HelloWorld.sol contract, do the following:
-
Install the dotenv package in your project directory.
npm install dotenv --save -
Create a file called
.envin the project directory with the following contents.API_URL = "https://eth-goerli.g.alchemy.com/v2/your-api-key" PRIVATE_KEY = "your-metamask-private-key"Follow these instructions to export your private key from Metamask. The
API_URLneeds to be copied from your Alchemy account.NOTE: If you are going to push the project code to a public Github/Gitlab repository, remember to add the
.envfile to your.gitignore. -
Install Ethers.js by running the following command
npm install --save-dev @nomiclabs/hardhat-ethers "ethers@^5.0.0" -
Update the
hardhat.config.jsfile to have the following content./** * @type import('hardhat/config').HardhatUserConfig */ require('dotenv').config(); require("@nomiclabs/hardhat-ethers"); const { API_URL, PRIVATE_KEY } = process.env; module.exports = { solidity: "0.8.17", defaultNetwork: "goerli", networks: { hardhat: {}, goerli: { url: API_URL, accounts: [`0x${PRIVATE_KEY}`] } }, } -
Create a directory called
scriptsmkdir scripts -
Create a file called
deploy.jsin thescriptsdirectory with the following content.async function main() { const HelloWorld = await ethers.getContractFactory("HelloWorld"); // Start deployment, returning a promise that resolves to a contract object const hello_world = await HelloWorld.deploy("Hello World!"); console.log("Contract deployed to address:", hello_world.address); } main() .then(() => process.exit(0)) .catch(error => { console.error(error); process.exit(1); }); -
Deploy the contract by running the following command.
npx hardhat run scripts/deploy.js --network goerliYou should see a message of the following form. The address will be different in your case.
Contract deployed to address: 0xD1aEf927a80301b63dE477afe2410F25bf8Baf6aSave the contract address somewhere. It will be used in the next section.