Python与以太坊交互实战

Python与链上交互

环境

  • Linux VM-0-11-ubuntu 4.4.0-130-generic
  • Python3.6
  • vim 8.0

安装

  • node 和 npm 安装
  • testrpctruffle ,教程里面写的很清楚
  • 安装web3.py

    $ sudo pip3.6 install web3
    • 需要注意的几个点:
      • 必须要python3.5以上,实测3.6 ok
      • 安装过程中报错正常,可能缺少依赖,参考这里
  • 安装pysolc
$ sudo pip3.6 install py-solc

运行

  • 运行testrpc
  • 我们测试最简单的一个合约
pragma solidity ^0.4.4;
contract MyTest {
    function multiply(uint a) public pure returns(uint d) {
        return a * 7;
    }

    function say() public pure returns (string) {
        return "Hello Contract";
    }

    function deposit() returns(address){
        return msg.sender;
    }
}
# -*- coding:utf8 -*-
from web3 import Web3, HTTPProvider
# from web3.contract import ConciseContract
import logging


class BaseEthDao(object):
    def __init__(self, http_addr=''):
        self.web3 = self.get_web3(http_addr)

    def get_web3(self, http_addr):
        if not http_addr:
            http_addr = 'http://localhost:8545'
        return Web3(HTTPProvider(http_addr))

    def to_check_addr(self, addr):
        return Web3.toChecksumAddress(addr)

    def check_addr(self, addr):
        return Web3.isChecksumAddress(addr)

    def get_balance(self, addr):
        try:
            balance = self.web3.eth.getBalance(addr)
            return 0, balance
        except Exception as e:
            return -1, str(e)

contract_dal.py

# -*- coding:utf8 -*-
from base_dao import BaseEthDao
from solc import compile_source


def compile_source_file(file_path):
    with open(file_path, 'rt') as f:
       source = f.read()
    return compile_source(source)


class ContractDal(BaseEthDao):
    def __init__(self, contract_addr="", abi="", http_addr=""):
        super().__init__(http_addr)
        self.addr = contract_addr
        self.abi = abi

    def set_addr(self, addr):
        self.addr = addr

    def set_abi(self, abi):
        self.abi = abi

    def get_contract_instance(self, addr="", abi=""):
        if not addr:
            addr = self.addr
        if not abi:
            abi = self.abi
        if not self.check_addr(addr):
            addr = self.to_check_addr(addr)
        try:
            contract_instance = self.web3.eth.contract(address=addr, abi=abi)
            return 0, contract_instance
        except Exception as e:
            return -1, str(e)

    def get_abi(self, sol_path):
        compiled_sol = compile_source_file(sol_path)
        contract_id, contract_interface = compiled_sol.popitem()
        return contract_interface["abi"]

    def compile_sol(self, file_path):
        compiled_sol = compile_source_file(file_path)
        contract_id, contract_interface = compiled_sol.popitem()
        return contract_id, contract_interface


if __name__ == "__main__":
    contract_dal = ContractDal()
    # addr是合约地址,在truffle部署之后的build文件中找到对应的json文件可以发现里面的address
    code, contract_instance = contract_dal.get_contract_instance(addr='0xd0021ccef861690cf2fbfadec87c10cb666c2719',
                                                                 abi=contract_dal.get_abi('./Greeter.sol'))
    print(contract_instance.functions.say().call())
  • 运行上面代码
$ python3.6 install contract_dal.py

流程走通

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值