Skip to content
This repository has been archived by the owner on May 10, 2023. It is now read-only.

Commit

Permalink
Merge pull request #179 from darwinia-network/staking-opt
Browse files Browse the repository at this point in the history
Staking opt
  • Loading branch information
WoeOm authored Feb 1, 2021
2 parents 72488b2 + 53c01f2 commit 7bd0768
Show file tree
Hide file tree
Showing 21 changed files with 126 additions and 102 deletions.
10 changes: 5 additions & 5 deletions packages/apps-config/src/settings/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ function createLive (t: (key: string, text: string, options: { ns: string }) =>

function createTest (t: (key: string, text: string, options: { ns: string }) => string): Option[] {
return [
// {
// info: 'darwinia',
// text: t('rpc.darwinia', 'Darwinia Network (hosted by Darwinia)', { ns: 'apps-config' }),
// value: 'wss://cc1.darwinia.network'
// }
{
info: 'Pangolin',
text: t('rpc.pangolin.darwinia', 'Pangolin Test Network (hosted by Darwinia)', { ns: 'apps-config' }),
value: 'ws://t1.hkg.itering.com:9944'
}
];
}

Expand Down
1 change: 1 addition & 0 deletions packages/apps/public/locales/en/apps-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"rpc.kusama.parity": "Kusama (Polkadot Canary, hosted by Parity)",
"rpc.kusama.w3f": "Kusama (Polkadot Canary, hosted by Web3 Foundation)",
"rpc.local": "Local Node (Own, 127.0.0.1:9944)",
"rpc.pangolin.darwinia": "Pangolin Network (hosted by Darwinia)",
"rpc.westend": "Westend (Polkadot Testnet, hosted by Parity)",
"ss58.centrifuge": "Centrifuge (live)",
"ss58.crab": "Crab (live)",
Expand Down
3 changes: 2 additions & 1 deletion packages/apps/public/locales/en/page-staking-darwinia.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@
"last reward": "last reward",
"lock limit": "lock limit",
"locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional KTON rewards.": "locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional KTON rewards.",
"locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional {{KTON}} rewards.": "locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional {{KTON}} rewards.",
"nominators": "nominators",
"other stake": "other stake(Power)",
"own stake": "own stake(Power)",
Expand Down Expand Up @@ -159,4 +160,4 @@
"{{currency}} slashed": "{{currency}} slashed",
"{{currency}} total": "{{currency}} total",
"{{days}} days": "{{days}} days"
}
}
4 changes: 2 additions & 2 deletions packages/apps/public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,7 @@
"locked": "",
"locked balance": "",
"locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional KTON rewards.": "",
"locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional {{KTON}} rewards.": "",
"logs": "",
"manage hardware connections": "",
"matches": "",
Expand Down Expand Up @@ -995,7 +996,6 @@
"proposer": "",
"queued tx": "",
"reason": "",
"Rebond funds": "",
"recent blocks": "",
"recent events": "",
"record my vote as": "",
Expand Down Expand Up @@ -1165,4 +1165,4 @@
"{{threshold}}, passing": "",
"{{value}}, {{remaining}} blocks left": "",
"{{value}}x voting balance, locked for {{lock}}x enactment ({{period}} days)": ""
}
}
3 changes: 2 additions & 1 deletion packages/apps/public/locales/zh/apps-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
"rpc.header.test": "测试网络",
"rpc.kusama.w3f": "Darwinia Network (hosted by Darwinia)",
"rpc.local": "Local Node (Own, 127.0.0.1:9944)",
"rpc.pangolin.darwinia": "Pangolin 测试网络 (hosted by Darwinia)",
"ss58.crab": "Crab (live)",
"ss58.darwinia": "Darwinia (live)",
"ss58.default": "默认的验证人配置",
"ss58.substrate": "Substrate (generic)"
}
}
2 changes: 1 addition & 1 deletion packages/apps/public/locales/zh/page-staking-darwinia.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"Amount": "数量",
"Amount taken up-front from the reward by the validator before splitting the remainder between themselves and the nominators": "确认之前从奖励中预先提取的金额,然后将剩余部分分配给自己和提名人",
"Amount to add to the currently bonded funds. This is adjusted using the available funds on the account.": "当前质押金额的总量. 使用帐户中的可用资金进行调整.",
"Amount to add to the currently deposit funds. This is adjusted using the bonded funds on the account.": "Amount to add to the currently deposit funds. This is adjusted using the bonded funds on the account.",
"Amount to add to the currently deposit funds. This is adjusted using the bonded funds on the account.": "将冻结资产转换为锁定资产的数量",
"An account that is to receive the rewards.": "接收收益的账号",
"Any account can request payout for stakers, this is not limited to accounts that will be rewarded.": "Any account can request payout for stakers, this is not limited to accounts that will be rewarded.",
"Aura": "Aura",
Expand Down
2 changes: 1 addition & 1 deletion packages/apps/public/locales/zh/react-signer.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@
"wrong password": "密码错误",
"wrong password supplied": "密码错误",
"{{total}} estimated total amount (fees + value)": "{{total}} 估算的总金额(费用+转账数量)"
}
}
4 changes: 2 additions & 2 deletions packages/apps/public/locales/zh/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,7 @@
"locked": "",
"locked balance": "",
"locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional KTON rewards.": "",
"locked: The amount of tokens that cannot be operated and has a lock limit, which is used to gain voting power and earn additional {{KTON}} rewards.": "",
"logs": "",
"manage hardware connections": "",
"matches": "",
Expand Down Expand Up @@ -995,7 +996,6 @@
"proposer": "",
"queued tx": "",
"reason": "",
"Rebond funds": "",
"recent blocks": "",
"recent events": "",
"record my vote as": "",
Expand Down Expand Up @@ -1165,4 +1165,4 @@
"{{threshold}}, passing": "",
"{{value}}, {{remaining}} blocks left": "",
"{{value}}x voting balance, locked for {{lock}}x enactment ({{period}} days)": ""
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class BondExtra extends TxComponent<Props, State> {
public render (): React.ReactNode {
const { isOpen, onClose, stashId, t } = this.props;
const { accept, currencyType, extrinsic, maxAdditional, promiseMonth } = this.state;
const canSubmit = !!maxAdditional && maxAdditional.gtn(0) && promiseMonth;
const canSubmit = !!maxAdditional && maxAdditional.gtn(0) && promiseMonth && accept;

if (!isOpen) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,7 @@ function Account ({ allStashes, className, isInElection, isOwnStash, next, onUpd
{t('Deposit')}
</Menu.Item>
<Menu.Item
// disabled={!isOwnController || isInElection}
disabled={isInElection}
onClick={toggleRebond}
>
{t('Rebond funds')}
Expand Down
4 changes: 2 additions & 2 deletions packages/page-staking/src/Targets/Validator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ interface Props {
toggleSelected: (accountId: string) => void;
}

function Validator ({ canSelect, info: { accountId, bondOther, bondOwn, bondTotal, commissionPer, currentEraCommissionPer, isCommission, isFavorite, isNominating, key, numNominators, rankOverall, rewardPayout, validatorPayment }, isSelected, toggleFavorite, toggleSelected }: Props): React.ReactElement<Props> {
function Validator ({ canSelect, info: { accountId, bondOther, bondOwn, bondTotal, commissionPer, currentEraCommissionPer, isCommission, isFavorite, isNominating, isValidator, key, numNominators, rankOverall, rewardPayout, validatorPayment }, isSelected, toggleFavorite, toggleSelected }: Props): React.ReactElement<Props> {
const _onQueryStats = useCallback(
(): void => {
window.location.hash = `/staking/query/${key}`;
Expand All @@ -34,7 +34,7 @@ function Validator ({ canSelect, info: { accountId, bondOther, bondOwn, bondTota
);

return (
<tr className={`${isNominating && 'isHighlight'}`}>
<tr className={`${isNominating && 'isHighlight'} ${!isValidator && 'isWaiting'}`}>
<Favorite
address={key}
isFavorite={isFavorite}
Expand Down
23 changes: 13 additions & 10 deletions packages/page-staking/src/Targets/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,14 @@ function sort (sortBy: TargetSortBy, sortFromMax: boolean, validators: Validator
validators[a].isFavorite === validators[b].isFavorite
? 0
: (validators[a].isFavorite ? -1 : 1)
).sort((a, b) =>
validators[a].isValidator === validators[b].isValidator
? 0
: (validators[a].isValidator ? -1 : 1)
);
}

function Targets ({ className, ownStashes, targets: { calcWith, lastReward, nominators, setCalcWith, toggleFavorite, totalStaked, validators, waitings } }: Props): React.ReactElement<Props> {
function Targets ({ className, ownStashes, targets: { calcWith, lastReward, nominators, setCalcWith, toggleFavorite, totalStaked, validators } }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const ownNominators = useOwnNominators(ownStashes);
const [selected, setSelected] = useState<string[]>([]);
Expand Down Expand Up @@ -137,15 +141,14 @@ function Targets ({ className, ownStashes, targets: { calcWith, lastReward, nomi
// filter={filter}
header={header}
>
{validators && sorted && (validators.length === sorted.length) && sorted.map((index): React.ReactNode =>
<Validator
canSelect={selected.length < MAX_NOMINATIONS}
info={validators[index]}
isSelected={selected.includes(validators[index].key)}
key={validators[index].key}
toggleFavorite={toggleFavorite}
toggleSelected={_toggleSelected}
/>
{validators && sorted && (validators.length === sorted.length) && sorted.map((index): React.ReactNode => <Validator
canSelect={selected.length < MAX_NOMINATIONS}
info={validators[index]}
isSelected={selected.includes(validators[index].key)}
key={validators[index].key}
toggleFavorite={toggleFavorite}
toggleSelected={_toggleSelected}
/>
)}
</Table>
</div>
Expand Down
1 change: 1 addition & 0 deletions packages/page-staking/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export interface ValidatorInfo extends ValidatorInfoRank {
isCommission: boolean;
isFavorite: boolean;
isNominating: boolean;
isValidator: boolean;
key: string;
numNominators: number;
rewardPayout: BN;
Expand Down
69 changes: 5 additions & 64 deletions packages/page-staking/src/useSortedTargets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function mapIndex (mapBy: TargetSortBy): (info: ValidatorInfo, index: number) =>

function sortValidators (list: ValidatorInfo[]): ValidatorInfo[] {
return list
.filter((a) => a.bondTotal.gtn(0))
// .filter((a) => a.bondTotal.gtn(0))
.sort((a, b) => b.commissionPer - a.commissionPer)
.map(mapIndex('rankComm'))
.sort((a, b) => b.currentEraCommissionPer - a.currentEraCommissionPer)
Expand Down Expand Up @@ -71,7 +71,7 @@ function extractInfo (allAccounts: string[], amount: BN = baseBalance(), elected
const perValidatorReward = lastReward.divn(electedInfo.info.length);

const validators = sortValidators(
electedInfo.info.map(({ accountId, exposure: _exposure, validatorPrefs }, index): ValidatorInfo => {
[...electedInfo.info, ...waitingInfo.info].map(({ accountId, exposure: _exposure, validatorPrefs }, index): ValidatorInfo => {
const exposure = _exposure || {
others: registry.createType('Vec<IndividualExposure>'),
own: registry.createType('Compact<Balance>'),
Expand Down Expand Up @@ -109,10 +109,11 @@ function extractInfo (allAccounts: string[], amount: BN = baseBalance(), elected
bondShare: 0,
bondTotal,
commissionPer: (((prefs as ValidatorPrefs).commission?.unwrap() || new BN(0)).toNumber() / 10_000_000),
currentEraCommissionPer: ((electedInfo.activeComminssions[index].commission?.unwrap() || new BN(0)).toNumber() / 10_000_000),
currentEraCommissionPer: ((electedInfo.activeComminssions[index]?.commission?.unwrap() || new BN(0)).toNumber() / 10_000_000),
isCommission: !!(prefs as ValidatorPrefs).commission,
isFavorite: favorites.includes(key),
isNominating,
isValidator: index < electedInfo.info.length,
key,
numNominators: exposure.others.length,
rankBondOther: 0,
Expand All @@ -130,67 +131,7 @@ function extractInfo (allAccounts: string[], amount: BN = baseBalance(), elected
})
);

const waitings = sortValidators(
waitingInfo.info.map(({ accountId, exposure: _exposure, validatorPrefs }, index): ValidatorInfo => {
const exposure = _exposure || {
others: registry.createType('Vec<IndividualExposure>'),
own: registry.createType('Compact<Balance>'),
total: registry.createType('Compact<Balance>')
};
const prefs = (validatorPrefs as (ValidatorPrefs | ValidatorPrefsTo196)) || {
commission: registry.createType('Compact<Perbill>')
};
const bondOwn = exposure.ownPower;
const bondTotal = exposure.totalPower;
const validatorPayment = (prefs as ValidatorPrefsTo196).validatorPayment
? (prefs as ValidatorPrefsTo196).validatorPayment.unwrap() as BN
: (prefs as ValidatorPrefs).commission.unwrap().mul(perValidatorReward).div(PERBILL);
const key = accountId.toString();
const rewardSplit = perValidatorReward.sub(validatorPayment);
const rewardPayout = rewardSplit.gtn(0)
? amount.mul(rewardSplit).div(amount.add(bondTotal))
: new BN(0);
const isNominating = exposure.others.reduce((isNominating, indv): boolean => {
const nominator = indv.who.toString();

if (!nominators.includes(nominator)) {
nominators.push(nominator);
}

return isNominating || allAccounts.includes(nominator);
}, allAccounts.includes(key));

totalStaked = totalStaked.add(bondTotal);

return {
accountId,
bondOther: bondTotal.sub(bondOwn),
bondOwn,
bondShare: 0,
bondTotal,
commissionPer: (((prefs as ValidatorPrefs).commission?.unwrap() || new BN(0)).toNumber() / 10_000_000),
currentEraCommissionPer: ((electedInfo.activeComminssions[index].commission?.unwrap() || new BN(0)).toNumber() / 10_000_000),
isCommission: !!(prefs as ValidatorPrefs).commission,
isFavorite: favorites.includes(key),
isNominating,
key,
numNominators: exposure.others.length,
rankBondOther: 0,
rankBondOwn: 0,
rankBondTotal: 0,
rankComm: 0,
rankActiveComm: 0,
rankOverall: 0,
rankPayment: 0,
rankReward: 0,
rewardPayout,
rewardSplit,
validatorPayment
};
})
);

return { nominators, totalStaked, validators, waitings };
return { nominators, totalStaked, validators };
}

export default function useSortedTargets (): SortedTargets {
Expand Down
10 changes: 8 additions & 2 deletions packages/react-components-darwinia/src/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,13 @@ export default styled(Table)`
&.isHighlight {
td {
background: #ffffed;
background: #ffffed !important;
}
}
&.isWaiting {
td {
background: #f2f2f2;
}
}
Expand Down Expand Up @@ -184,7 +190,7 @@ export default styled(Table)`
color: darkorange;
}
}
th {
background: #666;
color: #eee;
Expand Down
6 changes: 5 additions & 1 deletion packages/react-components/src/Table/Body.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,11 @@ export default React.memo(styled(Body)`
tr {
&.isHighlight td {
background: #ffffed;
background: #ffffed !important;
}
&.isWaiting td {
background: #f2f2f2;
}
&:last-child td {
Expand Down
2 changes: 1 addition & 1 deletion packages/types/src/codec/AbstractInt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export default abstract class AbstractInt extends BN implements Codec {
if (rawType === 'Balance') {
return this.isMax()
? 'everything'
: formatBalance(this, { decimals: this.registry.chainDecimals, withSi: true, withUnit: this.registry.chainToken });
: formatBalance(this, { decimals: this.registry.chainDecimals[0], withSi: true, withUnit: this.registry.chainToken[0] });
}

const [, divisor] = FORMATTERS.find(([type]) => type === rawType) || [];
Expand Down
29 changes: 29 additions & 0 deletions packages/util/src/array/chunk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0

/**
* @name arrayChunk
* @summary Split T[] into T[][] based on the defind size
* @description
* Returns a set ao arrays based on the chunksize
* @example
* <BR>
*
* ```javascript
* import { arrayChunk } from '@polkadot/util';
*
* arrayChunk([1, 2, 3, 4, 5]); // [[1, 2], [3, 4], [5]]
* ```
*/
export function arrayChunk <T> (array: T[], chunkSize: number): T[][] {
const outputSize = Math.ceil(array.length / chunkSize);
const output = Array<T[]>(outputSize);

for (let index = 0; index < outputSize; index++) {
const offset = index * chunkSize;

output[index] = array.slice(offset, offset + chunkSize);
}

return output;
}
11 changes: 5 additions & 6 deletions packages/util/src/array/filter.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// Copyright 2017-2020 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0

import isNull from '../is/null';
import isUndefined from '../is/undefined';
import { isNull } from '../is/null';
import { isUndefined } from '../is/undefined';

/**
* @name arrayFilter
Expand All @@ -21,7 +20,7 @@ import isUndefined from '../is/undefined';
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function arrayFilter <T = any> (array: T[], allowNulls = true): T[] {
export function arrayFilter <T = any> (array: T[], allowNulls = true): T[] {
return array.filter((value) =>
!isUndefined(value) && (allowNulls || !isNull(value))
);
Expand Down
Loading

0 comments on commit 7bd0768

Please sign in to comment.