UsdtWalletService.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services;
  12. use App\Models\CapitalLogModel;
  13. use App\Models\CoinLogModel;
  14. use App\Models\MemberModel;
  15. use App\Services\Api\MemberService;
  16. use App\Services\Common\CoinLogService;
  17. use BitWasp\Bitcoin\Address\AddressCreator;
  18. use BitWasp\Bitcoin\Address\PayToPubKeyHashAddress;
  19. use BitWasp\Bitcoin\Bitcoin;
  20. use BitWasp\Bitcoin\Crypto\Random\Random;
  21. use BitWasp\Bitcoin\Key\Factory\PrivateKeyFactory;
  22. use BitWasp\Bitcoin\Script\WitnessProgram;
  23. use GuzzleHttp\Client;
  24. use IEXBase\TronAPI\Tron;
  25. use Tron\Api;
  26. use Tron\TRC20;
  27. use Tron\TRX;
  28. use Web3\Methods\Eth\SendRawTransaction;
  29. use Web3p\EthereumTx\ERC20Transaction;
  30. use Web3p\EthereumTx\Transaction;
  31. use Web3p\EthereumUtil\Util;
  32. /**
  33. * USDT链管理-服务类
  34. * Class UsdtWalletService
  35. * @package App\Services
  36. */
  37. class UsdtWalletService extends BaseService
  38. {
  39. protected $apiUrl = '';
  40. protected $config = [];
  41. // 静态对象
  42. protected static $instance = null;
  43. protected $apiUrls = [
  44. 'usdt_trx2_transfer_log' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&only_confirmed=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  45. 'usdt_trx2_transfer_logs' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  46. ];
  47. /**
  48. * 构造函数
  49. * UsdtWalletService constructor.
  50. */
  51. public function __construct()
  52. {
  53. $this->memberModel = new MemberModel();
  54. $this->coinModel = new CoinLogModel();
  55. $this->capitalModel = new CapitalLogModel();
  56. $this->config = ConfigService::make()->getConfigOptionByGroup(4);
  57. if (empty($this->config)) {
  58. return false;
  59. }
  60. }
  61. /**
  62. * 静态入口
  63. * @return static|null
  64. */
  65. public static function make()
  66. {
  67. if (!self::$instance) {
  68. self::$instance = (new UsdtWalletService());
  69. }
  70. return self::$instance;
  71. }
  72. /**
  73. * 获取TRC2.0钱包地址
  74. * @throws \Tron\Exceptions\TronErrorException
  75. */
  76. public function getTrxAddress()
  77. {
  78. try {
  79. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  80. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
  81. $trxWallet = new TRX($api);
  82. $addressData = $trxWallet->generateAddress();
  83. $addressData = (array)$addressData;
  84. return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
  85. } catch (\Exception $exception) {
  86. $this->error = $exception->getMessage();
  87. return false;
  88. }
  89. }
  90. /**
  91. * trx 转账
  92. * @param $to 进账账户
  93. * @param $amount 转账金额
  94. * @throws \Tron\Exceptions\TransactionException
  95. * @throws \Tron\Exceptions\TronErrorException
  96. */
  97. public function trxTransfer($to, $amount, $from = '')
  98. {
  99. if ($amount <= 0) {
  100. $this->error = '2205';
  101. return false;
  102. }
  103. if (empty($this->config['tron_api_url'])) {
  104. $this->error = '2206';
  105. return false;
  106. }
  107. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  108. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  109. $trxWallet = new TRX($api);
  110. // 获取钱包参数
  111. try {
  112. $otcAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  113. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  114. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  115. $this->error = '2203';
  116. return false;
  117. }
  118. $tron = new Tron();
  119. // 获取平台钱包hex
  120. $tron->setAddress($otcAddress);
  121. $otcAddress = $tron->getAddress();
  122. $tron->setAddress($to);
  123. $toAddress = $tron->getAddress();
  124. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  125. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  126. $result = $trxWallet->transfer($from, $to, $amount);
  127. return $result;
  128. } catch (\Exception $exception) {
  129. $message = $exception->getMessage();
  130. $this->error = $message;
  131. return false;
  132. }
  133. }
  134. /**
  135. * usdt-trc2.0 转账
  136. * @param $to 进账账户
  137. * @param $amount 转账金额
  138. * @param $from 转账账户
  139. * @param $fromPrivate 转账账户私钥
  140. * @throws \Tron\Exceptions\TransactionException
  141. * @throws \Tron\Exceptions\TronErrorException
  142. */
  143. public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivate = '')
  144. {
  145. if ($amount <= 0) {
  146. $this->error = '2205';
  147. return false;
  148. }
  149. if (empty($this->config['tron_api_url'])) {
  150. $this->error = '2206';
  151. return false;
  152. }
  153. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  154. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  155. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  156. // 获取钱包参数
  157. try {
  158. // 用出账钱包转账
  159. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('trc_out_address');
  160. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('trc_out_private_key');
  161. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  162. $this->error = '2203';
  163. return false;
  164. }
  165. $tron = new Tron();
  166. // 获取平台钱包hex
  167. $tron->setAddress($otcAddress);
  168. $otcAddress = $tron->getAddress();
  169. // 获取收款钱包hex
  170. $tron->setAddress($to);
  171. $toAddress = $tron->getAddress();
  172. RedisService::set("caches:wallet:transfer:temp_{$to}",['to'=> $to,'out'=> $otcAddress,'outPrivate'=> $otcAddressPrivate,'amount'=> $amount], 7200);
  173. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  174. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  175. $result = $trxWallet->transfer($from, $to, $amount);
  176. $result = (array)$result;
  177. if(isset($result['txID'])){
  178. return $result;
  179. }
  180. return false;
  181. } catch (\Exception $exception) {
  182. $message = $exception->getMessage();
  183. $this->error = $message;
  184. RedisService::set("caches:wallet:transfer:error_{$toAddress['base58']}", $exception, 600);
  185. return false;
  186. }
  187. }
  188. /**
  189. * usdt-trc2.0 归集
  190. * @throws \Tron\Exceptions\TransactionException
  191. * @throws \Tron\Exceptions\TronErrorException
  192. */
  193. public function usdtTrcTrigger($force = false)
  194. {
  195. if (empty($this->config['tron_api_url'])) {
  196. $this->error = '2206';
  197. return false;
  198. }
  199. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  200. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  201. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  202. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  203. // 获取钱包参数
  204. try {
  205. // 用收账钱包归集
  206. $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
  207. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
  208. // 出账手续费钱包
  209. $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  210. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  211. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  212. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  213. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
  214. $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
  215. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  216. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  217. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  218. $this->error = '2203';
  219. return false;
  220. }
  221. // 出账钱包
  222. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  223. $this->error = '2203';
  224. return false;
  225. }
  226. $page = RedisService::get("caches:wallet:transferPage");
  227. $page = $page ? $page : 1;
  228. // 归集时间段为凌晨0点-5点
  229. if ((date('H:i') >= '05:00') && !$force) {
  230. $this->error = '不在归集时间段';
  231. return false;
  232. }
  233. if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
  234. $this->error = '不要频繁操作,30秒后重试';
  235. return false;
  236. }
  237. // 上锁
  238. RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
  239. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  240. if (empty($addrList)) {
  241. RedisService::set("caches:wallet:transferPage", 1, 600);
  242. $this->error = '1019';
  243. return false;
  244. }
  245. // 平台钱包地址
  246. $count = 0;
  247. $failedCount = 0;
  248. $retryCount = 0;
  249. $notBalance = false;
  250. $tron = new Tron();
  251. $tron->setAddress($otcAddress);
  252. $otcAddress = $tron->getAddress();
  253. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  254. // 平台出账钱包地址
  255. $tron->setAddress($otcOutAddress);
  256. $otcOutAddress = $tron->getAddress();
  257. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  258. $cacheKey = "caches:wallet:trigger:";
  259. foreach ($addrList as $v) {
  260. try {
  261. // 获取子钱包TRC-USDT余额
  262. $userId = isset($v['id']) ? $v['id'] : 0;
  263. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  264. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  265. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  266. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  267. // 可归集的USDT余额
  268. $triggerUsdt = $trcWallet->balance($triggerAddress);
  269. // USDT 余额低于归集金额,则不归集
  270. if ($triggerUsdt < $triggerMin) {
  271. $failedCount++;
  272. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  273. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  274. continue;
  275. }
  276. // 获取子钱包TRX余额
  277. $triggerTrx = $trxWallet->balance($triggerAddress);
  278. // 获取平台出账钱包TRX余额
  279. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  280. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  281. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  282. $failedCount++;
  283. $notBalance = true;
  284. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  285. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  286. continue;
  287. }
  288. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  289. if ($triggerTrx < $triggerFree) {
  290. $retryCount++;
  291. $result = $this->trxTransfer($address, $triggerFree);
  292. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  293. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  294. continue;
  295. }
  296. // 满足归集条件处理
  297. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  298. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  299. $count++;
  300. } catch (\Exception $exception) {
  301. $failedCount++;
  302. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  303. }
  304. }
  305. // 超出分页数,下次处理下一页
  306. if (count($addrList) >= 200) {
  307. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  308. }
  309. if ($count > 0) {
  310. $this->error = lang(2225, ['success' => $count, 'fail' => $failedCount, 'retry' => $retryCount]);
  311. return ['success' => $count, 'fail' => $failedCount, 'retryCount' => $retryCount];
  312. } else if ($failedCount == count($addrList)) {
  313. $this->error = 2221;
  314. return false;
  315. } else if ($retryCount) {
  316. $this->error = lang(2222, ['num' => $retryCount]);
  317. return false;
  318. } else if ($notBalance) {
  319. $this->error = 2221;
  320. return false;
  321. } else {
  322. $this->error = lang(2224, ['num' => $failedCount]);
  323. return false;
  324. }
  325. } catch (\Exception $exception) {
  326. $this->error = $exception->getMessage();
  327. return false;
  328. }
  329. }
  330. /**
  331. * 监听USDT-TRC2.0转账记录并进账
  332. * @param $userId 用户ID
  333. * @param $address 用户钱包地址
  334. * @param int $coinType 币种:1-usdt
  335. * @param int $limit 转账记录数,最新的
  336. * @return array|false
  337. */
  338. public function getTrc20RechargeLog($userId, $address, $coinType = 1, $limit = 50)
  339. {
  340. if ($userId <= 0 || empty($address)) {
  341. $this->error = '1013';
  342. return false;
  343. }
  344. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  345. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  346. RedisService::set("caches:wallets:recharge_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  347. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  348. $result = $result ? json_decode($result, true) : [];
  349. $datas = isset($result['data']) ? $result['data'] : [];
  350. $status = isset($result['success']) ? $result['success'] : '';
  351. if ($status != true || empty($datas)) {
  352. $this->error = '2207';
  353. return false;
  354. }
  355. $logs = [];
  356. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  357. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  358. foreach ($datas as $v) {
  359. $amount = isset($v['value']) ? intval($v['value']) : 0;
  360. $amount = moneyFormat($amount / 1000000, 6);
  361. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  362. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  363. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  364. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  365. $orderNo = get_order_num('TR');
  366. $log = [
  367. 'user_id' => $userId,
  368. 'change_type' => 1,
  369. 'coin_type' => $coinType,
  370. 'contact_type' => 1,
  371. 'order_no' => $orderNo,
  372. 'from_address' => isset($v['from']) ? $v['from'] : '',
  373. 'to_address' => isset($v['to']) ? $v['to'] : '',
  374. 'txid' => $txid,
  375. 'num' => $amount,
  376. 'balance' => $balance,
  377. 'create_time' => $time ? $time : time(),
  378. 'update_time' => time(),
  379. 'status' => 2,
  380. 'mark' => 1,
  381. ];
  382. if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
  383. $this->memberModel->where(['id' => $userId])->increment('trc_usdt', $amount);
  384. $log['status'] = 1;
  385. $data = [
  386. 'order_no' => $orderNo,
  387. 'user_id' => $userId,
  388. 'type' => 4,
  389. 'pay_type' => 1,
  390. 'trade_type' => 3,
  391. 'change_type' => 1,
  392. 'num' => $amount,
  393. 'total' => 0,
  394. 'balance' => floatval($balance + $amount),
  395. 'create_time' => time(),
  396. 'update_time' => time(),
  397. 'remark' => '存币',
  398. 'status' => 1,
  399. 'mark' => 1,
  400. ];
  401. $this->capitalModel->edit($data);
  402. }
  403. $logs[] = $log;
  404. $this->coinModel->insert($log);
  405. }
  406. }
  407. return $logs;
  408. }
  409. /**
  410. * 获取USDT-TRC2.0交易记录(进出账)
  411. * @param $address 用户钱包地址
  412. * @param int $coinType 币种:1-usdt
  413. * @param int $limit 转账记录数,最新的
  414. * @return array|false
  415. */
  416. public function getTrc20TransferLog($address, $type = 1, $limit = 50)
  417. {
  418. if (empty($address)) {
  419. $this->error = '1013';
  420. return false;
  421. }
  422. // 存币
  423. if ($type == 1) {
  424. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  425. } // 提币
  426. else {
  427. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  428. }
  429. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  430. RedisService::set("caches:wallets:transfer_temp_otc_{$type}", ['url' => $this->config['tron_api_url'] . $url], 600);
  431. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  432. $result = $result ? json_decode($result, true) : [];
  433. $datas = isset($result['data']) ? $result['data'] : [];
  434. $status = isset($result['success']) ? $result['success'] : '';
  435. if ($status != true || empty($datas)) {
  436. $this->error = '2207';
  437. return false;
  438. }
  439. if ($datas) {
  440. foreach ($datas as &$item) {
  441. $time = ($item['block_timestamp'] / 1000);
  442. $item['time_text'] = $time ? datetime($time, 'm-d H:i') : '';
  443. $item['num'] = floatval($item['value'] / 1000000);
  444. $item['contact_type'] = 1;
  445. $item['change_type'] = $type;
  446. $item['status'] = 1;
  447. }
  448. }
  449. return $datas;
  450. }
  451. /**
  452. * 监听USDT-TRC2.0提币记录并进账(平台钱包)
  453. * @param $address 用户钱包地址
  454. * @param int $limit 转账记录数,最新的
  455. * @return array|false
  456. */
  457. public function getTrc20TransferLogByOtc($address, $limit = 50)
  458. {
  459. if (empty($address)) {
  460. $this->error = '1013';
  461. return false;
  462. }
  463. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  464. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  465. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  466. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  467. $result = $result ? json_decode($result, true) : [];
  468. $datas = isset($result['data']) ? $result['data'] : [];
  469. $status = isset($result['success']) ? $result['success'] : '';
  470. if ($status != true || empty($datas)) {
  471. $this->error = '2207';
  472. return false;
  473. }
  474. $logs = [];
  475. foreach ($datas as $v) {
  476. $amount = isset($v['value']) ? intval($v['value']) : 0;
  477. $amount = moneyFormat($amount / 1000000, 6);
  478. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  479. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  480. if ($time > time() - 12 * 3600) {
  481. // 有记录,且是用户提币
  482. $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
  483. $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
  484. if ($coinInfo && $userId && $coinInfo['status'] == 4) {
  485. // 直接更新提币状态
  486. CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['status' => 1, 'update_time' => time()]);
  487. // 明细处理
  488. $num = floatval($coinInfo['num'] + $coinInfo['free']);
  489. $data = [
  490. 'order_no' => $coinInfo['order_no'],
  491. 'user_id' => $userId,
  492. 'type' => 5,
  493. 'pay_type' => 1,
  494. 'trade_type' => 3,
  495. 'change_type' => 2,
  496. 'num' => $num,
  497. 'total' => 0,
  498. 'balance' => floatval($coinInfo['balance'] - $num),
  499. 'create_time' => time(),
  500. 'update_time' => time(),
  501. 'remark' => '提币',
  502. 'status' => 1,
  503. 'mark' => 1,
  504. ];
  505. $this->capitalModel->edit($data);
  506. $logs[] = ['log' => $v, 'order' => $coinInfo];
  507. }
  508. }
  509. }
  510. return $logs;
  511. }
  512. /**
  513. * 监听USDT-TRC2.0充值记录并进账(用户子钱包)
  514. * @param $userId 用户ID
  515. * @param $address 用户钱包地址
  516. * @param int $coinType 币种:1-usdt
  517. * @param int $limit 转账记录数,最新的
  518. * @return array|false
  519. */
  520. public function getTrc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
  521. {
  522. if ($userId <= 0 || empty($address)) {
  523. $this->error = '1013';
  524. return false;
  525. }
  526. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  527. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  528. RedisService::set("caches:wallets:transfer_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  529. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  530. $result = $result ? json_decode($result, true) : [];
  531. $datas = isset($result['data']) ? $result['data'] : [];
  532. $status = isset($result['success']) ? $result['success'] : '';
  533. if ($status != true || empty($datas)) {
  534. $this->error = '2207';
  535. return false;
  536. }
  537. $logs = [];
  538. $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
  539. $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
  540. foreach ($datas as $v) {
  541. $amount = isset($v['value']) ? intval($v['value']) : 0;
  542. $amount = moneyFormat($amount / 1000000, 6);
  543. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  544. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  545. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  546. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  547. $orderNo = get_order_num('TW');
  548. $log = [
  549. 'user_id' => $userId,
  550. 'change_type' => 2,
  551. 'coin_type' => $coinType,
  552. 'contact_type' => 1,
  553. 'order_no' => $orderNo,
  554. 'from_address' => isset($v['from']) ? $v['from'] : '',
  555. 'to_address' => isset($v['to']) ? $v['to'] : '',
  556. 'txid' => $txid,
  557. 'num' => $amount,
  558. 'balance' => $balance,
  559. 'create_time' => $time ? $time : time(),
  560. 'update_time' => time(),
  561. 'status' => 2,
  562. 'mark' => 1,
  563. ];
  564. if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
  565. $this->memberModel->where(['id' => $userId])->decrement('trc_usdt', $amount);
  566. $log['status'] = 1;
  567. // 明细处理
  568. $data = [
  569. 'order_no' => $orderNo,
  570. 'user_id' => $userId,
  571. 'type' => 5,
  572. 'pay_type' => 1,
  573. 'trade_type' => 3,
  574. 'change_type' => 2,
  575. 'num' => $amount,
  576. 'total' => 0,
  577. 'balance' => floatval($balance - $amount),
  578. 'create_time' => time(),
  579. 'update_time' => time(),
  580. 'remark' => '提币',
  581. 'status' => 1,
  582. 'mark' => 1,
  583. ];
  584. $this->capitalModel->edit($data);
  585. }
  586. $logs[] = $log;
  587. $this->coinModel->insert($log);
  588. }
  589. }
  590. return $logs;
  591. }
  592. /**
  593. * TRX余额
  594. * @param $address
  595. * @return false|float|string
  596. */
  597. public function getTrxBalance($address)
  598. {
  599. $cacheKey = "caches:wallet:balance:{$address}";
  600. if (RedisService::get($cacheKey)) {
  601. return false;
  602. }
  603. if (empty($address)) {
  604. $this->error = '1018';
  605. return false;
  606. }
  607. if (empty($this->config['tron_api_url'])) {
  608. $this->error = '2206';
  609. return false;
  610. }
  611. try {
  612. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  613. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  614. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  615. $tron = new Tron();
  616. $tron->setAddress($address);
  617. $address = $tron->getAddress();
  618. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  619. $result = $trxWallet->balance($address);
  620. return $result ? floatval($result) : '0.00';
  621. } catch (\Exception $exception) {
  622. $this->error = $exception->getMessage();
  623. return false;
  624. }
  625. }
  626. /**
  627. * USDT-TRC20余额
  628. * @param $address
  629. * @return false|float|string
  630. */
  631. public function getTrc20Usdt($address)
  632. {
  633. if (empty($address)) {
  634. $this->error = '1018';
  635. return false;
  636. }
  637. if (empty($this->config['tron_api_url'])) {
  638. $this->error = '2206';
  639. return false;
  640. }
  641. try {
  642. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  643. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  644. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  645. $tron = new Tron();
  646. $tron->setAddress($address);
  647. $address = $tron->getAddress();
  648. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  649. $result = $trxWallet->balance($address);
  650. return $result ? floatval($result) : '0.00';
  651. } catch (\Exception $exception) {
  652. $this->error = $exception->getMessage();
  653. return false;
  654. }
  655. }
  656. /********************** ERC钱包 **************************/
  657. /**
  658. * 获取ERC2.0钱包地址
  659. * @param string $type
  660. * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
  661. */
  662. public function getErcAddress()
  663. {
  664. $random = new Random();
  665. $network = Bitcoin::getNetwork();
  666. $privateKeyFactory = new PrivateKeyFactory();
  667. $privateKey = $privateKeyFactory->generateCompressed($random);
  668. $publicKey = $privateKey->getPublicKey();
  669. // p2pkh 格式的地址
  670. $addressService = new PayToPubKeyHashAddress($publicKey->getPubKeyHash());
  671. // 将生成的钱包保存到数据库中
  672. $wif = $privateKey->toWif($network);
  673. $address = $addressService->getAddress();
  674. return ['wif' => $wif, 'hexAddress' => $this->getHexAddress($address), 'address' => $address];
  675. }
  676. /**
  677. * 获取HASH钱包地址
  678. * @param $address 钱包地址
  679. * @return \BitWasp\Buffertools\BufferInterface
  680. * @throws \BitWasp\Bitcoin\Exceptions\UnrecognizedAddressException
  681. */
  682. public function getHexAddress($address)
  683. {
  684. $data = WitnessProgram::v0((new AddressCreator())->fromString($address)->getHash());
  685. $buffer = $data->getProgram()->getHex();
  686. return $buffer ? '0x' . $buffer : '';
  687. }
  688. /**
  689. * 监听USDT-ERC2.0提币记录并进账(平台钱包)
  690. * @param $address 用户钱包地址
  691. * @param int $limit 转账记录数,最新的
  692. * @return array|false
  693. */
  694. public function getErc20TransferLogByOtc($address, $limit = 50)
  695. {
  696. return false;
  697. if (empty($address)) {
  698. $this->error = '1013';
  699. return false;
  700. }
  701. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  702. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  703. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  704. }
  705. /**
  706. * ERC 转账
  707. * @throws \Tron\Exceptions\TransactionException
  708. * @throws \Tron\Exceptions\TronErrorException
  709. */
  710. public function ercTransfer($force = false)
  711. {
  712. if ($amount <= 0) {
  713. $this->error = '2205';
  714. return false;
  715. }
  716. if (empty($this->config['eth_api_url'])) {
  717. $this->error = '2206';
  718. return false;
  719. }
  720. if (empty($this->config['eth_api_key'])) {
  721. $this->error = '2207';
  722. return false;
  723. }
  724. // 获取钱包参数
  725. try {
  726. // 用出账钱包转账
  727. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  728. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  729. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  730. $this->error = '2228';
  731. return false;
  732. }
  733. $amount = floatval($amount*pow(10,18));
  734. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  735. $headers = ["Content-Type" => 'application/json'];
  736. $params = [
  737. "from"=> $otcAddress, // 来源
  738. "to"=> $to, // 收款
  739. "gas"=> '0x'.dechex(90000), // gas量,默认90000
  740. "gasPrice"=> "0x9184e72a000",
  741. "value"=> '0x'.dechex($amount),
  742. ];
  743. $transaction = new Transaction($params);
  744. $transaction->sign($otcAddressPrivate);
  745. $hash = $transaction->hash();
  746. $data = [
  747. "jsonrpc" => "2.0",
  748. "method" => "eth_sendRawTransaction",
  749. "params" => ['0x'.$hash],
  750. "id" => 1
  751. ];
  752. RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data,'hash'=> $hash], 600);
  753. $result = curl_api($url, json_encode($data), $headers);
  754. $result = $result ? json_decode($result, true) : [];
  755. $tradeHash = isset($result['result'])? $result['result'] : '';
  756. if($tradeHash && hexdec($tradeHash) != 0){
  757. return ['txid'=> $tradeHash,'amount'=> $amount];
  758. }else{
  759. $this->error = '2229';
  760. return false;
  761. }
  762. } catch (\Exception $exception) {
  763. $message = $exception->getMessage();
  764. $this->error = $message;
  765. return false;
  766. }
  767. }
  768. /**
  769. * usdt-erc2.0 转账
  770. * @param $to 进账账户
  771. * @param $amount 转账金额
  772. * @param $from 转账账户
  773. * @param $fromPrivate 转账账户私钥
  774. * @throws \Tron\Exceptions\TransactionException
  775. * @throws \Tron\Exceptions\TronErrorException
  776. */
  777. public function usdtErcTransfer($to, $amount, $from = '', $fromPrivate = '')
  778. {
  779. if ($amount <= 0) {
  780. $this->error = '2205';
  781. return false;
  782. }
  783. if (empty($this->config['eth_api_url'])) {
  784. $this->error = '2206';
  785. return false;
  786. }
  787. if (empty($this->config['eth_api_key'])) {
  788. $this->error = '2207';
  789. return false;
  790. }
  791. // 获取钱包参数
  792. try {
  793. // 用出账钱包转账
  794. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  795. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  796. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  797. $this->error = '2228';
  798. return false;
  799. }
  800. $amount = floatval($amount*pow(10,18));
  801. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  802. $headers = ["Content-Type" => 'application/json'];
  803. $sign = $this->getSha3Sign("transferFrom(address,address,uint256)");
  804. $params = [
  805. "from"=> $otcAddress, // 来源
  806. "to"=> $to, // 收款
  807. "gas"=> '0x'.dechex(90000), // gas量,默认90000
  808. "gasPrice"=> "0x9184e72a000",
  809. "value"=> '0x'.dechex($amount),
  810. "data"=> $this->getTransactionSignData($sign, $to, $amount)
  811. ];
  812. // $transaction = new Transaction($params);
  813. // $hash = $transaction->sign($otcAddressPrivate);
  814. $data = [
  815. "jsonrpc" => "2.0",
  816. // "method" => "eth_sendTransaction",
  817. "method" => "eth_sendTransaction",
  818. "params" => $params,
  819. // "params" => ['0x'.$hash],
  820. "id" => 1
  821. ];
  822. RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data], 600);
  823. $result = curl_api($url, json_encode($data), $headers);
  824. $result = $result ? json_decode($result, true) : [];
  825. $tradeHash = isset($result['result'])? $result['result'] : '';
  826. $error = isset($result['error'])? $result['error'] : [];
  827. if($tradeHash && hexdec($tradeHash) != 0){
  828. return ['txid'=> $tradeHash,'amount'=> $amount];
  829. }else{
  830. $this->error = isset($error['message'])? $error['message'] : '2229';
  831. return false;
  832. }
  833. } catch (\Exception $exception) {
  834. $message = $exception->getMessage();
  835. $this->error = $message;
  836. return false;
  837. }
  838. }
  839. /**
  840. * TRC余额
  841. * @param $address
  842. * @return false|float|string
  843. */
  844. public function getErcBalance($address)
  845. {
  846. if (empty($address)) {
  847. $this->error = '1018';
  848. return false;
  849. }
  850. if (empty($this->config['eth_api_url'])) {
  851. $this->error = '2206';
  852. return false;
  853. }
  854. if (empty($this->config['eth_api_key'])) {
  855. $this->error = '2207';
  856. return false;
  857. }
  858. try {
  859. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  860. $headers = ["Content-Type" => 'application/json'];
  861. $data = [
  862. "jsonrpc" => "2.0",
  863. "method" => "eth_getBalance",
  864. "params" => [$address, "latest"],
  865. "id" => 1
  866. ];
  867. $result = curl_api($url, json_encode($data), $headers);
  868. $result = $result ? json_decode($result, true) : [];
  869. $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
  870. return $balance ? floatval($balance/pow(10,18)) : '0.00';
  871. } catch (\Exception $exception) {
  872. $this->error = $exception->getMessage();
  873. return false;
  874. }
  875. }
  876. /**
  877. * USDT-ERC20余额
  878. * @param $address
  879. * @return false|float|string
  880. */
  881. public function getErc20Usdt($address)
  882. {
  883. if (empty($address)) {
  884. $this->error = '1018';
  885. return false;
  886. }
  887. if (empty($this->config['eth_api_url'])) {
  888. $this->error = '2206';
  889. return false;
  890. }
  891. if (empty($this->config['eth_api_key'])) {
  892. $this->error = '2207';
  893. return false;
  894. }
  895. if(empty($this->config['erc_contract_address'])){
  896. $this->error = '2228';
  897. return false;
  898. }
  899. try {
  900. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  901. $headers = ["Content-Type" => 'application/json'];
  902. $sign = $this->getSha3Sign("balanceOf(address)");
  903. $data = [
  904. "jsonrpc" => "2.0",
  905. "method" => "eth_call",
  906. "params" => [["to"=> $this->config['erc_contract_address'],"data"=> $this->getSignData($sign, $address)], "latest"],
  907. "id" => 1
  908. ];
  909. $result = curl_api($url, json_encode($data), $headers);
  910. $result = $result ? json_decode($result, true) : [];
  911. $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
  912. $balance = $balance? floatval($balance/1000000) : '0.00';
  913. return $balance? $balance : '0.00';
  914. } catch (\Exception $exception) {
  915. $this->error = $exception->getMessage();
  916. return false;
  917. }
  918. }
  919. /**
  920. * 合约方法签名编号
  921. * @param string $data
  922. * @return string
  923. */
  924. public function getSha3Sign($data)
  925. {
  926. $util = new Util();
  927. $result = $util->sha3($data);
  928. return '0x'.substr($result,0,8);
  929. }
  930. /**
  931. * 获取签名数据
  932. * @param $sign
  933. * @param $address
  934. * @return string
  935. */
  936. public function getSignData($sign, $address)
  937. {
  938. return $sign.str_repeat('0', 24).substr($address,2);
  939. }
  940. /**
  941. * 获取交易签名参数
  942. * @param $sign 调用的合约方法生成的sha3签名编号
  943. * @param $toAddress 收款地址
  944. * @param $amount 转账金额/十进制
  945. * @return string
  946. */
  947. public function getTransactionSignData($sign, $toAddress, $amount)
  948. {
  949. $toAddress = substr($toAddress,2); // 去掉0x
  950. $toAddressSign = str_repeat('0', 64-strlen($toAddress)).$toAddress; // 前面补齐0为64位
  951. $amount = dechex($amount); // 十进制转十六进制
  952. $amountSign = str_repeat('0', 64-strlen($amount)).$amount; // 前面补齐0为64位
  953. return $sign.$toAddressSign.$amountSign;
  954. }
  955. /**
  956. * 获取USDT-ERC2.0交易记录(进出账)
  957. * @param $address 用户钱包地址
  958. * @param int $coinType 币种:1-usdt
  959. * @param int $limit 转账记录数,最新的
  960. * @return array|false
  961. */
  962. public function getErc20TransferLog($address, $type = 1, $limit = 50)
  963. {
  964. }
  965. /**
  966. * usdt-trc2.0 归集
  967. * @throws \Tron\Exceptions\TransactionException
  968. * @throws \Tron\Exceptions\TronErrorException
  969. */
  970. public function usdtErcTrigger($force = false)
  971. {
  972. return false;
  973. if (empty($this->config['tron_api_url'])) {
  974. $this->error = '2206';
  975. return false;
  976. }
  977. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  978. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  979. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  980. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  981. // 获取钱包参数
  982. try {
  983. // 用收账钱包归集
  984. $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
  985. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
  986. // 出账手续费钱包
  987. $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  988. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  989. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  990. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  991. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
  992. $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
  993. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  994. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  995. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  996. $this->error = '2203';
  997. return false;
  998. }
  999. // 出账钱包
  1000. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  1001. $this->error = '2203';
  1002. return false;
  1003. }
  1004. $page = RedisService::get("caches:wallet:transferPage");
  1005. $page = $page ? $page : 1;
  1006. // 归集时间段为凌晨0点-5点
  1007. if ((date('H:i') >= '05:00') && !$force) {
  1008. $this->error = '不在归集时间段';
  1009. return false;
  1010. }
  1011. if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
  1012. $this->error = '不要频繁操作,30秒后重试';
  1013. return false;
  1014. }
  1015. // 上锁
  1016. RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
  1017. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  1018. if (empty($addrList)) {
  1019. RedisService::set("caches:wallet:transferPage", 1, 600);
  1020. $this->error = '1019';
  1021. return false;
  1022. }
  1023. // 平台钱包地址
  1024. $count = 0;
  1025. $failedCount = 0;
  1026. $tron = new Tron();
  1027. $tron->setAddress($otcAddress);
  1028. $otcAddress = $tron->getAddress();
  1029. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  1030. // 平台出账钱包地址
  1031. $tron->setAddress($otcOutAddress);
  1032. $otcOutAddress = $tron->getAddress();
  1033. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  1034. $cacheKey = "caches:wallet:trigger:";
  1035. foreach ($addrList as $v) {
  1036. try {
  1037. // 获取子钱包TRC-USDT余额
  1038. $userId = isset($v['id']) ? $v['id'] : 0;
  1039. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  1040. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  1041. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  1042. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  1043. // 可归集的USDT余额
  1044. $triggerUsdt = $trcWallet->balance($triggerAddress);
  1045. // USDT 余额低于归集金额,则不归集
  1046. if ($triggerUsdt < $triggerMin) {
  1047. $failedCount++;
  1048. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  1049. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1050. continue;
  1051. }
  1052. // 获取子钱包TRX余额
  1053. $triggerTrx = $trxWallet->balance($triggerAddress);
  1054. // 获取平台出账钱包TRX余额
  1055. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  1056. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  1057. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  1058. $failedCount++;
  1059. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  1060. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1061. continue;
  1062. }
  1063. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  1064. if ($triggerTrx < $triggerFree) {
  1065. $failedCount++;
  1066. $result = $this->trxTransfer($address, $triggerFree);
  1067. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  1068. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  1069. continue;
  1070. }
  1071. // 满足归集条件处理
  1072. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  1073. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  1074. $count++;
  1075. } catch (\Exception $exception) {
  1076. $failedCount++;
  1077. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  1078. }
  1079. }
  1080. // 超出分页数,下次处理下一页
  1081. if (count($addrList) >= 200) {
  1082. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  1083. }
  1084. if ($count > 0) {
  1085. return ['success' => $count, 'fail' => $failedCount];
  1086. } else {
  1087. $this->error = 1021;
  1088. return false;
  1089. }
  1090. } catch (\Exception $exception) {
  1091. $this->error = $exception->getMessage();
  1092. return false;
  1093. }
  1094. }
  1095. }