TronHelper.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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 (\Exception $e) {
  370. // return ['error' => $e->getMessage()];
  371. // }
  372. }
  373. /**
  374. * @description: 获取TRC20账户余额
  375. * @param {*} $address
  376. * @return {*}
  377. */
  378. public static function getTrc20Balance($address)
  379. {
  380. self::init();
  381. $contractAddress = self::getContractAddress('USDT');
  382. $hexAddress = self::base58check2HexString($address);
  383. $postData = [
  384. 'owner_address' => $hexAddress,
  385. 'contract_address' => self::base58check2HexString($contractAddress),
  386. 'function_selector' => 'balanceOf(address)',
  387. 'parameter' => str_pad(substr($hexAddress, 2), 64, '0', STR_PAD_LEFT),
  388. ];
  389. // try {
  390. $response = self::$client->post('/wallet/triggerconstantcontract', [
  391. 'headers' => [
  392. 'Content-Type' => 'application/json',
  393. 'TRON-PRO-API-KEY' => '3b241a9c-0076-49bf-b883-a003c97c19f6', // 添加这一行
  394. ],
  395. 'json' => $postData,
  396. ]);
  397. $body = $response->getBody()->getContents();
  398. $data = json_decode($body, true);
  399. $hexBalance = $data['constant_result'][0] ?? '0x0';
  400. return hexdec($hexBalance) / 1e6; // USDT 精度是 6 位
  401. // } catch (\Exception $e) {
  402. // // 可以记录日志或抛出异常
  403. // return 0;
  404. // }
  405. }
  406. /**
  407. * 查询交易确认数
  408. * @param string $txid 交易哈希
  409. * @return array
  410. */
  411. public static function getTransactionConfirmations(string $txid): array
  412. {
  413. // $client = new Client(['timeout' => 10]);
  414. self::init();
  415. try {
  416. // 1. 获取交易信息
  417. $txResp = self::$client->post('/wallet/gettransactioninfobyid', [
  418. 'json' => ['value' => $txid],
  419. 'headers' => ['Accept' => 'application/json'],
  420. ]);
  421. $txData = json_decode($txResp->getBody()->getContents(), true);
  422. if (!isset($txData['blockNumber'])) {
  423. return ['success' => false, 'message' => '交易尚未被打包或无效'];
  424. }
  425. $txBlock = $txData['blockNumber'];
  426. // 2. 获取最新区块高度
  427. $blockResp = self::$client->get('/wallet/getnowblock', [
  428. 'headers' => ['Accept' => 'application/json'],
  429. ]);
  430. $blockData = json_decode($blockResp->getBody()->getContents(), true);
  431. $latestBlock = $blockData['block_header']['raw_data']['number'] ?? 0;
  432. if ($latestBlock == 0) {
  433. return ['success' => false, 'message' => '无法获取最新区块'];
  434. }
  435. // 3. 计算确认数
  436. $confirmations = $latestBlock - $txBlock + 1;
  437. return [
  438. 'success' => true,
  439. 'txid' => $txid,
  440. 'block_number' => $txBlock,
  441. 'latest_block' => $latestBlock,
  442. 'confirmations' => $confirmations,
  443. ];
  444. } catch (\Exception $e) {
  445. return ['success' => false, 'message' => $e->getMessage()];
  446. }
  447. }
  448. /**
  449. * 加密私钥
  450. */
  451. public static function encryptPrivateKey(string $privateKeyHex): string
  452. {
  453. return Crypt::encryptString($privateKeyHex);
  454. }
  455. /**
  456. * 解密私钥
  457. */
  458. public static function decryptPrivateKey(string $encrypted): string
  459. {
  460. return Crypt::decryptString($encrypted);
  461. }
  462. /**
  463. * 获取合约地址
  464. * @param $currency
  465. * @return string
  466. */
  467. public static function getContractAddress($currency)
  468. {
  469. $currency = strtoupper($currency);
  470. switch ($currency) {
  471. case 'USDT'://usdt
  472. if(self::getTronNetwork()){
  473. $contractAddress = 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf'; // nile测试地址
  474. }else{
  475. $contractAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
  476. }
  477. break;
  478. case 'USDC'://usdc
  479. $contractAddress = 'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8';
  480. break;
  481. case 'USDJ'://USDJ
  482. $contractAddress = 'TMwFHYXLJaRUPeW6421aqXL4ZEzPRFGkGT';
  483. break;
  484. case 'TUSD'://TUSD
  485. $contractAddress = 'TUpMhErZL2fhh4sVNULAbNKLokS4GjC1F4';
  486. break;
  487. case 'BTC'://BTC
  488. $contractAddress = 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9';
  489. break;
  490. case 'ETH'://ETH
  491. $contractAddress = 'THb4CqiFdwNHsWsQCs4JhzwjMWys4aqCbF';
  492. break;
  493. case 'USDD'://USDD
  494. $contractAddress = 'TPYmHEhy5n8TCEfYGqW2rPxsghSfzghPDn';
  495. break;
  496. default:
  497. $contractAddress = '';
  498. }
  499. return $contractAddress;
  500. }
  501. public static function base58_encode($string)
  502. {
  503. if (is_string($string) === false) {
  504. return false;
  505. }
  506. if ($string === '') {
  507. return '';
  508. }
  509. $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  510. $base = strlen($alphabet);
  511. $bytes = array_values(unpack('C*', $string));
  512. $decimal = $bytes[0];
  513. for ($i = 1, $l = count($bytes); $i < $l; $i++) {
  514. $decimal = bcmul($decimal, 256);
  515. $decimal = bcadd($decimal, $bytes[$i]);
  516. }
  517. $output = '';
  518. while ($decimal >= $base) {
  519. $div = bcdiv($decimal, $base, 0);
  520. $mod = bcmod($decimal, $base);
  521. $output .= $alphabet[$mod];
  522. $decimal = $div;
  523. }
  524. if ($decimal > 0) {
  525. $output .= $alphabet[$decimal];
  526. }
  527. $output = strrev($output);
  528. foreach ($bytes as $byte) {
  529. if ($byte === 0) {
  530. $output = $alphabet[0].$output;
  531. continue;
  532. }
  533. break;
  534. }
  535. return $output;
  536. }
  537. public static function base58_decode($base58)
  538. {
  539. if (is_string($base58) === false) {
  540. return false;
  541. }
  542. if ($base58 === '') {
  543. return '';
  544. }
  545. $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  546. $base = strlen($alphabet);
  547. $indexes = array_flip(str_split($alphabet));
  548. $chars = str_split($base58);
  549. foreach ($chars as $char) {
  550. if (isset($indexes[$char]) === false) {
  551. return false;
  552. }
  553. }
  554. $decimal = $indexes[$chars[0]];
  555. for ($i = 1, $l = count($chars); $i < $l; $i++) {
  556. $decimal = bcmul($decimal, $base);
  557. $decimal = bcadd($decimal, $indexes[$chars[$i]]);
  558. }
  559. $output = '';
  560. while ($decimal > 0) {
  561. $byte = bcmod($decimal, 256);
  562. $output = pack('C', $byte).$output;
  563. $decimal = bcdiv($decimal, 256, 0);
  564. }
  565. foreach ($chars as $char) {
  566. if ($indexes[$char] === 0) {
  567. $output = "\x00".$output;
  568. continue;
  569. }
  570. break;
  571. }
  572. return $output;
  573. }
  574. //encode address from byte[] to base58check string
  575. public static function base58check_en($address)
  576. {
  577. $hash0 = hash("sha256", $address);
  578. $hash1 = hash("sha256", hex2bin($hash0));
  579. $checksum = substr($hash1, 0, 8);
  580. $address .= hex2bin($checksum);
  581. return self::base58_encode($address);
  582. }
  583. public static function base58check_de($base58add)
  584. {
  585. $address = self::base58_decode($base58add);
  586. $size = strlen($address);
  587. if ($size !== 25) {
  588. return false;
  589. }
  590. $checksum = substr($address, 21);
  591. $address = substr($address, 0, 21);
  592. $hash0 = hash("sha256", $address);
  593. $hash1 = hash("sha256", hex2bin($hash0));
  594. $checksum0 = substr($hash1, 0, 8);
  595. $checksum1 = bin2hex($checksum);
  596. if (strcmp($checksum0, $checksum1)) {
  597. return false;
  598. }
  599. return $address;
  600. }
  601. public static function hexString2Base58check($hexString)
  602. {
  603. $address = hex2bin($hexString);
  604. return self::base58check_en($address);
  605. }
  606. public static function base58check2HexString($base58add)
  607. {
  608. $address = self::base58check_de($base58add);
  609. return bin2hex($address);
  610. }
  611. public static function hexString2Base64($hexString)
  612. {
  613. $address = hex2bin($hexString);
  614. return base64_encode($address);
  615. }
  616. public static function base642HexString($base64)
  617. {
  618. $address = base64_decode($base64);
  619. return bin2hex($address);
  620. }
  621. public static function base58check2Base64($base58add)
  622. {
  623. $address =self::base58check_de($base58add);
  624. return base64_encode($address);
  625. }
  626. public static function base642Base58check($base64)
  627. {
  628. $address = base64_decode($base64);
  629. return self::base58check_en($address);
  630. }
  631. public static function getrandstr($length)
  632. {
  633. $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
  634. $randStr = str_shuffle($str);//打乱字符串
  635. return substr($randStr, 0, $length);
  636. }
  637. /**
  638. * 检测是否有效钱包地址
  639. * @param $address
  640. * @return bool
  641. */
  642. public static function isValidAddress($address)
  643. {
  644. if (empty($address)) {
  645. return false;
  646. }
  647. if (strlen($address) != 34) {
  648. return false;
  649. }
  650. if (substr($address, 0, 1) != 'T') {
  651. return false;
  652. }
  653. // 验证地址
  654. $client = new Client([
  655. 'verify' => false, // 关闭 SSL 验证
  656. ]);
  657. $response = $client->request('POST', 'https://api.shasta.trongrid.io/wallet/validateaddress', [
  658. 'body' => json_encode(["address" => $address]),
  659. 'headers' => [
  660. 'Accept' => 'application/json',
  661. 'Content-Type' => 'application/json',
  662. ],
  663. ]);
  664. $resp = $response->getBody()->getContents();
  665. $resp = json_decode($resp);
  666. // 失败提示错误
  667. if ($resp->result === false) {
  668. return false;
  669. }
  670. return true;
  671. }
  672. /**
  673. * 获取私钥,通过私钥可以拿到收款地址,各种权限
  674. * 注意:必须拿28位字符串来生成地址,否则无法生成正常的地址
  675. * @param $base64
  676. * @return string
  677. */
  678. public function getPrivateKey($base64)
  679. {
  680. return $this->base642HexString($base64);
  681. }
  682. /**
  683. * 生成波场key
  684. * @param $memberId
  685. * @return string
  686. */
  687. public static function makePrivateKey($memberId)
  688. {
  689. $fix = 'SSTGsstg';//固定8前缀,避免和其他人同地址
  690. $rand = TronHelper::getrandstr(20);//10位数随机,避免同地址
  691. $base64Sting = $fix.$rand.str_pad($memberId, 15, 0, STR_PAD_LEFT);
  692. $tronHelper = new TronHelper();
  693. return $tronHelper->getPrivateKey($base64Sting);
  694. }
  695. /**
  696. * 查询余额
  697. * @param $privateKey
  698. * @return int
  699. */
  700. public static function getBalance($address, $currency)
  701. {
  702. bcscale(6);
  703. $rate = 1000000;
  704. $currency = strtoupper($currency);
  705. if(self::getTronNetwork()){
  706. $api = TronApi::testNetNilo();
  707. }else{
  708. $api = TronApi::mainNet();
  709. }
  710. $privateKey = self::makePrivateKey(time());
  711. $credential = Credential::fromPrivateKey($privateKey);
  712. $kit = new TronKit($api, $credential);
  713. if ($currency == 'TRX') {
  714. try {
  715. $balance = $kit->getTrxBalance($address);
  716. return bcdiv($balance, $rate);
  717. } catch (\Exception $e) {
  718. return bcmul(0, 0);
  719. }
  720. }
  721. try {
  722. $contractAddress = self::getContractAddress($currency);
  723. $usdt = $kit->Trc20($contractAddress);
  724. $balance = $usdt->balanceOf($address);
  725. return bcdiv($balance, $rate);
  726. } catch (\Exception $e) {
  727. return bcmul(0, 0);
  728. }
  729. }
  730. /**
  731. * 获取转账信息
  732. * @param $txid
  733. */
  734. public static function getSendInfo($txid)
  735. {
  736. // $api = TronApi::mainNet();
  737. if(self::getTronNetwork()){
  738. $api = TronApi::testNetNilo();
  739. }else{
  740. $api = TronApi::mainNet();
  741. }
  742. $ret = $api->getTransaction($txid);
  743. $retArr = $ret->ret;
  744. if (isset($retArr[0]->contractRet)) {
  745. return $retArr[0]->contractRet;
  746. }
  747. return 'UNKNOWN';
  748. }
  749. /**
  750. * 完整交易详情,如果交易未完成或者不成功,返回空
  751. * @param $txid
  752. * @return string
  753. */
  754. public static function getTransactionInfoById($txid)
  755. {
  756. // $api = TronApi::mainNet();
  757. if(self::getTronNetwork()){
  758. $api = TronApi::testNetNilo();
  759. }else{
  760. $api = TronApi::mainNet();
  761. }
  762. $ret = $api->getTransactionInfoById($txid);
  763. return json_decode(json_encode($ret), true);
  764. }
  765. /**
  766. * 获取出款账户地址
  767. */
  768. public static function getWithdrawAddress()
  769. {
  770. // $privateKey = Yii::$app->params['withdraw_address_trx_key'];
  771. // $credential = Credential::fromPrivateKey($privateKey);
  772. // return $credential->address()->base58();
  773. }
  774. /**
  775. * 获取地址
  776. * @param $fromKey
  777. */
  778. public static function getAddressByPrivateKey($fromKey)
  779. {
  780. $credential = Credential::fromPrivateKey($fromKey);
  781. return $credential->address()->base58();
  782. }
  783. /**
  784. * 转账给指定地址
  785. * @param $fromKey
  786. * @param $toAddress
  787. * @param $amount
  788. * @throws \Exception
  789. */
  790. public static function sendTrx($fromKey, $toAddress, $amount)
  791. {
  792. if ($amount <= 0) {
  793. throw new \Exception('不能低于 0 trx');
  794. }
  795. // from 初始化
  796. if(self::getTronNetwork()){
  797. $api = TronApi::testNetNilo();
  798. }else{
  799. $api = TronApi::mainNet();
  800. }
  801. $credential = Credential::fromPrivateKey($fromKey);
  802. $kit = new TronKit($api, $credential);
  803. // from 余额判断
  804. $from = $credential->address()->base58();
  805. $balance = self::getBalance($from, 'TRX');
  806. $rate = 1000000;
  807. if ($balance < $amount) {
  808. return '余额不足';
  809. }
  810. // 发送
  811. try {
  812. return $kit->sendTrx($toAddress, 1 * bcmul($amount, $rate, 6));
  813. } catch (\Exception $e) {
  814. Log::error('转账错误,fromKey='.$fromKey.'toAddress='.$toAddress.'amount='.$amount);
  815. Log::error('转账错误'.$e->getMessage());
  816. return false;
  817. }
  818. }
  819. /**usdt转账
  820. * @param $fromKey
  821. * @param $toAddress
  822. * @param $amount
  823. * @param $currency
  824. * @return bool|object
  825. * @throws \Exception
  826. */
  827. public static function sendTrc20($fromKey, $toAddress, $amount, $currency)
  828. {
  829. if ($amount <= 0) {
  830. throw new \Exception('不能低于 0 USDT');
  831. }
  832. $credential = Credential::fromPrivateKey($fromKey);
  833. $credential->address()->hex();
  834. if(self::getTronNetwork()){
  835. $api = TronApi::testNetNilo();
  836. }else{
  837. $api = TronApi::mainNet();
  838. }
  839. $kit = new TronKit($api, $credential);
  840. $contractAddress = self::getContractAddress($currency);
  841. $rate = 1000000;//换算汇率
  842. // $balance = self::getBalance(self::getAddressByPrivateKey($fromKey), $currency); //查询Trc20代币余额
  843. $balance = self::getTrc20Balance(self::getAddressByPrivateKey($fromKey)); //查询Trc20代币余额
  844. if ($balance < $amount) {
  845. throw new \Exception('余额不足');
  846. }
  847. $trc20 = $kit->Trc20($contractAddress); //创建Trc20代币合约实例
  848. try {
  849. $ret = $trc20->transfer($toAddress, (int) bcmul($amount, $rate)); //转账Trc20代币
  850. return (object) [
  851. 'txid' => $ret->tx->txID,
  852. 'result' => $ret->result,
  853. ];
  854. } catch (\Exception $e) {
  855. Log::error('Trc20转账错误,fromKey='.$fromKey.'toAddress='.$toAddress.'amount='.$amount);
  856. Log::error('Trc20转账错误'.$e->getMessage());
  857. return false;
  858. }
  859. }
  860. /**
  861. * 归集账户资金校验
  862. * trade_status:
  863. * - failed 转账失败
  864. * - waiting 转账成功,尚未校验
  865. * - closed waiting 之后,脚本查询时,交易验证成功
  866. * - aborted waiting 之后,脚本查询时,交易验证失败
  867. * @param $fromKey
  868. * @param $toAddress
  869. * @param $amount
  870. * @param $memberId
  871. * @param string $currency
  872. * @param string $net
  873. * @return bool
  874. * @throws \Exception
  875. */
  876. public function actionFundsGather(
  877. $fromKey,
  878. $toAddress,
  879. $amount,
  880. $memberId,
  881. $currency = 'TRX',
  882. $net = 'TRC20'
  883. ) {
  884. // $currency = strtoupper($currency);
  885. // if ($amount <= 0) {
  886. // throw new \Exception('不能低于 0 trx');
  887. // }
  888. // if (empty($toAddress)) {
  889. // throw new \Exception('收款地址不能为空');
  890. // }
  891. // $fromAddress = self::getAddressByPrivateKey($fromKey);
  892. // $remainAmount = self::getBalance($fromAddress, $currency);
  893. // if ($remainAmount < $amount) {
  894. // throw new \Exception('余额不足,归集失败');
  895. // }
  896. // $min = MinRechargeEnum::getValue($currency);
  897. // if ($currency == 'TRX') {
  898. // $ret = self::sendTrx($fromKey, $toAddress, $amount);
  899. // } else {
  900. // // 发送
  901. // //校验trx是否足够,不够就充值10燃烧费用进来
  902. // if (self::getBalance($fromAddress, 'TRX') < 10) {
  903. // $withdrawAddressTrxKey = Yii::$app->params['withdraw_address_trx_key'];
  904. // self::sendTrx($withdrawAddressTrxKey, self::getAddressByPrivateKey($fromKey), 10);
  905. // }
  906. // $ret = self::sendTrc20($fromKey, $toAddress, $amount, $currency);
  907. // }
  908. // //少于最低可入款额度,不入账,只做归集
  909. // if ($min > $remainAmount) {
  910. // return false;
  911. // }
  912. // try {
  913. // // 记录
  914. // $fundsGather = new Recharge();
  915. // $fundsGather->member_id = $memberId;
  916. // $fundsGather->txid = $ret->txid;
  917. // $fundsGather->amount = $amount;
  918. // $fundsGather->address = $toAddress;
  919. // $fundsGather->created_at = time();
  920. // $fundsGather->currency = $currency;
  921. // $fundsGather->usdt_balance = bcmul($amount, ExchangeRateService::getExchangeRate($currency),
  922. // CommonEnum::DIGITS);
  923. // $fundsGather->is_auto = 1;
  924. // $fundsGather->count = Recharge::find()->where(['member_id' => $memberId])->count() + 1;
  925. // $fundsGather->net = $net;
  926. // $fundsGather->ordernum = StrHelper::createOrdernum();
  927. // // 记录「充值请求次数」
  928. // $member = Member::findOne($memberId);
  929. // $member->recharge_request_count = $fundsGather->count;
  930. // $member->save();
  931. // if ($ret->result == 1) { // 成功
  932. // $fundsGather->trade_status = 'waiting';
  933. // if ($fundsGather->save()) {
  934. // return true;
  935. // }
  936. // } else { // 失败
  937. // $fundsGather->trade_status = 'failed';
  938. // $fundsGather->save();
  939. // }
  940. // } catch (Exception $e) {
  941. // throw new \Exception('转账异常'.$e->getMessage());
  942. // }
  943. return false;
  944. }
  945. }