UsdtWalletService.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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\HierarchicalKeyFactory;
  22. use BitWasp\Bitcoin\Key\Factory\PrivateKeyFactory;
  23. use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39Mnemonic;
  24. use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39SeedGenerator;
  25. use BitWasp\Bitcoin\Mnemonic\MnemonicFactory;
  26. use BitWasp\Bitcoin\Script\WitnessProgram;
  27. use GuzzleHttp\Client;
  28. use IEXBase\TronAPI\Tron;
  29. use Tron\Api;
  30. use Tron\TRC20;
  31. use Tron\TRX;
  32. use Web3\Personal;
  33. use Web3\Web3;
  34. use Web3p\EthereumUtil\Util;
  35. /**
  36. * USDT链管理-服务类
  37. * Class UsdtWalletService
  38. * @package App\Services
  39. */
  40. class UsdtWalletService extends BaseService
  41. {
  42. protected $apiUrl = '';
  43. protected $config = [];
  44. protected $apiUrls = [
  45. 'usdt_trx2_transfer_log' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&only_confirmed=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  46. 'usdt_trx2_transfer_logs' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  47. ];
  48. /**
  49. * 构造函数
  50. * UsdtWalletService constructor.
  51. */
  52. public function __construct()
  53. {
  54. $this->memberModel = new MemberModel();
  55. $this->coinModel = new CoinLogModel();
  56. $this->capitalModel = new CapitalLogModel();
  57. $this->config = ConfigService::make()->getConfigOptionByGroup(4);
  58. $this->apiUrl = isset($this->config['usdt_api_url']) ? $this->config['usdt_api_url'] : '';
  59. if (empty($this->config) || empty($this->apiUrl)) {
  60. return false;
  61. }
  62. }
  63. /**
  64. * 静态入口
  65. * @return UsdtWalletService|null
  66. */
  67. public static function make()
  68. {
  69. return parent::make(); // TODO: Change the autogenerated stub
  70. }
  71. /**
  72. * 获取TRC2.0钱包地址
  73. * @throws \Tron\Exceptions\TronErrorException
  74. */
  75. public function getTrxAddress()
  76. {
  77. try {
  78. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  79. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
  80. $trxWallet = new TRX($api);
  81. $addressData = $trxWallet->generateAddress();
  82. $addressData = (array)$addressData;
  83. return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
  84. } catch (\Exception $exception) {
  85. $this->error = $exception->getMessage();
  86. return false;
  87. }
  88. }
  89. /**
  90. * trx 转账
  91. * @param $to 进账账户
  92. * @param $amount 转账金额
  93. * @throws \Tron\Exceptions\TransactionException
  94. * @throws \Tron\Exceptions\TronErrorException
  95. */
  96. public function trxTransfer($to, $amount, $from = '')
  97. {
  98. if ($amount <= 0) {
  99. $this->error = '2205';
  100. return false;
  101. }
  102. if (empty($this->config['tron_api_url'])) {
  103. $this->error = '2206';
  104. return false;
  105. }
  106. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  107. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  108. $trxWallet = new TRX($api);
  109. // 获取钱包参数
  110. try {
  111. $otcAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  112. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  113. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  114. $this->error = '2203';
  115. return false;
  116. }
  117. $tron = new Tron();
  118. // 获取平台钱包hex
  119. $tron->setAddress($otcAddress);
  120. $otcAddress = $tron->getAddress();
  121. $tron->setAddress($to);
  122. $toAddress = $tron->getAddress();
  123. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  124. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  125. $result = $trxWallet->transfer($from, $to, $amount);
  126. return $result;
  127. } catch (\Exception $exception) {
  128. $message = $exception->getMessage();
  129. $this->error = $message;
  130. return false;
  131. }
  132. }
  133. /**
  134. * usdt-trc2.0 转账
  135. * @param $to 进账账户
  136. * @param $amount 转账金额
  137. * @param $from 转账账户
  138. * @param $fromPrivate 转账账户私钥
  139. * @throws \Tron\Exceptions\TransactionException
  140. * @throws \Tron\Exceptions\TronErrorException
  141. */
  142. public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivate = '')
  143. {
  144. if ($amount <= 0) {
  145. $this->error = '2205';
  146. return false;
  147. }
  148. if (empty($this->config['tron_api_url'])) {
  149. $this->error = '2206';
  150. return false;
  151. }
  152. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  153. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  154. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  155. // 获取钱包参数
  156. try {
  157. // 用出账钱包转账
  158. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('trc_out_address');
  159. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('trc_out_private_key');
  160. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  161. $this->error = '2203';
  162. return false;
  163. }
  164. $tron = new Tron();
  165. // 获取平台钱包hex
  166. $tron->setAddress($otcAddress);
  167. $otcAddress = $tron->getAddress();
  168. // 获取收款钱包hex
  169. $tron->setAddress($to);
  170. $toAddress = $tron->getAddress();
  171. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  172. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  173. $result = $trxWallet->transfer($from, $to, $amount);
  174. return $result;
  175. } catch (\Exception $exception) {
  176. $message = $exception->getMessage();
  177. $this->error = $message;
  178. return false;
  179. }
  180. }
  181. /**
  182. * usdt-trc2.0 归集
  183. * @throws \Tron\Exceptions\TransactionException
  184. * @throws \Tron\Exceptions\TronErrorException
  185. */
  186. public function usdtTrcTrigger($force = false)
  187. {
  188. if (empty($this->config['tron_api_url'])) {
  189. $this->error = '2206';
  190. return false;
  191. }
  192. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  193. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  194. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  195. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  196. // 获取钱包参数
  197. try {
  198. // 用收账钱包归集
  199. $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
  200. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
  201. // 出账手续费钱包
  202. $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  203. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  204. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  205. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  206. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
  207. $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
  208. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  209. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  210. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  211. $this->error = '2203';
  212. return false;
  213. }
  214. // 出账钱包
  215. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  216. $this->error = '2203';
  217. return false;
  218. }
  219. $page = RedisService::get("caches:wallet:transferPage");
  220. $page = $page ? $page : 1;
  221. // 归集时间段为凌晨0点-5点
  222. if ((date('H:i') >= '05:00') && !$force) {
  223. $this->error = '不在归集时间段';
  224. return false;
  225. }
  226. if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
  227. $this->error = '不要频繁操作,30秒后重试';
  228. return false;
  229. }
  230. // 上锁
  231. RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
  232. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  233. if (empty($addrList)) {
  234. RedisService::set("caches:wallet:transferPage", 1, 600);
  235. $this->error = '1019';
  236. return false;
  237. }
  238. // 平台钱包地址
  239. $count = 0;
  240. $failedCount = 0;
  241. $retryCount = 0;
  242. $tron = new Tron();
  243. $tron->setAddress($otcAddress);
  244. $otcAddress = $tron->getAddress();
  245. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  246. // 平台出账钱包地址
  247. $tron->setAddress($otcOutAddress);
  248. $otcOutAddress = $tron->getAddress();
  249. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  250. $cacheKey = "caches:wallet:trigger:";
  251. foreach ($addrList as $v) {
  252. try {
  253. // 获取子钱包TRC-USDT余额
  254. $userId = isset($v['id']) ? $v['id'] : 0;
  255. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  256. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  257. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  258. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  259. // 可归集的USDT余额
  260. $triggerUsdt = $trcWallet->balance($triggerAddress);
  261. // USDT 余额低于归集金额,则不归集
  262. if ($triggerUsdt < $triggerMin) {
  263. $failedCount++;
  264. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  265. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  266. continue;
  267. }
  268. // 获取子钱包TRX余额
  269. $triggerTrx = $trxWallet->balance($triggerAddress);
  270. // 获取平台出账钱包TRX余额
  271. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  272. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  273. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  274. $failedCount++;
  275. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  276. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  277. continue;
  278. }
  279. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  280. if ($triggerTrx < $triggerFree) {
  281. $retryCount++;
  282. $result = $this->trxTransfer($address, $triggerFree);
  283. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  284. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  285. continue;
  286. }
  287. // 满足归集条件处理
  288. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  289. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  290. $count++;
  291. } catch (\Exception $exception) {
  292. $failedCount++;
  293. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  294. }
  295. }
  296. // 超出分页数,下次处理下一页
  297. if (count($addrList) >= 200) {
  298. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  299. }
  300. if ($count > 0) {
  301. return ['success' => $count, 'fail' => $failedCount,'retryCount'=>$retryCount];
  302. } else if ($failedCount == count($addrList)){
  303. $this->error = 2221;
  304. return false;
  305. } else if ($retryCount){
  306. $this->error = lang(2222,['num'=> $retryCount]);
  307. return false;
  308. } else {
  309. $this->error = 1021;
  310. return false;
  311. }
  312. } catch (\Exception $exception) {
  313. $this->error = $exception->getMessage();
  314. return false;
  315. }
  316. }
  317. /**
  318. * 监听USDT-TRC2.0转账记录并进账
  319. * @param $userId 用户ID
  320. * @param $address 用户钱包地址
  321. * @param int $coinType 币种:1-usdt
  322. * @param int $limit 转账记录数,最新的
  323. * @return array|false
  324. */
  325. public function getTrc20RechargeLog($userId, $address, $coinType = 1, $limit = 50)
  326. {
  327. if ($userId <= 0 || empty($address)) {
  328. $this->error = '1013';
  329. return false;
  330. }
  331. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  332. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  333. RedisService::set("caches:wallets:recharge_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  334. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  335. $result = $result ? json_decode($result, true) : [];
  336. $datas = isset($result['data']) ? $result['data'] : [];
  337. $status = isset($result['success']) ? $result['success'] : '';
  338. if ($status != true || empty($datas)) {
  339. $this->error = '2207';
  340. return false;
  341. }
  342. $logs = [];
  343. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  344. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  345. foreach ($datas as $v) {
  346. $amount = isset($v['value']) ? intval($v['value']) : 0;
  347. $amount = moneyFormat($amount / 1000000, 6);
  348. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  349. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  350. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  351. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  352. $orderNo = get_order_num('TR');
  353. $log = [
  354. 'user_id' => $userId,
  355. 'change_type' => 1,
  356. 'coin_type' => $coinType,
  357. 'contact_type' => 1,
  358. 'order_no' => $orderNo,
  359. 'from_address' => isset($v['from']) ? $v['from'] : '',
  360. 'to_address' => isset($v['to']) ? $v['to'] : '',
  361. 'txid' => $txid,
  362. 'num' => $amount,
  363. 'balance' => $balance,
  364. 'create_time' => $time ? $time : time(),
  365. 'update_time' => time(),
  366. 'status' => 2,
  367. 'mark' => 1,
  368. ];
  369. if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
  370. $this->memberModel->where(['id' => $userId])->increment('trc_usdt', $amount);
  371. $log['status'] = 1;
  372. $data = [
  373. 'order_no' => $orderNo,
  374. 'user_id' => $userId,
  375. 'type' => 4,
  376. 'pay_type' => 1,
  377. 'trade_type' => 3,
  378. 'change_type' => 1,
  379. 'num' => $amount,
  380. 'total' => 0,
  381. 'balance' => floatval($balance + $amount),
  382. 'create_time' => time(),
  383. 'update_time' => time(),
  384. 'remark' => '存币',
  385. 'status' => 1,
  386. 'mark' => 1,
  387. ];
  388. $this->capitalModel->edit($data);
  389. }
  390. $logs[] = $log;
  391. $this->coinModel->insert($log);
  392. }
  393. }
  394. return $logs;
  395. }
  396. /**
  397. * 获取USDT-TRC2.0交易记录(进出账)
  398. * @param $address 用户钱包地址
  399. * @param int $coinType 币种:1-usdt
  400. * @param int $limit 转账记录数,最新的
  401. * @return array|false
  402. */
  403. public function getTrc20TransferLog($address, $type = 1, $limit = 50)
  404. {
  405. if (empty($address)) {
  406. $this->error = '1013';
  407. return false;
  408. }
  409. // 存币
  410. if ($type == 1) {
  411. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  412. } // 提币
  413. else {
  414. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  415. }
  416. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  417. RedisService::set("caches:wallets:transfer_temp_otc_{$type}", ['url' => $this->config['tron_api_url'] . $url], 600);
  418. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  419. $result = $result ? json_decode($result, true) : [];
  420. $datas = isset($result['data']) ? $result['data'] : [];
  421. $status = isset($result['success']) ? $result['success'] : '';
  422. if ($status != true || empty($datas)) {
  423. $this->error = '2207';
  424. return false;
  425. }
  426. if ($datas) {
  427. foreach ($datas as &$item) {
  428. $time = ($item['block_timestamp'] / 1000);
  429. $item['time_text'] = $time ? datetime($time, 'm-d H:i') : '';
  430. $item['num'] = floatval($item['value'] / 1000000);
  431. $item['contact_type'] = 1;
  432. $item['change_type'] = $type;
  433. $item['status'] = 1;
  434. }
  435. }
  436. return $datas;
  437. }
  438. /**
  439. * 监听USDT-TRC2.0提币记录并进账(平台钱包)
  440. * @param $address 用户钱包地址
  441. * @param int $limit 转账记录数,最新的
  442. * @return array|false
  443. */
  444. public function getTrc20TransferLogByOtc($address, $limit = 50)
  445. {
  446. if (empty($address)) {
  447. $this->error = '1013';
  448. return false;
  449. }
  450. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  451. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  452. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  453. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  454. $result = $result ? json_decode($result, true) : [];
  455. $datas = isset($result['data']) ? $result['data'] : [];
  456. $status = isset($result['success']) ? $result['success'] : '';
  457. if ($status != true || empty($datas)) {
  458. $this->error = '2207';
  459. return false;
  460. }
  461. $logs = [];
  462. foreach ($datas as $v) {
  463. $amount = isset($v['value']) ? intval($v['value']) : 0;
  464. $amount = moneyFormat($amount / 1000000, 6);
  465. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  466. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  467. if ($time > time() - 12 * 3600) {
  468. // 有记录,且是用户提币
  469. $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
  470. $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
  471. if ($coinInfo && $userId && $coinInfo['status'] == 4) {
  472. // 直接更新提币状态
  473. CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['status' => 1, 'update_time' => time()]);
  474. // 明细处理
  475. $num = floatval($coinInfo['num'] + $coinInfo['free']);
  476. $data = [
  477. 'order_no' => $coinInfo['order_no'],
  478. 'user_id' => $userId,
  479. 'type' => 5,
  480. 'pay_type' => 1,
  481. 'trade_type' => 3,
  482. 'change_type' => 2,
  483. 'num' => $num,
  484. 'total' => 0,
  485. 'balance' => floatval($coinInfo['balance'] - $num),
  486. 'create_time' => time(),
  487. 'update_time' => time(),
  488. 'remark' => '提币',
  489. 'status' => 1,
  490. 'mark' => 1,
  491. ];
  492. $this->capitalModel->edit($data);
  493. $logs[] = ['log' => $v, 'order' => $coinInfo];
  494. }
  495. }
  496. }
  497. return $logs;
  498. }
  499. /**
  500. * 监听USDT-TRC2.0充值记录并进账(用户子钱包)
  501. * @param $userId 用户ID
  502. * @param $address 用户钱包地址
  503. * @param int $coinType 币种:1-usdt
  504. * @param int $limit 转账记录数,最新的
  505. * @return array|false
  506. */
  507. public function getTrc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
  508. {
  509. if ($userId <= 0 || empty($address)) {
  510. $this->error = '1013';
  511. return false;
  512. }
  513. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  514. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  515. RedisService::set("caches:wallets:transfer_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  516. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  517. $result = $result ? json_decode($result, true) : [];
  518. $datas = isset($result['data']) ? $result['data'] : [];
  519. $status = isset($result['success']) ? $result['success'] : '';
  520. if ($status != true || empty($datas)) {
  521. $this->error = '2207';
  522. return false;
  523. }
  524. $logs = [];
  525. $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
  526. $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
  527. foreach ($datas as $v) {
  528. $amount = isset($v['value']) ? intval($v['value']) : 0;
  529. $amount = moneyFormat($amount / 1000000, 6);
  530. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  531. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  532. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  533. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  534. $orderNo = get_order_num('TW');
  535. $log = [
  536. 'user_id' => $userId,
  537. 'change_type' => 2,
  538. 'coin_type' => $coinType,
  539. 'contact_type' => 1,
  540. 'order_no' => $orderNo,
  541. 'from_address' => isset($v['from']) ? $v['from'] : '',
  542. 'to_address' => isset($v['to']) ? $v['to'] : '',
  543. 'txid' => $txid,
  544. 'num' => $amount,
  545. 'balance' => $balance,
  546. 'create_time' => $time ? $time : time(),
  547. 'update_time' => time(),
  548. 'status' => 2,
  549. 'mark' => 1,
  550. ];
  551. if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
  552. $this->memberModel->where(['id' => $userId])->decrement('trc_usdt', $amount);
  553. $log['status'] = 1;
  554. // 明细处理
  555. $data = [
  556. 'order_no' => $orderNo,
  557. 'user_id' => $userId,
  558. 'type' => 5,
  559. 'pay_type' => 1,
  560. 'trade_type' => 3,
  561. 'change_type' => 2,
  562. 'num' => $amount,
  563. 'total' => 0,
  564. 'balance' => floatval($balance - $amount),
  565. 'create_time' => time(),
  566. 'update_time' => time(),
  567. 'remark' => '提币',
  568. 'status' => 1,
  569. 'mark' => 1,
  570. ];
  571. $this->capitalModel->edit($data);
  572. }
  573. $logs[] = $log;
  574. $this->coinModel->insert($log);
  575. }
  576. }
  577. return $logs;
  578. }
  579. /**
  580. * TRX余额
  581. * @param $address
  582. * @return false|float|string
  583. */
  584. public function getTrxBalance($address)
  585. {
  586. $cacheKey = "caches:wallet:balance:{$address}";
  587. if (RedisService::get($cacheKey)) {
  588. return false;
  589. }
  590. if (empty($address)) {
  591. $this->error = '1018';
  592. return false;
  593. }
  594. if (empty($this->config['tron_api_url'])) {
  595. $this->error = '2206';
  596. return false;
  597. }
  598. try {
  599. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  600. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  601. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  602. $tron = new Tron();
  603. $tron->setAddress($address);
  604. $address = $tron->getAddress();
  605. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  606. $result = $trxWallet->balance($address);
  607. return $result ? floatval($result) : '0.00';
  608. } catch (\Exception $exception) {
  609. $this->error = $exception->getMessage();
  610. return false;
  611. }
  612. }
  613. /**
  614. * USDT-TRC20余额
  615. * @param $address
  616. * @return false|float|string
  617. */
  618. public function getTrc20Usdt($address)
  619. {
  620. if (empty($address)) {
  621. $this->error = '1018';
  622. return false;
  623. }
  624. if (empty($this->config['tron_api_url'])) {
  625. $this->error = '2206';
  626. return false;
  627. }
  628. try {
  629. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  630. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  631. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  632. $tron = new Tron();
  633. $tron->setAddress($address);
  634. $address = $tron->getAddress();
  635. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  636. $result = $trxWallet->balance($address);
  637. return $result ? floatval($result) : '0.00';
  638. } catch (\Exception $exception) {
  639. $this->error = $exception->getMessage();
  640. return false;
  641. }
  642. }
  643. /********************** ERC钱包 **************************/
  644. /**
  645. * 获取ERC2.0钱包地址
  646. * @param string $type
  647. * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
  648. */
  649. public function getErcAddress()
  650. {
  651. $random = new Random();
  652. $network = Bitcoin::getNetwork();
  653. $privateKeyFactory = new PrivateKeyFactory();
  654. $privateKey = $privateKeyFactory->generateCompressed($random);
  655. $publicKey = $privateKey->getPublicKey();
  656. // p2pkh 格式的地址
  657. $addressService = new PayToPubKeyHashAddress($publicKey->getPubKeyHash());
  658. // 将生成的钱包保存到数据库中
  659. $wif = $privateKey->toWif($network);
  660. $address = $addressService->getAddress();
  661. return ['wif' => $wif, 'hexAddress' => $this->getHexAddress($address), 'address' => $address];
  662. }
  663. /**
  664. * 获取HASH钱包地址
  665. * @param $address 钱包地址
  666. * @return \BitWasp\Buffertools\BufferInterface
  667. * @throws \BitWasp\Bitcoin\Exceptions\UnrecognizedAddressException
  668. */
  669. public function getHexAddress($address)
  670. {
  671. $data = WitnessProgram::v0((new AddressCreator())->fromString($address)->getHash());
  672. $buffer = $data->getProgram()->getHex();
  673. return $buffer ? '0x' . $buffer : '';
  674. }
  675. /**
  676. * 监听USDT-ERC2.0提币记录并进账(平台钱包)
  677. * @param $address 用户钱包地址
  678. * @param int $limit 转账记录数,最新的
  679. * @return array|false
  680. */
  681. public function getErc20TransferLogByOtc($address, $limit = 50)
  682. {
  683. return false;
  684. if (empty($address)) {
  685. $this->error = '1013';
  686. return false;
  687. }
  688. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  689. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  690. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  691. }
  692. /**
  693. * USDT-ERC20余额
  694. * @param $address
  695. * @return false|float|string
  696. */
  697. public function getErc20Usdt($address)
  698. {
  699. $cacheKey = "caches:wallet:balance:{$address}";
  700. if (RedisService::get($cacheKey)) {
  701. return false;
  702. }
  703. if (empty($address)) {
  704. $this->error = '1018';
  705. return false;
  706. }
  707. try {
  708. return '0.00';
  709. } catch (\Exception $exception) {
  710. $this->error = $exception->getMessage();
  711. return false;
  712. }
  713. }
  714. /**
  715. * 获取USDT-ERC2.0交易记录(进出账)
  716. * @param $address 用户钱包地址
  717. * @param int $coinType 币种:1-usdt
  718. * @param int $limit 转账记录数,最新的
  719. * @return array|false
  720. */
  721. public function getErc20TransferLog($address, $type = 1, $limit = 50)
  722. {
  723. }
  724. /**
  725. * usdt-trc2.0 归集
  726. * @throws \Tron\Exceptions\TransactionException
  727. * @throws \Tron\Exceptions\TronErrorException
  728. */
  729. public function usdtErcTrigger($force = false)
  730. {
  731. return false;
  732. if (empty($this->config['tron_api_url'])) {
  733. $this->error = '2206';
  734. return false;
  735. }
  736. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  737. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  738. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  739. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  740. // 获取钱包参数
  741. try {
  742. // 用收账钱包归集
  743. $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
  744. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
  745. // 出账手续费钱包
  746. $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  747. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  748. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  749. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  750. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
  751. $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
  752. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  753. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  754. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  755. $this->error = '2203';
  756. return false;
  757. }
  758. // 出账钱包
  759. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  760. $this->error = '2203';
  761. return false;
  762. }
  763. $page = RedisService::get("caches:wallet:transferPage");
  764. $page = $page ? $page : 1;
  765. // 归集时间段为凌晨0点-5点
  766. if ((date('H:i') >= '05:00') && !$force) {
  767. $this->error = '不在归集时间段';
  768. return false;
  769. }
  770. if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
  771. $this->error = '不要频繁操作,30秒后重试';
  772. return false;
  773. }
  774. // 上锁
  775. RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
  776. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  777. if (empty($addrList)) {
  778. RedisService::set("caches:wallet:transferPage", 1, 600);
  779. $this->error = '1019';
  780. return false;
  781. }
  782. // 平台钱包地址
  783. $count = 0;
  784. $failedCount = 0;
  785. $tron = new Tron();
  786. $tron->setAddress($otcAddress);
  787. $otcAddress = $tron->getAddress();
  788. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  789. // 平台出账钱包地址
  790. $tron->setAddress($otcOutAddress);
  791. $otcOutAddress = $tron->getAddress();
  792. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  793. $cacheKey = "caches:wallet:trigger:";
  794. foreach ($addrList as $v) {
  795. try {
  796. // 获取子钱包TRC-USDT余额
  797. $userId = isset($v['id']) ? $v['id'] : 0;
  798. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  799. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  800. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  801. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  802. // 可归集的USDT余额
  803. $triggerUsdt = $trcWallet->balance($triggerAddress);
  804. // USDT 余额低于归集金额,则不归集
  805. if ($triggerUsdt < $triggerMin) {
  806. $failedCount++;
  807. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  808. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  809. continue;
  810. }
  811. // 获取子钱包TRX余额
  812. $triggerTrx = $trxWallet->balance($triggerAddress);
  813. // 获取平台出账钱包TRX余额
  814. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  815. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  816. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  817. $failedCount++;
  818. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  819. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  820. continue;
  821. }
  822. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  823. if ($triggerTrx < $triggerFree) {
  824. $failedCount++;
  825. $result = $this->trxTransfer($address, $triggerFree);
  826. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  827. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  828. continue;
  829. }
  830. // 满足归集条件处理
  831. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  832. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  833. $count++;
  834. } catch (\Exception $exception) {
  835. $failedCount++;
  836. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  837. }
  838. }
  839. // 超出分页数,下次处理下一页
  840. if (count($addrList) >= 200) {
  841. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  842. }
  843. if ($count > 0) {
  844. return ['success' => $count, 'fail' => $failedCount];
  845. } else {
  846. $this->error = 1021;
  847. return false;
  848. }
  849. } catch (\Exception $exception) {
  850. $this->error = $exception->getMessage();
  851. return false;
  852. }
  853. }
  854. }