git.delta.rocks / unique-network / refs/commits / 5b36ad8fb241

difftreelog

fix untstake

PraetorP2022-09-02parents: #de3cc29 #1021988.patch.diff
in: master

4 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
418 }418 }
419}419}
420420
421pub struct Unique<C, P> {421macro_rules! define_struct_for_server_api {
422 client: Arc<C>,422 ($name:ident) => {
423 _marker: std::marker::PhantomData<P>,423 pub struct $name<C, P> {
424}424 client: Arc<C>,
425425 _marker: std::marker::PhantomData<P>,
426 }
427
426impl<C, P> Unique<C, P> {428 impl<C, P> $name<C, P> {
427 pub fn new(client: Arc<C>) -> Self {429 pub fn new(client: Arc<C>) -> Self {
428 Self {430 Self {
429 client,431 client,
430 _marker: Default::default(),432 _marker: Default::default(),
431 }433 }
432 }434 }
433}435 }
434436 };
435pub struct AppPromotion<C, P> {437}
436 client: Arc<C>,438
437 _marker: std::marker::PhantomData<P>,439define_struct_for_server_api!(Unique);
438}
439
440impl<C, P> AppPromotion<C, P> {440define_struct_for_server_api!(AppPromotion);
441 pub fn new(client: Arc<C>) -> Self {
442 Self {
443 client,
444 _marker: Default::default(),
445 }
446 }
447}
448
449pub struct Rmrk<C, P> {
450 client: Arc<C>,
451 _marker: std::marker::PhantomData<P>,
452}
453
454impl<C, P> Rmrk<C, P> {441define_struct_for_server_api!(Rmrk);
455 pub fn new(client: Arc<C>) -> Self {
456 Self {
457 client,
458 _marker: Default::default(),
459 }
460 }
461}
462442
463macro_rules! pass_method {443macro_rules! pass_method {
464 (444 (
615 |v| v595 |v| v
616 .into_iter()596 .into_iter()
617 .map(|(b, a)| (b, a.to_string()))597 .map(|(b, a)| (b, a.to_string()))
618 .collect::<Vec<_>>(), unique_api);598 .collect::<Vec<_>>(), app_promotion_api);
619 pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), unique_api);599 pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), app_promotion_api);
620 pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), unique_api);600 pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);
621 pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>601 pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>
622 |v| v602 |v| v
623 .into_iter()603 .into_iter()
624 .map(|(b, a)| (b, a.to_string()))604 .map(|(b, a)| (b, a.to_string()))
625 .collect::<Vec<_>>(), unique_api);605 .collect::<Vec<_>>(), app_promotion_api);
626}606}
627607
628#[allow(deprecated)]608#[allow(deprecated)]
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
38use sp_block_builder::BlockBuilder;38use sp_block_builder::BlockBuilder;
39use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};39use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
40use sc_service::TransactionPool;40use sc_service::TransactionPool;
41use uc_rpc::AppPromotion;
42use std::{collections::BTreeMap, sync::Arc};41use std::{collections::BTreeMap, sync::Arc};
4342
44use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};43use up_common::types::opaque::{Hash, AccountId, RuntimeInstance, Index, Block, BlockNumber, Balance};
237236
238 io.merge(Unique::new(client.clone()).into_rpc())?;237 io.merge(Unique::new(client.clone()).into_rpc())?;
239238
240 // #[cfg(not(feature = "unique-runtime"))]239 #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
241 io.merge(AppPromotion::new(client.clone()).into_rpc())?;240 io.merge(AppPromotion::new(client.clone()).into_rpc())?;
242241
243 #[cfg(not(feature = "unique-runtime"))]242 #[cfg(not(feature = "unique-runtime"))]
modifiedtests/src/app-promotion.test.tsdiffbeforeafterboth
35let alice: IKeyringPair;35let alice: IKeyringPair;
36let palletAdmin: IKeyringPair;36let palletAdmin: IKeyringPair;
37let nominal: bigint;37let nominal: bigint;
38let promotionStartBlock: number | null = null;
39const palletAddress = calculatePalleteAddress('appstake');38const palletAddress = calculatePalleteAddress('appstake');
40let accounts: IKeyringPair[] = [];39let accounts: IKeyringPair[] = [];
4140
51 if (!promotionStartBlock) {50 if (!promotionStartBlock) {
52 promotionStartBlock = (await helper.api!.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();51 promotionStartBlock = (await helper.api!.query.parachainSystem.lastRelayChainBlockNumber()).toNumber();
53 }52 }
53 await helper.signTransaction(alice, helper.api!.tx.sudo.sudo(helper.api!.tx.promotion.startAppPromotion(promotionStartBlock!)));
54 accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests54 accounts = await helper.arrange.createCrowd(100, 1000n, alice); // create accounts-pool to speed up tests
55 });55 });
56});56});
89 });89 });
90 });90 });
9191
92 it('should allow to stake with nonce', async () => {92 it('should allow to create maximum 10 stakes for account', async () => {
93 await usingPlaygrounds(async (helper) => {93 await usingPlaygrounds(async (helper) => {
94 const staker = accounts.pop()!;94 const [staker] = await helper.arrange.createAccounts([2000n], alice);
95 const transactions = [];95 console.log(staker.address);
96 for (let nonce = 0; nonce < 9; nonce++) {96 for (let i = 0; i < 10; i++) {
97 transactions.push(helper.signTransaction(staker, helper.api?.tx.promotion.stake(100n * nominal), 'Staker stakes with nonce', {nonce}));97 await helper.staking.stake(staker, 100n * nominal);
98 }98 }
99
100 // can have 10 stakes
101 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(1000n * nominal);
102 expect(await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).to.have.length(10);
103
104 await expect(helper.staking.stake(staker, 100n * nominal)).to.be.rejected;
105
106 // After unstake can stake again
99 await Promise.allSettled(transactions);107 await helper.staking.unstake(staker);
100108 await helper.staking.stake(staker, 100n * nominal);
101 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(900n * nominal);109 expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.equal(100n * nominal);
102 });110 });
103 });111 });
104 112
128 });136 });
129 });137 });
130
131 it('should allow to create maximum 10 stakes for account', async () => {
132
133 });
134});138});
135139
136describe('unstake balance extrinsic', () => { 140describe('unstake balance extrinsic', () => {
151 });155 });
152 });156 });
153157
154 it('should unlock balance after unlocking period ends and subtract it from "pendingUnstake"', async () => {158 it('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async () => {
159 // TODO Flaky test
155 await usingPlaygrounds(async (helper) => {160 await usingPlaygrounds(async (helper) => {
156 const staker = accounts.pop()!;161 const staker = accounts.pop()!;
157 await helper.staking.stake(staker, 100n * nominal);162 await helper.staking.stake(staker, 100n * nominal);
158 await helper.staking.unstake(staker);163 await helper.staking.unstake(staker);
159164
160 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n165 // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
161 await waitForRelayBlock(helper.api!, 20);166 await waitForRelayBlock(helper.api!, 20);
162 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n * nominal, miscFrozen: 0n, feeFrozen: 0n});167 expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
163 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);168 expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
164169
165 // staker can transfer:170 // staker can transfer:
192 expect(stakedPerBlock).to.be.deep.equal([]);197 expect(stakedPerBlock).to.be.deep.equal([]);
193 expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);198 expect(unstakedPerBlock).to.be.deep.equal([600n * nominal]);
194199
195 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});200 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 600n * nominal, feeFrozen: 0n, miscFrozen: 0n});
196 await waitForRelayBlock(helper.api!, 20);201 await waitForRelayBlock(helper.api!, 20);
197 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});202 expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
198 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);203 expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
635 it('can not be called by non admin', async () => {640 it('can not be called by non admin', async () => {
636 await usingPlaygrounds(async (helper) => {641 await usingPlaygrounds(async (helper) => {
637 const nonAdmin = accounts.pop()!;642 const nonAdmin = accounts.pop()!;
638 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.payoutStakers(50))).to.be.rejected;643 await expect(helper.signTransaction(nonAdmin, helper.api!.tx.promotion.payoutStakers(100))).to.be.rejected;
639 });644 });
640 });645 });
641646
647 await helper.staking.stake(staker, 100n * nominal);652 await helper.staking.stake(staker, 100n * nominal);
648 await helper.staking.stake(staker, 200n * nominal);653 await helper.staking.stake(staker, 200n * nominal);
649 await waitForRelayBlock(helper.api!, 30);654 await waitForRelayBlock(helper.api!, 30);
650 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));655 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
651656
652 const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);657 const totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
653 expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);658 expect(totalStakedPerBlock).to.be.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n)]);
654 });659 });
655 });660 });
656661
657 it('shoud be paid for more than one period if payments was missed', async () => {662 it('shoud be paid for more than one period if payments was missed', async () => {
663 // TODO flaky test
658 await usingPlaygrounds(async (helper) => {664 await usingPlaygrounds(async (helper) => {
659 const staker = accounts.pop()!;665 const staker = accounts.pop()!;
660666
661 await helper.staking.stake(staker, 100n * nominal);667 await helper.staking.stake(staker, 100n * nominal);
662 await helper.staking.stake(staker, 200n * nominal);668 await helper.staking.stake(staker, 200n * nominal);
663669
664 await waitForRelayBlock(helper.api!, 55);670 await waitForRelayBlock(helper.api!, 55);
665 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));671 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
666 const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});672 const stakedPerBlock = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
667 expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));673 expect(stakedPerBlock[0][1]).to.be.equal(calculateIncome(100n * nominal, 10n, 2));
668 expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));674 expect(stakedPerBlock[1][1]).to.be.equal(calculateIncome(200n * nominal, 10n, 2));
675 });681 });
676 682
677 it('should not be credited for unstaked (reserved) balance', async () => {683 it('should not be credited for unstaked (reserved) balance', async () => {
678 expect.fail('Test not implemented');
679 await usingPlaygrounds(async helper => {684 await usingPlaygrounds(async helper => {
685 // staker unstakes before rewards has been initialized
680 const staker = accounts.pop()!;686 const staker = accounts.pop()!;
687 await helper.staking.stake(staker, 100n * nominal);
688 await waitForRelayBlock(helper.api!, 40);
689 await helper.staking.unstake(staker);
690
691 // so he did not receive any rewards
692 const totalBalanceBefore = await helper.balance.getSubstrate(staker.address);
693 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
694 const totalBalanceAfter = await helper.balance.getSubstrate(staker.address);
695
696 expect(totalBalanceBefore).to.be.equal(totalBalanceAfter);
681 });697 });
682 });698 });
683 699
691 await helper.staking.stake(staker, 300n * nominal);707 await helper.staking.stake(staker, 300n * nominal);
692 708
693 await waitForRelayBlock(helper.api!, 34);709 await waitForRelayBlock(helper.api!, 34);
694 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));710 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
695 let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);711 let totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
696 expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n), calculateIncome(300n * nominal, 10n)]);712 expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n), calculateIncome(200n * nominal, 10n), calculateIncome(300n * nominal, 10n)]);
697 713
698 await waitForRelayBlock(helper.api!, 20);714 await waitForRelayBlock(helper.api!, 20);
699 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(50));715 await helper.signTransaction(palletAdmin, helper.api!.tx.promotion.payoutStakers(100));
700 totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);716 totalStakedPerBlock = (await helper.staking.getTotalStakedPerBlock({Substrate: staker.address})).map(s => s[1]);
701 expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2), calculateIncome(200n * nominal, 10n, 2), calculateIncome(300n * nominal, 10n, 2)]); 717 expect(totalStakedPerBlock).to.deep.equal([calculateIncome(100n * nominal, 10n, 2), calculateIncome(200n * nominal, 10n, 2), calculateIncome(300n * nominal, 10n, 2)]);
702 });718 });
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
6import '@polkadot/api-base/types/storage';6import '@polkadot/api-base/types/storage';
77
8import type { ApiTypes, AugmentedQuery, QueryableStorageEntry } from '@polkadot/api-base/types';8import type { ApiTypes, AugmentedQuery, QueryableStorageEntry } from '@polkadot/api-base/types';
9import type { BTreeMap, Bytes, Option, U256, U8aFixed, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types-codec';9import type { BTreeMap, Bytes, Option, U256, U8aFixed, Vec, bool, u128, u16, u32, u64, u8 } from '@polkadot/types-codec';
10import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';10import type { AnyNumber, ITuple } from '@polkadot/types-codec/types';
11import type { AccountId32, H160, H256 } from '@polkadot/types/interfaces/runtime';11import type { AccountId32, H160, H256 } from '@polkadot/types/interfaces/runtime';
12import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueQueueConfigData, EthereumBlock, EthereumLog, EthereumReceiptReceiptV3, EthereumTransactionTransactionV2, FpRpcTransactionStatus, FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmContractHelpersSponsoringModeT, PalletNonfungibleItemData, PalletRefungibleItemData, PalletTransactionPaymentReleases, PalletTreasuryProposal, PalletUniqueSchedulerScheduledV3, PhantomTypeUpDataStructs, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpRuntimeDigest, SpTrieStorageProof, UpDataStructsCollection, UpDataStructsCollectionStats, UpDataStructsProperties, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsPropertyPermission, UpDataStructsPropertyScope, UpDataStructsSponsorshipStateBasicCrossAccountIdRepr, UpDataStructsTokenChild } from '@polkadot/types/lookup';12import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundChannelDetails, CumulusPalletXcmpQueueOutboundChannelDetails, CumulusPalletXcmpQueueQueueConfigData, EthereumBlock, EthereumLog, EthereumReceiptReceiptV3, EthereumTransactionTransactionV2, FpRpcTransactionStatus, FrameSupportWeightsPerDispatchClassU64, FrameSystemAccountInfo, FrameSystemEventRecord, FrameSystemLastRuntimeUpgradeInfo, FrameSystemPhase, OrmlVestingVestingSchedule, PalletBalancesAccountData, PalletBalancesBalanceLock, PalletBalancesReleases, PalletBalancesReserveData, PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmContractHelpersSponsoringModeT, PalletNonfungibleItemData, PalletRefungibleItemData, PalletTransactionPaymentReleases, PalletTreasuryProposal, PalletUniqueSchedulerScheduledV3, PhantomTypeUpDataStructs, PolkadotCorePrimitivesOutboundHrmpMessage, PolkadotPrimitivesV2AbridgedHostConfiguration, PolkadotPrimitivesV2PersistedValidationData, PolkadotPrimitivesV2UpgradeRestriction, SpRuntimeDigest, SpTrieStorageProof, UpDataStructsCollection, UpDataStructsCollectionStats, UpDataStructsProperties, UpDataStructsPropertiesMapPropertyPermission, UpDataStructsPropertyPermission, UpDataStructsPropertyScope, UpDataStructsSponsorshipStateBasicCrossAccountIdRepr, UpDataStructsTokenChild } from '@polkadot/types/lookup';
512 };512 };
513 promotion: {513 promotion: {
514 admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;514 admin: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;
515 /**515 /**
516 * Stores the address of the staker for which the last revenue recalculation was performed.516 * Stores hash a record for which the last revenue recalculation was performed.
517 * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.517 * If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
518 **/518 **/
519 lastCalcucaltedStaker: AugmentedQuery<ApiType, () => Observable<Option<AccountId32>>, []> & QueryableStorageEntry<ApiType, []>;519 nextCalculatedRecord: AugmentedQuery<ApiType, () => Observable<Option<ITuple<[AccountId32, u32]>>>, []> & QueryableStorageEntry<ApiType, []>;
520 /**520 /**
521 * Next target block when interest is recalculated521 * Next target block when interest is recalculated
522 **/522 **/
529 * Amount of tokens staked by account in the blocknumber.529 * Amount of tokens staked by account in the blocknumber.
530 **/530 **/
531 staked: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<ITuple<[u128, u32]>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;531 staked: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<ITuple<[u128, u32]>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>;
532 /**
533 * Amount of stakes for an Account
534 **/
535 stakesPerAccount: AugmentedQuery<ApiType, (arg: AccountId32 | string | Uint8Array) => Observable<u8>, [AccountId32]> & QueryableStorageEntry<ApiType, [AccountId32]>;
532 /**536 /**
533 * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.537 * A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.
534 **/538 **/