andelf / tronpy

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

Added blockNumber parameter for trigger_constant_contract #138

Open joseddg92 opened 3 weeks ago

joseddg92 commented 3 weeks ago

Despite being undocumented, (it does not appear in https://developers.tron.network/reference/triggerconstantcontract) there is a blockNumber paramter that can be used to retrieve the return value of a SmartContract in old blocks.

This could be added to Tron.py trigger_constant_contract like below. If the developer sees it OK, I could event send the pull request. Of course, ContractMethod.call method would also need adaptation so that this can be called from instantiated Contracts easily.

def trigger_constant_contract(
    self,
    owner_address: TAddress,
    contract_address: TAddress,
    function_selector: str,
    parameter: str,
    blockNumber: Union[int, str]
) -> dict:
    body = {
            "owner_address": keys.to_base58check_address(owner_address),
            "contract_address": keys.to_base58check_address(contract_address),
            "function_selector": function_selector,
            "parameter": parameter,
            "visible": True,
        }
    if blockNumber:
            body["blockNumber"] = blockNumber
    ret = self.provider.make_request(
        "wallet/triggerconstantcontract",
        body,
    )
    self._handle_api_error(ret)
    if "message" in ret.get("result", {}):
        msg = ret["result"]["message"]
        result = ret.get("constant_result", [])
        try:
            if result and len(result[0]) > (4 + 32) * 2:
                error_msg = tron_abi.decode_single("string", bytes.fromhex(result[0])[4 + 32 :])
                msg = f"{msg}: {error_msg}"
        except Exception:
            pass
        raise TvmError(msg)
    return ret