Tron.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. <?php
  2. /**
  3. * TronAPI
  4. *
  5. * @author Shamsudin Serderov <steein.shamsudin@gmail.com>
  6. * @license https://github.com/iexbase/tron-api/blob/master/LICENSE (MIT License)
  7. * @version 1.3.4
  8. * @link https://github.com/iexbase/tron-api
  9. *
  10. * For the full copyright and license information, please view the LICENSE
  11. * file that was distributed with this source code.
  12. */
  13. declare(strict_types=1);
  14. namespace IEXBase\TronAPI;
  15. use Elliptic\EC;
  16. use IEXBase\TronAPI\Exception\TRC20Exception;
  17. use IEXBase\TronAPI\Support\Base58;
  18. use IEXBase\TronAPI\Support\Base58Check;
  19. use IEXBase\TronAPI\Support\Crypto;
  20. use IEXBase\TronAPI\Support\Hash;
  21. use IEXBase\TronAPI\Support\Keccak;
  22. use IEXBase\TronAPI\Support\Utils;
  23. use IEXBase\TronAPI\Provider\HttpProviderInterface;
  24. use IEXBase\TronAPI\Exception\TronException;
  25. /**
  26. * A PHP API for interacting with the Tron (TRX)
  27. *
  28. * @package TronAPI
  29. * @author Shamsudin Serderov <steein.shamsudin@gmail.com>
  30. * @since 1.0.0
  31. */
  32. class Tron implements TronInterface
  33. {
  34. use TronAwareTrait,
  35. Concerns\ManagesUniversal,
  36. Concerns\ManagesTronscan;
  37. const ADDRESS_SIZE = 34;
  38. const ADDRESS_PREFIX = "41";
  39. const ADDRESS_PREFIX_BYTE = 0x41;
  40. /**
  41. * Default Address:
  42. * Example:
  43. * - base58: T****
  44. * - hex: 41****
  45. *
  46. * @var array
  47. */
  48. public $address = [
  49. 'base58' => null,
  50. 'hex' => null
  51. ];
  52. /**
  53. * Private key
  54. *
  55. * @var string
  56. */
  57. protected $privateKey;
  58. /**
  59. * Default block
  60. *
  61. * @var string|integer|bool
  62. */
  63. protected $defaultBlock = 'latest';
  64. /**
  65. * Transaction Builder
  66. *
  67. * @var TransactionBuilder
  68. */
  69. protected $transactionBuilder;
  70. /**
  71. * Transaction Builder
  72. *
  73. * @var TransactionBuilder
  74. */
  75. protected $trc20Contract;
  76. /**
  77. * Provider manager
  78. *
  79. * @var TronManager
  80. */
  81. protected $manager;
  82. /**
  83. * Object Result
  84. *
  85. * @var bool
  86. */
  87. protected $isObject = false;
  88. /**
  89. * Create a new Tron object
  90. *
  91. * @param HttpProviderInterface $fullNode
  92. * @param HttpProviderInterface $solidityNode
  93. * @param HttpProviderInterface|null $eventServer
  94. * @param HttpProviderInterface|null $signServer
  95. * @param HttpProviderInterface|null $explorer
  96. * @param string $privateKey
  97. * @throws TronException
  98. */
  99. public function __construct(?HttpProviderInterface $fullNode = null,
  100. ?HttpProviderInterface $solidityNode = null,
  101. ?HttpProviderInterface $eventServer = null,
  102. ?HttpProviderInterface $signServer = null,
  103. ?HttpProviderInterface $explorer = null,
  104. ?string $privateKey = null)
  105. {
  106. if(!is_null($privateKey)) {
  107. $this->setPrivateKey($privateKey);
  108. }
  109. $this->setManager(new TronManager($this, [
  110. 'fullNode' => $fullNode,
  111. 'solidityNode' => $solidityNode,
  112. 'eventServer' => $eventServer,
  113. 'signServer' => $signServer,
  114. ]));
  115. $this->transactionBuilder = new TransactionBuilder($this);
  116. }
  117. /**
  118. * Create a new tron instance if the value isn't one already.
  119. *
  120. * @param HttpProviderInterface|null $fullNode
  121. * @param HttpProviderInterface|null $solidityNode
  122. * @param HttpProviderInterface|null $eventServer
  123. * @param HttpProviderInterface|null $signServer
  124. * @param string|null $privateKey
  125. * @return static
  126. * @throws TronException
  127. */
  128. public static function make(?HttpProviderInterface $fullNode = null,
  129. ?HttpProviderInterface $solidityNode = null,
  130. ?HttpProviderInterface $eventServer = null,
  131. ?HttpProviderInterface $signServer = null,
  132. string $privateKey = null) {
  133. return new static($fullNode, $solidityNode, $eventServer, $signServer, $privateKey);
  134. }
  135. /**
  136. * Фасад для Laravel
  137. *
  138. * @return Tron
  139. */
  140. public function getFacade(): Tron {
  141. return $this;
  142. }
  143. /**
  144. * Enter the link to the manager nodes
  145. *
  146. * @param $providers
  147. */
  148. public function setManager($providers) {
  149. $this->manager = $providers;
  150. }
  151. /**
  152. * Get provider manager
  153. *
  154. * @return TronManager
  155. */
  156. public function getManager(): TronManager {
  157. return $this->manager;
  158. }
  159. /**
  160. * Contract module
  161. *
  162. * @param string $contractAddress
  163. * @param string|null $abi
  164. * @return TRC20Contract
  165. */
  166. public function contract(string $contractAddress, string $abi = null)
  167. {
  168. return new TRC20Contract($this, $contractAddress, $abi);
  169. }
  170. /**
  171. * Set is object
  172. *
  173. * @param bool $value
  174. * @return Tron
  175. */
  176. public function setIsObject(bool $value)
  177. {
  178. $this->isObject = boolval($value);
  179. return $this;
  180. }
  181. /**
  182. * Get Transaction Builder
  183. *
  184. * @return TransactionBuilder
  185. */
  186. public function getTransactionBuilder(): TransactionBuilder
  187. {
  188. return $this->transactionBuilder;
  189. }
  190. /**
  191. * Check connected provider
  192. *
  193. * @param $provider
  194. * @return bool
  195. */
  196. public function isValidProvider($provider): bool
  197. {
  198. return ($provider instanceof HttpProviderInterface);
  199. }
  200. /**
  201. * Enter the default block
  202. *
  203. * @param bool $blockID
  204. * @return void
  205. * @throws TronException
  206. */
  207. public function setDefaultBlock($blockID = false): void
  208. {
  209. if($blockID === false || $blockID == 'latest' || $blockID == 'earliest' || $blockID === 0) {
  210. $this->defaultBlock = $blockID;
  211. return;
  212. }
  213. if(!is_integer($blockID)) {
  214. throw new TronException('Invalid block ID provided');
  215. }
  216. $this->defaultBlock = abs($blockID);
  217. }
  218. /**
  219. * Get default block
  220. *
  221. * @return string|integer|bool
  222. */
  223. public function getDefaultBlock()
  224. {
  225. return $this->defaultBlock;
  226. }
  227. /**
  228. * Enter your private account key
  229. *
  230. * @param string $privateKey
  231. */
  232. public function setPrivateKey(string $privateKey): void
  233. {
  234. $this->privateKey = $privateKey;
  235. }
  236. /**
  237. * Enter your account address
  238. *
  239. * @param string $address
  240. */
  241. public function setAddress(string $address): void
  242. {
  243. $_toHex = $this->address2HexString($address);
  244. $_fromHex = $this->hexString2Address($address);
  245. $this->address = [
  246. 'hex' => $_toHex,
  247. 'base58' => $_fromHex
  248. ];
  249. }
  250. /**
  251. * Get account address
  252. *
  253. * @return array
  254. */
  255. public function getAddress(): array
  256. {
  257. return $this->address;
  258. }
  259. /**
  260. * Get customized provider data
  261. *
  262. * @return array
  263. */
  264. public function providers(): array
  265. {
  266. return $this->manager->getProviders();
  267. }
  268. /**
  269. * Check Connection Providers
  270. *
  271. * @return array
  272. */
  273. public function isConnected(): array
  274. {
  275. return $this->manager->isConnected();
  276. }
  277. /**
  278. * Last block number
  279. *
  280. * @return array
  281. * @throws TronException
  282. */
  283. public function getCurrentBlock(): array
  284. {
  285. return $this->manager->request('wallet/getnowblock');
  286. }
  287. /**
  288. * Will return all events matching the filters.
  289. *
  290. * @param $contractAddress
  291. * @param int $sinceTimestamp
  292. * @param string|null $eventName
  293. * @param int $blockNumber
  294. * @return array
  295. * @throws TronException
  296. */
  297. public function getEventResult($contractAddress, int $sinceTimestamp = 0, string $eventName = null, int $blockNumber = 0)
  298. {
  299. if (!$this->isValidProvider($this->manager->eventServer())) {
  300. throw new TronException('No event server configured');
  301. }
  302. $routeParams = [];
  303. if($eventName && !$contractAddress) {
  304. throw new TronException('Usage of event name filtering requires a contract address');
  305. }
  306. if($blockNumber && !$eventName)
  307. throw new TronException('Usage of block number filtering requires an event name');
  308. if($contractAddress) {
  309. array_push($routeParams, $contractAddress);
  310. }
  311. if($eventName) {
  312. array_push($routeParams, $eventName);
  313. }
  314. if($blockNumber) {
  315. array_push($routeParams, $blockNumber);
  316. }
  317. $routeParams = implode('/', $routeParams);
  318. return $this->manager->request("event/contract/{$routeParams}?since={$sinceTimestamp}");
  319. }
  320. /**
  321. * Will return all events within a transactionID.
  322. *
  323. * @param string $transactionID
  324. * @return array
  325. * @throws TronException
  326. */
  327. public function getEventByTransactionID(string $transactionID)
  328. {
  329. if (!$this->isValidProvider($this->manager->eventServer())) {
  330. throw new TronException('No event server configured');
  331. }
  332. return $this->manager->request("event/transaction/{$transactionID}");
  333. }
  334. /**
  335. * Get block details using HashString or blockNumber
  336. *
  337. * @param null $block
  338. * @return array
  339. * @throws TronException
  340. */
  341. public function getBlock($block = null): array
  342. {
  343. $block = (is_null($block) ? $this->defaultBlock : $block);
  344. if($block === false) {
  345. throw new TronException('No block identifier provided');
  346. }
  347. if($block == 'earliest') {
  348. $block = 0;
  349. }
  350. if($block == 'latest') {
  351. return $this->getCurrentBlock();
  352. }
  353. if(Utils::isHex($block)) {
  354. return $this->getBlockByHash($block);
  355. }
  356. return $this->getBlockByNumber($block);
  357. }
  358. /**
  359. * Query block by ID
  360. *
  361. * @param $hashBlock
  362. * @return array
  363. * @throws TronException
  364. */
  365. public function getBlockByHash(string $hashBlock): array
  366. {
  367. return $this->manager->request('wallet/getblockbyid', [
  368. 'value' => $hashBlock
  369. ]);
  370. }
  371. /**
  372. * Query block by height
  373. *
  374. * @param $blockID
  375. * @return array
  376. * @throws TronException
  377. */
  378. public function getBlockByNumber(int $blockID): array
  379. {
  380. if(!is_integer($blockID) || $blockID < 0) {
  381. throw new TronException('Invalid block number provided');
  382. }
  383. $response = $this->manager->request('wallet/getblockbynum', [
  384. 'num' => intval($blockID)
  385. ]);
  386. if (empty($response)) {
  387. throw new TronException('Block not found');
  388. }
  389. return $response;
  390. }
  391. /**
  392. * Total number of transactions in a block
  393. *
  394. * @param $block
  395. * @return int
  396. * @throws TronException
  397. */
  398. public function getBlockTransactionCount($block): int
  399. {
  400. $transaction = $this->getBlock($block)['transactions'];
  401. if(!$transaction) {
  402. return 0;
  403. }
  404. return count($transaction);
  405. }
  406. /**
  407. * Get transaction details from Block
  408. *
  409. * @param null $block
  410. * @param int $index
  411. * @return array | string
  412. * @throws TronException
  413. */
  414. public function getTransactionFromBlock($block = null, $index = 0)
  415. {
  416. if(!is_integer($index) || $index < 0) {
  417. throw new TronException('Invalid transaction index provided');
  418. }
  419. $transactions = $this->getBlock($block)['transactions'];
  420. if(!$transactions || count($transactions) < $index) {
  421. throw new TronException('Transaction not found in block');
  422. }
  423. return $transactions[$index];
  424. }
  425. /**
  426. * Query transaction based on id
  427. *
  428. * @param $transactionID
  429. * @return array
  430. * @throws TronException
  431. */
  432. public function getTransaction(string $transactionID): array
  433. {
  434. $response = $this->manager->request('wallet/gettransactionbyid', [
  435. 'value' => $transactionID
  436. ]);
  437. if(!$response) {
  438. throw new TronException('Transaction not found');
  439. }
  440. return $response;
  441. }
  442. /**
  443. * Query transaction fee based on id
  444. *
  445. * @param $transactionID
  446. * @return array
  447. * @throws TronException
  448. */
  449. public function getTransactionInfo(string $transactionID): array
  450. {
  451. return $this->manager->request('walletsolidity/gettransactioninfobyid', [
  452. 'value' => $transactionID
  453. ]);
  454. }
  455. /**
  456. * Query the list of transactions received by an address
  457. *
  458. * @param string $address
  459. * @param int $limit
  460. * @param int $offset
  461. * @return array
  462. * @throws TronException
  463. */
  464. public function getTransactionsToAddress(string $address, int $limit = 30, int $offset = 0)
  465. {
  466. return $this->getTransactionsRelated($address,'to', $limit, $offset);
  467. }
  468. /**
  469. * Query the list of transactions sent by an address
  470. *
  471. * @param string $address
  472. * @param int $limit
  473. * @param int $offset
  474. * @return array
  475. * @throws TronException
  476. */
  477. public function getTransactionsFromAddress(string $address, int $limit = 30, int $offset = 0)
  478. {
  479. return $this->getTransactionsRelated($address,'from', $limit, $offset);
  480. }
  481. /**
  482. * Query information about an account
  483. *
  484. * @param $address
  485. * @return array
  486. * @throws TronException
  487. */
  488. public function getAccount(string $address = null): array
  489. {
  490. $address = (!is_null($address) ? $this->toHex($address) : $this->address['hex']);
  491. return $this->manager->request('walletsolidity/getaccount', [
  492. 'address' => $address
  493. ]);
  494. }
  495. /**
  496. * Getting a balance
  497. *
  498. * @param string $address
  499. * @param bool $fromTron
  500. * @return float
  501. * @throws TronException
  502. */
  503. public function getBalance(string $address = null, bool $fromTron = false): float
  504. {
  505. $account = $this->getAccount($address);
  506. if(!array_key_exists('balance', $account)) {
  507. return 0;
  508. }
  509. return ($fromTron == true ?
  510. $this->fromTron($account['balance']) :
  511. $account['balance']);
  512. }
  513. /**
  514. * Get token balance
  515. *
  516. * @param string $address
  517. * @param int $tokenId
  518. * @param bool $fromTron
  519. * @return array|int
  520. * @throws TronException
  521. */
  522. public function getTokenBalance(int $tokenId, string $address, bool $fromTron = false)
  523. {
  524. $account = $this->getAccount($address);
  525. if(isset($account['assetV2']) and !empty($account['assetV2']) )
  526. {
  527. $value = array_filter($account['assetV2'], function($item) use ($tokenId) {
  528. return $item['key'] == $tokenId;
  529. });
  530. if(empty($value)) {
  531. throw new TronException('Token id not found');
  532. }
  533. $first = array_shift($value);
  534. return ($fromTron == true ? $this->fromTron($first['value']) : $first['value']);
  535. }
  536. return 0;
  537. }
  538. /**
  539. * Query bandwidth information.
  540. *
  541. * @param $address
  542. * @return array
  543. * @throws TronException
  544. */
  545. public function getBandwidth(string $address = null)
  546. {
  547. $address = (!is_null($address) ? $this->toHex($address) : $this->address['hex']);
  548. return $this->manager->request('wallet/getaccountnet', [
  549. 'address' => $address
  550. ]);
  551. }
  552. /**
  553. * Getting data in the "from","to" directions
  554. *
  555. * @param string $address
  556. * @param string $direction
  557. * @param int $limit
  558. * @param int $offset
  559. * @return array
  560. * @throws TronException
  561. */
  562. public function getTransactionsRelated(string $address, string $direction = 'to', int $limit = 30, int $offset = 0)
  563. {
  564. if(!in_array($direction, ['to', 'from'])) {
  565. throw new TronException('Invalid direction provided: Expected "to", "from"');
  566. }
  567. if(!is_integer($limit) || $limit < 0 || ($offset && $limit < 1)) {
  568. throw new TronException('Invalid limit provided');
  569. }
  570. if(!is_integer($offset) || $offset < 0) {
  571. throw new TronException('Invalid offset provided');
  572. }
  573. $response = $this->manager->request(sprintf('walletextension/gettransactions%sthis', $direction), [
  574. 'account' => ['address' => $this->toHex($address)],
  575. 'limit' => $limit,
  576. 'offset' => $offset
  577. ]);
  578. return array_merge($response, ['direction' => $direction]);
  579. }
  580. /**
  581. * Count all transactions on the network
  582. *
  583. * @return integer
  584. * @throws TronException
  585. */
  586. public function getTransactionCount(): int
  587. {
  588. $response = $this->manager->request('wallet/totaltransaction');
  589. return $response['num'];
  590. }
  591. /**
  592. * Send transaction to Blockchain
  593. *
  594. * @param string $to
  595. * @param float $amount
  596. * @param string|null $message
  597. * @param string $from
  598. *
  599. * @return array
  600. * @throws TronException
  601. */
  602. public function sendTransaction(string $to, float $amount, string $message= null, string $from = null): array
  603. {
  604. if (is_null($from)) {
  605. $from = $this->address['hex'];
  606. }
  607. $transaction = $this->transactionBuilder->sendTrx($to, $amount, $from);
  608. $signedTransaction = $this->signTransaction($transaction, $message);
  609. $response = $this->sendRawTransaction($signedTransaction);
  610. return array_merge($response, $signedTransaction);
  611. }
  612. /**
  613. * Send token transaction to Blockchain
  614. *
  615. * @param string $to
  616. * @param float $amount
  617. * @param int $tokenID
  618. * @param string $from
  619. *
  620. * @return array
  621. * @throws TronException
  622. */
  623. public function sendTokenTransaction(string $to, float $amount, int $tokenID = null, string $from = null): array
  624. {
  625. if (is_null($from)) {
  626. $from = $this->address['hex'];
  627. }
  628. $transaction = $this->transactionBuilder->sendToken($to, $this->toTron($amount), (string)$tokenID, $from);
  629. $signedTransaction = $this->signTransaction($transaction);
  630. $response = $this->sendRawTransaction($signedTransaction);
  631. return array_merge($response, $signedTransaction);
  632. }
  633. /**
  634. * Sign the transaction, the api has the risk of leaking the private key,
  635. * please make sure to call the api in a secure environment
  636. *
  637. * @param $transaction
  638. * @param string|null $message
  639. * @return array
  640. * @throws TronException
  641. */
  642. public function signTransaction($transaction, string $message = null): array
  643. {
  644. if(!$this->privateKey) {
  645. throw new TronException('Missing private key');
  646. }
  647. if(!is_array($transaction)) {
  648. throw new TronException('Invalid transaction provided');
  649. }
  650. if(isset($transaction['Error']))
  651. throw new TronException($transaction['Error']);
  652. if(isset($transaction['signature'])) {
  653. throw new TronException('Transaction is already signed');
  654. }
  655. if(!is_null($message)) {
  656. $transaction['raw_data']['data'] = $this->stringUtf8toHex($message);
  657. }
  658. $signature = Support\Secp::sign($transaction['txID'], $this->privateKey);
  659. $transaction['signature'] = [$signature];
  660. return $transaction;
  661. }
  662. /**
  663. * Broadcast the signed transaction
  664. *
  665. * @param $signedTransaction
  666. * @return array
  667. * @throws TronException
  668. */
  669. public function sendRawTransaction($signedTransaction): array
  670. {
  671. if(!is_array($signedTransaction)) {
  672. throw new TronException('Invalid transaction provided');
  673. }
  674. if(!array_key_exists('signature', $signedTransaction) || !is_array($signedTransaction['signature'])) {
  675. throw new TronException('Transaction is not signed');
  676. }
  677. return $this->manager->request('wallet/broadcasttransaction',
  678. $signedTransaction);
  679. }
  680. /**
  681. * Modify account name
  682. * Note: Username is allowed to edit only once.
  683. *
  684. * @param $address
  685. * @param $account_name
  686. * @return array
  687. * @throws TronException
  688. */
  689. public function changeAccountName(string $address = null, string $account_name)
  690. {
  691. $address = (!is_null($address) ? $address : $this->address['hex']);
  692. $transaction = $this->manager->request('wallet/updateaccount', [
  693. 'account_name' => $this->stringUtf8toHex($account_name),
  694. 'owner_address' => $this->toHex($address)
  695. ]);
  696. $signedTransaction = $this->signTransaction($transaction);
  697. $response = $this->sendRawTransaction($signedTransaction);
  698. return $response;
  699. }
  700. /**
  701. * Send funds to the Tron account (option 2)
  702. *
  703. * @param array $args
  704. * @return array
  705. * @throws TronException
  706. */
  707. public function send(...$args): array {
  708. return $this->sendTransaction(...$args);
  709. }
  710. /**
  711. * Send funds to the Tron account (option 3)
  712. *
  713. * @param array $args
  714. * @return array
  715. * @throws TronException
  716. */
  717. public function sendTrx(...$args): array {
  718. return $this->sendTransaction(...$args);
  719. }
  720. /**
  721. * Creating a new token based on Tron
  722. *
  723. * @param array token {
  724. * "owner_address": "41e552f6487585c2b58bc2c9bb4492bc1f17132cd0",
  725. * "name": "0x6173736574497373756531353330383934333132313538",
  726. * "abbr": "0x6162627231353330383934333132313538",
  727. * "total_supply": 4321,
  728. * "trx_num": 1,
  729. * "num": 1,
  730. * "start_time": 1530894315158,
  731. * "end_time": 1533894312158,
  732. * "description": "007570646174654e616d6531353330363038383733343633",
  733. * "url": "007570646174654e616d6531353330363038383733343633",
  734. * "free_asset_net_limit": 10000,
  735. * "public_free_asset_net_limit": 10000,
  736. * "frozen_supply": { "frozen_amount": 1, "frozen_days": 2 }
  737. *
  738. * @return array
  739. * @throws TronException
  740. */
  741. public function createToken($token = [])
  742. {
  743. return $this->manager->request('wallet/createassetissue', [
  744. 'owner_address' => $this->toHex($token['owner_address']),
  745. 'name' => $this->stringUtf8toHex($token['name']),
  746. 'abbr' => $this->stringUtf8toHex($token['abbr']),
  747. 'description' => $this->stringUtf8toHex($token['description']),
  748. 'url' => $this->stringUtf8toHex($token['url']),
  749. 'total_supply' => $token['total_supply'],
  750. 'trx_num' => $token['trx_num'],
  751. 'num' => $token['num'],
  752. 'start_time' => $token['start_time'],
  753. 'end_time' => $token['end_time'],
  754. 'free_asset_net_limit' => $token['free_asset_net_limit'],
  755. 'public_free_asset_net_limit' => $token['public_free_asset_net_limit'],
  756. 'frozen_supply' => $token['frozen_supply']
  757. ]);
  758. }
  759. /**
  760. * Create an account.
  761. * Uses an already activated account to create a new account
  762. *
  763. * @param $address
  764. * @param $newAccountAddress
  765. * @return array
  766. * @throws TronException
  767. */
  768. public function registerAccount(string $address, string $newAccountAddress): array
  769. {
  770. return $this->manager->request('wallet/createaccount', [
  771. 'owner_address' => $this->toHex($address),
  772. 'account_address' => $this->toHex($newAccountAddress)
  773. ]);
  774. }
  775. /**
  776. * Apply to become a super representative
  777. *
  778. * @param $address
  779. * @param $url
  780. * @return array
  781. * @throws TronException
  782. */
  783. public function applyForSuperRepresentative(string $address, string $url)
  784. {
  785. return $this->manager->request('wallet/createwitness', [
  786. 'owner_address' => $this->toHex($address),
  787. 'url' => $this->stringUtf8toHex($url)
  788. ]);
  789. }
  790. /**
  791. * Transfer Token
  792. *
  793. * @param $to
  794. * @param $amount
  795. * @param $tokenID
  796. * @param $from
  797. * @return array
  798. * @throws TronException
  799. */
  800. public function sendToken(string $to, int $amount, string $tokenID, string $from = null)
  801. {
  802. if($from == null) {
  803. $from = $this->address['hex'];
  804. }
  805. $transfer = $this->transactionBuilder->sendToken($to, $amount, $tokenID, $from);
  806. $signedTransaction = $this->signTransaction($transfer);
  807. $response = $this->sendRawTransaction($signedTransaction);
  808. return array_merge($response, $signedTransaction);
  809. }
  810. /**
  811. * Purchase a Token
  812. * @param $issuerAddress
  813. * @param $tokenID
  814. * @param $amount
  815. * @param null $buyer
  816. * @return array
  817. * @throws TronException
  818. */
  819. public function purchaseToken($issuerAddress, $tokenID, $amount, $buyer = null)
  820. {
  821. if($buyer == null) {
  822. $buyer = $this->address['hex'];
  823. }
  824. $purchase = $this->transactionBuilder->purchaseToken($issuerAddress, $tokenID, $amount, $buyer);
  825. $signedTransaction = $this->signTransaction($purchase);
  826. $response = $this->sendRawTransaction($signedTransaction);
  827. return array_merge($response, $signedTransaction);
  828. }
  829. /**
  830. * Freezes an amount of TRX.
  831. * Will give bandwidth OR Energy and TRON Power(voting rights) to the owner of the frozen tokens.
  832. *
  833. * @param float $amount
  834. * @param int $duration
  835. * @param string $resource
  836. * @param string $owner_address
  837. * @return array
  838. * @throws TronException
  839. */
  840. public function freezeBalance(float $amount = 0, int $duration = 3, string $resource = 'BANDWIDTH', string $owner_address = null)
  841. {
  842. if($owner_address == null) {
  843. $owner_address = $this->address['hex'];
  844. }
  845. $freeze = $this->transactionBuilder->freezeBalance($amount, $duration, $resource, $owner_address);
  846. $signedTransaction = $this->signTransaction($freeze);
  847. $response = $this->sendRawTransaction($signedTransaction);
  848. return array_merge($response, $signedTransaction);
  849. }
  850. /**
  851. * Unfreeze TRX that has passed the minimum freeze duration.
  852. * Unfreezing will remove bandwidth and TRON Power.
  853. *
  854. * @param string $resource
  855. * @param string $owner_address
  856. * @return array
  857. * @throws TronException
  858. */
  859. public function unfreezeBalance(string $resource = 'BANDWIDTH', string $owner_address = null)
  860. {
  861. if($owner_address == null) {
  862. $owner_address = $this->address['hex'];
  863. }
  864. $unfreeze = $this->transactionBuilder->unfreezeBalance($resource, $owner_address);
  865. $signedTransaction = $this->signTransaction($unfreeze);
  866. $response = $this->sendRawTransaction($signedTransaction);
  867. return array_merge($response, $signedTransaction);
  868. }
  869. /**
  870. * Withdraw Super Representative rewards, useable every 24 hours.
  871. *
  872. * @param string $owner_address
  873. * @return array
  874. * @throws TronException
  875. */
  876. public function withdrawBlockRewards(string $owner_address = null)
  877. {
  878. if($owner_address == null) {
  879. $owner_address = $this->address['hex'];
  880. }
  881. $withdraw = $this->transactionBuilder->withdrawBlockRewards($owner_address);
  882. $signedTransaction = $this->signTransaction($withdraw);
  883. $response = $this->sendRawTransaction($signedTransaction);
  884. return array_merge($response, $signedTransaction);
  885. }
  886. /**
  887. * Update a Token's information
  888. *
  889. * @param string $description
  890. * @param string $url
  891. * @param int $freeBandwidth
  892. * @param int $freeBandwidthLimit
  893. * @param $owner_address
  894. * @return array
  895. * @throws TronException
  896. */
  897. public function updateToken(string $description,
  898. string $url,
  899. int $freeBandwidth = 0,
  900. int $freeBandwidthLimit = 0,
  901. string $owner_address = null)
  902. {
  903. if($owner_address == null) {
  904. $owner_address = $this->address['hex'];
  905. }
  906. $withdraw = $this->transactionBuilder->updateToken($description, $url, $freeBandwidth, $freeBandwidthLimit, $owner_address);
  907. $signedTransaction = $this->signTransaction($withdraw);
  908. $response = $this->sendRawTransaction($signedTransaction);
  909. return array_merge($response, $signedTransaction);
  910. }
  911. /**
  912. * Node list
  913. *
  914. * @return array
  915. * @throws TronException
  916. */
  917. public function listNodes(): array
  918. {
  919. $nodes = $this->manager->request('wallet/listnodes');
  920. return array_map(function($item) {
  921. $address = $item['address'];
  922. return sprintf('%s:%s', $this->toUtf8($address['host']), $address['port']);
  923. }, $nodes['nodes']);
  924. }
  925. /**
  926. * List the tokens issued by an account.
  927. *
  928. * @param string $address
  929. * @return array
  930. * @throws TronException
  931. */
  932. public function getTokensIssuedByAddress(string $address = null)
  933. {
  934. $address = (!is_null($address) ? $this->toHex($address) : $this->address['hex']);
  935. return $this->manager->request('wallet/getassetissuebyaccount',[
  936. 'address' => $address
  937. ]);
  938. }
  939. /**
  940. * Query token by name.
  941. *
  942. * @param $tokenID
  943. * @return array
  944. * @throws TronException
  945. */
  946. public function getTokenFromID($tokenID = null)
  947. {
  948. return $this->manager->request('wallet/getassetissuebyname', [
  949. 'value' => $this->stringUtf8toHex($tokenID)
  950. ]);
  951. }
  952. /**
  953. * Query a range of blocks by block height
  954. *
  955. * @param int $start
  956. * @param int $end
  957. * @return array
  958. * @throws TronException
  959. */
  960. public function getBlockRange(int $start = 0, int $end = 30)
  961. {
  962. if(!is_integer($start) || $start < 0) {
  963. throw new TronException('Invalid start of range provided');
  964. }
  965. if(!is_integer($end) || $end <= $start) {
  966. throw new TronException('Invalid end of range provided');
  967. }
  968. return $this->manager->request('wallet/getblockbylimitnext', [
  969. 'startNum' => intval($start),
  970. 'endNum' => intval($end) + 1
  971. ])['block'];
  972. }
  973. /**
  974. * Query the latest blocks
  975. *
  976. * @param int $limit
  977. * @return array
  978. * @throws TronException
  979. */
  980. public function getLatestBlocks(int $limit = 1): array
  981. {
  982. if(!is_integer($limit) || $limit <= 0) {
  983. throw new TronException('Invalid limit provided');
  984. }
  985. return $this->manager->request('wallet/getblockbylatestnum', [
  986. 'num' => $limit
  987. ])['block'];
  988. }
  989. /**
  990. * Query the list of Super Representatives
  991. *
  992. * @return array
  993. * @throws TronException
  994. */
  995. public function listSuperRepresentatives(): array
  996. {
  997. return $this->manager->request('wallet/listwitnesses')['witnesses'];
  998. }
  999. /**
  1000. * Query the list of Tokens with pagination
  1001. *
  1002. * @param int $limit
  1003. * @param int $offset
  1004. * @return array
  1005. * @throws TronException
  1006. */
  1007. public function listTokens(int $limit = 0, int $offset = 0)
  1008. {
  1009. if(!is_integer($limit) || $limit < 0 || ($offset && $limit < 1)) {
  1010. throw new TronException('Invalid limit provided');
  1011. }
  1012. if(!is_integer($offset) || $offset < 0) {
  1013. throw new TronException('Invalid offset provided');
  1014. }
  1015. if(!$limit) {
  1016. return $this->manager->request('wallet/getassetissuelist')['assetIssue'];
  1017. }
  1018. return $this->manager->request('wallet/getpaginatedassetissuelist', [
  1019. 'offset' => intval($offset),
  1020. 'limit' => intval($limit)
  1021. ])['assetIssue'];
  1022. }
  1023. /**
  1024. * Get the time of the next Super Representative vote
  1025. *
  1026. * @return float
  1027. * @throws TronException
  1028. */
  1029. public function timeUntilNextVoteCycle(): float
  1030. {
  1031. $num = $this->manager->request('wallet/getnextmaintenancetime')['num'];
  1032. if($num == -1) {
  1033. throw new TronException('Failed to get time until next vote cycle');
  1034. }
  1035. return floor($num / 1000);
  1036. }
  1037. /**
  1038. * Validate address
  1039. *
  1040. * @param string $address
  1041. * @param bool $hex
  1042. * @return array
  1043. * @throws TronException
  1044. */
  1045. public function validateAddress(string $address = null, bool $hex = false): array
  1046. {
  1047. $address = (!is_null($address) ? $address : $this->address['hex']);
  1048. if($hex) {
  1049. $address = $this->toHex($address);
  1050. }
  1051. return $this->manager->request('wallet/validateaddress', [
  1052. 'address' => $address
  1053. ]);
  1054. }
  1055. /**
  1056. * Validate Tron Address (Locale)
  1057. *
  1058. * @param string|null $address
  1059. * @return bool
  1060. */
  1061. public function isAddress(string $address = null): bool
  1062. {
  1063. if(strlen($address) !== self::ADDRESS_SIZE)
  1064. return false;
  1065. $address = Base58Check::decode($address, 0, 0, false);
  1066. $utf8 = hex2bin($address);
  1067. if(strlen($utf8) !== 25) return false;
  1068. if(strpos($utf8 , chr(self::ADDRESS_PREFIX_BYTE)) !== 0) return false;
  1069. $checkSum = substr($utf8, 21);
  1070. $address = substr($utf8, 0, 21);
  1071. $hash0 = Hash::SHA256($address);
  1072. $hash1 = Hash::SHA256($hash0);
  1073. $checkSum1 = substr($hash1, 0, 4);
  1074. if ($checkSum === $checkSum1)
  1075. return true;
  1076. return false;
  1077. }
  1078. /**
  1079. * Deploys a contract
  1080. *
  1081. * @param $abi
  1082. * @param $bytecode
  1083. * @param $feeLimit
  1084. * @param $address
  1085. * @param int $callValue
  1086. * @param int $bandwidthLimit
  1087. * @return array
  1088. * @throws TronException
  1089. */
  1090. public function deployContract($abi, $bytecode, $feeLimit, $address, $callValue = 0, $bandwidthLimit = 0)
  1091. {
  1092. $payable = array_filter(json_decode($abi, true), function($v)
  1093. {
  1094. if($v['type'] == 'constructor' && $v['payable']) {
  1095. return $v['payable'];
  1096. }
  1097. return null;
  1098. });
  1099. if($feeLimit > 1000000000) {
  1100. throw new TronException('fee_limit must not be greater than 1000000000');
  1101. }
  1102. if($payable && $callValue == 0) {
  1103. throw new TronException('call_value must be greater than 0 if contract is type payable');
  1104. }
  1105. if(!$payable && $callValue > 0) {
  1106. throw new TronException('call_value can only equal to 0 if contract type isn‘t payable');
  1107. }
  1108. return $this->manager->request('wallet/deploycontract', [
  1109. 'owner_address' => $this->toHex($address),
  1110. 'fee_limit' => $feeLimit,
  1111. 'call_value' => $callValue,
  1112. 'consume_user_resource_percent' => $bandwidthLimit,
  1113. 'abi' => $abi,
  1114. 'bytecode' => $bytecode
  1115. ]);
  1116. }
  1117. /**
  1118. * Get a list of exchanges
  1119. *
  1120. * @return array
  1121. * @throws TronException
  1122. */
  1123. public function listExchanges()
  1124. {
  1125. return $this->manager->request('/wallet/listexchanges', []);
  1126. }
  1127. /**
  1128. * Query the resource information of the account
  1129. *
  1130. * @param string $address
  1131. * @return array
  1132. * @throws TronException
  1133. */
  1134. public function getAccountResources(string $address = null)
  1135. {
  1136. $address = (!is_null($address) ? $address : $this->address['hex']);
  1137. return $this->manager->request('/wallet/getaccountresource', [
  1138. 'address' => $this->toHex($address)
  1139. ]);
  1140. }
  1141. /**
  1142. * Create a new account
  1143. *
  1144. * @return TronAddress
  1145. * @throws TronException
  1146. */
  1147. public function createAccount(): TronAddress
  1148. {
  1149. return $this->generateAddress();
  1150. }
  1151. public function getAddressHex(string $pubKeyBin): string
  1152. {
  1153. if (strlen($pubKeyBin) == 65) {
  1154. $pubKeyBin = substr($pubKeyBin, 1);
  1155. }
  1156. $hash = Keccak::hash($pubKeyBin, 256);
  1157. return self::ADDRESS_PREFIX . substr($hash, 24);
  1158. }
  1159. public function getBase58CheckAddress(string $addressBin): string
  1160. {
  1161. $hash0 = Hash::SHA256($addressBin);
  1162. $hash1 = Hash::SHA256($hash0);
  1163. $checksum = substr($hash1, 0, 4);
  1164. $checksum = $addressBin . $checksum;
  1165. return Base58::encode(Crypto::bin2bc($checksum));
  1166. }
  1167. /**
  1168. * Generate new address
  1169. *
  1170. * @return TronAddress
  1171. * @throws TronException
  1172. */
  1173. public function generateAddress(): TronAddress
  1174. {
  1175. $ec = new EC('secp256k1');
  1176. // Generate keys
  1177. $key = $ec->genKeyPair();
  1178. $priv = $ec->keyFromPrivate($key->priv);
  1179. $pubKeyHex = $priv->getPublic(false, "hex");
  1180. $pubKeyBin = hex2bin($pubKeyHex);
  1181. $addressHex = $this->getAddressHex($pubKeyBin);
  1182. $addressBin = hex2bin($addressHex);
  1183. $addressBase58 = $this->getBase58CheckAddress($addressBin);
  1184. return new TronAddress([
  1185. 'private_key' => $priv->getPrivate('hex'),
  1186. 'public_key' => $pubKeyHex,
  1187. 'address_hex' => $addressHex,
  1188. 'address_base58' => $addressBase58
  1189. ]);
  1190. }
  1191. /**
  1192. * Helper function that will convert HEX to UTF8
  1193. *
  1194. * @param $str
  1195. * @return string
  1196. */
  1197. public function toUtf8($str): string {
  1198. return pack('H*', $str);
  1199. }
  1200. /**
  1201. * Query token by id.
  1202. *
  1203. * @param string $token_id
  1204. * @return array
  1205. * @throws TronException
  1206. */
  1207. public function getTokenByID(string $token_id): array
  1208. {
  1209. if(!is_string($token_id))
  1210. throw new TronException('Invalid token ID provided');
  1211. return $this->manager->request('/wallet/getassetissuebyid', [
  1212. 'value' => $token_id
  1213. ]);
  1214. }
  1215. }