UsdtWalletService.php 49 KB

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