UsdtWalletService.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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, $cache=false)
  598. {
  599. if (empty($address)) {
  600. $this->error = '1018';
  601. return false;
  602. }
  603. if (empty($this->config['tron_api_url'])) {
  604. $this->error = '2206';
  605. return false;
  606. }
  607. $cacheKey = "caches:wallet:balance:trx_{$address}";
  608. if ($data = RedisService::get($cacheKey) && $cache) {
  609. return $data;
  610. }
  611. if(RedisService::get($cacheKey.'_lock') && $cache){
  612. return false;
  613. }
  614. try {
  615. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  616. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  617. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  618. $tron = new Tron();
  619. $tron->setAddress($address);
  620. $address = $tron->getAddress();
  621. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  622. $result = $trxWallet->balance($address);
  623. $result = $result ? floatval($result) : '0.00';
  624. RedisService::set($cacheKey, $result, rand(5, 10));
  625. RedisService::set($cacheKey.'_lock', true, rand(5, 10));
  626. return $result;
  627. } catch (\Exception $exception) {
  628. $this->error = $exception->getMessage();
  629. return false;
  630. }
  631. }
  632. /**
  633. * USDT-TRC20余额
  634. * @param $address
  635. * @return false|float|string
  636. */
  637. public function getTrc20Usdt($address, $cache=false)
  638. {
  639. if (empty($address)) {
  640. $this->error = '1018';
  641. return false;
  642. }
  643. if (empty($this->config['tron_api_url'])) {
  644. $this->error = '2206';
  645. return false;
  646. }
  647. $cacheKey = "caches:wallet:balance:usdt_{$address}";
  648. if ($data = RedisService::get($cacheKey) && $cache) {
  649. return $data;
  650. }
  651. if(RedisService::get($cacheKey.'_lock') && $cache){
  652. return false;
  653. }
  654. try {
  655. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  656. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  657. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  658. $tron = new Tron();
  659. $tron->setAddress($address);
  660. $address = $tron->getAddress();
  661. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  662. $result = $trxWallet->balance($address);
  663. $result = $result ? floatval($result) : '0.00';
  664. RedisService::set($cacheKey, $result, rand(5, 10));
  665. RedisService::set($cacheKey.'_lock', true, rand(5, 10));
  666. return $result;
  667. } catch (\Exception $exception) {
  668. $this->error = $exception->getMessage();
  669. return false;
  670. }
  671. }
  672. /********************** ERC钱包 **************************/
  673. /**
  674. * 获取ERC2.0钱包地址
  675. * @param string $type
  676. * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
  677. */
  678. public function getErcAddress()
  679. {
  680. $random = new Random();
  681. $network = Bitcoin::getNetwork();
  682. $privateKeyFactory = new PrivateKeyFactory();
  683. $privateKey = $privateKeyFactory->generateCompressed($random);
  684. $publicKey = $privateKey->getPublicKey();
  685. // p2pkh 格式的地址
  686. $addressService = new PayToPubKeyHashAddress($publicKey->getPubKeyHash());
  687. // 将生成的钱包保存到数据库中
  688. $wif = $privateKey->toWif($network);
  689. $address = $addressService->getAddress();
  690. return ['wif' => $wif, 'hexAddress' => $this->getHexAddress($address), 'address' => $address];
  691. }
  692. /**
  693. * 获取HASH钱包地址
  694. * @param $address 钱包地址
  695. * @return \BitWasp\Buffertools\BufferInterface
  696. * @throws \BitWasp\Bitcoin\Exceptions\UnrecognizedAddressException
  697. */
  698. public function getHexAddress($address)
  699. {
  700. $data = WitnessProgram::v0((new AddressCreator())->fromString($address)->getHash());
  701. $buffer = $data->getProgram()->getHex();
  702. return $buffer ? '0x' . $buffer : '';
  703. }
  704. /**
  705. * 监听USDT-ERC2.0提币记录并进账(平台钱包)
  706. * @param $address 用户钱包地址
  707. * @param int $limit 转账记录数,最新的
  708. * @return array|false
  709. */
  710. public function getErc20TransferLogByOtc($address, $limit = 50)
  711. {
  712. return false;
  713. if (empty($address)) {
  714. $this->error = '1013';
  715. return false;
  716. }
  717. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  718. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  719. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  720. }
  721. /**
  722. * ERC 转账
  723. * @throws \Tron\Exceptions\TransactionException
  724. * @throws \Tron\Exceptions\TronErrorException
  725. */
  726. public function ercTransfer($to, $amount, $from, $fromPrivate)
  727. {
  728. if ($amount <= 0) {
  729. $this->error = '2205';
  730. return false;
  731. }
  732. if (empty($this->config['eth_api_url'])) {
  733. $this->error = '2206';
  734. return false;
  735. }
  736. if (empty($this->config['eth_api_key'])) {
  737. $this->error = '2207';
  738. return false;
  739. }
  740. // 获取钱包参数
  741. try {
  742. // 用出账钱包转账
  743. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  744. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  745. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  746. $this->error = '2228';
  747. return false;
  748. }
  749. $amount = floatval($amount*pow(10,18));
  750. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  751. $headers = ["Content-Type" => 'application/json'];
  752. $params = [
  753. "from"=> $otcAddress, // 来源
  754. "to"=> $to, // 收款
  755. "gas"=> '0x'.dechex(90000), // gas量,默认90000
  756. "gasPrice"=> "0x9184e72a000",
  757. "value"=> '0x'.dechex($amount),
  758. ];
  759. $transaction = new Transaction($params);
  760. $transaction->sign($otcAddressPrivate);
  761. $hash = $transaction->hash();
  762. $data = [
  763. "jsonrpc" => "2.0",
  764. "method" => "eth_sendRawTransaction",
  765. "params" => ['0x'.$hash],
  766. "id" => 1
  767. ];
  768. RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data,'hash'=> $hash], 600);
  769. $result = curl_api($url, json_encode($data), $headers);
  770. $result = $result ? json_decode($result, true) : [];
  771. $tradeHash = isset($result['result'])? $result['result'] : '';
  772. if($tradeHash && hexdec($tradeHash) != 0){
  773. return ['txid'=> $tradeHash,'amount'=> $amount];
  774. }else{
  775. $this->error = '2229';
  776. return false;
  777. }
  778. } catch (\Exception $exception) {
  779. $message = $exception->getMessage();
  780. $this->error = $message;
  781. return false;
  782. }
  783. }
  784. /**
  785. * usdt-erc2.0 转账
  786. * @param $to 进账账户
  787. * @param $amount 转账金额
  788. * @param $from 转账账户
  789. * @param $fromPrivate 转账账户私钥
  790. * @throws \Tron\Exceptions\TransactionException
  791. * @throws \Tron\Exceptions\TronErrorException
  792. */
  793. public function usdtErcTransfer($to, $amount, $from = '', $fromPrivate = '')
  794. {
  795. if ($amount <= 0) {
  796. $this->error = '2205';
  797. return false;
  798. }
  799. if (empty($this->config['eth_api_url'])) {
  800. $this->error = '2206';
  801. return false;
  802. }
  803. if (empty($this->config['eth_api_key'])) {
  804. $this->error = '2207';
  805. return false;
  806. }
  807. // 获取钱包参数
  808. try {
  809. // 用出账钱包转账
  810. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  811. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  812. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  813. $this->error = '2228';
  814. return false;
  815. }
  816. $amount = floatval($amount*pow(10,18));
  817. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  818. $headers = ["Content-Type" => 'application/json'];
  819. $sign = $this->getSha3Sign("transferFrom(address,address,uint256)");
  820. $params = [
  821. "from"=> $otcAddress, // 来源
  822. "to"=> $to, // 收款
  823. "gas"=> '0x'.dechex(90000), // gas量,默认90000
  824. "gasPrice"=> "0x9184e72a000",
  825. "value"=> '0x'.dechex($amount),
  826. "data"=> $this->getTransactionSignData($sign, $to, $amount)
  827. ];
  828. // $transaction = new Transaction($params);
  829. // $hash = $transaction->sign($otcAddressPrivate);
  830. $data = [
  831. "jsonrpc" => "2.0",
  832. // "method" => "eth_sendTransaction",
  833. "method" => "eth_sendTransaction",
  834. "params" => $params,
  835. // "params" => ['0x'.$hash],
  836. "id" => 1
  837. ];
  838. RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data], 600);
  839. $result = curl_api($url, json_encode($data), $headers);
  840. $result = $result ? json_decode($result, true) : [];
  841. $tradeHash = isset($result['result'])? $result['result'] : '';
  842. $error = isset($result['error'])? $result['error'] : [];
  843. if($tradeHash && hexdec($tradeHash) != 0){
  844. return ['txid'=> $tradeHash,'amount'=> $amount];
  845. }else{
  846. $this->error = isset($error['message'])? $error['message'] : '2229';
  847. return false;
  848. }
  849. } catch (\Exception $exception) {
  850. $message = $exception->getMessage();
  851. $this->error = $message;
  852. return false;
  853. }
  854. }
  855. /**
  856. * TRC余额
  857. * @param $address
  858. * @return false|float|string
  859. */
  860. public function getErcBalance($address, $cache=false)
  861. {
  862. if (empty($address)) {
  863. $this->error = '1018';
  864. return false;
  865. }
  866. if (empty($this->config['eth_api_url'])) {
  867. $this->error = '2206';
  868. return false;
  869. }
  870. if (empty($this->config['eth_api_key'])) {
  871. $this->error = '2207';
  872. return false;
  873. }
  874. $cacheKey = "caches:wallet:balance:erc_{$address}";
  875. if ($data = RedisService::get($cacheKey) && $cache) {
  876. return $data;
  877. }
  878. if(RedisService::get($cacheKey.'_lock') && $cache){
  879. return false;
  880. }
  881. try {
  882. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  883. $headers = ["Content-Type" => 'application/json'];
  884. $data = [
  885. "jsonrpc" => "2.0",
  886. "method" => "eth_getBalance",
  887. "params" => [$address, "latest"],
  888. "id" => 1
  889. ];
  890. $result = curl_api($url, json_encode($data), $headers);
  891. $result = $result ? json_decode($result, true) : [];
  892. $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
  893. $balance = $balance ? floatval($balance/pow(10,18)) : '0.00';
  894. RedisService::set($cacheKey, $balance, rand(5, 10));
  895. RedisService::set($cacheKey.'_lock', true, rand(5, 10));
  896. return $balance;
  897. } catch (\Exception $exception) {
  898. $this->error = $exception->getMessage();
  899. return false;
  900. }
  901. }
  902. /**
  903. * USDT-ERC20余额
  904. * @param $address
  905. * @return false|float|string
  906. */
  907. public function getErc20Usdt($address, $cache=false)
  908. {
  909. if (empty($address)) {
  910. $this->error = '1018';
  911. return false;
  912. }
  913. if (empty($this->config['eth_api_url'])) {
  914. $this->error = '2206';
  915. return false;
  916. }
  917. if (empty($this->config['eth_api_key'])) {
  918. $this->error = '2207';
  919. return false;
  920. }
  921. if(empty($this->config['erc_contract_address'])){
  922. $this->error = '2228';
  923. return false;
  924. }
  925. $cacheKey = "caches:wallet:balance:erc_usdt_{$address}";
  926. if ($data = RedisService::get($cacheKey) && $cache) {
  927. return $data;
  928. }
  929. if(RedisService::get($cacheKey.'_lock') && $cache){
  930. return false;
  931. }
  932. try {
  933. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  934. $headers = ["Content-Type" => 'application/json'];
  935. $sign = $this->getSha3Sign("balanceOf(address)");
  936. $data = [
  937. "jsonrpc" => "2.0",
  938. "method" => "eth_call",
  939. "params" => [["to"=> $this->config['erc_contract_address'],"data"=> $this->getSignData($sign, $address)], "latest"],
  940. "id" => 1
  941. ];
  942. $result = curl_api($url, json_encode($data), $headers);
  943. $result = $result ? json_decode($result, true) : [];
  944. $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
  945. $balance = $balance? floatval($balance/1000000) : '0.00';
  946. $balance = $balance? $balance : '0.00';
  947. RedisService::set($cacheKey, $balance, rand(5, 10));
  948. RedisService::set($cacheKey.'_lock', true, rand(5, 10));
  949. return $balance;
  950. } catch (\Exception $exception) {
  951. $this->error = $exception->getMessage();
  952. return false;
  953. }
  954. }
  955. /**
  956. * 合约方法签名编号
  957. * @param string $data
  958. * @return string
  959. */
  960. public function getSha3Sign($data)
  961. {
  962. $util = new Util();
  963. $result = $util->sha3($data);
  964. return '0x'.substr($result,0,8);
  965. }
  966. /**
  967. * 获取签名数据
  968. * @param $sign
  969. * @param $address
  970. * @return string
  971. */
  972. public function getSignData($sign, $address)
  973. {
  974. return $sign.str_repeat('0', 24).substr($address,2);
  975. }
  976. /**
  977. * 获取交易签名参数
  978. * @param $sign 调用的合约方法生成的sha3签名编号
  979. * @param $toAddress 收款地址
  980. * @param $amount 转账金额/十进制
  981. * @return string
  982. */
  983. public function getTransactionSignData($sign, $toAddress, $amount)
  984. {
  985. $toAddress = substr($toAddress,2); // 去掉0x
  986. $toAddressSign = str_repeat('0', 64-strlen($toAddress)).$toAddress; // 前面补齐0为64位
  987. $amount = dechex($amount); // 十进制转十六进制
  988. $amountSign = str_repeat('0', 64-strlen($amount)).$amount; // 前面补齐0为64位
  989. return $sign.$toAddressSign.$amountSign;
  990. }
  991. /**
  992. * 获取USDT-ERC2.0交易记录(进出账)
  993. * @param $address 用户钱包地址
  994. * @param int $coinType 币种:1-usdt
  995. * @param int $limit 转账记录数,最新的
  996. * @return array|false
  997. */
  998. public function getErc20TransferLog($address, $type = 1, $limit = 50)
  999. {
  1000. }
  1001. /**
  1002. * usdt-trc2.0 归集
  1003. * @throws \Tron\Exceptions\TransactionException
  1004. * @throws \Tron\Exceptions\TronErrorException
  1005. */
  1006. public function usdtErcTrigger($force = false)
  1007. {
  1008. return false;
  1009. if (empty($this->config['tron_api_url'])) {
  1010. $this->error = '2206';
  1011. return false;
  1012. }
  1013. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  1014. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  1015. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  1016. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  1017. // 获取钱包参数
  1018. try {
  1019. // 用收账钱包归集
  1020. $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
  1021. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
  1022. // 出账手续费钱包
  1023. $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  1024. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  1025. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  1026. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  1027. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
  1028. $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
  1029. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  1030. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  1031. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  1032. $this->error = '2203';
  1033. return false;
  1034. }
  1035. // 出账钱包
  1036. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  1037. $this->error = '2203';
  1038. return false;
  1039. }
  1040. $page = RedisService::get("caches:wallet:transferPage");
  1041. $page = $page ? $page : 1;
  1042. // 归集时间段为凌晨0点-5点
  1043. if ((date('H:i') >= '05:00') && !$force) {
  1044. $this->error = '不在归集时间段';
  1045. return false;
  1046. }
  1047. if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
  1048. $this->error = '不要频繁操作,30秒后重试';
  1049. return false;
  1050. }
  1051. // 上锁
  1052. RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
  1053. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  1054. if (empty($addrList)) {
  1055. RedisService::set("caches:wallet:transferPage", 1, 600);
  1056. $this->error = '1019';
  1057. return false;
  1058. }
  1059. // 平台钱包地址
  1060. $count = 0;
  1061. $failedCount = 0;
  1062. $tron = new Tron();
  1063. $tron->setAddress($otcAddress);
  1064. $otcAddress = $tron->getAddress();
  1065. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  1066. // 平台出账钱包地址
  1067. $tron->setAddress($otcOutAddress);
  1068. $otcOutAddress = $tron->getAddress();
  1069. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  1070. $cacheKey = "caches:wallet:trigger:";
  1071. foreach ($addrList as $v) {
  1072. try {
  1073. // 获取子钱包TRC-USDT余额
  1074. $userId = isset($v['id']) ? $v['id'] : 0;
  1075. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  1076. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  1077. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  1078. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  1079. // 可归集的USDT余额
  1080. $triggerUsdt = $trcWallet->balance($triggerAddress);
  1081. // USDT 余额低于归集金额,则不归集
  1082. if ($triggerUsdt < $triggerMin) {
  1083. $failedCount++;
  1084. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  1085. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1086. continue;
  1087. }
  1088. // 获取子钱包TRX余额
  1089. $triggerTrx = $trxWallet->balance($triggerAddress);
  1090. // 获取平台出账钱包TRX余额
  1091. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  1092. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  1093. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  1094. $failedCount++;
  1095. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  1096. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1097. continue;
  1098. }
  1099. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  1100. if ($triggerTrx < $triggerFree) {
  1101. $failedCount++;
  1102. $result = $this->trxTransfer($address, $triggerFree);
  1103. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  1104. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  1105. continue;
  1106. }
  1107. // 满足归集条件处理
  1108. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  1109. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  1110. $count++;
  1111. } catch (\Exception $exception) {
  1112. $failedCount++;
  1113. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  1114. }
  1115. }
  1116. // 超出分页数,下次处理下一页
  1117. if (count($addrList) >= 200) {
  1118. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  1119. }
  1120. if ($count > 0) {
  1121. return ['success' => $count, 'fail' => $failedCount];
  1122. } else {
  1123. $this->error = 1021;
  1124. return false;
  1125. }
  1126. } catch (\Exception $exception) {
  1127. $this->error = $exception->getMessage();
  1128. return false;
  1129. }
  1130. }
  1131. }