How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (2024)

Improve

Smart contracts are blocks of code that reside on the blockchain. It is like an Ethereum account but there is a critical difference between an external account and a smart contract. Unlike a smart contract, an external account can connect to multiple Ethereum networks (Goerli testnet, mainnet, etc.) whereas a smart contract is only specific to one individual network (the network it is deployed on). When a smart contract is deployed, it creates an instance (contract account) on the network. One can create multiple instances of a smart contract on the network or multiple networks. Deployment of a smart contract is done by sending a transaction to the network with bytecode.

Deploying To A Local Network

An emulator can be used to deploy a smart contract on a local network eg. Ganache-cli. It takes care of everything and the user doesn’t have to worry about the security and the gas amount required for transactions since everything is happening on a local test network. All one has to do is pass the ganache provider as an argument to the web3 instance(web3 facilitates the connection between the blockchain network and the js application).

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (1)

Deploying To Actual Ethereum Network

Before deploying a smart contract to an actual Ethereum network make sure the account has some ether in it. Deploying a contract is like sending a transaction and it needs some gas amount to process. Unlike deploying on a local network, transactions will take some time to complete (anywhere between 15 seconds to 5 minutes). Web3 is used to interact with the network the same way it is done in local deployment except customize the provider that will be passed into the web3 instance. Instead of creating our own node that connects to the Ethereum network, one can use a developer platform with RPC endpoints like Infura or Alchemy. With one of these accounts, you have an API key that gives access to their Infura / Alchemy blockchain nodes that are already hosted on the Ethereum network. Simply sign-up for Infura and get an endpoint that will be used in the code to deploy the smart contract. The below tutorial shows a smart contract being deployed with Infura. For a smart contract tutorial using tools like Alchemy (ethers.js, Hardhat, Solidity, and Metamask), refer to this basic tutorial – “Hello World Smart Contract“.

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (2)

example.sol- Below is the sample solidity code used for testing. All it does is set a public variable as the address of the sender.

Solidity

// Solidity program to implement

// the above approach

pragma solidity ^0.8.4;

// Creating a contract named Example

contract Example

{

// Public variable of type address

address public manager;

// Constructor function to set manager

// as address of sender

constructor()

{

manager = msg.sender;

}

}

 
 


Step 1- Install the required dependencies by running the following commands-

npm i [email protected] [email protected] [email protected]

Make sure to install the same versions for the following scripts to run successfully.

Step 2- Sign up for Infura and create a project on a particular Ethereum network to get access to the endpoint. The endpoint will be required to deploy the smart contract on the infura node that is already hosted on the Ethereum network. To create a project on infura-

  • Click on create a new project.
  • Give it a name.
  • Select the network to deploy the smart contract on.
  • A maximum of 3 projects can be created on infura for free.

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (3)How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (4)

Step 3 – Get access to Bytecode and ABI (Compile the smart contract). Solidity compiler gives a huge piece of code as output, one can print the output to console if required. Only the relevant part (relevant for deployment) i.e., bytecode and interface are extracted from the output in the following script.

Compile.js- Below is the javascript file.

Javascript

// Javascript file to implement

// the above approach

const path = require("path");

const fs = require("fs");

const solc = require("solc");

// remember to change line 8 to your

// own file path. Make sure you have your

// own file name or contract name in line

// 13, 28 and 30 as well.

const examplePath = path.resolve(__dirname, "contracts", "example.sol");

const source = fs.readFileSync(examplePath, "utf-8");

var input = {

language: 'Solidity',

sources: {

'example.sol': {

content: source

}

},

settings: {

outputSelection: {

'*': {

'*': ['*']

}

}

}

};

var output = JSON.parse(solc.compile(JSON.stringify(input)));

var interface = output.contracts["example.sol"]["example"].abi;

var bytecode = output.contracts['example.sol']["example"].evm.bytecode.object;

module.exports = { interface, bytecode };

 
 

Step 4 – Add the Metamask extension to google chrome from the Chrome web store.

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (5)

Step 5 – Once have access to the bytecode and interface, all that is required is to create a provider with own mnemonic phrase and infura endpoint using the truffle-hdwallet-provider that was installed earlier. Create a web3 instance and pass the provider as an argument. Finally, use the deploy method with bytecode as an argument to deploy the smart contract.

deploy.js

Javascript

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

// Web3 constructor function.

const Web3 = require("web3");

// Get bytecode and ABI after compiling

// solidity code.

const { interface, bytecode } = require("file-path");

const provider = new HDWalletProvider(

"mnemonic phrase",

// Remember to change this to your own phrase!

"-"

// Remember to change this to your own endpoint!

);

// Create an instance of Web3 and pass the

// provider as an argument.

const web3 = new Web3(provider);

const deploy = async () => {

// Get access to all accounts linked to mnemonic

// Make sure you have metamask installed.

const accounts = await web3.eth.getAccounts();

console.log("Attempting to deploy from account", accounts[0]);

// Pass initial gas and account to use in the send function

const result = await new web3.eth.Contract(interface)

.deploy({ data: bytecode })

.send({ gas: "1000000", from: accounts[0]});

console.log("Contract deployed to", result.options.address);

};

deploy();

// The purpose of creating a function and

// calling it at the end -

// so that we can use async await instead

// of using promises

 
 


Output:

Contract is deployed to 0x8716443863c87ee791C1ee15289e61503Ad4443c

Now the contract is deployed on the network, its functionality can be tested using remix IDE or one can create an interface to interact with the smart contract on the network.

Interacting With Deployed Smart Contract Using Remix IDE

Remix can be used to connect to actual Ethereum networks and interact with deployed smart contracts. It is the easiest way to interact with a deployed smart contract without having to make a fancy frontend.

Step 1- Open Remix IDE in chrome browser and copy the solidity code of the deployed smart contract and paste it in the Ballot.sol file in the IDE. Switch to the solidity compiler by clicking on the “S” icon on the sidebar and compile it.

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (6)

Step 2- Navigate to Deploy and run transactions from the sidebar and select injected web3 from environment dropdown. It is the instance of web3 injected by metamask into your browser. It also has access to all the accounts.

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (7)

Step 3- Instead of deploying the smart contract, copy the address of the already deployed smart contract in the “At Address” field. This button is disabled until you put in a valid address. Once the button is clicked, the list of functions from your smart contracts can be seen. One can interact with a deployed smart contract using these function buttons. Since the “example.sol” has only one variable, manager. Clicking this button will give the address of the account it was deployed from as the output.

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (8)

Before Mainnet Deployment | Goerli Testnet

Before deploying to the Ethereum mainnet, we recommend deploying to the Goerli testnet. Note that with the recent Ethereum merge, Goerli is the only Ethereum-supported testnet. Other testnets like Rinkeby, Kovan, and Ropsten have been deprecated.

By deploying on Goerli testnet first, you’re able to test your smart contract without it costing real money (in the form of real ETH). In order to deploy to Goerli testnet (https://eth-goerli.g.alchemy.com/v2/Alchemy-API-key or https://goerli.infura.io/v3/Infura-API-key), you’ll need test Goerli Ether (“Goerli testETH”). You get Goerli testETH from Goerli faucets – for example, Alchemy provides a free Goerli faucet where you can get more testETH every day: goerlifaucet.com.

Goerli Faucet :

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (9)

Goerli Faucet



Last Updated : 04 Apr, 2023

Like Article

Save Article

Previous

Ethereum - Gas and Fees

Next

"Hello World" Smart Contract in Remix-IDE

Share your thoughts in the comments

Please Login to comment...

How to Simply Deploy a Smart Contract on Ethereum? - GeeksforGeeks (2024)

FAQs

How do you simply deploy a smart contract on Ethereum? ›

To deploy your smart contract, go to the “Deploy & Run Transactions” tab, and select “IncrementDecrement” from the dropdown menu. In the “Environment” dropdown, select the network you want to deploy your contract to (e.g., “Remix VM” for a local testing network or “Injected Web3” for the main Ethereum network).

How much does it cost to deploy a smart contract on ETH? ›

Smart contract creation cost can be anywhere from $10 to $2,000 assuming Ether costs between $1,500 to $2,000. The biggest factors are 1) Ethereum price, 2) the size of the compiled contract (in bytes), 3) the current gas price on the Ethereum network.

How to use MetaMask to deploy a smart contract? ›

Deploy a Smart Contract
  1. Connect to Metamask​ Before you get started, make sure you have connected Metamask to your network of choice. ...
  2. Access Remix IDE​ ...
  3. Create Your Smart Contract​ ...
  4. Compile Your Smart Contract​ ...
  5. Deploy Your Smart Contract​ ...
  6. Interact with Your Deployed Contract​ ...
  7. Set Up Hardhat​ ...
  8. Add Your Contract​
Jun 18, 2024

How do I deploy a smart contract on Etherscan? ›

Let's get started!
  1. Step 1: Generate an API Key on your Etherscan account. An Etherscan API Key is necessary to verify that you're the owner of the smart contract that you're trying to publish.
  2. Step 2: Hardhat-deployed Smart Contracts. ...
  3. Step 3: Check out your smart contract on Etherscan!

How to deploy a smart contract for free? ›

Create and Deploy your Smart Contract
  1. Step 1: Connect to the Ethereum network. ...
  2. Step 2: Create your app (and API key) ...
  3. Step 3: Create an Ethereum account (address) ...
  4. Step 4: Add ether from a Faucet. ...
  5. Step 5: Check your Balance. ...
  6. Step 6: Initialize our project. ...
  7. Step 7: Download Hardhat. ...
  8. Step 8: Create Hardhat project.

How much gas is required to deploy a smart contract? ›

Creation of your contract

The base cost for the creation of a smart contract, according to Ethereum's yellow paper, is about 32000 gas. Nevertheless, the final cost of the smart contract deployment depends on the following: Size of the deployed code (in bytes).

How many smart contracts are deployed on Ethereum? ›

As of Sep 2023, more than 61 61 61 61 million smart contracts have been deployed on Ethereum (Cloud, 2023) , the largest blockchain supporting smart contracts.

What is the size limit for ETH smart contracts? ›

🤔 Every blockchain has a limit on the maximum size of Smart Contract bytecode that can be deployed. In the world of Ethereum, after the implementation of EIP170, the maximum bytecode size is 24.576 kilobytes.

What happens when you deploy a smart contract? ›

When a smart contract is deployed, it creates an instance (contract account) on the network. One can create multiple instances of a smart contract on the network or multiple networks. Deployment of a smart contract is done by sending a transaction to the network with bytecode.

How to make money from Ethereum smart contract? ›

Real-World Examples of Smart Contract Revenue Streams
  1. Purchase ETH on a centralized exchange like Coinbase.
  2. Send ETH to a Web3 wallet like MetaMask.
  3. Visit the Aave website and connect your wallet.
  4. Deposit ETH into a lending pool and start earning interest automatically.
Nov 13, 2023

What are examples of smart contracts? ›

Now you understand how smart contracts work, let's look at some smart contract examples from the real world.
  • Clinical trials. Data sharing between institutions is vital to effective clinical trials. ...
  • Music industry. ...
  • Supply chain management. ...
  • Property ownership. ...
  • Mortgages. ...
  • Retail. ...
  • Digital identity. ...
  • Recording financial data.

How do you deploy smart contract on Ethereum private network? ›

With the basic setup now complete, you can dive into creating a blockchain smart contract.
  1. 3.1. Install Hardhat. ...
  2. 3.2 Prepare the Ethereum smart contract code. Create a directory for smart contracts and create a contract file: ...
  3. 3.3. Complete the Hardhat config. ...
  4. 3.4. Compile the code. ...
  5. 3.5. Deploy the smart contract.
Jul 12, 2023

How do I deploy an ERC20 smart contract? ›

How to create your own ERC-20 smart contract:
  1. Click 1: Select “ERC20 OpenZepplin” under 'Project Templates. ...
  2. Click 4: Select “Compile MyToken.sol” ...
  3. Click 6: Select “Injected Provider — Metamask” ...
  4. Click 8: Select your desired chain for your ERC-20 (In the picture below, you can see that I selected Base)
Feb 4, 2024

How does Ethereum execute smart contracts? ›

Think of the EVM as a distributed global computer where all smart contracts are executed. (Ethereum is sometimes referred to as a “world computer.”) Ethereum lets developers program their own smart contracts to define EVM instructions. The EVM executes a contract according to the rules the developer programmed.

Top Articles
The seven senses of sharks
Discover the Top 10 AI-Proof Jobs in This Era of Automation
Northern Counties Soccer Association Nj
Blorg Body Pillow
How To Do A Springboard Attack In Wwe 2K22
New Slayer Boss - The Araxyte
Craglist Oc
Evil Dead Rise Showtimes Near Massena Movieplex
Richard Sambade Obituary
Apnetv.con
What's New on Hulu in October 2023
Tribune Seymour
Comenity Credit Card Guide 2024: Things To Know And Alternatives
Obituary Times Herald Record
Ktbs Payroll Login
Shariraye Update
Things To Do In Atlanta Tomorrow Night
Premier Reward Token Rs3
Peraton Sso
Velocity. The Revolutionary Way to Measure in Scrum
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Melendez Imports Menu
Wemod Vampire Survivors
Shadbase Get Out Of Jail
Gas Buddy Prices Near Me Zip Code
Naval Academy Baseball Roster
As families searched, a Texas medical school cut up their loved ones
Craigslist Northern Minnesota
Anesthesia Simstat Answers
897 W Valley Blvd
Guide to Cost-Benefit Analysis of Investment Projects Economic appraisal tool for Cohesion Policy 2014-2020
Planned re-opening of Interchange welcomed - but questions still remain
Kempsville Recreation Center Pool Schedule
Dtlr On 87Th Cottage Grove
Bt33Nhn
Texas Baseball Officially Releases 2023 Schedule
Muziq Najm
دانلود سریال خاندان اژدها دیجی موویز
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Anguilla Forum Tripadvisor
Pro-Ject’s T2 Super Phono Turntable Is a Super Performer, and It’s a Super Bargain Too
Pink Runtz Strain, The Ultimate Guide
Oklahoma City Farm & Garden Craigslist
Timothy Warren Cobb Obituary
Race Deepwoken
Enter The Gungeon Gunther
Theater X Orange Heights Florida
Stephen Dilbeck, The First Hicks Baby: 5 Fast Facts You Need to Know
El Patron Menu Bardstown Ky
How to Do a Photoshoot in BitLife - Playbite
99 Fishing Guide
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 5902

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.