Deploying A Smart Contract With An Ethereum Parity Node

Follow

How To Deploy A Smart Contract To Ethereum Parity node Using Web3py

Ethereum Private Parity 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:

Additionally, we provide two scripts which you can find below:

  • The Greeter contract is a very simple example Smart Contract. It allows anybody to set a greeting which is saved immutably on the Blockchain until somebody changes it.
  • The Python script takes the compiled Greeter Contract and deploys it on the Blockchain.

 

Step 1: Copy the scripts

Copy and paste the scripts below into separate files:

  1. Copy the Greeter contract into a file called,  <greeter.sol>.
  2. Copy the Python script into a file called, <deploy.sol>.

 

Step 2: Compile the smart contract

In the directory where you saved the Greeter contract, run the following command:

solc Greeter.sol --combined-json abi,bin --pretty-json > solc-output.json

This compiles the smart contract and saves the result in a JSON file. The contents of that file should look like this :

{
  "contracts" :
  {
"Greeter.sol:Greeter" :
    "abi" : "[{\"constant\":false,\"inputs\":[{\"name\":\"_greeting\",\"type\":\"string\"}],\"name\":\"setGreeting\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"greet\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"greeting\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]", 
    "bin" : "6080604052348015610[...]12e44313242b008a2c43f4e260916d0dcf53b0029" 
}
    }, 
    "version" : "0.5.2+commit.1df8f40c.Darwin.appleclang"
}

The output combines two different results from the compiler:

The ABI (Application Binary Interface) describes how to use the smart contract. This part is necessary to interact with the smart contract once it’s deployed
The BIN (Binary) part contains the compiled smart contract.</code

Next, we will use the Python script to deploy the BIN part to the Blockchain.

Step 3: Deploy the compiled smart contract

We will now focus on the Python script that deploys the smart contract. The script performs multiple steps.

First, it connects to an Ethereum node. This can be any node from a locally running node to a Ganache development node or a Blockdaemon node. In order to connect to a node, please replace the endpoint in the following line:

w3 = Web3(HTTPProvider('[Replace with the node’s RPC endpoint]'))

The endpoint can be found in your node's dashboard, here:

 

eth_priv_connect_menu.jpg

After that, it gets the account ready, from which the smart contract will be deployed. While technically possible we strongly advise to not keep accounts on the nodes to avoid any risk of leaking of the private key. Instead, we use the account to sign the transaction before sending it to the node. This ensures that the private key of the account remains on a local machine rather than the node.

For simplicity sake, we’ve put the key directly in the script. In a production environment, we strongly recommend to save the key in a separate file and load it during the execution of the Python script. That way extra permissions can be set on the key file to prevent unauthorized users from accessing it.

senderKey = input("[Replace with private key]")

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

Please make sure that the account is well funded. Deploying a smart contract costs Ether!

Next, the script loads the compiled smart contract from the previously generated solc output. It then takes that and creates a transaction that deploys the smart contract. The transaction gets signed using the private key from above and gets send to the node.

It usually takes between a few seconds and a few minutes for the transaction to get mined. The script waits for that and prints the address under which the contract is deployed.

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;
       }
}

Python3 code

import sys
import json
from web3 import Web3, HTTPProvider
from web3.contract import ConciseContract

Connect to the Blockdaemon Ethereum endpoint
w3 = Web3(HTTPProvider('https://NODEURL))

Note: To get your private node URL open the connect menu in your dashboard

action_mentu__connect.jpg

 

enode.jpg

 Load the output generated by the solidity compile
if len(sys.argv) <= 1:
print(f"USAGE: python3 {sys.argv[0]} <solc-output.json>") sys.exit(1)
try: 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}")
sys.exit(2)
Get the private key of a pre-funded account
senderKey = input(" D52C7CDE8D579FBBA204717AE1F6765B30CA9FF9B01A9D16F3ACB6EE36ACF233: ")
try: senderAccount = w3.eth.account.privateKeyToAccount(senderKey) except: print("ERROR: Not a valid private key") sys.exit(1)
Get contract data
contractsData = solcOutput["contracts"]

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.