UsdtWalletService.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  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 floatval($data);
  770. }
  771. if (RedisService::get($cacheKey . '_lock') && $cache) {
  772. return false;
  773. }
  774. try {
  775. $url = sprintf($this->apiUrls['erc_balance'],$address, $this->config['eth_api_key']);
  776. $url = $this->config['eth_api_url'] . $url;
  777. RedisService::set("caches:trades:erc:balance_{$address}", ['url' => $url, 'config' => $this->config], 600);
  778. $result = curl_api($url);
  779. $result = $result? json_decode($result, true) : [];
  780. $balance = isset($result['result']) ? floatval($result['result']) : 0.00;
  781. $balance = $balance>0? floatval($balance / pow(10, 18)) : '0.00';
  782. RedisService::set($cacheKey, $balance, rand(5, 10));
  783. RedisService::set($cacheKey . '_lock', true, rand(10, 20));
  784. return floatval($balance);
  785. } catch (\Exception $exception) {
  786. $this->error = $exception->getMessage();
  787. return false;
  788. }
  789. }
  790. /**
  791. * USDT-ERC20余额
  792. * @param $address
  793. * @return false|float|string
  794. */
  795. public function getErc20Usdt($address, $cache = false)
  796. {
  797. if (empty($address)) {
  798. $this->error = '1018';
  799. return false;
  800. }
  801. if (empty($this->config['eth_api_url'])) {
  802. $this->error = '2206';
  803. return false;
  804. }
  805. if (empty($this->config['eth_api_key'])) {
  806. $this->error = '2207';
  807. return false;
  808. }
  809. if (empty($this->config['erc_contract_address'])) {
  810. $this->error = '2228';
  811. return false;
  812. }
  813. $cacheKey = "caches:wallet:balance:erc_usdt_{$address}";
  814. if ($data = RedisService::get($cacheKey) && $cache) {
  815. return floatval($data);
  816. }
  817. if (RedisService::get($cacheKey . '_lock') && $cache) {
  818. return false;
  819. }
  820. try {
  821. $url = sprintf($this->apiUrls['erc20_balance'], $this->config['erc_contract_address'],$address, $this->config['eth_api_key']);
  822. $url = $this->config['eth_api_url'] . $url;
  823. RedisService::set("caches:trades:erc:balance20_{$address}", ['url' => $url, 'config' => $this->config], 600);
  824. $result = curl_api($url);
  825. $result = $result? json_decode($result, true) : [];
  826. $balance = isset($result['result']) ? floatval($result['result']) : 0.00;
  827. $balance = $balance>0? floatval($balance / pow(10, 6)) : '0.00';
  828. RedisService::set($cacheKey, floatval($balance), rand(5, 10));
  829. RedisService::set($cacheKey . '_lock', true, rand(10, 20));
  830. return floatval($balance);
  831. } catch (\Exception $exception) {
  832. $this->error = $exception->getMessage();
  833. return false;
  834. }
  835. }
  836. /**
  837. * ERC 转账
  838. * @param $to
  839. * @param $amount
  840. * @param string $from
  841. * @param string $fromPrivate
  842. * @return array|false
  843. */
  844. public function ercTransfer($to, $amount, $from = '', $fromPrivate = '')
  845. {
  846. if ($amount <= 0) {
  847. $this->error = '2205';
  848. return false;
  849. }
  850. if (empty($this->config['eth_api_url'])) {
  851. $this->error = '2206';
  852. return false;
  853. }
  854. if (empty($this->config['eth_api_key'])) {
  855. $this->error = '2207';
  856. return false;
  857. }
  858. // 获取钱包参数
  859. try {
  860. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  861. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  862. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  863. $this->error = '2228';
  864. return false;
  865. }
  866. $amount = floatval($amount * pow(10, 18));
  867. $params = [
  868. "from" => $otcAddress, // 来源
  869. "to" => $to, // 收款
  870. "gas" => '0x' . dechex(90000), // gas量,默认90000
  871. "gasPrice" => "0x9184e72a000",
  872. "value" => '0x' . dechex($amount),
  873. "data" => ''
  874. ];
  875. $transaction = new Transaction($params);
  876. $transaction->sign($otcAddressPrivate);
  877. $hex = '0x' . $transaction;
  878. $url = sprintf($this->apiUrls['erc_transaction'], $hex, $this->config['eth_api_key']);
  879. $url = $this->config['eth_api_url'] . $url;
  880. RedisService::set("caches:trades:erc:transfer_{$to}", ['url' => $url, 'params' => $params, 'hex' => $hex], 600);
  881. $result = curl_api($url);
  882. $result = $result ? json_decode($result, true) : [];
  883. $tradeHash = isset($result['result']) ? $result['result'] : '';
  884. if ($tradeHash && hexdec($tradeHash) != 0) {
  885. return ['txid' => $tradeHash, 'amount' => $amount];
  886. } else {
  887. $this->error = '2229';
  888. return false;
  889. }
  890. } catch (\Exception $exception) {
  891. $message = $exception->getMessage();
  892. $this->error = $message;
  893. return false;
  894. }
  895. }
  896. /**
  897. * usdt-erc2.0 转账
  898. * @param $to 进账账户
  899. * @param $amount 转账金额
  900. * @param $from 转账账户
  901. * @param $fromPrivate 转账账户私钥
  902. * @throws \Tron\Exceptions\TransactionException
  903. * @throws \Tron\Exceptions\TronErrorException
  904. */
  905. public function usdtErcTransfer($to, $amount, $from = '', $fromPrivate = '')
  906. {
  907. if ($amount <= 0) {
  908. $this->error = '2205';
  909. return false;
  910. }
  911. if (empty($this->config['eth_api_url'])) {
  912. $this->error = '2206';
  913. return false;
  914. }
  915. if (empty($this->config['eth_api_key'])) {
  916. $this->error = '2207';
  917. return false;
  918. }
  919. // 获取钱包参数
  920. try {
  921. // 用出账钱包转账
  922. $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
  923. $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
  924. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  925. $this->error = '2228';
  926. return false;
  927. }
  928. $amount = floatval($amount * pow(10, 18));
  929. $sign = $this->getSha3Sign("transfer(address,uint256)");
  930. $params = [
  931. "from" => $otcAddress, // 来源
  932. "to" => $to, // 收款
  933. "gas" => '0x' . dechex(90000), // gas量,默认90000
  934. "gasPrice" => "0x9184e72a000",
  935. "value" => '0x' . dechex($amount),
  936. "data" => $this->getTransactionSignData($sign, $to, $amount)
  937. ];
  938. $transaction = new Transaction($params);
  939. $transaction->sign($otcAddressPrivate);
  940. $hex = '0x' . $transaction;
  941. $url = sprintf($this->apiUrls['erc_transaction'], $hex, $this->config['eth_api_key']);
  942. $url = $this->config['eth_api_url'] . $url;
  943. RedisService::set("caches:trades:erc20:transfer_{$to}", ['url' => $url, 'params' => $params, 'hex' => $hex], 600);
  944. $result = curl_api($url);
  945. $result = $result ? json_decode($result, true) : [];
  946. $tradeHash = isset($result['result']) ? $result['result'] : '';
  947. $error = isset($result['error']) ? $result['error'] : [];
  948. if ($tradeHash && hexdec($tradeHash) != 0) {
  949. return ['txID' => $tradeHash, 'amount' => $amount];
  950. } else {
  951. $this->error = isset($error['message']) ? $error['message'] : '2229';
  952. return false;
  953. }
  954. } catch (\Exception $exception) {
  955. $message = $exception->getMessage();
  956. $this->error = $message;
  957. return false;
  958. }
  959. }
  960. /**
  961. * 合约方法签名编号
  962. * @param string $data
  963. * @return string
  964. */
  965. public function getSha3Sign($data)
  966. {
  967. $util = new Util();
  968. $result = $util->sha3($data);
  969. return '0x' . substr($result, 0, 8);
  970. }
  971. /**
  972. * 获取签名数据
  973. * @param $sign
  974. * @param $address
  975. * @return string
  976. */
  977. public function getSignData($sign, $address)
  978. {
  979. return $sign . str_repeat('0', 24) . substr($address, 2);
  980. }
  981. /**
  982. * 获取交易签名参数
  983. * @param $sign 调用的合约方法生成的sha3签名编号
  984. * @param $toAddress 收款地址
  985. * @param $amount 转账金额/十进制
  986. * @return string
  987. */
  988. public function getTransactionSignData($sign, $toAddress, $amount)
  989. {
  990. $toAddress = substr($toAddress, 2); // 去掉0x
  991. $toAddressSign = str_repeat('0', 64 - strlen($toAddress)) . $toAddress; // 前面补齐0为64位
  992. $amount = dechex($amount); // 十进制转十六进制
  993. $amountSign = str_repeat('0', 64 - strlen($amount)) . $amount; // 前面补齐0为64位
  994. return $sign . $toAddressSign . $amountSign;
  995. }
  996. /**
  997. * 监听USDT-ERC2.0用户子钱包存币处理
  998. * @param $userId 用户ID
  999. * @param $address 用户钱包地址
  1000. * @param int $coinType 币种:1-usdt
  1001. * @param int $limit 转账记录数,最新的
  1002. * @return array|false
  1003. */
  1004. public function getErc20RechargeLog($userId, $address, $coinType = 1, $limit = 50)
  1005. {
  1006. if ($userId <= 0 || empty($address)) {
  1007. $this->error = '1013';
  1008. return false;
  1009. }
  1010. if (empty($this->config['eth_api_url'])) {
  1011. $this->error = '2206';
  1012. return false;
  1013. }
  1014. if (empty($this->config['eth_api_key'])) {
  1015. $this->error = '2207';
  1016. return false;
  1017. }
  1018. try {
  1019. $cacheKey = "caches:wallets:recharge:erc_{$userId}_{$address}";
  1020. if (RedisService::get($cacheKey . '_lock')) {
  1021. return false;
  1022. }
  1023. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1024. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, 1, $limit, $this->config['eth_api_key']);
  1025. $url = $this->config['eth_api_url'] . $url;
  1026. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1027. $result = curl_api($url);
  1028. $result = $result ? json_decode($result, true) : [];
  1029. $status = isset($result['status']) ? $result['status'] : 0;
  1030. $datas = isset($result['result']) ? $result['result'] : [];
  1031. if ($status != 1 || empty($datas)) {
  1032. $this->error = '2207';
  1033. return false;
  1034. }
  1035. $logs = [];
  1036. $coinInMin = ConfigService::make()->getConfigByCode('erc_in_limit');
  1037. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  1038. if ($datas) {
  1039. foreach ($datas as $v) {
  1040. $amount = isset($v['value']) ? intval($v['value']) : 0;
  1041. $amount = moneyFormat($amount / 1000000, 6);
  1042. $time = isset($v['timeStamp']) ? intval($v['timeStamp']) : 0;
  1043. $txid = isset($v['hash']) ? $v['hash'] : '';
  1044. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  1045. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  1046. $orderNo = get_order_num('ER');
  1047. $log = [
  1048. 'type' => 1,
  1049. 'user_id' => $userId,
  1050. 'change_type' => 1,
  1051. 'coin_type' => $coinType,
  1052. 'contact_type' => 2,
  1053. 'order_no' => $orderNo,
  1054. 'from_address' => isset($v['from']) ? $v['from'] : '',
  1055. 'to_address' => isset($v['to']) ? $v['to'] : '',
  1056. 'txid' => $txid,
  1057. 'num' => $amount,
  1058. 'balance' => $balance,
  1059. 'create_time' => $time ? $time : time(),
  1060. 'update_time' => time(),
  1061. 'status' => 2,
  1062. 'mark' => 1,
  1063. ];
  1064. if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
  1065. $this->memberModel->where(['id' => $userId])->increment('erc_usdt', $amount);
  1066. $log['status'] = 1;
  1067. $data = [
  1068. 'order_no' => $orderNo,
  1069. 'user_id' => $userId,
  1070. 'type' => 4,
  1071. 'pay_type' => 1,
  1072. 'trade_type' => 3,
  1073. 'change_type' => 1,
  1074. 'num' => $amount,
  1075. 'total' => 0,
  1076. 'balance' => floatval($balance + $amount),
  1077. 'create_time' => time(),
  1078. 'update_time' => time(),
  1079. 'remark' => '存币:' . $amount,
  1080. 'status' => 1,
  1081. 'mark' => 1,
  1082. ];
  1083. $this->capitalModel->edit($data);
  1084. }
  1085. $logs[] = $log;
  1086. $this->coinModel->insert($log);
  1087. }
  1088. }
  1089. }
  1090. return $datas;
  1091. } catch (\Exception $exception) {
  1092. $message = $exception->getMessage();
  1093. $this->error = $message;
  1094. return false;
  1095. }
  1096. }
  1097. /**
  1098. * 获取USDT-ERC2.0交易记录(进出账)
  1099. * @param $address 用户钱包地址
  1100. * @param int $coinType 币种:1-usdt
  1101. * @param int $limit 转账记录数,最新的
  1102. * @return array|false
  1103. */
  1104. public function getErc20TransferLog($address, $type = 1, $page = 1, $limit = 50)
  1105. {
  1106. if (empty($this->config['eth_api_url'])) {
  1107. $this->error = '2206';
  1108. return false;
  1109. }
  1110. if (empty($this->config['eth_api_key'])) {
  1111. $this->error = '2207';
  1112. return false;
  1113. }
  1114. try {
  1115. $cacheKey = "caches:wallets:transfer:erc_{$address}";
  1116. if (RedisService::get($cacheKey . '_lock')) {
  1117. return false;
  1118. }
  1119. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1120. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, $page, $limit, $this->config['eth_api_key']);
  1121. $url = $this->config['eth_api_url'] . $url;
  1122. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1123. $result = curl_api($url);
  1124. $result = $result ? json_decode($result, true) : [];
  1125. $status = isset($result['status']) ? $result['status'] : 0;
  1126. $datas = isset($result['result']) ? $result['result'] : [];
  1127. if ($status != 1 || empty($datas)) {
  1128. $this->error = '2207';
  1129. return false;
  1130. }
  1131. return $datas;
  1132. } catch (\Exception $exception) {
  1133. $message = $exception->getMessage();
  1134. $this->error = $message;
  1135. return false;
  1136. }
  1137. }
  1138. /**
  1139. * 监听USDT-ERC2.0提币记录并进账(平台钱包)
  1140. * @param $address 用户钱包地址
  1141. * @param int $limit 转账记录数,最新的
  1142. * @return array|false
  1143. */
  1144. public function getErc20TransferLogByOtc($address, $limit = 100)
  1145. {
  1146. if (empty($address)) {
  1147. $this->error = '1013';
  1148. return false;
  1149. }
  1150. if (empty($this->config['eth_api_url'])) {
  1151. $this->error = '2206';
  1152. return false;
  1153. }
  1154. if (empty($this->config['eth_api_key'])) {
  1155. $this->error = '2207';
  1156. return false;
  1157. }
  1158. try {
  1159. $cacheKey = "caches:wallets:transfer:erc_{$address}";
  1160. if (RedisService::get($cacheKey . '_lock')) {
  1161. return false;
  1162. }
  1163. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1164. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, 1, $limit, $this->config['eth_api_key']);
  1165. $url = $this->config['eth_api_url'] . $url;
  1166. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1167. $result = curl_api($url);
  1168. $result = $result ? json_decode($result, true) : [];
  1169. $status = isset($result['status']) ? $result['status'] : 0;
  1170. $datas = isset($result['result']) ? $result['result'] : [];
  1171. if ($status != 1 || empty($datas)) {
  1172. $this->error = '2207';
  1173. return false;
  1174. }
  1175. $results = [
  1176. 'logs' => [],
  1177. 'trades' => [],
  1178. ];
  1179. if ($datas) {
  1180. foreach ($datas as $v) {
  1181. $from = isset($v['from']) ? trim($v['from']) : '';
  1182. $to = isset($v['to']) ? trim($v['to']) : '';
  1183. $amount = isset($v['value']) ? intval($v['value']) : 0;
  1184. $decimal = isset($v['tokenDecimal']) ? intval($v['tokenDecimal']) : 0;
  1185. $decimal = $decimal ? $decimal : 6;
  1186. $amount = moneyFormat($amount / pow(10, $decimal), 6);
  1187. $time = isset($v['timeStamp']) ? intval($v['timeStamp']) : 0;
  1188. $txid = isset($v['hash']) ? $v['hash'] : '';
  1189. if ($time > time() - 12 * 3600 && $from == $address) {
  1190. // 有记录,且是用户提币
  1191. $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
  1192. $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
  1193. if ($coinInfo && $userId && $coinInfo['status'] == 4 && $coinInfo['contact_type'] == 2) {
  1194. // 直接更新提币状态
  1195. CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['status' => 1, 'update_time' => time()]);
  1196. // 明细处理
  1197. $num = floatval($coinInfo['num'] + $coinInfo['free']);
  1198. $data = [
  1199. 'order_no' => $coinInfo['order_no'],
  1200. 'user_id' => $userId,
  1201. 'type' => 5,
  1202. 'pay_type' => 1,
  1203. 'trade_type' => 3,
  1204. 'change_type' => 2,
  1205. 'num' => $num,
  1206. 'total' => 0,
  1207. 'balance' => floatval($coinInfo['balance'] - $num),
  1208. 'create_time' => time(),
  1209. 'update_time' => time(),
  1210. 'remark' => '提币:' . $amount,
  1211. 'status' => 1,
  1212. 'mark' => 1,
  1213. ];
  1214. $this->capitalModel->edit($data);
  1215. $results['trades'][] = ['log' => $v, 'order' => $coinInfo];
  1216. }
  1217. } // 其他交易明细
  1218. else if ($time > time() - 7 * 12 * 3600 && !$coinInfo) {
  1219. $results['logs'][] = [
  1220. 'type' => 3,
  1221. 'user_id' => 0,
  1222. 'from_address' => $from,
  1223. 'to_address' => $to,
  1224. 'change_type' => $from == $address ? 2 : 1,
  1225. 'coin_type' => 1,
  1226. 'contact_type' => 2,
  1227. 'order_no' => get_order_num('TC'),
  1228. 'txid' => $txid,
  1229. 'num' => $amount,
  1230. 'free' => 0,
  1231. 'balance' => 0,
  1232. 'create_time' => time(),
  1233. 'update_time' => time(),
  1234. 'status' => 1,
  1235. 'mark' => 1,
  1236. ];
  1237. }
  1238. }
  1239. }
  1240. if ($results['logs']) {
  1241. $this->coinModel->insertAll($results['logs']);
  1242. }
  1243. return $results;
  1244. } catch (\Exception $exception) {
  1245. $message = $exception->getMessage();
  1246. $this->error = $message;
  1247. return false;
  1248. }
  1249. }
  1250. /**
  1251. * USDT-ERC20 用户子钱包提币处理
  1252. * @param $userId
  1253. * @param $address
  1254. * @param int $coinType
  1255. * @param int $limit
  1256. * @return false
  1257. */
  1258. public function getErc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
  1259. {
  1260. if (empty($address)) {
  1261. $this->error = '1013';
  1262. return false;
  1263. }
  1264. if (empty($this->config['eth_api_url'])) {
  1265. $this->error = '2206';
  1266. return false;
  1267. }
  1268. if (empty($this->config['eth_api_key'])) {
  1269. $this->error = '2207';
  1270. return false;
  1271. }
  1272. try {
  1273. $cacheKey = "caches:wallets:transfer:erc_{$address}";
  1274. if (RedisService::get($cacheKey . '_lock')) {
  1275. return false;
  1276. }
  1277. RedisService::set($cacheKey . '_lock', ['config' => $this->config, 'address' => $address], rand(5, 10));
  1278. $url = sprintf($this->apiUrls['erc20_transaction_log'], $address, 1, $limit, $this->config['eth_api_key']);
  1279. $url = $this->config['eth_api_url'] . $url;
  1280. RedisService::set("caches:trades:erc20:logs_{$address}", ['url' => $url, 'params' => ['address' => $address, 'config' => $this->config, 'limit' => $limit]], 600);
  1281. $result = curl_api($url);
  1282. $result = $result ? json_decode($result, true) : [];
  1283. $status = isset($result['status']) ? $result['status'] : 0;
  1284. $datas = isset($result['result']) ? $result['result'] : [];
  1285. if ($status != 1 || empty($datas)) {
  1286. $this->error = '2207';
  1287. return false;
  1288. }
  1289. $logs = [];
  1290. $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
  1291. $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
  1292. if ($datas) {
  1293. foreach ($datas as $v) {
  1294. $decimal = isset($v['tokenDecimal']) ? intval($v['tokenDecimal']) : 0;
  1295. $decimal = $decimal ? $decimal : 6;
  1296. $amount = isset($v['value']) ? intval($v['value']) : 0;
  1297. $amount = moneyFormat($amount / pow(10, $decimal), 6);
  1298. $time = isset($v['timestamp']) ? intval($v['timestamp']) : 0;
  1299. $txid = isset($v['hash']) ? $v['hash'] : '';
  1300. if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
  1301. $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
  1302. $orderNo = get_order_num('TW');
  1303. $log = [
  1304. 'user_id' => $userId,
  1305. 'change_type' => 2,
  1306. 'coin_type' => $coinType,
  1307. 'contact_type' => 2,
  1308. 'order_no' => $orderNo,
  1309. 'from_address' => isset($v['from']) ? $v['from'] : '',
  1310. 'to_address' => isset($v['to']) ? $v['to'] : '',
  1311. 'txid' => $txid,
  1312. 'num' => $amount,
  1313. 'balance' => $balance,
  1314. 'create_time' => $time ? $time : time(),
  1315. 'update_time' => time(),
  1316. 'status' => 2,
  1317. 'mark' => 1,
  1318. ];
  1319. if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
  1320. $this->memberModel->where(['id' => $userId])->decrement('erc_usdt', $amount);
  1321. $log['status'] = 1;
  1322. // 明细处理
  1323. $data = [
  1324. 'order_no' => $orderNo,
  1325. 'user_id' => $userId,
  1326. 'type' => 5,
  1327. 'pay_type' => 1,
  1328. 'trade_type' => 3,
  1329. 'change_type' => 2,
  1330. 'num' => $amount,
  1331. 'total' => 0,
  1332. 'balance' => floatval($balance - $amount),
  1333. 'create_time' => time(),
  1334. 'update_time' => time(),
  1335. 'remark' => '提币:' . $amount,
  1336. 'status' => 1,
  1337. 'mark' => 1,
  1338. ];
  1339. $this->capitalModel->edit($data);
  1340. }
  1341. $logs[] = $log;
  1342. $this->coinModel->insert($log);
  1343. }
  1344. }
  1345. }
  1346. return $logs;
  1347. } catch (\Exception $exception) {
  1348. $message = $exception->getMessage();
  1349. $this->error = $message;
  1350. return false;
  1351. }
  1352. }
  1353. /**
  1354. * usdt-erc2.0 归集
  1355. * @throws \Tron\Exceptions\TransactionException
  1356. * @throws \Tron\Exceptions\TronErrorException
  1357. */
  1358. public function usdtErcTrigger($force = false)
  1359. {
  1360. if (empty($this->config['eth_api_url'])) {
  1361. $this->error = '2206';
  1362. return false;
  1363. }
  1364. if (empty($this->config['eth_api_key'])) {
  1365. $this->error = '2207';
  1366. return false;
  1367. }
  1368. // 获取钱包参数
  1369. try {
  1370. // 用收账钱包归集
  1371. $otcAddress = ConfigService::make()->getConfigByCode('erc_address');
  1372. $otcAddressPrivate = ConfigService::make()->getConfigByCode('erc_private_key');
  1373. // 出账手续费钱包
  1374. $otcOutAddress = ConfigService::make()->getConfigByCode('erc_out_address');
  1375. $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('erc_out_private_key');
  1376. $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
  1377. $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
  1378. $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_eth_free');
  1379. $triggerFree = $triggerFree > 0 ? $triggerFree : (5/pow(10, 8));
  1380. $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
  1381. $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
  1382. if (empty($otcAddress) || empty($otcAddressPrivate)) {
  1383. $this->error = '2203';
  1384. return false;
  1385. }
  1386. // 出账钱包
  1387. if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
  1388. $this->error = '2203';
  1389. return false;
  1390. }
  1391. $page = RedisService::get("caches:wallet:transferRecPage");
  1392. $page = $page ? $page : 1;
  1393. // 归集时间段为凌晨0点-5点
  1394. if ((date('H:i') >= '05:00') && !$force) {
  1395. $this->error = '不在归集时间段';
  1396. return false;
  1397. }
  1398. if (RedisService::get("caches:wallet:triggerErcLock:{$page}")) {
  1399. $this->error = '不要频繁操作,30秒后重试';
  1400. return false;
  1401. }
  1402. // 上锁
  1403. RedisService::set("caches:wallet:triggerErcLock:{$page}", 1, rand(10, 30));
  1404. $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
  1405. if (empty($addrList)) {
  1406. RedisService::set("caches:wallet:transferErcPage", 1, 600);
  1407. $this->error = '1019';
  1408. return false;
  1409. }
  1410. // 平台钱包地址
  1411. $count = 0;
  1412. $failedCount = 0;
  1413. $api = new Etherscan($this->config['eth_api_key']);
  1414. $cacheKey = "caches:wallet:triggerErc:";
  1415. foreach ($addrList as $v) {
  1416. try {
  1417. // 获取子钱包TRC-USDT余额
  1418. $userId = isset($v['id']) ? $v['id'] : 0;
  1419. $address = isset($v['trc_address']) ? $v['trc_address'] : '';
  1420. $triggerAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
  1421. $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
  1422. // 可归集的USDT余额
  1423. $result = $api->tokenBalance($triggerAddress);
  1424. $triggerUsdt = isset($result['result']) ? floatval($result['result']) : 0.00;
  1425. $triggerUsdt = $triggerUsdt ? floatval($triggerUsdt / pow(10, 6)) : '0.00';
  1426. // USDT 余额低于归集金额,则不归集
  1427. if ($triggerUsdt < $triggerMin) {
  1428. $failedCount++;
  1429. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
  1430. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1431. continue;
  1432. }
  1433. // 获取子钱包Eth余额
  1434. $result = $api->balance($triggerAddress);
  1435. $triggerEth = isset($result['result']) ? floatval($result['result']) : 0.00;
  1436. $triggerEth = $triggerEth ? floatval($triggerEth / pow(10, 18)) : '0.00';
  1437. // 获取平台出账钱包ETH余额
  1438. $result = $api->balance($otcOutAddress);
  1439. $otcOutEthTotal = isset($result['result']) ? floatval($result['result']) : 0.00;
  1440. $otcOutEthTotal = $otcOutEthTotal ? floatval($otcOutEthTotal / pow(10, 18)) : '0.00';
  1441. // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
  1442. if ($triggerEth < $triggerFree && $otcOutEthTotal < $triggerFree) {
  1443. $failedCount++;
  1444. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerEth, 'otcTrx' => $otcOutEthTotal, 'error' => '平台钱包ETH手续费不足', 'date' => date('Y-m-d H:i:s')];
  1445. RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
  1446. continue;
  1447. }
  1448. // 如果子钱包ETH不足手续费5个gwei,平台ETH充足则自动充值后下次调用时归集
  1449. if ($triggerEth < $triggerFree) {
  1450. $failedCount++;
  1451. $result = $this->ercTransfer($address, $triggerFree);
  1452. $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerEth' => $triggerEth, 'transfer' => $result, 'error' => '归集钱包ETH手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
  1453. RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
  1454. continue;
  1455. }
  1456. // 满足归集条件处理
  1457. $result = $this->usdtErcTransfer($otcOutAddress, $triggerUsdt, $triggerAddress, $addressPrivate);
  1458. RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
  1459. $count++;
  1460. } catch (\Exception $exception) {
  1461. $failedCount++;
  1462. RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
  1463. }
  1464. }
  1465. // 超出分页数,下次处理下一页
  1466. if (count($addrList) >= 200) {
  1467. RedisService::set("caches:wallet:transferErcPage", $page + 1, 600);
  1468. }
  1469. if ($count > 0) {
  1470. return ['success' => $count, 'fail' => $failedCount];
  1471. } else {
  1472. $this->error = 1021;
  1473. return false;
  1474. }
  1475. } catch (\Exception $exception) {
  1476. $this->error = $exception->getMessage();
  1477. return false;
  1478. }
  1479. }
  1480. }