TronHelper.php 35 KB

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