UsdtWalletService.php 32 KB

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