Ethereum: interacción de contrato inteligente a través de Web3

Ethereum: interacción de contrato inteligente a través de Web3

1. Preparación del entorno

1.1 Instalar dependencias relacionadas

Instalar pip3

sudo apt install python3-pip -y

Use pip3 para instalar el paquete python web3

pip3 install web3

Instalar ipython3

sudo apt install ipython3 -y

1.2 instalar ganache

Descargar ganache

Ingrese el siguiente comando para ejecutar ganache (el contenido después de ./ depende de la versión específica)

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

inserte la descripción de la imagen aquí

1.3 Pruebas

Entrar en el entorno interactivo de Python

ipython3

Ingrese el siguiente código para probar la conexión

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

inserte la descripción de la imagen aquí

2. Crear un nuevo contrato de estudiante

2.1 Configurar la información del contrato

Cree contractsuna nueva carpeta Student.sole ingrese el siguiente contenido:

// 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 Escribir guiones web3

2.2.1 Crear un nuevo archivo Student.py

importar biblioteca

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

Declarar algunas variables globales

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									# 默认账户

Conectar la cadena de prueba

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

Establecer cuenta predeterminada

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

Obtener abi y código de bytes

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()

Implementar el contrato y obtener la dirección del contrato

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)

método principal

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 Compilar contrato y ejecutar

compilar

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

correr

python3 Student.py

inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/cacique111/article/details/126151109
Recomendado
Clasificación