[
  {
    "path": ".gitignore",
    "content": ".idea\nvendor\n*.lock"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Fenguoz\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README-CN.md",
    "content": "[English](./README.md) | 中文\n\n<h1 align=\"center\">TRON-PHP</h1>\n\n<p align=\"center\">\n  <a href=\"https://github.com/Fenguoz/tron-php/releases\"><img src=\"https://poser.pugx.org/Fenguoz/tron-php/v/stable\" alt=\"Stable Version\"></a>\n  <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>\n  <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>\n  <a href=\"https://packagist.org/packages/Fenguoz/tron-php\"><img src=\"https://poser.pugx.org/Fenguoz/tron-php/downloads\" alt=\"Total Downloads\"></a>\n</p>\n\n## 概述\n\nTRON-PHP 目前支持波场的 TRX 和 TRC20 中常用生成地址，发起转账，离线签名等功能。\n\n## 特点\n\n1. 一套写法兼容 TRON 网络中 TRX 货币和 TRC 系列所有通证\n1. 接口方法可可灵活增减\n\n## 支持方法\n\n- 生成地址 `generateAddress()`\n- 验证地址 `validateAddress(Address $address)`\n- 根据私钥得到地址 `privateKeyToAddress(string $privateKeyHex)`\n- 查询余额 `balance(Address $address)`\n- 交易转账(离线签名) `transfer(Address $from, Address $to, float $amount)`\n- 查询最新区块 `blockNumber()`\n- 根据区块链查询信息 `blockByNumber(int $blockID)`\n- 根据交易哈希查询信息 `transactionReceipt(string $txHash)`\n\n## 快速开始\n\n### 安装\n\nPHP8\n``` php\ncomposer require fenguoz/tron-php\n```\n\nor PHP7\n``` php\ncomposer require fenguoz/tron-php ~1.3\n```\n\n### 接口调用\n\n``` php\nuse GuzzleHttp\\Client;\n\n$uri = 'https://api.trongrid.io';// mainnet\n// $uri = 'https://api.shasta.trongrid.io';// shasta testnet\n$api = new \\Tron\\Api(new Client(['base_uri' => $uri]));\n\n$trxWallet = new \\Tron\\TRX($api);\n$addressData = $trxWallet->generateAddress();\n// $addressData->privateKey\n// $addressData->address\n\n$config = [\n    'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20\n    'decimals' => 6,\n];\n$trc20Wallet = new \\Tron\\TRC20($api, $config);\n$addressData = $trc20Wallet->generateAddress();\n```\n\n## 计划\n\n- 支持 TRC10\n- 智能合约\n\n## 扩展包\n\n| 扩展包名 | 描述 | 应用场景 |\n| :-----| :---- | :---- |\n| [fenguoz/tron-api](https://github.com/fenguoz/tron-api) | 波场官方文档推荐 PHP 扩展包 | 波场基础Api |\n\n## 🌟🌟\n\n[![Stargazers over time](https://starchart.cc/Fenguoz/tron-php.svg)](https://starchart.cc/Fenguoz/tron-php)\n\n## 合作\n\n联系方式\n- WX：zgf243944672\n- QQ：243944672\n"
  },
  {
    "path": "README.md",
    "content": "English | [中文](./README-CN.md)\n\n<h1 align=\"center\">TRON-PHP</h1>\n\n<p align=\"center\">\n  <a href=\"https://github.com/Fenguoz/tron-php/releases\"><img src=\"https://poser.pugx.org/Fenguoz/tron-php/v/stable\" alt=\"Stable Version\"></a>\n  <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>\n  <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>\n  <a href=\"https://packagist.org/packages/Fenguoz/tron-php\"><img src=\"https://poser.pugx.org/Fenguoz/tron-php/downloads\" alt=\"Total Downloads\"></a>\n</p>\n\n## Introduction\n\nSupport 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\n\n## Advantage\n\n1. One set of scripts is compatible with all TRX currencies and TRC20 certifications in the TRON network\n1. Interface methods can be added or subtracted flexibly\n\n## Support Method\n\n- Generate address `generateAddress()`\n- Verify address `validateAddress(Address $address)`\n- Get the address according to the private key `privateKeyToAddress(string $privateKeyHex)`\n- Check balances `balance(Address $address)`\n- Transaction transfer (offline signature) `transfer(string $from, string $to, float $amount)`\n- Query the latest block `blockNumber()`\n- Query information according to the blockchain `blockByNumber(int $blockID)`\n- *Query information based on transaction hash `transactionReceipt(string $txHash)`\n\n## Quick Start\n\n### Install\n\nPHP8\n``` php\ncomposer require fenguoz/tron-php\n```\n\nor PHP7\n``` php\ncomposer require fenguoz/tron-php ~1.3\n```\n\n### Interface\n\n``` php\nuse GuzzleHttp\\Client;\n\n$uri = 'https://api.trongrid.io';// mainnet\n// $uri = 'https://api.shasta.trongrid.io';// shasta testnet\n$api = new \\Tron\\Api(new Client(['base_uri' => $uri]));\n\n$trxWallet = new \\Tron\\TRX($api);\n$addressData = $trxWallet->generateAddress();\n// $addressData->privateKey\n// $addressData->address\n\n$config = [\n    'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20\n    'decimals' => 6,\n];\n$trc20Wallet = new \\Tron\\TRC20($api, $config);\n$addressData = $trc20Wallet->generateAddress();\n```\n\n## Plan\n\n- Support TRC10\n- Smart Contract\n\n## Package\n\n| Name | description | Scenes |\n| :-----| :---- | :---- |\n| [Fenguoz/tron-api](https://github.com/Fenguoz/tron-api) | TRON official document recommends PHP extension package | TRON basic API |\n\n## 🌟🌟\n\n[![Stargazers over time](https://starchart.cc/Fenguoz/tron-php.svg)](https://starchart.cc/Fenguoz/tron-php)\n\n## Cooperate\n\nContact\n- WX：zgf243944672\n- QQ：243944672\n"
  },
  {
    "path": "composer.json",
    "content": "{\n    \"name\": \"fenguoz/tron-php\",\n    \"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\",\n    \"keywords\": [\n        \"php\",\n        \"tron\",\n        \"trx\",\n        \"trc20\"\n    ],\n    \"type\": \"library\",\n    \"homepage\": \"https://github.com/Fenguoz/tron-php\",\n    \"license\": \"MIT\",\n    \"authors\": [\n        {\n            \"name\": \"Fenguoz\",\n            \"email\": \"243944672@qq.com\"\n        }\n    ],\n    \"require\": {\n        \"php\": \">=8.0\",\n        \"fenguoz/tron-api\": \"~1.1\",\n        \"ionux/phactor\": \"1.0.8\",\n        \"kornrunner/keccak\": \"~1.0\"\n    },\n    \"require-dev\": {\n        \"phpunit/phpunit\": \"~7.5 || ~9.0\"\n    },\n    \"autoload\": {\n        \"psr-4\": {\n            \"Tron\\\\\": \"src/\"\n        }\n    },\n    \"autoload-dev\": {\n        \"psr-4\": {\n            \"Test\\\\\": \"tests/\"\n        }\n    }\n}\n"
  },
  {
    "path": "src/Address.php",
    "content": "<?php\n\nnamespace Tron;\n\nuse IEXBase\\TronAPI\\Support\\Base58Check;\nuse IEXBase\\TronAPI\\Support\\Hash;\n\nclass Address\n{\n    public $privateKey,\n        $address,\n        $hexAddress = '';\n\n    const ADDRESS_SIZE = 34;\n    const ADDRESS_PREFIX = \"41\";\n    const ADDRESS_PREFIX_BYTE = 0x41;\n\n    public function __construct(string $address = '', string $privateKey = '', string $hexAddress = '')\n    {\n        if (strlen($address) === 0) {\n            throw new \\InvalidArgumentException('Address can not be empty');\n        }\n\n        $this->privateKey = $privateKey;\n        $this->address = $address;\n        $this->hexAddress = $hexAddress;\n    }\n\n    /**\n     * Dont rely on this. Always use Wallet::validateAddress to double check\n     * against tronGrid.\n     *\n     * @return bool\n     */\n    public function isValid(): bool\n    {\n        if (strlen($this->address) !== Address::ADDRESS_SIZE) {\n            return false;\n        }\n\n        $address = Base58Check::decode($this->address, false, 0, false);\n        $utf8 = hex2bin($address);\n\n        if (strlen($utf8) !== 25) {\n            return false;\n        }\n\n        if (strpos($utf8, chr(self::ADDRESS_PREFIX_BYTE)) !== 0) {\n            return false;\n        }\n\n        $checkSum = substr($utf8, 21);\n        $address = substr($utf8, 0, 21);\n\n        $hash0 = Hash::SHA256($address);\n        $hash1 = Hash::SHA256($hash0);\n        $checkSum1 = substr($hash1, 0, 4);\n\n        if ($checkSum === $checkSum1) {\n            return true;\n        }\n\n        return false;\n    }\n}\n"
  },
  {
    "path": "src/Api.php",
    "content": "<?php\n\nnamespace Tron;\n\nuse GuzzleHttp\\Client;\nuse Tron\\Exceptions\\TronErrorException;\n\nclass Api\n{\n    private $_client;\n\n    public function __construct(Client $client)\n    {\n        $this->_client = $client;\n    }\n\n    public function getClient(): Client\n    {\n        return $this->_client;\n    }\n\n    /**\n     * Abstracts some common functionality like formatting the post data\n     * along with error handling.\n     *\n     * @throws TronErrorException\n     */\n    public function post(string $endpoint, array $data = [], bool $returnAssoc = false)\n    {\n        if (sizeof($data)) {\n            $data = ['json' => $data];\n        }\n\n        $stream = (string)$this->getClient()->post($endpoint, $data)->getBody();\n        $body = json_decode($stream, $returnAssoc);\n\n        $this->checkForErrorResponse($returnAssoc, $body);\n\n        return $body;\n    }\n\n    /**\n     * Check if the response has an error and throw it.\n     *\n     * @param bool $returnAssoc\n     * @param $body\n     * @throws TronErrorException\n     */\n    private function checkForErrorResponse(bool $returnAssoc, $body)\n    {\n        if ($returnAssoc) {\n            if (isset($body['Error'])) {\n                throw new TronErrorException($body['Error']);\n            } elseif (isset($body['code']) && isset($body['message'])) {\n                throw new TronErrorException($body['code'] . ': ' . hex2bin($body['message']));\n            }\n        }\n\n        if (isset($body->Error)) {\n            throw new TronErrorException($body->Error);\n        } elseif (isset($body->code) && isset($body->message)) {\n            throw new TronErrorException($body->code . ': ' . hex2bin($body->message));\n        }\n    }\n}\n"
  },
  {
    "path": "src/Block.php",
    "content": "<?php\n\nnamespace Tron;\n\nclass Block\n{\n    public $blockID;\n    public $block_header;\n    public $transactions;\n\n    public function __construct(string $blockID, array $block_header, array $transactions = [])\n    {\n        if (!strlen($blockID)) {\n            throw new \\Exception('blockID empty');\n        }\n\n        $this->blockID = $blockID;\n        $this->block_header = $block_header;\n        $this->transactions = $transactions;\n    }\n}\n"
  },
  {
    "path": "src/Exceptions/TransactionException.php",
    "content": "<?php\n\nnamespace Tron\\Exceptions;\n\nclass TransactionException extends \\Exception\n{\n}\n"
  },
  {
    "path": "src/Exceptions/TronErrorException.php",
    "content": "<?php\n\nnamespace Tron\\Exceptions;\n\nclass TronErrorException extends \\Exception\n{\n}\n"
  },
  {
    "path": "src/Interfaces/WalletInterface.php",
    "content": "<?php\n\nnamespace Tron\\Interfaces;\n\nuse Tron\\Address;\nuse Tron\\Block;\nuse Tron\\Transaction;\n\ninterface WalletInterface\n{\n    public function generateAddress(): Address;\n\n    public function validateAddress(Address $address): bool;\n\n    public function privateKeyToAddress(string $privateKeyHex): Address;\n\n    public function balance(Address $address);\n\n    public function transfer(Address $from, Address $to, float $amount): Transaction;\n\n    public function blockNumber(): Block;\n\n    public function blockByNumber(int $blockID): Block;\n\n    public function transactionReceipt(string $txHash);\n}\n"
  },
  {
    "path": "src/Support/Formatter.php",
    "content": "<?php\n\nnamespace Tron\\Support;\n\n/**\n * 数据签名\n * Class Formatter\n * @package Ethereum\n */\nclass Formatter\n{\n\n    /**\n     * 对于方法名和参数类型做签名\n     * @param $method\n     * @return string\n     */\n    public static function toMethodFormat($method)\n    {\n        return Utils::stripZero(substr(Utils::sha3($method), 0, 10));\n    }\n\n    /**\n     * 地址签名\n     * @param $address\n     * @return string\n     */\n    public static function toAddressFormat($address)\n    {\n        if (Utils::isAddress($address)) {\n            $address = strtolower($address);\n\n            if (Utils::isZeroPrefixed($address)) {\n                $address = Utils::stripZero($address);\n            }\n        }\n        return implode('', array_fill(0, 64 - strlen($address), 0)) . $address;\n    }\n\n    /**\n     * 数字签名\n     * @param $value\n     * @param int $digit\n     * @return string\n     */\n    public static function toIntegerFormat($value, $digit = 64)\n    {\n        $bn = Utils::toBn($value);\n        $bnHex = $bn->toHex(true);\n        $padded = mb_substr($bnHex, 0, 1);\n\n        if ($padded !== 'f') {\n            $padded = '0';\n        }\n        return implode('', array_fill(0, $digit - mb_strlen($bnHex), $padded)) . $bnHex;\n    }\n}\n"
  },
  {
    "path": "src/Support/Key.php",
    "content": "<?php\n\nnamespace Tron\\Support;\n\nuse Elliptic\\EC;\nuse IEXBase\\TronAPI\\Support\\Base58;\nuse IEXBase\\TronAPI\\Support\\Crypto;\nuse IEXBase\\TronAPI\\Support\\Hash;\n\nuse InvalidArgumentException;\nuse RuntimeException;\n\nclass Key\n{\n    /**\n     * Generate the Address of the provided Public key\n     * \n     * @param string $publicKey \n     * \n     * @return string\n     */\n    public static function publicKeyToAddress(string $publicKey)\n    {\n        if (Utils::isHex($publicKey) === false) {\n            throw new InvalidArgumentException('Invalid public key format.');\n        }\n        $publicKey = Utils::stripZero($publicKey);\n        if (strlen($publicKey) !== 130) {\n            throw new InvalidArgumentException('Invalid public key length.');\n        }\n        return substr(Utils::sha3(substr(hex2bin($publicKey), 1)), 24);\n    }\n\n    /**\n     * Generate the Address of the provided Private key\n     * \n     * @param string $privateKey \n     * \n     * @return string\n     */\n    public static function privateKeyToAddress(string $privateKey)\n    {\n        return self::publicKeyToAddress(\n            self::privateKeyToPublicKey($privateKey)\n        );\n    }\n\n    /**\n     * Generate the Public key for provided Private key\n     * \n     * @param string $privateKey Private Key\n     * \n     * @return string\n     */\n    public static function privateKeyToPublicKey(string $privateKey)\n    {\n        if (Utils::isHex($privateKey) === false) {\n            throw new InvalidArgumentException('Invalid private key format.');\n        }\n        $privateKey = Utils::stripZero($privateKey);\n\n        if (strlen($privateKey) !== 64) {\n            throw new InvalidArgumentException('Invalid private key length.');\n        }\n\n        $secp256k1 = new EC('secp256k1');\n        $privateKey = $secp256k1->keyFromPrivate($privateKey, 'hex');\n        $publicKey = $privateKey->getPublic(false, 'hex');\n\n        return $publicKey;\n    }\n\n    public static function getBase58CheckAddress(string $addressHex): string\n    {\n        $addressBin = hex2bin($addressHex);\n        $hash0 = Hash::SHA256($addressBin);\n        $hash1 = Hash::SHA256($hash0);\n        $checksum = substr($hash1, 0, 4);\n        $checksum = $addressBin . $checksum;\n\n        return Base58::encode(Crypto::bin2bc($checksum));\n    }\n}\n"
  },
  {
    "path": "src/Support/Utils.php",
    "content": "<?php\n\nnamespace Tron\\Support;\n\nuse InvalidArgumentException;\nuse kornrunner\\Keccak;\nuse phpseclib\\Math\\BigInteger;\nuse Psr\\Http\\Message\\StreamInterface;\n\nclass Utils\n{\n    /**\n     * SHA3_NULL_HASH\n     *\n     * @const string\n     */\n    const SHA3_NULL_HASH = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';\n\n    /**\n     * NEGATIVE1\n     * Cannot work, see: http://php.net/manual/en/language.constants.syntax.php\n     *\n     * @const\n     */\n    // const NEGATIVE1 = new BigInteger(-1);\n\n    /**\n     * construct\n     *\n     * @return void\n     */\n    // public function __construct() {}\n\n    /**\n     * toHex\n     * Encoding string or integer or numeric string(is not zero prefixed) or big number to hex.\n     *\n     * @param string|int|BigInteger $value\n     * @param bool $isPrefix\n     * @return string\n     */\n    public static function toHex($value, $isPrefix = false)\n    {\n        if (is_numeric($value)) {\n            // turn to hex number\n            $bn = self::toBn($value);\n            $hex = $bn->toHex(true);\n            $hex = preg_replace('/^0+(?!$)/', '', $hex);\n        } elseif (is_string($value)) {\n            $value = self::stripZero($value);\n            $hex = implode('', unpack('H*', $value));\n        } elseif ($value instanceof BigInteger) {\n            $hex = $value->toHex(true);\n            $hex = preg_replace('/^0+(?!$)/', '', $hex);\n        } else {\n            throw new InvalidArgumentException('The value to toHex function is not support.');\n        }\n        if ($isPrefix) {\n            return '0x' . $hex;\n        }\n        return $hex;\n    }\n\n    /**\n     * hexToBin\n     *\n     * @param string\n     * @return string\n     */\n    public static function hexToBin($value)\n    {\n        if (!is_string($value)) {\n            throw new InvalidArgumentException('The value to hexToBin function must be string.');\n        }\n        if (self::isZeroPrefixed($value)) {\n            $count = 1;\n            $value = str_replace('0x', '', $value, $count);\n        }\n        return pack('H*', $value);\n    }\n\n    /**\n     * isZeroPrefixed\n     *\n     * @param string\n     * @return bool\n     */\n    public static function isZeroPrefixed($value)\n    {\n        if (!is_string($value)) {\n            throw new InvalidArgumentException('The value to isZeroPrefixed function must be string.');\n        }\n        return (strpos($value, '0x') === 0);\n    }\n\n    /**\n     * stripZero\n     *\n     * @param string $value\n     * @return string\n     */\n    public static function stripZero($value)\n    {\n        if (self::isZeroPrefixed($value)) {\n            $count = 1;\n            return str_replace('0x', '', $value, $count);\n        }\n        return $value;\n    }\n\n    /**\n     * isNegative\n     *\n     * @param string\n     * @return bool\n     */\n    public static function isNegative($value)\n    {\n        if (!is_string($value)) {\n            throw new InvalidArgumentException('The value to isNegative function must be string.');\n        }\n        return (strpos($value, '-') === 0);\n    }\n\n    /**\n     * isAddress\n     *\n     * @param string $value\n     * @return bool\n     */\n    public static function isAddress($value)\n    {\n        if (!is_string($value)) {\n            throw new InvalidArgumentException('The value to isAddress function must be string.');\n        }\n        if (preg_match('/^(0x|0X)?[a-f0-9A-F]{40}$/', $value) !== 1) {\n            return false;\n        } elseif (preg_match('/^(0x|0X)?[a-f0-9]{40}$/', $value) === 1 || preg_match('/^(0x|0X)?[A-F0-9]{40}$/', $value) === 1) {\n            return true;\n        }\n        return self::isAddressChecksum($value);\n    }\n\n    /**\n     * isAddressChecksum\n     *\n     * @param string $value\n     * @return bool\n     */\n    public static function isAddressChecksum($value)\n    {\n        if (!is_string($value)) {\n            throw new InvalidArgumentException('The value to isAddressChecksum function must be string.');\n        }\n        $value = self::stripZero($value);\n        $hash = self::stripZero(self::sha3(mb_strtolower($value)));\n\n        for ($i = 0; $i < 40; $i++) {\n            if (\n                (intval($hash[$i], 16) > 7 && mb_strtoupper($value[$i]) !== $value[$i]) ||\n                (intval($hash[$i], 16) <= 7 && mb_strtolower($value[$i]) !== $value[$i])\n            ) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * isHex\n     *\n     * @param string $value\n     * @return bool\n     */\n    public static function isHex($value)\n    {\n        return (is_string($value) && preg_match('/^(0x)?[a-f0-9A-F]*$/', $value) === 1);\n    }\n\n    /**\n     * sha3\n     * keccak256\n     *\n     * @param string $value\n     * @return string\n     */\n    public static function sha3($value)\n    {\n        if (!is_string($value)) {\n            throw new InvalidArgumentException('The value to sha3 function must be string.');\n        }\n        if (strpos($value, '0x') === 0) {\n            $value = self::hexToBin($value);\n        }\n        $hash = Keccak::hash($value, 256);\n\n        if ($hash === self::SHA3_NULL_HASH) {\n            return null;\n        }\n        return $hash;\n    }\n\n    /**\n     * toBn\n     * Change number or number string to BigInteger.\n     *\n     * @param BigInteger|string|int $number\n     * @return array|BigInteger\n     */\n    public static function toBn($number)\n    {\n        if ($number instanceof BigInteger) {\n            $bn = $number;\n        } elseif (is_int($number)) {\n            $bn = new BigInteger($number);\n        } elseif (is_numeric($number)) {\n            $number = (string) $number;\n\n            if (self::isNegative($number)) {\n                $count = 1;\n                $number = str_replace('-', '', $number, $count);\n                $negative1 = new BigInteger(-1);\n            }\n            if (strpos($number, '.') > 0) {\n                $comps = explode('.', $number);\n\n                if (count($comps) > 2) {\n                    throw new InvalidArgumentException('toBn number must be a valid number.');\n                }\n                $whole = $comps[0];\n                $fraction = $comps[1];\n\n                return [\n                    new BigInteger($whole),\n                    new BigInteger($fraction),\n                    strlen($comps[1]),\n                    isset($negative1) ? $negative1 : false\n                ];\n            } else {\n                $bn = new BigInteger($number);\n            }\n            if (isset($negative1)) {\n                $bn = $bn->multiply($negative1);\n            }\n        } elseif (is_string($number)) {\n            $number = mb_strtolower($number);\n\n            if (self::isNegative($number)) {\n                $count = 1;\n                $number = str_replace('-', '', $number, $count);\n                $negative1 = new BigInteger(-1);\n            }\n            if (self::isZeroPrefixed($number) || preg_match('/[a-f]+/', $number) === 1) {\n                $number = self::stripZero($number);\n                $bn = new BigInteger($number, 16);\n            } elseif (empty($number)) {\n                $bn = new BigInteger(0);\n            } else {\n                throw new InvalidArgumentException('toBn number must be valid hex string.');\n            }\n            if (isset($negative1)) {\n                $bn = $bn->multiply($negative1);\n            }\n        } else {\n            throw new InvalidArgumentException('toBn number must be BigInteger, string or int.');\n        }\n        return $bn;\n    }\n\n    /**\n     * 根据精度展示资产\n     * @param $number\n     * @param int $decimals\n     * @return string\n     */\n    public static function toDisplayAmount($number, int $decimals)\n    {\n        $number = number_format($number,0,'.','');//格式化\n        $bn = self::toBn($number);\n        $bnt = self::toBn(pow(10, $decimals));\n\n        return self::divideDisplay($bn->divide($bnt), $decimals);\n    }\n\n    public static function divideDisplay(array $divResult, int $decimals)\n    {\n        list($bnq, $bnr) = $divResult;\n        $ret = \"$bnq->value\";\n        if ($bnr->value > 0) {\n            $ret .= '.' . rtrim(sprintf(\"%0{$decimals}d\", $bnr->value), '0');\n        }\n\n        return $ret;\n    }\n\n    public static function toMinUnitByDecimals($number, int $decimals)\n    {\n        $bn = self::toBn($number);\n        $bnt = self::toBn(pow(10, $decimals));\n\n        if (is_array($bn)) {\n            // fraction number\n            list($whole, $fraction, $fractionLength, $negative1) = $bn;\n\n            $whole = $whole->multiply($bnt);\n\n            switch (MATH_BIGINTEGER_MODE) {\n                case $whole::MODE_GMP:\n                    static $two;\n                    $powerBase = gmp_pow(gmp_init(10), (int) $fractionLength);\n                    break;\n                case $whole::MODE_BCMATH:\n                    $powerBase = bcpow('10', (string) $fractionLength, 0);\n                    break;\n                default:\n                    $powerBase = pow(10, (int) $fractionLength);\n                    break;\n            }\n            $base = new BigInteger($powerBase);\n            $fraction = $fraction->multiply($bnt)->divide($base)[0];\n\n            if ($negative1 !== false) {\n                return $whole->add($fraction)->multiply($negative1);\n            }\n            return $whole->add($fraction);\n        }\n\n        return $bn->multiply($bnt);\n    }\n}\n"
  },
  {
    "path": "src/TRC20.php",
    "content": "<?php\n\nnamespace Tron;\n\nuse IEXBase\\TronAPI\\Exception\\TronException;\nuse Tron\\Exceptions\\TransactionException;\nuse Tron\\Exceptions\\TronErrorException;\nuse Tron\\Support\\Formatter;\nuse Tron\\Support\\Utils;\nuse InvalidArgumentException;\n\nclass TRC20 extends TRX\n{\n    protected $contractAddress;\n\n    protected $decimals;\n\n    public function __construct(Api $_api, array $config)\n    {\n        parent::__construct($_api, $config);\n\n        $this->contractAddress = new Address(\n            $config['contract_address'],\n            '',\n            $this->tron->address2HexString($config['contract_address'])\n        );\n        $this->decimals = $config['decimals'];\n    }\n\n    public function balance(Address $address)\n    {\n        $format = Formatter::toAddressFormat($address->hexAddress);\n        $body = $this->_api->post('/wallet/triggersmartcontract', [\n            'contract_address' => $this->contractAddress->hexAddress,\n            'function_selector' => 'balanceOf(address)',\n            'parameter' => $format,\n            'owner_address' => $address->hexAddress,\n        ]);\n\n        if (isset($body->result->code)) {\n            throw new TronErrorException(hex2bin($body->result->message));\n        }\n\n        try {\n            $balance = Utils::toDisplayAmount(hexdec($body->constant_result[0]), $this->decimals);\n        } catch (InvalidArgumentException $e) {\n            throw new TronErrorException($e->getMessage());\n        }\n        return $balance;\n    }\n\n    public function transfer(Address $from, Address $to, float $amount): Transaction\n    {\n        $this->tron->setAddress($from->address);\n        $this->tron->setPrivateKey($from->privateKey);\n\n        $toFormat = Formatter::toAddressFormat($to->hexAddress);\n        try {\n            $amount = Utils::toMinUnitByDecimals($amount, $this->decimals);\n        } catch (InvalidArgumentException $e) {\n            throw new TronErrorException($e->getMessage());\n        }\n        $numberFormat = Formatter::toIntegerFormat($amount);\n\n        $body = $this->_api->post('/wallet/triggersmartcontract', [\n            'contract_address' => $this->contractAddress->hexAddress,\n            'function_selector' => 'transfer(address,uint256)',\n            'parameter' => \"{$toFormat}{$numberFormat}\",\n            'fee_limit' => 100000000,\n            'call_value' => 0,\n            'owner_address' => $from->hexAddress,\n        ], true);\n\n        if (isset($body['result']['code'])) {\n            throw new TransactionException(hex2bin($body['result']['message']));\n        }\n\n        try {\n            $tradeobj = $this->tron->signTransaction($body['transaction']);\n            $response = $this->tron->sendRawTransaction($tradeobj);\n        } catch (TronException $e) {\n            throw new TransactionException($e->getMessage(), $e->getCode());\n        }\n\n        if (isset($response['result']) && $response['result'] == true) {\n            return new Transaction(\n                $body['transaction']['txID'],\n                $body['transaction']['raw_data'],\n                'PACKING'\n            );\n        } else {\n            throw new TransactionException(hex2bin($response['result']['message']));\n        }\n    }\n}\n"
  },
  {
    "path": "src/TRX.php",
    "content": "<?php\n\nnamespace Tron;\n\nuse Phactor\\Key;\nuse IEXBase\\TronAPI\\Exception\\TronException;\nuse IEXBase\\TronAPI\\Tron;\nuse IEXBase\\TronAPI\\Provider\\HttpProvider;\nuse Tron\\Interfaces\\WalletInterface;\nuse Tron\\Exceptions\\TronErrorException;\nuse Tron\\Exceptions\\TransactionException;\nuse Tron\\Support\\Key as SupportKey;\nuse InvalidArgumentException;\n\nclass TRX implements WalletInterface\n{\n    protected $_api;\n\n    protected $tron;\n    \n    public function __construct(Api $_api, array $config = [])\n    {\n        $this->_api = $_api;\n\n        $host = $_api->getClient()->getConfig('base_uri')->getScheme() . '://' . $_api->getClient()->getConfig('base_uri')->getHost();\n        $fullNode = new HttpProvider($host);\n        $solidityNode = new HttpProvider($host);\n        $eventServer = new HttpProvider($host);\n        try {\n            $this->tron = new Tron($fullNode, $solidityNode, $eventServer);\n        } catch (TronException $e) {\n            throw new TronErrorException($e->getMessage(), $e->getCode());\n        }\n    }\n\n    public function generateAddress(): Address\n    {\n        $attempts = 0;\n        $validAddress = false;\n\n        do {\n            if ($attempts++ === 5) {\n                throw new TronErrorException('Could not generate valid key');\n            }\n\n            $key = new Key([\n                'private_key_hex' => '',\n                'private_key_dec' => '',\n                'public_key' => '',\n                'public_key_compressed' => '',\n                'public_key_x' => '',\n                'public_key_y' => ''\n            ]);\n            $keyPair = $key->GenerateKeypair();\n            $privateKeyHex = $keyPair['private_key_hex'];\n            $pubKeyHex = $keyPair['public_key'];\n\n            //We cant use hex2bin unless the string length is even.\n            if (strlen($pubKeyHex) % 2 !== 0) {\n                continue;\n            }\n\n            try {\n                $addressHex = Address::ADDRESS_PREFIX . SupportKey::publicKeyToAddress($pubKeyHex);\n                $addressBase58 = SupportKey::getBase58CheckAddress($addressHex);\n            } catch (InvalidArgumentException $e) {\n                throw new TronErrorException($e->getMessage());\n            }\n            $address = new Address($addressBase58, $privateKeyHex, $addressHex);\n            $validAddress = $this->validateAddress($address);\n        } while (!$validAddress);\n\n        return $address;\n    }\n\n    public function validateAddress(Address $address): bool\n    {\n        if (!$address->isValid()) {\n            return false;\n        }\n\n        $body = $this->_api->post('/wallet/validateaddress', [\n            'address' => $address->address,\n        ]);\n\n        return $body->result;\n    }\n\n    public function privateKeyToAddress(string $privateKeyHex): Address\n    {\n        try {\n            $addressHex = Address::ADDRESS_PREFIX . SupportKey::privateKeyToAddress($privateKeyHex);\n            $addressBase58 = SupportKey::getBase58CheckAddress($addressHex);\n        } catch (InvalidArgumentException $e) {\n            throw new TronErrorException($e->getMessage());\n        }\n        $address = new Address($addressBase58, $privateKeyHex, $addressHex);\n        $validAddress = $this->validateAddress($address);\n        if (!$validAddress) {\n            throw new TronErrorException('Invalid private key');\n        }\n\n        return $address;\n    }\n\n    public function balance(Address $address)\n    {\n        $this->tron->setAddress($address->address);\n        return $this->tron->getBalance(null, true);\n    }\n\n    public function transfer(Address $from, Address $to, float $amount): Transaction\n    {\n        $this->tron->setAddress($from->address);\n        $this->tron->setPrivateKey($from->privateKey);\n\n        try {\n            $transaction = $this->tron->getTransactionBuilder()->sendTrx($to->address, $amount, $from->address);\n            $signedTransaction = $this->tron->signTransaction($transaction);\n            $response = $this->tron->sendRawTransaction($signedTransaction);\n        } catch (TronException $e) {\n            throw new TransactionException($e->getMessage(), $e->getCode());\n        }\n\n        if (isset($response['result']) && $response['result'] == true) {\n            return new Transaction(\n                $transaction['txID'],\n                $transaction['raw_data'],\n                'PACKING'\n            );\n        } else {\n            throw new TransactionException(hex2bin($response['message']));\n        }\n    }\n\n    public function blockNumber(): Block\n    {\n        try {\n            $block = $this->tron->getCurrentBlock();\n        } catch (TronException $e) {\n            throw new TransactionException($e->getMessage(), $e->getCode());\n        }\n        $transactions = isset($block['transactions']) ? $block['transactions'] : [];\n        return new Block($block['blockID'], $block['block_header'], $transactions);\n    }\n\n    public function blockByNumber(int $blockID): Block\n    {\n        try {\n            $block = $this->tron->getBlockByNumber($blockID);\n        } catch (TronException $e) {\n            throw new TransactionException($e->getMessage(), $e->getCode());\n        }\n\n        $transactions = isset($block['transactions']) ? $block['transactions'] : [];\n        return new Block($block['blockID'], $block['block_header'], $transactions);\n    }\n\n    public function transactionReceipt(string $txHash): Transaction\n    {\n        try {\n            $detail = $this->tron->getTransaction($txHash);\n        } catch (TronException $e) {\n            throw new TransactionException($e->getMessage(), $e->getCode());\n        }\n        return new Transaction(\n            $detail['txID'],\n            $detail['raw_data'],\n            $detail['ret'][0]['contractRet'] ?? ''\n        );\n    }\n}\n"
  },
  {
    "path": "src/Transaction.php",
    "content": "<?php\n\nnamespace Tron;\n\nclass Transaction\n{\n    public $signature = [];\n    public $txID = '';\n    public $raw_data = [];\n    public $contractRet = '';\n\n    public function __construct(string $txID, array $rawData, string $contractRet)\n    {\n        $this->txID = $txID;\n        $this->raw_data = $rawData;\n        $this->contractRet = $contractRet;\n    }\n\n    public function isSigned(): bool\n    {\n        return (bool)sizeof($this->signature);\n    }\n}\n"
  },
  {
    "path": "tests/TRC20Test.php",
    "content": "<?php\n\n/**\n * This file is part of the tron-php package\n *\n * @category tron-php\n * @package  tron-php\n * @author   Fenguoz <243944672@qq.com>\n * @license  https://github.com/Fenguoz/tron-php/blob/master/LICENSE MIT\n * @link     https://github.com/Fenguoz/tron-php\n */\n\nnamespace Tests;\n\nuse GuzzleHttp\\Client;\nuse PHPUnit\\Framework\\TestCase;\nuse Tron\\Address;\nuse Tron\\Api;\nuse Tron\\TRC20;\n\nclass TRC20Test extends TestCase\n{\n    const URI = 'https://api.trongrid.io'; // mainnet\n    // const URI = 'https://api.shasta.trongrid.io'; // shasta testnet\n    const ADDRESS = 'TGytofNKuSReFmFxsgnNx19em3BAVBTpVB';\n    const PRIVATE_KEY = '0xf1b4b7d86a3eff98f1bace9cb2665d0cad3a3f949bc74a7ffb2aaa968c07f521';\n    const BLOCK_ID = 13402554;\n    const TX_HASH = '539e6c2429f19a8626fadc1211985728e310f5bd5d2749c88db2e3f22a8fdf69';\n    const CONTRACT = [\n        'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', // USDT TRC20\n        'decimals' => 6,\n    ];\n\n    private function getTRC20()\n    {\n        $api = new Api(new Client(['base_uri' => self::URI]));\n        $config = self::CONTRACT;\n        $trxWallet = new TRC20($api, $config);\n        return $trxWallet;\n    }\n\n    public function testGenerateAddress()\n    {\n        $addressData = $this->getTRC20()->generateAddress();\n        var_dump($addressData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testPrivateKeyToAddress()\n    {\n        $privateKey = self::PRIVATE_KEY;\n        $addressData = $this->getTRC20()->privateKeyToAddress($privateKey);\n        var_dump($addressData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testBalance()\n    {\n        $address = new Address(\n            self::ADDRESS,\n            '',\n            $this->getTRC20()->tron->address2HexString(self::ADDRESS)\n        );\n        $balanceData = $this->getTRC20()->balance($address);\n        var_dump($balanceData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testTransfer()\n    {\n        $privateKey = self::PRIVATE_KEY;\n        $address = self::ADDRESS;\n        $amount = 1;\n\n        $from = $this->getTRC20()->privateKeyToAddress($privateKey);\n        $to = new Address(\n            $address,\n            '',\n            $this->getTRC20()->tron->address2HexString($address)\n        );\n        $transferData = $this->getTRC20()->transfer($from, $to, $amount);\n        var_dump($transferData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testBlockNumber()\n    {\n        $blockData = $this->getTRC20()->blockNumber();\n        var_dump($blockData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testBlockByNumber()\n    {\n        $blockID = self::BLOCK_ID;\n        $blockData = $this->getTRC20()->blockByNumber($blockID);\n        var_dump($blockData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testTransactionReceipt()\n    {\n        $txHash = self::TX_HASH;\n        $txData = $this->getTRC20()->transactionReceipt($txHash);\n        var_dump($txData);\n\n        $this->assertTrue(true);\n    }\n}\n"
  },
  {
    "path": "tests/TRXTest.php",
    "content": "<?php\n\n/**\n * This file is part of the tron-php package\n *\n * @category tron-php\n * @package  tron-php\n * @author   Fenguoz <243944672@qq.com>\n * @license  https://github.com/Fenguoz/tron-php/blob/master/LICENSE MIT\n * @link     https://github.com/Fenguoz/tron-php\n */\n\nnamespace Tests;\n\nuse GuzzleHttp\\Client;\nuse PHPUnit\\Framework\\TestCase;\nuse Tron\\Address;\nuse Tron\\Api;\nuse Tron\\TRX;\n\nclass TRXTest extends TestCase\n{\n    const URI = 'https://api.shasta.trongrid.io'; // shasta testnet\n    const ADDRESS = 'TGytofNKuSReFmFxsgnNx19em3BAVBTpVB';\n    const PRIVATE_KEY = '0xf1b4b7d86a3eff98f1bace9cb2665d0cad3a3f949bc74a7ffb2aaa968c07f521';\n    const BLOCK_ID = 13402554;\n    const TX_HASH = '539e6c2429f19a8626fadc1211985728e310f5bd5d2749c88db2e3f22a8fdf69';\n\n    private function getTRX()\n    {\n        $api = new Api(new Client(['base_uri' => self::URI]));\n        $trxWallet = new TRX($api);\n        return $trxWallet;\n    }\n\n    public function testGenerateAddress()\n    {\n        $addressData = $this->getTRX()->generateAddress();\n        var_dump($addressData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testPrivateKeyToAddress()\n    {\n        $privateKey = self::PRIVATE_KEY;\n        $addressData = $this->getTRX()->privateKeyToAddress($privateKey);\n        var_dump($addressData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testBalance()\n    {\n        $address = new Address(\n            self::ADDRESS,\n            '',\n            $this->getTRX()->tron->address2HexString(self::ADDRESS)\n        );\n        $balanceData = $this->getTRX()->balance($address);\n        var_dump($balanceData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testTransfer()\n    {\n        $privateKey = self::PRIVATE_KEY;\n        $address = self::ADDRESS;\n        $amount = 1;\n\n        $from = $this->getTRX()->privateKeyToAddress($privateKey);\n        $to = new Address(\n            $address,\n            '',\n            $this->getTRX()->tron->address2HexString($address)\n        );\n        $transferData = $this->getTRX()->transfer($from, $to, $amount);\n        var_dump($transferData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testBlockNumber()\n    {\n        $blockData = $this->getTRX()->blockNumber();\n        var_dump($blockData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testBlockByNumber()\n    {\n        $blockID = self::BLOCK_ID;\n        $blockData = $this->getTRX()->blockByNumber($blockID);\n        var_dump($blockData);\n\n        $this->assertTrue(true);\n    }\n\n    public function testTransactionReceipt()\n    {\n        $txHash = self::TX_HASH;\n        $txData = $this->getTRX()->transactionReceipt($txHash);\n        var_dump($txData);\n\n        $this->assertTrue(true);\n    }\n}\n"
  }
]