UsdtWalletService.php 40 KB

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