UsdtWalletService.php 48 KB

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