UsdtWalletService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  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. $tron = new Tron();
  242. $tron->setAddress($otcAddress);
  243. $otcAddress = $tron->getAddress();
  244. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  245. // 平台出账钱包地址
  246. $tron->setAddress($otcOutAddress);
  247. $otcOutAddress = $tron->getAddress();
  248. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  249. $cacheKey = "caches:wallet:trigger:";
  250. foreach ($addrList as $v) {
  251. try {
  252. // 获取子钱包TRC-USDT余额
  253. $userId = isset($v['id']) ? $v['id'] : 0;
  254. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  255. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  256. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  257. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  258. // 可归集的USDT余额
  259. $triggerUsdt = $trcWallet->balance($triggerAddress);
  260. // USDT 余额低于归集金额,则不归集
  261. if ($triggerUsdt < $triggerMin) {
  262. $failedCount++;
  263. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  264. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  265. continue;
  266. }
  267. // 获取子钱包TRX余额
  268. $triggerTrx = $trxWallet->balance($triggerAddress);
  269. // 获取平台出账钱包TRX余额
  270. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  271. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  272. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  273. $failedCount++;
  274. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  275. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  276. continue;
  277. }
  278. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  279. if ($triggerTrx < $triggerFree) {
  280. $failedCount++;
  281. $result = $this->trxTransfer($address, $triggerFree);
  282. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  283. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  284. continue;
  285. }
  286. // 满足归集条件处理
  287. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  288. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  289. $count++;
  290. } catch (\Exception $exception) {
  291. $failedCount++;
  292. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  293. }
  294. }
  295. // 超出分页数,下次处理下一页
  296. if (count($addrList) >= 200) {
  297. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  298. }
  299. if ($count > 0) {
  300. return ['success' => $count, 'fail' => $failedCount];
  301. } else {
  302. $this->error = 1021;
  303. return false;
  304. }
  305. } catch (\Exception $exception) {
  306. $this->error = $exception->getMessage();
  307. return false;
  308. }
  309. }
  310. /**
  311. * 监听USDT-TRC2.0转账记录并进账
  312. * @param $userId 用户ID
  313. * @param $address 用户钱包地址
  314. * @param int $coinType 币种:1-usdt
  315. * @param int $limit 转账记录数,最新的
  316. * @return array|false
  317. */
  318. public function getTrc20RechargeLog($userId, $address, $coinType = 1, $limit = 50)
  319. {
  320. if ($userId <= 0 || empty($address)) {
  321. $this->error = '1013';
  322. return false;
  323. }
  324. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  325. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  326. RedisService::set("caches:wallets:recharge_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  327. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  328. $result = $result ? json_decode($result, true) : [];
  329. $datas = isset($result['data']) ? $result['data'] : [];
  330. $status = isset($result['success']) ? $result['success'] : '';
  331. if ($status != true || empty($datas)) {
  332. $this->error = '2207';
  333. return false;
  334. }
  335. $logs = [];
  336. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  337. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  338. foreach ($datas as $v) {
  339. $amount = isset($v['value']) ? intval($v['value']) : 0;
  340. $amount = moneyFormat($amount / 1000000, 6);
  341. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  342. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  343. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  344. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  345. $orderNo = get_order_num('TR');
  346. $log = [
  347. 'user_id' => $userId,
  348. 'change_type' => 1,
  349. 'coin_type' => $coinType,
  350. 'contact_type' => 1,
  351. 'order_no' => $orderNo,
  352. 'from_address' => isset($v['from']) ? $v['from'] : '',
  353. 'to_address' => isset($v['to']) ? $v['to'] : '',
  354. 'txid' => $txid,
  355. 'num' => $amount,
  356. 'balance' => $balance,
  357. 'create_time' => $time ? $time : time(),
  358. 'update_time' => time(),
  359. 'status' => 2,
  360. 'mark' => 1,
  361. ];
  362. if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
  363. $this->memberModel->where(['id' => $userId])->increment('trc_usdt', $amount);
  364. $log['status'] = 1;
  365. $data = [
  366. 'order_no' => $orderNo,
  367. 'user_id' => $userId,
  368. 'type' => 4,
  369. 'pay_type' => 1,
  370. 'trade_type' => 3,
  371. 'change_type' => 1,
  372. 'num' => $amount,
  373. 'total' => 0,
  374. 'balance' => floatval($balance + $amount),
  375. 'create_time' => time(),
  376. 'update_time' => time(),
  377. 'remark' => '存币',
  378. 'status' => 1,
  379. 'mark' => 1,
  380. ];
  381. $this->capitalModel->edit($data);
  382. }
  383. $logs[] = $log;
  384. $this->coinModel->insert($log);
  385. }
  386. }
  387. return $logs;
  388. }
  389. /**
  390. * 获取USDT-TRC2.0交易记录(进出账)
  391. * @param $address 用户钱包地址
  392. * @param int $coinType 币种:1-usdt
  393. * @param int $limit 转账记录数,最新的
  394. * @return array|false
  395. */
  396. public function getTrc20TransferLog($address, $type = 1, $limit = 50)
  397. {
  398. if (empty($address)) {
  399. $this->error = '1013';
  400. return false;
  401. }
  402. // 存币
  403. if ($type == 1) {
  404. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  405. } // 提币
  406. else {
  407. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  408. }
  409. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  410. RedisService::set("caches:wallets:transfer_temp_otc_{$type}", ['url' => $this->config['tron_api_url'] . $url], 600);
  411. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  412. $result = $result ? json_decode($result, true) : [];
  413. $datas = isset($result['data']) ? $result['data'] : [];
  414. $status = isset($result['success']) ? $result['success'] : '';
  415. if ($status != true || empty($datas)) {
  416. $this->error = '2207';
  417. return false;
  418. }
  419. if ($datas) {
  420. foreach ($datas as &$item) {
  421. $time = ($item['block_timestamp'] / 1000);
  422. $item['time_text'] = $time ? datetime($time, 'm-d H:i') : '';
  423. $item['num'] = floatval($item['value'] / 1000000);
  424. $item['contact_type'] = 1;
  425. $item['change_type'] = $type;
  426. $item['status'] = 1;
  427. }
  428. }
  429. return $datas;
  430. }
  431. /**
  432. * 监听USDT-TRC2.0提币记录并进账(平台钱包)
  433. * @param $address 用户钱包地址
  434. * @param int $limit 转账记录数,最新的
  435. * @return array|false
  436. */
  437. public function getTrc20TransferLogByOtc($address, $limit = 50)
  438. {
  439. if (empty($address)) {
  440. $this->error = '1013';
  441. return false;
  442. }
  443. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  444. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  445. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  446. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  447. $result = $result ? json_decode($result, true) : [];
  448. $datas = isset($result['data']) ? $result['data'] : [];
  449. $status = isset($result['success']) ? $result['success'] : '';
  450. if ($status != true || empty($datas)) {
  451. $this->error = '2207';
  452. return false;
  453. }
  454. $logs = [];
  455. foreach ($datas as $v) {
  456. $amount = isset($v['value']) ? intval($v['value']) : 0;
  457. $amount = moneyFormat($amount / 1000000, 6);
  458. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  459. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  460. if ($time > time() - 12 * 3600) {
  461. // 有记录,且是用户提币
  462. $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
  463. $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
  464. if ($coinInfo && $userId && $coinInfo['status'] == 4) {
  465. // 直接更新提币状态
  466. CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['status' => 1, 'update_time' => time()]);
  467. // 明细处理
  468. $num = floatval($coinInfo['num'] + $coinInfo['free']);
  469. $data = [
  470. 'order_no' => $coinInfo['order_no'],
  471. 'user_id' => $userId,
  472. 'type' => 5,
  473. 'pay_type' => 1,
  474. 'trade_type' => 3,
  475. 'change_type' => 2,
  476. 'num' => $num,
  477. 'total' => 0,
  478. 'balance' => floatval($coinInfo['balance'] - $num),
  479. 'create_time' => time(),
  480. 'update_time' => time(),
  481. 'remark' => '提币',
  482. 'status' => 1,
  483. 'mark' => 1,
  484. ];
  485. $this->capitalModel->edit($data);
  486. $logs[] = ['log' => $v, 'order' => $coinInfo];
  487. }
  488. }
  489. }
  490. return $logs;
  491. }
  492. /**
  493. * 监听USDT-TRC2.0充值记录并进账(用户子钱包)
  494. * @param $userId 用户ID
  495. * @param $address 用户钱包地址
  496. * @param int $coinType 币种:1-usdt
  497. * @param int $limit 转账记录数,最新的
  498. * @return array|false
  499. */
  500. public function getTrc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
  501. {
  502. if ($userId <= 0 || empty($address)) {
  503. $this->error = '1013';
  504. return false;
  505. }
  506. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  507. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  508. RedisService::set("caches:wallets:transfer_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  509. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  510. $result = $result ? json_decode($result, true) : [];
  511. $datas = isset($result['data']) ? $result['data'] : [];
  512. $status = isset($result['success']) ? $result['success'] : '';
  513. if ($status != true || empty($datas)) {
  514. $this->error = '2207';
  515. return false;
  516. }
  517. $logs = [];
  518. $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
  519. $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
  520. foreach ($datas as $v) {
  521. $amount = isset($v['value']) ? intval($v['value']) : 0;
  522. $amount = moneyFormat($amount / 1000000, 6);
  523. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  524. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  525. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  526. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  527. $orderNo = get_order_num('TW');
  528. $log = [
  529. 'user_id' => $userId,
  530. 'change_type' => 2,
  531. 'coin_type' => $coinType,
  532. 'contact_type' => 1,
  533. 'order_no' => $orderNo,
  534. 'from_address' => isset($v['from']) ? $v['from'] : '',
  535. 'to_address' => isset($v['to']) ? $v['to'] : '',
  536. 'txid' => $txid,
  537. 'num' => $amount,
  538. 'balance' => $balance,
  539. 'create_time' => $time ? $time : time(),
  540. 'update_time' => time(),
  541. 'status' => 2,
  542. 'mark' => 1,
  543. ];
  544. if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
  545. $this->memberModel->where(['id' => $userId])->decrement('trc_usdt', $amount);
  546. $log['status'] = 1;
  547. // 明细处理
  548. $data = [
  549. 'order_no' => $orderNo,
  550. 'user_id' => $userId,
  551. 'type' => 5,
  552. 'pay_type' => 1,
  553. 'trade_type' => 3,
  554. 'change_type' => 2,
  555. 'num' => $amount,
  556. 'total' => 0,
  557. 'balance' => floatval($balance - $amount),
  558. 'create_time' => time(),
  559. 'update_time' => time(),
  560. 'remark' => '提币',
  561. 'status' => 1,
  562. 'mark' => 1,
  563. ];
  564. $this->capitalModel->edit($data);
  565. }
  566. $logs[] = $log;
  567. $this->coinModel->insert($log);
  568. }
  569. }
  570. return $logs;
  571. }
  572. /**
  573. * TRX余额
  574. * @param $address
  575. * @return false|float|string
  576. */
  577. public function getTrxBalance($address)
  578. {
  579. $cacheKey = "caches:wallet:balance:{$address}";
  580. if (RedisService::get($cacheKey)) {
  581. return false;
  582. }
  583. if (empty($address)) {
  584. $this->error = '1018';
  585. return false;
  586. }
  587. if (empty($this->config['tron_api_url'])) {
  588. $this->error = '2206';
  589. return false;
  590. }
  591. try {
  592. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  593. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  594. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  595. $tron = new Tron();
  596. $tron->setAddress($address);
  597. $address = $tron->getAddress();
  598. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  599. $result = $trxWallet->balance($address);
  600. return $result ? floatval($result) : '0.00';
  601. } catch (\Exception $exception) {
  602. $this->error = $exception->getMessage();
  603. return false;
  604. }
  605. }
  606. /**
  607. * USDT-TRC20余额
  608. * @param $address
  609. * @return false|float|string
  610. */
  611. public function getTrc20Usdt($address)
  612. {
  613. if (empty($address)) {
  614. $this->error = '1018';
  615. return false;
  616. }
  617. if (empty($this->config['tron_api_url'])) {
  618. $this->error = '2206';
  619. return false;
  620. }
  621. try {
  622. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  623. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  624. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  625. $tron = new Tron();
  626. $tron->setAddress($address);
  627. $address = $tron->getAddress();
  628. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  629. $result = $trxWallet->balance($address);
  630. return $result ? floatval($result) : '0.00';
  631. } catch (\Exception $exception) {
  632. $this->error = $exception->getMessage();
  633. return false;
  634. }
  635. }
  636. /********************** ERC钱包 **************************/
  637. /**
  638. * 获取ERC2.0钱包地址
  639. * @param string $type
  640. * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
  641. */
  642. public function getErcAddress()
  643. {
  644. $random = new Random();
  645. $network = Bitcoin::getNetwork();
  646. $privateKeyFactory = new PrivateKeyFactory();
  647. $privateKey = $privateKeyFactory->generateCompressed($random);
  648. $publicKey = $privateKey->getPublicKey();
  649. // p2pkh 格式的地址
  650. $addressService = new PayToPubKeyHashAddress($publicKey->getPubKeyHash());
  651. // 将生成的钱包保存到数据库中
  652. $wif = $privateKey->toWif($network);
  653. $address = $addressService->getAddress();
  654. return ['wif' => $wif, 'hexAddress' => $this->getHexAddress($address), 'address' => $address];
  655. }
  656. /**
  657. * 获取HASH钱包地址
  658. * @param $address 钱包地址
  659. * @return \BitWasp\Buffertools\BufferInterface
  660. * @throws \BitWasp\Bitcoin\Exceptions\UnrecognizedAddressException
  661. */
  662. public function getHexAddress($address)
  663. {
  664. $data = WitnessProgram::v0((new AddressCreator())->fromString($address)->getHash());
  665. $buffer = $data->getProgram()->getHex();
  666. return $buffer ? '0x' . $buffer : '';
  667. }
  668. /**
  669. * 监听USDT-ERC2.0提币记录并进账(平台钱包)
  670. * @param $address 用户钱包地址
  671. * @param int $limit 转账记录数,最新的
  672. * @return array|false
  673. */
  674. public function getErc20TransferLogByOtc($address, $limit = 50)
  675. {
  676. return false;
  677. if (empty($address)) {
  678. $this->error = '1013';
  679. return false;
  680. }
  681. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  682. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  683. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  684. }
  685. /**
  686. * USDT-ERC20余额
  687. * @param $address
  688. * @return false|float|string
  689. */
  690. public function getErc20Usdt($address)
  691. {
  692. $cacheKey = "caches:wallet:balance:{$address}";
  693. if (RedisService::get($cacheKey)) {
  694. return false;
  695. }
  696. if (empty($address)) {
  697. $this->error = '1018';
  698. return false;
  699. }
  700. try {
  701. return '0.00';
  702. } catch (\Exception $exception) {
  703. $this->error = $exception->getMessage();
  704. return false;
  705. }
  706. }
  707. /**
  708. * 获取USDT-ERC2.0交易记录(进出账)
  709. * @param $address 用户钱包地址
  710. * @param int $coinType 币种:1-usdt
  711. * @param int $limit 转账记录数,最新的
  712. * @return array|false
  713. */
  714. public function getErc20TransferLog($address, $type = 1, $limit = 50)
  715. {
  716. }
  717. }