andelf / tronpy

TRON Python Client Library.
MIT License
212 stars 96 forks source link

calculate the bandwidth #128

Closed pendejo-dev closed 8 months ago

pendejo-dev commented 8 months ago

I'm trying to calculate the bandwidth commission, but I don't get the figure completely correct, what could I be wrong about?

` async def get_estimated_bandwidth(self, owner_address: str, to_address: str, amount: int): contract = await self.client.get_contract(TRC20_CONTRACT_ADDRESS) txn = await contract.functions.transfer(to_address, amount * 1000000) with_owner = await txn.with_owner(owner_address).fee_limit(35_000_000).build()

    value = with_owner.to_json()["raw_data"]["contract"][0]["parameter"]["value"]
    data = bytes.fromhex(value['data'])

    function = contract.get_function_by_selector(data[:4])
    params = trx_abi.decode(["address", "uint256"], data[4:])

    constant_contract_result = await self.client.trigger_constant_contract(
        owner_address=owner_address,
        contract_address=TRC20_CONTRACT_ADDRESS,
        function_selector='transfer(address,uint256)',
        parameter=function._prepare_parameter(*params)
    )

    private_key_to_bytes = PrivateKey(bytes.fromhex("PrivateKey"))
    sign = with_owner.sign(private_key_to_bytes)
    raw_data_hex = constant_contract_result['transaction']["raw_data_hex"]

    # Получаем длину raw_data_hex
    raw_data_hex_length = len(raw_data_hex)

    # Получаем длину каждой подписи и суммируем их
    signature_lengths = [len(signature) for signature in sign.to_json()["signature"]]
    total_signature_length = sum(signature_lengths)

    # Суммируем общую длину
    total_length = raw_data_hex_length + total_signature_length

    # Округляем и добавляем 68
    how_many_bandwidth_need = round(total_length / 2) + 68

    return how_many_bandwidth_need`
MrNaif2018 commented 8 months ago

You can't calculate it like that. Use trontxsize package: https://github.com/bitcart/trontxsize