Skip to content

Commit

Permalink
refactor!: hoist Cardano.Percent to util package
Browse files Browse the repository at this point in the history
  • Loading branch information
mirceahasegan committed Jun 5, 2023
1 parent 19cabfe commit e4da0e3
Show file tree
Hide file tree
Showing 16 changed files with 55 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
} from './types';
import { Cardano, StakePoolStats } from '@cardano-sdk/core';
import { Hash32ByteBase16 } from '@cardano-sdk/crypto';
import { bufferToHexString, isNotNil } from '@cardano-sdk/util';
import { Percent, bufferToHexString, isNotNil } from '@cardano-sdk/util';
import Fraction from 'fraction.js';

const getPoolStatus = (
Expand Down Expand Up @@ -65,7 +65,7 @@ export const calcNodeMetricsValues = (metrics: PoolMetrics['metrics'], apy?: num
const isZeroStake = liveStake === 0n;
const size: Cardano.StakePoolMetricsSize = {
active: activeStakePercentage,
live: Cardano.Percent(!isZeroStake ? 1 - activeStakePercentage : 0)
live: Percent(!isZeroStake ? 1 - activeStakePercentage : 0)
};
const stake: Cardano.StakePoolMetricsStake = {
active: activeStake,
Expand Down Expand Up @@ -245,12 +245,12 @@ export const mapPoolMetrics = (poolMetricsModel: PoolMetricsModel): PoolMetrics
hashId: Number(poolMetricsModel.pool_hash_id),
metrics: {
activeStake: BigInt(poolMetricsModel.active_stake),
activeStakePercentage: Cardano.Percent(Number(poolMetricsModel.active_stake_percentage)),
activeStakePercentage: Percent(Number(poolMetricsModel.active_stake_percentage)),
blocksCreated: poolMetricsModel.blocks_created,
delegators: poolMetricsModel.delegators,
livePledge: BigInt(poolMetricsModel.live_pledge),
liveStake: BigInt(poolMetricsModel.live_stake),
saturation: Cardano.Percent(Number.parseFloat(poolMetricsModel.saturation))
saturation: Percent(Number.parseFloat(poolMetricsModel.saturation))
}
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Cardano, Paginated, QueryStakePoolsArgs } from '@cardano-sdk/core';
import { Percent } from '@cardano-sdk/util';
export interface PoolUpdateModel {
id: string; // pool hash id
update_id: string;
Expand Down Expand Up @@ -130,8 +131,8 @@ export interface PoolMetrics extends CommonPoolInfo {
livePledge: Cardano.Lovelace;
activeStake: Cardano.Lovelace;
liveStake: Cardano.Lovelace;
activeStakePercentage: Cardano.Percent;
saturation: Cardano.Percent;
activeStakePercentage: Percent;
saturation: Percent;
delegators: number;
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Cardano, Paginated } from '@cardano-sdk/core';
import { Hash32ByteBase16 } from '@cardano-sdk/crypto';
import { Percent, isNotNil } from '@cardano-sdk/util';
import { RelayModel, mapRelay } from '../DbSyncStakePoolProvider';
import { isNotNil } from '@cardano-sdk/util';

export type Margin = {
numerator: number;
Expand Down Expand Up @@ -90,10 +90,10 @@ const defaultMetrics: Cardano.StakePoolMetrics = {
blocksCreated: 0,
delegators: 0,
livePledge: 0n,
saturation: Cardano.Percent(0),
saturation: Percent(0),
size: {
active: Cardano.Percent(0),
live: Cardano.Percent(0)
active: Percent(0),
live: Percent(0)
},
stake: {
active: 0n,
Expand All @@ -105,14 +105,14 @@ const mapMetrics = (pool: PoolModel): Cardano.StakePoolMetrics => {
if (pool.metrics_live_pledge === null) return defaultMetrics;

return {
apy: pool.metrics_apy ? Cardano.Percent(Number.parseFloat(pool.metrics_apy)) : undefined,
apy: pool.metrics_apy ? Percent(Number.parseFloat(pool.metrics_apy)) : undefined,
blocksCreated: pool.metrics_minted_blocks,
delegators: pool.metrics_live_delegators,
livePledge: BigInt(pool.metrics_live_pledge),
saturation: Cardano.Percent(Number.parseFloat(pool.metrics_live_saturation)),
saturation: Percent(Number.parseFloat(pool.metrics_live_saturation)),
size: {
active: Cardano.Percent(Number.parseFloat(pool.metrics_active_size)),
live: Cardano.Percent(Number.parseFloat(pool.metrics_live_size))
active: Percent(Number.parseFloat(pool.metrics_active_size)),
live: Percent(Number.parseFloat(pool.metrics_live_size))
},
stake: {
active: BigInt(pool.metrics_active_stake),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Cardano, StakePoolProvider } from '@cardano-sdk/core';
import { CurrentPoolMetricsEntity } from '@cardano-sdk/projection-typeorm';
import { DataSource } from 'typeorm';
import { Percent } from '@cardano-sdk/util';
import { initHandlerTest, poolId } from './util';
import { logger } from '@cardano-sdk/util-dev';
import { savePoolMetrics } from '../../src/PgBoss';
Expand Down Expand Up @@ -30,8 +31,8 @@ describe('stakePoolMetricsHandler', () => {
blocksCreated: 23,
delegators: 15,
livePledge: 23_000_000n,
saturation: Cardano.Percent(0.002),
size: { active: Cardano.Percent(0.0005), live: Cardano.Percent(0.0005) },
saturation: Percent(0.002),
size: { active: Percent(0.0005), live: Percent(0.0005) },
stake: { active: 42_000_000n, live: 42_000_000n }
};

Expand Down
11 changes: 1 addition & 10 deletions packages/core/src/Cardano/types/StakePool/StakePool.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
import { EpochNo } from '../Block';
import { Lovelace } from '../Value';
import { OpaqueNumber } from '@cardano-sdk/util';
import { Percent } from '@cardano-sdk/util';
import { PoolIdHex } from './primitives';
import { PoolParameters } from './PoolParameters';

/**
* The Percentage is a relative value that indicates the hundredth parts of any quantity.
*
* One percent 1% (0.01) represents the one hundredth, 2 percent 2% (0.02) represents two hundredths,
* 100% (1.0) represents the whole, 200% (2.0) twice the given quantity and so on…
*/
export type Percent = OpaqueNumber<'Percent'>;
export const Percent = (value: number): Percent => value as unknown as Percent;

/**
* Stake quantities for a Stake Pool.
*/
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/Cardano/util/estimateStakePoolAPY.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Percent, StakePoolEpochRewards } from '../types';
import { Percent } from '@cardano-sdk/util';
import { StakePoolEpochRewards } from '../types';

const MILLISECONDS_PER_DAY = 1000 * 60 * 60 * 24;

Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/Provider/Provider.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Cardano } from '..';
import { Percent } from '../Cardano';

// eslint-disable-next-line import/no-extraneous-dependencies
import { Logger } from 'ts-log';
import { Percent } from '@cardano-sdk/util';
import { Tip } from '@cardano-ogmios/schema';

export type HealthCheckResponse = {
Expand Down
3 changes: 2 additions & 1 deletion packages/core/test/Cardano/util/estimateStakePoolAPY.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Cardano } from '../../../src';
import { Percent } from '@cardano-sdk/util';

describe('estimateStakePoolAPY', () => {
const rewards = {
activeStake: 10_365_739_303_707n,
epochLength: 432_000_000,
memberROI: Cardano.Percent(0.000_829_950_248_854_788),
memberROI: Percent(0.000_829_950_248_854_788),
memberRewards: 8_579_404_603n,
pledge: 28_487_625_262n
} as Cardano.StakePoolEpochRewards;
Expand Down
5 changes: 3 additions & 2 deletions packages/core/test/CardanoNode/mocks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Cardano, EraSummary, HealthCheckResponse, Milliseconds, StakeDistribution } from '../../src';
import { Percent } from '@cardano-sdk/util';

const mockEraSummaries: EraSummary[] = [
{
Expand Down Expand Up @@ -55,7 +56,7 @@ export const healthCheckResponseMock = (opts?: {
blockNo?: number;
slot?: number;
hash?: string;
networkSync?: Cardano.Percent;
networkSync?: Percent;
withTip?: boolean;
projectedTip?: {
blockNo?: number;
Expand All @@ -69,7 +70,7 @@ export const healthCheckResponseMock = (opts?: {
hash: opts?.hash ?? '9ef43ab6e234fcf90d103413096c7da752da2f45b15e1259f43d476afd12932c',
slot: opts?.slot ?? 52_819_355
},
networkSync: opts?.networkSync ?? Cardano.Percent(0.999)
networkSync: opts?.networkSync ?? Percent(0.999)
},
ok: true,
...(opts?.withTip === false
Expand Down
4 changes: 2 additions & 2 deletions packages/ogmios/src/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { Cardano } from '@cardano-sdk/core';
import {
ConnectionConfig,
InteractionContext,
Expand All @@ -7,6 +6,7 @@ import {
createInteractionContext
} from '@cardano-ogmios/client';
import { Logger } from 'ts-log';
import { Percent } from '@cardano-sdk/util';

/**
* Converts an Ogmios connection URL to an Ogmios ConnectionConfig Object
Expand Down Expand Up @@ -56,7 +56,7 @@ export const createInteractionContextWithLogger = (
export const ogmiosServerHealthToHealthCheckResponse = ({ lastKnownTip, networkSynchronization }: ServerHealth) => ({
localNode: {
ledgerTip: lastKnownTip,
networkSync: Cardano.Percent(networkSynchronization)
networkSync: Percent(networkSynchronization)
},
ok: networkSynchronization > 0.99
});
4 changes: 2 additions & 2 deletions packages/ogmios/test/util.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Cardano } from '@cardano-sdk/core';
import { HEALTH_RESPONSE_BODY } from './mocks/util';
import { InteractionContext, ServerHealth } from '@cardano-ogmios/client';
import { Logger } from 'ts-log';
import { Percent } from '@cardano-sdk/util';
import { createInteractionContextWithLogger, ogmiosServerHealthToHealthCheckResponse } from '../src';
import { createLogger } from '@cardano-sdk/util-dev';
import { createMockOgmiosServer, listenPromise, serverClosePromise } from './mocks/mockOgmiosServer';
Expand Down Expand Up @@ -91,7 +91,7 @@ describe('util', () => {
expect(ogmiosServerHealthToHealthCheckResponse({ ...serverHealth, networkSynchronization })).toEqual({
localNode: {
ledgerTip: serverHealth.lastKnownTip,
networkSync: Cardano.Percent(networkSynchronization)
networkSync: Percent(networkSynchronization)
},
ok: true
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BigIntColumnOptions, DeleteCascadeRelationOptions } from './util';
import { Cardano } from '@cardano-sdk/core';
import { Column, Entity, JoinColumn, OneToOne, PrimaryColumn } from 'typeorm';
import { Percent } from '@cardano-sdk/util';
import { StakePoolEntity } from './StakePool.entity';
import { float } from './transformers';

Expand Down Expand Up @@ -33,14 +34,14 @@ export class CurrentPoolMetricsEntity {
livePledge?: Cardano.Lovelace;

@Column({ transformer: float, type: 'numeric' })
liveSaturation?: Cardano.Percent;
liveSaturation?: Percent;

@Column({ transformer: float, type: 'numeric' })
activeSize?: Cardano.Percent;
activeSize?: Percent;

@Column({ transformer: float, type: 'numeric' })
liveSize?: Cardano.Percent;
liveSize?: Percent;

@Column({ transformer: float, type: 'numeric' })
apy?: Cardano.Percent;
apy?: Percent;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BigIntColumnOptions, DeleteCascadeRelationOptions } from './util';
import { BlockEntity } from './Block.entity';
import { Cardano } from '@cardano-sdk/core';
import { Column, Entity, JoinColumn, ManyToOne, OneToOne, PrimaryColumn } from 'typeorm';
import { Percent } from '@cardano-sdk/util';
import { PoolMetadataEntity } from './PoolMetadata.entity';
import { StakePoolEntity } from './StakePool.entity';

Expand All @@ -26,7 +27,7 @@ export class PoolRegistrationEntity {
@Column({ type: 'jsonb' })
margin?: Cardano.Fraction;
@Column({ type: 'float4' })
marginPercent?: Cardano.Percent;
marginPercent?: Percent;
@Column('jsonb')
relays?: Cardano.Relay[];
@Column('jsonb')
Expand Down
9 changes: 5 additions & 4 deletions packages/util-dev/src/mockProviders/mockRewardsProvider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Cardano, Paginated, StakePoolProvider } from '@cardano-sdk/core';
import { Percent } from '@cardano-sdk/util';
import { epochRewards, rewardAccountBalance, rewardAccountBalance2, rewardsHistory, rewardsHistory2 } from './mockData';
import { getRandomTxId } from './mockChainHistoryProvider';
import delay from 'delay';
Expand Down Expand Up @@ -41,14 +42,14 @@ export const generateStakePools = (qty: number): Cardano.StakePool[] =>
url: 'https://git.io/JJ7wm'
},
metrics: {
apy: Cardano.Percent(0),
apy: Percent(0),
blocksCreated: 0,
delegators: 1,
livePledge: 495_463_149n,
saturation: Cardano.Percent(0.000_035_552_103_558_591_88),
saturation: Percent(0.000_035_552_103_558_591_88),
size: {
active: Cardano.Percent(1),
live: Cardano.Percent(0)
active: Percent(1),
live: Percent(0)
},
stake: {
active: 2_986_376_991n,
Expand Down
10 changes: 10 additions & 0 deletions packages/util/src/Percent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { OpaqueNumber } from './opaqueTypes';

/**
* The Percentage is a relative value that indicates the hundredth parts of any quantity.
*
* One percent 1% (0.01) represents the one hundredth, 2 percent 2% (0.02) represents two hundredths,
* 100% (1.0) represents the whole, 200% (2.0) twice the given quantity and so on…
*/
export type Percent = OpaqueNumber<'Percent'>;
export const Percent = (value: number): Percent => value as unknown as Percent;
1 change: 1 addition & 0 deletions packages/util/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ export * from './environment';
export * from './patchObject';
export * from './isPromise';
export * from './transformer';
export * from './Percent';
export { PromiseOrValue, resolveObjectValues } from './util';

0 comments on commit e4da0e3

Please sign in to comment.