How to Deploy a Smart Contract in 5 Minutes?

Smart contracts are one of the crucial elements in the domain of blockchain technology. Without smart contracts, the world of blockchain might have revolved solely around cryptocurrencies. However, smart contracts have provided the benefit of programmability for blockchain networks. Do you want to learn how to deploy smart contracts within 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 smart contracts is that they are pieces of code stored on a blockchain network. Smart contracts are similar to Ethereum accounts, albeit with significant differences against external accounts. For example, external accounts could connect to multiple Ethereum networks, such as Goerli Testnet. On the other hand, smart contracts are specific to the particular network on which they are deployed. 

When you deploy smart contract, it will help you create a contract account or instance on the network. Developers could generate multiple instances of a smart contract on one or multiple blockchain networks. You can deploy smart contracts by sending transactions to the network in the form of bytecode. Developers can choose different approaches for deploying smart contracts on Ethereum. Let us learn more about the recommended methods for deploying smart contracts in 5 minutes.

Curious to understand the complete smart contract development lifecycle? Enroll now in the Smart Contracts Development Course

Overview of Smart Contracts

Many of you might have doubts regarding the technical requirements for deploying smart contracts. However, you can overcome your apprehensions to deploy smart contract Ethereum with an overview of the fundamental concepts of smart contracts. Smart contracts are self-executing programs that can execute agreements and transactions without the involvement of intermediaries. Smart contracts have the following distinctive features,

  • Turing completeness.
  • Execution of contractual agreement between parties.
  • Autonomous execution of transactions or agreements.
  • Flexibility for execution in virtual machines such as EVM.
  • Deployment on blockchain network. 

You can create smart contracts by leveraging programming languages such as Solidity. Subsequently, you can use different tools, such as Hardhat and Truffle, for deploying smart contracts on the desired blockchain network.

smart contract deploying methods

Deploying Smart Contracts Using Hardhat

Hardhat is one of the popular tools used for deploying smart contracts. You don’t have to follow any important technical prerequisites for using Hardhat to facilitate smart contract deployment on the blockchain. Here are the important steps for deploying smart contracts by using Hardhat. 

  • Setting up the Environment

Before you create an instance on smart contract, you would have to set up the environment for deploying smart contracts. You can run the following code in the terminal of your system.

mkdir my-project-folder

cd my-project-folder

npm init -y

npm install --save-dev hardhat

The project starts by developing a project folder, followed by using ‘npm init –y’ to generate an NPM project. The ‘-y’ would imply the need for affirmation for every prompt. Subsequently, you can follow ‘deploy smart contract example’ by installing the ‘hardhat’ library.

Hardhat serves as a comprehensive Ethereum development environment, which helps in testing, compiling, deploying, and debugging smart contracts. It is also important to ensure installation of all project-centric dependencies. For example, you should add ‘npm install @openzeppelin/contracts’ for NFT smart contracts.

Excited to learn about the critical vulnerabilities and security risks in smart contract development, Enroll now in the Smart Contracts Security Course!

  • Initiating Hardhat Project

The next step in deploying smart contracts using Hardhat involves initiating a Hardhat project. Within the project folder, you have to use the ‘npx hardhat’ command to create a basic Hardhat project. You have to select the default option for supporting all prompt questions. 

The guides on how to deploy smart contracts using Hardhat also require identification of folders with a sample smart contract within the contract folder. You have to delete the files such as ‘contracts/Greeter.sol’, ‘test/sample-test.js,’ and ‘script/sample-script.js.’ Subsequently, you would have to save the smart contract within the ‘\contracts’ folder.

  • Configuration of Network and Private Key 

You can use a Testnet such as the Mumbai Testnet by Polygon. In the case of this example, you have to open the ‘hardhat.config.js’ and use the following code in place of the existing code. 

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


module.exports = {

  solidity: '0.8.3',

  networks: {

    mumbai: {

      url: '<mumbai-rpc>',

      accounts: ['<your-private-key>'],

    },

  },

};

As you deploy smart contract using Hardhat, it is important to follow certain precautions in this step. You would have to select the correct Solidity version and add the Mumbai RPC alongside your private key. You can also find a list of RPCs within the official document. It is also important to ensure that the file containing your private key should be restricted to the local machine. In addition, you can also configure the other networks within the networks section of the code. You could choose the network you want to use in the final deployment phase.

Certified Enterprise Blockchain Professional Certification

  • Creating the Code for Deploying Smart Contracts 

Once you have set up the configuration file and development environment, you have to work on the code for smart contract deployment. You have to create the ‘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)

    }

}

runMain()

The code provides a clear explanation for the different elements with clarity. You can utilize ‘hre.ethers’ for obtaining the contract and deploying it. However, it is important to follow certain precautions, such as,

Refraining from using ‘.sol’ in the ‘your-contract-name’ section in line 2. You can only use ‘myContract’ in this case. 

In the next line, you have to provide all the parameters needed for the ‘constructor’ in your smart contract. 

The lines from 7 to 11 can help you interact with smart contracts by invoking the desired functions. 

The final stage to deploy smart contract Ethereum is practically the easiest one in the guide for deploying smart contracts. You can use the following command for deploying the smart contract.

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

You can find the output in the terminal with a message indicating successful Solidity compilation. It is important to remember the address of your smart contract, which is essential for creating the front end.

Want to understand the importance of smart contracts audits? Check out Smart Contract Audit Presentation now!

Deploying Smart Contracts by Using Truffle    

Developers could find multiple setup options for deployment, migration, and accessibility of smart contracts. In addition, they could choose different options according to the level of visibility they want in the Ethereum Virtual Machine. The two options involve using Geth for running a full Ethereum mining node and using an online IDE such as Remix. On the other hand, you can create instance on smart contract and deploy it with better effectiveness by using Truffle. It is a popular smart contract development tool for compilation and deployment of smart contracts while offering enhanced control and visibility.

Before you start using Truffle for deploying smart contracts, it is important to follow some essential precautions. First of all, you must save your Metamask wallet mnemonic.  In addition, you would have to obtain some test Ether. Another important requirement for deploying smart contracts involves obtaining a Ropsten API key through Infura. Here are the important steps required for deploying a smart contract by using Truffle. 

The first step in a guide on how to deploy smart contracts using Truffle involves setting up Truffle. You can use the following command for setting up Truffle,

npm install –g truffle

Now, you have to create an empty repository and ‘cd’ in it, followed by using the following command, 

truffle init  

Then, you have to install the HDWalletProvider.

npm install --save truffle-hdwallet-provider 

You have to create the new contract ‘HelloWorld.sol’ in the ‘./contracts’ section by using the following code.

pragma solidity ^0.4.23;

contract HelloWorld {

    function sayHello() public pure returns(string){

        return(“hello world”);

    }

}

The actual step for deploying the contract involves creation of a deployment script. You have to create the ‘2_deploy_contracts.js’ deployment script in the ‘./migrations’ folder by using the following code:

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

module.exports = function(deployer) {

    deployer.deploy(HelloWorld, “hello”);

    // Additional contracts can be deployed here

};
  • Configuration of Ropsten Network and Provider

Developers can configure the Ropsten network and provider by adding the following snippet in the ‘module.exports’ section in ‘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 ‘mnemonic’ in the code. At the same time, you should also add ‘.gitignore’ to the file that contains your wallet mnemonic. Now, you can deploy the smart contract to Ropsten by using the following command. 

truffle deploy --network ropsten

Truffle would deploy to the local developer network only by default. The deployment would lead to a console log like the following,

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…

In this stage, you should pay attention to saving your contract address. You can examine the wallet address transactions by using an explorer-like Etherscan. 

  • Access the Deployed Network

Another crucial addition to the steps in deploy smart contract example using Truffle framework involves setting up the Truffle console to the Ropsten network.

truffle console --network ropsten

You can access the deployed instance of your smart contract by using the following command,

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

You could also retrieve the instance by using the public address through the following command,

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

In this case, the ‘HelloWorld.abi’ is the locally compiled ABI. The ‘contractAddress’ is the contract instance deployed publicly.

Build your identity as a certified blockchain expert with 101 Blockchains’ Blockchain Certifications designed to provide enhanced career prospects.

How Can You Deploy Smart Contracts to a Local Network?

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

How Can You Deploy Smart Contracts to Ethereum Network?

Prior to deployment of smart contracts to Ethereum blockchain, it is important to ensure that the account has the required Ether balance. The process of deploying a contract is similar to sending a transaction that would require gas fees for processing. However, the process to deploy smart contract directly to Ethereum would require some time to complete.

Web3.js can help you interact with the network in the same way as local deployment, albeit with customizing the provider that would be passed to the web3 instance. Rather than creating your own nodes for connecting to the Ethereum network, you can utilize a developer platform with RPC endpoints such as Alchemy or Infura.

Start learning Smart Contracts and its development tools with World’s first Smart Contracts Skill Path with quality resources tailored by industry experts Now!

Conclusion

The guide on how to deploy smart contracts by using tools like Hardhat and Truffle provides a clear roadmap for deploying smart contracts within 5 minutes. You should also notice the best practices for deploying smart contracts to local network and directly to Ethereum network. However, it is also important to learn about the important dependencies and requirements for deploying smart contracts. Learn more about smart contract development and explore the essential best practices for creating and deploying smart contracts right now.

Unlock your career with 101 Blockchains' Learning Programs

*Disclaimer: The article should not be taken as, and is not intended to provide any investment advice. Claims made in this article do not constitute investment advice and should not be taken as such. 101 Blockchains shall not be responsible for any loss sustained by any person who relies on this article. Do your own research!

Source link

Check Also

Binance Academy Introduces University-Accredited Programs with Discount and Rewards

. . . Binance Academy has recently unveiled a range of university-accredited programs in partnership …