TronHelper.php 36 KB

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