@q-dev/q-js-sdk
Version:
Typescript Library to interact with Q System Contracts
82 lines • 3.45 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RewardKPI = void 0;
const web3_adapter_1 = require("./web3-adapter");
const unit_converter_1 = require("./unit-converter");
const SECONDS_PER_BLOCK = 5;
const SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
class RewardKPI {
constructor(signerOrProvider, registry) {
this._adapter = new web3_adapter_1.Web3Adapter(signerOrProvider);
this._registry = registry;
this._converter = new unit_converter_1.UnitConverter();
this._rewardsPerSecond = this._converter.toBigNumber('0');
}
async getRootNodesAPR() {
const [rootNodes, constitution] = await Promise.all([
this._registry.rootNodes(),
this._registry.constitution()
]);
const [stakes, rewardsShare] = await Promise.all([
rootNodes.getStakes(),
constitution.getUint('constitution.rewardShareRootNodes')
]);
const totalStake = this._getTotalStake(stakes.map(r => this._adapter.fromWei(r.value)));
const yearlyRewards = await this._getYearlyRewards(rewardsShare);
return this._getAPR(totalStake, yearlyRewards);
}
async getValidatorsAPR() {
const [validators, constitution] = await Promise.all([
this._registry.validators(),
this._registry.constitution()
]);
const [shortList, rewardsShare] = await Promise.all([
validators.getShortList(),
constitution.getUint('constitution.rewardShareValidatorNodes')
]);
const yearlyRewards = await this._getYearlyRewards(rewardsShare);
const totalStake = this._getTotalStake(shortList.map(v => v.balance));
return this._getAPR(totalStake, yearlyRewards);
}
async _getYearlyRewards(share) {
if (this._rewardsPerSecond.isZero()) {
// Optimize loading by getting proxy events only once
await this._calculateRewardsPerSecond();
}
return this._rewardsPerSecond
.multipliedBy(SECONDS_IN_YEAR)
.multipliedBy(this._converter.fromFraction(share))
.toString();
}
async _calculateRewardsPerSecond() {
var _a;
const [proxy, latestBlock] = await Promise.all([
this._registry.defaultAllocationProxy(),
this._adapter.getBlockNumber()
]);
const [proxyBalance, events] = await Promise.all([
proxy.getBalance(),
proxy.instance.queryFilter(proxy.instance.filters.Allocated(), latestBlock - 100000, 'latest')
]);
const latestEventBlock = ((_a = events[events.length - 1]) === null || _a === void 0 ? void 0 : _a.blockNumber) || 0;
const blocksDelta = latestBlock - latestEventBlock;
this._rewardsPerSecond = this._converter
.toBigNumber(proxyBalance)
.div(blocksDelta * SECONDS_PER_BLOCK);
}
_getTotalStake(stakes) {
const totalStake = stakes.reduce((acc, item) => {
return acc.plus(this._converter.toBigNumber(item));
}, this._converter.toBigNumber('0'));
return totalStake.toString();
}
async _getAPR(totalStake, yearlyRewards) {
return this._converter
.toBigNumber(yearlyRewards)
.div(totalStake)
.multipliedBy(100)
.toString();
}
}
exports.RewardKPI = RewardKPI;
//# sourceMappingURL=reward-kpi.js.map