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

Capacity runtime api with list_unclaimed_rewards endpoint #2088

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

83 changes: 83 additions & 0 deletions e2e/capacity/list_unclaimed_rewards.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import '@frequency-chain/api-augment';
import assert from 'assert';
import { Extrinsic, ExtrinsicHelper } from '../scaffolding/extrinsicHelpers';
import { getFundingSource } from '../scaffolding/funding';
import {
createKeys,
createMsaAndProvider,
stakeToProvider,
CENTS,
DOLLARS,
createAndFundKeypair,
createProviderKeysAndId,
boostProvider,
getNextEpochBlock,
getNextRewardEraBlock,
} from '../scaffolding/helpers';
import { isTestnet } from '../scaffolding/env';
import { KeyringPair } from '@polkadot/keyring/types';
import { UnclaimedRewardInfo } from '@frequency-chain/api-augment/interfaces';
import { Vec } from '@polkadot/types';

const fundingSource = getFundingSource('capacity-replenishment');

describe('Capacity: list_unclaimed_rewards', function() {
const providerBalance = 2n * DOLLARS;

const setUpForBoosting = async (boosterName: string, providerName: string): Promise<[number, KeyringPair]> => {
const booster = await createAndFundKeypair(fundingSource, 5n * DOLLARS, boosterName);
const providerKeys = createKeys(providerName);
const provider = await createMsaAndProvider(fundingSource, providerKeys, providerName, providerBalance);
await assert.doesNotReject(boostProvider(fundingSource, booster, provider, 1n * DOLLARS));

return [provider.toNumber(), booster];
};

it('can be called', async function() {
const [_provider, booster] = await setUpForBoosting("booster1", "provider1");
const result = ExtrinsicHelper.api.rpc.state.call(
'CapacityRuntimeApi_list_unclaimed_rewards', booster.address);
let count = 0;
const subscription = result.subscribe((x) => {
count++;
});
// Failing to do this results in "helpful" error:
// `Bad input data provided to list_unclaimed_rewards: Input buffer has still data left after decoding!`
subscription.unsubscribe();
assert(count === 0, `should have been empty but had ${count} items`);
});

it('returns correct rewards after enough eras have passed', async function() {
if (isTestnet()) {
this.skip();
}
const [_provider, booster] = await setUpForBoosting("booster2", "provider2");
console.debug(`Booster pubkey: ${booster.address}`);

await ExtrinsicHelper.runToBlock(await getNextRewardEraBlock());
await ExtrinsicHelper.runToBlock(await getNextRewardEraBlock());
await ExtrinsicHelper.runToBlock(await getNextRewardEraBlock());

const encodedAddr = ExtrinsicHelper.api.registry.createType('AccountId32', booster.address);

const result = await ExtrinsicHelper.apiPromise.rpc.state.call(
'CapacityRuntimeApi_list_unclaimed_rewards', encodedAddr);

const decResult: Vec<UnclaimedRewardInfo> = ExtrinsicHelper.api.registry.createType('Vec<UnclaimedRewardInfo>', result);
let count = 0;
assert(decResult.every(item => {
count++;
return item.staked_amount.toHuman() === '1.0000 UNIT';
}));
assert.equal(count, 3);

assert.equal(decResult[0].eligible_amount.toHuman(), '1.0000 UNIT');
assert.equal(decResult[0].earned_amount.toHuman(), '3.8000 mUNIT');

assert.equal(decResult[1].eligible_amount.toHuman(), '1.0000 UNIT');
assert.equal(decResult[1].earned_amount.toHuman(), '3.8000 mUNIT');

assert.equal(decResult[2].eligible_amount.toHuman(), '1.0000 UNIT');
assert.equal(decResult[2].earned_amount.toHuman(), '3.8000 mUNIT');
});
});
3 changes: 1 addition & 2 deletions e2e/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions js/api-augment/definitions/capacity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export default {
rpc: {
dummy: { description: "This API has no custom RPCs", params: [], type: 'undefined' },
},
types: {
RewardEra: 'u32',
Balance: 'u128',
BlockNumber: 'u32',
UnclaimedRewardInfo: {
reward_era: 'RewardEra',
expires_at_block: 'BlockNumber',
staked_amount: 'Balance',
eligible_amount: 'Balance',
earned_amount: 'Balance',
}
},
runtime: {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice. By the way, do this show up in PolkadotUI now?

Copy link
Collaborator Author

@shannonwells shannonwells Jul 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It won't until it merges to main and is released, and I think you also have to post a PR with the updated release to PolkadotJS ui

CapacityRuntimeApi: [
{
methods: {
list_unclaimed_rewards: {
description: 'List any rewards that can be claimed up to the previous Reward Era',
params: [ { name: 'address', type: 'AccountId' }, ],
type: 'Vec<UnclaimedRewardInfo>',
},
},
version: 1,
},
],
},
};
1 change: 1 addition & 0 deletions js/api-augment/definitions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export { default as statefulStorage } from './statefulStorage.js';
export { default as handles } from './handles.js';
export { default as frequency } from './frequency.js';
export { default as frequencyTxPayment } from './frequencyTxPayment.js';
export { default as capacity } from './capacity';
1 change: 1 addition & 0 deletions js/api-augment/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ describe('index', function () {
'MsaRuntimeApi',
'SchemasRuntimeApi',
'StatefulStorageRuntimeApi',
'CapacityRuntimeApi',
]);
});

Expand Down
27 changes: 27 additions & 0 deletions pallets/capacity/src/runtime-api/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
[package]
name = "pallet-capacity-runtime-api"
version = "0.0.0"
description = "A package that adds Runtime Api for the Stateful Storage pallet"
shannonwells marked this conversation as resolved.
Show resolved Hide resolved
authors = ["Frequency"]
license = "Apache-2.0"
publish = false
homepage = "https://frequency.xyz"
repository = "https://github.com/frequency-chain/frequency/"
edition = "2021"


[dependencies]
parity-scale-codec = { workspace = true, features = ["derive"] }
sp-api = { workspace = true, default-features = false }
sp-std = { workspace = true, default-features = false }
sp-runtime = { workspace = true, default-features = false }
common-primitives = { path="../../../../common/primitives", default-features = false}

[features]
default = ["std"]
std = [
"parity-scale-codec/std",
"sp-api/std",
"sp-std/std",
"sp-runtime/std"
]
43 changes: 43 additions & 0 deletions pallets/capacity/src/runtime-api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::unnecessary_mut_passed)]
#![allow(rustdoc::bare_urls)]
// Strong Documentation Lints
#![deny(
rustdoc::broken_intra_doc_links,
rustdoc::missing_crate_level_docs,
rustdoc::invalid_codeblock_attributes,
missing_docs
)]

//! Runtime API definition for [Capacity](../pallet_capacity/index.html)
//!
//! This api must be implemented by the node runtime.
//! Runtime APIs Provide:
//! - An interface between the runtime and Custom RPCs.
//! - Runtime interfaces for end users beyond just State Queries

use common_primitives::capacity::UnclaimedRewardInfo;
use parity_scale_codec::Codec;
use sp_runtime::traits::MaybeDisplay;
use sp_std::vec::Vec;

// Here we declare the runtime API. It is implemented it the `impl` block in
// runtime files (the `runtime` folder)
sp_api::decl_runtime_apis! {
/// Runtime Version for Capacity
/// - MUST be incremented if anything changes
/// - Also update in js/api-augment
/// - See: https://paritytech.github.io/polkadot/doc/polkadot_primitives/runtime_api/index.html
#[api_version(1)]
/// Runtime APIs for [Capacity](../pallet_capacity/index.html)
pub trait CapacityRuntimeApi<AccountId, Balance, BlockNumber> where
AccountId: Codec + MaybeDisplay,
Balance: Codec + MaybeDisplay,
BlockNumber: Codec + MaybeDisplay,
{
// state_call method: CapacityRuntimeApi_list_unclaimed_rewards
/// Get the list of unclaimed rewards information for each eligible Reward Era.
fn list_unclaimed_rewards(who: AccountId) -> Vec<UnclaimedRewardInfo<Balance, BlockNumber>>;
}
}
3 changes: 1 addition & 2 deletions pallets/capacity/src/tests/claim_staking_rewards_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ use crate::{
},
testing_utils::{run_to_block, setup_provider},
},
Error,
Event,
Error, Event,
Event::ProviderBoostRewardClaimed,
MessageSourceId,
StakingType::*,
Expand Down
2 changes: 2 additions & 0 deletions runtime/frequency/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ pallet-time-release = { path = "../../pallets/time-release", default-features =
common-primitives = { default-features = false, path = "../../common/primitives" }
common-runtime = { path = "../common", default-features = false }
pallet-capacity = { path = "../../pallets/capacity", default-features = false }
pallet-capacity-runtime-api = { path="../../pallets/capacity/src/runtime-api", default-features = false }
pallet-frequency-tx-payment = { path = "../../pallets/frequency-tx-payment", default-features = false }
pallet-frequency-tx-payment-runtime-api = { path = "../../pallets/frequency-tx-payment/src/runtime-api", default-features = false }
pallet-messages = { path = "../../pallets/messages", default-features = false }
Expand Down Expand Up @@ -113,6 +114,7 @@ std = [
"pallet-authorship/std",
"pallet-balances/std",
"pallet-capacity/std",
"pallet-capacity-runtime-api/std",
"pallet-collator-selection/std",
"pallet-collective/std",
"pallet-democracy/std",
Expand Down
12 changes: 11 additions & 1 deletion runtime/frequency/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ use sp_version::NativeVersion;
use sp_version::RuntimeVersion;

use common_primitives::{
handles::*, messages::*, msa::*, node::*, rpc::RpcEvent, schema::*, stateful_storage::*,
capacity::*, handles::*, messages::*, msa::*, node::*, rpc::RpcEvent, schema::*,
stateful_storage::*,
};

pub use common_runtime::{
Expand Down Expand Up @@ -1518,6 +1519,15 @@ impl_runtime_apis! {
}
}

impl pallet_capacity_runtime_api::CapacityRuntimeApi<Block, AccountId, Balance, BlockNumber> for Runtime {
fn list_unclaimed_rewards(who: AccountId) -> Vec<UnclaimedRewardInfo<Balance, BlockNumber>> {
match Capacity::list_unclaimed_rewards(&who) {
Ok(rewards) => return rewards.into_inner(),
Err(_) => return Vec::new(),
}
}
}

saraswatpuneet marked this conversation as resolved.
Show resolved Hide resolved
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: UpgradeCheckSelect) -> (Weight, Weight) {
Expand Down