@polkadot/types/interfaces#Voting TypeScript Examples
The following examples show how to use
@polkadot/types/interfaces#Voting.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx From crust-apps with Apache License 2.0 | 4 votes |
function Overview ({ className = '', onStatusChange }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api, systemChain } = useApi();
const { allAccounts, hasAccounts } = useAccounts();
const { isIpfs } = useIpfs();
const { isLedgerEnabled } = useLedger();
const [isCreateOpen, toggleCreate] = useToggle();
const [isImportOpen, toggleImport] = useToggle();
const [isLedgerOpen, toggleLedger] = useToggle();
const [isMultisigOpen, toggleMultisig] = useToggle();
const [isProxyOpen, toggleProxy] = useToggle();
const [isQrOpen, toggleQr] = useToggle();
const [favorites, toggleFavorite] = useFavorites(STORE_FAVS);
const [{ balanceTotal }, setBalances] = useState<Balances>({ accounts: {} });
const [filterOn, setFilter] = useState<string>('');
const [sortedAccountsWithDelegation, setSortedAccountsWithDelegation] = useState<SortedAccount[] | undefined>();
const [{ sortedAccounts, sortedAddresses }, setSorted] = useState<Sorted>({ sortedAccounts: [], sortedAddresses: [] });
const delegations = useCall<Voting[]>(api.query.democracy?.votingOf?.multi, [sortedAddresses]);
const proxies = useCall<[ProxyDefinition[], BN][]>(api.query.proxy?.proxies.multi, [sortedAddresses], {
transform: (result: [([AccountId, ProxyType] | ProxyDefinition)[], BN][]): [ProxyDefinition[], BN][] =>
api.tx.proxy.addProxy.meta.args.length === 3
? result as [ProxyDefinition[], BN][]
: (result as [[AccountId, ProxyType][], BN][]).map(([arr, bn]): [ProxyDefinition[], BN] =>
[arr.map(([delegate, proxyType]): ProxyDefinition => api.createType('ProxyDefinition', { delegate, proxyType })), bn]
)
});
const isMainnet = systemChain !== 'Crust Maxwell';
const isLoading = useLoadingDelay();
const headerRef = !isMainnet ? useRef([
[t('accounts'), 'start', 3],
// [t('parent'), 'address media--1400'],
[t('type'), 'address media--1400'],
// [t('tags'), 'start'],
[t('transactions'), 'start'],
[t('CRU'), 'expand'],
[t('CSM'), 'expand'],
[t('Candy')],
[t('CRU18')],
[],
[undefined, 'media--1400']
]) : useRef([
[t('accounts'), 'start', 3],
[t('parent'), 'address media--1400'],
[t('type'), 'address media--1400'],
[t('tags'), 'start'],
[t('transactions'), 'start'],
[t('CRU'), 'expand'],
[],
[undefined, 'media--1400']
]);
useEffect((): void => {
const sortedAccounts = sortAccounts(allAccounts, favorites);
const sortedAddresses = sortedAccounts.map((a) => a.account.address);
setSorted({ sortedAccounts, sortedAddresses });
}, [allAccounts, favorites]);
useEffect(() => {
setSortedAccountsWithDelegation(
sortedAccounts?.map((account, index) => {
let delegation: Delegation | undefined;
if (delegations && delegations[index]?.isDelegating) {
const { balance: amount, conviction, target } = delegations[index].asDelegating;
delegation = {
accountDelegated: target.toString(),
amount,
conviction
};
}
return ({
...account,
delegation
});
})
);
}, [api, delegations, sortedAccounts]);
const _setBalance = useCallback(
(account: string, balance: BN) =>
setBalances(({ accounts }: Balances): Balances => {
accounts[account] = balance;
return {
accounts,
balanceTotal: Object.values(accounts).reduce((total: BN, value: BN) => total.add(value), BN_ZERO)
};
}),
[]
);
const footer = useMemo(() => !isMainnet ? (
<tr>
<td colSpan={3} />
{/* <td className='media--1400' /> */}
<td colSpan={2} />
{/* <td className='media--1500' /> */}
<td className='number'>
{balanceTotal && <FormatBalance value={balanceTotal} />}
</td>
<td />
<td />
<td />
<td />
<td className='media--1400' />
</tr>
) : (
<tr>
<td colSpan={3} />
<td className='media--1400' />
<td colSpan={2} />
<td className='media--1500' />
<td className='number'>
{balanceTotal && <FormatBalance value={balanceTotal} />}
</td>
<td />
<td className='media--1400' />
</tr>
), [balanceTotal, isMainnet]);
const filter = useMemo(() => (
<div className='filter--tags'>
<Input
autoFocus
isFull
label={t<string>('filter by name or tags')}
onChange={setFilter}
value={filterOn}
/>
</div>
), [filterOn, t]);
return (
<div className={className}>
{isCreateOpen && (
<CreateModal
onClose={toggleCreate}
onStatusChange={onStatusChange}
/>
)}
{isImportOpen && (
<ImportModal
onClose={toggleImport}
onStatusChange={onStatusChange}
/>
)}
{isLedgerOpen && (
<Ledger onClose={toggleLedger} />
)}
{isMultisigOpen && (
<Multisig
onClose={toggleMultisig}
onStatusChange={onStatusChange}
/>
)}
{isProxyOpen && (
<Proxy
onClose={toggleProxy}
onStatusChange={onStatusChange}
/>
)}
{isQrOpen && (
<Qr
onClose={toggleQr}
onStatusChange={onStatusChange}
/>
)}
<Button.Group>
<Button
icon='plus'
isDisabled={isIpfs}
label={t<string>('Add account')}
onClick={toggleCreate}
/>
<Button
icon='sync'
isDisabled={isIpfs}
label={t<string>('Restore JSON')}
onClick={toggleImport}
/>
<Button
icon='qrcode'
label={t<string>('Add via Qr')}
onClick={toggleQr}
/>
{isLedgerEnabled && (
<>
<Button
icon='project-diagram'
label={t<string>('Add via Ledger')}
onClick={toggleLedger}
/>
</>
)}
<Button
icon='plus'
isDisabled={!(api.tx.multisig || api.tx.utility) || !hasAccounts}
label={t<string>('Multisig')}
onClick={toggleMultisig}
/>
<Button
icon='plus'
isDisabled={!api.tx.proxy || !hasAccounts}
label={t<string>('Proxied')}
onClick={toggleProxy}
/>
</Button.Group>
<BannerExtension />
<BannerClaims />
<Table
empty={!isLoading && sortedAccountsWithDelegation && t<string>("You don't have any accounts. Some features are currently hidden and will only become available once you have accounts.")}
filter={filter}
footer={footer}
header={headerRef.current}
>
{!isLoading && sortedAccountsWithDelegation?.map(({ account, delegation, isFavorite }, index): React.ReactNode => isMainnet
? (
<AccountMainnet
account={account}
delegation={delegation}
filter={filterOn}
isFavorite={isFavorite}
key={`${index}:${account.address}`}
proxy={proxies?.[index]}
setBalance={_setBalance}
toggleFavorite={toggleFavorite}
/>
)
: (
<Account
account={account}
delegation={delegation}
filter={filterOn}
isFavorite={isFavorite}
key={`${index}:${account.address}`}
proxy={proxies?.[index]}
setBalance={_setBalance}
toggleFavorite={toggleFavorite}
/>
))}
</Table>
</div>
);
}
Example #2
Source File: index.tsx From crust-apps with Apache License 2.0 | 4 votes |
function Overview ({ className = '' }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { allAccounts, hasAccounts } = useAccounts();
const [favorites, toggleFavorite] = useFavorites(STORE_FAVS);
const [, setBalances] = useState<Balances>({ accounts: {} });
const [filterOn, setFilter] = useState<string>('');
const [{ sortedAccounts, sortedAddresses }, setSorted] = useState<Sorted>({ sortedAccounts: [], sortedAddresses: [] });
const [sortedAccountsWithDelegation, setSortedAccountsWithDelegation] = useState<SortedAccount[] | undefined>();
const [ownMerchants, setOwnMerchants] = useState<SortedAccount[] | undefined>();
const delegations = useCall<Voting[]>(api.query.democracy?.votingOf?.multi, [sortedAddresses]);
const proxies = useCall<[ProxyDefinition[], BN][]>(api.query.proxy?.proxies.multi, [sortedAddresses], {
transform: (result: [([AccountId, ProxyType] | ProxyDefinition)[], BN][]): [ProxyDefinition[], BN][] =>
api.tx.proxy.addProxy.meta.args.length === 3
? result as [ProxyDefinition[], BN][]
: (result as [[AccountId, ProxyType][], BN][]).map(([arr, bn]): [ProxyDefinition[], BN] =>
[arr.map(([delegate, proxyType]): ProxyDefinition => api.createType('ProxyDefinition', { delegate, proxyType })), bn]
)
});
const [allMerchants, setAllMerchants] = useState<string[]>([]);
const isLoading = useLoadingDelay();
const headerRef = useRef([
[t('accounts'), 'start', 3],
[t('reward')],
[t('maximum receivable income')],
[t('collateral')],
// [t('balances'), 'expand'],
[]
]);
const getAllMerchants = () => {
let unsub: (() => void) | undefined;
const fns: any[] = [
[api.query.benefits.marketBenefits.entries]
];
const allMerchants:string[] = [];
api.combineLatest<any[]>(fns, ([ledgers]): void => {
if (Array.isArray(ledgers)) {
ledgers.forEach(([{ args: [accountId] }, value]) => {
allMerchants.push(accountId.toString());
});
setAllMerchants(allMerchants);
}
}).then((_unsub): void => {
unsub = _unsub;
}).catch(console.error);
return (): void => {
unsub && unsub();
};
};
useEffect(() => {
getAllMerchants();
}, []);
useEffect(() => {
const tmp: SortedAccount[] = [];
if (sortedAccountsWithDelegation && allMerchants) {
for (const myAccount of sortedAccountsWithDelegation) {
if (allMerchants.includes(myAccount.account.address.toString())) {
tmp.push(myAccount);
}
}
setOwnMerchants(tmp);
}
}, [sortedAccountsWithDelegation, allMerchants]);
useEffect((): void => {
const sortedAccounts = sortAccounts(allAccounts, favorites);
const sortedAddresses = sortedAccounts.map((a) => a.account.address);
setSorted({ sortedAccounts, sortedAddresses });
}, [allAccounts, favorites]);
useEffect(() => {
setSortedAccountsWithDelegation(
sortedAccounts?.map((account, index) => {
let delegation: Delegation | undefined;
if (delegations && delegations[index]?.isDelegating) {
const { balance: amount, conviction, target } = delegations[index].asDelegating;
delegation = {
accountDelegated: target.toString(),
amount,
conviction
};
}
return ({
...account,
delegation
});
})
);
}, [api, delegations, sortedAccounts]);
const _setBalance = useCallback(
(account: string, balance: BN) =>
setBalances(({ accounts }: Balances): Balances => {
accounts[account] = balance;
return {
accounts,
balanceTotal: Object.values(accounts).reduce((total: BN, value: BN) => total.add(value), BN_ZERO)
};
}),
[]
);
const filter = useMemo(() => (
<div className='filter--tags'>
<Input
autoFocus
isFull
label={t<string>('filter by name or tags')}
onChange={setFilter}
value={filterOn}
/>
</div>
), [filterOn, t]);
return (
<div className={className}>
{(!hasAccounts || (!isLoading && sortedAccountsWithDelegation)) && <Banner type="warning">
<p>{t<string>('Storage merchant should first increase collateral in the “storage market benefits module” to qualify for the storage market rewards.')} <a href='#/benefit/storageMarket'>{t<string>('Increase collateral...')}</a></p>
</Banner>}
<Table
empty={(!hasAccounts || (!isLoading && sortedAccountsWithDelegation)) && t<string>("You don't have merchant accounts. Some features are currently hidden and will only become available once you have merchant accounts.")}
filter={filter}
header={headerRef.current}
>
{!isLoading && ownMerchants?.map(({ account, delegation, isFavorite }, index): React.ReactNode => (
<Merchant
account={account}
delegation={delegation}
filter={filterOn}
isFavorite={isFavorite}
key={account.address}
proxy={proxies?.[index]}
setBalance={_setBalance}
toggleFavorite={toggleFavorite}
/>
))}
</Table>
</div>
);
}
Example #3
Source File: index.tsx From crust-apps with Apache License 2.0 | 4 votes |
function Overview ({ className = '' }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const { allAccounts, hasAccounts } = useAccounts();
const [favorites, toggleFavorite] = useFavorites(STORE_FAVS);
const [, setBalances] = useState<Balances>({ accounts: {} });
const [filterOn, setFilter] = useState<string>('');
const [{ sortedAccounts, sortedAddresses }, setSorted] = useState<Sorted>({ sortedAccounts: [], sortedAddresses: [] });
const [sortedAccountsWithDelegation, setSortedAccountsWithDelegation] = useState<SortedAccount[] | undefined>();
const [ownMerchants, setOwnMerchants] = useState<SortedAccount[] | undefined>();
const delegations = useCall<Voting[]>(api.query.democracy?.votingOf?.multi, [sortedAddresses]);
const proxies = useCall<[ProxyDefinition[], BN][]>(api.query.proxy?.proxies.multi, [sortedAddresses], {
transform: (result: [([AccountId, ProxyType] | ProxyDefinition)[], BN][]): [ProxyDefinition[], BN][] =>
api.tx.proxy.addProxy.meta.args.length === 3
? result as [ProxyDefinition[], BN][]
: (result as [[AccountId, ProxyType][], BN][]).map(([arr, bn]): [ProxyDefinition[], BN] =>
[arr.map(([delegate, proxyType]): ProxyDefinition => api.createType('ProxyDefinition', { delegate, proxyType })), bn]
)
});
const [isRegisterOpen, toggleRegister] = useToggle();
const [allMerchants, setAllMerchants] = useState<string[]>([]);
const isLoading = useLoadingDelay();
const headerRef = useRef([
[t('accounts'), 'start', 3],
[t('reward')],
[t('maximum receivable income')],
[t('collateral')],
// [t('balances'), 'expand'],
[]
]);
const getAllMerchants = () => {
let unsub: (() => void) | undefined;
const fns: any[] = [
[api.query.market.merchantLedgers.entries]
];
const allMerchants:string[] = [];
api.combineLatest<any[]>(fns, ([ledgers]): void => {
if (Array.isArray(ledgers)) {
ledgers.forEach(([{ args: [accountId] }]) => {
allMerchants.push(accountId.toString());
});
setAllMerchants(allMerchants);
}
}).then((_unsub): void => {
unsub = _unsub;
}).catch(console.error);
return (): void => {
unsub && unsub();
};
};
useEffect(() => {
getAllMerchants();
}, []);
useEffect(() => {
const tmp: SortedAccount[] = [];
if (sortedAccountsWithDelegation && allMerchants) {
for (const myAccount of sortedAccountsWithDelegation) {
if (allMerchants.includes(myAccount.account.address.toString())) {
tmp.push(myAccount);
}
}
setOwnMerchants(tmp);
}
}, [sortedAccountsWithDelegation, allMerchants]);
useEffect((): void => {
const sortedAccounts = sortAccounts(allAccounts, favorites);
const sortedAddresses = sortedAccounts.map((a) => a.account.address);
setSorted({ sortedAccounts, sortedAddresses });
}, [allAccounts, favorites]);
useEffect(() => {
// TODO: to confirm
if ( !delegations?.length) {
return;
}
setSortedAccountsWithDelegation(
sortedAccounts?.map((account, index) => {
let delegation: Delegation | undefined;
if (delegations && delegations[index]?.isDelegating) {
const { balance: amount, conviction, target } = delegations[index].asDelegating;
delegation = {
accountDelegated: target.toString(),
amount,
conviction
};
}
return ({
...account,
delegation
});
})
);
}, [api, delegations, sortedAccounts]);
const _setBalance = useCallback(
(account: string, balance: BN) =>
setBalances(({ accounts }: Balances): Balances => {
accounts[account] = balance;
return {
accounts,
balanceTotal: Object.values(accounts).reduce((total: BN, value: BN) => total.add(value), BN_ZERO)
};
}),
[]
);
const filter = useMemo(() => (
<div className='filter--tags'>
<Input
autoFocus
isFull
label={t<string>('filter by name or tags')}
onChange={setFilter}
value={filterOn}
/>
</div>
), [filterOn, t]);
return (
<div className={className}>
{isRegisterOpen && (
<Register
key='modal-transfer'
onClose={toggleRegister}
onSuccess={getAllMerchants}
/>
)}
<Button.Group>
<Button
icon='plus'
label={t<string>('Register')}
onClick={toggleRegister}
/>
</Button.Group>
<Table
empty={(!hasAccounts || (!isLoading && sortedAccountsWithDelegation)) && t<string>("You don't have merchant accounts. Some features are currently hidden and will only become available once you have merchant accounts.")}
filter={filter}
header={headerRef.current}
>
{!isLoading && ownMerchants?.map(({ account, delegation, isFavorite }, index): React.ReactNode => (
<Merchant
account={account}
delegation={delegation}
filter={filterOn}
isFavorite={isFavorite}
key={account.address}
proxy={proxies?.[index]}
setBalance={_setBalance}
toggleFavorite={toggleFavorite}
/>
))}
</Table>
</div>
);
}
Example #4
Source File: AddressInfo.tsx From subscan-multisig-react with Apache License 2.0 | 4 votes |
function createBalanceItems(
formatIndex: number,
lookup: Record<string, string>,
t: TFunction,
{
address,
balanceDisplay,
balancesAll,
bestNumber,
democracyLocks,
isAllLocked,
otherBonded,
ownBonded,
stakingInfo,
votingOf,
withBalanceToggle,
}: {
address: string;
balanceDisplay: BalanceActiveType;
balancesAll?: DeriveBalancesAll | DeriveBalancesAccountData;
bestNumber: BlockNumber;
democracyLocks?: DeriveDemocracyLock[];
isAllLocked: boolean;
otherBonded: BN[];
ownBonded: BN;
stakingInfo?: DeriveStakingAccount;
votingOf?: Voting;
withBalanceToggle: boolean;
}
): React.ReactNode {
const allItems: React.ReactNode[] = [];
const deriveBalances = balancesAll as DeriveBalancesAll;
// eslint-disable-next-line
!withBalanceToggle &&
balancesAll &&
balanceDisplay.total &&
allItems.push(
<React.Fragment key={0}>
<Label label={t<string>('total')} />
<FormatBalance
className="result"
formatIndex={formatIndex}
value={balancesAll.freeBalance.add(balancesAll.reservedBalance)}
/>
</React.Fragment>
);
// eslint-disable-next-line
balancesAll &&
balanceDisplay.available &&
(balancesAll as DeriveBalancesAll).availableBalance &&
allItems.push(
<React.Fragment key={1}>
<Label label={t<string>('transferrable')} />
<FormatBalance
className="result"
formatIndex={formatIndex}
value={(balancesAll as DeriveBalancesAll).availableBalance}
/>
</React.Fragment>
);
if (balanceDisplay.vested && deriveBalances?.isVesting) {
const allVesting = deriveBalances.vesting.filter(({ endBlock }) => bestNumber.lt(endBlock));
allItems.push(
<React.Fragment key={2}>
<Label label={t<string>('vested')} />
<FormatBalance
className='result'
formatIndex={formatIndex}
labelPost={
<Icon
icon='info-circle'
tooltip={`${address}-vested-trigger`}
/>
}
value={deriveBalances.vestedBalance}
>
<Tooltip
text={
<>
<div>
{formatBalance(deriveBalances.vestedClaimable, { forceUnit: '-' })}
<div className='faded'>{t('available to be unlocked')}</div>
</div>
{allVesting.map(({ endBlock, locked, perBlock, vested }, index) => (
<div
className='inner'
key={`item:${index}`}
>
<div>
{formatBalance(vested, { forceUnit: '-' })}
<div className='faded'>{t('of {{locked}} vested', { replace: { locked: formatBalance(locked, { forceUnit: '-' }) } })}</div>
</div>
<div>
<BlockToTime value={endBlock.sub(bestNumber)} />
<div className='faded'>{t('until block')} {formatNumber(endBlock)}</div>
</div>
<div>
{formatBalance(perBlock)}
<div className='faded'>{t('per block')}</div>
</div>
</div>
))}
</>
}
trigger={`${address}-vested-trigger`}
/>
</FormatBalance>
</React.Fragment>
);
}
balanceDisplay.locked &&
balancesAll &&
(isAllLocked || (balancesAll as DeriveBalancesAll).lockedBalance?.gtn(0)) &&
allItems.push(
<React.Fragment key={3}>
<Label label={t<string>('locked')} />
<FormatBalance
className="result"
formatIndex={formatIndex}
label={<Icon icon="info-circle" tooltip={`${address}-locks-trigger`} />}
value={isAllLocked ? 'all' : (balancesAll as DeriveBalancesAll).lockedBalance}
>
<Tooltip
text={(balancesAll as DeriveBalancesAll).lockedBreakdown.map(
({ amount, id, reasons }, index): React.ReactNode => (
<div key={index}>
{amount?.isMax() ? t<string>('everything') : formatBalance(amount, { forceUnit: '-' })}
{id && <div className="faded">{lookupLock(lookup, id)}</div>}
<div className="faded">{reasons.toString()}</div>
</div>
)
)}
trigger={`${address}-locks-trigger`}
/>
</FormatBalance>
</React.Fragment>
);
balanceDisplay.reserved &&
balancesAll?.reservedBalance?.gtn(0) &&
allItems.push(
<React.Fragment key={4}>
<Label label={t<string>('reserved')} />
<FormatBalance className="result" formatIndex={formatIndex} value={balancesAll.reservedBalance} />
</React.Fragment>
);
balanceDisplay.bonded &&
(ownBonded.gtn(0) || otherBonded.length !== 0) &&
allItems.push(
<React.Fragment key={5}>
<Label label={t<string>('bonded')} />
<FormatBalance className="result" formatIndex={formatIndex} value={ownBonded}>
{otherBonded.length !== 0 && (
<>
(+
{otherBonded.map(
(bonded, index): React.ReactNode => (
<FormatBalance formatIndex={formatIndex} key={index} value={bonded} />
)
)}
)
</>
)}
</FormatBalance>
</React.Fragment>
);
balanceDisplay.redeemable &&
stakingInfo?.redeemable?.gtn(0) &&
allItems.push(
<React.Fragment key={6}>
<Label label={t<string>('redeemable')} />
<StakingRedeemable className="result" stakingInfo={stakingInfo} />
</React.Fragment>
);
if (balanceDisplay.unlocking) {
stakingInfo?.unlocking &&
allItems.push(
<React.Fragment key={7}>
<Label label={t<string>('unbonding')} />
<div className="result">
<StakingUnbonding stakingInfo={stakingInfo} />
</div>
</React.Fragment>
);
if (democracyLocks && democracyLocks.length !== 0) {
allItems.push(
<React.Fragment key={8}>
<Label label={t<string>('democracy')} />
<div className="result">
<DemocracyLocks value={democracyLocks} />
</div>
</React.Fragment>
);
} else if (votingOf && votingOf.isDirect) {
const {
prior: [unlockAt, balance],
} = votingOf.asDirect;
balance.gt(BN_ZERO) &&
unlockAt.gt(BN_ZERO) &&
allItems.push(
<React.Fragment key={8}>
<Label label={t<string>('democracy')} />
<div className="result">
<DemocracyLocks value={[{ balance, isFinished: bestNumber.gt(unlockAt), unlockAt }]} />
</div>
</React.Fragment>
);
}
}
if (withBalanceToggle) {
return (
<React.Fragment key={formatIndex}>
<Expander
summary={
<FormatBalance
formatIndex={formatIndex}
value={balancesAll && balancesAll.freeBalance.add(balancesAll.reservedBalance)}
/>
}
>
{allItems.length !== 0 && <div className="body column">{allItems}</div>}
</Expander>
</React.Fragment>
);
}
return <React.Fragment key={formatIndex}>{allItems}</React.Fragment>;
}