Added pool hashrate chart

This commit is contained in:
nymkappa 2022-03-08 12:50:47 +01:00
parent 0cc82bbf1d
commit ad2dcc46e4
No known key found for this signature in database
GPG key ID: E155910B16E8BD04
7 changed files with 228 additions and 55 deletions

View file

@ -299,6 +299,7 @@ class Server {
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pools/2y', routes.$getPools.bind(routes, '2y'))
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pools/3y', routes.$getPools.bind(routes, '3y'))
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pools/all', routes.$getPools.bind(routes, 'all'))
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId/hashrate/:interval', routes.$getPoolHistoricalHashrate)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId/blocks', routes.$getPoolBlocks)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId/blocks/:height', routes.$getPoolBlocks)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId', routes.$getPool)

View file

@ -116,6 +116,41 @@ class HashratesRepository {
}
}
/**
* Returns a pool hashrate history
*/
public async $getPoolWeeklyHashrate(interval: string | null, poolId: number): Promise<any[]> {
interval = Common.getSqlInterval(interval);
const connection = await DB.pool.getConnection();
let query = `SELECT UNIX_TIMESTAMP(hashrate_timestamp) as timestamp, avg_hashrate as avgHashrate, share, pools.name as poolName
FROM hashrates
JOIN pools on pools.id = pool_id`;
if (interval) {
query += ` WHERE hashrate_timestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()
AND hashrates.type = 'weekly'
AND pool_id = ${poolId}`;
} else {
query += ` WHERE hashrates.type = 'weekly'
AND pool_id = ${poolId}`;
}
query += ` ORDER by hashrate_timestamp`;
try {
const [rows]: any[] = await connection.query(query);
connection.release();
return rows;
} catch (e) {
connection.release();
logger.err('$getPoolWeeklyHashrate() error' + (e instanceof Error ? e.message : e));
throw e;
}
}
public async $setLatestRunTimestamp(key: string, val: any = null) {
const connection = await DB.pool.getConnection();
const query = `UPDATE state SET number = ? WHERE name = ?`;

View file

@ -603,6 +603,22 @@ class Routes {
}
}
public async $getPoolHistoricalHashrate(req: Request, res: Response) {
try {
const hashrates = await HashratesRepository.$getPoolWeeklyHashrate(req.params.interval ?? null, parseInt(req.params.poolId, 10));
const oldestIndexedBlockTimestamp = await BlocksRepository.$oldestBlockTimestamp();
res.header('Pragma', 'public');
res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 300).toUTCString());
res.json({
oldestIndexedBlockTimestamp: oldestIndexedBlockTimestamp,
hashrates: hashrates,
});
} catch (e) {
res.status(500).send(e instanceof Error ? e.message : e);
}
}
public async $getHistoricalHashrate(req: Request, res: Response) {
try {
const hashrates = await HashratesRepository.$getNetworkDailyHashrate(req.params.interval ?? null);

View file

@ -1,30 +1,16 @@
<div class="container">
<div *ngIf="poolStats$ | async as poolStats">
<div style="display: flex; justify-content: space-between; flex-wrap: wrap;">
<h1 class="m-0">
<img width="50" src="{{ poolStats['logo'] }}" onError="this.src = './resources/mining-pools/default.svg'" class="mr-3">
<img width="50" src="{{ poolStats['logo'] }}" onError="this.src = './resources/mining-pools/default.svg'"
class="mr-3">
{{ poolStats.pool.name }}
</h1>
<div class="box pl-0 bg-transparent">
<div class="pl-0 bg-transparent">
<div class="card-header mb-0 mb-lg-4 pr-0 pl-0">
<form [formGroup]="radioGroupForm" class="formRadioGroup ml-0">
<div class="btn-group btn-group-toggle" ngbRadioGroup name="radioBasic" formControlName="dateSpan">
<label ngbButtonLabel class="btn-primary btn-sm">
<input ngbButton type="radio" [value]="'24h'"> 24h
</label>
<label ngbButtonLabel class="btn-primary btn-sm">
<input ngbButton type="radio" [value]="'3d'"> 3D
</label>
<label ngbButtonLabel class="btn-primary btn-sm">
<input ngbButton type="radio" [value]="'1w'"> 1W
</label>
<label ngbButtonLabel class="btn-primary btn-sm">
<input ngbButton type="radio" [value]="'1m'"> 1M
</label>
<label ngbButtonLabel class="btn-primary btn-sm">
<input ngbButton type="radio" [value]="'3m'"> 3M
</label>
<label ngbButtonLabel class="btn-primary btn-sm">
<input ngbButton type="radio" [value]="'6m'"> 6M
</label>
@ -44,6 +30,7 @@
</form>
</div>
</div>
</div>
<div class="box">
<div class="row">
@ -54,10 +41,13 @@
<td class="col-4 col-lg-3">Addresses</td>
<td class="text-truncate" *ngIf="poolStats.pool.addresses.length else noaddress">
<div class="scrollable">
<a *ngFor="let address of poolStats.pool.addresses" [routerLink]="['/address' | relativeUrl, address]">{{ address }}<br></a>
<a *ngFor="let address of poolStats.pool.addresses"
[routerLink]="['/address' | relativeUrl, address]">{{ address }}<br></a>
</div>
</td>
<ng-template #noaddress><td>~</td></ng-template>
<ng-template #noaddress>
<td>~</td>
</ng-template>
</tr>
<tr>
<td class="col-4 col-lg-3">Coinbase Tags</td>
@ -84,7 +74,13 @@
</div>
</div>
<table class="table table-borderless" [alwaysCallback]="true" infiniteScroll [infiniteScrollDistance]="1.5" [infiniteScrollUpDistance]="1.5" [infiniteScrollThrottle]="50" (scrolled)="loadMore()">
<div class="chart" echarts [initOpts]="chartInitOptions" [options]="chartOptions"></div>
<div class="text-center loadingGraphs" *ngIf="isLoading">
<div class="spinner-border text-light"></div>
</div>
<table class="table table-borderless" [alwaysCallback]="true" infiniteScroll [infiniteScrollDistance]="1.5"
[infiniteScrollUpDistance]="1.5" [infiniteScrollThrottle]="50" (scrolled)="loadMore()">
<thead>
<th style="width: 15%;" i18n="latest-blocks.height">Height</th>
<th class="d-none d-md-block" style="width: 20%;" i18n="latest-blocks.timestamp">Timestamp</th>
@ -97,12 +93,17 @@
<tr *ngFor="let block of blocks">
<td><a [routerLink]="['/block' | relativeUrl, block.id]">{{ block.height }}</a></td>
<td class="d-none d-md-block">&lrm;{{ block.timestamp * 1000 | date:'yyyy-MM-dd HH:mm' }}</td>
<td><app-time-since [time]="block.timestamp" [fastRender]="true"></app-time-since></td>
<td class=""><app-amount [satoshis]="block['reward']" digitsInfo="1.2-2" [noFiat]="true"></app-amount></td>
<td>
<app-time-since [time]="block.timestamp" [fastRender]="true"></app-time-since>
</td>
<td class="">
<app-amount [satoshis]="block['reward']" digitsInfo="1.2-2" [noFiat]="true"></app-amount>
</td>
<td class="d-none d-lg-block">{{ block.tx_count | number }}</td>
<td>
<div class="progress">
<div class="progress-bar progress-mempool" role="progressbar" [ngStyle]="{'width': (block.weight / stateService.env.BLOCK_WEIGHT_UNITS)*100 + '%' }"></div>
<div class="progress-bar progress-mempool" role="progressbar"
[ngStyle]="{'width': (block.weight / stateService.env.BLOCK_WEIGHT_UNITS)*100 + '%' }"></div>
<div class="progress-text" [innerHTML]="block.size | bytes: 2"></div>
</div>
</td>

View file

@ -18,9 +18,8 @@
display: flex;
flex-direction: column;
@media (min-width: 830px) {
margin-left: 2%;
flex-direction: row;
float: left;
float: right;
margin-top: 0px;
}
.btn-sm {

View file

@ -1,11 +1,14 @@
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ChangeDetectionStrategy, Component, Inject, Input, LOCALE_ID, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { EChartsOption, graphic } from 'echarts';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { distinctUntilChanged, map, startWith, switchMap, tap } from 'rxjs/operators';
import { distinctUntilChanged, map, startWith, switchMap, tap, toArray } from 'rxjs/operators';
import { BlockExtended, PoolStat } from 'src/app/interfaces/node-api.interface';
import { ApiService } from 'src/app/services/api.service';
import { StateService } from 'src/app/services/state.service';
import { selectPowerOfTen } from 'src/app/bitcoin.utils';
import { formatNumber } from '@angular/common';
@Component({
selector: 'app-pool',
@ -14,34 +17,57 @@ import { StateService } from 'src/app/services/state.service';
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PoolComponent implements OnInit {
@Input() right: number | string = 45;
@Input() left: number | string = 75;
poolStats$: Observable<PoolStat>;
blocks$: Observable<BlockExtended[]>;
isLoading = true;
radioGroupForm: FormGroup;
chartOptions: EChartsOption = {};
chartInitOptions = {
renderer: 'svg',
width: 'auto',
height: 'auto',
};
fromHeight: number = -1;
fromHeightSubject: BehaviorSubject<number> = new BehaviorSubject(this.fromHeight);
blocks: BlockExtended[] = [];
poolId: number = undefined;
radioGroupForm: FormGroup;
constructor(
@Inject(LOCALE_ID) public locale: string,
private apiService: ApiService,
private route: ActivatedRoute,
public stateService: StateService,
private formBuilder: FormBuilder,
) {
this.radioGroupForm = this.formBuilder.group({ dateSpan: '1w' });
this.radioGroupForm.controls.dateSpan.setValue('1w');
this.radioGroupForm = this.formBuilder.group({ dateSpan: 'all' });
this.radioGroupForm.controls.dateSpan.setValue('all');
}
ngOnInit(): void {
this.poolStats$ = combineLatest([
this.route.params.pipe(map((params) => params.poolId)),
this.radioGroupForm.get('dateSpan').valueChanges.pipe(startWith('1w')),
this.radioGroupForm.get('dateSpan').valueChanges.pipe(startWith('all')),
])
.pipe(
switchMap((params: any) => {
this.poolId = params[0];
return this.apiService.getPoolHashrate$(this.poolId, params[1] ?? 'all')
.pipe(
switchMap((data) => {
this.prepareChartOptions(data.hashrates.map(val => [val.timestamp * 1000, val.avgHashrate]));
return params;
}),
toArray(),
)
}),
switchMap((params: any) => {
if (this.blocks.length === 0) {
this.fromHeightSubject.next(undefined);
}
@ -55,6 +81,7 @@ export class PoolComponent implements OnInit {
poolStats.pool.regexes = regexes.slice(0, -3);
poolStats.pool.addresses = poolStats.pool.addresses;
this.isLoading = false;
return Object.assign({
logo: `./resources/mining-pools/` + poolStats.pool.name.toLowerCase().replace(' ', '').replace('.', '') + '.svg'
}, poolStats);
@ -74,6 +101,96 @@ export class PoolComponent implements OnInit {
)
}
prepareChartOptions(data) {
this.chartOptions = {
animation: false,
color: [
new graphic.LinearGradient(0, 0, 0, 0.65, [
{ offset: 0, color: '#F4511E' },
{ offset: 0.25, color: '#FB8C00' },
{ offset: 0.5, color: '#FFB300' },
{ offset: 0.75, color: '#FDD835' },
{ offset: 1, color: '#7CB342' }
]),
'#D81B60',
],
grid: {
right: this.right,
left: this.left,
bottom: 60,
},
tooltip: {
show: !this.isMobile(),
trigger: 'axis',
axisPointer: {
type: 'line'
},
backgroundColor: 'rgba(17, 19, 31, 1)',
borderRadius: 4,
shadowColor: 'rgba(0, 0, 0, 0.5)',
textStyle: {
color: '#b1b1b1',
align: 'left',
},
borderColor: '#000',
formatter: function (data) {
let hashratePowerOfTen: any = selectPowerOfTen(1);
let hashrate = data[0].data[1];
if (this.isMobile()) {
hashratePowerOfTen = selectPowerOfTen(data[0].data[1]);
hashrate = Math.round(data[0].data[1] / hashratePowerOfTen.divider);
}
return `
<b style="color: white; margin-left: 18px">${data[0].axisValueLabel}</b><br>
<span>${data[0].marker} ${data[0].seriesName}: ${formatNumber(hashrate, this.locale, '1.0-0')} ${hashratePowerOfTen.unit}H/s</span><br>
`;
}.bind(this)
},
xAxis: {
type: 'time',
splitNumber: (this.isMobile()) ? 5 : 10,
},
yAxis: [
{
min: function (value) {
return value.min * 0.9;
},
type: 'value',
name: 'Hashrate',
axisLabel: {
color: 'rgb(110, 112, 121)',
formatter: (val) => {
const selectedPowerOfTen: any = selectPowerOfTen(val);
const newVal = Math.round(val / selectedPowerOfTen.divider);
return `${newVal} ${selectedPowerOfTen.unit}H/s`
}
},
splitLine: {
show: false,
}
},
],
series: [
{
name: 'Hashrate',
showSymbol: false,
symbol: 'none',
data: data,
type: 'line',
lineStyle: {
width: 2,
},
},
],
};
}
isMobile() {
return (window.innerWidth <= 767.98);
}
loadMore() {
this.fromHeightSubject.next(this.blocks[this.blocks.length - 1]?.height);
}

View file

@ -143,6 +143,10 @@ export class ApiService {
);
}
getPoolHashrate$(poolId: number, interval: string | undefined): Observable<any> {
return this.httpClient.get<any>(this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${poolId}/hashrate/${interval}`);
}
getPoolBlocks$(poolId: number, fromHeight: number): Observable<BlockExtended[]> {
return this.httpClient.get<BlockExtended[]>(
this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${poolId}/blocks` +