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 May 29, 2023
1 parent c18e09d commit 78d20c7
Show file tree
Hide file tree
Showing 14 changed files with 43 additions and 33 deletions.
Expand Up @@ -29,7 +29,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 @@ -68,7 +68,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 @@ -247,7 +247,7 @@ export const mapEpochReward = (epochRewardModel: EpochRewardModel): EpochReward
epoch: Cardano.EpochNo(epochRewardModel.epoch_no),
epochLength: Number(epochRewardModel.epoch_length),
leaderRewards: BigInt(epochRewardModel.leader_rewards),
memberROI: Cardano.Percent(epochRewardModel.member_roi),
memberROI: Percent(epochRewardModel.member_roi),
memberRewards: BigInt(epochRewardModel.member_rewards),
pledge: BigInt(epochRewardModel.pledge)
},
Expand Down Expand Up @@ -275,12 +275,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
@@ -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 @@ -146,8 +147,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
11 changes: 1 addition & 10 deletions packages/core/src/Cardano/types/StakePool/StakePool.ts
@@ -1,19 +1,10 @@
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';
import { TransactionId } from '../Transaction';

/**
* 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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
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, PrimaryColumn } from 'typeorm';
import { Percent } from '@cardano-sdk/util';
import { StakePoolEntity } from './StakePool.entity';

@Entity()
Expand All @@ -25,7 +26,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
3 changes: 2 additions & 1 deletion packages/util-dev/src/createStubStakePoolProvider.ts
@@ -1,4 +1,5 @@
import { Cardano, StakePoolProvider } from '@cardano-sdk/core';
import { Percent } from '@cardano-sdk/util';
import delay from 'delay';

export const somePartialStakePools: Cardano.StakePool[] = [
Expand All @@ -9,7 +10,7 @@ export const somePartialStakePools: Cardano.StakePool[] = [
epoch: Cardano.EpochNo(123),
epochLength: 432_000_000,
leaderRewards: 1_000_000n,
memberROI: Cardano.Percent(0.000_68),
memberROI: Percent(0.000_68),
memberRewards: 2_000_000n,
pledge: 1_000_000_000n
}
Expand Down
11 changes: 6 additions & 5 deletions packages/util-dev/src/mockProviders/mockRewardsProvider.ts
@@ -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 @@ -28,7 +29,7 @@ export const generateStakePools = (qty: number): Cardano.StakePool[] =>
epoch: Cardano.EpochNo(205),
epochLength: 431_850_000,
leaderRewards: 1000n,
memberROI: Cardano.Percent(0),
memberROI: Percent(0),
memberRewards: 2000n,
pledge: 986_376_991n
}
Expand All @@ -52,14 +53,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
@@ -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
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 78d20c7

Please sign in to comment.