UsdtWalletService.php 77 KB

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