UsdtWalletService1.php 82 KB

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