Tron.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  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\Support\Base58;
  17. use IEXBase\TronAPI\Support\Base58Check;
  18. use IEXBase\TronAPI\Support\Crypto;
  19. use IEXBase\TronAPI\Support\Hash;
  20. use IEXBase\TronAPI\Support\Keccak;
  21. use IEXBase\TronAPI\Support\Utils;
  22. use IEXBase\TronAPI\Provider\HttpProviderInterface;
  23. use IEXBase\TronAPI\Exception\TronException;
  24. use Tron\Address;
  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. *
  43. * @var array
  44. */
  45. public $address = [
  46. 'base58' => null,
  47. 'hex' => null
  48. ];
  49. /**
  50. * Private key
  51. *
  52. * @var string
  53. */
  54. protected $privateKey;
  55. /**
  56. * Default block
  57. *
  58. * @var string|integer|bool
  59. */
  60. protected $defaultBlock = 'latest';
  61. /**
  62. * Transaction Builder
  63. *
  64. * @var TransactionBuilder
  65. */
  66. protected $transactionBuilder;
  67. /**
  68. * Provider manager
  69. *
  70. * @var TronManager
  71. */
  72. protected $manager;
  73. /**
  74. * Online sign
  75. *
  76. * @var boolean
  77. */
  78. protected $isOnlineSign = false;
  79. /**
  80. * Object Result
  81. *
  82. * @var bool
  83. */
  84. protected $isObject = false;
  85. /**
  86. * Create a new Tron object
  87. *
  88. * @param HttpProviderInterface $fullNode
  89. * @param HttpProviderInterface $solidityNode
  90. * @param HttpProviderInterface|null $eventServer
  91. * @param HttpProviderInterface|null $signServer
  92. * @param HttpProviderInterface|null $explorer
  93. * @param string $privateKey
  94. * @throws TronException
  95. */
  96. public function __construct(?HttpProviderInterface $fullNode = null,
  97. ?HttpProviderInterface $solidityNode = null,
  98. ?HttpProviderInterface $eventServer = null,
  99. ?HttpProviderInterface $signServer = null,
  100. ?HttpProviderInterface $explorer = null,
  101. ?string $privateKey = null)
  102. {
  103. if (!is_null($privateKey)) {
  104. $this->setPrivateKey($privateKey);
  105. }
  106. $this->setManager(new TronManager($this, [
  107. 'fullNode' => $fullNode,
  108. 'solidityNode' => $solidityNode,
  109. 'eventServer' => $eventServer,
  110. 'signServer' => $signServer,
  111. ]));
  112. $this->transactionBuilder = new TransactionBuilder($this);
  113. }
  114. /**
  115. * Create a new tron instance if the value isn't one already.
  116. *
  117. * @param HttpProviderInterface|null $fullNode
  118. * @param HttpProviderInterface|null $solidityNode
  119. * @param HttpProviderInterface|null $eventServer
  120. * @param HttpProviderInterface|null $signServer
  121. * @param string|null $privateKey
  122. * @return static
  123. * @throws TronException
  124. */
  125. public static function make(?HttpProviderInterface $fullNode = null,
  126. ?HttpProviderInterface $solidityNode = null,
  127. ?HttpProviderInterface $eventServer = null,
  128. ?HttpProviderInterface $signServer = null,
  129. string $privateKey = null)
  130. {
  131. return new static($fullNode, $solidityNode, $eventServer, $signServer, $privateKey);
  132. }
  133. /**
  134. * Enter the link to the manager nodes
  135. *
  136. * @param $providers
  137. */
  138. public function setManager($providers)
  139. {
  140. $this->manager = $providers;
  141. }
  142. /**
  143. * Get provider manager
  144. *
  145. * @return TronManager
  146. */
  147. public function getManager(): TronManager
  148. {
  149. return $this->manager;
  150. }
  151. /**
  152. * Set is object
  153. *
  154. * @param bool $value
  155. * @return Tron
  156. */
  157. public function setIsObject(bool $value)
  158. {
  159. $this->isObject = boolval($value);
  160. return $this;
  161. }
  162. /**
  163. * Get Transaction Builder
  164. *
  165. * @return TransactionBuilder
  166. */
  167. public function getTransactionBuilder(): TransactionBuilder
  168. {
  169. return $this->transactionBuilder;
  170. }
  171. /**
  172. * Check connected provider
  173. *
  174. * @param $provider
  175. * @return bool
  176. */
  177. public function isValidProvider($provider): bool
  178. {
  179. return ($provider instanceof HttpProviderInterface);
  180. }
  181. /**
  182. * Enter the default block
  183. *
  184. * @param bool $blockID
  185. * @return void
  186. * @throws TronException
  187. */
  188. public function setDefaultBlock($blockID = false): void
  189. {
  190. if ($blockID === false || $blockID == 'latest' || $blockID == 'earliest' || $blockID === 0) {
  191. $this->defaultBlock = $blockID;
  192. return;
  193. }
  194. if (!is_integer($blockID)) {
  195. throw new TronException('Invalid block ID provided');
  196. }
  197. $this->defaultBlock = abs($blockID);
  198. }
  199. /**
  200. * Get default block
  201. *
  202. * @return string|integer|bool
  203. */
  204. public function getDefaultBlock()
  205. {
  206. return $this->defaultBlock;
  207. }
  208. /**
  209. * Enter your private account key
  210. *
  211. * @param string $privateKey
  212. */
  213. public function setPrivateKey(string $privateKey): void
  214. {
  215. $this->privateKey = $privateKey;
  216. }
  217. /**
  218. * Set online sign
  219. *
  220. * @param bool $sign
  221. * @return Tron
  222. */
  223. public function setIsOnlineSign(bool $sign): Tron
  224. {
  225. $this->isOnlineSign = $sign;
  226. return $this;
  227. }
  228. /**
  229. * Enter your account address
  230. *
  231. * @param string $address
  232. */
  233. public function setAddress(string $address): void
  234. {
  235. $_toHex = $this->address2HexString($address);
  236. $_fromHex = $this->hexString2Address($address);
  237. $this->address = [
  238. 'hex' => $_toHex,
  239. 'base58' => $_fromHex
  240. ];
  241. }
  242. /**
  243. * Get account address
  244. *
  245. * @return array
  246. */
  247. public function getAddress(): array
  248. {
  249. return $this->address;
  250. }
  251. /**
  252. * Get customized provider data
  253. *
  254. * @return array
  255. */
  256. public function providers(): array
  257. {
  258. return $this->manager->getProviders();
  259. }
  260. /**
  261. * Check Connection Providers
  262. *
  263. * @return array
  264. */
  265. public function isConnected(): array
  266. {
  267. return $this->manager->isConnected();
  268. }
  269. /**
  270. * Last block number
  271. *
  272. * @return array
  273. * @throws TronException
  274. */
  275. public function getCurrentBlock(): array
  276. {
  277. return $this->manager->request('wallet/getnowblock');
  278. }
  279. /**
  280. * Will return all events matching the filters.
  281. *
  282. * @param $contractAddress
  283. * @param int $sinceTimestamp
  284. * @param string|null $eventName
  285. * @param int $blockNumber
  286. * @return array
  287. * @throws TronException
  288. */
  289. public function getEventResult($contractAddress, int $sinceTimestamp = 0, string $eventName = null, int $blockNumber = 0)
  290. {
  291. if (!$this->isValidProvider($this->manager->eventServer())) {
  292. throw new TronException('No event server configured');
  293. }
  294. $routeParams = [];
  295. if ($eventName && !$contractAddress) {
  296. throw new TronException('Usage of event name filtering requires a contract address');
  297. }
  298. if ($blockNumber && !$eventName)
  299. throw new TronException('Usage of block number filtering requires an event name');
  300. if ($contractAddress) {
  301. array_push($routeParams, $contractAddress);
  302. }
  303. if ($eventName) {
  304. array_push($routeParams, $eventName);
  305. }
  306. if ($blockNumber) {
  307. array_push($routeParams, $blockNumber);
  308. }
  309. $routeParams = implode('/', $routeParams);
  310. return $this->manager->request("event/contract/{$routeParams}?since={$sinceTimestamp}");
  311. }
  312. /**
  313. * Will return all events within a transactionID.
  314. *
  315. * @param string $transactionID
  316. * @return array
  317. * @throws TronException
  318. */
  319. public function getEventByTransactionID(string $transactionID)
  320. {
  321. if (!$this->isValidProvider($this->manager->eventServer())) {
  322. throw new TronException('No event server configured');
  323. }
  324. return $this->manager->request("event/transaction/{$transactionID}");
  325. }
  326. /**
  327. * Get block details using HashString or blockNumber
  328. *
  329. * @param null $block
  330. * @return array
  331. * @throws TronException
  332. */
  333. public function getBlock($block = null): array
  334. {
  335. $block = (is_null($block) ? $this->defaultBlock : $block);
  336. if ($block === false) {
  337. throw new TronException('No block identifier provided');
  338. }
  339. if ($block == 'earliest') {
  340. $block = 0;
  341. }
  342. if ($block == 'latest') {
  343. return $this->getCurrentBlock();
  344. }
  345. if (Utils::isHex($block)) {
  346. return $this->getBlockByHash($block);
  347. }
  348. return $this->getBlockByNumber($block);
  349. }
  350. /**
  351. * Query block by ID
  352. *
  353. * @param $hashBlock
  354. * @return array
  355. * @throws TronException
  356. */
  357. public function getBlockByHash(string $hashBlock): array
  358. {
  359. return $this->manager->request('wallet/getblockbyid', [
  360. 'value' => $hashBlock
  361. ]);
  362. }
  363. /**
  364. * Query block by height
  365. *
  366. * @param $blockID
  367. * @return array
  368. * @throws TronException
  369. */
  370. public function getBlockByNumber(int $blockID): array
  371. {
  372. if (!is_integer($blockID) || $blockID < 0) {
  373. throw new TronException('Invalid block number provided');
  374. }
  375. $response = $this->manager->request('wallet/getblockbynum', [
  376. 'num' => intval($blockID)
  377. ]);
  378. if (empty($response)) {
  379. throw new TronException('Block not found');
  380. }
  381. return $response;
  382. }
  383. /**
  384. * Total number of transactions in a block
  385. *
  386. * @param $block
  387. * @return int
  388. * @throws TronException
  389. */
  390. public function getBlockTransactionCount($block): int
  391. {
  392. $transaction = $this->getBlock($block)['transactions'];
  393. if (!$transaction) {
  394. return 0;
  395. }
  396. return count($transaction);
  397. }
  398. /**
  399. * Get transaction details from Block
  400. *
  401. * @param null $block
  402. * @param int $index
  403. * @return array | string
  404. * @throws TronException
  405. */
  406. public function getTransactionFromBlock($block = null, $index = 0)
  407. {
  408. if (!is_integer($index) || $index < 0) {
  409. throw new TronException('Invalid transaction index provided');
  410. }
  411. $transactions = $this->getBlock($block)['transactions'];
  412. if (!$transactions || count($transactions) < $index) {
  413. throw new TronException('Transaction not found in block');
  414. }
  415. return $transactions[$index];
  416. }
  417. /**
  418. * Query transaction based on id
  419. *
  420. * @param $transactionID
  421. * @return array
  422. * @throws TronException
  423. */
  424. public function getTransaction(string $transactionID): array
  425. {
  426. $response = $this->manager->request('wallet/gettransactionbyid', [
  427. 'value' => $transactionID
  428. ]);
  429. if (!$response) {
  430. throw new TronException('Transaction not found');
  431. }
  432. return $response;
  433. }
  434. /**
  435. * Query transaction fee based on id
  436. *
  437. * @param $transactionID
  438. * @return array
  439. * @throws TronException
  440. */
  441. public function getTransactionInfo(string $transactionID): array
  442. {
  443. return $this->manager->request('walletsolidity/gettransactioninfobyid', [
  444. 'value' => $transactionID
  445. ]);
  446. }
  447. /**
  448. * Query the list of transactions received by an address
  449. *
  450. * @param string $address
  451. * @param int $limit
  452. * @param int $offset
  453. * @return array
  454. * @throws TronException
  455. */
  456. public function getTransactionsToAddress(string $address, int $limit = 30, int $offset = 0)
  457. {
  458. return $this->getTransactionsRelated($address, 'to', $limit, $offset);
  459. }
  460. /**
  461. * Query the list of transactions sent by an address
  462. *
  463. * @param string $address
  464. * @param int $limit
  465. * @param int $offset
  466. * @return array
  467. * @throws TronException
  468. */
  469. public function getTransactionsFromAddress(string $address, int $limit = 30, int $offset = 0)
  470. {
  471. return $this->getTransactionsRelated($address, 'from', $limit, $offset);
  472. }
  473. /**
  474. * Query information about an account
  475. *
  476. * @param $address
  477. * @return array
  478. * @throws TronException
  479. */
  480. public function getAccount(string $address = null): array
  481. {
  482. $address = (!is_null($address) ? $this->toHex($address) : $this->address['hex']);
  483. return $this->manager->request('walletsolidity/getaccount', [
  484. 'address' => $address
  485. ]);
  486. }
  487. /**
  488. * Getting a balance
  489. *
  490. * @param string $address
  491. * @param bool $fromTron
  492. * @return float
  493. * @throws TronException
  494. */
  495. public function getBalance(string $address = null, bool $fromTron = false): float
  496. {
  497. $account = $this->getAccount($address);
  498. if (!array_key_exists('balance', $account)) {
  499. return 0;
  500. }
  501. return ($fromTron == true ?
  502. $this->fromTron($account['balance']) :
  503. $account['balance']);
  504. }
  505. /**
  506. * Get token balance
  507. *
  508. * @param string $address
  509. * @param int $tokenId
  510. * @param bool $fromTron
  511. * @return array|int
  512. * @throws TronException
  513. */
  514. public function getTokenBalance(int $tokenId, string $address, bool $fromTron = false)
  515. {
  516. $account = $this->getAccount($address);
  517. if (isset($account['assetV2']) and !empty($account['assetV2'])) {
  518. $value = array_filter($account['assetV2'], function ($item) use ($tokenId) {
  519. return $item['key'] == $tokenId;
  520. });
  521. if (empty($value)) {
  522. throw new TronException('Token id not found');
  523. }
  524. $first = array_shift($value);
  525. return ($fromTron == true ? $this->fromTron($first['value']) : $first['value']);
  526. }
  527. return 0;
  528. }
  529. /**
  530. * Query bandwidth information.
  531. *
  532. * @param $address
  533. * @return array
  534. * @throws TronException
  535. */
  536. public function getBandwidth(string $address = null)
  537. {
  538. $address = (!is_null($address) ? $this->toHex($address) : $this->address['hex']);
  539. return $this->manager->request('wallet/getaccountnet', [
  540. 'address' => $address
  541. ]);
  542. }
  543. /**
  544. * Getting data in the "from","to" directions
  545. *
  546. * @param string $address
  547. * @param string $direction
  548. * @param int $limit
  549. * @param int $offset
  550. * @return array
  551. * @throws TronException
  552. */
  553. public function getTransactionsRelated(string $address, string $direction = 'to', int $limit = 30, int $offset = 0)
  554. {
  555. if (!in_array($direction, ['to', 'from'])) {
  556. throw new TronException('Invalid direction provided: Expected "to", "from"');
  557. }
  558. if (!is_integer($limit) || $limit < 0 || ($offset && $limit < 1)) {
  559. throw new TronException('Invalid limit provided');
  560. }
  561. if (!is_integer($offset) || $offset < 0) {
  562. throw new TronException('Invalid offset provided');
  563. }
  564. $response = $this->manager->request(sprintf('walletextension/gettransactions%sthis', $direction), [
  565. 'account' => ['address' => $this->toHex($address)],
  566. 'limit' => $limit,
  567. 'offset' => $offset
  568. ]);
  569. return array_merge($response, ['direction' => $direction]);
  570. }
  571. /**
  572. * Count all transactions on the network
  573. *
  574. * @return integer
  575. * @throws TronException
  576. */
  577. public function getTransactionCount(): int
  578. {
  579. $response = $this->manager->request('wallet/totaltransaction');
  580. return $response['num'];
  581. }
  582. /**
  583. * Send transaction to Blockchain
  584. *
  585. * @param string $to
  586. * @param float $amount
  587. * @param string|null $message
  588. * @param string $from
  589. *
  590. * @return array
  591. * @throws TronException
  592. */
  593. public function sendTransaction(string $to, float $amount, string $message = null, string $from = null): array
  594. {
  595. if (is_null($from)) {
  596. $from = $this->address['hex'];
  597. }
  598. $transaction = $this->transactionBuilder->sendTrx($to, $amount, $from);
  599. $signedTransaction = $this->signTransaction($transaction, $message);
  600. $response = $this->sendRawTransaction($signedTransaction);
  601. return array_merge($response, $signedTransaction);
  602. }
  603. /**
  604. * Send token transaction to Blockchain
  605. *
  606. * @param string $to
  607. * @param float $amount
  608. * @param int $tokenID
  609. * @param string $from
  610. *
  611. * @return array
  612. * @throws TronException
  613. */
  614. public function sendTokenTransaction(string $to, float $amount, int $tokenID = null, string $from = null): array
  615. {
  616. if (is_null($from)) {
  617. $from = $this->address['hex'];
  618. }
  619. $transaction = $this->transactionBuilder->sendToken($to, $this->toTron($amount), (string)$tokenID, $from);
  620. $signedTransaction = $this->signTransaction($transaction);
  621. $response = $this->sendRawTransaction($signedTransaction);
  622. return array_merge($response, $signedTransaction);
  623. }
  624. /**
  625. * Sign the transaction, the api has the risk of leaking the private key,
  626. * please make sure to call the api in a secure environment
  627. *
  628. * @param $transaction
  629. * @param string|null $message
  630. * @return array
  631. * @throws TronException
  632. */
  633. public function signTransaction($transaction, string $message = null): array
  634. {
  635. if (!$this->privateKey) {
  636. throw new TronException('Missing private key');
  637. }
  638. if (!is_array($transaction)) {
  639. throw new TronException('Invalid transaction provided');
  640. }
  641. if (isset($transaction['Error']))
  642. throw new TronException($transaction['Error']);
  643. if (isset($transaction['signature'])) {
  644. throw new TronException('Transaction is already signed');
  645. }
  646. if (!is_null($message)) {
  647. $transaction['raw_data']['data'] = $this->stringUtf8toHex($message);
  648. }
  649. // Online sign tx
  650. if ($this->isOnlineSign == true) {
  651. return $this->manager->request('wallet/gettransactionsign', [
  652. 'transaction' => $transaction,
  653. 'privateKey' => $this->privateKey
  654. ]);
  655. }
  656. $signature = Support\Secp::sign($transaction['txID'], $this->privateKey);
  657. $transaction['signature'] = [$signature];
  658. return $transaction;
  659. }
  660. /**
  661. * Broadcast the signed transaction
  662. *
  663. * @param $signedTransaction
  664. * @return array
  665. * @throws TronException
  666. */
  667. public function sendRawTransaction($signedTransaction): array
  668. {
  669. if (!is_array($signedTransaction)) {
  670. throw new TronException('Invalid transaction provided');
  671. }
  672. if (!array_key_exists('signature', $signedTransaction) || !is_array($signedTransaction['signature'])) {
  673. throw new TronException('Transaction is not signed');
  674. }
  675. return $this->manager->request('wallet/broadcasttransaction',
  676. $signedTransaction);
  677. }
  678. /**
  679. * Modify account name
  680. * Note: Username is allowed to edit only once.
  681. *
  682. * @param $address
  683. * @param $account_name
  684. * @return array
  685. * @throws TronException
  686. */
  687. public function changeAccountName(string $address = null, string $account_name)
  688. {
  689. $address = (!is_null($address) ? $address : $this->address['hex']);
  690. $transaction = $this->manager->request('wallet/updateaccount', [
  691. 'account_name' => $this->stringUtf8toHex($account_name),
  692. 'owner_address' => $this->toHex($address)
  693. ]);
  694. $signedTransaction = $this->signTransaction($transaction);
  695. $response = $this->sendRawTransaction($signedTransaction);
  696. return $response;
  697. }
  698. /**
  699. * Send funds to the Tron account (option 2)
  700. *
  701. * @param array $args
  702. * @return array
  703. * @throws TronException
  704. */
  705. public function send(...$args): array
  706. {
  707. return $this->sendTransaction(...$args);
  708. }
  709. /**
  710. * Send funds to the Tron account (option 3)
  711. *
  712. * @param array $args
  713. * @return array
  714. * @throws TronException
  715. */
  716. public function sendTrx(...$args): array
  717. {
  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)
  1062. {
  1063. $address = Base58Check::decode($address, 0, 0, false);
  1064. $utf8 = hex2bin($address);
  1065. if (strlen($address) !== self::ADDRESS_SIZE)
  1066. return false;
  1067. if (strlen($utf8) !== 25 or strpos($utf8, self::ADDRESS_PREFIX_BYTE) !== 0)
  1068. 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. if ($v['type'] == 'constructor' && $v['payable']) {
  1094. return $v['payable'];
  1095. }
  1096. return null;
  1097. });
  1098. if ($feeLimit > 1000000000) {
  1099. throw new TronException('fee_limit must not be greater than 1000000000');
  1100. }
  1101. if ($payable && $callValue == 0) {
  1102. throw new TronException('call_value must be greater than 0 if contract is type payable');
  1103. }
  1104. if (!$payable && $callValue > 0) {
  1105. throw new TronException('call_value can only equal to 0 if contract type isn‘t payable');
  1106. }
  1107. return $this->manager->request('wallet/deploycontract', [
  1108. 'owner_address' => $this->toHex($address),
  1109. 'fee_limit' => $feeLimit,
  1110. 'call_value' => $callValue,
  1111. 'consume_user_resource_percent' => $bandwidthLimit,
  1112. 'abi' => $abi,
  1113. 'bytecode' => $bytecode
  1114. ]);
  1115. }
  1116. /**
  1117. * Get a list of exchanges
  1118. *
  1119. * @return array
  1120. * @throws TronException
  1121. */
  1122. public function listExchanges()
  1123. {
  1124. return $this->manager->request('/wallet/listexchanges', []);
  1125. }
  1126. /**
  1127. * Query the resource information of the account
  1128. *
  1129. * @param string $address
  1130. * @return array
  1131. * @throws TronException
  1132. */
  1133. public function getAccountResources(string $address = null)
  1134. {
  1135. $address = (!is_null($address) ? $address : $this->address['hex']);
  1136. return $this->manager->request('/wallet/getaccountresource', [
  1137. 'address' => $this->toHex($address)
  1138. ]);
  1139. }
  1140. /**
  1141. * Create a new account
  1142. *
  1143. * @return array
  1144. * @throws TronException
  1145. */
  1146. public function createAccount(): array
  1147. {
  1148. return $this->generateAddress();
  1149. }
  1150. public function getAddressHex(string $pubKeyBin): string
  1151. {
  1152. if (strlen($pubKeyBin) == 65) {
  1153. $pubKeyBin = substr($pubKeyBin, 1);
  1154. }
  1155. $hash = Keccak::hash($pubKeyBin, 256);
  1156. return self::ADDRESS_PREFIX . substr($hash, 24);
  1157. }
  1158. public function getBase58CheckAddress(string $addressBin): string
  1159. {
  1160. $hash0 = Hash::SHA256($addressBin);
  1161. $hash1 = Hash::SHA256($hash0);
  1162. $checksum = substr($hash1, 0, 4);
  1163. $checksum = $addressBin . $checksum;
  1164. return Base58::encode(Crypto::bin2bc($checksum));
  1165. }
  1166. /**
  1167. * Generate new address
  1168. *
  1169. * @return TronAddress
  1170. * @throws TronException
  1171. */
  1172. public function generateAddress(): TronAddress
  1173. {
  1174. $ec = new EC('secp256k1');
  1175. // Generate keys
  1176. $key = $ec->genKeyPair();
  1177. $priv = $ec->keyFromPrivate($key->priv);
  1178. $pubKeyHex = $priv->getPublic(false, "hex");
  1179. $pubKeyBin = hex2bin($pubKeyHex);
  1180. $addressHex = $this->getAddressHex($pubKeyBin);
  1181. $addressBin = hex2bin($addressHex);
  1182. $addressBase58 = $this->getBase58CheckAddress($addressBin);
  1183. return new TronAddress([
  1184. 'private_key' => $priv->getPrivate('hex'),
  1185. 'public_key' => $pubKeyHex,
  1186. 'address_hex' => $addressHex,
  1187. 'address_base58' => $addressBase58
  1188. ]);
  1189. }
  1190. /**
  1191. * Helper function that will convert HEX to UTF8
  1192. *
  1193. * @param $str
  1194. * @return string
  1195. */
  1196. public function toUtf8($str): string
  1197. {
  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. }