Blockchain

How to deploy a smart contract in 5 minutes?

Smart contracts are one of the important elements in the realm of blockchain technology. Without smart contracts, the world of blockchain would only revolve around cryptocurrencies. However, smart contracts have brought the benefit of programmability to blockchain networks. Want to learn how to deploy a smart contract in 5 minutes? Interestingly, you are not the only one with such questions.

Smart contracts provide the foundation for creating dApps on the blockchain of your choice. The best thing about a smart contract is that it is a piece of code stored on a blockchain network. Smart contracts are similar to Ethereum accounts, although there are significant differences from external accounts. For example, external accounts can connect to multiple Ethereum networks, such as the Goerli Testnet. Smart contracts, on the other hand, depend on the specific network on which they are deployed.

Deploying a smart contract helps create contract accounts or instances on the network. Developers can create multiple instances of a smart contract on one or more blockchain networks. Smart contracts can be deployed by sending transactions to the network in bytecode format. Developers can choose from a variety of approaches to deploy smart contracts on Ethereum. Learn the recommended methods for deploying smart contracts in 5 minutes.

Want to understand the entire smart contract development lifecycle? Enroll in our smart contract development course today

Smart Contract Overview

Many of you may have doubts about the technical requirements for smart contract deployment. However, an overview of the basic concepts of smart contracts can help you overcome your concerns about deploying smart contracts on Ethereum. Smart contracts are self-executing programs that can execute contracts and transactions without the intervention of intermediaries. Smart contracts have the following characteristics:

  • Turing completeness.
  • Implementation of contractual agreements between parties.
  • Autonomous execution of transactions or contracts.
  • Flexibility to run on virtual machines such as EVM.
  • Deployed on blockchain network.

Smart contracts can be created using programming languages ​​such as Solidity. Afterwards, you can use various tools such as Hardhat and Truffle to deploy your smart contract on your desired blockchain network.

How to deploy smart contractsHow to deploy smart contracts

Deploying smart contracts using Hardhat

Hardhat is one of the popular tools used for smart contract deployment. There is no need to follow any significant technical prerequisites to use Hardhat to facilitate smart contract deployment on blockchain. Here are the important steps to deploy a smart contract using Hardhat:

  • Preferences

Before creating an instance for a smart contract, you must set up an environment for smart contract deployment. You can run the following code in your system terminal:

mkdir my-project-folder

cd my-project-folder

npm init -y

npm install --save-dev hardhat

The project starts with developing the project folder and using ‘npm init –y’ to create an NPM project. ‘-y’ means all prompts require confirmation. You can then install the ‘hardhat’ library and follow the ‘Smart Contract Deployment Example’.

Hardhat serves as a comprehensive Ethereum development environment that helps you test, compile, deploy, and debug smart contracts. It is also important to install all project-centric dependencies. For example, for NFT smart contracts you need to add ‘npm install @openzeppelin/contracts’.

I would like to learn about important vulnerabilities and security risks in smart contract development. Enroll in our Smart Contract Security course today!

  • Hardhat project started

The next step in deploying smart contracts using Hardhat involves starting a Hardhat project. You need to create a basic Hardhat project using the ‘npx hardhat’ command within the project folder. You should select the default option to support all prompt questions.

Our guide on how to deploy smart contracts using Hardhat requires you to identify the folder with the sample smart contract within the contracts folder. You must delete files such as ‘contracts/Greeter.sol’, ‘test/sample-test.js’, and ‘script/sample-script.js’. Afterwards, you need to save the smart contract in the ‘\contracts’ folder.

  • Network and private key configuration

You can use a testnet like Polygon’s Mumbai Testnet. For this example, you will need to open ‘hardhat.config.js’ and use the following code instead of the existing code:

require('@nomiclabs/hardhat-waffle');


module.exports = 

  solidity: '0.8.3',

  networks: 

    mumbai: 

      url: '<mumbai-rpc>',

      accounts: ('<your-private-key>'),

    ,

  ,

;

When deploying smart contracts using Hardhat, it is important to follow certain precautions at this stage. You need to select the correct Solidity version and add the Mumbai RPC along with the private key. You can also find a list of RPCs in the official documentation. It is also important to restrict files containing private keys to your local system. You can also configure other networks within the network section of your code. In the final deployment step, you can choose which network you want to use.

Certified Enterprise Blockchain Professional CertificationCertified Enterprise Blockchain Professional Certification

  • Code generation for smart contract deployment

After setting up your configuration files and development environment, you need to work on the code to deploy your smart contract. You need to create a ‘deploy.js’ file within the ‘\scripts’ folder and use the following code:

const main = async () => 

    const ContractFactory = await hre.ethers.getContractFactory('your-contract-name') // the file name under 'contracts' folder, without '.sol'

    const Contract = await ContractFactory.deploy(param1, param2, ...) // the constructor params

    await Contract.deployed()

    console.log("Contract deployed to:", Contract.address)


    // // You can test the function.

    // let txn = await nftContract.functionName()

    // // Wait for it to be mined.

    // await txn.wait()

    // console.log("function invoked!")




const runMain = async () => 

    try 

        await main()

        process.exit(0) // emit the exit event that ends all tasks immediately, even if there are still asynchronous operations that have not been done. The shell that executed node should see the exit code as 0.

     catch (error) 

        console.log(error)

        process.exit(1)

    


main run()

The code clearly provides clear explanations of the various elements. You can utilize ‘hre.ethers’ to acquire and distribute contracts. However, it is important to follow certain precautions:

Avoid using ‘.sol’ in the ‘your-contract-name’ section on line 2. In this case you can only use ‘myContract’.

In the next line, you need to provide all the required parameters to the ‘creator’ of your smart contract.

Lines 7 to 11 can help us interact with the smart contract by calling the desired function.

The final step to deploying a smart contract on Ethereum is actually the easiest step in the smart contract deployment guide. To deploy a smart contract, you can use the following command:

‘npx hardhat run scripts/deploy.js –network Mumbai’

You will find output in the terminal with a message indicating a successful Solidity compilation. It is important to remember the address of the smart contract that is essential for creating the frontend.

Do you want to understand the importance of smart contract auditing? Check out the Smart Contract Audit presentation now!

Deploying smart contracts using Truffle

Developers will find several setup options for deployment, migration, and accessibility of smart contracts. You can also choose from a variety of options depending on the level of visibility you want on the Ethereum Virtual Machine. Two options include using Geth and using an online IDE like Remix to run a full Ethereum mining node. Truffle, on the other hand, allows smart contracts to create instances and deploy them more efficiently. A popular smart contract development tool for compiling and deploying smart contracts while providing increased control and visibility.

Before using Truffle for smart contract deployment, it is important to follow some essential precautions. First, you need to save your MetaMask wallet mnemonic. Plus, you need to get some Ether for testing. Another important requirement for deploying smart contracts is obtaining a Ropsten API key through Infura. Here are the important steps required to deploy a smart contract using Truffle:

The first step in our guide on how to deploy smart contracts using Truffle is to set up Truffle. To set up Truffle, you can use the following command:

npm install –g truffle

Now you need to create an empty repository and type ‘cd’ inside it and then use the following command.

truffle init  

Then you need to install HDWalletProvider.

npm install --save truffle-hdwallet-provider 

You need to create a new contract ‘HelloWorld.sol’ in the ‘./contracts’ section using the following code:

pragma solidity ^0.4.23;

contract HelloWorld 

    function sayHello() public pure returns(string)

        return(“hello world”);

    


The actual steps to deploy a contract include creating a deployment script. You need to create a deployment script ‘2_deploy_contracts.js’ in the ‘./migrations’ folder using the following code:

var HelloWorld = artifacts.require(“HelloWorld”);

module.exports = function(deployer) 

    deployer.deploy(HelloWorld, “hello”);

    // Additional contracts can be deployed here

;
  • Ropsten network and provider configuration

Developers can configure the Ropsten network and provider by adding the following snippet to the ‘module.exports’ section of ‘truffle.js’.

var HDWalletProvider = require("truffle-hdwallet-provider");

const MNEMONIC = 'YOUR WALLET KEY';


module.exports = 

  networks: 

    development: 

      host: "127.0.0.1",

      port: 7545,

      network_id: "*"

    ,

    ropsten: 

      provider: function() 

        return new HDWalletProvider(MNEMONIC, "https://ropsten.infura.io/YOUR_API_KEY")

      ,

      network_id: 3,

      gas: 4000000      //make sure this gas allocation isn't over 4M, which is the max

    

  

;

It is important to use your own ‘API_KEY’ and ‘mnemonics’ in your code. At the same time, you must also add ‘.gitignore’ to the file containing your wallet mnemonic. You can now deploy your smart contract on Ropsten using the following command:

truffle deploy --network ropsten

Truffle is deployed by default only to local developer networks. Deployment generates the following console log:

Running migration: 1_initial_migration.js
Deploying Migrations…
… 0xd01dd7...
Migrations: 0xf741...
Saving successful migration to network…
… 0x78ed...
Saving artifacts…
Running migration: 2_deploy_contracts.js
Deploying HelloWorld…
… 0x0aa9...
HelloWorld: (SAVE THIS ADDRESS!!)
Saving successful migration to network…
… 0xee95...
Saving artifacts…

At this stage, you must be careful about saving the contract address. You can use Etherscan, similar to Explorer, to check wallet address transactions.

  • Access your deployed network

Another important addition to the step of deploying a smart contract example using the Truffle framework is setting up a Truffle console on the Ropsten network.

truffle console --network ropsten

You can access the deployed smart contract instance using the following command:

HelloWorld.deployed().then(function(instance)return instance );

You can also search for instances using their public addresses with the following command:

web3.eth.contract(HelloWorld.abi, contractAddress)

In this case ‘HelloWorld.abi’ is the locally compiled ABI. ‘contractAddress’ is a publicly distributed contract instance.

Build your identity as a certified blockchain professional with 101 Blockchains’ blockchain certification, designed to provide enhanced career prospects.

How can I deploy smart contracts on my local network?

Another important highlight of the smart contract deployment guide is that Ethereum refers to deploying smart contracts on a local network. You can use an emulator to deploy smart contracts on your local network, such as Ganache-cli. The emulator manages all aspects of contract deployment, so you don’t have to worry about security and the amount of gas required for your transactions. However, you must pass the Ganache provider in argument form to the web3 instance.

How can I deploy smart contracts on the Ethereum network?

Before deploying a smart contract on the Ethereum blockchain, it is important to ensure that you have the required Ether balance in your account. The process of distributing a contract is similar to sending a transaction that requires a gas fee for processing. However, the process of deploying a smart contract directly to Ethereum requires some time to complete.

Web3.js can help you interact with the network in the same way as your local deployment, even if you customize the provider passed to your web3 instance. Instead of creating your own node to connect to the Ethereum network, you can leverage a developer platform with an RPC endpoint, such as Alchemy or Infura.

Start learning smart contracts and development tools with the world’s first smart contract technology path featuring high-quality resources tailored by industry experts!

conclusion

Our guide on how to deploy smart contracts using tools like Hardhat and Truffle provides a clear roadmap for deploying smart contracts in under 5 minutes. You should also check out best practices for deploying smart contracts on your local network and directly on the Ethereum network. However, it is also important to learn about the important dependencies and requirements for smart contract deployment. Learn more about smart contract development and discover essential best practices for creating and deploying smart contracts today.

Build your career with 101 blockchain learning programsBuild your career with 101 blockchain learning programs

*Disclaimer: This article should not be considered, and is not intended to provide, investment advice. The statements made in this article are not investment advice and should not be taken as such. 101 Blockchain is not responsible for any loss suffered by anyone relying on this document. Do your own research!

Related Articles

Back to top button