Skip to content

Commit

Permalink
hotfix: merge the latest hotfix branch to main (#1383)
Browse files Browse the repository at this point in the history
* dApps loading error fix for Shibuya (#1377)

* Tier thresholds derivation support (#1376)

* Tier thresholds derivation support

* Additional comments

* Pallet version check

* Fix: estimated realized inflation not showing (#1379)

* Re-try fetch from cbridge (#1382)

---------

Co-authored-by: Bobo <[email protected]>
  • Loading branch information
impelcrypto and bobo-k2 authored Sep 13, 2024
1 parent 8ece1cf commit 0192225
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 73 deletions.
3 changes: 2 additions & 1 deletion src/hooks/useChainInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,10 @@ export function useChainInfo(api: ApiPromise) {
const specName: string = api.runtimeVersion.specName.toString();
const systemChain: string = ((await api.rpc.system.chain()) || '<unknown>').toString();
let info = createInfo(api, systemChain, specName);
chainInfo.value = info;

const metadata = await api.call.metadata.metadataAtVersion(15);
info.rawMetadata = metadata.toHex();

chainInfo.value = info;
});

Expand Down
9 changes: 7 additions & 2 deletions src/staking-v3/components/data/DataList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { defineComponent, computed, onMounted } from 'vue';
import { useDataCalculations } from 'src/staking-v3/hooks';
import DataCard from './DataCard.vue';
import { useDappStaking, useDapps, usePeriod } from 'src/staking-v3/hooks';
Expand All @@ -154,7 +154,8 @@ export default defineComponent({
numberOfStakersAndLockers,
tokensToBeBurned,
} = useDataCalculations();
const { activeInflationConfiguration, estimatedInflation } = useInflation();
const { activeInflationConfiguration, estimatedInflation, estimateRealizedInflation } =
useInflation();

const totalDapps = computed<number>(() => registeredDapps.value?.length ?? 0);
const tvl = computed<string>(() => (currentEraInfo.value?.totalLocked ?? BigInt(0)).toString());
Expand Down Expand Up @@ -182,6 +183,10 @@ export default defineComponent({
estimatedInflation.value ? `${estimatedInflation.value.toFixed(2)} %` : '--'
);

onMounted(() => {
estimateRealizedInflation();
});

return {
protocolState,
periodName,
Expand Down
2 changes: 1 addition & 1 deletion src/staking-v3/components/leaderboard/Tier.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<div class="text--reward">{{ $t('stakingV3.threshold') }}</div>
<div class="text--amount">
<token-balance-native
:balance="tiersConfiguration?.tierThresholds[tier - 1]?.amount?.toString() ?? '0'"
:balance="tiersConfiguration?.tierThresholds[tier - 1]?.toString() ?? '0'"
:decimals="0"
/>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/staking-v3/hooks/useDapps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function useDapps() {

try {
aggregator.publish(new BusyMessage(true));
const dApps = await service.getDapps();
const dApps = await service.getDapps(currentNetworkName.value.toLowerCase());
store.commit('stakingV3/addDapps', dApps.fullInfo);
store.commit('stakingV3/addNewDapps', dApps.chainInfo);
// Memo: this can a heavy operations since we are querying all dapps stakes for a chain.
Expand Down
13 changes: 9 additions & 4 deletions src/staking-v3/logic/interfaces/DappStakingV3.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Balance } from '@astar-network/metamask-astar-types';
import { AccountId32, Permill } from '@polkadot/types/interfaces';
import { AccountId32, Perbill, Permill } from '@polkadot/types/interfaces';
import {
BTreeMap,
Compact,
Expand Down Expand Up @@ -126,14 +126,19 @@ export interface PalletDappStakingV3ContractStakeAmount extends Struct {
readonly tierLabel: Option<PalletDappStakingV3TierLabel>;
}

export interface PalletDappStakingV3TiersConfiguration extends Struct {
readonly numberOfSlots: Compact<u16>;
export interface PalletDappStakingV3TiersConfigurationLegacy extends Struct {
readonly slotsPerTier: Vec<u16>;
readonly rewardPortion: Vec<Permill>;
readonly tierThresholds: Vec<PalletDappStakingV3TierThreshold>;
}

interface PalletDappStakingV3TierThreshold extends Enum {
export interface PalletDappStakingV3TiersConfiguration extends Struct {
readonly slotsPerTier: Vec<u16>;
readonly rewardPortion: Vec<Perbill>;
readonly tierThresholds: Vec<u128>;
}

export interface PalletDappStakingV3TierThreshold extends Enum {
readonly isFixedTvlAmount: boolean;
readonly asFixedTvlAmount: {
readonly amount: u128;
Expand Down
8 changes: 1 addition & 7 deletions src/staking-v3/logic/models/DappStaking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,13 +172,7 @@ export interface TiersConfiguration {
readonly numberOfSlots: number;
readonly slotsPerTier: number[];
readonly rewardPortion: number[];
readonly tierThresholds: TierThreshold[];
}

interface TierThreshold {
readonly amount: BigInt;
readonly minimumAmount?: BigInt;
readonly type: TvlAmountType;
readonly tierThresholds: bigint[];
}

export interface InflationParam {
Expand Down
50 changes: 33 additions & 17 deletions src/staking-v3/logic/repositories/DappStakingRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import {
SingularStakingInfo,
StakeAmount,
TiersConfiguration,
TvlAmountType,
} from '../models';
import axios from 'axios';
import { inject, injectable } from 'inversify';
Expand All @@ -38,10 +37,12 @@ import {
PalletDappStakingV3SingularStakingInfo,
PalletDappStakingV3StakeAmount,
PalletDappStakingV3TiersConfiguration,
PalletDappStakingV3TiersConfigurationLegacy,
PalletDappStakingV3TierThreshold,
SmartContractAddress,
} from '../interfaces';
import { IEventAggregator } from 'src/v2/messaging';
import { Option, StorageKey, u32, u128, Bytes } from '@polkadot/types';
import { Option, StorageKey, u32, u128, Bytes, u16 } from '@polkadot/types';
import { IDappStakingRepository } from './IDappStakingRepository';
import { Guard } from 'src/v2/common';
import { ethers } from 'ethers';
Expand Down Expand Up @@ -512,26 +513,41 @@ export class DappStakingRepository implements IDappStakingRepository {
}

public async getTiersConfiguration(): Promise<TiersConfiguration> {
const TIER_DERIVATION_PALLET_VERSION = 8;
const api = await this.api.getApi();
const configuration =
await api.query.dappStaking.tierConfig<PalletDappStakingV3TiersConfiguration>();
const palletVersion = (await api.query.dappStaking.palletVersion<u16>()).toNumber();
let configuration:
| PalletDappStakingV3TiersConfiguration
| PalletDappStakingV3TiersConfigurationLegacy;

if (palletVersion >= TIER_DERIVATION_PALLET_VERSION) {
configuration =
await api.query.dappStaking.tierConfig<PalletDappStakingV3TiersConfiguration>();
} else {
configuration =
await api.query.dappStaking.tierConfig<PalletDappStakingV3TiersConfigurationLegacy>();
}

return {
numberOfSlots: configuration.numberOfSlots.toNumber(),
numberOfSlots: configuration.slotsPerTier.reduce((acc, val) => acc + val.toNumber(), 0),
slotsPerTier: configuration.slotsPerTier.map((slot) => slot.toNumber()),
rewardPortion: configuration.rewardPortion.map((portion) => portion.toNumber() / 1_000_000),
tierThresholds: configuration.tierThresholds.map((threshold) =>
threshold.isDynamicTvlAmount
? {
type: TvlAmountType.DynamicTvlAmount,
amount: threshold.asDynamicTvlAmount.amount.toBigInt(),
minimumAmount: threshold.asDynamicTvlAmount.minimumAmount.toBigInt(),
}
: {
type: TvlAmountType.FixedTvlAmount,
amount: threshold.asFixedTvlAmount.amount.toBigInt(),
}
),
tierThresholds: configuration.tierThresholds.map((threshold) => {
// Support both u128 and PalletDappStakingV3TierThreshold.
// If threshold has isUnsigned property it's u128.
// TODO: remove palletVersion check when u128 is used for all thresholds. Most likely in Astar period 003.
if (palletVersion < TIER_DERIVATION_PALLET_VERSION) {
const t = <PalletDappStakingV3TierThreshold>threshold;
if (t.isDynamicTvlAmount) {
return t.asDynamicTvlAmount.amount.toBigInt();
} else {
return t.asFixedTvlAmount.amount.toBigInt();
}
} else {
const t = <u128>threshold;
return t.toBigInt();
}
}),
};
}

Expand Down
12 changes: 7 additions & 5 deletions src/staking-v3/logic/services/DappStakingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,15 @@ export class DappStakingService extends SignerService implements IDappStakingSer
}

// @inheritdoc
public async getDapps(): Promise<{ fullInfo: CombinedDappInfo[]; chainInfo: DappInfo[] }> {
const metadata = await this.metadataRepository.getChainMetadata();
const chain = metadata.chain.toLowerCase();
public async getDapps(
network: string
): Promise<{ fullInfo: CombinedDappInfo[]; chainInfo: DappInfo[] }> {
Guard.ThrowIfUndefined('network', network);

const [storeDapps, chainDapps, tokenApiDapps] = await Promise.all([
this.dappStakingRepository.getDapps(chain),
this.dappStakingRepository.getDapps(network.toLowerCase()),
this.dappStakingRepository.getChainDapps(),
this.tokenApiRepository.getDapps(chain),
this.tokenApiRepository.getDapps(network.toLowerCase()),
]);

// Map on chain and in store dApps (registered only)
Expand Down
2 changes: 1 addition & 1 deletion src/staking-v3/logic/services/IDappStakingService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export interface IDappStakingService {
* Gets the dapps for the given network.
* @returns A map containing full dapps info (chain and firebase data) and chain info (only for new dapps not stored in firebase yet).
*/
getDapps(): Promise<{ fullInfo: CombinedDappInfo[]; chainInfo: DappInfo[] }>;
getDapps(network: string): Promise<{ fullInfo: CombinedDappInfo[]; chainInfo: DappInfo[] }>;

/**
* Invokes claim staker rewards, unstake and unlock calls.
Expand Down
74 changes: 40 additions & 34 deletions src/v2/repositories/implementations/EvmAssetsRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export class EvmAssetsRepository implements IEvmAssetsRepository {
isFetchUsd: boolean;
}): Promise<Erc20Token[]> {
Guard.ThrowIfUndefined('currentAccount', currentAccount);
const numberOfRetries = 2;

if (
String(srcChainId) === providerEndpoints[endpointKey.SHIBUYA].evmChainId ||
Expand All @@ -67,43 +68,48 @@ export class EvmAssetsRepository implements IEvmAssetsRepository {
return [];
}

const data = await getTransferConfigs(currentNetworkIdx);
if (!data || !data.tokens) {
throw Error('Cannot fetch from cBridge API');
}
const seen = new Set();
// Todo: use srcChain and destChainID to re-define token information for bridging (ex: PKEX)
for (let i = 0; i < numberOfRetries; i++) {
const data = await getTransferConfigs(currentNetworkIdx);
if (!data || !data.tokens) {
continue;
}

const tokens = (await Promise.all(
objToArray(data.tokens[srcChainId as EvmChain])
.flat()
.map(async (token: CbridgeToken) => {
const t = getSelectedToken({ srcChainId, token });
if (!t) return undefined;
const formattedToken = castCbridgeToErc20({ srcChainId, token: t });
const isDuplicated = seen.has(formattedToken.address);
seen.add(formattedToken.address);
// Memo: Remove the duplicated contract address (ex: PKEX)
if (isDuplicated) return undefined;
const seen = new Set();
// Todo: use srcChain and destChainID to re-define token information for bridging (ex: PKEX)

const { balUsd, userBalance } = await this.updateTokenBalanceHandler({
userAddress: currentAccount,
token: formattedToken,
isFetchUsd,
srcChainId,
});
const tokenWithBalance = {
...formattedToken,
userBalance,
userBalanceUsd: String(balUsd),
};
return castCbridgeTokenData(tokenWithBalance);
})
)) as Erc20Token[];
const tokens = (await Promise.all(
objToArray(data.tokens[srcChainId as EvmChain])
.flat()
.map(async (token: CbridgeToken) => {
const t = getSelectedToken({ srcChainId, token });
if (!t) return undefined;
const formattedToken = castCbridgeToErc20({ srcChainId, token: t });
const isDuplicated = seen.has(formattedToken.address);
seen.add(formattedToken.address);
// Memo: Remove the duplicated contract address (ex: PKEX)
if (isDuplicated) return undefined;

return tokens.filter((token) => {
return token !== undefined;
});
const { balUsd, userBalance } = await this.updateTokenBalanceHandler({
userAddress: currentAccount,
token: formattedToken,
isFetchUsd,
srcChainId,
});
const tokenWithBalance = {
...formattedToken,
userBalance,
userBalanceUsd: String(balUsd),
};
return castCbridgeTokenData(tokenWithBalance);
})
)) as Erc20Token[];

return tokens.filter((token) => {
return token !== undefined;
});
}

throw Error('Cannot fetch from cBridge API');
}

public async fetchRegisteredAssets({
Expand Down

0 comments on commit 0192225

Please sign in to comment.