123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668 |
- <?php
- namespace crmeb\services\blockchain;
- use app\models\lala\WalletLog;
- use app\models\user\UserMoney;
- use crmeb\basic\BaseModel;
- use GuzzleHttp\Client;
- use think\db\exception\DataNotFoundException;
- use think\db\exception\DbException;
- use think\db\exception\ModelNotFoundException;
- use think\facade\Log;
- use Tron\Address;
- use Tron\Api;
- use Tron\Exceptions\TronErrorException;
- use Tron\TRC20;
- use Tron\TRX;
- class BlockChianService
- {
- //TODO main
- /**
- * 生成地址
- * @param string $code
- * @return array
- */
- public static function createAddress(string $code): array
- {
- $code = strtoupper($code);
- if (method_exists(self::class, $code . 'CreateAddress')) {
- $function = $code . 'CreateAddress';
- return self::$function();
- } else {
- return ["privateKey" => "",
- "address" => "",
- "hexAddress" => ""];
- }
- }
- /**
- * 生成地址
- * @param string $code
- * @param string $address
- * @return float
- */
- public static function balance(string $code, string $address): float
- {
- $code = strtoupper($code);
- if (method_exists(self::class, $code . 'Balance')) {
- $function = $code . 'Balance';
- return self::$function($address);
- } else {
- return 0;
- }
- }
- /**
- * 归集
- * @param array $money_info
- * @param string $summary_address
- * @param Address $gas_address
- * @return bool
- */
- public static function summary(array $money_info, string $summary_address, Address $gas_address): bool
- {
- $code = strtoupper($money_info['money_type']);
- if (method_exists(self::class, $code . 'Summary')) {
- $function = $code . 'Summary';
- return self::$function($money_info, $summary_address, $gas_address);
- } else {
- Log::error('币种' . $code . '尚不支持归集');
- return true;
- }
- }
- /**
- * 交易
- * @param string $code
- * @param Address $from
- * @param Address $to
- * @param float $amount
- * @return bool
- */
- public static function transfer(string $code, Address $from, Address $to, float $amount): bool
- {
- $code = strtoupper($code);
- if (method_exists(self::class, $code . 'Transfer')) {
- $function = $code . 'Transfer';
- return self::$function($from, $to, $amount);
- } else {
- Log::error('币种' . $code . '尚不支持交易');
- return true;
- }
- }
- /**
- * 获取交易
- * @param string $code
- * @param $address
- * @param $start_time
- * @return array
- */
- public static function checkTransfer(string $code, $address, $start_time): array
- {
- $code = strtoupper($code);
- if (method_exists(self::class, $code . 'CheckTransfer')) {
- $function = $code . 'CheckTransfer';
- return self::$function($address, $start_time);
- } else {
- return [];
- }
- }
- /**
- * 查询交易
- * @param string $code
- * @param string $txID
- * @return array
- */
- public static function getTransfer(string $code, string $txID): array
- {
- $code = strtoupper($code);
- if (method_exists(self::class, $code . 'GetTransfer')) {
- $function = $code . 'GetTransfer';
- return self::$function($txID);
- } else {
- return [];
- }
- }
- //TODO main - end
- //TODO auto
- /**
- * 自动获取交易记录
- * @return bool
- */
- public static function autoGetTransfer(): bool
- {
- $address = UserMoney::select();
- foreach ($address as $v) {
- if ($v['address']) {
- $res = BlockChianService::checkTransfer($v['money_type'], $v['address'], $v['max_timestamp'] + 1);
- // var_dump($res);
- // BaseModel::rollbackTrans();
- // exit();
- if ($res) {
- // $max_timestamp = $v['max_timestamp'];
- switch ($v['money_type']) {
- case 'USDT':
- case 'LALA':
- if (isset($res['data'])) {
- foreach ($res['data'] as $vv) {
- // if ($vv['block_timestamp'] > $max_timestamp) {
- // $max_timestamp = $vv['block_timestamp'];
- // }
- $data = [
- 'symbol' => $v['money_type'],
- 'transaction_id' => $vv['transaction_id'],
- 'from' => $vv['from'],
- 'to' => $vv['to'],
- 'type' => $vv['type'],
- 'amount' => bcdiv($vv['value'], bcpow(10, $vv['token_info']['decimals']), 8),
- 'block_timestamp' => $vv['block_timestamp'],
- ];
- if (!WalletLog::be($data)) {
- WalletLog::beginTrans();
- try {
- WalletLog::create($data);
- WalletLog::commitTrans();
- } catch (\Exception $e) {
- WalletLog::rollbackTrans();
- Log::error('AutoLoadTransferFail:' . $e->getMessage());
- return false;
- }
- }
- }
- }
- break;
- default:
- break;
- }
- // }
- }
- UserMoney::beginTrans();
- // if ($max_timestamp != $v['max_timestamp']) {
- try {
- UserMoney::where('address', $v['address'])->update(['max_timestamp' => time() * 1000]);
- UserMoney::commitTrans();
- } catch (\Exception $e) {
- UserMoney::rollbackTrans();
- Log::error('AutoLoadTransferFail:' . $e->getMessage());
- return false;
- }
- }
- }
- return true;
- }
- /**
- * 自动确认交易
- * @return bool
- */
- public static function autoCheckTransfer(): bool
- {
- BaseModel::beginTrans();
- try {
- $list = WalletLog::where('state', 0)->select();
- foreach ($list as $v) {
- $res = BlockChianService::getTransfer($v['symbol'], $v['transaction_id']);
- if ($res['status']) {
- switch ($v['symbol']) {
- case 'USDT':
- case 'LALA':
- if (isset($res['data'])) {
- if (isset($res['data']->contractRet)) {
- if ($res['data']->contractRet === 'SUCCESS') {
- $update['state'] = 1;
- WalletLog::where('id', $v['id'])->update($update);
- $user = UserMoney::where('address', $v['to'])->where('money_type', $v['symbol'])->value('uid');
- if ($user) {
- UserMoney::incomeMoney($user, $v['symbol'], $v['amount'], 'recharge', '用户充值', '用户充值' . $v['amount'] . $v['symbol'], $v['id']);
- }
- } else {
- $update['state'] = 2;
- WalletLog::where('id', $v['id'])->update($update);
- }
- }
- }
- break;
- default:
- break;
- }
- }
- }
- BaseModel::commitTrans();
- return true;
- } catch (\Exception $e) {
- BaseModel::rollbackTrans();
- Log::error('AutoCheckTransferFail:' . $e->getMessage());
- return false;
- }
- }
- /**
- * 自动归集
- * @return bool
- * @throws DataNotFoundException
- * @throws DbException
- * @throws ModelNotFoundException
- */
- public function autoSummary(): bool
- {
- $money_types = sys_data('money_type');
- // var_dump($money_types);
- $res = true;
- foreach ($money_types as $v) {
- if ($v['charge']) {
- //TODO 接入链上充值
- //有交易记录的地址
- $addresses = UserMoney::where('max_timestamp', '>', 0)->select()->toArray();
- foreach ($addresses as $vv) {
- // var_dump($vv);
- $res = $res && self::summary($vv, $v['summary_address'], new Address($v['gas_address'], $v['gas_key']));
- }
- }
- }
- return $res;
- }
- //TODO auto - end
- //TODO USDT
- /**
- * USDT 创建地址
- * @return array
- */
- public static function USDTCreateAddress(): array
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
- 'decimals' => 6,
- ];
- $trxWallet = new TRC20($api, $config);
- $address = $trxWallet->generateAddress();
- return [
- 'privateKey' => $address->privateKey,
- 'address' => $address->address,
- 'hexAddress' => $address->hexAddress
- ];
- } catch (\Exception $e) {
- return [
- 'privateKey' => '',
- 'address' => '',
- 'hexAddress' => ''
- ];
- }
- }
- /**
- * USDT 余额
- * @param $address
- * @return float
- */
- public static function USDTBalance($address): float
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
- 'decimals' => 6,
- ];
- $trxWallet = new TRC20($api, $config);
- $balance = $trxWallet->balance(new Address($address));
- return (float)$balance;
- } catch (\Exception $e) {
- return 0;
- }
- }
- /**
- * USDT 交易
- * @param $from
- * @param $to
- * @param $amount
- * @return array
- */
- public static function USDTTransfer($from, $to, $amount): array
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
- 'decimals' => 6,
- ];
- $trxWallet = new TRC20($api, $config);
- $transfer = $trxWallet->transfer($from, $to, $amount);
- return ['msg' => 'success', 'data' => $transfer, 'status' => true];
- } catch (\Exception $e) {
- return ['msg' => $e->getMessage(), 'status' => false, 'data' => $e->getTrace()];
- }
- }
- /**
- * USDT 获取交易记录
- * @param $address
- * @param $start_time
- * @return array|mixed
- */
- public static function USDTCheckTransfer($address, $start_time)
- {
- try {
- $uri = "https://api.trongrid.io/v1/accounts/{$address}/transactions/trc20";
- $contract_address = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';// USDT TRC20
- return json_decode(do_request($uri, [
- 'min_timestamp' => $start_time,
- 'limit' => 200,
- 'contract_address' => $contract_address,
- 'order_by' => 'block_timestamp,asc'
- ], null, false), true);
- } catch (\Exception $e) {
- return ['msg' => $e->getMessage(), 'status' => false, 'data' => $e->getTrace()];
- }
- }
- /**
- * USDT 确认交易记录
- * @param $txID
- * @return array
- */
- public static function USDTGetTransfer($txID)
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
- 'decimals' => 6,
- ];
- $trxWallet = new TRC20($api, $config);
- $transfer = $trxWallet->transactionReceipt($txID);
- return ['msg' => 'success', 'data' => $transfer, 'status' => true];
- } catch (\Exception $e) {
- return ['msg' => $e->getMessage(), 'status' => false, 'data' => $e->getTrace()];
- }
- }
- /**
- * USDT 归集
- * @param $money_info
- * @param $summary_address
- * @param $gas_address
- * @return bool
- * @throws TronErrorException
- */
- public static function USDTSummary($money_info, $summary_address, $gas_address): bool
- {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',// USDT TRC20
- 'decimals' => 6,
- ];
- $trxWallet = new TRC20($api, $config);
- $address = new Address($money_info['address'], $money_info['privateKey'], $money_info['hexAddress']);
- $balance = $trxWallet->balance($address);
- //var_dump($balance);
- if ($balance > 0) {
- $trx = new TRX($api);
- $trx_balance = $trx->balance($address);
- //var_dump($trx_balance);
- if ($trx_balance < sys_config('trx_gas', 10)) {
- $trade_trx = ceil(10 - $trx_balance);
- //执行手续费转账
- $gas_trx_balance = $trx->balance($gas_address);
- if ($gas_trx_balance < $trade_trx + 2) {
- Log::error('USDT手续费账户余额不足');
- return false;
- }
- try {
- $res = $trx->transfer($gas_address, $address, $trade_trx);
- // var_dump($res);
- if (isset($res->txID)) {
- Log::error('转账TRX交易哈希:' . $res->txID);
- return true;
- } else {
- Log::error('转账TRX失败');
- return false;
- }
- } catch (\Exception $e) {
- Log::error('转账TRX失败' . $e->getMessage());
- return false;
- }
- } else {
- //执行转账
- try {
- $res = self::USDTTransfer($address, new Address($summary_address), $balance);
- // var_dump($res);
- if ($res['status']) {
- Log::error('转账交易哈希:' . $res['data']->txID);
- return true;
- } else {
- Log::error('转账失败' . $res['msg']);
- return false;
- }
- } catch (\Exception $e) {
- Log::error('转账失败' . $e->getMessage());
- return false;
- }
- }
- }
- return true;
- }
- //TODO USDT - end
- //TODO LALA
- /**
- * LALA 创建地址
- * @return array
- */
- public static function LALACreateAddress(): array
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TLuwWZ8MkB6FFJDLYc19u7d4tFq2GV3rPL',// LALA TRC20
- 'decimals' => 8,
- ];
- $trxWallet = new TRC20($api, $config);
- $address = $trxWallet->generateAddress();
- return [
- 'privateKey' => $address->privateKey,
- 'address' => $address->address,
- 'hexAddress' => $address->hexAddress
- ];
- } catch (\Exception $e) {
- return [
- 'privateKey' => '',
- 'address' => '',
- 'hexAddress' => ''
- ];
- }
- }
- /**
- * USDT 余额
- * @param $address
- * @return float
- */
- public static function LALABalance($address): float
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TLuwWZ8MkB6FFJDLYc19u7d4tFq2GV3rPL',// USDT TRC20
- 'decimals' => 8,
- ];
- $trxWallet = new TRC20($api, $config);
- $balance = $trxWallet->balance(new Address($address));
- return (float)$balance;
- } catch (\Exception $e) {
- return 0;
- }
- }
- /**
- * LALA 交易
- * @param $from
- * @param $to
- * @param $amount
- * @return array
- */
- public static function LALATransfer($from, $to, $amount): array
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TLuwWZ8MkB6FFJDLYc19u7d4tFq2GV3rPL',// LALA TRC20
- 'decimals' => 8,
- ];
- $trxWallet = new TRC20($api, $config);
- $transfer = $trxWallet->transfer($from, $to, $amount);
- return ['msg' => 'success', 'data' => $transfer, 'status' => true];
- } catch (\Exception $e) {
- return ['msg' => $e->getMessage(), 'status' => false, 'data' => $e->getTrace()];
- }
- }
- /**
- * LALA 获取交易记录
- * @param $address
- * @param $start_time
- * @return array
- */
- public static function LALACheckTransfer($address, $start_time)
- {
- try {
- $uri = "https://api.trongrid.io/v1/accounts/{$address}/transactions/trc20";
- $contract_address = 'TLuwWZ8MkB6FFJDLYc19u7d4tFq2GV3rPL';// LALA TRC20
- return json_decode(do_request($uri, [
- 'min_timestamp' => $start_time,
- 'limit' => 200,
- 'contract_address' => $contract_address,
- 'order_by' => 'block_timestamp,asc'
- ], null, false), true);
- } catch (\Exception $e) {
- return ['msg' => $e->getMessage(), 'status' => false, 'data' => $e->getTrace()];
- }
- }
- /**
- * LALA 确认交易
- * @param $txID
- * @return array
- */
- public static function LALAGetTransfer($txID)
- {
- try {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TLuwWZ8MkB6FFJDLYc19u7d4tFq2GV3rPL',// LALA TRC20
- 'decimals' => 8,
- ];
- $trxWallet = new TRC20($api, $config);
- $transfer = $trxWallet->transactionReceipt($txID);
- return ['msg' => 'success', 'data' => $transfer, 'status' => true];
- } catch (\Exception $e) {
- return ['msg' => $e->getMessage(), 'status' => false, 'data' => $e->getTrace()];
- }
- }
- /**
- * LALA 归集
- * @param $money_info
- * @param $summary_address
- * @param $gas_address
- * @return bool
- * @throws TronErrorException
- */
- public static function LALASummary($money_info, $summary_address, $gas_address): bool
- {
- $uri = 'https://api.trongrid.io';
- $api = new Api(new Client(['base_uri' => $uri]));
- $config = [
- 'contract_address' => 'TLuwWZ8MkB6FFJDLYc19u7d4tFq2GV3rPL',// LALA TRC20
- 'decimals' => 8,
- ];
- $trxWallet = new TRC20($api, $config);
- $address = new Address($money_info['address'], $money_info['privateKey'], $money_info['hexAddress']);
- $balance = $trxWallet->balance($address);
- //var_dump($balance);
- if ($balance > 0) {
- $trx = new TRX($api);
- $trx_balance = $trx->balance($address);
- //var_dump($trx_balance);
- if ($trx_balance < sys_config('trx_gas', 10)) {
- $trade_trx = ceil(10 - $trx_balance);
- //执行手续费转账
- $gas_trx_balance = $trx->balance($gas_address);
- if ($gas_trx_balance < $trade_trx + 2) {
- Log::error('LALA手续费账户余额不足');
- return false;
- }
- try {
- $res = $trx->transfer($gas_address, $address, $trade_trx);
- // var_dump($res);
- if (isset($res->txID)) {
- Log::error('转账TRX交易哈希:' . $res->txID);
- return true;
- } else {
- Log::error('转账TRX失败');
- return false;
- }
- } catch (\Exception $e) {
- Log::error('转账TRX失败' . $e->getMessage());
- return false;
- }
- } else {
- //执行转账
- try {
- $res = self::LALATransfer($address, new Address($summary_address), $balance);
- // var_dump($res);
- if ($res['status']) {
- Log::error('转账交易哈希:' . $res['data']->txID);
- return true;
- } else {
- Log::error('转账失败' . $res['msg']);
- return false;
- }
- } catch (\Exception $e) {
- Log::error('转账失败' . $e->getMessage());
- return false;
- }
- }
- }
- return true;
- }
- //TODO LALA - end
- }
|