UsdtWalletService_back.php 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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\PrivateKeyFactory;
  22. use BitWasp\Bitcoin\Script\WitnessProgram;
  23. use GuzzleHttp\Client;
  24. use IEXBase\TronAPI\Tron;
  25. use Tron\Api;
  26. use Tron\TRC20;
  27. use Tron\TRX;
  28. use Web3p\EthereumTx\Transaction;
  29. use Web3p\EthereumUtil\Util;
  30. /**
  31. * USDT链管理-服务类
  32. * Class UsdtWalletService
  33. * @package App\Services
  34. */
  35. class UsdtWalletService_back extends BaseService
  36. {
  37. protected $apiUrl = '';
  38. protected $config = [];
  39. // 静态对象
  40. protected static $instance = null;
  41. protected $apiUrls = [
  42. 'usdt_trx2_transfer_log' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&only_confirmed=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  43. 'usdt_trx2_transfer_logs' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  44. 'erc_balance' => '/ethereum/%s/dashboards/address/%s',
  45. 'erc20_balance' => '/ethereum/erc-20/%s/dashboards/address/%s',
  46. 'erc_transaction'=> '/raw/transaction/',
  47. 'erc20_transaction'=> '//raw/transaction/',
  48. 'erc_push_transaction'=> '/push/transaction/',
  49. ];
  50. /**
  51. * 构造函数
  52. * UsdtWalletService constructor.
  53. */
  54. public function __construct()
  55. {
  56. $this->memberModel = new MemberModel();
  57. $this->coinModel = new CoinLogModel();
  58. $this->capitalModel = new CapitalLogModel();
  59. $this->config = ConfigService::make()->getConfigOptionByGroup(4);
  60. if (empty($this->config)) {
  61. return false;
  62. }
  63. }
  64. /**
  65. * 静态入口
  66. * @return static|null
  67. */
  68. public static function make()
  69. {
  70. if (!self::$instance) {
  71. self::$instance = (new UsdtWalletService());
  72. }
  73. return self::$instance;
  74. }
  75. /**
  76. * 获取TRC2.0钱包地址
  77. * @throws \Tron\Exceptions\TronErrorException
  78. */
  79. public function getTrxAddress()
  80. {
  81. try {
  82. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  83. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
  84. $trxWallet = new TRX($api);
  85. $addressData = $trxWallet->generateAddress();
  86. $addressData = (array)$addressData;
  87. return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
  88. } catch (\Exception $exception) {
  89. $this->error = $exception->getMessage();
  90. return false;
  91. }
  92. }
  93. /**
  94. * trx 转账
  95. * @param $to 进账账户
  96. * @param $amount 转账金额
  97. * @throws \Tron\Exceptions\TransactionException
  98. * @throws \Tron\Exceptions\TronErrorException
  99. */
  100. public function trxTransfer($to, $amount, $from = '')
  101. {
  102. if ($amount <= 0) {
  103. $this->error = '2205';
  104. return false;
  105. }
  106. if (empty($this->config['tron_api_url'])) {
  107. $this->error = '2206';
  108. return false;
  109. }
  110. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  111. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  112. $trxWallet = new TRX($api);
  113. // 获取钱包参数
  114. try {
  115. $otcAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  116. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  117. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  118. $this->error = '2203';
  119. return false;
  120. }
  121. $tron = new Tron();
  122. // 获取平台钱包hex
  123. $tron->setAddress($otcAddress);
  124. $otcAddress = $tron->getAddress();
  125. $tron->setAddress($to);
  126. $toAddress = $tron->getAddress();
  127. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  128. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  129. $result = $trxWallet->transfer($from, $to, $amount);
  130. return $result;
  131. } catch (\Exception $exception) {
  132. $message = $exception->getMessage();
  133. $this->error = $message;
  134. return false;
  135. }
  136. }
  137. /**
  138. * usdt-trc2.0 转账
  139. * @param $to 进账账户
  140. * @param $amount 转账金额
  141. * @param $from 转账账户
  142. * @param $fromPrivate 转账账户私钥
  143. * @throws \Tron\Exceptions\TransactionException
  144. * @throws \Tron\Exceptions\TronErrorException
  145. */
  146. public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivate = '')
  147. {
  148. if ($amount <= 0) {
  149. $this->error = '2205';
  150. return false;
  151. }
  152. if (empty($this->config['tron_api_url'])) {
  153. $this->error = '2206';
  154. return false;
  155. }
  156. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  157. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  158. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  159. // 获取钱包参数
  160. try {
  161. // 用出账钱包转账
  162. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('trc_out_address');
  163. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('trc_out_private_key');
  164. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  165. $this->error = '2203';
  166. return false;
  167. }
  168. $tron = new Tron();
  169. // 获取平台钱包hex
  170. $tron->setAddress($otcAddress);
  171. $otcAddress = $tron->getAddress();
  172. // 获取收款钱包hex
  173. $tron->setAddress($to);
  174. $toAddress = $tron->getAddress();
  175. RedisService::set("caches:wallet:transfer:temp_{$to}",['to'=> $to,'out'=> $otcAddress,'outPrivate'=> $otcAddressPrivate,'amount'=> $amount], 7200);
  176. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  177. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  178. $result = $trxWallet->transfer($from, $to, $amount);
  179. $result = (array)$result;
  180. if(isset($result['txID'])){
  181. return $result;
  182. }
  183. return false;
  184. } catch (\Exception $exception) {
  185. $message = $exception->getMessage();
  186. $this->error = $message;
  187. RedisService::set("caches:wallet:transfer:error_{$toAddress['base58']}", $exception, 600);
  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. $retryCount = 0;
  252. $notBalance = false;
  253. $tron = new Tron();
  254. $tron->setAddress($otcAddress);
  255. $otcAddress = $tron->getAddress();
  256. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  257. // 平台出账钱包地址
  258. $tron->setAddress($otcOutAddress);
  259. $otcOutAddress = $tron->getAddress();
  260. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  261. $cacheKey = "caches:wallet:trigger:";
  262. foreach ($addrList as $v) {
  263. try {
  264. // 获取子钱包TRC-USDT余额
  265. $userId = isset($v['id']) ? $v['id'] : 0;
  266. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  267. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  268. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  269. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  270. // 可归集的USDT余额
  271. $triggerUsdt = $trcWallet->balance($triggerAddress);
  272. // USDT 余额低于归集金额,则不归集
  273. if ($triggerUsdt < $triggerMin) {
  274. $failedCount++;
  275. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  276. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  277. continue;
  278. }
  279. // 获取子钱包TRX余额
  280. $triggerTrx = $trxWallet->balance($triggerAddress);
  281. // 获取平台出账钱包TRX余额
  282. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  283. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  284. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  285. $failedCount++;
  286. $notBalance = true;
  287. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  288. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  289. continue;
  290. }
  291. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  292. if ($triggerTrx < $triggerFree) {
  293. $retryCount++;
  294. $result = $this->trxTransfer($address, $triggerFree);
  295. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  296. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  297. continue;
  298. }
  299. // 满足归集条件处理
  300. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  301. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  302. $count++;
  303. } catch (\Exception $exception) {
  304. $failedCount++;
  305. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  306. }
  307. }
  308. // 超出分页数,下次处理下一页
  309. if (count($addrList) >= 200) {
  310. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  311. }
  312. if ($count > 0) {
  313. $this->error = lang(2225, ['success' => $count, 'fail' => $failedCount, 'retry' => $retryCount]);
  314. return ['success' => $count, 'fail' => $failedCount, 'retryCount' => $retryCount];
  315. } else if ($failedCount == count($addrList)) {
  316. $this->error = 2221;
  317. return false;
  318. } else if ($retryCount) {
  319. $this->error = lang(2222, ['num' => $retryCount]);
  320. return false;
  321. } else if ($notBalance) {
  322. $this->error = 2221;
  323. return false;
  324. } else {
  325. $this->error = lang(2224, ['num' => $failedCount]);
  326. return false;
  327. }
  328. } catch (\Exception $exception) {
  329. $this->error = $exception->getMessage();
  330. return false;
  331. }
  332. }
  333. /**
  334. * 监听USDT-TRC2.0转账记录并进账
  335. * @param $userId 用户ID
  336. * @param $address 用户钱包地址
  337. * @param int $coinType 币种:1-usdt
  338. * @param int $limit 转账记录数,最新的
  339. * @return array|false
  340. */
  341. public function getTrc20RechargeLog($userId, $address, $coinType = 1, $limit = 50)
  342. {
  343. if ($userId <= 0 || empty($address)) {
  344. $this->error = '1013';
  345. return false;
  346. }
  347. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  348. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  349. RedisService::set("caches:wallets:recharge_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  350. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  351. $result = $result ? json_decode($result, true) : [];
  352. $datas = isset($result['data']) ? $result['data'] : [];
  353. $status = isset($result['success']) ? $result['success'] : '';
  354. if ($status != true || empty($datas)) {
  355. $this->error = '2207';
  356. return false;
  357. }
  358. $logs = [];
  359. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  360. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  361. foreach ($datas as $v) {
  362. $amount = isset($v['value']) ? intval($v['value']) : 0;
  363. $amount = moneyFormat($amount / 1000000, 6);
  364. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  365. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  366. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  367. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  368. $orderNo = get_order_num('TR');
  369. $log = [
  370. 'user_id' => $userId,
  371. 'change_type' => 1,
  372. 'coin_type' => $coinType,
  373. 'contact_type' => 1,
  374. 'order_no' => $orderNo,
  375. 'from_address' => isset($v['from']) ? $v['from'] : '',
  376. 'to_address' => isset($v['to']) ? $v['to'] : '',
  377. 'txid' => $txid,
  378. 'num' => $amount,
  379. 'balance' => $balance,
  380. 'create_time' => $time ? $time : time(),
  381. 'update_time' => time(),
  382. 'status' => 2,
  383. 'mark' => 1,
  384. ];
  385. if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
  386. $this->memberModel->where(['id' => $userId])->increment('trc_usdt', $amount);
  387. $log['status'] = 1;
  388. $data = [
  389. 'order_no' => $orderNo,
  390. 'user_id' => $userId,
  391. 'type' => 4,
  392. 'pay_type' => 1,
  393. 'trade_type' => 3,
  394. 'change_type' => 1,
  395. 'num' => $amount,
  396. 'total' => 0,
  397. 'balance' => floatval($balance + $amount),
  398. 'create_time' => time(),
  399. 'update_time' => time(),
  400. 'remark' => '存币',
  401. 'status' => 1,
  402. 'mark' => 1,
  403. ];
  404. $this->capitalModel->edit($data);
  405. }
  406. $logs[] = $log;
  407. $this->coinModel->insert($log);
  408. }
  409. }
  410. return $logs;
  411. }
  412. /**
  413. * 获取USDT-TRC2.0交易记录(进出账)
  414. * @param $address 用户钱包地址
  415. * @param int $coinType 币种:1-usdt
  416. * @param int $limit 转账记录数,最新的
  417. * @return array|false
  418. */
  419. public function getTrc20TransferLog($address, $type = 1, $limit = 50)
  420. {
  421. if (empty($address)) {
  422. $this->error = '1013';
  423. return false;
  424. }
  425. // 存币
  426. if ($type == 1) {
  427. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  428. } // 提币
  429. else {
  430. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  431. }
  432. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  433. RedisService::set("caches:wallets:transfer_temp_otc_{$type}", ['url' => $this->config['tron_api_url'] . $url], 600);
  434. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  435. $result = $result ? json_decode($result, true) : [];
  436. $datas = isset($result['data']) ? $result['data'] : [];
  437. $status = isset($result['success']) ? $result['success'] : '';
  438. if ($status != true || empty($datas)) {
  439. $this->error = '2207';
  440. return false;
  441. }
  442. if ($datas) {
  443. foreach ($datas as &$item) {
  444. $time = ($item['block_timestamp'] / 1000);
  445. $item['time_text'] = $time ? datetime($time, 'm-d H:i') : '';
  446. $item['num'] = floatval($item['value'] / 1000000);
  447. $item['contact_type'] = 1;
  448. $item['change_type'] = $type;
  449. $item['status'] = 1;
  450. }
  451. }
  452. return $datas;
  453. }
  454. /**
  455. * 监听USDT-TRC2.0提币记录并进账(平台钱包)
  456. * @param $address 用户钱包地址
  457. * @param int $limit 转账记录数,最新的
  458. * @return array|false
  459. */
  460. public function getTrc20TransferLogByOtc($address, $limit = 50)
  461. {
  462. if (empty($address)) {
  463. $this->error = '1013';
  464. return false;
  465. }
  466. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  467. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  468. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  469. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  470. $result = $result ? json_decode($result, true) : [];
  471. $datas = isset($result['data']) ? $result['data'] : [];
  472. $status = isset($result['success']) ? $result['success'] : '';
  473. if ($status != true || empty($datas)) {
  474. $this->error = '2207';
  475. return false;
  476. }
  477. $logs = [];
  478. foreach ($datas as $v) {
  479. $amount = isset($v['value']) ? intval($v['value']) : 0;
  480. $amount = moneyFormat($amount / 1000000, 6);
  481. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  482. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  483. if ($time > time() - 12 * 3600) {
  484. // 有记录,且是用户提币
  485. $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
  486. $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
  487. if ($coinInfo && $userId && $coinInfo['status'] == 4) {
  488. // 直接更新提币状态
  489. CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['status' => 1, 'update_time' => time()]);
  490. // 明细处理
  491. $num = floatval($coinInfo['num'] + $coinInfo['free']);
  492. $data = [
  493. 'order_no' => $coinInfo['order_no'],
  494. 'user_id' => $userId,
  495. 'type' => 5,
  496. 'pay_type' => 1,
  497. 'trade_type' => 3,
  498. 'change_type' => 2,
  499. 'num' => $num,
  500. 'total' => 0,
  501. 'balance' => floatval($coinInfo['balance'] - $num),
  502. 'create_time' => time(),
  503. 'update_time' => time(),
  504. 'remark' => '提币',
  505. 'status' => 1,
  506. 'mark' => 1,
  507. ];
  508. $this->capitalModel->edit($data);
  509. $logs[] = ['log' => $v, 'order' => $coinInfo];
  510. }
  511. }
  512. }
  513. return $logs;
  514. }
  515. /**
  516. * 监听USDT-TRC2.0充值记录并进账(用户子钱包)
  517. * @param $userId 用户ID
  518. * @param $address 用户钱包地址
  519. * @param int $coinType 币种:1-usdt
  520. * @param int $limit 转账记录数,最新的
  521. * @return array|false
  522. */
  523. public function getTrc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
  524. {
  525. if ($userId <= 0 || empty($address)) {
  526. $this->error = '1013';
  527. return false;
  528. }
  529. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  530. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  531. RedisService::set("caches:wallets:transfer_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  532. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  533. $result = $result ? json_decode($result, true) : [];
  534. $datas = isset($result['data']) ? $result['data'] : [];
  535. $status = isset($result['success']) ? $result['success'] : '';
  536. if ($status != true || empty($datas)) {
  537. $this->error = '2207';
  538. return false;
  539. }
  540. $logs = [];
  541. $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
  542. $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
  543. foreach ($datas as $v) {
  544. $amount = isset($v['value']) ? intval($v['value']) : 0;
  545. $amount = moneyFormat($amount / 1000000, 6);
  546. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  547. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  548. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  549. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  550. $orderNo = get_order_num('TW');
  551. $log = [
  552. 'user_id' => $userId,
  553. 'change_type' => 2,
  554. 'coin_type' => $coinType,
  555. 'contact_type' => 1,
  556. 'order_no' => $orderNo,
  557. 'from_address' => isset($v['from']) ? $v['from'] : '',
  558. 'to_address' => isset($v['to']) ? $v['to'] : '',
  559. 'txid' => $txid,
  560. 'num' => $amount,
  561. 'balance' => $balance,
  562. 'create_time' => $time ? $time : time(),
  563. 'update_time' => time(),
  564. 'status' => 2,
  565. 'mark' => 1,
  566. ];
  567. if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
  568. $this->memberModel->where(['id' => $userId])->decrement('trc_usdt', $amount);
  569. $log['status'] = 1;
  570. // 明细处理
  571. $data = [
  572. 'order_no' => $orderNo,
  573. 'user_id' => $userId,
  574. 'type' => 5,
  575. 'pay_type' => 1,
  576. 'trade_type' => 3,
  577. 'change_type' => 2,
  578. 'num' => $amount,
  579. 'total' => 0,
  580. 'balance' => floatval($balance - $amount),
  581. 'create_time' => time(),
  582. 'update_time' => time(),
  583. 'remark' => '提币',
  584. 'status' => 1,
  585. 'mark' => 1,
  586. ];
  587. $this->capitalModel->edit($data);
  588. }
  589. $logs[] = $log;
  590. $this->coinModel->insert($log);
  591. }
  592. }
  593. return $logs;
  594. }
  595. /**
  596. * TRX余额
  597. * @param $address
  598. * @return false|float|string
  599. */
  600. public function getTrxBalance($address, $cache=false)
  601. {
  602. if (empty($address)) {
  603. $this->error = '1018';
  604. return false;
  605. }
  606. if (empty($this->config['tron_api_url'])) {
  607. $this->error = '2206';
  608. return false;
  609. }
  610. $cacheKey = "caches:wallet:balance:trx_{$address}";
  611. if ($data = RedisService::get($cacheKey) && $cache) {
  612. return $data;
  613. }
  614. if(RedisService::get($cacheKey.'_lock') && $cache){
  615. return false;
  616. }
  617. try {
  618. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  619. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  620. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  621. $tron = new Tron();
  622. $tron->setAddress($address);
  623. $address = $tron->getAddress();
  624. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  625. $result = $trxWallet->balance($address);
  626. $result = $result ? floatval($result) : '0.00';
  627. RedisService::set($cacheKey, $result, rand(5, 10));
  628. RedisService::set($cacheKey.'_lock', true, rand(10, 20));
  629. return $result;
  630. } catch (\Exception $exception) {
  631. $this->error = $exception->getMessage();
  632. return false;
  633. }
  634. }
  635. /**
  636. * USDT-TRC20余额
  637. * @param $address
  638. * @return false|float|string
  639. */
  640. public function getTrc20Usdt($address, $cache=false)
  641. {
  642. if (empty($address)) {
  643. $this->error = '1018';
  644. return false;
  645. }
  646. if (empty($this->config['tron_api_url'])) {
  647. $this->error = '2206';
  648. return false;
  649. }
  650. $cacheKey = "caches:wallet:balance:usdt_{$address}";
  651. if ($data = RedisService::get($cacheKey) && $cache) {
  652. return $data;
  653. }
  654. if(RedisService::get($cacheKey.'_lock') && $cache){
  655. return false;
  656. }
  657. try {
  658. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  659. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  660. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  661. $tron = new Tron();
  662. $tron->setAddress($address);
  663. $address = $tron->getAddress();
  664. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  665. $result = $trxWallet->balance($address);
  666. $result = $result ? floatval($result) : '0.00';
  667. RedisService::set($cacheKey, $result, rand(5, 10));
  668. RedisService::set($cacheKey.'_lock', true, rand(10, 20));
  669. return $result;
  670. } catch (\Exception $exception) {
  671. $this->error = $exception->getMessage();
  672. return false;
  673. }
  674. }
  675. /********************** ERC钱包 **************************/
  676. /**
  677. * 获取ERC2.0钱包地址
  678. * @param string $type
  679. * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
  680. */
  681. public function getErcAddress()
  682. {
  683. $random = new Random();
  684. $network = Bitcoin::getNetwork();
  685. $privateKeyFactory = new PrivateKeyFactory();
  686. $privateKey = $privateKeyFactory->generateCompressed($random);
  687. $publicKey = $privateKey->getPublicKey();
  688. // p2pkh 格式的地址
  689. $addressService = new PayToPubKeyHashAddress($publicKey->getPubKeyHash());
  690. // 将生成的钱包保存到数据库中
  691. $wif = $privateKey->toWif($network);
  692. $address = $addressService->getAddress();
  693. return ['wif' => $wif, 'hexAddress' => $this->getHexAddress($address), 'address' => $address];
  694. }
  695. /**
  696. * 获取HASH钱包地址
  697. * @param $address 钱包地址
  698. * @return \BitWasp\Buffertools\BufferInterface
  699. * @throws \BitWasp\Bitcoin\Exceptions\UnrecognizedAddressException
  700. */
  701. public function getHexAddress($address)
  702. {
  703. $data = WitnessProgram::v0((new AddressCreator())->fromString($address)->getHash());
  704. $buffer = $data->getProgram()->getHex();
  705. return $buffer ? '0x' . $buffer : '';
  706. }
  707. /**
  708. * 监听USDT-ERC2.0提币记录并进账(平台钱包)
  709. * @param $address 用户钱包地址
  710. * @param int $limit 转账记录数,最新的
  711. * @return array|false
  712. */
  713. public function getErc20TransferLogByOtc($address, $limit = 50)
  714. {
  715. return false;
  716. if (empty($address)) {
  717. $this->error = '1013';
  718. return false;
  719. }
  720. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  721. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  722. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  723. }
  724. /**
  725. * ERC 转账
  726. * @throws \Tron\Exceptions\TransactionException
  727. * @throws \Tron\Exceptions\TronErrorException
  728. */
  729. public function ercTransfer($to, $amount, $from='', $fromPrivate='')
  730. {
  731. if ($amount <= 0) {
  732. $this->error = '2205';
  733. return false;
  734. }
  735. if (empty($this->config['eth_api_url'])) {
  736. $this->error = '2206';
  737. return false;
  738. }
  739. if (empty($this->config['eth_api_key'])) {
  740. $this->error = '2207';
  741. return false;
  742. }
  743. // 获取钱包参数
  744. try {
  745. // 用出账钱包转账
  746. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  747. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  748. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  749. $this->error = '2228';
  750. return false;
  751. }
  752. $amount = floatval($amount*pow(10,18));
  753. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  754. $headers = ["Content-Type" => 'application/json'];
  755. $params = [
  756. "from"=> $otcAddress, // 来源
  757. "to"=> $to, // 收款
  758. "gas"=> '0x'.dechex(90000), // gas量,默认90000
  759. "gasPrice"=> "0x9184e72a000",
  760. "value"=> '0x'.dechex($amount),
  761. "data"=> ''
  762. ];
  763. var_dump($params);
  764. $transaction = new Transaction($params);
  765. $transaction->sign($otcAddressPrivate);
  766. $hash = $transaction->hash();
  767. $data = [
  768. "jsonrpc" => "2.0",
  769. "method" => "eth_sendRawTransaction",
  770. "params" => ['0x'.$hash],
  771. "id" => 1
  772. ];
  773. var_dump($data);
  774. RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data,'hash'=> $hash], 600);
  775. $result = curl_api($url, json_encode($data), $headers);
  776. $result = $result ? json_decode($result, true) : [];
  777. $tradeHash = isset($result['result'])? $result['result'] : '';
  778. if($tradeHash && hexdec($tradeHash) != 0){
  779. return ['txid'=> $tradeHash,'amount'=> $amount];
  780. }else{
  781. $this->error = '2229';
  782. return false;
  783. }
  784. } catch (\Exception $exception) {
  785. $message = $exception->getMessage();
  786. $this->error = $message;
  787. return false;
  788. }
  789. }
  790. /**
  791. * usdt-erc2.0 转账
  792. * @param $to 进账账户
  793. * @param $amount 转账金额
  794. * @param $from 转账账户
  795. * @param $fromPrivate 转账账户私钥
  796. * @throws \Tron\Exceptions\TransactionException
  797. * @throws \Tron\Exceptions\TronErrorException
  798. */
  799. public function usdtErcTransfer($to, $amount, $from = '', $fromPrivate = '')
  800. {
  801. if ($amount <= 0) {
  802. $this->error = '2205';
  803. return false;
  804. }
  805. if (empty($this->config['eth_api_url'])) {
  806. $this->error = '2206';
  807. return false;
  808. }
  809. if (empty($this->config['eth_api_key'])) {
  810. $this->error = '2207';
  811. return false;
  812. }
  813. // 获取钱包参数
  814. try {
  815. // 用出账钱包转账
  816. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  817. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  818. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  819. $this->error = '2228';
  820. return false;
  821. }
  822. $amount = floatval($amount*pow(10,18));
  823. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  824. $headers = ["Content-Type" => 'application/json'];
  825. $sign = $this->getSha3Sign("transfer(address,uint256)");
  826. $params = [
  827. "from"=> $otcAddress, // 来源
  828. "to"=> $to, // 收款
  829. "gas"=> '0x'.dechex(90000), // gas量,默认90000
  830. "gasPrice"=> "0x9184e72a000",
  831. "value"=> '0x'.dechex($amount),
  832. "data"=> $this->getTransactionSignData($sign, $to, $amount)
  833. ];
  834. var_dump($params);
  835. $transaction = new Transaction($params);
  836. $sign = $transaction->sign($otcAddressPrivate);
  837. $hash = $transaction->hash();
  838. var_dump($hash);
  839. $data = [
  840. "jsonrpc" => "2.0",
  841. // "method" => "eth_sendTransaction",
  842. "method" => "eth_call",
  843. // "params" => $params,
  844. "params" => ['0x'.$hash],
  845. "id" => 1
  846. ];
  847. RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data], 600);
  848. $result = curl_api($url, json_encode($data), $headers);
  849. $result = $result ? json_decode($result, true) : [];
  850. $tradeHash = isset($result['result'])? $result['result'] : '';
  851. $error = isset($result['error'])? $result['error'] : [];
  852. if($tradeHash && hexdec($tradeHash) != 0){
  853. return ['txid'=> $tradeHash,'amount'=> $amount];
  854. }else{
  855. $this->error = isset($error['message'])? $error['message'] : '2229';
  856. return false;
  857. }
  858. } catch (\Exception $exception) {
  859. $message = $exception->getMessage();
  860. $this->error = $message;
  861. return false;
  862. }
  863. }
  864. /**
  865. * TRC余额
  866. * @param $address
  867. * @return false|float|string
  868. */
  869. public function getErcBalance($address, $cache=false)
  870. {
  871. if (empty($address)) {
  872. $this->error = '1018';
  873. return false;
  874. }
  875. if (empty($this->config['eth_api_url'])) {
  876. $this->error = '2206';
  877. return false;
  878. }
  879. if (empty($this->config['eth_api_key'])) {
  880. $this->error = '2207';
  881. return false;
  882. }
  883. $cacheKey = "caches:wallet:balance:erc_{$address}";
  884. if ($data = RedisService::get($cacheKey) && $cache) {
  885. return $data;
  886. }
  887. if(RedisService::get($cacheKey.'_lock') && $cache){
  888. return false;
  889. }
  890. try {
  891. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  892. $headers = ["Content-Type" => 'application/json'];
  893. $data = [
  894. "jsonrpc" => "2.0",
  895. "method" => "eth_getBalance",
  896. "params" => [$address, "latest"],
  897. "id" => 1
  898. ];
  899. $result = curl_api($url, json_encode($data), $headers);
  900. $result = $result ? json_decode($result, true) : [];
  901. $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
  902. $balance = $balance ? floatval($balance/pow(10,18)) : '0.00';
  903. RedisService::set($cacheKey, $balance, rand(5, 10));
  904. RedisService::set($cacheKey.'_lock', true, rand(10, 20));
  905. return $balance;
  906. } catch (\Exception $exception) {
  907. $this->error = $exception->getMessage();
  908. return false;
  909. }
  910. }
  911. /**
  912. * USDT-ERC20余额
  913. * @param $address
  914. * @return false|float|string
  915. */
  916. public function getErc20Usdt($address, $cache=false)
  917. {
  918. if (empty($address)) {
  919. $this->error = '1018';
  920. return false;
  921. }
  922. if (empty($this->config['eth_api_url'])) {
  923. $this->error = '2206';
  924. return false;
  925. }
  926. if (empty($this->config['eth_api_key'])) {
  927. $this->error = '2207';
  928. return false;
  929. }
  930. if(empty($this->config['erc_contract_address'])){
  931. $this->error = '2228';
  932. return false;
  933. }
  934. $cacheKey = "caches:wallet:balance:erc_usdt_{$address}";
  935. if ($data = RedisService::get($cacheKey) && $cache) {
  936. return $data;
  937. }
  938. if(RedisService::get($cacheKey.'_lock') && $cache){
  939. return false;
  940. }
  941. try {
  942. $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
  943. $headers = ["Content-Type" => 'application/json'];
  944. $sign = $this->getSha3Sign("balanceOf(address)");
  945. $data = [
  946. "jsonrpc" => "2.0",
  947. "method" => "eth_call",
  948. "params" => [["to"=> $this->config['erc_contract_address'],"data"=> $this->getSignData($sign, $address)], "latest"],
  949. "id" => 1
  950. ];
  951. $result = curl_api($url, json_encode($data), $headers);
  952. $result = $result ? json_decode($result, true) : [];
  953. $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
  954. $balance = $balance? floatval($balance/1000000) : '0.00';
  955. $balance = $balance? $balance : '0.00';
  956. RedisService::set($cacheKey, $balance, rand(5, 10));
  957. RedisService::set($cacheKey.'_lock', true, rand(10, 20));
  958. return $balance;
  959. } catch (\Exception $exception) {
  960. $this->error = $exception->getMessage();
  961. return false;
  962. }
  963. }
  964. /**
  965. * 合约方法签名编号
  966. * @param string $data
  967. * @return string
  968. */
  969. public function getSha3Sign($data)
  970. {
  971. $util = new Util();
  972. $result = $util->sha3($data);
  973. return '0x'.substr($result,0,8);
  974. }
  975. /**
  976. * 获取签名数据
  977. * @param $sign
  978. * @param $address
  979. * @return string
  980. */
  981. public function getSignData($sign, $address)
  982. {
  983. return $sign.str_repeat('0', 24).substr($address,2);
  984. }
  985. /**
  986. * 获取交易签名参数
  987. * @param $sign 调用的合约方法生成的sha3签名编号
  988. * @param $toAddress 收款地址
  989. * @param $amount 转账金额/十进制
  990. * @return string
  991. */
  992. public function getTransactionSignData($sign, $toAddress, $amount)
  993. {
  994. $toAddress = substr($toAddress,2); // 去掉0x
  995. $toAddressSign = str_repeat('0', 64-strlen($toAddress)).$toAddress; // 前面补齐0为64位
  996. $amount = dechex($amount); // 十进制转十六进制
  997. $amountSign = str_repeat('0', 64-strlen($amount)).$amount; // 前面补齐0为64位
  998. return $sign.$toAddressSign.$amountSign;
  999. }
  1000. /**
  1001. * 获取USDT-ERC2.0交易记录(进出账)
  1002. * @param $address 用户钱包地址
  1003. * @param int $coinType 币种:1-usdt
  1004. * @param int $limit 转账记录数,最新的
  1005. * @return array|false
  1006. */
  1007. public function getErc20TransferLog($address, $type = 1, $limit = 50)
  1008. {
  1009. }
  1010. /**
  1011. * usdt-trc2.0 归集
  1012. * @throws \Tron\Exceptions\TransactionException
  1013. * @throws \Tron\Exceptions\TronErrorException
  1014. */
  1015. public function usdtErcTrigger($force = false)
  1016. {
  1017. return false;
  1018. if (empty($this->config['tron_api_url'])) {
  1019. $this->error = '2206';
  1020. return false;
  1021. }
  1022. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  1023. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  1024. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  1025. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  1026. // 获取钱包参数
  1027. try {
  1028. // 用收账钱包归集
  1029. $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
  1030. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
  1031. // 出账手续费钱包
  1032. $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  1033. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  1034. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  1035. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  1036. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
  1037. $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
  1038. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  1039. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  1040. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  1041. $this->error = '2203';
  1042. return false;
  1043. }
  1044. // 出账钱包
  1045. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  1046. $this->error = '2203';
  1047. return false;
  1048. }
  1049. $page = RedisService::get("caches:wallet:transferPage");
  1050. $page = $page ? $page : 1;
  1051. // 归集时间段为凌晨0点-5点
  1052. if ((date('H:i') >= '05:00') && !$force) {
  1053. $this->error = '不在归集时间段';
  1054. return false;
  1055. }
  1056. if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
  1057. $this->error = '不要频繁操作,30秒后重试';
  1058. return false;
  1059. }
  1060. // 上锁
  1061. RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
  1062. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  1063. if (empty($addrList)) {
  1064. RedisService::set("caches:wallet:transferPage", 1, 600);
  1065. $this->error = '1019';
  1066. return false;
  1067. }
  1068. // 平台钱包地址
  1069. $count = 0;
  1070. $failedCount = 0;
  1071. $tron = new Tron();
  1072. $tron->setAddress($otcAddress);
  1073. $otcAddress = $tron->getAddress();
  1074. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  1075. // 平台出账钱包地址
  1076. $tron->setAddress($otcOutAddress);
  1077. $otcOutAddress = $tron->getAddress();
  1078. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  1079. $cacheKey = "caches:wallet:trigger:";
  1080. foreach ($addrList as $v) {
  1081. try {
  1082. // 获取子钱包TRC-USDT余额
  1083. $userId = isset($v['id']) ? $v['id'] : 0;
  1084. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  1085. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  1086. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  1087. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  1088. // 可归集的USDT余额
  1089. $triggerUsdt = $trcWallet->balance($triggerAddress);
  1090. // USDT 余额低于归集金额,则不归集
  1091. if ($triggerUsdt < $triggerMin) {
  1092. $failedCount++;
  1093. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  1094. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1095. continue;
  1096. }
  1097. // 获取子钱包TRX余额
  1098. $triggerTrx = $trxWallet->balance($triggerAddress);
  1099. // 获取平台出账钱包TRX余额
  1100. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  1101. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  1102. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  1103. $failedCount++;
  1104. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  1105. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1106. continue;
  1107. }
  1108. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  1109. if ($triggerTrx < $triggerFree) {
  1110. $failedCount++;
  1111. $result = $this->trxTransfer($address, $triggerFree);
  1112. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  1113. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  1114. continue;
  1115. }
  1116. // 满足归集条件处理
  1117. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  1118. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  1119. $count++;
  1120. } catch (\Exception $exception) {
  1121. $failedCount++;
  1122. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  1123. }
  1124. }
  1125. // 超出分页数,下次处理下一页
  1126. if (count($addrList) >= 200) {
  1127. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  1128. }
  1129. if ($count > 0) {
  1130. return ['success' => $count, 'fail' => $failedCount];
  1131. } else {
  1132. $this->error = 1021;
  1133. return false;
  1134. }
  1135. } catch (\Exception $exception) {
  1136. $this->error = $exception->getMessage();
  1137. return false;
  1138. }
  1139. }
  1140. }