Ethereum: Smart Contract Interaction via Web3

Ethereum: Smart Contract Interaction via Web3

1. Environment preparation

1.1 Install related dependencies

​ Install pip3

sudo apt install python3-pip -y

​ Use pip3 to install the web3 python package

pip3 install web3

Install ipython3

sudo apt install ipython3 -y

1.2 install ganache

​ Download ganache

​ Enter the following command to run ganache (the content after ./ depends on the specific version)

./ganache-2.5.4-linux-x86_64.AppImage &

insert image description here

1.3 Testing

​ Enter the Python interactive environment

ipython3

​ Enter the following code to test the connection

from web3 import Web3
w3 = Web3(Web3.HTTPProvider("http://localhost:7545"))
w3.isConnected()

insert image description here

2. Create a new student contract

2.1 Configure contract information

​ Create contractsa new folder Student.soland enter the following content:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.16 <0.9.0;

contract Student{

    string name;

    constructor() {
        // name = _name;
        name = "Tom";
    }

    function getName() public view returns (string memory) {
        return name;
    }

}

2.2 Writing web3 scripts

2.2.1 Create a new Student.py file

​ import library

from web3 import Web3
import os
import sys
import getopt
import uuid

​ Declare some global variables

url = "http://localhost:7545"   				# 以太坊测试链 rpc 连接端口
contract_address_file = 'contract_student.txt'  # 合约地址保存文件
abi_file = "Student/Student.abi"  				# abi 文件
bytecode_file = "Student/Student.bin"  			# 字节码文件
account_id = 0									# 默认账户

​ Connect the test chain

# 连接测试链
w3 = Web3(Web3.HTTPProvider(url))   
eth = w3.eth
print("eth connect:", w3.isConnected())

​ Set default account

def set_default_account():
    """
        设置调用合约、发送交易的账户
    """
    global account_id
    eth.defaultAccount = eth.accounts[account_id]

​ Get abi and bytecode

def get_abi_from_file(file):
    """
       从文件中获取abi
    """
    with open(file, 'r') as f:
        return f.read() 

def get_bytecode_from_file(file):
    """
        从文件中获取字节码
    """
    with open(file, 'r') as f:
        return "0x" + f.read()

​ Deploy the contract and get the contract address

def deploy_contract(abi, bytecode):
    """
        部署合约
    """
    contract = eth.contract(abi=abi, bytecode=bytecode)     # 创建合约
    tx_hash = contract.constructor().transact()             # 部署合约(发送构造函数的交易,需相对应合约中的参数)
    tx_receipt = eth.waitForTransactionReceipt(tx_hash)     # 等待交易回执
    print("contract address:", tx_receipt.contractAddress)  # 合约地址
    # 保存合约
    global contract_address_file
    with open(contract_address_file, "w") as f:
        f.write(tx_receipt.contractAddress)
    # 通过地址获取已部署合约
    deployed_contract = eth.contract(address=tx_receipt.contractAddress, abi=abi)
    return deployed_contract

def get_deployed_contract(abi, bytecode):
    """
        获取部署合约,如果本地已保存合约地址,则调用该地址的合约,否则重新创建一个新的合约
    """
    try:
        # 尝试获取已有合约
        with open(contract_address_file, "r") as f:
            contract_address = f.read()
        print("contract address:", contract_address)
        deployed_contract = eth.contract(address=contract_address, abi=abi)
        return deployed_contract
    except IOError:
        # 获取已有合约失败则重新部署新合约
        return deploy_contract(abi, bytecode)

​ main method

if __name__ == '__main__':
    set_default_account()
    abi = get_abi_from_file(abi_file)
    bytecode = get_bytecode_from_file(bytecode_file)
    deployed_contract = get_deployed_contract(abi, bytecode)
    print(deployed_contract.functions.getName().call())

2.2.2 Compile contract and run

​ Compile

solc --abi --bin --overwrite -o Student Student.sol 

​ run

python3 Student.py

insert image description here

Guess you like

Origin blog.csdn.net/cacique111/article/details/126151109