Repository: Fenguoz/tron-php
Branch: master
Commit: fff2b4316740
Files: 19
Total size: 38.6 KB
Directory structure:
gitextract_q3mnkphk/
├── .gitignore
├── LICENSE
├── README-CN.md
├── README.md
├── composer.json
├── src/
│ ├── Address.php
│ ├── Api.php
│ ├── Block.php
│ ├── Exceptions/
│ │ ├── TransactionException.php
│ │ └── TronErrorException.php
│ ├── Interfaces/
│ │ └── WalletInterface.php
│ ├── Support/
│ │ ├── Formatter.php
│ │ ├── Key.php
│ │ └── Utils.php
│ ├── TRC20.php
│ ├── TRX.php
│ └── Transaction.php
└── tests/
├── TRC20Test.php
└── TRXTest.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.idea
vendor
*.lock
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2021 Fenguoz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README-CN.md
================================================
[English](./README.md) | 中文
<h1 align="center">TRON-PHP</h1>
<p align="center">
<a href="https://github.com/Fenguoz/tron-php/releases"><img src="https://poser.pugx.org/Fenguoz/tron-php/v/stable" alt="Stable Version"></a>
<a href="https://www.php.net"><img src="https://img.shields.io/badge/php-%3E=7.2-brightgreen.svg?maxAge=2592000" alt="Php Version"></a>
<a href="https://github.com/Fenguoz/tron-php/blob/master/LICENSE"><img src="https://img.shields.io/github/license/fenguoz/tron-php.svg?maxAge=2592000" alt="tron-php License"></a>
<a href="https://packagist.org/packages/Fenguoz/tron-php"><img src="https://poser.pugx.org/Fenguoz/tron-php/downloads" alt="Total Downloads"></a>
</p>
## 概述
TRON-PHP 目前支持波场的 TRX 和 TRC20 中常用生成地址,发起转账,离线签名等功能。
## 特点
1. 一套写法兼容 TRON 网络中 TRX 货币和 TRC 系列所有通证
1. 接口方法可可灵活增减
## 支持方法
- 生成地址 `generateAddress()`
- 验证地址 `validateAddress(Address $address)`
- 根据私钥得到地址 `privateKeyToAddress(string $privateKeyHex)`
- 查询余额 `balance(Address $address)`
- 交易转账(离线签名) `transfer(Address $from, Address $to, float $amount)`
- 查询最新区块 `blockNumber()`
- 根据区块链查询信息 `blockByNumber(int $blockID)`
- 根据交易哈希查询信息 `transactionReceipt(string $txHash)`
## 快速开始
### 安装
PHP8
``` php
composer require fenguoz/tron-php
```
or PHP7
``` php
composer require fenguoz/tron-php ~1.3
```
### 接口调用
``` php
use GuzzleHttp\Client;
$uri = 'https://api.trongrid.io';// mainnet
// $uri = 'https://api.shasta.trongrid.io';// shasta testnet
$api = new \Tron\Api(new Client(['base_uri' => $uri]));
$trxWallet = new \Tron\TRX($api);
$addressData = $trxWallet->generateAddress();
// $addressData->privateKey
// $addressData->address
$config = [
'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
'decimals' => 6,
];
$trc20Wallet = new \Tron\TRC20($api, $config);
$addressData = $trc20Wallet->generateAddress();
```
## 计划
- 支持 TRC10
- 智能合约
## 扩展包
| 扩展包名 | 描述 | 应用场景 |
| :-----| :---- | :---- |
| [fenguoz/tron-api](https://github.com/fenguoz/tron-api) | 波场官方文档推荐 PHP 扩展包 | 波场基础Api |
## 🌟🌟
[](https://starchart.cc/Fenguoz/tron-php)
## 合作
联系方式
- WX:zgf243944672
- QQ:243944672
================================================
FILE: README.md
================================================
English | [中文](./README-CN.md)
<h1 align="center">TRON-PHP</h1>
<p align="center">
<a href="https://github.com/Fenguoz/tron-php/releases"><img src="https://poser.pugx.org/Fenguoz/tron-php/v/stable" alt="Stable Version"></a>
<a href="https://www.php.net"><img src="https://img.shields.io/badge/php-%3E=7.2-brightgreen.svg?maxAge=2592000" alt="Php Version"></a>
<a href="https://github.com/Fenguoz/tron-php/blob/master/LICENSE"><img src="https://img.shields.io/github/license/fenguoz/tron-php.svg?maxAge=2592000" alt="tron-php License"></a>
<a href="https://packagist.org/packages/Fenguoz/tron-php"><img src="https://poser.pugx.org/Fenguoz/tron-php/downloads" alt="Total Downloads"></a>
</p>
## Introduction
Support TRON's TRX and TRC20, which include functions such as address creation, balance query, transaction transfer, query the latest blockchain, query information based on the blockchain, and query information based on the transaction hash
## Advantage
1. One set of scripts is compatible with all TRX currencies and TRC20 certifications in the TRON network
1. Interface methods can be added or subtracted flexibly
## Support Method
- Generate address `generateAddress()`
- Verify address `validateAddress(Address $address)`
- Get the address according to the private key `privateKeyToAddress(string $privateKeyHex)`
- Check balances `balance(Address $address)`
- Transaction transfer (offline signature) `transfer(string $from, string $to, float $amount)`
- Query the latest block `blockNumber()`
- Query information according to the blockchain `blockByNumber(int $blockID)`
- *Query information based on transaction hash `transactionReceipt(string $txHash)`
## Quick Start
### Install
PHP8
``` php
composer require fenguoz/tron-php
```
or PHP7
``` php
composer require fenguoz/tron-php ~1.3
```
### Interface
``` php
use GuzzleHttp\Client;
$uri = 'https://api.trongrid.io';// mainnet
// $uri = 'https://api.shasta.trongrid.io';// shasta testnet
$api = new \Tron\Api(new Client(['base_uri' => $uri]));
$trxWallet = new \Tron\TRX($api);
$addressData = $trxWallet->generateAddress();
// $addressData->privateKey
// $addressData->address
$config = [
'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
'decimals' => 6,
];
$trc20Wallet = new \Tron\TRC20($api, $config);
$addressData = $trc20Wallet->generateAddress();
```
## Plan
- Support TRC10
- Smart Contract
## Package
| Name | description | Scenes |
| :-----| :---- | :---- |
| [Fenguoz/tron-api](https://github.com/Fenguoz/tron-api) | TRON official document recommends PHP extension package | TRON basic API |
## 🌟🌟
[](https://starchart.cc/Fenguoz/tron-php)
## Cooperate
Contact
- WX:zgf243944672
- QQ:243944672
================================================
FILE: composer.json
================================================
{
"name": "fenguoz/tron-php",
"description": "Support TRON's TRX and TRC20, which include functions such as address creation, balance query, transaction transfer, query the latest blockchain, query information based on the blockchain, and query information based on the transaction hash",
"keywords": [
"php",
"tron",
"trx",
"trc20"
],
"type": "library",
"homepage": "https://github.com/Fenguoz/tron-php",
"license": "MIT",
"authors": [
{
"name": "Fenguoz",
"email": "243944672@qq.com"
}
],
"require": {
"php": ">=8.0",
"fenguoz/tron-api": "~1.1",
"ionux/phactor": "1.0.8",
"kornrunner/keccak": "~1.0"
},
"require-dev": {
"phpunit/phpunit": "~7.5 || ~9.0"
},
"autoload": {
"psr-4": {
"Tron\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Test\\": "tests/"
}
}
}
================================================
FILE: src/Address.php
================================================
<?php
namespace Tron;
use IEXBase\TronAPI\Support\Base58Check;
use IEXBase\TronAPI\Support\Hash;
class Address
{
public $privateKey,
$address,
$hexAddress = '';
const ADDRESS_SIZE = 34;
const ADDRESS_PREFIX = "41";
const ADDRESS_PREFIX_BYTE = 0x41;
public function __construct(string $address = '', string $privateKey = '', string $hexAddress = '')
{
if (strlen($address) === 0) {
throw new \InvalidArgumentException('Address can not be empty');
}
$this->privateKey = $privateKey;
$this->address = $address;
$this->hexAddress = $hexAddress;
}
/**
* Dont rely on this. Always use Wallet::validateAddress to double check
* against tronGrid.
*
* @return bool
*/
public function isValid(): bool
{
if (strlen($this->address) !== Address::ADDRESS_SIZE) {
return false;
}
$address = Base58Check::decode($this->address, false, 0, false);
$utf8 = hex2bin($address);
if (strlen($utf8) !== 25) {
return false;
}
if (strpos($utf8, chr(self::ADDRESS_PREFIX_BYTE)) !== 0) {
return false;
}
$checkSum = substr($utf8, 21);
$address = substr($utf8, 0, 21);
$hash0 = Hash::SHA256($address);
$hash1 = Hash::SHA256($hash0);
$checkSum1 = substr($hash1, 0, 4);
if ($checkSum === $checkSum1) {
return true;
}
return false;
}
}
================================================
FILE: src/Api.php
================================================
<?php
namespace Tron;
use GuzzleHttp\Client;
use Tron\Exceptions\TronErrorException;
class Api
{
private $_client;
public function __construct(Client $client)
{
$this->_client = $client;
}
public function getClient(): Client
{
return $this->_client;
}
/**
* Abstracts some common functionality like formatting the post data
* along with error handling.
*
* @throws TronErrorException
*/
public function post(string $endpoint, array $data = [], bool $returnAssoc = false)
{
if (sizeof($data)) {
$data = ['json' => $data];
}
$stream = (string)$this->getClient()->post($endpoint, $data)->getBody();
$body = json_decode($stream, $returnAssoc);
$this->checkForErrorResponse($returnAssoc, $body);
return $body;
}
/**
* Check if the response has an error and throw it.
*
* @param bool $returnAssoc
* @param $body
* @throws TronErrorException
*/
private function checkForErrorResponse(bool $returnAssoc, $body)
{
if ($returnAssoc) {
if (isset($body['Error'])) {
throw new TronErrorException($body['Error']);
} elseif (isset($body['code']) && isset($body['message'])) {
throw new TronErrorException($body['code'] . ': ' . hex2bin($body['message']));
}
}
if (isset($body->Error)) {
throw new TronErrorException($body->Error);
} elseif (isset($body->code) && isset($body->message)) {
throw new TronErrorException($body->code . ': ' . hex2bin($body->message));
}
}
}
================================================
FILE: src/Block.php
================================================
<?php
namespace Tron;
class Block
{
public $blockID;
public $block_header;
public $transactions;
public function __construct(string $blockID, array $block_header, array $transactions = [])
{
if (!strlen($blockID)) {
throw new \Exception('blockID empty');
}
$this->blockID = $blockID;
$this->block_header = $block_header;
$this->transactions = $transactions;
}
}
================================================
FILE: src/Exceptions/TransactionException.php
================================================
<?php
namespace Tron\Exceptions;
class TransactionException extends \Exception
{
}
================================================
FILE: src/Exceptions/TronErrorException.php
================================================
<?php
namespace Tron\Exceptions;
class TronErrorException extends \Exception
{
}
================================================
FILE: src/Interfaces/WalletInterface.php
================================================
<?php
namespace Tron\Interfaces;
use Tron\Address;
use Tron\Block;
use Tron\Transaction;
interface WalletInterface
{
public function generateAddress(): Address;
public function validateAddress(Address $address): bool;
public function privateKeyToAddress(string $privateKeyHex): Address;
public function balance(Address $address);
public function transfer(Address $from, Address $to, float $amount): Transaction;
public function blockNumber(): Block;
public function blockByNumber(int $blockID): Block;
public function transactionReceipt(string $txHash);
}
================================================
FILE: src/Support/Formatter.php
================================================
<?php
namespace Tron\Support;
/**
* 数据签名
* Class Formatter
* @package Ethereum
*/
class Formatter
{
/**
* 对于方法名和参数类型做签名
* @param $method
* @return string
*/
public static function toMethodFormat($method)
{
return Utils::stripZero(substr(Utils::sha3($method), 0, 10));
}
/**
* 地址签名
* @param $address
* @return string
*/
public static function toAddressFormat($address)
{
if (Utils::isAddress($address)) {
$address = strtolower($address);
if (Utils::isZeroPrefixed($address)) {
$address = Utils::stripZero($address);
}
}
return implode('', array_fill(0, 64 - strlen($address), 0)) . $address;
}
/**
* 数字签名
* @param $value
* @param int $digit
* @return string
*/
public static function toIntegerFormat($value, $digit = 64)
{
$bn = Utils::toBn($value);
$bnHex = $bn->toHex(true);
$padded = mb_substr($bnHex, 0, 1);
if ($padded !== 'f') {
$padded = '0';
}
return implode('', array_fill(0, $digit - mb_strlen($bnHex), $padded)) . $bnHex;
}
}
================================================
FILE: src/Support/Key.php
================================================
<?php
namespace Tron\Support;
use Elliptic\EC;
use IEXBase\TronAPI\Support\Base58;
use IEXBase\TronAPI\Support\Crypto;
use IEXBase\TronAPI\Support\Hash;
use InvalidArgumentException;
use RuntimeException;
class Key
{
/**
* Generate the Address of the provided Public key
*
* @param string $publicKey
*
* @return string
*/
public static function publicKeyToAddress(string $publicKey)
{
if (Utils::isHex($publicKey) === false) {
throw new InvalidArgumentException('Invalid public key format.');
}
$publicKey = Utils::stripZero($publicKey);
if (strlen($publicKey) !== 130) {
throw new InvalidArgumentException('Invalid public key length.');
}
return substr(Utils::sha3(substr(hex2bin($publicKey), 1)), 24);
}
/**
* Generate the Address of the provided Private key
*
* @param string $privateKey
*
* @return string
*/
public static function privateKeyToAddress(string $privateKey)
{
return self::publicKeyToAddress(
self::privateKeyToPublicKey($privateKey)
);
}
/**
* Generate the Public key for provided Private key
*
* @param string $privateKey Private Key
*
* @return string
*/
public static function privateKeyToPublicKey(string $privateKey)
{
if (Utils::isHex($privateKey) === false) {
throw new InvalidArgumentException('Invalid private key format.');
}
$privateKey = Utils::stripZero($privateKey);
if (strlen($privateKey) !== 64) {
throw new InvalidArgumentException('Invalid private key length.');
}
$secp256k1 = new EC('secp256k1');
$privateKey = $secp256k1->keyFromPrivate($privateKey, 'hex');
$publicKey = $privateKey->getPublic(false, 'hex');
return $publicKey;
}
public static function getBase58CheckAddress(string $addressHex): string
{
$addressBin = hex2bin($addressHex);
$hash0 = Hash::SHA256($addressBin);
$hash1 = Hash::SHA256($hash0);
$checksum = substr($hash1, 0, 4);
$checksum = $addressBin . $checksum;
return Base58::encode(Crypto::bin2bc($checksum));
}
}
================================================
FILE: src/Support/Utils.php
================================================
<?php
namespace Tron\Support;
use InvalidArgumentException;
use kornrunner\Keccak;
use phpseclib\Math\BigInteger;
use Psr\Http\Message\StreamInterface;
class Utils
{
/**
* SHA3_NULL_HASH
*
* @const string
*/
const SHA3_NULL_HASH = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';
/**
* NEGATIVE1
* Cannot work, see: http://php.net/manual/en/language.constants.syntax.php
*
* @const
*/
// const NEGATIVE1 = new BigInteger(-1);
/**
* construct
*
* @return void
*/
// public function __construct() {}
/**
* toHex
* Encoding string or integer or numeric string(is not zero prefixed) or big number to hex.
*
* @param string|int|BigInteger $value
* @param bool $isPrefix
* @return string
*/
public static function toHex($value, $isPrefix = false)
{
if (is_numeric($value)) {
// turn to hex number
$bn = self::toBn($value);
$hex = $bn->toHex(true);
$hex = preg_replace('/^0+(?!$)/', '', $hex);
} elseif (is_string($value)) {
$value = self::stripZero($value);
$hex = implode('', unpack('H*', $value));
} elseif ($value instanceof BigInteger) {
$hex = $value->toHex(true);
$hex = preg_replace('/^0+(?!$)/', '', $hex);
} else {
throw new InvalidArgumentException('The value to toHex function is not support.');
}
if ($isPrefix) {
return '0x' . $hex;
}
return $hex;
}
/**
* hexToBin
*
* @param string
* @return string
*/
public static function hexToBin($value)
{
if (!is_string($value)) {
throw new InvalidArgumentException('The value to hexToBin function must be string.');
}
if (self::isZeroPrefixed($value)) {
$count = 1;
$value = str_replace('0x', '', $value, $count);
}
return pack('H*', $value);
}
/**
* isZeroPrefixed
*
* @param string
* @return bool
*/
public static function isZeroPrefixed($value)
{
if (!is_string($value)) {
throw new InvalidArgumentException('The value to isZeroPrefixed function must be string.');
}
return (strpos($value, '0x') === 0);
}
/**
* stripZero
*
* @param string $value
* @return string
*/
public static function stripZero($value)
{
if (self::isZeroPrefixed($value)) {
$count = 1;
return str_replace('0x', '', $value, $count);
}
return $value;
}
/**
* isNegative
*
* @param string
* @return bool
*/
public static function isNegative($value)
{
if (!is_string($value)) {
throw new InvalidArgumentException('The value to isNegative function must be string.');
}
return (strpos($value, '-') === 0);
}
/**
* isAddress
*
* @param string $value
* @return bool
*/
public static function isAddress($value)
{
if (!is_string($value)) {
throw new InvalidArgumentException('The value to isAddress function must be string.');
}
if (preg_match('/^(0x|0X)?[a-f0-9A-F]{40}$/', $value) !== 1) {
return false;
} elseif (preg_match('/^(0x|0X)?[a-f0-9]{40}$/', $value) === 1 || preg_match('/^(0x|0X)?[A-F0-9]{40}$/', $value) === 1) {
return true;
}
return self::isAddressChecksum($value);
}
/**
* isAddressChecksum
*
* @param string $value
* @return bool
*/
public static function isAddressChecksum($value)
{
if (!is_string($value)) {
throw new InvalidArgumentException('The value to isAddressChecksum function must be string.');
}
$value = self::stripZero($value);
$hash = self::stripZero(self::sha3(mb_strtolower($value)));
for ($i = 0; $i < 40; $i++) {
if (
(intval($hash[$i], 16) > 7 && mb_strtoupper($value[$i]) !== $value[$i]) ||
(intval($hash[$i], 16) <= 7 && mb_strtolower($value[$i]) !== $value[$i])
) {
return false;
}
}
return true;
}
/**
* isHex
*
* @param string $value
* @return bool
*/
public static function isHex($value)
{
return (is_string($value) && preg_match('/^(0x)?[a-f0-9A-F]*$/', $value) === 1);
}
/**
* sha3
* keccak256
*
* @param string $value
* @return string
*/
public static function sha3($value)
{
if (!is_string($value)) {
throw new InvalidArgumentException('The value to sha3 function must be string.');
}
if (strpos($value, '0x') === 0) {
$value = self::hexToBin($value);
}
$hash = Keccak::hash($value, 256);
if ($hash === self::SHA3_NULL_HASH) {
return null;
}
return $hash;
}
/**
* toBn
* Change number or number string to BigInteger.
*
* @param BigInteger|string|int $number
* @return array|BigInteger
*/
public static function toBn($number)
{
if ($number instanceof BigInteger) {
$bn = $number;
} elseif (is_int($number)) {
$bn = new BigInteger($number);
} elseif (is_numeric($number)) {
$number = (string) $number;
if (self::isNegative($number)) {
$count = 1;
$number = str_replace('-', '', $number, $count);
$negative1 = new BigInteger(-1);
}
if (strpos($number, '.') > 0) {
$comps = explode('.', $number);
if (count($comps) > 2) {
throw new InvalidArgumentException('toBn number must be a valid number.');
}
$whole = $comps[0];
$fraction = $comps[1];
return [
new BigInteger($whole),
new BigInteger($fraction),
strlen($comps[1]),
isset($negative1) ? $negative1 : false
];
} else {
$bn = new BigInteger($number);
}
if (isset($negative1)) {
$bn = $bn->multiply($negative1);
}
} elseif (is_string($number)) {
$number = mb_strtolower($number);
if (self::isNegative($number)) {
$count = 1;
$number = str_replace('-', '', $number, $count);
$negative1 = new BigInteger(-1);
}
if (self::isZeroPrefixed($number) || preg_match('/[a-f]+/', $number) === 1) {
$number = self::stripZero($number);
$bn = new BigInteger($number, 16);
} elseif (empty($number)) {
$bn = new BigInteger(0);
} else {
throw new InvalidArgumentException('toBn number must be valid hex string.');
}
if (isset($negative1)) {
$bn = $bn->multiply($negative1);
}
} else {
throw new InvalidArgumentException('toBn number must be BigInteger, string or int.');
}
return $bn;
}
/**
* 根据精度展示资产
* @param $number
* @param int $decimals
* @return string
*/
public static function toDisplayAmount($number, int $decimals)
{
$number = number_format($number,0,'.','');//格式化
$bn = self::toBn($number);
$bnt = self::toBn(pow(10, $decimals));
return self::divideDisplay($bn->divide($bnt), $decimals);
}
public static function divideDisplay(array $divResult, int $decimals)
{
list($bnq, $bnr) = $divResult;
$ret = "$bnq->value";
if ($bnr->value > 0) {
$ret .= '.' . rtrim(sprintf("%0{$decimals}d", $bnr->value), '0');
}
return $ret;
}
public static function toMinUnitByDecimals($number, int $decimals)
{
$bn = self::toBn($number);
$bnt = self::toBn(pow(10, $decimals));
if (is_array($bn)) {
// fraction number
list($whole, $fraction, $fractionLength, $negative1) = $bn;
$whole = $whole->multiply($bnt);
switch (MATH_BIGINTEGER_MODE) {
case $whole::MODE_GMP:
static $two;
$powerBase = gmp_pow(gmp_init(10), (int) $fractionLength);
break;
case $whole::MODE_BCMATH:
$powerBase = bcpow('10', (string) $fractionLength, 0);
break;
default:
$powerBase = pow(10, (int) $fractionLength);
break;
}
$base = new BigInteger($powerBase);
$fraction = $fraction->multiply($bnt)->divide($base)[0];
if ($negative1 !== false) {
return $whole->add($fraction)->multiply($negative1);
}
return $whole->add($fraction);
}
return $bn->multiply($bnt);
}
}
================================================
FILE: src/TRC20.php
================================================
<?php
namespace Tron;
use IEXBase\TronAPI\Exception\TronException;
use Tron\Exceptions\TransactionException;
use Tron\Exceptions\TronErrorException;
use Tron\Support\Formatter;
use Tron\Support\Utils;
use InvalidArgumentException;
class TRC20 extends TRX
{
protected $contractAddress;
protected $decimals;
public function __construct(Api $_api, array $config)
{
parent::__construct($_api, $config);
$this->contractAddress = new Address(
$config['contract_address'],
'',
$this->tron->address2HexString($config['contract_address'])
);
$this->decimals = $config['decimals'];
}
public function balance(Address $address)
{
$format = Formatter::toAddressFormat($address->hexAddress);
$body = $this->_api->post('/wallet/triggersmartcontract', [
'contract_address' => $this->contractAddress->hexAddress,
'function_selector' => 'balanceOf(address)',
'parameter' => $format,
'owner_address' => $address->hexAddress,
]);
if (isset($body->result->code)) {
throw new TronErrorException(hex2bin($body->result->message));
}
try {
$balance = Utils::toDisplayAmount(hexdec($body->constant_result[0]), $this->decimals);
} catch (InvalidArgumentException $e) {
throw new TronErrorException($e->getMessage());
}
return $balance;
}
public function transfer(Address $from, Address $to, float $amount): Transaction
{
$this->tron->setAddress($from->address);
$this->tron->setPrivateKey($from->privateKey);
$toFormat = Formatter::toAddressFormat($to->hexAddress);
try {
$amount = Utils::toMinUnitByDecimals($amount, $this->decimals);
} catch (InvalidArgumentException $e) {
throw new TronErrorException($e->getMessage());
}
$numberFormat = Formatter::toIntegerFormat($amount);
$body = $this->_api->post('/wallet/triggersmartcontract', [
'contract_address' => $this->contractAddress->hexAddress,
'function_selector' => 'transfer(address,uint256)',
'parameter' => "{$toFormat}{$numberFormat}",
'fee_limit' => 100000000,
'call_value' => 0,
'owner_address' => $from->hexAddress,
], true);
if (isset($body['result']['code'])) {
throw new TransactionException(hex2bin($body['result']['message']));
}
try {
$tradeobj = $this->tron->signTransaction($body['transaction']);
$response = $this->tron->sendRawTransaction($tradeobj);
} catch (TronException $e) {
throw new TransactionException($e->getMessage(), $e->getCode());
}
if (isset($response['result']) && $response['result'] == true) {
return new Transaction(
$body['transaction']['txID'],
$body['transaction']['raw_data'],
'PACKING'
);
} else {
throw new TransactionException(hex2bin($response['result']['message']));
}
}
}
================================================
FILE: src/TRX.php
================================================
<?php
namespace Tron;
use Phactor\Key;
use IEXBase\TronAPI\Exception\TronException;
use IEXBase\TronAPI\Tron;
use IEXBase\TronAPI\Provider\HttpProvider;
use Tron\Interfaces\WalletInterface;
use Tron\Exceptions\TronErrorException;
use Tron\Exceptions\TransactionException;
use Tron\Support\Key as SupportKey;
use InvalidArgumentException;
class TRX implements WalletInterface
{
protected $_api;
protected $tron;
public function __construct(Api $_api, array $config = [])
{
$this->_api = $_api;
$host = $_api->getClient()->getConfig('base_uri')->getScheme() . '://' . $_api->getClient()->getConfig('base_uri')->getHost();
$fullNode = new HttpProvider($host);
$solidityNode = new HttpProvider($host);
$eventServer = new HttpProvider($host);
try {
$this->tron = new Tron($fullNode, $solidityNode, $eventServer);
} catch (TronException $e) {
throw new TronErrorException($e->getMessage(), $e->getCode());
}
}
public function generateAddress(): Address
{
$attempts = 0;
$validAddress = false;
do {
if ($attempts++ === 5) {
throw new TronErrorException('Could not generate valid key');
}
$key = new Key([
'private_key_hex' => '',
'private_key_dec' => '',
'public_key' => '',
'public_key_compressed' => '',
'public_key_x' => '',
'public_key_y' => ''
]);
$keyPair = $key->GenerateKeypair();
$privateKeyHex = $keyPair['private_key_hex'];
$pubKeyHex = $keyPair['public_key'];
//We cant use hex2bin unless the string length is even.
if (strlen($pubKeyHex) % 2 !== 0) {
continue;
}
try {
$addressHex = Address::ADDRESS_PREFIX . SupportKey::publicKeyToAddress($pubKeyHex);
$addressBase58 = SupportKey::getBase58CheckAddress($addressHex);
} catch (InvalidArgumentException $e) {
throw new TronErrorException($e->getMessage());
}
$address = new Address($addressBase58, $privateKeyHex, $addressHex);
$validAddress = $this->validateAddress($address);
} while (!$validAddress);
return $address;
}
public function validateAddress(Address $address): bool
{
if (!$address->isValid()) {
return false;
}
$body = $this->_api->post('/wallet/validateaddress', [
'address' => $address->address,
]);
return $body->result;
}
public function privateKeyToAddress(string $privateKeyHex): Address
{
try {
$addressHex = Address::ADDRESS_PREFIX . SupportKey::privateKeyToAddress($privateKeyHex);
$addressBase58 = SupportKey::getBase58CheckAddress($addressHex);
} catch (InvalidArgumentException $e) {
throw new TronErrorException($e->getMessage());
}
$address = new Address($addressBase58, $privateKeyHex, $addressHex);
$validAddress = $this->validateAddress($address);
if (!$validAddress) {
throw new TronErrorException('Invalid private key');
}
return $address;
}
public function balance(Address $address)
{
$this->tron->setAddress($address->address);
return $this->tron->getBalance(null, true);
}
public function transfer(Address $from, Address $to, float $amount): Transaction
{
$this->tron->setAddress($from->address);
$this->tron->setPrivateKey($from->privateKey);
try {
$transaction = $this->tron->getTransactionBuilder()->sendTrx($to->address, $amount, $from->address);
$signedTransaction = $this->tron->signTransaction($transaction);
$response = $this->tron->sendRawTransaction($signedTransaction);
} catch (TronException $e) {
throw new TransactionException($e->getMessage(), $e->getCode());
}
if (isset($response['result']) && $response['result'] == true) {
return new Transaction(
$transaction['txID'],
$transaction['raw_data'],
'PACKING'
);
} else {
throw new TransactionException(hex2bin($response['message']));
}
}
public function blockNumber(): Block
{
try {
$block = $this->tron->getCurrentBlock();
} catch (TronException $e) {
throw new TransactionException($e->getMessage(), $e->getCode());
}
$transactions = isset($block['transactions']) ? $block['transactions'] : [];
return new Block($block['blockID'], $block['block_header'], $transactions);
}
public function blockByNumber(int $blockID): Block
{
try {
$block = $this->tron->getBlockByNumber($blockID);
} catch (TronException $e) {
throw new TransactionException($e->getMessage(), $e->getCode());
}
$transactions = isset($block['transactions']) ? $block['transactions'] : [];
return new Block($block['blockID'], $block['block_header'], $transactions);
}
public function transactionReceipt(string $txHash): Transaction
{
try {
$detail = $this->tron->getTransaction($txHash);
} catch (TronException $e) {
throw new TransactionException($e->getMessage(), $e->getCode());
}
return new Transaction(
$detail['txID'],
$detail['raw_data'],
$detail['ret'][0]['contractRet'] ?? ''
);
}
}
================================================
FILE: src/Transaction.php
================================================
<?php
namespace Tron;
class Transaction
{
public $signature = [];
public $txID = '';
public $raw_data = [];
public $contractRet = '';
public function __construct(string $txID, array $rawData, string $contractRet)
{
$this->txID = $txID;
$this->raw_data = $rawData;
$this->contractRet = $contractRet;
}
public function isSigned(): bool
{
return (bool)sizeof($this->signature);
}
}
================================================
FILE: tests/TRC20Test.php
================================================
<?php
/**
* This file is part of the tron-php package
*
* @category tron-php
* @package tron-php
* @author Fenguoz <243944672@qq.com>
* @license https://github.com/Fenguoz/tron-php/blob/master/LICENSE MIT
* @link https://github.com/Fenguoz/tron-php
*/
namespace Tests;
use GuzzleHttp\Client;
use PHPUnit\Framework\TestCase;
use Tron\Address;
use Tron\Api;
use Tron\TRC20;
class TRC20Test extends TestCase
{
const URI = 'https://api.trongrid.io'; // mainnet
// const URI = 'https://api.shasta.trongrid.io'; // shasta testnet
const ADDRESS = 'TGytofNKuSReFmFxsgnNx19em3BAVBTpVB';
const PRIVATE_KEY = '0xf1b4b7d86a3eff98f1bace9cb2665d0cad3a3f949bc74a7ffb2aaa968c07f521';
const BLOCK_ID = 13402554;
const TX_HASH = '539e6c2429f19a8626fadc1211985728e310f5bd5d2749c88db2e3f22a8fdf69';
const CONTRACT = [
'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', // USDT TRC20
'decimals' => 6,
];
private function getTRC20()
{
$api = new Api(new Client(['base_uri' => self::URI]));
$config = self::CONTRACT;
$trxWallet = new TRC20($api, $config);
return $trxWallet;
}
public function testGenerateAddress()
{
$addressData = $this->getTRC20()->generateAddress();
var_dump($addressData);
$this->assertTrue(true);
}
public function testPrivateKeyToAddress()
{
$privateKey = self::PRIVATE_KEY;
$addressData = $this->getTRC20()->privateKeyToAddress($privateKey);
var_dump($addressData);
$this->assertTrue(true);
}
public function testBalance()
{
$address = new Address(
self::ADDRESS,
'',
$this->getTRC20()->tron->address2HexString(self::ADDRESS)
);
$balanceData = $this->getTRC20()->balance($address);
var_dump($balanceData);
$this->assertTrue(true);
}
public function testTransfer()
{
$privateKey = self::PRIVATE_KEY;
$address = self::ADDRESS;
$amount = 1;
$from = $this->getTRC20()->privateKeyToAddress($privateKey);
$to = new Address(
$address,
'',
$this->getTRC20()->tron->address2HexString($address)
);
$transferData = $this->getTRC20()->transfer($from, $to, $amount);
var_dump($transferData);
$this->assertTrue(true);
}
public function testBlockNumber()
{
$blockData = $this->getTRC20()->blockNumber();
var_dump($blockData);
$this->assertTrue(true);
}
public function testBlockByNumber()
{
$blockID = self::BLOCK_ID;
$blockData = $this->getTRC20()->blockByNumber($blockID);
var_dump($blockData);
$this->assertTrue(true);
}
public function testTransactionReceipt()
{
$txHash = self::TX_HASH;
$txData = $this->getTRC20()->transactionReceipt($txHash);
var_dump($txData);
$this->assertTrue(true);
}
}
================================================
FILE: tests/TRXTest.php
================================================
<?php
/**
* This file is part of the tron-php package
*
* @category tron-php
* @package tron-php
* @author Fenguoz <243944672@qq.com>
* @license https://github.com/Fenguoz/tron-php/blob/master/LICENSE MIT
* @link https://github.com/Fenguoz/tron-php
*/
namespace Tests;
use GuzzleHttp\Client;
use PHPUnit\Framework\TestCase;
use Tron\Address;
use Tron\Api;
use Tron\TRX;
class TRXTest extends TestCase
{
const URI = 'https://api.shasta.trongrid.io'; // shasta testnet
const ADDRESS = 'TGytofNKuSReFmFxsgnNx19em3BAVBTpVB';
const PRIVATE_KEY = '0xf1b4b7d86a3eff98f1bace9cb2665d0cad3a3f949bc74a7ffb2aaa968c07f521';
const BLOCK_ID = 13402554;
const TX_HASH = '539e6c2429f19a8626fadc1211985728e310f5bd5d2749c88db2e3f22a8fdf69';
private function getTRX()
{
$api = new Api(new Client(['base_uri' => self::URI]));
$trxWallet = new TRX($api);
return $trxWallet;
}
public function testGenerateAddress()
{
$addressData = $this->getTRX()->generateAddress();
var_dump($addressData);
$this->assertTrue(true);
}
public function testPrivateKeyToAddress()
{
$privateKey = self::PRIVATE_KEY;
$addressData = $this->getTRX()->privateKeyToAddress($privateKey);
var_dump($addressData);
$this->assertTrue(true);
}
public function testBalance()
{
$address = new Address(
self::ADDRESS,
'',
$this->getTRX()->tron->address2HexString(self::ADDRESS)
);
$balanceData = $this->getTRX()->balance($address);
var_dump($balanceData);
$this->assertTrue(true);
}
public function testTransfer()
{
$privateKey = self::PRIVATE_KEY;
$address = self::ADDRESS;
$amount = 1;
$from = $this->getTRX()->privateKeyToAddress($privateKey);
$to = new Address(
$address,
'',
$this->getTRX()->tron->address2HexString($address)
);
$transferData = $this->getTRX()->transfer($from, $to, $amount);
var_dump($transferData);
$this->assertTrue(true);
}
public function testBlockNumber()
{
$blockData = $this->getTRX()->blockNumber();
var_dump($blockData);
$this->assertTrue(true);
}
public function testBlockByNumber()
{
$blockID = self::BLOCK_ID;
$blockData = $this->getTRX()->blockByNumber($blockID);
var_dump($blockData);
$this->assertTrue(true);
}
public function testTransactionReceipt()
{
$txHash = self::TX_HASH;
$txData = $this->getTRX()->transactionReceipt($txHash);
var_dump($txData);
$this->assertTrue(true);
}
}
gitextract_q3mnkphk/
├── .gitignore
├── LICENSE
├── README-CN.md
├── README.md
├── composer.json
├── src/
│ ├── Address.php
│ ├── Api.php
│ ├── Block.php
│ ├── Exceptions/
│ │ ├── TransactionException.php
│ │ └── TronErrorException.php
│ ├── Interfaces/
│ │ └── WalletInterface.php
│ ├── Support/
│ │ ├── Formatter.php
│ │ ├── Key.php
│ │ └── Utils.php
│ ├── TRC20.php
│ ├── TRX.php
│ └── Transaction.php
└── tests/
├── TRC20Test.php
└── TRXTest.php
SYMBOL INDEX (79 symbols across 14 files)
FILE: src/Address.php
class Address (line 8) | class Address
method __construct (line 18) | public function __construct(string $address = '', string $privateKey =...
method isValid (line 35) | public function isValid(): bool
FILE: src/Api.php
class Api (line 8) | class Api
method __construct (line 12) | public function __construct(Client $client)
method getClient (line 17) | public function getClient(): Client
method post (line 28) | public function post(string $endpoint, array $data = [], bool $returnA...
method checkForErrorResponse (line 49) | private function checkForErrorResponse(bool $returnAssoc, $body)
FILE: src/Block.php
class Block (line 5) | class Block
method __construct (line 11) | public function __construct(string $blockID, array $block_header, arra...
FILE: src/Exceptions/TransactionException.php
class TransactionException (line 5) | class TransactionException extends \Exception
FILE: src/Exceptions/TronErrorException.php
class TronErrorException (line 5) | class TronErrorException extends \Exception
FILE: src/Interfaces/WalletInterface.php
type WalletInterface (line 9) | interface WalletInterface
method generateAddress (line 11) | public function generateAddress(): Address;
method validateAddress (line 13) | public function validateAddress(Address $address): bool;
method privateKeyToAddress (line 15) | public function privateKeyToAddress(string $privateKeyHex): Address;
method balance (line 17) | public function balance(Address $address);
method transfer (line 19) | public function transfer(Address $from, Address $to, float $amount): T...
method blockNumber (line 21) | public function blockNumber(): Block;
method blockByNumber (line 23) | public function blockByNumber(int $blockID): Block;
method transactionReceipt (line 25) | public function transactionReceipt(string $txHash);
FILE: src/Support/Formatter.php
class Formatter (line 10) | class Formatter
method toMethodFormat (line 18) | public static function toMethodFormat($method)
method toAddressFormat (line 28) | public static function toAddressFormat($address)
method toIntegerFormat (line 46) | public static function toIntegerFormat($value, $digit = 64)
FILE: src/Support/Key.php
class Key (line 13) | class Key
method publicKeyToAddress (line 22) | public static function publicKeyToAddress(string $publicKey)
method privateKeyToAddress (line 41) | public static function privateKeyToAddress(string $privateKey)
method privateKeyToPublicKey (line 55) | public static function privateKeyToPublicKey(string $privateKey)
method getBase58CheckAddress (line 73) | public static function getBase58CheckAddress(string $addressHex): string
FILE: src/Support/Utils.php
class Utils (line 10) | class Utils
method toHex (line 42) | public static function toHex($value, $isPrefix = false)
method hexToBin (line 70) | public static function hexToBin($value)
method isZeroPrefixed (line 88) | public static function isZeroPrefixed($value)
method stripZero (line 102) | public static function stripZero($value)
method isNegative (line 117) | public static function isNegative($value)
method isAddress (line 131) | public static function isAddress($value)
method isAddressChecksum (line 150) | public static function isAddressChecksum($value)
method isHex (line 175) | public static function isHex($value)
method sha3 (line 187) | public static function sha3($value)
method toBn (line 210) | public static function toBn($number)
method toDisplayAmount (line 276) | public static function toDisplayAmount($number, int $decimals)
method divideDisplay (line 285) | public static function divideDisplay(array $divResult, int $decimals)
method toMinUnitByDecimals (line 296) | public static function toMinUnitByDecimals($number, int $decimals)
FILE: src/TRC20.php
class TRC20 (line 12) | class TRC20 extends TRX
method __construct (line 18) | public function __construct(Api $_api, array $config)
method balance (line 30) | public function balance(Address $address)
method transfer (line 52) | public function transfer(Address $from, Address $to, float $amount): T...
FILE: src/TRX.php
class TRX (line 15) | class TRX implements WalletInterface
method __construct (line 21) | public function __construct(Api $_api, array $config = [])
method generateAddress (line 36) | public function generateAddress(): Address
method validateAddress (line 76) | public function validateAddress(Address $address): bool
method privateKeyToAddress (line 89) | public function privateKeyToAddress(string $privateKeyHex): Address
method balance (line 106) | public function balance(Address $address)
method transfer (line 112) | public function transfer(Address $from, Address $to, float $amount): T...
method blockNumber (line 136) | public function blockNumber(): Block
method blockByNumber (line 147) | public function blockByNumber(int $blockID): Block
method transactionReceipt (line 159) | public function transactionReceipt(string $txHash): Transaction
FILE: src/Transaction.php
class Transaction (line 5) | class Transaction
method __construct (line 12) | public function __construct(string $txID, array $rawData, string $cont...
method isSigned (line 19) | public function isSigned(): bool
FILE: tests/TRC20Test.php
class TRC20Test (line 21) | class TRC20Test extends TestCase
method getTRC20 (line 34) | private function getTRC20()
method testGenerateAddress (line 42) | public function testGenerateAddress()
method testPrivateKeyToAddress (line 50) | public function testPrivateKeyToAddress()
method testBalance (line 59) | public function testBalance()
method testTransfer (line 72) | public function testTransfer()
method testBlockNumber (line 90) | public function testBlockNumber()
method testBlockByNumber (line 98) | public function testBlockByNumber()
method testTransactionReceipt (line 107) | public function testTransactionReceipt()
FILE: tests/TRXTest.php
class TRXTest (line 21) | class TRXTest extends TestCase
method getTRX (line 29) | private function getTRX()
method testGenerateAddress (line 36) | public function testGenerateAddress()
method testPrivateKeyToAddress (line 44) | public function testPrivateKeyToAddress()
method testBalance (line 53) | public function testBalance()
method testTransfer (line 66) | public function testTransfer()
method testBlockNumber (line 84) | public function testBlockNumber()
method testBlockByNumber (line 92) | public function testBlockByNumber()
method testTransactionReceipt (line 101) | public function testTransactionReceipt()
Condensed preview — 19 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (43K chars).
[
{
"path": ".gitignore",
"chars": 19,
"preview": ".idea\nvendor\n*.lock"
},
{
"path": "LICENSE",
"chars": 1064,
"preview": "MIT License\n\nCopyright (c) 2021 Fenguoz\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof"
},
{
"path": "README-CN.md",
"chars": 2184,
"preview": "[English](./README.md) | 中文\n\n<h1 align=\"center\">TRON-PHP</h1>\n\n<p align=\"center\">\n <a href=\"https://github.com/Fenguoz/"
},
{
"path": "README.md",
"chars": 2801,
"preview": "English | [中文](./README-CN.md)\n\n<h1 align=\"center\">TRON-PHP</h1>\n\n<p align=\"center\">\n <a href=\"https://github.com/Fengu"
},
{
"path": "composer.json",
"chars": 996,
"preview": "{\n \"name\": \"fenguoz/tron-php\",\n \"description\": \"Support TRON's TRX and TRC20, which include functions such as addr"
},
{
"path": "src/Address.php",
"chars": 1531,
"preview": "<?php\n\nnamespace Tron;\n\nuse IEXBase\\TronAPI\\Support\\Base58Check;\nuse IEXBase\\TronAPI\\Support\\Hash;\n\nclass Address\n{\n "
},
{
"path": "src/Api.php",
"chars": 1689,
"preview": "<?php\n\nnamespace Tron;\n\nuse GuzzleHttp\\Client;\nuse Tron\\Exceptions\\TronErrorException;\n\nclass Api\n{\n private $_client"
},
{
"path": "src/Block.php",
"chars": 442,
"preview": "<?php\n\nnamespace Tron;\n\nclass Block\n{\n public $blockID;\n public $block_header;\n public $transactions;\n\n publ"
},
{
"path": "src/Exceptions/TransactionException.php",
"chars": 85,
"preview": "<?php\n\nnamespace Tron\\Exceptions;\n\nclass TransactionException extends \\Exception\n{\n}\n"
},
{
"path": "src/Exceptions/TronErrorException.php",
"chars": 83,
"preview": "<?php\n\nnamespace Tron\\Exceptions;\n\nclass TronErrorException extends \\Exception\n{\n}\n"
},
{
"path": "src/Interfaces/WalletInterface.php",
"chars": 598,
"preview": "<?php\n\nnamespace Tron\\Interfaces;\n\nuse Tron\\Address;\nuse Tron\\Block;\nuse Tron\\Transaction;\n\ninterface WalletInterface\n{\n"
},
{
"path": "src/Support/Formatter.php",
"chars": 1204,
"preview": "<?php\n\nnamespace Tron\\Support;\n\n/**\n * 数据签名\n * Class Formatter\n * @package Ethereum\n */\nclass Formatter\n{\n\n /**\n "
},
{
"path": "src/Support/Key.php",
"chars": 2287,
"preview": "<?php\n\nnamespace Tron\\Support;\n\nuse Elliptic\\EC;\nuse IEXBase\\TronAPI\\Support\\Base58;\nuse IEXBase\\TronAPI\\Support\\Crypto;"
},
{
"path": "src/Support/Utils.php",
"chars": 9339,
"preview": "<?php\n\nnamespace Tron\\Support;\n\nuse InvalidArgumentException;\nuse kornrunner\\Keccak;\nuse phpseclib\\Math\\BigInteger;\nuse "
},
{
"path": "src/TRC20.php",
"chars": 3192,
"preview": "<?php\n\nnamespace Tron;\n\nuse IEXBase\\TronAPI\\Exception\\TronException;\nuse Tron\\Exceptions\\TransactionException;\nuse Tron\\"
},
{
"path": "src/TRX.php",
"chars": 5760,
"preview": "<?php\n\nnamespace Tron;\n\nuse Phactor\\Key;\nuse IEXBase\\TronAPI\\Exception\\TronException;\nuse IEXBase\\TronAPI\\Tron;\nuse IEXB"
},
{
"path": "src/Transaction.php",
"chars": 455,
"preview": "<?php\n\nnamespace Tron;\n\nclass Transaction\n{\n public $signature = [];\n public $txID = '';\n public $raw_data = []"
},
{
"path": "tests/TRC20Test.php",
"chars": 3033,
"preview": "<?php\n\n/**\n * This file is part of the tron-php package\n *\n * @category tron-php\n * @package tron-php\n * @author Feng"
},
{
"path": "tests/TRXTest.php",
"chars": 2768,
"preview": "<?php\n\n/**\n * This file is part of the tron-php package\n *\n * @category tron-php\n * @package tron-php\n * @author Feng"
}
]
About this extraction
This page contains the full source code of the Fenguoz/tron-php GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 19 files (38.6 KB), approximately 10.8k tokens, and a symbol index with 79 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.