Web3py 1 - Start a Blockchain

By Sheldon L Published at 2020-02-09 Updated at 2020-02-09


Part 1

# check if it is authed
curl https://mainnet.infura.io/v3/8fa5e8ad9f914ec1867eadfbf93b1de0 \
-X POST \
-d '{"id": 1,"jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params":["latest", false]}'
export all_proxy=socks5://127.0.0.1:1080
conda create --name web3 python=3.8
conda activate web3
export all_proxy=""
pip install pysocks
export all_proxy=socks5://127.0.0.1:1080
pip install web3
python
from web3 import Web3
infura_url = "https://mainnet.infura.io/v3/8fa5e8ad9f914ec1867eadfbf93b1de0"    #`ENDPOINT` link start with `https://`
web3 = Web3(Web3.HTTPProvider(infura_url))
web3.isConnected()
web3.eth.blockNumber

balance = web3.eth.getBalance("0xfF0F5c90C28288730348867e464672C81d45E43A")    # metamask account
web3.fromWei(balance, 'ether')
cd $hub/mysite_test
mkdir blockchain-web3
cd blockchain-web3
touch app.py
touch requirements.txt

# open in project
from web3 import Web3


infura_url = "https://mainnet.infura.io/v3/8fa5e8ad9f914ec1867eadfbf93b1de0"

web3 = Web3(Web3.HTTPProvider(infura_url))
print(web3.isConnected())
print(web3.eth.blockNumber)

balance = web3.eth.getBalance("0xfF0F5c90C28288730348867e464672C81d45E43A")
print(web3.fromWei(balance, 'ether'))
python app.py

Part 2

import json
from web3 import Web3

# test connection
infura_url = "https://mainnet.infura.io/v3/8fa5e8ad9f914ec1867eadfbf93b1de0"

web3 = Web3(Web3.HTTPProvider(infura_url))
print(web3.isConnected())

# address is the smart contract deployed
address = "0xdAC17F958D2ee523a2206206994597C13D831ec7"

# the example in etherscan:
# abi is a json / array of the smart contract
# `https://etherscan.io/adress/0xdac17f958d2ee523a2206206994597c13d831ec7#code`
# find `Contract ABI`, copy
abi = json.loads(
    '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_upgradedAddress","type":"address"}],"name":"deprecate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"deprecated","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_evilUser","type":"address"}],"name":"addBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"upgradedAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"maximumFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_maker","type":"address"}],"name":"getBlackListStatus","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newBasisPoints","type":"uint256"},{"name":"newMaxFee","type":"uint256"}],"name":"setParams","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"issue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"redeem","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"basisPointsRate","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"isBlackListed","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_clearedUser","type":"address"}],"name":"removeBlackList","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"MAX_UINT","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_blackListedUser","type":"address"}],"name":"destroyBlackFunds","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_initialSupply","type":"uint256"},{"name":"_name","type":"string"},{"name":"_symbol","type":"string"},{"name":"_decimals","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Issue","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"amount","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newAddress","type":"address"}],"name":"Deprecate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"feeBasisPoints","type":"uint256"},{"indexed":false,"name":"maxFee","type":"uint256"}],"name":"Params","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_blackListedUser","type":"address"},{"indexed":false,"name":"_balance","type":"uint256"}],"name":"DestroyedBlackFunds","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"AddedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"_user","type":"address"}],"name":"RemovedBlackList","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"}]'
)

contract = web3.eth.contract(address=address, abi=abi)
print(contract)

# check the `Read Contract`, `Holders`, ...,  tabs
totalSupply = contract.functions.totalSupply().call()
name = contract.functions.name().call()
symbol = contract.functions.symbol().call()
holder_1 = contract.functions.balanceOf("0xdAC17F958D2ee523a2206206994597C13D831ec7").call()

print(web3.fromWei(totalSupply, 'ether'))
print(name)
print(symbol)
print(web3.fromWei(holder_1, 'ether'))

Part 3

import json
from web3 import Web3


# connect
ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))

print(web3.isConnected())
print(web3.eth.blockNumber)


# transact currency from account_1 to account_2
account_1 = "0x560B1b0E246E075eE1F6848dD40237C4cF46545c"
account_2 = "0x4267AC0eaAb772fbFCa668049406e0624F46d809"

private_key_1 = "020b98db75b8378277bb7f9d82d6d12b56d7b44f0473b77794d9006ec88270ac"

# get the nonce
nonce = web3.eth.getTransactionCount(account_1)

# build the transaction
tx = {
    'nonce': nonce,
    'to': account_2,
    'value': web3.toWei(1, 'ether'),
    'gas': 2000000,
    'gasPrice': web3.toWei('50', 'gwei'),
}

# sign the transaction
signed_tx = web3.eth.account.signTransaction(tx, private_key_1)

# send the transaction
tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)

# get transaction hash
print(tx_hash)

Part 4 - Build Ethereum Dapps

import json
from web3 import Web3


# connect
ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))

web3.eth.defaultAccount = web3.eth.accounts[0]

print(web3.isConnected())
print(web3.eth.blockNumber)


# Address
address = "0xFFfa8b353495170ECa8c6265452c1CD18bb065E3"
# or checksum address if all in lowercase
#address = Web3.toChecksumAddress("0xfffa8b353495170eca8c6265452c1cd18bb065e3")

abi = json.loads('[{"inputs":[],"name":"retreive","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"name":"store","outputs":[],"stateMutability":"nonpayable","type":"function"}]')

contract = web3.eth.contract(address=address, abi=abi)

storage_before = contract.functions.retreive().call()
print('storage =', storage_before)

tx_hash = contract.functions.store(1).transact()
print('tx_hash = {}'.format(tx_hash))

web3.eth.waitForTransactionReceipt(tx_hash)
storage_after = contract.functions.retreive().call()
print('storage =', storage_after)

Part 5 - Create Smart Contract 1

import json
from web3 import Web3


# connect
ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))

web3.eth.defaultAccount = web3.eth.accounts[0]

print(web3.isConnected())
print(web3.eth.blockNumber)


abi = json.loads('[{"inputs":[],"name":"retreive","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"num","type":"uint256"}],"name":"store","outputs":[],"stateMutability":"nonpayable","type":"function"}]')
bytecode = "608060405234801561001057600080fd5b5060c78061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80636057361d146037578063b05784b8146062575b600080fd5b606060048036036020811015604b57600080fd5b8101908080359060200190929190505050607e565b005b60686088565b6040518082815260200191505060405180910390f35b8060008190555050565b6000805490509056fea264697066735822122078fcdd186f07e48f2aee328c99bd40f9d5f25425a57536fb1cda58aaa09ecec264736f6c63430006010033"

# construct
Storage = web3.eth.contract(abi=abi, bytecode=bytecode)

tx_hash = Storage.constructor().transact()
print(tx_hash)

tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
address = tx_receipt.contractAddress
print(address)

# contract
contract = web3.eth.contract(address=address, abi=abi)

storage_before = contract.functions.retreive().call()
print('storage =', storage_before)

# transact
tx_hash = contract.functions.store(1).transact()
print('tx_hash = {}'.format(tx_hash))

tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
address = tx_receipt.contractAddress
print(address)

storage_after = contract.functions.retreive().call()
print('storage =', storage_after)

Part 6 - Create Smart Contract 2

import json
from web3 import Web3


# test connection
infura_url = "https://mainnet.infura.io/v3/8fa5e8ad9f914ec1867eadfbf93b1de0"
web3 = Web3(Web3.HTTPProvider(infura_url))
print(web3.isConnected())


print('example 1')
latest_block_number = web3.eth.blockNumber
print(latest_block_number)
latest_block_detail = web3.eth.getBlock(latest_block_number)
print(latest_block_detail)


print('example 2')
for i in range(0,10):
    block_num = latest_block_number - i
    print(block_num)


print('example 3')
hash = '0x6fa5c295c997c1c90970ea7eacb3d78f7dea147837db96067164d2db1e322396'   # block hash
block = web3.eth.getTransactionByBlock(hash, 2)
print(block)

Part 7 - Create Account without Metamask

from web3 import Web3


# test connection
infura_url = "https://mainnet.infura.io/v3/8fa5e8ad9f914ec1867eadfbf93b1de0"
web3 = Web3(Web3.HTTPProvider(infura_url))
print(web3.isConnected())

web3 = Web3(Web3.HTTPProvider(infura_url))
web3.eth.account.create()
print(account)
print(account.)

print(account.privateKey)    # DANGEROUS!
# should encrypt key:
keystore = account.encrypt('password')
print(keystore)    # can keep this in a private file
print(web3.eth.account.decrypt(keystore, 'password'))