TronHelper.php 36 KB

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