Open In App

Deploy a Smart Contract on Ethereum with Python, Truffle and web3py

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

This article discusses deploying a Smart Contract on Ethereum with Python, Truffle, and web3py.

Prerequisite: In order to write a simple smart contract, deploy it to a personal Ethereum blockchain, and call the contract using Python3, install the below software on a PC:

1. Python3 v3.5.3 or later versions: Install python following the instructions here. If python is already installed in the system, then check the version using the following command on the command prompt or Windows Powershell(In Windows) or Terminal(In Mac):

python –version

2. NodeJS v8.9.4 or later: Install NodeJs following the instructions here. If NodeJS is installed in the system, then check its version using the following command on the command prompt or Windows Powershell(In Windows) or Terminal(In Mac):-

node -v

Upon installing the above-mentioned Programming Language and Runtime Environment in your system, we are ready to move forward with deploying the smart contract.

Approach

The entire process is divided into 4 major sections:

  1. Setting up the Project: This involves installing necessary frameworks like Truffle.
  2. Scripting the Smart Contract: This step involves writing a smart contract in the solidity programming language. 
  3. Deploying the Smart Contract to the Blockchain: This involves deploying the smart contract to the Ethereum Blockchain using Truffle.
  4. Using Python to Call the Deployed Smart Contract: This involves calling the smart contract using a python code and web3.

Let’s discuss each of these steps in detail.

Step 1: Setting up the Project

1. The first step is to make a directory for the project. Open the command prompt or equivalent software on the system and execute the following commands:

mkdir geeks-eth

mkdir command is used to make directories/folders on your system.

2. Inside the recently made geeks-eth folder, install truffle(globally). A truffle is a popular tool for making smart contracts, a testing framework aiming to make the life of Ethereum developers easier.

cd geeks-eth

npm install g-truffle

Install Truffle

 

3. After the successful installation of truffle, use the truffle CLI tool to initialize an empty smart contract project:

truffle init

The command will create a project structure for us to set up and start the project. Output like this will be visible when the initialization operation is successful.

Successful installation of truffle

Initialization

The above command will create the following structure:

  • contracts/: Directory for solidity contracts source code.
  • migrations/: Directory for contracts migration files.
  • test/: Directory for test files. 
  • truffle.js: Truffle configuration files.

Step 2: Scripting the Smart Contract

1. Open the folder geeks-eth, which was just created and initialized. In the folder, find a folder named contracts/. In that folder, create and write a new solidity document which can be done using an IDE. Let’s say we create a solidity document gfg.sol and start scripting in it.

Solidity




// Solidity program to print
// message
pragma solidity >= 0.5.0 < 0.9.0;
 
contract gfg{
  function geeks() public pure returns (string memory)
  {
    return 'Hey there! I m learning from GeeksForGeeks!';
  }
}


2. After writing the code next task is to compile the solidity code. Here, the truffle will be used to compile the contract from the project root folder. Hence open the command prompt again to run the following commands:

truffle compile

3. Compilation takes a few seconds. After compilation is completed, a message like “Compiled successfully using:” will be displayed. It will output the compiled contract gfg.sol as gfg.json inside build/contracts -> gfg.json.

4. Since we have compiled a contract, it can be now deployed to our running blockchain(local).

Step 3: Deploying Smart Contract to the Blockchain

In order to deploy a smart contract to the blockchain migration script and truffle suite are required.

1. A migration script:

  • For the migration script, let us create a JavaScript file named 2_deploy_contract.js inside the migrations folder.
  • Then write migration script in that JS document as done below:

Javascript




var gfg = artifacts.require("gfg");
 
module.exports = function(deployer) {
    deployer.deploy(gfg);
};


2. Truffle suite contains its own blockchain that we can use for testing purposes. 

  • Open CMD(terminal) and run:

truffle develop

3. Upon running the above command, find an output similar to:

Running truffle suite

 

4. Upon getting the above output, migrate the smart contract by using the command migrate:

truffle(develop)> migrate

Migrate command calls each migration in migrations/, deploying the contracts to the blockchain(local).

5. Upon running the migrate command see an output like:

Migrate command

Smart Contract deployed on our personal Ethereum blockchain

Explanation:

  • transaction hash: acts as a reference number for the parties involved in the transaction.
  • contract address: address on the Ethereum network hosting this contract instance.
  • account: An Ethereum account is an entity with an ether (ETH) balance that can send transactions on Ethereum.

Step 4: Using Python to call the Deployed Contract

1. In root folder “geeks-eth/” create a python file alongside other folders. Code using python so the smart contract that is deployed can be called:

Python




# Python program to call the
# smart contract
import json
from web3 import Web3, HTTPProvider
 
# truffle development blockchain address
blockchain_address = 'http://127.0.0.1:9545'
 
# Client instance to interact with the blockchain
web3 = Web3(HTTPProvider(blockchain_address))
 
web3.eth.defaultAccount = web3.eth.accounts[0]
 
# Setting the default account (so we don't need
#to set the "from" for every transaction call)
 
# Path to the compiled contract JSON file
compiled_contract_path = 'build/contracts/gfg.json'
 
# Deployed contract address (see `migrate` command output:
# `contract address`)
# Do Not Copy from here, contract address will be different
# for different contracts.
deployed_contract_address = '0x15C667a5b0a3e6600AB50F88bF438180A4233879'
 
# load contract info as JSON
with open(compiled_contract_path) as file:
    contract_json = json.load(file
     
    # fetch contract's abi - necessary to call its functions
    contract_abi = contract_json['abi']
 
# Fetching deployed contract reference
contract = web3.eth.contract(
    address = deployed_contract_address, abi = contract_abi)
 
# Calling contract function (this is not persisted
# to the blockchain)
output = contract.functions.geeks().call()
 
print(output)


2. After scripting the python code, open the terminal to finally call the Smart contract. Before that, install the web3 python library using the pip command.

pip install web3

3. It may take a few seconds, but once completed, we will be ready to call our Smart Contract.

python my_app.py

Smart contract output

Output from our Smart Contract

As in the smart contract (gfg.sol) we coded the message “Hey there! I am learning from GeeksForGeeks !”, the same is displayed as output when the smart contract is called using python.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads