Merge pull request #1456 from mempool/nymkappa/feature/pool-slug-url

Use mining pool slug in urls
This commit is contained in:
softsimon 2022-03-26 11:07:48 +04:00 committed by GitHub
commit dc9ef154d4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 75 additions and 54 deletions

View file

@ -137,7 +137,8 @@ class Blocks {
} }
blockExtended.extras.pool = { blockExtended.extras.pool = {
id: pool.id, id: pool.id,
name: pool.name name: pool.name,
slug: pool.slug,
}; };
} }

View file

@ -33,7 +33,8 @@ class Mining {
link: poolInfo.link, link: poolInfo.link,
blockCount: poolInfo.blockCount, blockCount: poolInfo.blockCount,
rank: rank++, rank: rank++,
emptyBlocks: emptyBlocksCount.length > 0 ? emptyBlocksCount[0]['count'] : 0 emptyBlocks: emptyBlocksCount.length > 0 ? emptyBlocksCount[0]['count'] : 0,
slug: poolInfo.slug,
}; };
poolsStats.push(poolStat); poolsStats.push(poolStat);
}); });
@ -54,14 +55,14 @@ class Mining {
/** /**
* Get all mining pool stats for a pool * Get all mining pool stats for a pool
*/ */
public async $getPoolStat(poolId: number): Promise<object> { public async $getPoolStat(slug: string): Promise<object> {
const pool = await PoolsRepository.$getPool(poolId); const pool = await PoolsRepository.$getPool(slug);
if (!pool) { if (!pool) {
throw new Error(`This mining pool does not exist`); throw new Error(`This mining pool does not exist`);
} }
const blockCount: number = await BlocksRepository.$blockCount(poolId); const blockCount: number = await BlocksRepository.$blockCount(pool.id);
const emptyBlocksCount = await BlocksRepository.$countEmptyBlocks(poolId); const emptyBlocksCount = await BlocksRepository.$countEmptyBlocks(pool.id);
return { return {
pool: pool, pool: pool,

View file

@ -301,11 +301,11 @@ class Server {
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pools/2y', routes.$getPools.bind(routes, '2y')) .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/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/pools/all', routes.$getPools.bind(routes, 'all'))
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId/hashrate', routes.$getPoolHistoricalHashrate) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:slug/hashrate', routes.$getPoolHistoricalHashrate)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId/blocks', routes.$getPoolBlocks) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:slug/blocks', routes.$getPoolBlocks)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId/blocks/:height', routes.$getPoolBlocks) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:slug/blocks/:height', routes.$getPoolBlocks)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId', routes.$getPool) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:slug', routes.$getPool)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:poolId/:interval', routes.$getPool) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/pool/:slug/:interval', routes.$getPool)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/difficulty', routes.$getHistoricalDifficulty) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/difficulty', routes.$getHistoricalDifficulty)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/difficulty/:interval', routes.$getHistoricalDifficulty) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/difficulty/:interval', routes.$getHistoricalDifficulty)
.get(config.MEMPOOL.API_URL_PREFIX + 'mining/hashrate/pools', routes.$getPoolsHistoricalHashrate) .get(config.MEMPOOL.API_URL_PREFIX + 'mining/hashrate/pools', routes.$getPoolsHistoricalHashrate)

View file

@ -6,6 +6,7 @@ export interface PoolTag {
link: string; link: string;
regexes: string; // JSON array regexes: string; // JSON array
addresses: string; // JSON array addresses: string; // JSON array
slug: string;
} }
export interface PoolInfo { export interface PoolInfo {
@ -13,6 +14,7 @@ export interface PoolInfo {
name: string; name: string;
link: string; link: string;
blockCount: number; blockCount: number;
slug: string;
} }
export interface PoolStats extends PoolInfo { export interface PoolStats extends PoolInfo {
@ -87,6 +89,7 @@ export interface BlockExtension {
pool?: { pool?: {
id: number; id: number;
name: string; name: string;
slug: string;
}; };
avgFee?: number; avgFee?: number;
avgFeeRate?: number; avgFeeRate?: number;

View file

@ -3,6 +3,7 @@ import { DB } from '../database';
import logger from '../logger'; import logger from '../logger';
import { Common } from '../api/common'; import { Common } from '../api/common';
import { prepareBlock } from '../utils/blocks-utils'; import { prepareBlock } from '../utils/blocks-utils';
import PoolsRepository from './PoolsRepository';
class BlocksRepository { class BlocksRepository {
/** /**
@ -235,13 +236,18 @@ class BlocksRepository {
/** /**
* Get blocks mined by a specific mining pool * Get blocks mined by a specific mining pool
*/ */
public async $getBlocksByPool(poolId: number, startHeight: number | undefined = undefined): Promise<object[]> { public async $getBlocksByPool(slug: string, startHeight: number | undefined = undefined): Promise<object[]> {
const pool = await PoolsRepository.$getPool(slug);
if (!pool) {
throw new Error(`This mining pool does not exist`);
}
const params: any[] = []; const params: any[] = [];
let query = ` SELECT *, UNIX_TIMESTAMP(blocks.blockTimestamp) as blockTimestamp, let query = ` SELECT *, UNIX_TIMESTAMP(blocks.blockTimestamp) as blockTimestamp,
previous_block_hash as previousblockhash previous_block_hash as previousblockhash
FROM blocks FROM blocks
WHERE pool_id = ?`; WHERE pool_id = ?`;
params.push(poolId); params.push(pool.id);
if (startHeight !== undefined) { if (startHeight !== undefined) {
query += ` AND height < ?`; query += ` AND height < ?`;
@ -277,7 +283,7 @@ class BlocksRepository {
try { try {
const [rows]: any[] = await connection.query(` const [rows]: any[] = await connection.query(`
SELECT *, UNIX_TIMESTAMP(blocks.blockTimestamp) as blockTimestamp, SELECT *, UNIX_TIMESTAMP(blocks.blockTimestamp) as blockTimestamp,
pools.id as pool_id, pools.name as pool_name, pools.link as pool_link, pools.id as pool_id, pools.name as pool_name, pools.link as pool_link, pools.slug as pool_slug,
pools.addresses as pool_addresses, pools.regexes as pool_regexes, pools.addresses as pool_addresses, pools.regexes as pool_regexes,
previous_block_hash as previousblockhash previous_block_hash as previousblockhash
FROM blocks FROM blocks

View file

@ -120,8 +120,11 @@ class HashratesRepository {
/** /**
* Returns a pool hashrate history * Returns a pool hashrate history
*/ */
public async $getPoolWeeklyHashrate(poolId: number): Promise<any[]> { public async $getPoolWeeklyHashrate(slug: string): Promise<any[]> {
const connection = await DB.getConnection(); const pool = await PoolsRepository.$getPool(slug);
if (!pool) {
throw new Error(`This mining pool does not exist`);
}
// Find hashrate boundaries // Find hashrate boundaries
let query = `SELECT MIN(hashrate_timestamp) as firstTimestamp, MAX(hashrate_timestamp) as lastTimestamp let query = `SELECT MIN(hashrate_timestamp) as firstTimestamp, MAX(hashrate_timestamp) as lastTimestamp
@ -134,8 +137,11 @@ class HashratesRepository {
firstTimestamp: '1970-01-01', firstTimestamp: '1970-01-01',
lastTimestamp: '9999-01-01' lastTimestamp: '9999-01-01'
}; };
let connection;
try { try {
const [rows]: any[] = await connection.query(query, [poolId]); connection = await DB.getConnection();
const [rows]: any[] = await connection.query(query, [pool.id]);
boundaries = rows[0]; boundaries = rows[0];
connection.release(); connection.release();
} catch (e) { } catch (e) {
@ -152,7 +158,7 @@ class HashratesRepository {
ORDER by hashrate_timestamp`; ORDER by hashrate_timestamp`;
try { try {
const [rows]: any[] = await connection.query(query, [boundaries.firstTimestamp, boundaries.lastTimestamp, poolId]); const [rows]: any[] = await connection.query(query, [boundaries.firstTimestamp, boundaries.lastTimestamp, pool.id]);
connection.release(); connection.release();
return rows; return rows;

View file

@ -9,7 +9,7 @@ class PoolsRepository {
*/ */
public async $getPools(): Promise<PoolTag[]> { public async $getPools(): Promise<PoolTag[]> {
const connection = await DB.getConnection(); const connection = await DB.getConnection();
const [rows] = await connection.query('SELECT id, name, addresses, regexes FROM pools;'); const [rows] = await connection.query('SELECT id, name, addresses, regexes, slug FROM pools;');
connection.release(); connection.release();
return <PoolTag[]>rows; return <PoolTag[]>rows;
} }
@ -19,7 +19,7 @@ class PoolsRepository {
*/ */
public async $getUnknownPool(): Promise<PoolTag> { public async $getUnknownPool(): Promise<PoolTag> {
const connection = await DB.getConnection(); const connection = await DB.getConnection();
const [rows] = await connection.query('SELECT id, name FROM pools where name = "Unknown"'); const [rows] = await connection.query('SELECT id, name, slug FROM pools where name = "Unknown"');
connection.release(); connection.release();
return <PoolTag>rows[0]; return <PoolTag>rows[0];
} }
@ -30,7 +30,7 @@ class PoolsRepository {
public async $getPoolsInfo(interval: string | null = null): Promise<PoolInfo[]> { public async $getPoolsInfo(interval: string | null = null): Promise<PoolInfo[]> {
interval = Common.getSqlInterval(interval); interval = Common.getSqlInterval(interval);
let query = `SELECT COUNT(height) as blockCount, pool_id as poolId, pools.name as name, pools.link as link let query = `SELECT COUNT(height) as blockCount, pool_id as poolId, pools.name as name, pools.link as link, slug
FROM blocks FROM blocks
JOIN pools on pools.id = pool_id`; JOIN pools on pools.id = pool_id`;
@ -80,16 +80,17 @@ class PoolsRepository {
/** /**
* Get mining pool statistics for one pool * Get mining pool statistics for one pool
*/ */
public async $getPool(poolId: any): Promise<object> { public async $getPool(slug: string): Promise<PoolTag> {
const query = ` const query = `
SELECT * SELECT *
FROM pools FROM pools
WHERE pools.id = ?`; WHERE pools.slug = ?`;
// logger.debug(query); let connection;
const connection = await DB.getConnection();
try { try {
const [rows] = await connection.query(query, [poolId]); connection = await DB.getConnection();
const [rows] = await connection.query(query, [slug]);
connection.release(); connection.release();
rows[0].regexes = JSON.parse(rows[0].regexes); rows[0].regexes = JSON.parse(rows[0].regexes);

View file

@ -539,7 +539,7 @@ class Routes {
public async $getPool(req: Request, res: Response) { public async $getPool(req: Request, res: Response) {
try { try {
const stats = await mining.$getPoolStat(parseInt(req.params.poolId, 10)); const stats = await mining.$getPoolStat(req.params.slug);
res.header('Pragma', 'public'); res.header('Pragma', 'public');
res.header('Cache-control', 'public'); res.header('Cache-control', 'public');
res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString()); res.setHeader('Expires', new Date(Date.now() + 1000 * 60).toUTCString());
@ -552,7 +552,7 @@ class Routes {
public async $getPoolBlocks(req: Request, res: Response) { public async $getPoolBlocks(req: Request, res: Response) {
try { try {
const poolBlocks = await BlocksRepository.$getBlocksByPool( const poolBlocks = await BlocksRepository.$getBlocksByPool(
parseInt(req.params.poolId, 10), req.params.slug,
req.params.height === undefined ? undefined : parseInt(req.params.height, 10), req.params.height === undefined ? undefined : parseInt(req.params.height, 10),
); );
res.header('Pragma', 'public'); res.header('Pragma', 'public');
@ -606,7 +606,7 @@ class Routes {
public async $getPoolHistoricalHashrate(req: Request, res: Response) { public async $getPoolHistoricalHashrate(req: Request, res: Response) {
try { try {
const hashrates = await HashratesRepository.$getPoolWeeklyHashrate(parseInt(req.params.poolId, 10)); const hashrates = await HashratesRepository.$getPoolWeeklyHashrate(req.params.slug);
const oldestIndexedBlockTimestamp = await BlocksRepository.$oldestBlockTimestamp(); const oldestIndexedBlockTimestamp = await BlocksRepository.$oldestBlockTimestamp();
res.header('Pragma', 'public'); res.header('Pragma', 'public');
res.header('Cache-control', 'public'); res.header('Cache-control', 'public');

View file

@ -23,6 +23,7 @@ export function prepareBlock(block: any): BlockExtended {
pool: block?.extras?.pool ?? (block?.pool_id ? { pool: block?.extras?.pool ?? (block?.pool_id ? {
id: block.pool_id, id: block.pool_id,
name: block.pool_name, name: block.pool_name,
slug: block.pool_slug,
} : undefined), } : undefined),
} }
}; };

View file

@ -85,7 +85,7 @@ let routes: Routes = [
path: 'pool', path: 'pool',
children: [ children: [
{ {
path: ':poolId', path: ':slug',
component: PoolComponent, component: PoolComponent,
}, },
] ]
@ -227,7 +227,7 @@ let routes: Routes = [
path: 'pool', path: 'pool',
children: [ children: [
{ {
path: ':poolId', path: ':slug',
component: PoolComponent, component: PoolComponent,
}, },
] ]
@ -363,7 +363,7 @@ let routes: Routes = [
path: 'pool', path: 'pool',
children: [ children: [
{ {
path: ':poolId', path: ':slug',
component: PoolComponent, component: PoolComponent,
}, },
] ]

View file

@ -25,7 +25,7 @@
<div class="time-difference"><app-time-since [time]="block.timestamp" [fastRender]="true"></app-time-since></div> <div class="time-difference"><app-time-since [time]="block.timestamp" [fastRender]="true"></app-time-since></div>
</div> </div>
<div class="animated" [class]="showMiningInfo ? 'show' : 'hide'" *ngIf="block.extras?.pool != undefined"> <div class="animated" [class]="showMiningInfo ? 'show' : 'hide'" *ngIf="block.extras?.pool != undefined">
<a class="badge badge-primary" [routerLink]="[('/mining/pool/' + block.extras.pool.id) | relativeUrl]"> <a class="badge badge-primary" [routerLink]="[('/mining/pool/' + block.extras.pool.slug) | relativeUrl]">
{{ block.extras.pool.name}}</a> {{ block.extras.pool.name}}</a>
</div> </div>
</div> </div>

View file

@ -85,7 +85,7 @@
<td class="d-none d-md-block">{{ pool.rank }}</td> <td class="d-none d-md-block">{{ pool.rank }}</td>
<td class="text-right"><img width="25" height="25" src="{{ pool.logo }}" <td class="text-right"><img width="25" height="25" src="{{ pool.logo }}"
onError="this.src = './resources/mining-pools/default.svg'"></td> onError="this.src = './resources/mining-pools/default.svg'"></td>
<td class=""><a [routerLink]="[('/mining/pool/' + pool.poolId) | relativeUrl]">{{ pool.name }}</a></td> <td class=""><a [routerLink]="[('/mining/pool/' + pool.slug) | relativeUrl]">{{ pool.name }}</a></td>
<td class="" *ngIf="this.poolsWindowPreference === '24h' && !isLoading">{{ pool.lastEstimatedHashrate }} {{ <td class="" *ngIf="this.poolsWindowPreference === '24h' && !isLoading">{{ pool.lastEstimatedHashrate }} {{
miningStats.miningUnits.hashrateUnit }}</td> miningStats.miningUnits.hashrateUnit }}</td>
<td class="">{{ pool['blockText'] }}</td> <td class="">{{ pool['blockText'] }}</td>

View file

@ -158,7 +158,7 @@ export class PoolRankingComponent implements OnInit {
} }
} }
}, },
data: pool.poolId, data: pool.slug,
} as PieSeriesOption); } as PieSeriesOption);
}); });

View file

@ -30,9 +30,9 @@ export class PoolComponent implements OnInit {
}; };
blocks: BlockExtended[] = []; blocks: BlockExtended[] = [];
poolId: number = undefined; slug: string = undefined;
loadMoreSubject: BehaviorSubject<number> = new BehaviorSubject(this.poolId); loadMoreSubject: BehaviorSubject<string> = new BehaviorSubject(this.slug);
constructor( constructor(
@Inject(LOCALE_ID) public locale: string, @Inject(LOCALE_ID) public locale: string,
@ -43,23 +43,23 @@ export class PoolComponent implements OnInit {
} }
ngOnInit(): void { ngOnInit(): void {
this.poolStats$ = this.route.params.pipe(map((params) => params.poolId)) this.poolStats$ = this.route.params.pipe(map((params) => params.slug))
.pipe( .pipe(
switchMap((poolId: any) => { switchMap((slug: any) => {
this.isLoading = true; this.isLoading = true;
this.poolId = poolId; this.slug = slug;
this.loadMoreSubject.next(this.poolId); this.loadMoreSubject.next(this.slug);
return this.apiService.getPoolHashrate$(this.poolId) return this.apiService.getPoolHashrate$(this.slug)
.pipe( .pipe(
switchMap((data) => { switchMap((data) => {
this.isLoading = false; this.isLoading = false;
this.prepareChartOptions(data.hashrates.map(val => [val.timestamp * 1000, val.avgHashrate])); this.prepareChartOptions(data.hashrates.map(val => [val.timestamp * 1000, val.avgHashrate]));
return poolId; return slug;
}), }),
); );
}), }),
switchMap(() => { switchMap(() => {
return this.apiService.getPoolStats$(this.poolId); return this.apiService.getPoolStats$(this.slug);
}), }),
map((poolStats) => { map((poolStats) => {
let regexes = '"'; let regexes = '"';
@ -78,10 +78,10 @@ export class PoolComponent implements OnInit {
this.blocks$ = this.loadMoreSubject this.blocks$ = this.loadMoreSubject
.pipe( .pipe(
switchMap((flag) => { switchMap((flag) => {
if (this.poolId === undefined) { if (this.slug === undefined) {
return []; return [];
} }
return this.apiService.getPoolBlocks$(this.poolId, this.blocks[this.blocks.length - 1]?.height); return this.apiService.getPoolBlocks$(this.slug, this.blocks[this.blocks.length - 1]?.height);
}), }),
tap((newBlocks) => { tap((newBlocks) => {
this.blocks = this.blocks.concat(newBlocks); this.blocks = this.blocks.concat(newBlocks);
@ -180,7 +180,7 @@ export class PoolComponent implements OnInit {
} }
loadMore() { loadMore() {
this.loadMoreSubject.next(this.poolId); this.loadMoreSubject.next(this.slug);
} }
trackByBlock(index: number, block: BlockExtended) { trackByBlock(index: number, block: BlockExtended) {

View file

@ -120,7 +120,7 @@
<td class="table-cell-height" ><a [routerLink]="['/block' | relativeUrl, block.id]" [state]="{ data: { block: block } }">{{ block.height }}</a></td> <td class="table-cell-height" ><a [routerLink]="['/block' | relativeUrl, block.id]" [state]="{ data: { block: block } }">{{ block.height }}</a></td>
<td *ngIf="!stateService.env.MINING_DASHBOARD" class="table-cell-mined" ><app-time-since [time]="block.timestamp" [fastRender]="true"></app-time-since></td> <td *ngIf="!stateService.env.MINING_DASHBOARD" class="table-cell-mined" ><app-time-since [time]="block.timestamp" [fastRender]="true"></app-time-since></td>
<td *ngIf="stateService.env.MINING_DASHBOARD" class="table-cell-mined pl-lg-4"> <td *ngIf="stateService.env.MINING_DASHBOARD" class="table-cell-mined pl-lg-4">
<a class="clear-link" [routerLink]="[('/mining/pool/' + block.extras.pool.id) | relativeUrl]"> <a class="clear-link" [routerLink]="[('/mining/pool/' + block.extras.pool.slug) | relativeUrl]">
<img width="20" height="20" src="{{ block.extras.pool['logo'] }}" <img width="20" height="20" src="{{ block.extras.pool['logo'] }}"
onError="this.src = './resources/mining-pools/default.svg'"> onError="this.src = './resources/mining-pools/default.svg'">
<span class="pool-name">{{ block.extras.pool.name }}</span> <span class="pool-name">{{ block.extras.pool.name }}</span>

View file

@ -71,6 +71,7 @@ export interface SinglePoolStats {
lastEstimatedHashrate: string; lastEstimatedHashrate: string;
emptyBlockRatio: string; emptyBlockRatio: string;
logo: string; logo: string;
slug: string;
} }
export interface PoolsStats { export interface PoolsStats {
blockCount: number; blockCount: number;
@ -107,6 +108,7 @@ export interface BlockExtension {
pool?: { pool?: {
id: number; id: number;
name: string; name: string;
slug: string;
} }
stage?: number; // Frontend only stage?: number; // Frontend only

View file

@ -132,17 +132,17 @@ export class ApiService {
); );
} }
getPoolStats$(poolId: number): Observable<PoolStat> { getPoolStats$(slug: string): Observable<PoolStat> {
return this.httpClient.get<PoolStat>(this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${poolId}`); return this.httpClient.get<PoolStat>(this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${slug}`);
} }
getPoolHashrate$(poolId: number): Observable<any> { getPoolHashrate$(slug: string): Observable<any> {
return this.httpClient.get<any>(this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${poolId}/hashrate`); return this.httpClient.get<any>(this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${slug}/hashrate`);
} }
getPoolBlocks$(poolId: number, fromHeight: number): Observable<BlockExtended[]> { getPoolBlocks$(slug: string, fromHeight: number): Observable<BlockExtended[]> {
return this.httpClient.get<BlockExtended[]>( return this.httpClient.get<BlockExtended[]>(
this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${poolId}/blocks` + this.apiBaseUrl + this.apiBasePath + `/api/v1/mining/pool/${slug}/blocks` +
(fromHeight !== undefined ? `/${fromHeight}` : '') (fromHeight !== undefined ? `/${fromHeight}` : '')
); );
} }