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

Feat: Bond proxy #1636

Merged
merged 19 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
16 changes: 8 additions & 8 deletions src/renderer/entities/operation/ui/SignButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,6 @@ import { SignableWalletFamily, WalletType } from '@shared/core';
import { Button, Icon } from '@shared/ui';
import { IconNames } from '@shared/ui/Icon/data';

type Props = {
type?: WalletType;
disabled?: boolean;
onClick?: () => void;
className?: string;
};

const WalletIcon: Record<SignableWalletFamily, IconNames> = {
[WalletType.POLKADOT_VAULT]: 'vault',
[WalletType.WALLET_CONNECT]: 'walletConnect',
Expand All @@ -30,7 +23,14 @@ const WalletText: Record<SignableWalletFamily, string> = {

const UnkownWalletText = 'operation.sign.unknown';

export const SignButton = ({ disabled, type, onClick, className }: Props) => {
type Props = {
type?: WalletType; // TODO: should not be undefined
disabled?: boolean;
className?: string;
onClick?: () => void;
};

export const SignButton = ({ disabled, type, className, onClick }: Props) => {
const { t } = useI18n();

return (
Expand Down
111 changes: 59 additions & 52 deletions src/renderer/entities/staking/api/eraService.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,66 @@
import { ApiPromise } from '@polkadot/api';

import { IEraService } from '../lib/types';
import type { EraIndex } from '@shared/core';

export const useEra = (): IEraService => {
const subscribeActiveEra = (api: ApiPromise, callback: (era?: EraIndex) => void): Promise<() => void> => {
return api.query.staking.activeEra((data: any) => {
try {
const unwrappedData = data.unwrap();
callback(unwrappedData.get('index').toNumber());
} catch (error) {
console.warn(error);
callback(undefined);
}
});
};

const getTimeToEra = async (api: ApiPromise, destinationEra?: EraIndex): Promise<number> => {
if (!destinationEra) return 0;

const eraLength = api.consts.staking.sessionsPerEra.toNumber();
const sessionDuration = api.consts.babe.epochDuration.toNumber();
const blockTime = api.consts.babe.expectedBlockTime.toNumber() / 1000;

const activeEra = (await api.query.staking.activeEra()).unwrap().index;

const { eraStartSessionIndex, currentSessionIndex, currentSlot, genesisSlot } = await Promise.all([
api.query.staking.erasStartSessionIndex(activeEra),
api.query.session.currentIndex(),
api.query.babe.currentSlot(),
api.query.babe.genesisSlot(),
]).then(([eraStartSessionIndex, currentSessionIndex, currentSlot, genesisSlot]) => {
return {
eraStartSessionIndex: eraStartSessionIndex.unwrap().toNumber(),
currentSessionIndex: currentSessionIndex.toNumber(),
currentSlot: currentSlot.toNumber(),
genesisSlot: genesisSlot.toNumber(),
};
});

const sessionStartSlot = currentSessionIndex * sessionDuration + genesisSlot;
const sessionProgress = currentSlot - sessionStartSlot;
const eraProgress = (currentSessionIndex - eraStartSessionIndex) * sessionDuration + sessionProgress;
let eraRemained = eraProgress;
if (eraProgress > 0 && eraProgress > eraLength * sessionDuration) {
eraRemained = eraProgress % (eraLength * sessionDuration);
export const eraService = {
subscribeActiveEra,
getActiveEra,
getTimeToEra,
};

function subscribeActiveEra(api: ApiPromise, callback: (era?: EraIndex) => void): Promise<() => void> {
return api.query.staking.activeEra((data: any) => {
try {
const unwrappedData = data.unwrap();
callback(unwrappedData.get('index').toNumber());
} catch (error) {
console.warn(error);
callback(undefined);
}
const leftEras = destinationEra - activeEra.toNumber() - 1;
const blocksLeftForEras = leftEras * eraLength * sessionDuration;
});
}

return (eraRemained + blocksLeftForEras) * blockTime;
};
async function getActiveEra(api: ApiPromise): Promise<EraIndex | undefined> {
const eraData = await api.query.staking.activeEra();

return {
subscribeActiveEra,
getTimeToEra,
};
};
if (eraData.isNone) return undefined;

// @ts-ignore
return eraData.unwrap().get('index').toNumber();
}

async function getTimeToEra(api: ApiPromise, destinationEra?: EraIndex): Promise<number> {
if (!destinationEra) return 0;

const eraLength = api.consts.staking.sessionsPerEra.toNumber();
const sessionDuration = api.consts.babe.epochDuration.toNumber();
const blockTime = api.consts.babe.expectedBlockTime.toNumber() / 1000;

const activeEra = (await api.query.staking.activeEra()).unwrap().index;

const { eraStartSessionIndex, currentSessionIndex, currentSlot, genesisSlot } = await Promise.all([
api.query.staking.erasStartSessionIndex(activeEra),
api.query.session.currentIndex(),
api.query.babe.currentSlot(),
api.query.babe.genesisSlot(),
]).then(([eraStartSessionIndex, currentSessionIndex, currentSlot, genesisSlot]) => {
return {
eraStartSessionIndex: eraStartSessionIndex.unwrap().toNumber(),
currentSessionIndex: currentSessionIndex.toNumber(),
currentSlot: currentSlot.toNumber(),
genesisSlot: genesisSlot.toNumber(),
};
});

const sessionStartSlot = currentSessionIndex * sessionDuration + genesisSlot;
const sessionProgress = currentSlot - sessionStartSlot;
const eraProgress = (currentSessionIndex - eraStartSessionIndex) * sessionDuration + sessionProgress;
let eraRemained = eraProgress;
if (eraProgress > 0 && eraProgress > eraLength * sessionDuration) {
eraRemained = eraProgress % (eraLength * sessionDuration);
}
const leftEras = destinationEra - activeEra.toNumber() - 1;
const blocksLeftForEras = leftEras * eraLength * sessionDuration;

return (eraRemained + blocksLeftForEras) * blockTime;
}
3 changes: 1 addition & 2 deletions src/renderer/entities/staking/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export { getAvgApy, getValidatorsApy } from './apyCalculator';
export { useEra } from './eraService';
export { useStakingData } from './stakingDataService';
export { useStakingRewards } from './stakingRewardsService';
export { validatorsService } from './validatorsService';
export { useValidatorsMap } from '../lib/useValidatorsMap';
export { eraService } from './eraService';
9 changes: 0 additions & 9 deletions src/renderer/entities/staking/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,6 @@ export interface IStakingRewardsService {
isRewardsLoading: boolean;
}

// =====================================================
// ========== IValidatorsService interface =============
// =====================================================

export interface IEraService {
subscribeActiveEra: (api: ApiPromise, callback: (era?: EraIndex) => void) => Promise<() => void>;
getTimeToEra: (api: ApiPromise, era?: EraIndex) => Promise<number>;
}

// =====================================================
// ======================= General =====================
// =====================================================
Expand Down
6 changes: 2 additions & 4 deletions src/renderer/entities/staking/lib/useValidatorsMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,17 @@ import { useEffect, useState } from 'react';
import { ApiPromise } from '@polkadot/api';

import { ValidatorMap } from './types';
import { useEra, validatorsService } from '../api';
import { validatorsService, eraService } from '../api';

export const useValidatorsMap = (api?: ApiPromise, isLightClient?: boolean): ValidatorMap => {
const { subscribeActiveEra } = useEra();

const [era, setEra] = useState<number>();
const [validators, setValidators] = useState<ValidatorMap>({});

useEffect(() => {
let unsubEra: () => void | undefined;

if (api?.query.staking) {
subscribeActiveEra(api, setEra).then((unsubFn) => (unsubEra = unsubFn));
eraService.subscribeActiveEra(api, setEra).then((unsubFn) => (unsubEra = unsubFn));
}

return () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useI18n } from '@app/providers';
import { BaseModal, BodyText, Identicon, Truncate } from '@shared/ui';
import { cnTw, stakeableAmount, toAddress } from '@shared/lib/utils';
import type { Account, Asset, ChainId, Explorer, AccountId } from '@shared/core';
import type { Account, Asset, ChainId, AccountId } from '@shared/core';
import { AssetBalance } from '../../../asset';
import { useAssetBalances } from '../../../balance';

Expand All @@ -11,12 +11,11 @@ type Props = {
amounts?: string[];
asset: Asset;
chainId: ChainId;
explorers?: Explorer[];
addressPrefix: number;
onClose: () => void;
};

export const AccountsModal = ({ isOpen, accounts, asset, chainId, explorers, addressPrefix, onClose }: Props) => {
export const AccountsModal = ({ isOpen, accounts, asset, chainId, addressPrefix, onClose }: Props) => {
const { t } = useI18n();

const accountIds = accounts.map((account) => account.accountId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { BaseModal } from '@shared/ui';
import { useI18n } from '@app/providers';
import { Validator } from '@shared/core/types/validator';
import type { Explorer } from '@shared/core';
import { ValidatorsTable } from '@entities/staking/ui';

type Props = {
isOpen: boolean;
validators: Validator[];
explorers?: Explorer[];
onClose: () => void;
};

export const SelectedValidatorsModal = ({ isOpen, validators, explorers, onClose }: Props) => {
export const SelectedValidatorsModal = ({ isOpen, validators, onClose }: Props) => {
const { t } = useI18n();

return (
Expand All @@ -30,7 +28,7 @@ export const SelectedValidatorsModal = ({ isOpen, validators, explorers, onClose
key={validator.address}
className="grid items-center pl-5 pr-2 shrink-0 h-10 grid-cols-[1fr,40px] hover:bg-hover group"
>
<ValidatorsTable.ShortRow validator={validator} explorers={explorers} />
<ValidatorsTable.ShortRow validator={validator} />
</li>
))}
</ul>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ const TABLE_GRID_CELLS = 'grid-cols-[1fr,128px,128px,40px]';

type TableProps = {
validators: Validator[];
children: (validator: Validator, rowStyle: string) => JSX.Element;
listClassName?: string;
children: (validator: Validator, rowStyle: string) => JSX.Element;
};

const ValidatorsTableRoot = ({ validators, children, listClassName }: TableProps) => {
Expand Down Expand Up @@ -42,7 +42,7 @@ type RowProps = {
explorers?: Explorer[];
};

const ValidatorRow = ({ validator, explorers = [], asset }: RowProps) => (
const ValidatorRow = ({ validator, asset, explorers = [] }: RowProps) => (
<>
<div className="flex gap-x-2 items-center mr-auto" data-testid="validator">
<Identicon address={validator.address} background={false} size={20} />
Expand Down Expand Up @@ -76,27 +76,17 @@ const ValidatorRow = ({ validator, explorers = [], asset }: RowProps) => (
</>
);

const ValidatorShortRow = ({ validator, explorers = [] }: RowProps) => (
<>
<div className="flex gap-x-2 items-center mr-auto">
<Identicon address={validator.address} background={false} size={20} />
<div className="flex flex-col max-w-[276px]">
{validator.identity ? (
<BodyText className="text-text-secondary">{getComposedIdentity(validator.identity)}</BodyText>
) : (
<Truncate
className="text-body text-text-secondary"
ellipsis="..."
start={4}
end={4}
text={validator.address}
/>
)}
</div>
const ValidatorShortRow = ({ validator }: Pick<RowProps, 'validator'>) => (
<div className="flex gap-x-2 items-center mr-auto">
<Identicon address={validator.address} background={false} size={20} />
<div className="flex flex-col max-w-[276px]">
{validator.identity ? (
<BodyText className="text-text-secondary">{getComposedIdentity(validator.identity)}</BodyText>
) : (
<Truncate className="text-body text-text-secondary" ellipsis="..." start={4} end={4} text={validator.address} />
)}
</div>

<ExplorersPopover button={<IconButton name="info" />} address={validator.address} explorers={explorers} />
</>
</div>
);

export const ValidatorsTable = Object.assign(ValidatorsTableRoot, {
Expand Down
10 changes: 0 additions & 10 deletions src/renderer/entities/transaction/lib/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import type {
CallData,
HexString,
Timepoint,
Threshold,
AccountId,
ChainId,
MultisigAccount,
Expand All @@ -30,17 +29,8 @@ export type ITransactionService = {
unsigned: UnsignedTransaction;
payload: Uint8Array;
}>;
getSignedExtrinsic: (unsigned: UnsignedTransaction, signature: HexString, api: ApiPromise) => Promise<string>;
submitAndWatchExtrinsic: (
tx: string,
unsigned: UnsignedTransaction,
api: ApiPromise,
callback: (executed: boolean, params: ExtrinsicResultParams | string) => void,
) => void;
getTransactionFee: (transaction: Transaction, api: ApiPromise) => Promise<string>;
getExtrinsicWeight: (extrinsic: SubmittableExtrinsic<'promise'>) => Promise<Weight>;
getTxWeight: (transaction: Transaction, api: ApiPromise) => Promise<Weight>;
getMultisigDeposit: (threshold: Threshold, api: ApiPromise) => string;
getTransactionHash: (transaction: Transaction, api: ApiPromise) => HashData;
decodeCallData: (api: ApiPromise, accountId: Address, callData: CallData) => DecodedTransaction;
verifySignature: (payload: Uint8Array, signature: HexString, accountId: AccountId) => Boolean;
Expand Down
Loading
Loading