UsdtWalletService.php 32 KB

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