How To Deploy A Smart Contract with An Ethereum Node Using Web3py

Follow

How To Deploy A Smart Contract To Ethereum Using Web3py

Ethereum Public shared Node

So what's a Smart contract?

A smart contract is a virtual agreement that directly controls the transfer of assets or digital currencies between parties signing the contract, under certain conditions.

Precisely, smart contracts are self-executing contracts that are programmed to help you exchange anything of value in a conflict-free, transparent blockchain-based network. They are secure, digital, efficient and eliminate the go-betweens.

A smart contract runs on top of the blockchain network, so they are stored on a public database and cannot be changed. The parties signing the contract agree to follow a set of rules. If and when these predefined rules are met, the agreement is enforced automatically.

To get started deploying a smart contract with Ethereum, you will need to install a few extra tools:

 

Smart contract example and Python3 code deployment process

This process compiles the smart contract inside the Python code.

A simple Greeter contract

pragma solidity ^0.5.0; 
  contract Greeter {
string public greeting;
constructor() public {
greeting = 'Hello';

}
function setGreeting(string memory _greeting) public {
greeting = _greeting;
}

function greet() view public returns (string memory) {
return greeting;
} }ac

 

Python3 Code

import sys

import json

from web3 import Web3, HTTPProvider

from web3.contract import ConciseContract 

 Begin By:

# Connect to the Blockdaemon Ethereum endpoint
  
  >w3 = Web3(HTTPProvider('https:NODE URL*))

*Found in your Blockdaemon dashboard, connect menu

Step 1 load the output

# Load the output generated by the solidity compiler

if len(sys.argv) <= 1:
  
print(f"USAGE: python3 {sys.argv[0]} <solc-output.json>")
  
sys.exit(1)
  
try:A

with open(sys.argv[1]) as inFile:
  
solcOutput = json.load(inFile)
  
except Exception as e:
  
  print(f"ERROR: Cloud not load file {sys.argv[1]}: {e}")

 

Step 2, prepare the account

# Get the private key of a pre-funded account

senderKey = input("Enter account private key (e.g. export from MetaMask*): ")

try:

senderAccount = w3.eth.account.privateKeyToAccount(senderKey)

except:

print("ERROR: Not a valid private key")

>sys.exit(1)

For details on how to generate accounts and export the private key please ...

s# Get contract data

contractsData = solcOutput["contracts"]

Step 3, create and run the transaction

# solc can compile multiple contracts at once. We loop over all of them and deploy them individually

for contractName, contractData in contractsData.items():

># Build transaction to deploy smart contract

contract = w3.eth.contract(abi=contractData['abi'], bytecode=contractData['bin'])

transaction = contract.constructor().buildTransaction()

transaction['nonce'] = w3.eth.getTransactionCount(senderAccount.address) # Get correct transaction nonce for sender from the node

# Sign the transaction

signed = w3.eth.account.signTransaction(transaction, senderAccount.privateKey)

# Send it!

txHash = w3.eth.sendRawTransaction(signed.rawTransaction)

print(f"Contract '{contractName}' deployed; Waiting to transaction receipt")

# Wait for the transaction to be mined, and get the transaction receipt

txReceipt = w3.eth.waitForTransactionReceipt(txHash)


print(f"Contract '{contractName}' deployed to: {txReceipt.contractAddress}")

 

 

watch a step by step video

 

0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.