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