TronHelper.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. <?php
  2. namespace App\Helpers;
  3. use Mdanter\Ecc\EccFactory;
  4. use Mdanter\Ecc\Random\RandomGeneratorFactory;
  5. use Illuminate\Support\Facades\Crypt;
  6. use GuzzleHttp\Client;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. use Illuminate\Support\Facades\Log;
  9. use TronTool\Credential;
  10. use TronTool\TronApi;
  11. use TronTool\TronKit;
  12. use kornrunner\Secp256k1;
  13. use kornrunner\Keccak;
  14. use App\Helpers\TronRawSerializer;
  15. use App\Http\Controllers\admin\Balance;
  16. use kornrunner\Signature\Signature;
  17. use Elliptic\EC;
  18. use kornrunner\Serializer\HexSignatureSerializer;
  19. class TronHelper
  20. {
  21. public static $isTest = true;
  22. public static $tronUrl = 'https://api.trongrid.io';
  23. public static $nileUrl = 'https://nile.trongrid.io'; // 测试网
  24. const CONFIRMED_NUMBER = 3; // 确认数
  25. protected static $client;
  26. public static function init()
  27. {
  28. if(self::getTronNetwork()){
  29. $url = self::$nileUrl;
  30. }else{
  31. $url = self::$tronUrl;
  32. }
  33. if (!self::$client) {
  34. self::$client = new Client([
  35. 'base_uri' => $url,
  36. 'timeout' => 10.0,
  37. 'headers' => [
  38. 'Accept' => 'application/json',
  39. 'Content-Type' => 'application/json'
  40. ],
  41. 'verify' => false
  42. ]);
  43. }
  44. }
  45. /**
  46. * @description: 获取网络
  47. * @return {*}
  48. */
  49. public static function getTronNetwork()
  50. {
  51. $netWork = config('app.tron_network'); // 默认是主网
  52. if($netWork == 'main'){
  53. return false;
  54. }else{
  55. return true;
  56. }
  57. }
  58. /**
  59. * @description: 创建钱包地址和私钥
  60. * @return {private_key,address}
  61. */
  62. public static function createAddress($memberId = ''): array
  63. {
  64. // 生成 TRC20 私钥
  65. $privateKey = self::makePrivateKey($memberId); // 默认不带 memberId
  66. // 从私钥生成地址
  67. $address = self::getAddressByPrivateKey($privateKey);
  68. // 记录日志
  69. Log::channel('wallet')->info('创建钱包地址', [
  70. 'member_id' => $memberId,
  71. 'address' => $address,
  72. 'private_key' => $privateKey,
  73. ]);
  74. return [
  75. 'address' => $address,
  76. 'private_key' => $privateKey,
  77. ];
  78. }
  79. /**
  80. * @description: 转账USDT
  81. * @param {*} $privateKey 转账秘钥
  82. * @param {*} $toAddress 接收地址
  83. * @param {*} $amount 转账金额
  84. * @return {*}
  85. */
  86. public static function transferUSDT($privateKey, $toAddress, $amount)
  87. {
  88. $nodeScript = base_path('node/index.js'); // Laravel根目录下的路径
  89. $nodeBin = 'node'; // 用 which node 查看,或自定义
  90. if(self::getTronNetwork()){
  91. $fullNodeUrl = self::$nileUrl;
  92. }else{
  93. $fullNodeUrl = self::$tronUrl;
  94. }
  95. $contractAddress = self::getContractAddress('USDT');
  96. $cmd = sprintf(
  97. '%s %s %s %s %s %s %s 2>&1',
  98. escapeshellcmd($nodeBin),
  99. escapeshellarg($nodeScript),
  100. escapeshellarg($privateKey),
  101. escapeshellarg($toAddress),
  102. escapeshellarg($contractAddress),
  103. escapeshellarg($fullNodeUrl),
  104. escapeshellarg($amount)
  105. );
  106. exec($cmd, $outputLines, $status);
  107. $output = implode("\n", $outputLines);
  108. $result = json_decode($output, true);
  109. return $result;
  110. // self::init();
  111. // $contractAddress = self::getContractAddress('USDT');
  112. // $fromAddress = self::getAddressByPrivateKey($privateKey);
  113. // // 1. 构建转账交易
  114. // $transferData = [
  115. // 'owner_address' => self::base58check2HexString($fromAddress),
  116. // 'contract_address' => self::base58check2HexString($contractAddress),
  117. // 'function_selector' => 'transfer(address,uint256)',
  118. // 'parameter' => self::buildParameter($toAddress, $amount),
  119. // 'visible' => false
  120. // ];
  121. // $response = self::$client->post('/wallet/triggersmartcontract', [
  122. // 'json' => $transferData
  123. // ]);
  124. // $data = json_decode($response->getBody(), true);
  125. // var_dump($data);
  126. // if (empty($data['transaction'])) {
  127. // throw new \Exception('构建转账交易失败: ' . json_encode($data));
  128. // }
  129. // $txid = $data['transaction']['txID'];
  130. // // 2. 签名交易
  131. // // $rawData = $data['transaction']['raw_data'];
  132. // // $rawDataBytes = TronRawSerializer::serializeRawData($rawData); // 自定义函数,返回 Protobuf 序列化后的二进制
  133. // // $txHash = hash('sha256', $rawDataBytes); // Tron使用 SHA256,不是 Keccak256
  134. // // // 使用私钥签名
  135. // // $secp256k1 = new Secp256k1();
  136. // // $signature = $secp256k1->sign($txHash, $privateKey);
  137. // // $signatureHex = self::formatTronSignature($signature);
  138. // $signedTx = self::signTronTransaction($data['transaction'],$privateKey);
  139. // // var_dump($signatureHex);
  140. // // $signedTx['visible'] = true;
  141. // // 3. 广播交易
  142. // // 将 signature 转成 hex 字符串
  143. // // $signatureHex = bin2hex($signature);
  144. // // $signatureHex = $signature;
  145. // // var_dump($signatureHex);
  146. // // 构建签名交易
  147. // // $signedTx = [
  148. // // 'txID' => $data['transaction']['txID'],
  149. // // 'raw_data' => $data['transaction']['raw_data'],
  150. // // 'signature' => $signatureHex,
  151. // // ];
  152. // var_dump($signedTx);
  153. // $broadcast = self::$client->post('/wallet/broadcasttransaction', [
  154. // 'json' => $signedTx
  155. // ]);
  156. // $broadcastData = json_decode($broadcast->getBody(), true);
  157. // return $broadcastData;
  158. }
  159. public static function signTronTransaction(array $transaction, string $privateKey): array
  160. {
  161. $rawData = $transaction['raw_data'] ?? null;
  162. if (!$rawData) {
  163. throw new \Exception('交易中没有 raw_data');
  164. }
  165. $rawDataBytes = TronRawSerializer::serializeRawData($rawData);
  166. $txHash = hash('sha256', $rawDataBytes, true); // 二进制哈希
  167. $privateKeyHex = ltrim($privateKey, '0x');
  168. if (strlen($privateKeyHex) !== 64) {
  169. throw new \Exception('私钥格式不正确');
  170. }
  171. $privateKeyBin = hex2bin($privateKeyHex);
  172. $secp256k1 = new Secp256k1();
  173. $signatureObj = $secp256k1->sign($txHash, $privateKeyBin);
  174. // r, s 都是 GMP 对象,转成32字节二进制字符串
  175. $rBin = self::gmpToBin32($signatureObj->getR());
  176. $sBin = self::gmpToBin32($signatureObj->getS());
  177. $signatureBin = $rBin . $sBin; // 64字节二进制签名
  178. $transaction['signature'] = [$signatureBin];
  179. return $transaction;
  180. }
  181. private static function gmpToBin32($gmpNum): string
  182. {
  183. $hex = gmp_strval($gmpNum, 16);
  184. if (strlen($hex) % 2 !== 0) {
  185. $hex = '0' . $hex;
  186. }
  187. $bin = hex2bin($hex);
  188. return str_pad($bin, 32, "\0", STR_PAD_LEFT);
  189. }
  190. /**
  191. * 构建 parameter 字符串(目标地址 + 金额)
  192. */
  193. protected static function buildParameter($toAddress, $amount)
  194. {
  195. $hexAddress = self::base58check2HexString($toAddress);
  196. $addr = str_pad(substr($hexAddress, 2), 64, '0', STR_PAD_LEFT); // 去掉 '41' 开头的 Tron 前缀
  197. $amt = str_pad(bcdechex(bcmul($amount, '1000000')), 64, '0', STR_PAD_LEFT); // USDT 精度 6
  198. return $addr . $amt;
  199. }
  200. // /**
  201. // * @param Signature $signature
  202. // * @return string 65字节签名的十六进制字符串
  203. // */
  204. // public static function formatTronSignature(Signature $signature): string
  205. // {
  206. // $r = gmp_strval($signature->getR(), 16);
  207. // $s = gmp_strval($signature->getS(), 16);
  208. // $v = dechex($signature->getRecoveryParam()); // v 即 recoveryParam
  209. // // 补齐 r 和 s 为 64位长度(即32字节)
  210. // $r = str_pad($r, 64, '0', STR_PAD_LEFT);
  211. // $s = str_pad($s, 64, '0', STR_PAD_LEFT);
  212. // $v = str_pad($v, 2, '0', STR_PAD_LEFT); // 1字节 = 2个hex字符
  213. // $v_decimal = hexdec($v); // 0
  214. // $v_decimal += 27; // 27
  215. // $v_hex = dechex($v_decimal); // "1b"
  216. // return $r . $s . $v_hex; // 返回最终的签名字符串
  217. // }
  218. /**
  219. * @description: 获取地址的YRX余额
  220. * @param {*} $addressBase58
  221. * @return {*}
  222. */
  223. public static function getTrxBalance($addressBase58)
  224. {
  225. $hexAddress = TronHelper::base58check2HexString($addressBase58);
  226. self::init();
  227. $response = self::$client->post('/wallet/getaccount', [
  228. 'json' => ['address' => $hexAddress]
  229. ]);
  230. $data = json_decode($response->getBody(), true);
  231. if (!empty($data['balance'])) {
  232. // TRX 的单位是 sun,1 TRX = 1_000_000 sun
  233. return $data['balance'] / 1_000_000;
  234. }
  235. return 0;
  236. }
  237. // /**
  238. // * @description: 向账户转TRX能量
  239. // * @param {*} $fromAddress
  240. // * @param {*} $privateKey
  241. // * @param {*} $toAddress
  242. // * @param {*} $amount
  243. // * @return {*}
  244. // */
  245. // public static function transferTRX($fromAddress, $privateKey, $toAddress, $amount)
  246. // {
  247. // self::init();
  248. // $ownerAddressHex = self::base58check2HexString($fromAddress);
  249. // $toAddressHex = self::base58check2HexString($toAddress);
  250. // $createData = [
  251. // 'owner_address' => $ownerAddressHex,
  252. // 'to_address' => $toAddressHex,
  253. // 'amount' => (int)($amount * 1_000_000), // TRX 精度为 6
  254. // ];
  255. // // 构建转账交易
  256. // $response = self::$client->post('/wallet/createtransaction', [
  257. // 'json' => $createData
  258. // ]);
  259. // $tx = json_decode($response->getBody(), true);
  260. // if (!isset($tx['txID'])) {
  261. // throw new \Exception('创建转账交易失败: ' . json_encode($tx));
  262. // }
  263. // // 签名交易
  264. // $signature = self::signTransaction($tx,$privateKey);
  265. // // 广播交易
  266. // $signedTx = [
  267. // 'txID' => $tx['txID'],
  268. // 'raw_data' => $tx['raw_data'],
  269. // 'raw_data_hex' => $tx['raw_data_hex'],
  270. // 'signature' => $signature,
  271. // ];
  272. // $response = self::$client->post('/wallet/broadcasttransaction', [
  273. // 'json' => $signedTx
  274. // ]);
  275. // var_dump($signedTx);
  276. // $result = json_decode($response->getBody(), true);
  277. // var_dump($result);
  278. // die();
  279. // // if (!isset($result['result']) || !$result['result']) {
  280. // // throw new \Exception('广播失败: ' . json_encode($result));
  281. // // }
  282. // return [
  283. // 'txID' => $tx['txID'],
  284. // 'result' => true
  285. // ];
  286. // }
  287. // /**
  288. // * @description: TRX签名
  289. // * @param {array} $transaction
  290. // * @param {string} $privateKey
  291. // * @return {*}
  292. // */
  293. // public static function signTransaction($tx, $privateKey)
  294. // {
  295. // if (empty($tx['raw_data_hex'])) {
  296. // throw new \Exception('原始交易数据为空,无法签名');
  297. // }
  298. // $rawDataHex = $tx['raw_data_hex'];
  299. // $rawDataBin = hex2bin($rawDataHex);
  300. // $hash = hash('sha256', $rawDataBin, true); // 原始数据做 SHA256
  301. // $signatureDer = self::ecdsaSignRaw($hash, $privateKey); // 返回 DER 格式签名
  302. // return [$signatureDer]; // Tron 要求是签名数组
  303. // }
  304. // public static function ecdsaSignRaw($hash, $privateKeyHex)
  305. // {
  306. // $ec = new EC('secp256k1');
  307. // $key = $ec->keyFromPrivate($privateKeyHex);
  308. // $signature = $key->sign(bin2hex($hash), ['canonical' => true]);
  309. // $r = str_pad($signature->r->toString('hex'), 64, '0', STR_PAD_LEFT);
  310. // $s = str_pad($signature->s->toString('hex'), 64, '0', STR_PAD_LEFT);
  311. // return hex2bin($r . $s); // 返回64字节的二进制字符串
  312. // }
  313. /**
  314. * 查询某地址的 TRX 充值记录
  315. * @param string $address 充值地址
  316. * @param int $limit 返回记录数
  317. * @return array
  318. */
  319. public static function getTrxTransactions(string $address, int $limit = 30): array
  320. {
  321. self::init();
  322. $response = self::$client->get("https://nile.trongrid.io/v1/accounts/{$address}/transactions", [
  323. 'query' => [
  324. 'limit' => $limit,
  325. 'only_confirmed' => 'true',
  326. 'order' => 'desc',
  327. ]
  328. ]);
  329. $data = json_decode($response->getBody()->getContents(), true);
  330. return $data;
  331. }
  332. /**
  333. * 查询某地址的 TRC20 USDT 充值记录
  334. * @param string $address 充值地址
  335. * @param int $limit 返回记录数
  336. * @return array
  337. */
  338. public static function getTrc20UsdtRecharges(string $address, int $limit = 30): array
  339. {
  340. self::init();
  341. $usdtContract = self::getContractAddress('USDT');
  342. $url = "/v1/accounts/{$address}/transactions/trc20?limit={$limit}";
  343. try {
  344. $response = self::$client->get($url, [
  345. 'headers' => [
  346. 'Accept' => 'application/json',
  347. ],
  348. 'timeout' => 10,
  349. ]);
  350. $data = json_decode($response->getBody()->getContents(), true);
  351. $recharges = [];
  352. foreach ($data['data'] ?? [] as $item) {
  353. $tokenAddress = $item['token_info']['address'] ?? '';
  354. if (strtolower($tokenAddress) !== strtolower($usdtContract)) {
  355. continue; // 不是USDT
  356. }
  357. if($item['to'] == $address){
  358. $recharges[] = [
  359. 'txid' => $item['transaction_id'],
  360. 'from_address' => $item['from'],
  361. 'to_address' => $item['to'],
  362. 'amount' => bcdiv($item['value'], bcpow('10', $item['token_info']['decimals']), 6),
  363. 'coin' => $item['token_info']['symbol'],
  364. 'block_time' => intval($item['block_timestamp'] / 1000),
  365. ];
  366. }
  367. }
  368. return $recharges;
  369. } catch (\Throwable $e) {
  370. Log::warning('获取TRC20 USDT充值记录失败', [
  371. 'address' => $address,
  372. 'error' => $e->getMessage(),
  373. ]);
  374. return [];
  375. }
  376. }
  377. /**
  378. * @description: 获取TRC20账户余额
  379. * @param {*} $address
  380. * @return {*}
  381. */
  382. public static function getTrc20Balance($address)
  383. {
  384. self::init();
  385. $contractAddress = self::getContractAddress('USDT');
  386. $hexAddress = self::base58check2HexString($address);
  387. $postData = [
  388. 'owner_address' => $hexAddress,
  389. 'contract_address' => self::base58check2HexString($contractAddress),
  390. 'function_selector' => 'balanceOf(address)',
  391. 'parameter' => str_pad(substr($hexAddress, 2), 64, '0', STR_PAD_LEFT),
  392. ];
  393. // try {
  394. $response = self::$client->post('/wallet/triggerconstantcontract', [
  395. 'headers' => [
  396. 'Content-Type' => 'application/json',
  397. 'TRON-PRO-API-KEY' => '3b241a9c-0076-49bf-b883-a003c97c19f6', // 添加这一行
  398. ],
  399. 'json' => $postData,
  400. ]);
  401. $body = $response->getBody()->getContents();
  402. $data = json_decode($body, true);
  403. $hexBalance = $data['constant_result'][0] ?? '0x0';
  404. return hexdec($hexBalance) / 1e6; // USDT 精度是 6 位
  405. // } catch (\Exception $e) {
  406. // // 可以记录日志或抛出异常
  407. // return 0;
  408. // }
  409. }
  410. /**
  411. * 查询交易确认数
  412. * @param string $txid 交易哈希
  413. * @return array
  414. */
  415. public static function getTransactionConfirmations(string $txid): array
  416. {
  417. // $client = new Client(['timeout' => 10]);
  418. self::init();
  419. try {
  420. // 1. 获取交易信息
  421. $txResp = self::$client->post('/wallet/gettransactioninfobyid', [
  422. 'json' => ['value' => $txid],
  423. 'headers' => ['Accept' => 'application/json'],
  424. ]);
  425. $txData = json_decode($txResp->getBody()->getContents(), true);
  426. if (!isset($txData['blockNumber'])) {
  427. return ['success' => false, 'message' => '交易尚未被打包或无效'];
  428. }
  429. $txBlock = $txData['blockNumber'];
  430. // 2. 获取最新区块高度
  431. $blockResp = self::$client->get('/wallet/getnowblock', [
  432. 'headers' => ['Accept' => 'application/json'],
  433. ]);
  434. $blockData = json_decode($blockResp->getBody()->getContents(), true);
  435. $latestBlock = $blockData['block_header']['raw_data']['number'] ?? 0;
  436. if ($latestBlock == 0) {
  437. return ['success' => false, 'message' => '无法获取最新区块'];
  438. }
  439. // 3. 计算确认数
  440. $confirmations = $latestBlock - $txBlock + 1;
  441. return [
  442. 'success' => true,
  443. 'txid' => $txid,
  444. 'block_number' => $txBlock,
  445. 'latest_block' => $latestBlock,
  446. 'confirmations' => $confirmations,
  447. ];
  448. } catch (\Exception $e) {
  449. return ['success' => false, 'message' => $e->getMessage()];
  450. }
  451. }
  452. /**
  453. * 加密私钥
  454. */
  455. public static function encryptPrivateKey(string $privateKeyHex): string
  456. {
  457. return Crypt::encryptString($privateKeyHex);
  458. }
  459. /**
  460. * 解密私钥
  461. */
  462. public static function decryptPrivateKey(string $encrypted): string
  463. {
  464. return Crypt::decryptString($encrypted);
  465. }
  466. /**
  467. * 获取合约地址
  468. * @param $currency
  469. * @return string
  470. */
  471. public static function getContractAddress($currency)
  472. {
  473. $currency = strtoupper($currency);
  474. switch ($currency) {
  475. case 'USDT'://usdt
  476. if(self::getTronNetwork()){
  477. $contractAddress = 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf'; // nile测试地址
  478. }else{
  479. $contractAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
  480. }
  481. break;
  482. case 'USDC'://usdc
  483. $contractAddress = 'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8';
  484. break;
  485. case 'USDJ'://USDJ
  486. $contractAddress = 'TMwFHYXLJaRUPeW6421aqXL4ZEzPRFGkGT';
  487. break;
  488. case 'TUSD'://TUSD
  489. $contractAddress = 'TUpMhErZL2fhh4sVNULAbNKLokS4GjC1F4';
  490. break;
  491. case 'BTC'://BTC
  492. $contractAddress = 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9';
  493. break;
  494. case 'ETH'://ETH
  495. $contractAddress = 'THb4CqiFdwNHsWsQCs4JhzwjMWys4aqCbF';
  496. break;
  497. case 'USDD'://USDD
  498. $contractAddress = 'TPYmHEhy5n8TCEfYGqW2rPxsghSfzghPDn';
  499. break;
  500. default:
  501. $contractAddress = '';
  502. }
  503. return $contractAddress;
  504. }
  505. public static function base58_encode($string)
  506. {
  507. if (is_string($string) === false) {
  508. return false;
  509. }
  510. if ($string === '') {
  511. return '';
  512. }
  513. $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  514. $base = strlen($alphabet);
  515. $bytes = array_values(unpack('C*', $string));
  516. $decimal = $bytes[0];
  517. for ($i = 1, $l = count($bytes); $i < $l; $i++) {
  518. $decimal = bcmul($decimal, 256);
  519. $decimal = bcadd($decimal, $bytes[$i]);
  520. }
  521. $output = '';
  522. while ($decimal >= $base) {
  523. $div = bcdiv($decimal, $base, 0);
  524. $mod = bcmod($decimal, $base);
  525. $output .= $alphabet[$mod];
  526. $decimal = $div;
  527. }
  528. if ($decimal > 0) {
  529. $output .= $alphabet[$decimal];
  530. }
  531. $output = strrev($output);
  532. foreach ($bytes as $byte) {
  533. if ($byte === 0) {
  534. $output = $alphabet[0].$output;
  535. continue;
  536. }
  537. break;
  538. }
  539. return $output;
  540. }
  541. public static function base58_decode($base58)
  542. {
  543. if (is_string($base58) === false) {
  544. return false;
  545. }
  546. if ($base58 === '') {
  547. return '';
  548. }
  549. $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  550. $base = strlen($alphabet);
  551. $indexes = array_flip(str_split($alphabet));
  552. $chars = str_split($base58);
  553. foreach ($chars as $char) {
  554. if (isset($indexes[$char]) === false) {
  555. return false;
  556. }
  557. }
  558. $decimal = $indexes[$chars[0]];
  559. for ($i = 1, $l = count($chars); $i < $l; $i++) {
  560. $decimal = bcmul($decimal, $base);
  561. $decimal = bcadd($decimal, $indexes[$chars[$i]]);
  562. }
  563. $output = '';
  564. while ($decimal > 0) {
  565. $byte = bcmod($decimal, 256);
  566. $output = pack('C', $byte).$output;
  567. $decimal = bcdiv($decimal, 256, 0);
  568. }
  569. foreach ($chars as $char) {
  570. if ($indexes[$char] === 0) {
  571. $output = "\x00".$output;
  572. continue;
  573. }
  574. break;
  575. }
  576. return $output;
  577. }
  578. //encode address from byte[] to base58check string
  579. public static function base58check_en($address)
  580. {
  581. $hash0 = hash("sha256", $address);
  582. $hash1 = hash("sha256", hex2bin($hash0));
  583. $checksum = substr($hash1, 0, 8);
  584. $address .= hex2bin($checksum);
  585. return self::base58_encode($address);
  586. }
  587. public static function base58check_de($base58add)
  588. {
  589. $address = self::base58_decode($base58add);
  590. $size = strlen($address);
  591. if ($size !== 25) {
  592. return false;
  593. }
  594. $checksum = substr($address, 21);
  595. $address = substr($address, 0, 21);
  596. $hash0 = hash("sha256", $address);
  597. $hash1 = hash("sha256", hex2bin($hash0));
  598. $checksum0 = substr($hash1, 0, 8);
  599. $checksum1 = bin2hex($checksum);
  600. if (strcmp($checksum0, $checksum1)) {
  601. return false;
  602. }
  603. return $address;
  604. }
  605. public static function hexString2Base58check($hexString)
  606. {
  607. $address = hex2bin($hexString);
  608. return self::base58check_en($address);
  609. }
  610. public static function base58check2HexString($base58add)
  611. {
  612. $address = self::base58check_de($base58add);
  613. return bin2hex($address);
  614. }
  615. public static function hexString2Base64($hexString)
  616. {
  617. $address = hex2bin($hexString);
  618. return base64_encode($address);
  619. }
  620. public static function base642HexString($base64)
  621. {
  622. $address = base64_decode($base64);
  623. return bin2hex($address);
  624. }
  625. public static function base58check2Base64($base58add)
  626. {
  627. $address =self::base58check_de($base58add);
  628. return base64_encode($address);
  629. }
  630. public static function base642Base58check($base64)
  631. {
  632. $address = base64_decode($base64);
  633. return self::base58check_en($address);
  634. }
  635. public static function getrandstr($length)
  636. {
  637. $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
  638. $randStr = str_shuffle($str);//打乱字符串
  639. return substr($randStr, 0, $length);
  640. }
  641. /**
  642. * 检测是否有效钱包地址
  643. * @param $address
  644. * @return bool
  645. */
  646. public static function isValidAddress($address)
  647. {
  648. if (empty($address)) {
  649. return false;
  650. }
  651. if (strlen($address) != 34) {
  652. return false;
  653. }
  654. if (substr($address, 0, 1) != 'T') {
  655. return false;
  656. }
  657. // 验证地址
  658. $client = new Client([
  659. 'verify' => false, // 关闭 SSL 验证
  660. ]);
  661. $response = $client->request('POST', 'https://api.shasta.trongrid.io/wallet/validateaddress', [
  662. 'body' => json_encode(["address" => $address]),
  663. 'headers' => [
  664. 'Accept' => 'application/json',
  665. 'Content-Type' => 'application/json',
  666. ],
  667. ]);
  668. $resp = $response->getBody()->getContents();
  669. $resp = json_decode($resp);
  670. // 失败提示错误
  671. if ($resp->result === false) {
  672. return false;
  673. }
  674. return true;
  675. }
  676. /**
  677. * 获取私钥,通过私钥可以拿到收款地址,各种权限
  678. * 注意:必须拿28位字符串来生成地址,否则无法生成正常的地址
  679. * @param $base64
  680. * @return string
  681. */
  682. public function getPrivateKey($base64)
  683. {
  684. return $this->base642HexString($base64);
  685. }
  686. /**
  687. * 生成波场key
  688. * @param $memberId
  689. * @return string
  690. */
  691. public static function makePrivateKey($memberId)
  692. {
  693. $fix = 'SSTGsstg';//固定8前缀,避免和其他人同地址
  694. $rand = TronHelper::getrandstr(20);//10位数随机,避免同地址
  695. $base64Sting = $fix.$rand.str_pad($memberId, 15, 0, STR_PAD_LEFT);
  696. $tronHelper = new TronHelper();
  697. return $tronHelper->getPrivateKey($base64Sting);
  698. }
  699. /**
  700. * 查询余额
  701. * @param $privateKey
  702. * @return int
  703. */
  704. public static function getBalance($address, $currency)
  705. {
  706. bcscale(6);
  707. $rate = 1000000;
  708. $currency = strtoupper($currency);
  709. if(self::getTronNetwork()){
  710. $api = TronApi::testNetNilo();
  711. }else{
  712. $api = TronApi::mainNet();
  713. }
  714. $privateKey = self::makePrivateKey(time());
  715. $credential = Credential::fromPrivateKey($privateKey);
  716. $kit = new TronKit($api, $credential);
  717. if ($currency == 'TRX') {
  718. try {
  719. $balance = $kit->getTrxBalance($address);
  720. return bcdiv($balance, $rate);
  721. } catch (\Exception $e) {
  722. return bcmul(0, 0);
  723. }
  724. }
  725. try {
  726. $contractAddress = self::getContractAddress($currency);
  727. $usdt = $kit->Trc20($contractAddress);
  728. $balance = $usdt->balanceOf($address);
  729. return bcdiv($balance, $rate);
  730. } catch (\Exception $e) {
  731. return bcmul(0, 0);
  732. }
  733. }
  734. /**
  735. * 获取转账信息
  736. * @param $txid
  737. */
  738. public static function getSendInfo($txid)
  739. {
  740. // $api = TronApi::mainNet();
  741. if(self::getTronNetwork()){
  742. $api = TronApi::testNetNilo();
  743. }else{
  744. $api = TronApi::mainNet();
  745. }
  746. $ret = $api->getTransaction($txid);
  747. $retArr = $ret->ret;
  748. if (isset($retArr[0]->contractRet)) {
  749. return $retArr[0]->contractRet;
  750. }
  751. return 'UNKNOWN';
  752. }
  753. /**
  754. * 完整交易详情,如果交易未完成或者不成功,返回空
  755. * @param $txid
  756. * @return string
  757. */
  758. public static function getTransactionInfoById($txid)
  759. {
  760. // $api = TronApi::mainNet();
  761. if(self::getTronNetwork()){
  762. $api = TronApi::testNetNilo();
  763. }else{
  764. $api = TronApi::mainNet();
  765. }
  766. $ret = $api->getTransactionInfoById($txid);
  767. return json_decode(json_encode($ret), true);
  768. }
  769. /**
  770. * 获取出款账户地址
  771. */
  772. public static function getWithdrawAddress()
  773. {
  774. // $privateKey = Yii::$app->params['withdraw_address_trx_key'];
  775. // $credential = Credential::fromPrivateKey($privateKey);
  776. // return $credential->address()->base58();
  777. }
  778. /**
  779. * 获取地址
  780. * @param $fromKey
  781. */
  782. public static function getAddressByPrivateKey($fromKey)
  783. {
  784. $credential = Credential::fromPrivateKey($fromKey);
  785. return $credential->address()->base58();
  786. }
  787. /**
  788. * 转账给指定地址
  789. * @param $fromKey
  790. * @param $toAddress
  791. * @param $amount
  792. * @throws \Exception
  793. */
  794. public static function sendTrx($fromKey, $toAddress, $amount)
  795. {
  796. if ($amount <= 0) {
  797. throw new \Exception('不能低于 0 trx');
  798. }
  799. // from 初始化
  800. if(self::getTronNetwork()){
  801. $api = TronApi::testNetNilo();
  802. }else{
  803. $api = TronApi::mainNet();
  804. }
  805. $credential = Credential::fromPrivateKey($fromKey);
  806. $kit = new TronKit($api, $credential);
  807. // from 余额判断
  808. $from = $credential->address()->base58();
  809. $balance = self::getBalance($from, 'TRX');
  810. $rate = 1000000;
  811. if ($balance < $amount) {
  812. return '余额不足';
  813. }
  814. // 发送
  815. try {
  816. return $kit->sendTrx($toAddress, 1 * bcmul($amount, $rate, 6));
  817. } catch (\Exception $e) {
  818. Log::error('转账错误,fromKey='.$fromKey.'toAddress='.$toAddress.'amount='.$amount);
  819. Log::error('转账错误'.$e->getMessage());
  820. return false;
  821. }
  822. }
  823. /**usdt转账
  824. * @param $fromKey
  825. * @param $toAddress
  826. * @param $amount
  827. * @param $currency
  828. * @return bool|object
  829. * @throws \Exception
  830. */
  831. public static function sendTrc20($fromKey, $toAddress, $amount, $currency)
  832. {
  833. if ($amount <= 0) {
  834. throw new \Exception('不能低于 0 USDT');
  835. }
  836. $credential = Credential::fromPrivateKey($fromKey);
  837. $credential->address()->hex();
  838. if(self::getTronNetwork()){
  839. $api = TronApi::testNetNilo();
  840. }else{
  841. $api = TronApi::mainNet();
  842. }
  843. $kit = new TronKit($api, $credential);
  844. $contractAddress = self::getContractAddress($currency);
  845. $rate = 1000000;//换算汇率
  846. // $balance = self::getBalance(self::getAddressByPrivateKey($fromKey), $currency); //查询Trc20代币余额
  847. $balance = self::getTrc20Balance(self::getAddressByPrivateKey($fromKey)); //查询Trc20代币余额
  848. if ($balance < $amount) {
  849. throw new \Exception('余额不足');
  850. }
  851. $trc20 = $kit->Trc20($contractAddress); //创建Trc20代币合约实例
  852. try {
  853. $ret = $trc20->transfer($toAddress, (int) bcmul($amount, $rate)); //转账Trc20代币
  854. return (object) [
  855. 'txid' => $ret->tx->txID,
  856. 'result' => $ret->result,
  857. ];
  858. } catch (\Exception $e) {
  859. Log::error('Trc20转账错误,fromKey='.$fromKey.'toAddress='.$toAddress.'amount='.$amount);
  860. Log::error('Trc20转账错误'.$e->getMessage());
  861. return false;
  862. }
  863. }
  864. /**
  865. * 归集账户资金校验
  866. * trade_status:
  867. * - failed 转账失败
  868. * - waiting 转账成功,尚未校验
  869. * - closed waiting 之后,脚本查询时,交易验证成功
  870. * - aborted waiting 之后,脚本查询时,交易验证失败
  871. * @param $fromKey
  872. * @param $toAddress
  873. * @param $amount
  874. * @param $memberId
  875. * @param string $currency
  876. * @param string $net
  877. * @return bool
  878. * @throws \Exception
  879. */
  880. public function actionFundsGather(
  881. $fromKey,
  882. $toAddress,
  883. $amount,
  884. $memberId,
  885. $currency = 'TRX',
  886. $net = 'TRC20'
  887. ) {
  888. // $currency = strtoupper($currency);
  889. // if ($amount <= 0) {
  890. // throw new \Exception('不能低于 0 trx');
  891. // }
  892. // if (empty($toAddress)) {
  893. // throw new \Exception('收款地址不能为空');
  894. // }
  895. // $fromAddress = self::getAddressByPrivateKey($fromKey);
  896. // $remainAmount = self::getBalance($fromAddress, $currency);
  897. // if ($remainAmount < $amount) {
  898. // throw new \Exception('余额不足,归集失败');
  899. // }
  900. // $min = MinRechargeEnum::getValue($currency);
  901. // if ($currency == 'TRX') {
  902. // $ret = self::sendTrx($fromKey, $toAddress, $amount);
  903. // } else {
  904. // // 发送
  905. // //校验trx是否足够,不够就充值10燃烧费用进来
  906. // if (self::getBalance($fromAddress, 'TRX') < 10) {
  907. // $withdrawAddressTrxKey = Yii::$app->params['withdraw_address_trx_key'];
  908. // self::sendTrx($withdrawAddressTrxKey, self::getAddressByPrivateKey($fromKey), 10);
  909. // }
  910. // $ret = self::sendTrc20($fromKey, $toAddress, $amount, $currency);
  911. // }
  912. // //少于最低可入款额度,不入账,只做归集
  913. // if ($min > $remainAmount) {
  914. // return false;
  915. // }
  916. // try {
  917. // // 记录
  918. // $fundsGather = new Recharge();
  919. // $fundsGather->member_id = $memberId;
  920. // $fundsGather->txid = $ret->txid;
  921. // $fundsGather->amount = $amount;
  922. // $fundsGather->address = $toAddress;
  923. // $fundsGather->created_at = time();
  924. // $fundsGather->currency = $currency;
  925. // $fundsGather->usdt_balance = bcmul($amount, ExchangeRateService::getExchangeRate($currency),
  926. // CommonEnum::DIGITS);
  927. // $fundsGather->is_auto = 1;
  928. // $fundsGather->count = Recharge::find()->where(['member_id' => $memberId])->count() + 1;
  929. // $fundsGather->net = $net;
  930. // $fundsGather->ordernum = StrHelper::createOrdernum();
  931. // // 记录「充值请求次数」
  932. // $member = Member::findOne($memberId);
  933. // $member->recharge_request_count = $fundsGather->count;
  934. // $member->save();
  935. // if ($ret->result == 1) { // 成功
  936. // $fundsGather->trade_status = 'waiting';
  937. // if ($fundsGather->save()) {
  938. // return true;
  939. // }
  940. // } else { // 失败
  941. // $fundsGather->trade_status = 'failed';
  942. // $fundsGather->save();
  943. // }
  944. // } catch (Exception $e) {
  945. // throw new \Exception('转账异常'.$e->getMessage());
  946. // }
  947. return false;
  948. }
  949. }