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) | 中文
TRON-PHP
## 概述
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)
TRON-PHP
## 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
================================================
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
================================================
_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
================================================
blockID = $blockID;
$this->block_header = $block_header;
$this->transactions = $transactions;
}
}
================================================
FILE: src/Exceptions/TransactionException.php
================================================
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
================================================
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
================================================
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
================================================
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
================================================
_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
================================================
txID = $txID;
$this->raw_data = $rawData;
$this->contractRet = $contractRet;
}
public function isSigned(): bool
{
return (bool)sizeof($this->signature);
}
}
================================================
FILE: tests/TRC20Test.php
================================================
* @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
================================================
* @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);
}
}