首页 > 解决方案 > PHP 中的 TRON API 智能合约交易

问题描述

我开始处理 API TRON。我是这个主题的新手。我iexbase/tron-api一般使用图书馆,一切都清楚,但智能合约不清楚。

    public function triggerSmartContract($abi,
                                     $contract,
                                     $function,
                                     $params,
                                     $feeLimit,
                                     $address,
                                     $callValue = 0,
                                     $bandwidthLimit = 0)
{
    $func_abi = [];
    foreach($abi as $key =>$item) {
        if(isset($item['name']) && $item['name'] === $function) {
            $func_abi = $item;
            break;
        }
    }

    if(count($func_abi) === 0)
        throw new TronException("Function $function not defined in ABI");

    if(!is_array($params))
        throw new TronException("Function params must be an array");

    if(count($func_abi['inputs']) !== count($params))
        throw new TronException("Count of params and abi inputs must be identical");

    if($feeLimit > 1000000000)
        throw new TronException('fee_limit must not be greater than 1000000000');


    $inputs = array_map(function($item){ return $item['type']; },$func_abi['inputs']);
    $signature = $func_abi['name'].'(';
    if(count($inputs) > 0)
        $signature .= implode(',',$inputs);
    $signature .= ')';

    $eth_abi = new Ethabi([
        'address' => new Address,
        'bool' => new Boolean,
        'bytes' => new Bytes,
        'dynamicBytes' => new DynamicBytes,
        'int' => new Integer,
        'string' => new Str,
        'uint' => new Uinteger,
    ]);
    $parameters = substr($eth_abi->encodeParameters($func_abi, $params),2);

    $result = $this->tron->getManager()->request('wallet/triggersmartcontract', [
        'contract_address' => $contract,
        'function_selector' => $signature,
        'parameter' => $parameters,
        'owner_address' =>  $address,
        'fee_limit'     =>  $feeLimit,
        'call_value'    =>  $callValue,
        'consume_user_resource_percent' =>  $bandwidthLimit,
    ]);

    if(!isset($result['result'])){
        throw new TronException('No result field in response. Raw response:'.print_r($result,true));
    }
    if(isset($result['result']['result'])) {
        if(count($func_abi['outputs']) >= 0 && isset($result['constant_result'])) {
            return $eth_abi->decodeParameters($func_abi, $result['constant_result'][0]);
        }
        return $result['transaction'];
    }
    $message = isset($result['result']['message']) ?
        $this->tron->hexString2Utf8($result['result']['message']) : '';

    throw new TronException('Failed to execute. Error:'.$message);
}

你能告诉我如何使用这个triggerSmartContract函数,以及在 ABI 参数中传递什么吗?

你能举出一些使用智能合约交易的例子吗?

对 ABI 的形成方式感兴趣吗?

标签: phptron

解决方案


推荐阅读