Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add final rewards+final used fee #75

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
165 changes: 145 additions & 20 deletions packages/sdk-core/src/modules/dapp-staking/pending-rewards/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Perbill } from '@polkadot/types/interfaces';
import { ApiPromise } from '@polkadot/api';
import { ethers } from 'ethers';
import { Codec } from '@polkadot/types/types';
import { hasProperty, truncate } from '@astar-network/astar-sdk-core';
import { commaStrToBigInt, hasProperty, truncate } from '@astar-network/astar-sdk-core';

export interface RewardDistributionConfig extends Struct {
readonly baseTreasuryPercent: Perbill;
Expand Down Expand Up @@ -85,10 +85,10 @@ const getClaimableEraRange = (era: number, currentEra: number): number[] => {
const formatGeneralStakerInfo = ({ eraTvls,
currentEra,
generalStakerInfo }: {
currentEra: number;
eraTvls: EraTvl[];
generalStakerInfo: [StorageKey<any>, Codec][];
}): { stakerInfo: StakerInfo[]; stakedEras: number[] } => {
currentEra: number;
eraTvls: EraTvl[];
generalStakerInfo: [StorageKey<any>, Codec][];
}): { stakerInfo: StakerInfo[]; stakedEras: number[] } => {
const stakerInfo: StakerInfo[] = [];
const stakedEras: number[] = [];

Expand Down Expand Up @@ -125,12 +125,12 @@ const estimateEraTokenIssuances = async ({ blockHeight,
stakedEras,
currentEra,
blocksPerEra }: {
blockHeight: number;
api: ApiPromise;
stakedEras: number[];
currentEra: number;
blocksPerEra: number;
}): Promise<EraTokenIssuances[]> => {
blockHeight: number;
api: ApiPromise;
stakedEras: number[];
currentEra: number;
blocksPerEra: number;
}): Promise<EraTokenIssuances[]> => {
const eraTokenIssuances: { era: number; eraTokenIssuance: number }[] = [];
const block7EraAgo = blockHeight - blocksPerEra * 7;
const [hash, currentIssuance] = await Promise.all([
Expand Down Expand Up @@ -169,12 +169,12 @@ const formatStakerPendingRewards = ({ stakerInfo,
eraTokenIssuances,
eraRewards,
rewardsDistributionConfig }: {
stakerInfo: StakerInfo[];
eraTvls: EraTvl[];
eraTokenIssuances: EraTokenIssuances[];
eraRewards: number;
rewardsDistributionConfig: DistributionConfig;
}) => {
stakerInfo: StakerInfo[];
eraTvls: EraTvl[];
eraTokenIssuances: EraTokenIssuances[];
eraRewards: number;
rewardsDistributionConfig: DistributionConfig;
}) => {
return stakerInfo.map((it) => {
const totalStaked = eraTvls[it.era].tvlLocked;
const { baseStakerPercent, adjustablePercent, idealDappsStakingTvl } = rewardsDistributionConfig;
Expand All @@ -199,9 +199,9 @@ const formatStakerPendingRewards = ({ stakerInfo,
// In other words, as the number of unclaimed eras increases, the difference increases (but it shouldn't be too far away).
export const estimatePendingRewards = async ({ api,
walletAddress }: {
api: ApiPromise;
walletAddress: string;
}): Promise<{ stakerPendingRewards: number }> => {
api: ApiPromise;
walletAddress: string;
}): Promise<{ stakerPendingRewards: number }> => {
try {
const [eraInfo, generalStakerInfo, blockHeight, blocksPerEra, rawBlockRewards, rewardsDistributionConfig] =
await Promise.all([
Expand Down Expand Up @@ -251,3 +251,128 @@ export const estimatePendingRewards = async ({ api,
return { stakerPendingRewards: 0 };
}
};




/**
* Memo:
* This method returns claimed reward amount by extrinsicHash and blockHeight that have the reward event.
* After StkingV3, Two kinds of rewards exist.
* - Staker Reward : When "Build&Earn" comes after the "Voting", stakers can get the reward by staking on dApps.
* - Bonus Reward : During the "Voting" subperiod makes the staker eligible for bonus rewards.
*/
export const claimedReward = async (
{
api, extrinsicHash, height
}:
{
api: ApiPromise, extrinsicHash: string, height: number
}): Promise<{ claimedRewards: number }> => {
try {

const blockHash = await api.rpc.chain.getBlockHash(height);
const signedBlock = await api.rpc.chain.getBlock(blockHash);
const apiAt = await api.at(signedBlock.block.header.hash);
const allRecords = (await apiAt.query.system.events()).toArray();

// Find the extrinsic index by matching the extrinsic hash
const extrinsicIndex = signedBlock.block.extrinsics.findIndex(
(ex) => ex.hash.toString() === extrinsicHash
);

if (extrinsicIndex === -1) {
throw new Error('Extrinsic not found in the block');
}

// Get events associated with the extrinsic
const extrinsicEvents = allRecords.filter((record) =>
record.phase.isApplyExtrinsic &&
record.phase.asApplyExtrinsic.eq(extrinsicIndex)
);

const methodRwd = 'Reward';
const methodBns = 'BonusReward';
const section = 'dappStaking';
let claimedReward = BigInt('0');

extrinsicEvents.map((e, idx) => {
console.log(e.toHuman(), idx);
if ((e.toHuman()?.event?.method == methodRwd || e.toHuman()?.event?.method == methodBns) &&
e.toHuman()?.event?.section == section) {
let tmpAmount = e.toHuman().event?.data?.amount;
let tmpAmountBigInt = commaStrToBigInt(tmpAmount);

claimedReward += tmpAmountBigInt;

} else {
claimedReward = claimedReward;
}
})

return { claimedRewards: Number(claimedReward) };

} catch (error) {
console.log(error);
throw error;
}
}

/**
* Memo:
* This method returns usedfee amount by extrinsicHash and blockHeight that have the actualFee.
*/
export const UsedFee = async (
{
api, extrinsicHash, height
}:
{
api: ApiPromise, extrinsicHash: string, height: number
}): Promise<{ usedFee: number }> => {
try {

const blockHash = await api.rpc.chain.getBlockHash(height);
const signedBlock = await api.rpc.chain.getBlock(blockHash);
const apiAt = await api.at(signedBlock.block.header.hash);
const allRecords = (await apiAt.query.system.events()).toArray();

// Find the extrinsic index by matching the extrinsic hash
const extrinsicIndex = signedBlock.block.extrinsics.findIndex(
(ex) => ex.hash.toString() === extrinsicHash
);

if (extrinsicIndex === -1) {
throw new Error('Extrinsic not found in the block');
}

// Get events associated with the extrinsic
const extrinsicEvents = allRecords.filter((record) =>
record.phase.isApplyExtrinsic &&
record.phase.asApplyExtrinsic.eq(extrinsicIndex)
);

const method = 'TransactionFeePaid';
const section = 'transactionPayment';

let usedFee = BigInt('0');

extrinsicEvents.map((e) => {
if (e.toHuman()?.event?.method == method &&
e.toHuman()?.event?.section == section) {
let tmpUsedFee = e.toHuman().event?.data?.actualFee;
let tmpUsedFeeBigInt = commaStrToBigInt(tmpUsedFee);

usedFee = tmpUsedFeeBigInt;

} else {
usedFee = usedFee;
}
})

return { usedFee: Number(usedFee) };

} catch (error) {
console.log(error);
throw error;
}
}
18 changes: 18 additions & 0 deletions packages/sdk-core/src/modules/units/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,21 @@ export const formatNumber = (value: number, digits: number): string => {

return item ? (value / item.value).toFixed(digits).replace(rx, '$1') + item.symbol : '0';
};


export function commaStrToBigInt(_str: string) {

let _strToStr = String(_str);

let _noCommaStr = _strToStr.replace(/,/g, '');

let rlt = BigInt("0");

if (_noCommaStr === "undefined") {
console.log(' _noCommaStr :undefined ');
} else {
rlt = BigInt(_noCommaStr);
}

return rlt;
}