UsdtWalletService.php 48 KB

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