python调用智能合约以及操作区块链的相关方法

官方文档:https://tronpy.readthedocs.io/en/latest/quickstart.html#using-tronpy

以下代码仅提供了示例

python调用智能合约

 pip install tronpy
from tronpy import Tron
from tronpy.keys import PrivateKey
from tronpy.exceptions import TvmError


class Contract:

    def __init__(self):
        # 实例化一个客户端  network是选择的网络 从主网或测试网中进行选择
        self.client = Tron(network='shasta', conf={
     'timeout': 10})
        # 连接智能合约
        self.connect_contract = self.client.get_contract(smart_contract_addr)
        print('合约连接成功')
        # 获取合约里所有的方法
        self.all_functions = self.connect_contract.functions
        print('获取合约里的全部方法')

    @staticmethod
    def sign(user_addr, pri_key, methods):
        """
        签名
        :param user_addr: 用户钱包地址
        :param pri_key: 钱包私钥
        :param methods: 执行的方法   例如:self.all_functions.userRegister('钱包地址')
        :return:
        """
        private_key = PrivateKey(bytes.fromhex(pri_key))
        txn = (methods
               .with_owner(user_addr)  # address of the private key
               .fee_limit(1000000000) # 这里最高写 1000_000_000
               .build()
               .sign(private_key)  # 用私钥签署交易
               )
        try:
            result = txn.broadcast().result()  # 将交易广播到TRON网络  等待合同调用结果
            return result
        except TvmError as e:
            return e
            
    def get_periods(self):
        """获取当前期数(阅读合约调用的方式)"""
        response = self.connect_contract.functions.period()
        print("当前期数:{}".format(response))

    def user_register(self, user_addr, pri_key, ref_addr):
        """
        注册  (编写合约调用的方式)
        :param user_addr: 注册用户的点钱包地址
        :param pri_key: 钱包的私钥
        :param ref_addr: 上级用户钱包地址
        :return:
        """
        msg = '用户注册'
        method = self.all_functions.userRegister(ref_addr)
        result = self.sign(user_addr=user_addr,
                           pri_key=pri_key, methods=method)
        if result is None:
            print('{}:注册成功'.format(user_addr))
        else:
            print('{}:{}'.format(msg, result))

操作区块链的相关方法

from tronpy import Tron
from tronpy.keys import PrivateKey
from tronpy.exceptions import AddressNotFound


class HttpClient:

    def __init__(self):
        """实例化一个客户端"""
        self.client = Tron(network='shasta', conf={
     'timeout': 30})

    def get_user_addr_balance(self, addr):
        """获取钱包trx余额"""
        response = self.client.get_account_balance(addr)
        return response

    def create_address(self):
        """创造一个钱包地址"""
        response = self.client.generate_address()
        return response

    def hex_address(self, addr):
        """将任何格式的地址转换为十六进制格式"""
        response = self.client.to_hex_address(addr)
        return response

    def create_transaction(self, from_pri_key, from_addr, to_addr, amount=500_000_000):
        """
        转账
        :param to_addr: 接收人地址
        :param from_pri_key: 转账人私钥
        :param from_addr: 转账人地址
        :param amount: 转账数量
        :return:
        """
        private_key = PrivateKey(bytes.fromhex(from_pri_key))
        txn = (
            self.client.trx.transfer(from_addr, to_addr, amount)
                .build()
                .inspect()
                .sign(private_key)
                .broadcast()
        )
        if txn:
            print('向{}转账成功!'.format(to_addr))

你可能感兴趣的:(区块链,区块链,python,tronpy,智能合约,python调用智能合约)