| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services;
- use App\Models\CapitalLogModel;
- use App\Models\CoinLogModel;
- use App\Models\MemberModel;
- use App\Services\Api\MemberService;
- use App\Services\Common\CoinLogService;
- use BitWasp\Bitcoin\Address\AddressCreator;
- use BitWasp\Bitcoin\Address\PayToPubKeyHashAddress;
- use BitWasp\Bitcoin\Bitcoin;
- use BitWasp\Bitcoin\Crypto\Random\Random;
- use BitWasp\Bitcoin\Key\Factory\PrivateKeyFactory;
- use BitWasp\Bitcoin\Script\WitnessProgram;
- use GuzzleHttp\Client;
- use IEXBase\TronAPI\Tron;
- use Tron\Api;
- use Tron\TRC20;
- use Tron\TRX;
- use Web3\Methods\Eth\SendRawTransaction;
- use Web3p\EthereumTx\ERC20Transaction;
- use Web3p\EthereumTx\Transaction;
- use Web3p\EthereumUtil\Util;
- /**
- * USDT链管理-服务类
- * Class UsdtWalletService
- * @package App\Services
- */
- class UsdtWalletService extends BaseService
- {
- protected $apiUrl = '';
- protected $config = [];
- // 静态对象
- protected static $instance = null;
- protected $apiUrls = [
- 'usdt_trx2_transfer_log' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&only_confirmed=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
- 'usdt_trx2_transfer_logs' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
- ];
- /**
- * 构造函数
- * UsdtWalletService constructor.
- */
- public function __construct()
- {
- $this->memberModel = new MemberModel();
- $this->coinModel = new CoinLogModel();
- $this->capitalModel = new CapitalLogModel();
- $this->config = ConfigService::make()->getConfigOptionByGroup(4);
- if (empty($this->config)) {
- return false;
- }
- }
- /**
- * 静态入口
- * @return static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = (new UsdtWalletService());
- }
- return self::$instance;
- }
- /**
- * 获取TRC2.0钱包地址
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function getTrxAddress()
- {
- try {
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
- $trxWallet = new TRX($api);
- $addressData = $trxWallet->generateAddress();
- $addressData = (array)$addressData;
- return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * trx 转账
- * @param $to 进账账户
- * @param $amount 转账金额
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function trxTransfer($to, $amount, $from = '')
- {
- if ($amount <= 0) {
- $this->error = '2205';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trxWallet = new TRX($api);
- // 获取钱包参数
- try {
- $otcAddress = ConfigService::make()->getConfigByCode('trc_out_address');
- $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
- if (empty($otcAddress) || empty($otcAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- $tron = new Tron();
- // 获取平台钱包hex
- $tron->setAddress($otcAddress);
- $otcAddress = $tron->getAddress();
- $tron->setAddress($to);
- $toAddress = $tron->getAddress();
- $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
- $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
- $result = $trxWallet->transfer($from, $to, $amount);
- return $result;
- } catch (\Exception $exception) {
- $message = $exception->getMessage();
- $this->error = $message;
- return false;
- }
- }
- /**
- * usdt-trc2.0 转账
- * @param $to 进账账户
- * @param $amount 转账金额
- * @param $from 转账账户
- * @param $fromPrivate 转账账户私钥
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivate = '')
- {
- if ($amount <= 0) {
- $this->error = '2205';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- // 获取钱包参数
- try {
- // 用出账钱包转账
- $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('trc_out_address');
- $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('trc_out_private_key');
- if (empty($otcAddress) || empty($otcAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- $tron = new Tron();
- // 获取平台钱包hex
- $tron->setAddress($otcAddress);
- $otcAddress = $tron->getAddress();
- // 获取收款钱包hex
- $tron->setAddress($to);
- $toAddress = $tron->getAddress();
- $from = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
- $to = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
- $result = $trxWallet->transfer($from, $to, $amount);
- return $result;
- } catch (\Exception $exception) {
- $message = $exception->getMessage();
- $this->error = $message;
- var_dump($exception);
- RedisService::set("caches:wallets:transfer:error_{$toAddress['base58']}", $exception, 600);
- return false;
- }
- }
- /**
- * usdt-trc2.0 归集
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function usdtTrcTrigger($force = false)
- {
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- // 获取钱包参数
- try {
- // 用收账钱包归集
- $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
- $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
- // 出账手续费钱包
- $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
- $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
- $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
- $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
- $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
- $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
- $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
- $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
- if (empty($otcAddress) || empty($otcAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- // 出账钱包
- if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- $page = RedisService::get("caches:wallet:transferPage");
- $page = $page ? $page : 1;
- // 归集时间段为凌晨0点-5点
- if ((date('H:i') >= '05:00') && !$force) {
- $this->error = '不在归集时间段';
- return false;
- }
- if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
- $this->error = '不要频繁操作,30秒后重试';
- return false;
- }
- // 上锁
- RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
- $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
- if (empty($addrList)) {
- RedisService::set("caches:wallet:transferPage", 1, 600);
- $this->error = '1019';
- return false;
- }
- // 平台钱包地址
- $count = 0;
- $failedCount = 0;
- $retryCount = 0;
- $notBalance = false;
- $tron = new Tron();
- $tron->setAddress($otcAddress);
- $otcAddress = $tron->getAddress();
- $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
- // 平台出账钱包地址
- $tron->setAddress($otcOutAddress);
- $otcOutAddress = $tron->getAddress();
- $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
- $cacheKey = "caches:wallet:trigger:";
- foreach ($addrList as $v) {
- try {
- // 获取子钱包TRC-USDT余额
- $userId = isset($v['id']) ? $v['id'] : 0;
- $address = isset($v['trc_address']) ? $v['trc_address'] : '';
- $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
- $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
- $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
- // 可归集的USDT余额
- $triggerUsdt = $trcWallet->balance($triggerAddress);
- // USDT 余额低于归集金额,则不归集
- if ($triggerUsdt < $triggerMin) {
- $failedCount++;
- $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
- RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
- continue;
- }
- // 获取子钱包TRX余额
- $triggerTrx = $trxWallet->balance($triggerAddress);
- // 获取平台出账钱包TRX余额
- $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
- // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
- if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
- $failedCount++;
- $notBalance = true;
- $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
- RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
- continue;
- }
- // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
- if ($triggerTrx < $triggerFree) {
- $retryCount++;
- $result = $this->trxTransfer($address, $triggerFree);
- $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
- RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
- continue;
- }
- // 满足归集条件处理
- $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
- RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
- $count++;
- } catch (\Exception $exception) {
- $failedCount++;
- RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
- }
- }
- // 超出分页数,下次处理下一页
- if (count($addrList) >= 200) {
- RedisService::set("caches:wallet:transferPage", $page + 1, 600);
- }
- if ($count > 0) {
- $this->error = lang(2225, ['success' => $count, 'fail' => $failedCount, 'retry' => $retryCount]);
- return ['success' => $count, 'fail' => $failedCount, 'retryCount' => $retryCount];
- } else if ($failedCount == count($addrList)) {
- $this->error = 2221;
- return false;
- } else if ($retryCount) {
- $this->error = lang(2222, ['num' => $retryCount]);
- return false;
- } else if ($notBalance) {
- $this->error = 2221;
- return false;
- } else {
- $this->error = lang(2224, ['num' => $failedCount]);
- return false;
- }
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * 监听USDT-TRC2.0转账记录并进账
- * @param $userId 用户ID
- * @param $address 用户钱包地址
- * @param int $coinType 币种:1-usdt
- * @param int $limit 转账记录数,最新的
- * @return array|false
- */
- public function getTrc20RechargeLog($userId, $address, $coinType = 1, $limit = 50)
- {
- if ($userId <= 0 || empty($address)) {
- $this->error = '1013';
- return false;
- }
- $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- RedisService::set("caches:wallets:recharge_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
- $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
- $result = $result ? json_decode($result, true) : [];
- $datas = isset($result['data']) ? $result['data'] : [];
- $status = isset($result['success']) ? $result['success'] : '';
- if ($status != true || empty($datas)) {
- $this->error = '2207';
- return false;
- }
- $logs = [];
- $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
- $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
- foreach ($datas as $v) {
- $amount = isset($v['value']) ? intval($v['value']) : 0;
- $amount = moneyFormat($amount / 1000000, 6);
- $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
- $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
- if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
- $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
- $orderNo = get_order_num('TR');
- $log = [
- 'user_id' => $userId,
- 'change_type' => 1,
- 'coin_type' => $coinType,
- 'contact_type' => 1,
- 'order_no' => $orderNo,
- 'from_address' => isset($v['from']) ? $v['from'] : '',
- 'to_address' => isset($v['to']) ? $v['to'] : '',
- 'txid' => $txid,
- 'num' => $amount,
- 'balance' => $balance,
- 'create_time' => $time ? $time : time(),
- 'update_time' => time(),
- 'status' => 2,
- 'mark' => 1,
- ];
- if ($amount >= $coinInMin && $this->memberModel->where(['id' => $userId])->increment('usdt_num', $amount)) {
- $this->memberModel->where(['id' => $userId])->increment('trc_usdt', $amount);
- $log['status'] = 1;
- $data = [
- 'order_no' => $orderNo,
- 'user_id' => $userId,
- 'type' => 4,
- 'pay_type' => 1,
- 'trade_type' => 3,
- 'change_type' => 1,
- 'num' => $amount,
- 'total' => 0,
- 'balance' => floatval($balance + $amount),
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => '存币',
- 'status' => 1,
- 'mark' => 1,
- ];
- $this->capitalModel->edit($data);
- }
- $logs[] = $log;
- $this->coinModel->insert($log);
- }
- }
- return $logs;
- }
- /**
- * 获取USDT-TRC2.0交易记录(进出账)
- * @param $address 用户钱包地址
- * @param int $coinType 币种:1-usdt
- * @param int $limit 转账记录数,最新的
- * @return array|false
- */
- public function getTrc20TransferLog($address, $type = 1, $limit = 50)
- {
- if (empty($address)) {
- $this->error = '1013';
- return false;
- }
- // 存币
- if ($type == 1) {
- $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'true', 'false');
- } // 提币
- else {
- $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
- }
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- RedisService::set("caches:wallets:transfer_temp_otc_{$type}", ['url' => $this->config['tron_api_url'] . $url], 600);
- $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
- $result = $result ? json_decode($result, true) : [];
- $datas = isset($result['data']) ? $result['data'] : [];
- $status = isset($result['success']) ? $result['success'] : '';
- if ($status != true || empty($datas)) {
- $this->error = '2207';
- return false;
- }
- if ($datas) {
- foreach ($datas as &$item) {
- $time = ($item['block_timestamp'] / 1000);
- $item['time_text'] = $time ? datetime($time, 'm-d H:i') : '';
- $item['num'] = floatval($item['value'] / 1000000);
- $item['contact_type'] = 1;
- $item['change_type'] = $type;
- $item['status'] = 1;
- }
- }
- return $datas;
- }
- /**
- * 监听USDT-TRC2.0提币记录并进账(平台钱包)
- * @param $address 用户钱包地址
- * @param int $limit 转账记录数,最新的
- * @return array|false
- */
- public function getTrc20TransferLogByOtc($address, $limit = 50)
- {
- if (empty($address)) {
- $this->error = '1013';
- return false;
- }
- $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
- $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
- $result = $result ? json_decode($result, true) : [];
- $datas = isset($result['data']) ? $result['data'] : [];
- $status = isset($result['success']) ? $result['success'] : '';
- if ($status != true || empty($datas)) {
- $this->error = '2207';
- return false;
- }
- $logs = [];
- foreach ($datas as $v) {
- $amount = isset($v['value']) ? intval($v['value']) : 0;
- $amount = moneyFormat($amount / 1000000, 6);
- $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
- $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
- if ($time > time() - 12 * 3600) {
- // 有记录,且是用户提币
- $coinInfo = CoinLogService::make()->getCacheInfoByTxid($txid);
- $userId = isset($coinInfo['user_id']) ? $coinInfo['user_id'] : 0;
- if ($coinInfo && $userId && $coinInfo['status'] == 4) {
- // 直接更新提币状态
- CoinLogModel::where(['txid' => $txid, 'user_id' => $userId])->update(['status' => 1, 'update_time' => time()]);
- // 明细处理
- $num = floatval($coinInfo['num'] + $coinInfo['free']);
- $data = [
- 'order_no' => $coinInfo['order_no'],
- 'user_id' => $userId,
- 'type' => 5,
- 'pay_type' => 1,
- 'trade_type' => 3,
- 'change_type' => 2,
- 'num' => $num,
- 'total' => 0,
- 'balance' => floatval($coinInfo['balance'] - $num),
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => '提币',
- 'status' => 1,
- 'mark' => 1,
- ];
- $this->capitalModel->edit($data);
- $logs[] = ['log' => $v, 'order' => $coinInfo];
- }
- }
- }
- return $logs;
- }
- /**
- * 监听USDT-TRC2.0充值记录并进账(用户子钱包)
- * @param $userId 用户ID
- * @param $address 用户钱包地址
- * @param int $coinType 币种:1-usdt
- * @param int $limit 转账记录数,最新的
- * @return array|false
- */
- public function getTrc20TransferLogByUser($userId, $address, $coinType = 1, $limit = 50)
- {
- if ($userId <= 0 || empty($address)) {
- $this->error = '1013';
- return false;
- }
- $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- RedisService::set("caches:wallets:transfer_temp_{$userId}", ['url' => $this->config['tron_api_url'] . $url], 600);
- $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 10);
- $result = $result ? json_decode($result, true) : [];
- $datas = isset($result['data']) ? $result['data'] : [];
- $status = isset($result['success']) ? $result['success'] : '';
- if ($status != true || empty($datas)) {
- $this->error = '2207';
- return false;
- }
- $logs = [];
- $coinOutMin = ConfigService::make()->getConfigByCode('trc_out_limit');
- $coinOutMin = $coinOutMin > 0 ? $coinOutMin : 0;
- foreach ($datas as $v) {
- $amount = isset($v['value']) ? intval($v['value']) : 0;
- $amount = moneyFormat($amount / 1000000, 6);
- $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
- $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
- if (!CoinLogService::make()->checkExists('txid', $txid) && $time > time() - 12 * 3600) {
- $balance = $this->memberModel->where(['id' => $userId])->value('usdt_num');
- $orderNo = get_order_num('TW');
- $log = [
- 'user_id' => $userId,
- 'change_type' => 2,
- 'coin_type' => $coinType,
- 'contact_type' => 1,
- 'order_no' => $orderNo,
- 'from_address' => isset($v['from']) ? $v['from'] : '',
- 'to_address' => isset($v['to']) ? $v['to'] : '',
- 'txid' => $txid,
- 'num' => $amount,
- 'balance' => $balance,
- 'create_time' => $time ? $time : time(),
- 'update_time' => time(),
- 'status' => 2,
- 'mark' => 1,
- ];
- if ($amount >= $coinOutMin && $this->memberModel->where(['id' => $userId])->decrement('usdt_num', $amount)) {
- $this->memberModel->where(['id' => $userId])->decrement('trc_usdt', $amount);
- $log['status'] = 1;
- // 明细处理
- $data = [
- 'order_no' => $orderNo,
- 'user_id' => $userId,
- 'type' => 5,
- 'pay_type' => 1,
- 'trade_type' => 3,
- 'change_type' => 2,
- 'num' => $amount,
- 'total' => 0,
- 'balance' => floatval($balance - $amount),
- 'create_time' => time(),
- 'update_time' => time(),
- 'remark' => '提币',
- 'status' => 1,
- 'mark' => 1,
- ];
- $this->capitalModel->edit($data);
- }
- $logs[] = $log;
- $this->coinModel->insert($log);
- }
- }
- return $logs;
- }
- /**
- * TRX余额
- * @param $address
- * @return false|float|string
- */
- public function getTrxBalance($address)
- {
- $cacheKey = "caches:wallet:balance:{$address}";
- if (RedisService::get($cacheKey)) {
- return false;
- }
- if (empty($address)) {
- $this->error = '1018';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- try {
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- $tron = new Tron();
- $tron->setAddress($address);
- $address = $tron->getAddress();
- $address = new \Tron\Address($address['base58'], '', $address['hex']);
- $result = $trxWallet->balance($address);
- return $result ? floatval($result) : '0.00';
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * USDT-TRC20余额
- * @param $address
- * @return false|float|string
- */
- public function getTrc20Usdt($address)
- {
- if (empty($address)) {
- $this->error = '1018';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- try {
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- $tron = new Tron();
- $tron->setAddress($address);
- $address = $tron->getAddress();
- $address = new \Tron\Address($address['base58'], '', $address['hex']);
- $result = $trxWallet->balance($address);
- return $result ? floatval($result) : '0.00';
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /********************** ERC钱包 **************************/
- /**
- * 获取ERC2.0钱包地址
- * @param string $type
- * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure
- */
- public function getErcAddress()
- {
- $random = new Random();
- $network = Bitcoin::getNetwork();
- $privateKeyFactory = new PrivateKeyFactory();
- $privateKey = $privateKeyFactory->generateCompressed($random);
- $publicKey = $privateKey->getPublicKey();
- // p2pkh 格式的地址
- $addressService = new PayToPubKeyHashAddress($publicKey->getPubKeyHash());
- // 将生成的钱包保存到数据库中
- $wif = $privateKey->toWif($network);
- $address = $addressService->getAddress();
- return ['wif' => $wif, 'hexAddress' => $this->getHexAddress($address), 'address' => $address];
- }
- /**
- * 获取HASH钱包地址
- * @param $address 钱包地址
- * @return \BitWasp\Buffertools\BufferInterface
- * @throws \BitWasp\Bitcoin\Exceptions\UnrecognizedAddressException
- */
- public function getHexAddress($address)
- {
- $data = WitnessProgram::v0((new AddressCreator())->fromString($address)->getHash());
- $buffer = $data->getProgram()->getHex();
- return $buffer ? '0x' . $buffer : '';
- }
- /**
- * 监听USDT-ERC2.0提币记录并进账(平台钱包)
- * @param $address 用户钱包地址
- * @param int $limit 转账记录数,最新的
- * @return array|false
- */
- public function getErc20TransferLogByOtc($address, $limit = 50)
- {
- return false;
- if (empty($address)) {
- $this->error = '1013';
- return false;
- }
- $url = sprintf($this->apiUrls['usdt_trx2_transfer_log'], $address, $limit, 'false', 'true');
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- RedisService::set("caches:wallets:transfer_temp_otc", ['url' => $this->config['tron_api_url'] . $url], 600);
- }
- /**
- * ERC 转账
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function ercTransfer($force = false)
- {
- if ($amount <= 0) {
- $this->error = '2205';
- return false;
- }
- if (empty($this->config['eth_api_url'])) {
- $this->error = '2206';
- return false;
- }
- if (empty($this->config['eth_api_key'])) {
- $this->error = '2207';
- return false;
- }
- // 获取钱包参数
- try {
- // 用出账钱包转账
- $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
- $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
- if (empty($otcAddress) || empty($otcAddressPrivate)) {
- $this->error = '2228';
- return false;
- }
- $amount = floatval($amount*pow(10,18));
- $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
- $headers = ["Content-Type" => 'application/json'];
- $params = [
- "from"=> $otcAddress, // 来源
- "to"=> $to, // 收款
- "gas"=> '0x'.dechex(90000), // gas量,默认90000
- "gasPrice"=> "0x9184e72a000",
- "value"=> '0x'.dechex($amount),
- ];
- $transaction = new Transaction($params);
- $transaction->sign($otcAddressPrivate);
- $hash = $transaction->hash();
- $data = [
- "jsonrpc" => "2.0",
- "method" => "eth_sendRawTransaction",
- "params" => ['0x'.$hash],
- "id" => 1
- ];
- RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data,'hash'=> $hash], 600);
- $result = curl_api($url, json_encode($data), $headers);
- $result = $result ? json_decode($result, true) : [];
- $tradeHash = isset($result['result'])? $result['result'] : '';
- if($tradeHash && hexdec($tradeHash) != 0){
- return ['txid'=> $tradeHash,'amount'=> $amount];
- }else{
- $this->error = '2229';
- return false;
- }
- } catch (\Exception $exception) {
- $message = $exception->getMessage();
- $this->error = $message;
- return false;
- }
- }
- /**
- * usdt-erc2.0 转账
- * @param $to 进账账户
- * @param $amount 转账金额
- * @param $from 转账账户
- * @param $fromPrivate 转账账户私钥
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function usdtErcTransfer($to, $amount, $from = '', $fromPrivate = '')
- {
- if ($amount <= 0) {
- $this->error = '2205';
- return false;
- }
- if (empty($this->config['eth_api_url'])) {
- $this->error = '2206';
- return false;
- }
- if (empty($this->config['eth_api_key'])) {
- $this->error = '2207';
- return false;
- }
- // 获取钱包参数
- try {
- // 用出账钱包转账
- $otcAddress = $from ? $from : ConfigService::make()->getConfigByCode('erc_out_address');
- $otcAddressPrivate = $from ? $fromPrivate : ConfigService::make()->getConfigByCode('erc_out_private_key');
- if (empty($otcAddress) || empty($otcAddressPrivate)) {
- $this->error = '2228';
- return false;
- }
- $amount = floatval($amount*pow(10,18));
- $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
- $headers = ["Content-Type" => 'application/json'];
- $sign = $this->getSha3Sign("transferFrom(address,address,uint256)");
- $params = [
- "from"=> $otcAddress, // 来源
- "to"=> $to, // 收款
- "gas"=> '0x'.dechex(90000), // gas量,默认90000
- "gasPrice"=> "0x9184e72a000",
- "value"=> '0x'.dechex($amount),
- "data"=> $this->getTransactionSignData($sign, $to, $amount)
- ];
- // $transaction = new Transaction($params);
- // $hash = $transaction->sign($otcAddressPrivate);
- $data = [
- "jsonrpc" => "2.0",
- // "method" => "eth_sendTransaction",
- "method" => "eth_sendTransaction",
- "params" => $params,
- // "params" => ['0x'.$hash],
- "id" => 1
- ];
- RedisService::set("caches:trades:erc:transfer_{$to}", ['params'=> $params,'data'=> $data], 600);
- $result = curl_api($url, json_encode($data), $headers);
- $result = $result ? json_decode($result, true) : [];
- $tradeHash = isset($result['result'])? $result['result'] : '';
- $error = isset($result['error'])? $result['error'] : [];
- if($tradeHash && hexdec($tradeHash) != 0){
- return ['txid'=> $tradeHash,'amount'=> $amount];
- }else{
- $this->error = isset($error['message'])? $error['message'] : '2229';
- return false;
- }
- } catch (\Exception $exception) {
- $message = $exception->getMessage();
- $this->error = $message;
- return false;
- }
- }
- /**
- * TRC余额
- * @param $address
- * @return false|float|string
- */
- public function getErcBalance($address)
- {
- if (empty($address)) {
- $this->error = '1018';
- return false;
- }
- if (empty($this->config['eth_api_url'])) {
- $this->error = '2206';
- return false;
- }
- if (empty($this->config['eth_api_key'])) {
- $this->error = '2207';
- return false;
- }
- try {
- $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
- $headers = ["Content-Type" => 'application/json'];
- $data = [
- "jsonrpc" => "2.0",
- "method" => "eth_getBalance",
- "params" => [$address, "latest"],
- "id" => 1
- ];
- $result = curl_api($url, json_encode($data), $headers);
- $result = $result ? json_decode($result, true) : [];
- $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
- return $balance ? floatval($balance/pow(10,18)) : '0.00';
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * USDT-ERC20余额
- * @param $address
- * @return false|float|string
- */
- public function getErc20Usdt($address)
- {
- if (empty($address)) {
- $this->error = '1018';
- return false;
- }
- if (empty($this->config['eth_api_url'])) {
- $this->error = '2206';
- return false;
- }
- if (empty($this->config['eth_api_key'])) {
- $this->error = '2207';
- return false;
- }
- if(empty($this->config['erc_contract_address'])){
- $this->error = '2228';
- return false;
- }
- try {
- $url = $this->config['eth_api_url'] . '/' . $this->config['eth_api_key'];
- $headers = ["Content-Type" => 'application/json'];
- $sign = $this->getSha3Sign("balanceOf(address)");
- $data = [
- "jsonrpc" => "2.0",
- "method" => "eth_call",
- "params" => [["to"=> $this->config['erc_contract_address'],"data"=> $this->getSignData($sign, $address)], "latest"],
- "id" => 1
- ];
- $result = curl_api($url, json_encode($data), $headers);
- $result = $result ? json_decode($result, true) : [];
- $balance = isset($result['result']) ? hexdec($result['result']) : 0.00;
- $balance = $balance? floatval($balance/1000000) : '0.00';
- return $balance? $balance : '0.00';
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * 合约方法签名编号
- * @param string $data
- * @return string
- */
- public function getSha3Sign($data)
- {
- $util = new Util();
- $result = $util->sha3($data);
- return '0x'.substr($result,0,8);
- }
- /**
- * 获取签名数据
- * @param $sign
- * @param $address
- * @return string
- */
- public function getSignData($sign, $address)
- {
- return $sign.str_repeat('0', 24).substr($address,2);
- }
- /**
- * 获取交易签名参数
- * @param $sign 调用的合约方法生成的sha3签名编号
- * @param $toAddress 收款地址
- * @param $amount 转账金额/十进制
- * @return string
- */
- public function getTransactionSignData($sign, $toAddress, $amount)
- {
- $toAddress = substr($toAddress,2); // 去掉0x
- $toAddressSign = str_repeat('0', 64-strlen($toAddress)).$toAddress; // 前面补齐0为64位
- $amount = dechex($amount); // 十进制转十六进制
- $amountSign = str_repeat('0', 64-strlen($amount)).$amount; // 前面补齐0为64位
- return $sign.$toAddressSign.$amountSign;
- }
- /**
- * 获取USDT-ERC2.0交易记录(进出账)
- * @param $address 用户钱包地址
- * @param int $coinType 币种:1-usdt
- * @param int $limit 转账记录数,最新的
- * @return array|false
- */
- public function getErc20TransferLog($address, $type = 1, $limit = 50)
- {
- }
- /**
- * usdt-trc2.0 归集
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function usdtErcTrigger($force = false)
- {
- return false;
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $this->config['tron_api_key']];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- // 获取钱包参数
- try {
- // 用收账钱包归集
- $otcAddress = ConfigService::make()->getConfigByCode('trc_address');
- $otcAddressPrivate = ConfigService::make()->getConfigByCode('trc_private_key');
- // 出账手续费钱包
- $otcOutAddress = ConfigService::make()->getConfigByCode('trc_out_address');
- $otcOutAddressPrivate = ConfigService::make()->getConfigByCode('trc_out_private_key');
- $triggerMin = ConfigService::make()->getConfigByCode('trade_trigger_min');
- $triggerTime = ConfigService::make()->getConfigByCode('trade_trigger_time');
- $triggerFree = ConfigService::make()->getConfigByCode('trade_trigger_free');
- $triggerFree = $triggerFree > 0 ? $triggerFree : 8;
- $triggerMin = $triggerMin > 0 ? $triggerMin : 0.1;
- $triggerTime = $triggerTime > 0 ? $triggerTime * 86400 : 86400;
- if (empty($otcAddress) || empty($otcAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- // 出账钱包
- if (empty($otcOutAddress) || empty($otcOutAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- $page = RedisService::get("caches:wallet:transferPage");
- $page = $page ? $page : 1;
- // 归集时间段为凌晨0点-5点
- if ((date('H:i') >= '05:00') && !$force) {
- $this->error = '不在归集时间段';
- return false;
- }
- if (RedisService::get("caches:wallet:triggerLock:{$page}")) {
- $this->error = '不要频繁操作,30秒后重试';
- return false;
- }
- // 上锁
- RedisService::set("caches:wallet:triggerLock:{$page}", 1, rand(10, 30));
- $addrList = MemberService::make()->getTriggerAddressList($triggerMin, $page, 200);
- if (empty($addrList)) {
- RedisService::set("caches:wallet:transferPage", 1, 600);
- $this->error = '1019';
- return false;
- }
- // 平台钱包地址
- $count = 0;
- $failedCount = 0;
- $tron = new Tron();
- $tron->setAddress($otcAddress);
- $otcAddress = $tron->getAddress();
- $otcAddressData = new \Tron\Address($otcAddress['base58'], $otcAddressPrivate, $otcAddress['hex']);
- // 平台出账钱包地址
- $tron->setAddress($otcOutAddress);
- $otcOutAddress = $tron->getAddress();
- $otcOutAddressData = new \Tron\Address($otcOutAddress['base58'], $otcOutAddressPrivate, $otcOutAddress['hex']);
- $cacheKey = "caches:wallet:trigger:";
- foreach ($addrList as $v) {
- try {
- // 获取子钱包TRC-USDT余额
- $userId = isset($v['id']) ? $v['id'] : 0;
- $address = isset($v['trc_address']) ? $v['trc_address'] : '';
- $hexAddress = isset($v['trc_hexaddress']) ? $v['trc_hexaddress'] : '';
- $addressPrivate = isset($v['trc_wif']) ? $v['trc_wif'] : '';
- $triggerAddress = new \Tron\Address($address, $addressPrivate, $hexAddress);
- // 可归集的USDT余额
- $triggerUsdt = $trcWallet->balance($triggerAddress);
- // USDT 余额低于归集金额,则不归集
- if ($triggerUsdt < $triggerMin) {
- $failedCount++;
- $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'error' => '用户余额不足归集', 'date' => date('Y-m-d H:i:s')];
- RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
- continue;
- }
- // 获取子钱包TRX余额
- $triggerTrx = $trxWallet->balance($triggerAddress);
- // 获取平台出账钱包TRX余额
- $otcOutTrxTotal = $trxWallet->balance($otcOutAddressData);
- // 如果子钱包和平台钱包TRX余额不足手续费,则不归集
- if ($triggerTrx < $triggerFree && $otcOutTrxTotal < $triggerFree) {
- $failedCount++;
- $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'otcTrx' => $otcOutTrxTotal, 'error' => '平台钱包手续费不足', 'date' => date('Y-m-d H:i:s')];
- RedisService::set($cacheKey . "U_{$userId}:error", $error, 7200);
- continue;
- }
- // 如果子钱包TRX不足手续费8个,平台TRX充足则自动充值后下次调用时归集
- if ($triggerTrx < $triggerFree) {
- $failedCount++;
- $result = $this->trxTransfer($address, $triggerFree);
- $error = ['data' => $v, 'usdt' => $triggerUsdt, 'triggerMin' => $triggerMin, 'triggerTrx' => $triggerTrx, 'transfer' => $result, 'error' => '归集钱包手续费不足,先充值', 'date' => date('Y-m-d H:i:s')];
- RedisService::set($cacheKey . "U_{$userId}:catch", $error, 7200);
- continue;
- }
- // 满足归集条件处理
- $result = $trcWallet->transfer($triggerAddress, $otcAddressData, $triggerUsdt);
- RedisService::set($cacheKey . "U_{$userId}:result", ['data' => $v, 'result' => $result, 'msg' => '归集已提交', 'date' => date('Y-m-d H:i:s')], 7200);
- $count++;
- } catch (\Exception $exception) {
- $failedCount++;
- RedisService::set($cacheKey . "U_{$userId}:exception", ['data' => $v, 'msg' => $exception->getMessage(), 'date' => date('Y-m-d H:i:s')], 7200);
- }
- }
- // 超出分页数,下次处理下一页
- if (count($addrList) >= 200) {
- RedisService::set("caches:wallet:transferPage", $page + 1, 600);
- }
- if ($count > 0) {
- return ['success' => $count, 'fail' => $failedCount];
- } else {
- $this->error = 1021;
- return false;
- }
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- }
|