Tron Block Chain PHP Docking Development Kit [TronTool]

Keywords: PHP JSON codec

The TronTool development kit is designed to rapidly increase support for Tron/USDT-TRC20 digital assets for PHP applications in scenarios that use their own Tron block chain nodes as well as in lightweight deployment scenarios based on Tron's official public API services.Official TronTool download address: http://sc.hubwiz.com/codebag/tron-php-lib/.

1. Overview of development packages

The TronTool development kit mainly contains the following features:

  • Supports Tron block chain native Trx transactions
  • Supports Tron smart contracts and TRC20 tokens, such as USDT-TRC20
  • Offline signature to support transactions to avoid disclosing private keys
  • Perfect Tron node API encapsulation, supporting APIs provided by full, solid, and event nodes
  • Supports the use of own or third-party nodes, such as Tron's officially provided public nodes

The TronTool package runs in Php 7.1+ and is currently version 1.0.0. The main classes/interfaces and relationships are shown in the following figure:

The main code file list for TronTool is as follows:

Code File Explain
tron.php/src/TronKit.php Tron Development Package Entry Class
tron.php/src/Trc20.php Tron TRC20 Intelligent Contract Encapsulation Class
tron.php/src/Contract.php Tron Intelligent Contract Encapsulation Class
tron.php/src/Credential.php Tron Block Chain Identity Class for Transaction Signatures
tron.php/src/Address.php Tron Address Representation Class
tron.php/src/TronApi.php Tron Node API Aggregation Encapsulation Class
tron.php/src/NodeClient.php HTTP Protocol Encapsulation Class
demo/NewAddressDemo.php Demonstration code to create a new Tron block chain address
demo/TrxDemo.php Demo code, Trx transfer transactions and balance inquiry
demo/Trc20Demo.php Demo code, Trc20 token transfer, balance inquiry, event monitoring, etc.
demo/DeployContractDemo.php Demo code, deployment of smart contracts
demo/build-contract.php Sample construction script for Trc20 currency contract
demo/contract/EzToken.sol Sample Trc20 currency contract
demo/contract/build/EzToken.abi ABI file for sample Trc20 currency contract
demo/contract/build/EzToken.bin Byte code file for a sample Trc20 currency contract
vendor Third party dependent package directory
composer.json composer profile

2. Use sample code

2.1 Create a new address

Enter the demo code directory at the terminal and execute the following commands:

~$ cd ~/trontool/demo
~/trontool/demo$ php NewAddressDemo.php

The results are as follows:

2.2 Trx Transfer and Balance Query

Enter the demo code directory at the terminal and execute the following commands:

~$ cd ~/trontool/demo
~/trontool/demo$ php TrxDemo.php

The results are as follows:

2.3 Trc20 token transfer, balance inquiry and event monitoring

Enter the demo code directory at the terminal and execute the following commands:

~$ cd ~/trontool/demo
~/trontool/demo$ php Trc20Demo.php

The results are as follows:

2.4 Tron Intelligent Contract Deployment

Enter the demo code directory at the terminal and execute the following commands:

~$ cd ~/trontool/demo
~/trontool/demo$ php DeployContractDemo.php

The results are as follows:

2. Use TronKit

TronKit is the gateway to the development kit, which allows you to quickly implement the following functions:

  • Trx Transfer and Balance Query
  • Trc20 token transfer, authorization, balance inquiry, etc.

2.1 Instantiate TronKit

TronKit instantiation requires passing in a TronApi object and a Reential object, which encapsulate the API provided by the Tron node and the identity information of the user signing the transaction.

For example, the following code creates a TronKit instance that connects to the Tron main chain and signs the transaction using the specified private key:

use TronTool\TronKit;
use TronTool\TronApi;
use TronTool\Credential;

$kit = new TronKit(
  TronApi::mainNet(),                                       //Access Main Chain
  Credential::fromPrivateKey('87c12d....d435')              //Use the specified private key
);

2.2 Trx Transfer and Balance Query

Use TronKit's sendTrx() method for Trx transfers, such as sending 1000 TRX:

$to = 'TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx';                 //Transfer destination address
$amount = 1000000000;                                       //Transfer amount in SUN
$ret = $kit->sendTrx($to,$amount);                          //Submit Trx Transfer Transaction
echo 'txid => ' . $ret->tx->txID .  PHP_EOL;                //Show transaction ID
echo 'result => ' . $ret->result . PHP_EOL;                 //Show transaction results

Note: The amount unit needs to be converted to SUN, 1 TRX = 1000000 SUN.

Use the getTrxBalance() method to query the Trx balance for the specified address, for example:

$addr = 'TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx';               //Tron address to query
$balance = $kit->getTrxBlanace($addr);                      //Query Trx balance in SUN
echo 'trx balance => ' . $balance . PHP_EOL;                //Show balance

2.3 TRC20 token transfer

Use the Trc20() method to obtain an instance of a specified TRC20 token contract, and then invoke the transfer() method of the contract to make a TRC20 token transfer.For example, the code below specifies a USDT-TRC20 token of 1315,300 minimum units to be transferred between addresses, i.e. 1.3153 USDT:

$to = 'TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx';                 //Transfer destination address
$amount = 1315300;                                          //Transfer amount in Trc20 currency
$contractAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'     //Deployment address of USDT-TRC20 token contract
$usdt = $kit->Trc20($contractAddress);                      //Create an instance of a Trc20 currency contract
$ret = $usdt->transfer($to,$amount);                        //Transfer Trc20 currency
echo 'txid => ' . $ret->tx->txID .  PHP_EOL;                //Show transfer transaction ID
echo 'result => ' . $ret->result . PHP_EOL;                 //Show transfer results

2.4 TRC20 Currency Balance Query

Use the Trc20() method to get an instance of the specified TRC20 token contract, and then call the balanceOf() method of the contract to query the TRC20 token balance at the specified address.For example, the following code queries the USDT token balance for a specified address:

$usdt = $kit->Trc20('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t');          //Create an instance of USDT-TRC20 token contract
$balance = $usdt->balanceOf('TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx');  //Query Trc20 Currency Balance
echo 'usdt balance => ' . $balance . PHP_EOL;                       //Show token balance

2.5 TRC20 token event query

Get the specified TRC20 token contract instance using the Trc20() method, and then call the events() method of the contract to query for the specified contract trigger event.

For example, query the last 10 seconds of USDT token contracts:

$usdt = $kit->Trc20('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t');    //Create an instance of a Trc20 currency contract
$since = time() - 10000;                                      //Calculate checkpoint
$events = $usdt->events($since);                              //Extract Contract Events
foreach($events as $event){                                   
  echo 'block height => ' . $event->block_number . PHP_EOL;   //Show event triggered block height
  echo 'event name => ' . $event->event_name . PHP_EOL;       //Show event name
}  

The result returned by events() is an array of event objects, with the main fields of each member object described as follows:

  • caller_contract_address: Call contract address, base58 format
  • transaction_id: The transaction ID that triggers the contract event, a hexadecimal string
  • result: list of contract event parameters, array
  • result_type: List of contract event parameter types, array
  • block_timestamp: Block timestamp, integer where the event is located
  • block_number: Block number where the event is located, integer
  • event_name: Event name, string
  • contract_address: Contract address, base58 format
  • event_index: Event index ordinal, integer

For example, here is a JSON representation of the Transfer event object for a TRC20 token contract, giving the event name in the event_name field and event parameters in the result field in two indexed forms:

{
  "caller_contract_address": "TS2Hzo6KpAc8Ym2nGb3idpMtUpM2GiK2gL",
  "transaction_id": "265cf378f4943b7c77b7a294f533d4b8c718c297dd28a664848d77cd3f3a0af0",
  "result": {
    "0": "0x2539ef4f3eb733c105a957eebb20fd60ad8c9a43",      //Event parameter 0
    "1": "0x6f6794f3904ff51f9fa81e928afdec91f6744a50",      //Event parameter 1
    "2": "8",                                               //Event parameter 2        
    "_from": "0x2539ef4f3eb733c105a957eebb20fd60ad8c9a43",  //Event parameter_from
    "_value": "8",                                          //Event parameter_value
    "_to": "0x6f6794f3904ff51f9fa81e928afdec91f6744a50"     //Event parameter_to
  },
  "result_type": {
    "_from": "address",                                     
    "_value": "uint256",
    "_to": "address"
  },
  "block_timestamp": 1586263455000,
  "block_number": 3539438,
  "event_name": "Transfer",                                 //Event Name   
  "contract_address": "TS2Hzo6KpAc8Ym2nGb3idpMtUpM2GiK2gL",
  "event_index": 0
}

3. Tron Block Chain Identity and Address Representation

In TronTool, Credential is used to characterize a user identity in the Tron block chain, and Address is used to characterize an address in the Tron block chain.The difference is that Credential contains the user's private key information and can be used to sign transactions, so it needs to be protected, whereas Address is publicly available information.

Create a new account using the static method create() of the Credential class.For example, the following code creates a new account and displays its private key, public key, and address:

use TronTool\Credential;

$credential = Credential::create();                           //Create a New Account
echo 'private key => ' . $credential->privateKey() . PHP_EOL; //Show private key
echo 'public key => ' . $credential->publicKey() . PHP_EOL;   //Show Public Key
echo 'address => ' . $credential->address() . PHP_EOL;        //display address

Credential can be instantiated by importing an existing private key using the static method fromPrivateKey().For example, the following code imports an existing private key and displays the address:

use TronTool\Credential;

$credential = Credential::fromPrivateKey('7889...023a');      //Import an existing private key
echo 'address => ' . $credential->address() . PHP_EOL;        //Show the corresponding address

In the Tron block chain, there are two representations of addresses: hexadecimal and base58, such as the following two representations of the same address:

  • base58: TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx
  • Hexadecimal: 412539EF4F3EB733C105A957EEBB20FD60AD8C9A43

The Address class contains the corresponding codec logic to instantiate Address from different forms of addresses.For example:

$a1 = Address::fromBase58('TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx');
echo $a1->hex() . PHP_EOL;        //Output: 412539EF4F3EB733C105A957EEBB20FD60AD8C9A43

$a2 = Address::fromHex('412539EF4F3EB733C105A957EEBB20FD60AD8C9A43');
echo $a2->base58() . PHP_EOL;     //Output: TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx

Sometimes we just need to simply convert the Address between base58 and 16. Instead of the intermediate Addresses object, we can use the static methods encode() and decode() directly.For example:

$a1 = Address::decode('TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx');
echo $a1 . PHP_EOL;             //Output: 412539EF4F3EB733C105A957EEBB20FD60AD8C9A43

$a2 = Address::encode('412539EF4F3EB733C105A957EEBB20FD60AD8C9A43');
echo $a2 . PHP_EOL;             //Output: TDN3QY85Jft3RwgyatjRNmrwRmwkn8qwqx

4. Use TronApi to access Tron Node API

Use TronApi to access Tron's various node APIs.TronApi aggregates APIs provided by a variety of Tron nodes, such as Tron full node, solidity node, and event service node.

When instantiating TronApi, you can specify different connection URL s for different types of Tron nodes, for example:

use TronTool\TronApi;

$tc = new TronApi(
  'https://api.trongrid.io', //Full Node URL
  'https://api.trongrid.io', //Contract Node URL
  'https://api.trongrid.io'//Event Node URL
);

When the URL s of these three nodes are the same, they can be abbreviated as:

$tc = new TronApi('https://api.trongrid.io');

If the TronGrid node provided by Tron is used, then two static functions mainNet() and testNet() provided by Tron Api can be used directly to join the main chain and the shasta test chain, respectively.

For example, the following code is equivalent:

$tc = new TronApi('https://api.trongrid.io');
$tc = TronApi::mainNet();                       //Equivalent to above

$tc = new TronApi('https://api.shasta.trongrid.io');
$tc = TronApi::testNet();                       //Equivalent to above

TronApi encapsulates the API s provided by Tron's official multiple nodes and maintains a basic relationship for easy discovery and utilization.For example, query the TRX balance of an account:

$info = $tc->getAccount('TEgM5CPeqowkKUXoKrFrpvB7vcBgVkD4tP');  //Query account information
echo 'balance -> ' . $info->balance . PHP_EOL;                  //Show account balance  

Tron Block Chain Docking PHP Development Kit: http://sc.hubwiz.com/codebag/tron-php-lib/

Posted by bmbc on Thu, 09 Apr 2020 18:42:42 -0700