UsdtWalletService.php 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681
  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 etherscan\api\Etherscan;
  24. use GuzzleHttp\Client;
  25. use IEXBase\TronAPI\Tron;
  26. use Tron\Api;
  27. use Tron\TRC20;
  28. use Tron\TRX;
  29. use Web3p\EthereumTx\Transaction;
  30. use Web3p\EthereumUtil\Util;
  31. /**
  32. * USDT链管理-服务类
  33. * Class UsdtWalletService
  34. * @package App\Services
  35. */
  36. class UsdtWalletService extends BaseService
  37. {
  38. protected $apiUrl = '';
  39. protected $config = [];
  40. // 静态对象
  41. protected static $instance = null;
  42. protected $apiUrls = [
  43. 'usdt_trx2_transfer_log' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&only_confirmed=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  44. 'usdt_trx2_transfer_logs' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  45. 'erc_balance' => '/api?module=account&action=balance&address=%s&tag=latest&apikey=%s',
  46. 'erc20_balance' => '/api?module=account&action=tokenbalance&contractaddress=%s&address=%s&tag=latest&apikey=%s',
  47. 'erc_transaction' => '/api?module=proxy&action=eth_sendRawTransaction&hex=%s&apikey=%s',
  48. 'erc_transaction_log' => '/api?module=account&action=txlist&address=%s&page=%s&offset=%s&sort=desc&apikey=%s',
  49. 'erc20_transaction_log' => '/api?module=account&action=tokentx&address=%s&page=%s&offset=%s&sort=desc&apikey=%s',
  50. ];
  51. /**
  52. * 构造函数
  53. * UsdtWalletService constructor.
  54. */
  55. public function __construct()
  56. {
  57. $this->memberModel = new MemberModel();
  58. $this->coinModel = new CoinLogModel();
  59. $this->capitalModel = new CapitalLogModel();
  60. $this->config = ConfigService::make()->getConfigOptionByGroup(4);
  61. if (empty($this->config)) {
  62. return false;
  63. }
  64. }
  65. /**
  66. * 静态入口
  67. * @return static|null
  68. */
  69. public static function make()
  70. {
  71. if (!self::$instance) {
  72. self::$instance = (new UsdtWalletService());
  73. }
  74. return self::$instance;
  75. }
  76. /**
  77. * 获取TRC2.0钱包地址
  78. * @throws \Tron\Exceptions\TronErrorException
  79. */
  80. public function getTrxAddress()
  81. {
  82. try {
  83. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  84. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
  85. $trxWallet = new TRX($api);
  86. $addressData = $trxWallet->generateAddress();
  87. $addressData = (array)$addressData;
  88. return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
  89. } catch (\Exception $exception) {
  90. $this->error = $exception->getMessage();
  91. return false;
  92. }
  93. }
  94. /**
  95. * trx 转账
  96. * @param $to 进账账户
  97. * @param $amount 转账金额
  98. * @throws \Tron\Exceptions\TransactionException
  99. * @throws \Tron\Exceptions\TronErrorException
  100. */
  101. public function trxTransfer($to, $amount, $from = '')
  102. {
  103. if ($amount <= 0) {
  104. $this->error = '2205';
  105. return false;
  106. }
  107. if (empty($this->config['tron_api_url'])) {
  108. $this->error = '2206';
  109. return false;
  110. }
  111. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  112. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  113. $trxWallet = new TRX($api);
  114. // 获取钱包参数
  115. try {
  116. $otcAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  117. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  118. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  119. $this->error = '2203';
  120. return false;
  121. }
  122. $tron = new Tron();
  123. // 获取平台钱包hex
  124. $tron->setAddress($otcAddress);
  125. $otcAddress = $tron->getAddress();
  126. $tron->setAddress($to);
  127. $toAddress = $tron->getAddress();
  128. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  129. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  130. $result = $trxWallet->transfer($from, $to, $amount);
  131. return $result;
  132. } catch (\Exception $exception) {
  133. $message = $exception->getMessage();
  134. $this->error = $message;
  135. return false;
  136. }
  137. }
  138. /**
  139. * usdt-trc2.0 转账
  140. * @param $to 进账账户
  141. * @param $amount 转账金额
  142. * @param $from 转账账户
  143. * @param $fromPrivate 转账账户私钥
  144. * @throws \Tron\Exceptions\TransactionException
  145. * @throws \Tron\Exceptions\TronErrorException
  146. */
  147. public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivate = '')
  148. {
  149. if ($amount <= 0) {
  150. $this->error = '2205';
  151. return false;
  152. }
  153. if (empty($this->config['tron_api_url'])) {
  154. $this->error = '2206';
  155. return false;
  156. }
  157. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  158. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  159. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  160. // 获取钱包参数
  161. try {
  162. // 用出账钱包转账
  163. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('trc_out_address');
  164. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('trc_out_private_key');
  165. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  166. $this->error = '2203';
  167. return false;
  168. }
  169. $tron = new Tron();
  170. // 获取平台钱包hex
  171. $tron->setAddress($otcAddress);
  172. $otcAddress = $tron->getAddress();
  173. // 获取收款钱包hex
  174. $tron->setAddress($to);
  175. $toAddress = $tron->getAddress();
  176. RedisService::set("caches:wallet:transfer:temp_{$to}", ['to' => $to, 'out' => $otcAddress, 'outPrivate' => $otcAddressPrivate, 'amount' => $amount], 7200);
  177. $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  178. $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  179. $result = $trxWallet->transfer($from, $to, $amount);
  180. $result = (array)$result;
  181. if (isset($result['txID'])) {
  182. return $result;
  183. }
  184. return false;
  185. } catch (\Exception $exception) {
  186. $message = $exception->getMessage();
  187. $this->error = $message;
  188. RedisService::set("caches:wallet:transfer:error_{$toAddress['base58']}", $exception, 600);
  189. return false;
  190. }
  191. }
  192. /**
  193. * usdt-trc2.0 归集
  194. * @throws \Tron\Exceptions\TransactionException
  195. * @throws \Tron\Exceptions\TronErrorException
  196. */
  197. public function usdtTrcTrigger($force = false)
  198. {
  199. if (empty($this->config['tron_api_url'])) {
  200. $this->error = '2206';
  201. return false;
  202. }
  203. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  204. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  205. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  206. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  207. // 获取钱包参数
  208. try {
  209. // 用收账钱包归集
  210. $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
  211. $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
  212. // 出账手续费钱包
  213. $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
  214. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
  215. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  216. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  217. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_trx_free');
  218. $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
  219. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  220. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  221. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  222. $this->error = '2203';
  223. return false;
  224. }
  225. // 出账钱包
  226. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  227. $this->error = '2203';
  228. return false;
  229. }
  230. $page = RedisService::get("caches:wallet:transferTrxPage");
  231. $page = $page ? $page : 1;
  232. // 归集时间段为凌晨0点-5点
  233. if ((date('H:i') >= '05:00') && !$force) {
  234. $this->error = '不在归集时间段';
  235. return false;
  236. }
  237. if (RedisService::get("caches:wallet:triggerTrxLock:{$page}")) {
  238. $this->error = '不要频繁操作,30秒后重试';
  239. return false;
  240. }
  241. // 上锁
  242. RedisService::set("caches:wallet:triggerTrxLock:{$page}", 1, rand(10, 30));
  243. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  244. if (empty($addrList)) {
  245. RedisService::set("caches:wallet:transferPage", 1, 600);
  246. $this->error = '1019';
  247. return false;
  248. }
  249. // 平台钱包地址
  250. $count = 0;
  251. $failedCount = 0;
  252. $retryCount = 0;
  253. $notBalance = false;
  254. $tron = new Tron();
  255. $tron->setAddress($otcAddress);
  256. $otcAddress = $tron->getAddress();
  257. $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
  258. // 平台出账钱包地址
  259. $tron->setAddress($otcOutAddress);
  260. $otcOutAddress = $tron->getAddress();
  261. $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
  262. $cacheKey = "caches:wallet:triggerTrx:";
  263. foreach ($addrList as $v) {
  264. try {
  265. // 获取子钱包TRC-USDT余额
  266. $userId = isset($v['id']) ? $v['id'] : 0;
  267. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  268. $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  269. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  270. $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
  271. // 可归集的USDT余额
  272. $triggerUsdt = $trcWallet->balance($triggerAddress);
  273. // USDT 余额低于归集金额,则不归集
  274. if ($triggerUsdt < $triggerMin) {
  275. $failedCount++;
  276. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  277. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  278. continue;
  279. }
  280. // 获取子钱包TRX余额
  281. $triggerTrx = $trxWallet->balance($triggerAddress);
  282. // 获取平台出账钱包TRX余额
  283. $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
  284. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  285. if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
  286. $failedCount++;
  287. $notBalance = true;
  288. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
  289. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  290. continue;
  291. }
  292. // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
  293. if ($triggerTrx < $triggerFree) {
  294. $retryCount++;
  295. $result = $this->trxTransfer($address, $triggerFree);
  296. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  297. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  298. continue;
  299. }
  300. // 满足归集条件处理
  301. $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
  302. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  303. $count++;
  304. } catch (\Exception $exception) {
  305. $failedCount++;
  306. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  307. }
  308. }
  309. // 超出分页数,下次处理下一页
  310. if (count($addrList) >= 200) {
  311. RedisService::set("caches:wallet:transferPage", $page + 1, 600);
  312. }
  313. if ($count > 0) {
  314. $this->error = lang(2225, ['success' => $count, 'fail' => $failedCount, 'retry' => $retryCount]);
  315. return ['success' => $count, 'fail' => $failedCount, 'retryCount' => $retryCount];
  316. } else if ($failedCount == count($addrList)) {
  317. $this->error = 2221;
  318. return false;
  319. } else if ($retryCount) {
  320. $this->error = lang(2222, ['num' => $retryCount]);
  321. return false;
  322. } else if ($notBalance) {
  323. $this->error = 2221;
  324. return false;
  325. } else {
  326. $this->error = lang(2224, ['num' => $failedCount]);
  327. return false;
  328. }
  329. } catch (\Exception $exception) {
  330. $this->error = $exception->getMessage();
  331. return false;
  332. }
  333. }
  334. /**
  335. * 监听USDT-TRC2.0用户子钱包充值存币处理
  336. * @param $userId 用户ID
  337. * @param $address 用户钱包地址
  338. * @param int $coinType 币种:1-usdt
  339. * @param int $limit 转账记录数,最新的
  340. * @return array|false
  341. */
  342. public function getTrc20RechargeLog($userId, $address, $coinType = 1, $limit = 100)
  343. {
  344. if ($userId <= 0 || empty($address)) {
  345. $this->error = '1013';
  346. return false;
  347. }
  348. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  349. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  350. RedisService::set("caches:wallets:recharge_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  351. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  352. $result = $result ? json_decode($result, true) : [];
  353. $datas = isset($result['data']) ? $result['data'] : [];
  354. $status = isset($result['success']) ? $result['success'] : '';
  355. if ($status != true || empty($datas)) {
  356. $this->error = '2207';
  357. return false;
  358. }
  359. $logs = [];
  360. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  361. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  362. if ($datas) {
  363. foreach ($datas as $v) {
  364. $amount = isset($v['value']) ? intval($v['value']) : 0;
  365. $amount = moneyFormat($amount / 1000000, 6);
  366. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  367. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  368. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  369. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  370. $orderNo = get_order_num('TR');
  371. $log = [
  372. 'user_id' => $userId,
  373. 'change_type' => 1,
  374. 'coin_type' => $coinType,
  375. 'contact_type' => 1,
  376. 'order_no' => $orderNo,
  377. 'from_address' => isset($v['from']) ? $v['from'] : '',
  378. 'to_address' => isset($v['to']) ? $v['to'] : '',
  379. 'txid' => $txid,
  380. 'num' => $amount,
  381. 'balance' => $balance,
  382. 'create_time' => $time ? $time : time(),
  383. 'update_time' => time(),
  384. 'status' => 2,
  385. 'mark' => 1,
  386. ];
  387. if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
  388. $this->memberModel->where(['id' => $userId])->increment('trc_usdt', $amount);
  389. $log['status'] = 1;
  390. $data = [
  391. 'order_no' => $orderNo,
  392. 'user_id' => $userId,
  393. 'type' => 4,
  394. 'pay_type' => 1,
  395. 'trade_type' => 3,
  396. 'change_type' => 1,
  397. 'num' => $amount,
  398. 'total' => 0,
  399. 'balance' => floatval($balance + $amount),
  400. 'create_time' => time(),
  401. 'update_time' => time(),
  402. 'remark' => '存币',
  403. 'status' => 1,
  404. 'mark' => 1,
  405. ];
  406. $this->capitalModel->edit($data);
  407. }
  408. $logs[] = $log;
  409. $this->coinModel->insert($log);
  410. }
  411. }
  412. }
  413. return $logs;
  414. }
  415. /**
  416. * 获取USDT-TRC2.0交易记录(进出账)
  417. * @param $address 用户钱包地址
  418. * @param int $coinType 币种:1-usdt
  419. * @param int $limit 转账记录数,最新的
  420. * @return array|false
  421. */
  422. public function getTrc20TransferLog($address, $type = 1, $limit = 50)
  423. {
  424. if (empty($address)) {
  425. $this->error = '1013';
  426. return false;
  427. }
  428. // 存币
  429. if ($type == 1) {
  430. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
  431. } // 提币
  432. else {
  433. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  434. }
  435. try {
  436. $cacheKey = "caches:wallets:transfer:trc_{$address}";
  437. if (RedisService::get($cacheKey . '_lock')) {
  438. return false;
  439. }
  440. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  441. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  442. RedisService::set("caches:wallets:transfer_temp_otc_{$type}", ['url' => $this->config['tron_api_url'] . $url], 600);
  443. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  444. $result = $result ? json_decode($result, true) : [];
  445. $datas = isset($result['data']) ? $result['data'] : [];
  446. $status = isset($result['success']) ? $result['success'] : '';
  447. if ($status != true || empty($datas)) {
  448. $this->error = '2207';
  449. return false;
  450. }
  451. return $datas;
  452. } catch (\Exception $exception) {
  453. $message = $exception->getMessage();
  454. $this->error = $message;
  455. return false;
  456. }
  457. }
  458. /**
  459. * 监听USDT-TRC2.0提币记录并进账(平台钱包)
  460. * @param $address 用户钱包地址
  461. * @param int $limit 转账记录数,最新的
  462. * @return array|false
  463. */
  464. public function getTrc20TransferLogByOtc($address, $limit = 50)
  465. {
  466. if (empty($address)) {
  467. $this->error = '1013';
  468. return false;
  469. }
  470. try {
  471. $cacheKey = "caches:wallets:transfer:trc_{$address}";
  472. if (RedisService::get($cacheKey . '_lock')) {
  473. return false;
  474. }
  475. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  476. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  477. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  478. RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
  479. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  480. $result = $result ? json_decode($result, true) : [];
  481. $datas = isset($result['data']) ? $result['data'] : [];
  482. $status = isset($result['success']) ? $result['success'] : '';
  483. if ($status != true || empty($datas)) {
  484. $this->error = '2207';
  485. return false;
  486. }
  487. $results = [
  488. 'logs' => [],
  489. 'trades' => []
  490. ];
  491. foreach ($datas as $v) {
  492. $amount = isset($v['value']) ? intval($v['value']) : 0;
  493. $amount = moneyFormat($amount / 1000000, 6);
  494. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  495. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  496. if ($time > time() - 12 * 3600) {
  497. // 有记录,且是用户提币
  498. $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
  499. $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
  500. if ($coinInfo && $userId && $coinInfo['status'] == 4 && $coinInfo['contact_type'] == 1) {
  501. // 直接更新提币状态
  502. CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['from_address' => $v['from'], 'status' => 1, 'update_time' => time()]);
  503. // 明细处理
  504. $num = floatval($coinInfo['num'] + $coinInfo['free']);
  505. $data = [
  506. 'order_no' => $coinInfo['order_no'],
  507. 'user_id' => $userId,
  508. 'type' => 5,
  509. 'pay_type' => 1,
  510. 'trade_type' => 3,
  511. 'change_type' => 2,
  512. 'num' => $num,
  513. 'total' => 0,
  514. 'balance' => floatval($coinInfo['balance'] - $num),
  515. 'create_time' => time(),
  516. 'update_time' => time(),
  517. 'remark' => '提币:' . $amount,
  518. 'status' => 1,
  519. 'mark' => 1,
  520. ];
  521. $this->capitalModel->edit($data);
  522. $results['trades'][] = ['log' => $v, 'order' => $coinInfo];
  523. } // 其他交易明细
  524. else if ($time > time() - 7 * 12 * 3600 && !$coinInfo) {
  525. $results['logs'][] = [
  526. 'type' => 3,
  527. 'user_id' => 0,
  528. 'from_address' => $v['from'],
  529. 'to_address' => $v['to'],
  530. 'change_type' => $v['from'] == $address ? 2 : 1,
  531. 'coin_type' => 1,
  532. 'contact_type' => 1,
  533. 'order_no' => get_order_num('TC'),
  534. 'txid' => $txid,
  535. 'num' => $amount,
  536. 'free' => 0,
  537. 'balance' => 0,
  538. 'create_time' => time(),
  539. 'update_time' => time(),
  540. 'status' => 1,
  541. 'mark' => 1,
  542. ];
  543. }
  544. }
  545. }
  546. if ($results['logs']) {
  547. $this->coinModel->insertAll($results['logs']);
  548. }
  549. return $results;
  550. } catch (\Exception $exception) {
  551. $message = $exception->getMessage();
  552. $this->error = $message;
  553. return false;
  554. }
  555. }
  556. /**
  557. * 监听USDT-TRC2.0用户子钱包提币处理
  558. * @param $userId 用户ID
  559. * @param $address 用户钱包地址
  560. * @param int $coinType 币种:1-usdt
  561. * @param int $limit 转账记录数,最新的
  562. * @return array|false
  563. */
  564. public function getTrc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
  565. {
  566. if ($userId <= 0 || empty($address)) {
  567. $this->error = '1013';
  568. return false;
  569. }
  570. $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
  571. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  572. RedisService::set("caches:wallets:transfer_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
  573. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
  574. $result = $result ? json_decode($result, true) : [];
  575. $datas = isset($result['data']) ? $result['data'] : [];
  576. $status = isset($result['success']) ? $result['success'] : '';
  577. if ($status != true || empty($datas)) {
  578. $this->error = '2207';
  579. return false;
  580. }
  581. $logs = [];
  582. $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
  583. $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
  584. foreach ($datas as $v) {
  585. $amount = isset($v['value']) ? intval($v['value']) : 0;
  586. $amount = moneyFormat($amount / 1000000, 6);
  587. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  588. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  589. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  590. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  591. $orderNo = get_order_num('TW');
  592. $log = [
  593. 'user_id' => $userId,
  594. 'change_type' => 2,
  595. 'coin_type' => $coinType,
  596. 'contact_type' => 1,
  597. 'order_no' => $orderNo,
  598. 'from_address' => isset($v['from']) ? $v['from'] : '',
  599. 'to_address' => isset($v['to']) ? $v['to'] : '',
  600. 'txid' => $txid,
  601. 'num' => $amount,
  602. 'balance' => $balance,
  603. 'create_time' => $time ? $time : time(),
  604. 'update_time' => time(),
  605. 'status' => 2,
  606. 'mark' => 1,
  607. ];
  608. if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
  609. $this->memberModel->where(['id' => $userId])->decrement('trc_usdt', $amount);
  610. $log['status'] = 1;
  611. // 明细处理
  612. $data = [
  613. 'order_no' => $orderNo,
  614. 'user_id' => $userId,
  615. 'type' => 5,
  616. 'pay_type' => 1,
  617. 'trade_type' => 3,
  618. 'change_type' => 2,
  619. 'num' => $amount,
  620. 'total' => 0,
  621. 'balance' => floatval($balance - $amount),
  622. 'create_time' => time(),
  623. 'update_time' => time(),
  624. 'remark' => '提币',
  625. 'status' => 1,
  626. 'mark' => 1,
  627. ];
  628. $this->capitalModel->edit($data);
  629. }
  630. $logs[] = $log;
  631. $this->coinModel->insert($log);
  632. }
  633. }
  634. return $logs;
  635. }
  636. /**
  637. * TRX余额
  638. * @param $address
  639. * @return false|float|string
  640. */
  641. public function getTrxBalance($address, $cache = false)
  642. {
  643. if (empty($address)) {
  644. $this->error = '1018';
  645. return false;
  646. }
  647. if (empty($this->config['tron_api_url'])) {
  648. $this->error = '2206';
  649. return false;
  650. }
  651. $cacheKey = "caches:wallet:balance:trx_{$address}";
  652. if ($data = RedisService::get($cacheKey) && $cache) {
  653. return $data;
  654. }
  655. if (RedisService::get($cacheKey . '_lock') && $cache) {
  656. return false;
  657. }
  658. try {
  659. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  660. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  661. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  662. $tron = new Tron();
  663. $tron->setAddress($address);
  664. $address = $tron->getAddress();
  665. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  666. $result = $trxWallet->balance($address);
  667. $result = $result ? floatval($result) : '0.00';
  668. RedisService::set($cacheKey, $result, rand(5, 10));
  669. RedisService::set($cacheKey . '_lock', true, rand(10, 20));
  670. return $result;
  671. } catch (\Exception $exception) {
  672. $this->error = $exception->getMessage();
  673. return false;
  674. }
  675. }
  676. /**
  677. * USDT-TRC20余额
  678. * @param $address
  679. * @return false|float|string
  680. */
  681. public function getTrc20Usdt($address, $cache = false)
  682. {
  683. if (empty($address)) {
  684. $this->error = '1018';
  685. return false;
  686. }
  687. if (empty($this->config['tron_api_url'])) {
  688. $this->error = '2206';
  689. return false;
  690. }
  691. $cacheKey = "caches:wallet:balance:usdt_{$address}";
  692. if ($data = RedisService::get($cacheKey) && $cache) {
  693. return $data;
  694. }
  695. if (RedisService::get($cacheKey . '_lock') && $cache) {
  696. return false;
  697. }
  698. try {
  699. $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
  700. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  701. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  702. $tron = new Tron();
  703. $tron->setAddress($address);
  704. $address = $tron->getAddress();
  705. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  706. $result = $trxWallet->balance($address);
  707. $result = $result ? floatval($result) : '0.00';
  708. RedisService::set($cacheKey, $result, rand(5, 10));
  709. RedisService::set($cacheKey . '_lock', true, rand(10, 20));
  710. return $result;
  711. } catch (\Exception $exception) {
  712. $this->error = $exception->getMessage();
  713. return false;
  714. }
  715. }
  716. /********************** ERC钱包 **************************/
  717. /**
  718. * 获取ERC2.0钱包地址
  719. * @param string $type
  720. * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
  721. */
  722. public function getErcAddress()
  723. {
  724. $random = new Random();
  725. $network = Bitcoin::getNetwork();
  726. $privateKeyFactory = new PrivateKeyFactory();
  727. $privateKey = $privateKeyFactory->generateCompressed($random);
  728. $publicKey = $privateKey->getPublicKey();
  729. // p2pkh 格式的地址
  730. $addressService = new PayToPubKeyHashAddress($publicKey->getPubKeyHash());
  731. // 将生成的钱包保存到数据库中
  732. $wif = $privateKey->toWif($network);
  733. $address = $addressService->getAddress();
  734. return ['wif' => $wif, 'hexAddress' => $this->getHexAddress($address), 'address' => $address];
  735. }
  736. /**
  737. * 获取HASH钱包地址
  738. * @param $address 钱包地址
  739. * @return \BitWasp\Buffertools\BufferInterface
  740. * @throws \BitWasp\Bitcoin\Exceptions\UnrecognizedAddressException
  741. */
  742. public function getHexAddress($address)
  743. {
  744. $data = WitnessProgram::v0((new AddressCreator())->fromString($address)->getHash());
  745. $buffer = $data->getProgram()->getHex();
  746. return $buffer ? '0x' . $buffer : '';
  747. }
  748. /**
  749. * TRC余额
  750. * @param $address
  751. * @return false|float|string
  752. */
  753. public function getErcBalance($address, $cache = false)
  754. {
  755. if (empty($address)) {
  756. $this->error = '1018';
  757. return false;
  758. }
  759. if (empty($this->config['eth_api_url'])) {
  760. $this->error = '2206';
  761. return false;
  762. }
  763. if (empty($this->config['eth_api_key'])) {
  764. $this->error = '2207';
  765. return false;
  766. }
  767. $cacheKey = "caches:wallet:balance:erc_{$address}";
  768. if ($data = RedisService::get($cacheKey) && $cache) {
  769. return $data;
  770. }
  771. if (RedisService::get($cacheKey . '_lock') && $cache) {
  772. return false;
  773. }
  774. try {
  775. $api = new Etherscan($this->config['eth_api_key']);
  776. $result = $api->balance($address);
  777. $balance = isset($result['result']) ? floatval($result['result']) : 0.00;
  778. $balance = $balance ? floatval($balance / pow(10, 18)) : '0.00';
  779. RedisService::set($cacheKey, $balance, rand(5, 10));
  780. RedisService::set($cacheKey . '_lock', true, rand(10, 20));
  781. return $balance;
  782. } catch (\Exception $exception) {
  783. $this->error = $exception->getMessage();
  784. return false;
  785. }
  786. }
  787. /**
  788. * USDT-ERC20余额
  789. * @param $address
  790. * @return false|float|string
  791. */
  792. public function getErc20Usdt($address, $cache = false)
  793. {
  794. if (empty($address)) {
  795. $this->error = '1018';
  796. return false;
  797. }
  798. if (empty($this->config['eth_api_url'])) {
  799. $this->error = '2206';
  800. return false;
  801. }
  802. if (empty($this->config['eth_api_key'])) {
  803. $this->error = '2207';
  804. return false;
  805. }
  806. if (empty($this->config['erc_contract_address'])) {
  807. $this->error = '2228';
  808. return false;
  809. }
  810. $cacheKey = "caches:wallet:balance:erc_usdt_{$address}";
  811. if ($data = RedisService::get($cacheKey) && $cache) {
  812. return $data;
  813. }
  814. if (RedisService::get($cacheKey . '_lock') && $cache) {
  815. return false;
  816. }
  817. try {
  818. $api = new Etherscan($this->config['eth_api_key']);
  819. $result = $api->tokenBalance($this->config['erc_contract_address'], $address);
  820. $balance = isset($result['result']) ? floatval($result['result']) : 0.00;
  821. $balance = $balance ? floatval($balance / pow(10, 6)) : '0.00';
  822. RedisService::set($cacheKey, $balance, rand(5, 10));
  823. RedisService::set($cacheKey . '_lock', true, rand(10, 20));
  824. return $balance;
  825. } catch (\Exception $exception) {
  826. $this->error = $exception->getMessage();
  827. return false;
  828. }
  829. }
  830. /**
  831. * ERC 转账
  832. * @param $to
  833. * @param $amount
  834. * @param string $from
  835. * @param string $fromPrivate
  836. * @return array|false
  837. */
  838. public function ercTransfer($to, $amount, $from = '', $fromPrivate = '')
  839. {
  840. if ($amount <= 0) {
  841. $this->error = '2205';
  842. return false;
  843. }
  844. if (empty($this->config['eth_api_url'])) {
  845. $this->error = '2206';
  846. return false;
  847. }
  848. if (empty($this->config['eth_api_key'])) {
  849. $this->error = '2207';
  850. return false;
  851. }
  852. // 获取钱包参数
  853. try {
  854. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  855. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  856. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  857. $this->error = '2228';
  858. return false;
  859. }
  860. $amount = floatval($amount * pow(10, 18));
  861. $params = [
  862. "from" => $otcAddress, // 来源
  863. "to" => $to, // 收款
  864. "gas" => '0x' . dechex(90000), // gas量,默认90000
  865. "gasPrice" => "0x9184e72a000",
  866. "value" => '0x' . dechex($amount),
  867. "data" => ''
  868. ];
  869. $transaction = new Transaction($params);
  870. $transaction->sign($otcAddressPrivate);
  871. $hex = '0x' . $transaction;
  872. $url = sprintf($this->apiUrls['erc_transaction'], $hex, $this->config['eth_api_key']);
  873. $url = $this->config['eth_api_url'] . $url;
  874. RedisService::set("caches:trades:erc:transfer_{$to}", ['url' => $url, 'params' => $params, 'hex' => $hex], 600);
  875. $result = curl_api($url);
  876. $result = $result ? json_decode($result, true) : [];
  877. $tradeHash = isset($result['result']) ? $result['result'] : '';
  878. if ($tradeHash && hexdec($tradeHash) != 0) {
  879. return ['txid' => $tradeHash, 'amount' => $amount];
  880. } else {
  881. $this->error = '2229';
  882. return false;
  883. }
  884. } catch (\Exception $exception) {
  885. $message = $exception->getMessage();
  886. $this->error = $message;
  887. return false;
  888. }
  889. }
  890. /**
  891. * usdt-erc2.0 转账
  892. * @param $to 进账账户
  893. * @param $amount 转账金额
  894. * @param $from 转账账户
  895. * @param $fromPrivate 转账账户私钥
  896. * @throws \Tron\Exceptions\TransactionException
  897. * @throws \Tron\Exceptions\TronErrorException
  898. */
  899. public function usdtErcTransfer($to, $amount, $from = '', $fromPrivate = '')
  900. {
  901. if ($amount <= 0) {
  902. $this->error = '2205';
  903. return false;
  904. }
  905. if (empty($this->config['eth_api_url'])) {
  906. $this->error = '2206';
  907. return false;
  908. }
  909. if (empty($this->config['eth_api_key'])) {
  910. $this->error = '2207';
  911. return false;
  912. }
  913. // 获取钱包参数
  914. try {
  915. // 用出账钱包转账
  916. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  917. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  918. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  919. $this->error = '2228';
  920. return false;
  921. }
  922. $amount = floatval($amount * pow(10, 18));
  923. $sign = $this->getSha3Sign("transfer(address,uint256)");
  924. $params = [
  925. "from" => $otcAddress, // 来源
  926. "to" => $to, // 收款
  927. "gas" => '0x' . dechex(90000), // gas量,默认90000
  928. "gasPrice" => "0x9184e72a000",
  929. "value" => '0x' . dechex($amount),
  930. "data" => $this->getTransactionSignData($sign, $to, $amount)
  931. ];
  932. $transaction = new Transaction($params);
  933. $transaction->sign($otcAddressPrivate);
  934. $hex = '0x' . $transaction;
  935. $url = sprintf($this->apiUrls['erc_transaction'], $hex, $this->config['eth_api_key']);
  936. $url = $this->config['eth_api_url'] . $url;
  937. RedisService::set("caches:trades:erc20:transfer_{$to}", ['url' => $url, 'params' => $params, 'hex' => $hex], 600);
  938. $result = curl_api($url);
  939. $result = $result ? json_decode($result, true) : [];
  940. $tradeHash = isset($result['result']) ? $result['result'] : '';
  941. $error = isset($result['error']) ? $result['error'] : [];
  942. if ($tradeHash && hexdec($tradeHash) != 0) {
  943. return ['txid' => $tradeHash, 'amount' => $amount];
  944. } else {
  945. $this->error = isset($error['message']) ? $error['message'] : '2229';
  946. return false;
  947. }
  948. } catch (\Exception $exception) {
  949. $message = $exception->getMessage();
  950. $this->error = $message;
  951. return false;
  952. }
  953. }
  954. /**
  955. * 合约方法签名编号
  956. * @param string $data
  957. * @return string
  958. */
  959. public function getSha3Sign($data)
  960. {
  961. $util = new Util();
  962. $result = $util->sha3($data);
  963. return '0x' . substr($result, 0, 8);
  964. }
  965. /**
  966. * 获取签名数据
  967. * @param $sign
  968. * @param $address
  969. * @return string
  970. */
  971. public function getSignData($sign, $address)
  972. {
  973. return $sign . str_repeat('0', 24) . substr($address, 2);
  974. }
  975. /**
  976. * 获取交易签名参数
  977. * @param $sign 调用的合约方法生成的sha3签名编号
  978. * @param $toAddress 收款地址
  979. * @param $amount 转账金额/十进制
  980. * @return string
  981. */
  982. public function getTransactionSignData($sign, $toAddress, $amount)
  983. {
  984. $toAddress = substr($toAddress, 2); // 去掉0x
  985. $toAddressSign = str_repeat('0', 64 - strlen($toAddress)) . $toAddress; // 前面补齐0为64位
  986. $amount = dechex($amount); // 十进制转十六进制
  987. $amountSign = str_repeat('0', 64 - strlen($amount)) . $amount; // 前面补齐0为64位
  988. return $sign . $toAddressSign . $amountSign;
  989. }
  990. /**
  991. * 监听USDT-ERC2.0用户子钱包存币处理
  992. * @param $userId 用户ID
  993. * @param $address 用户钱包地址
  994. * @param int $coinType 币种:1-usdt
  995. * @param int $limit 转账记录数,最新的
  996. * @return array|false
  997. */
  998. public function getErc20RechargeLog($userId, $address, $coinType = 1, $limit = 50)
  999. {
  1000. if ($userId <= 0 || empty($address)) {
  1001. $this->error = '1013';
  1002. return false;
  1003. }
  1004. if (empty($this->config['eth_api_url'])) {
  1005. $this->error = '2206';
  1006. return false;
  1007. }
  1008. if (empty($this->config['eth_api_key'])) {
  1009. $this->error = '2207';
  1010. return false;
  1011. }
  1012. try {
  1013. $cacheKey = "caches:wallets:recharge:erc_{$userId}_{$address}";
  1014. if (RedisService::get($cacheKey . '_lock')) {
  1015. return false;
  1016. }
  1017. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1018. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, 1, $limit, $this->config['eth_api_key']);
  1019. $url = $this->config['eth_api_url'] . $url;
  1020. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1021. $result = curl_api($url);
  1022. $result = $result ? json_decode($result, true) : [];
  1023. $status = isset($result['status']) ? $result['status'] : 0;
  1024. $datas = isset($result['result']) ? $result['result'] : [];
  1025. if ($status != 1 || empty($datas)) {
  1026. $this->error = '2207';
  1027. return false;
  1028. }
  1029. $logs = [];
  1030. $coinInMin = ConfigService::make()->getConfigByCode('erc_in_limit');
  1031. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  1032. if ($datas) {
  1033. foreach ($datas as $v) {
  1034. $amount = isset($v['value']) ? intval($v['value']) : 0;
  1035. $amount = moneyFormat($amount / 1000000, 6);
  1036. $time = isset($v['timeStamp']) ? intval($v['timeStamp']) : 0;
  1037. $txid = isset($v['hash']) ? $v['hash'] : '';
  1038. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  1039. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  1040. $orderNo = get_order_num('ER');
  1041. $log = [
  1042. 'type' => 1,
  1043. 'user_id' => $userId,
  1044. 'change_type' => 1,
  1045. 'coin_type' => $coinType,
  1046. 'contact_type' => 2,
  1047. 'order_no' => $orderNo,
  1048. 'from_address' => isset($v['from']) ? $v['from'] : '',
  1049. 'to_address' => isset($v['to']) ? $v['to'] : '',
  1050. 'txid' => $txid,
  1051. 'num' => $amount,
  1052. 'balance' => $balance,
  1053. 'create_time' => $time ? $time : time(),
  1054. 'update_time' => time(),
  1055. 'status' => 2,
  1056. 'mark' => 1,
  1057. ];
  1058. if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
  1059. $this->memberModel->where(['id' => $userId])->increment('erc_usdt', $amount);
  1060. $log['status'] = 1;
  1061. $data = [
  1062. 'order_no' => $orderNo,
  1063. 'user_id' => $userId,
  1064. 'type' => 4,
  1065. 'pay_type' => 1,
  1066. 'trade_type' => 3,
  1067. 'change_type' => 1,
  1068. 'num' => $amount,
  1069. 'total' => 0,
  1070. 'balance' => floatval($balance + $amount),
  1071. 'create_time' => time(),
  1072. 'update_time' => time(),
  1073. 'remark' => '存币:' . $amount,
  1074. 'status' => 1,
  1075. 'mark' => 1,
  1076. ];
  1077. $this->capitalModel->edit($data);
  1078. }
  1079. $logs[] = $log;
  1080. $this->coinModel->insert($log);
  1081. }
  1082. }
  1083. }
  1084. return $datas;
  1085. } catch (\Exception $exception) {
  1086. $message = $exception->getMessage();
  1087. $this->error = $message;
  1088. return false;
  1089. }
  1090. }
  1091. /**
  1092. * 获取USDT-ERC2.0交易记录(进出账)
  1093. * @param $address 用户钱包地址
  1094. * @param int $coinType 币种:1-usdt
  1095. * @param int $limit 转账记录数,最新的
  1096. * @return array|false
  1097. */
  1098. public function getErc20TransferLog($address, $type = 1, $page = 1, $limit = 50)
  1099. {
  1100. if (empty($this->config['eth_api_url'])) {
  1101. $this->error = '2206';
  1102. return false;
  1103. }
  1104. if (empty($this->config['eth_api_key'])) {
  1105. $this->error = '2207';
  1106. return false;
  1107. }
  1108. try {
  1109. $cacheKey = "caches:wallets:transfer:erc_{$address}";
  1110. if (RedisService::get($cacheKey . '_lock')) {
  1111. return false;
  1112. }
  1113. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1114. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, $page, $limit, $this->config['eth_api_key']);
  1115. $url = $this->config['eth_api_url'] . $url;
  1116. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1117. $result = curl_api($url);
  1118. $result = $result ? json_decode($result, true) : [];
  1119. $status = isset($result['status']) ? $result['status'] : 0;
  1120. $datas = isset($result['result']) ? $result['result'] : [];
  1121. if ($status != 1 || empty($datas)) {
  1122. $this->error = '2207';
  1123. return false;
  1124. }
  1125. return $datas;
  1126. } catch (\Exception $exception) {
  1127. $message = $exception->getMessage();
  1128. $this->error = $message;
  1129. return false;
  1130. }
  1131. }
  1132. /**
  1133. * 监听USDT-ERC2.0提币记录并进账(平台钱包)
  1134. * @param $address 用户钱包地址
  1135. * @param int $limit 转账记录数,最新的
  1136. * @return array|false
  1137. */
  1138. public function getErc20TransferLogByOtc($address, $limit = 100)
  1139. {
  1140. if (empty($address)) {
  1141. $this->error = '1013';
  1142. return false;
  1143. }
  1144. if (empty($this->config['eth_api_url'])) {
  1145. $this->error = '2206';
  1146. return false;
  1147. }
  1148. if (empty($this->config['eth_api_key'])) {
  1149. $this->error = '2207';
  1150. return false;
  1151. }
  1152. try {
  1153. $cacheKey = "caches:wallets:transfer:erc_{$address}";
  1154. if (RedisService::get($cacheKey . '_lock')) {
  1155. return false;
  1156. }
  1157. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1158. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, 1, $limit, $this->config['eth_api_key']);
  1159. $url = $this->config['eth_api_url'] . $url;
  1160. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1161. $result = curl_api($url);
  1162. $result = $result ? json_decode($result, true) : [];
  1163. $status = isset($result['status']) ? $result['status'] : 0;
  1164. $datas = isset($result['result']) ? $result['result'] : [];
  1165. if ($status != 1 || empty($datas)) {
  1166. $this->error = '2207';
  1167. return false;
  1168. }
  1169. $results = [
  1170. 'logs' => [],
  1171. 'trades' => [],
  1172. ];
  1173. if ($datas) {
  1174. foreach ($datas as $v) {
  1175. $from = isset($v['from']) ? trim($v['from']) : '';
  1176. $to = isset($v['to']) ? trim($v['to']) : '';
  1177. $amount = isset($v['value']) ? intval($v['value']) : 0;
  1178. $decimal = isset($v['tokenDecimal']) ? intval($v['tokenDecimal']) : 0;
  1179. $decimal = $decimal ? $decimal : 6;
  1180. $amount = moneyFormat($amount / pow(10, $decimal), 6);
  1181. $time = isset($v['timeStamp']) ? intval($v['timeStamp']) : 0;
  1182. $txid = isset($v['hash']) ? $v['hash'] : '';
  1183. if ($time > time() - 12 * 3600 && $from == $address) {
  1184. // 有记录,且是用户提币
  1185. $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
  1186. $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
  1187. if ($coinInfo && $userId && $coinInfo['status'] == 4 && $coinInfo['contact_type'] == 2) {
  1188. // 直接更新提币状态
  1189. CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['status' => 1, 'update_time' => time()]);
  1190. // 明细处理
  1191. $num = floatval($coinInfo['num'] + $coinInfo['free']);
  1192. $data = [
  1193. 'order_no' => $coinInfo['order_no'],
  1194. 'user_id' => $userId,
  1195. 'type' => 5,
  1196. 'pay_type' => 1,
  1197. 'trade_type' => 3,
  1198. 'change_type' => 2,
  1199. 'num' => $num,
  1200. 'total' => 0,
  1201. 'balance' => floatval($coinInfo['balance'] - $num),
  1202. 'create_time' => time(),
  1203. 'update_time' => time(),
  1204. 'remark' => '提币:' . $amount,
  1205. 'status' => 1,
  1206. 'mark' => 1,
  1207. ];
  1208. $this->capitalModel->edit($data);
  1209. $results['trades'][] = ['log' => $v, 'order' => $coinInfo];
  1210. }
  1211. } // 其他交易明细
  1212. else if ($time > time() - 7 * 12 * 3600 && !$coinInfo) {
  1213. $results['logs'][] = [
  1214. 'type' => 3,
  1215. 'user_id' => 0,
  1216. 'from_address' => $from,
  1217. 'to_address' => $to,
  1218. 'change_type' => $from == $address ? 2 : 1,
  1219. 'coin_type' => 1,
  1220. 'contact_type' => 2,
  1221. 'order_no' => get_order_num('TC'),
  1222. 'txid' => $txid,
  1223. 'num' => $amount,
  1224. 'free' => 0,
  1225. 'balance' => 0,
  1226. 'create_time' => time(),
  1227. 'update_time' => time(),
  1228. 'status' => 1,
  1229. 'mark' => 1,
  1230. ];
  1231. }
  1232. }
  1233. }
  1234. if ($results['logs']) {
  1235. $this->coinModel->insertAll($results['logs']);
  1236. }
  1237. return $results;
  1238. } catch (\Exception $exception) {
  1239. $message = $exception->getMessage();
  1240. $this->error = $message;
  1241. return false;
  1242. }
  1243. }
  1244. /**
  1245. * USDT-ERC20 用户子钱包提币处理
  1246. * @param $userId
  1247. * @param $address
  1248. * @param int $coinType
  1249. * @param int $limit
  1250. * @return false
  1251. */
  1252. public function getErc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
  1253. {
  1254. if (empty($address)) {
  1255. $this->error = '1013';
  1256. return false;
  1257. }
  1258. if (empty($this->config['eth_api_url'])) {
  1259. $this->error = '2206';
  1260. return false;
  1261. }
  1262. if (empty($this->config['eth_api_key'])) {
  1263. $this->error = '2207';
  1264. return false;
  1265. }
  1266. try {
  1267. $cacheKey = "caches:wallets:transfer:erc_{$address}";
  1268. if (RedisService::get($cacheKey . '_lock')) {
  1269. return false;
  1270. }
  1271. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1272. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, 1, $limit, $this->config['eth_api_key']);
  1273. $url = $this->config['eth_api_url'] . $url;
  1274. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1275. $result = curl_api($url);
  1276. $result = $result ? json_decode($result, true) : [];
  1277. $status = isset($result['status']) ? $result['status'] : 0;
  1278. $datas = isset($result['result']) ? $result['result'] : [];
  1279. if ($status != 1 || empty($datas)) {
  1280. $this->error = '2207';
  1281. return false;
  1282. }
  1283. $logs = [];
  1284. $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
  1285. $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
  1286. if ($datas) {
  1287. foreach ($datas as $v) {
  1288. $decimal = isset($v['tokenDecimal']) ? intval($v['tokenDecimal']) : 0;
  1289. $decimal = $decimal ? $decimal : 6;
  1290. $amount = isset($v['value']) ? intval($v['value']) : 0;
  1291. $amount = moneyFormat($amount / pow(10, $decimal), 6);
  1292. $time = isset($v['timestamp']) ? intval($v['timestamp']) : 0;
  1293. $txid = isset($v['hash']) ? $v['hash'] : '';
  1294. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  1295. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  1296. $orderNo = get_order_num('TW');
  1297. $log = [
  1298. 'user_id' => $userId,
  1299. 'change_type' => 2,
  1300. 'coin_type' => $coinType,
  1301. 'contact_type' => 2,
  1302. 'order_no' => $orderNo,
  1303. 'from_address' => isset($v['from']) ? $v['from'] : '',
  1304. 'to_address' => isset($v['to']) ? $v['to'] : '',
  1305. 'txid' => $txid,
  1306. 'num' => $amount,
  1307. 'balance' => $balance,
  1308. 'create_time' => $time ? $time : time(),
  1309. 'update_time' => time(),
  1310. 'status' => 2,
  1311. 'mark' => 1,
  1312. ];
  1313. if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
  1314. $this->memberModel->where(['id' => $userId])->decrement('erc_usdt', $amount);
  1315. $log['status'] = 1;
  1316. // 明细处理
  1317. $data = [
  1318. 'order_no' => $orderNo,
  1319. 'user_id' => $userId,
  1320. 'type' => 5,
  1321. 'pay_type' => 1,
  1322. 'trade_type' => 3,
  1323. 'change_type' => 2,
  1324. 'num' => $amount,
  1325. 'total' => 0,
  1326. 'balance' => floatval($balance - $amount),
  1327. 'create_time' => time(),
  1328. 'update_time' => time(),
  1329. 'remark' => '提币:' . $amount,
  1330. 'status' => 1,
  1331. 'mark' => 1,
  1332. ];
  1333. $this->capitalModel->edit($data);
  1334. }
  1335. $logs[] = $log;
  1336. $this->coinModel->insert($log);
  1337. }
  1338. }
  1339. }
  1340. return $logs;
  1341. } catch (\Exception $exception) {
  1342. $message = $exception->getMessage();
  1343. $this->error = $message;
  1344. return false;
  1345. }
  1346. }
  1347. /**
  1348. * usdt-erc2.0 归集
  1349. * @throws \Tron\Exceptions\TransactionException
  1350. * @throws \Tron\Exceptions\TronErrorException
  1351. */
  1352. public function usdtErcTrigger($force = false)
  1353. {
  1354. if (empty($this->config['eth_api_url'])) {
  1355. $this->error = '2206';
  1356. return false;
  1357. }
  1358. if (empty($this->config['eth_api_key'])) {
  1359. $this->error = '2207';
  1360. return false;
  1361. }
  1362. // 获取钱包参数
  1363. try {
  1364. // 用收账钱包归集
  1365. $otcAddress = ConfigService::make()->getConfigByCode('erc_address');
  1366. $otcAddressPrivate = ConfigService::make()->getConfigByCode('erc_private_key');
  1367. // 出账手续费钱包
  1368. $otcOutAddress = ConfigService::make()->getConfigByCode('erc_out_address');
  1369. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('erc_out_private_key');
  1370. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  1371. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  1372. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_eth_free');
  1373. $triggerFree = $triggerFree > 0 ? $triggerFree : (5/pow(10, 8));
  1374. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  1375. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  1376. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  1377. $this->error = '2203';
  1378. return false;
  1379. }
  1380. // 出账钱包
  1381. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  1382. $this->error = '2203';
  1383. return false;
  1384. }
  1385. $page = RedisService::get("caches:wallet:transferRecPage");
  1386. $page = $page ? $page : 1;
  1387. // 归集时间段为凌晨0点-5点
  1388. if ((date('H:i') >= '05:00') && !$force) {
  1389. $this->error = '不在归集时间段';
  1390. return false;
  1391. }
  1392. if (RedisService::get("caches:wallet:triggerErcLock:{$page}")) {
  1393. $this->error = '不要频繁操作,30秒后重试';
  1394. return false;
  1395. }
  1396. // 上锁
  1397. RedisService::set("caches:wallet:triggerErcLock:{$page}", 1, rand(10, 30));
  1398. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  1399. if (empty($addrList)) {
  1400. RedisService::set("caches:wallet:transferErcPage", 1, 600);
  1401. $this->error = '1019';
  1402. return false;
  1403. }
  1404. // 平台钱包地址
  1405. $count = 0;
  1406. $failedCount = 0;
  1407. $api = new Etherscan($this->config['eth_api_key']);
  1408. $cacheKey = "caches:wallet:triggerErc:";
  1409. foreach ($addrList as $v) {
  1410. try {
  1411. // 获取子钱包TRC-USDT余额
  1412. $userId = isset($v['id']) ? $v['id'] : 0;
  1413. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  1414. $triggerAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  1415. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  1416. // 可归集的USDT余额
  1417. $result = $api->tokenBalance($triggerAddress);
  1418. $triggerUsdt = isset($result['result']) ? floatval($result['result']) : 0.00;
  1419. $triggerUsdt = $triggerUsdt ? floatval($triggerUsdt / pow(10, 6)) : '0.00';
  1420. // USDT 余额低于归集金额,则不归集
  1421. if ($triggerUsdt < $triggerMin) {
  1422. $failedCount++;
  1423. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  1424. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1425. continue;
  1426. }
  1427. // 获取子钱包Eth余额
  1428. $result = $api->balance($triggerAddress);
  1429. $triggerEth = isset($result['result']) ? floatval($result['result']) : 0.00;
  1430. $triggerEth = $triggerEth ? floatval($triggerEth / pow(10, 18)) : '0.00';
  1431. // 获取平台出账钱包ETH余额
  1432. $result = $api->balance($otcOutAddress);
  1433. $otcOutEthTotal = isset($result['result']) ? floatval($result['result']) : 0.00;
  1434. $otcOutEthTotal = $otcOutEthTotal ? floatval($otcOutEthTotal / pow(10, 18)) : '0.00';
  1435. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  1436. if ($triggerEth < $triggerFree && $otcOutEthTotal < $triggerFree) {
  1437. $failedCount++;
  1438. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerEth, 'otcTrx' => $otcOutEthTotal, 'error' => '平台钱包ETH手续费不足', 'date' => date('Y-m-d H:i:s')];
  1439. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1440. continue;
  1441. }
  1442. // 如果子钱包ETH不足手续费5个gwei,平台ETH充足则自动充值后下次调用时归集
  1443. if ($triggerEth < $triggerFree) {
  1444. $failedCount++;
  1445. $result = $this->ercTransfer($address, $triggerFree);
  1446. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerEth' => $triggerEth, 'transfer' => $result, 'error' => '归集钱包ETH手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  1447. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  1448. continue;
  1449. }
  1450. // 满足归集条件处理
  1451. $result = $this->usdtErcTransfer($otcOutAddress, $triggerUsdt, $triggerAddress, $addressPrivate);
  1452. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  1453. $count++;
  1454. } catch (\Exception $exception) {
  1455. $failedCount++;
  1456. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  1457. }
  1458. }
  1459. // 超出分页数,下次处理下一页
  1460. if (count($addrList) >= 200) {
  1461. RedisService::set("caches:wallet:transferErcPage", $page + 1, 600);
  1462. }
  1463. if ($count > 0) {
  1464. return ['success' => $count, 'fail' => $failedCount];
  1465. } else {
  1466. $this->error = 1021;
  1467. return false;
  1468. }
  1469. } catch (\Exception $exception) {
  1470. $this->error = $exception->getMessage();
  1471. return false;
  1472. }
  1473. }
  1474. }