Cleanup auction bid refresh (#4838)

* Cleanup auction bide refresh

* Additional

* Adjust summary

* Cleanup data hook

* Cleanup

* align

* Auction end cleanups

* Ending period countdown

* labels

* Allow for first bid after ending

* Fix ending calc

* Adjust global table padding
This commit is contained in:
Jaco Greeff 2021-03-13 16:38:13 +01:00 committed by GitHub
parent 736056c314
commit 28900a6b44
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 301 additions and 71 deletions

View File

@ -2,24 +2,24 @@
// SPDX-License-Identifier: Apache-2.0
import type { AuctionIndex, BlockNumber, LeasePeriodOf } from '@polkadot/types/interfaces';
import type { Winning } from './types';
import React, { useRef } from 'react';
import { Table } from '@polkadot/react-components';
import { useTranslation } from '../translate';
import useWinningData from './useWinningData';
import WinBlock from './WinBlock';
interface Props {
auctionInfo: [LeasePeriodOf, BlockNumber] | null;
className?: string;
numAuctions: AuctionIndex | null;
winningData: Winning[] | null;
}
function Auction ({ auctionInfo, className, numAuctions }: Props): React.ReactElement<Props> {
function Auction ({ auctionInfo, className, numAuctions, winningData }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const winningData = useWinningData(auctionInfo);
const headerRef = useRef([
[t('winners'), 'start', 4],
@ -37,11 +37,12 @@ function Auction ({ auctionInfo, className, numAuctions }: Props): React.ReactEl
)}
header={headerRef.current}
>
{winningData?.map((value, count) => (
{auctionInfo && winningData?.map((value, count) => (
<WinBlock
isEven={!!(count % 2)}
isLatest={count === 0}
key={value.blockNumber.toString()}
key={`${count}:${value.blockNumber.toString()}`}
startBlock={auctionInfo[1]}
value={value}
/>
))}

View File

@ -1,12 +1,15 @@
// Copyright 2017-2021 @polkadot/app-auctions authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { AuctionIndex, BlockNumber, LeasePeriodOf } from '@polkadot/types/interfaces';
import type { UInt } from '@polkadot/types';
import type { AuctionIndex, Balance, BlockNumber, LeasePeriodOf } from '@polkadot/types/interfaces';
import type { Winning } from './types';
import React from 'react';
import { CardSummary, SummaryBox } from '@polkadot/react-components';
import { useApi, useCall } from '@polkadot/react-hooks';
import { FormatBalance } from '@polkadot/react-query';
import { formatNumber } from '@polkadot/util';
import { useTranslation } from '../translate';
@ -14,35 +17,76 @@ import { useTranslation } from '../translate';
interface Props {
auctionInfo: [LeasePeriodOf, BlockNumber] | null;
className?: string;
lastWinner: Winning | null;
numAuctions?: AuctionIndex | null;
}
function Summary ({ auctionInfo, className, numAuctions }: Props): React.ReactElement<Props> {
function Summary ({ auctionInfo, className, lastWinner, numAuctions }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const bestNumber = useCall<BlockNumber>(api.derive.chain.bestNumber);
const totalIssuance = useCall<Balance>(api.query.balances?.totalIssuance);
const [period, ending] = auctionInfo || [];
return (
<SummaryBox className={className}>
<CardSummary label={t<string>('auctions')}>
{formatNumber(numAuctions)}
</CardSummary>
{auctionInfo && (
<section>
<section>
<CardSummary label={t<string>('auctions')}>
{formatNumber(numAuctions)}
</CardSummary>
{period && (
<CardSummary label={t<string>('period')}>
{formatNumber(period)}
</CardSummary>
<CardSummary
label={t<string>('ending')}
progress={{
total: ending,
value: bestNumber,
withTime: true,
withTimeNumber: true
}}
/>
</section>
)}
</section>
{auctionInfo && (
<>
{totalIssuance && lastWinner && (
<CardSummary
label={t<string>('total')}
progress={{
hideValue: true,
total: totalIssuance,
value: lastWinner.total,
withTime: true
}}
>
<FormatBalance
value={lastWinner.total}
withSi
/>
</CardSummary>
)}
<section>
{bestNumber && ending && (
bestNumber.lt(ending)
? (
<CardSummary
label={t<string>('end period at')}
progress={{
hideGraph: true,
total: ending,
value: bestNumber,
withTime: true
}}
>
#{formatNumber(ending)}
</CardSummary>
)
: (
<CardSummary
label={t<string>('ending period')}
progress={{
total: api.consts.auctions.endingPeriod as UInt,
value: bestNumber.sub(ending),
withTime: true
}}
></CardSummary>
)
)}
</section>
</>
)}
</SummaryBox>
);

View File

@ -1,6 +1,7 @@
// Copyright 2017-2021 @polkadot/app-crowdloan authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BlockNumber } from '@polkadot/types/interfaces';
import type { Winning } from './types';
import React from 'react';
@ -11,10 +12,11 @@ interface Props {
className?: string;
isEven: boolean;
isLatest: boolean;
startBlock: BlockNumber;
value: Winning;
}
function WinBlock ({ className = '', isEven, isLatest, value: { blockNumber, winners } }: Props): React.ReactElement<Props> {
function WinBlock ({ className = '', isEven, isLatest, startBlock, value: { blockNumber, winners } }: Props): React.ReactElement<Props> {
return (
<>
{winners.map((value, index) => (
@ -24,6 +26,7 @@ function WinBlock ({ className = '', isEven, isLatest, value: { blockNumber, win
isFirst={index === 0}
isLatest={isLatest}
key={index}
startBlock={startBlock}
value={value}
/>
))}

View File

@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type BN from 'bn.js';
import type { BlockNumber } from '@polkadot/types/interfaces';
import type { WinnerData } from './types';
import React from 'react';
@ -17,22 +18,21 @@ interface Props {
className?: string;
isFirst: boolean;
isLatest: boolean;
startBlock: BlockNumber;
value: WinnerData;
}
function WinRanges ({ blockNumber, className = '', isFirst, isLatest, value: { accountId, paraId, range, value } }: Props): React.ReactElement<Props> {
function WinRanges ({ blockNumber, className = '', isFirst, isLatest, startBlock, value: { accountId, paraId, range, value } }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
return (
<tr className={className}>
<td>
{isFirst && (
<h1>
{isLatest
? t<string>('latest')
: <>#{formatNumber(blockNumber)}</>
}
</h1>
<h1>{isLatest
? t<string>('latest')
: <>#{formatNumber(blockNumber.isZero() ? startBlock : blockNumber)}</>
}</h1>
)}
</td>
<td className='number'><h1>{formatNumber(paraId)}</h1></td>

View File

@ -13,6 +13,7 @@ import { useApi, useCallMulti } from '@polkadot/react-hooks';
import Auction from './Auction';
import Bid from './Bid';
import Summary from './Summary';
import useWinningData from './useWinningData';
interface Props {
className?: string;
@ -40,11 +41,13 @@ function Auctions ({ className }: Props): React.ReactElement<Props> {
api.query.auctions.auctionCounter,
api.query.auctions.auctionInfo
], optionsMulti);
const winningData = useWinningData(auctionInfo && auctionInfo[1]);
return (
<div className={className}>
<Summary
auctionInfo={auctionInfo}
lastWinner={winningData && winningData[0]}
numAuctions={numAuctions}
/>
<Button.Group>
@ -53,6 +56,7 @@ function Auctions ({ className }: Props): React.ReactElement<Props> {
<Auction
auctionInfo={auctionInfo}
numAuctions={numAuctions}
winningData={winningData}
/>
</div>
);

View File

@ -13,5 +13,7 @@ export interface WinnerData {
export interface Winning {
blockNumber: BN;
blockOffset: BN;
total: BN;
winners: WinnerData[];
}

View File

@ -2,12 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
import type { Option, StorageKey } from '@polkadot/types';
import type { BlockNumber, LeasePeriodOf, WinningData } from '@polkadot/types/interfaces';
import type { BlockNumber, WinningData } from '@polkadot/types/interfaces';
import type { WinnerData, Winning } from './types';
import { useEffect, useState } from 'react';
import BN from 'bn.js';
import { useEffect, useRef, useState } from 'react';
import { useApi, useEventTrigger } from '@polkadot/react-hooks';
import { useApi, useCall, useEventTrigger } from '@polkadot/react-hooks';
import { BN_ONE, BN_ZERO } from '@polkadot/util';
const RANGES = [
'0-0', '0-1', '0-2', '0-3',
@ -16,51 +18,119 @@ const RANGES = [
'3-3'
];
const FIRST_PARAM = [0];
function isNewWinners (a: WinnerData[], b: WinnerData[]): boolean {
return JSON.stringify({ w: a }) !== JSON.stringify({ w: b });
}
function extractWinners (optData: Option<WinningData>): WinnerData[] {
return optData.isNone
? []
: optData.unwrap().reduce<WinnerData[]>((winners, optEntry, index): WinnerData[] => {
if (optEntry.isSome) {
const [accountId, paraId, value] = optEntry.unwrap();
winners.push({ accountId, paraId, range: RANGES[index], value });
}
return winners;
}, []);
}
function createWinning (endBlock: BlockNumber | null, blockOffset: BN | null | undefined, winners: WinnerData[]): Winning {
return {
blockNumber: endBlock && blockOffset
? blockOffset.add(endBlock)
: blockOffset || BN_ZERO,
blockOffset: blockOffset || BN_ZERO,
total: winners.reduce((total, { value }) => total.iadd(value), new BN(0)),
winners
};
}
function extractData (endBlock: BlockNumber | null, values: [StorageKey<[BlockNumber]>, Option<WinningData>][]): Winning[] {
return values
.sort(([{ args: [a] }], [{ args: [b] }]) => a.cmp(b))
.reduce((all: Winning[], [{ args: [blockOffset] }, optData]): Winning[] => {
if (optData.isSome) {
const winners = optData.unwrap().reduce<WinnerData[]>((winners, optEntry, index): WinnerData[] => {
if (optEntry.isSome) {
const [accountId, paraId, value] = optEntry.unwrap();
const winners = extractWinners(optData);
winners.push({ accountId, paraId, range: RANGES[index], value });
}
return winners;
}, []);
winners.length && (
all.length === 0 ||
JSON.stringify({ winners }) !== JSON.stringify({ winners: all[all.length - 1].winners })
) && all.push({
blockNumber: endBlock
? blockOffset.add(endBlock)
: blockOffset,
winners
});
}
winners.length && (
all.length === 0 ||
isNewWinners(winners, all[all.length - 1].winners)
) && all.push(createWinning(endBlock, blockOffset, winners));
return all;
}, [])
.reverse();
}
export default function useWinningData (auctionInfo: [LeasePeriodOf, BlockNumber] | null): Winning[] | null {
function mergeCurrent (prev: Winning[] | null, optCurrent: Option<WinningData>, endBlock: BlockNumber, blockOffset: BN): Winning[] | null {
const current = createWinning(endBlock, blockOffset, extractWinners(optCurrent));
if (current.winners.length && (!prev?.length || isNewWinners(current.winners, prev[0].winners))) {
return [current, ...(prev || [])];
}
return prev;
}
function mergeFirst (prev: Winning[] | null, optFirstData: Option<WinningData>): Winning[] | null {
if (prev && prev.length <= 1) {
const updated: Winning[] = prev || [];
const firstEntry = createWinning(null, null, extractWinners(optFirstData));
if (!firstEntry.winners.length) {
return updated;
} else if (!updated.length) {
return [firstEntry];
}
updated[updated.length - 1] = firstEntry;
return updated.slice();
}
return prev;
}
export default function useWinningData (endBlock: BlockNumber | null): Winning[] | null {
const { api } = useApi();
const [winning, setWinning] = useState<Winning[] | null>(null);
const trigger = useEventTrigger([api.events.auctions.BidAccepted]);
const bestNumber = useCall<BlockNumber>(api.derive.chain.bestNumber);
const trigger = useEventTrigger([api.events.auctions?.BidAccepted]);
const triggerRef = useRef(trigger);
const allEntries = useCall<[StorageKey<[BlockNumber]>, Option<WinningData>][]>(api.query.auctions?.winning.entries);
const optFirstData = useCall<Option<WinningData>>(api.query.auctions?.winning, FIRST_PARAM);
useEffect((): void => {
trigger &&
api.query.auctions.winning
.entries<Option<WinningData>, [BlockNumber]>()
.then((values) => setWinning(
extractData(auctionInfo && auctionInfo[1], values))
)
allEntries && setWinning(
extractData(endBlock, allEntries)
);
}, [allEntries, endBlock]);
useEffect((): void => {
optFirstData && setWinning((prev) =>
mergeFirst(prev, optFirstData)
);
}, [optFirstData]);
useEffect((): void => {
if (endBlock && bestNumber && triggerRef.current !== trigger) {
const blockOffset = bestNumber.gt(endBlock)
? bestNumber.sub(endBlock).add(BN_ONE)
: BN_ZERO;
triggerRef.current = trigger;
api.query.auctions
?.winning<Option<WinningData>>(blockOffset)
.then((optCurrent) => setWinning((prev) =>
mergeCurrent(prev, optCurrent, endBlock, blockOffset)
))
.catch(console.error);
}, [api, auctionInfo, trigger]);
}
}, [api, bestNumber, endBlock, trigger, triggerRef]);
return winning;
}

View File

@ -0,0 +1,108 @@
// Copyright 2017-2021 @polkadot/app-crowdloan authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Option } from '@polkadot/types';
import type { BlockNumber, WinningData } from '@polkadot/types/interfaces';
import type { WinnerData, Winning } from './types';
import BN from 'bn.js';
import { useEffect, useState } from 'react';
import { useApi, useCall } from '@polkadot/react-hooks';
import { BN_ZERO, bnToBn } from '@polkadot/util';
const RANGES = [
'0-0', '0-1', '0-2', '0-3',
'1-1', '1-2', '1-3',
'2-2', '2-3',
'3-3'
];
function isNewWinners (a: WinnerData[], b: WinnerData[]): boolean {
return JSON.stringify({ w: a }) !== JSON.stringify({ w: b });
}
function extractWinners (data: WinningData | null): WinnerData[] {
return data
? data.reduce<WinnerData[]>((winners, optEntry, index): WinnerData[] => {
if (optEntry.isSome) {
const [accountId, paraId, value] = optEntry.unwrap();
winners.push({ accountId, paraId, range: RANGES[index], value });
}
return winners;
}, [])
: [];
}
function createWinning (endBlock: BlockNumber | null, blockOffset: BN | null | undefined, winners: WinnerData[]): Winning {
return {
blockNumber: endBlock && blockOffset
? blockOffset.add(endBlock)
: blockOffset || BN_ZERO,
blockOffset: blockOffset || BN_ZERO,
total: winners.reduce((total, { value }) => total.iadd(value), new BN(0)),
winners
};
}
function extractData (endBlock: BlockNumber | null, values: WinningData[]): Winning[] {
return values
.reduce((all: Winning[], data, blockOffset): Winning[] => {
const winners = extractWinners(data);
winners.length && (
all.length === 0 ||
isNewWinners(winners, all[all.length - 1].winners)
) && all.push(createWinning(endBlock, bnToBn(blockOffset), winners));
return all;
}, [])
.reverse();
}
export default function useWinningData (endBlock: BlockNumber | null): Winning[] | null {
const { api } = useApi();
const [winning, setWinning] = useState<Winning[] | null>(null);
// the vec of all the winners
const winningVec = useCall<WinningData[]>(api.query.auctions?.winningVec);
// the first entry will update while we are not in the ending period, always track
const optFirst = useCall<Option<WinningData>>(api.query.auctions?.winning, [0]);
useEffect((): void => {
optFirst && setWinning((prev): Winning[] => {
const firstEntry = createWinning(null, null, extractWinners(optFirst.unwrapOr(null)));
if (!prev || prev.length <= 1) {
const updated: Winning[] = prev || [];
if (!firstEntry.winners.length) {
return updated;
} else if (updated.length) {
updated[updated.length - 1] = firstEntry;
return [...updated];
}
return [firstEntry];
}
return prev;
});
}, [optFirst]);
useEffect((): void => {
winningVec && setWinning((prev): Winning[] => {
const full = extractData(endBlock, winningVec);
return (!prev || full.length !== prev.length || isNewWinners(full[0].winners, prev[0].winners))
? full
: prev;
});
}, [endBlock, winningVec]);
return winning;
}

View File

@ -14,12 +14,12 @@ import Labelled from './Labelled';
import Progress from './Progress';
interface ProgressProps {
hideGraph?: boolean;
hideValue?: boolean;
isPercent?: boolean;
total?: BN | UInt;
value?: BN | UInt;
withTime?: boolean;
withTimeNumber?: boolean;
}
interface Props {
@ -65,10 +65,8 @@ function CardSummary ({ children, className = '', help, label, progress }: Props
{children}{
progress && !progress.hideValue && (
<>
{isTimed && (
progress.withTimeNumber
? formatNumber(progress.total)
: <BlockToTime blocks={progress.total} />
{isTimed && !children && (
<BlockToTime blocks={progress.total} />
)}
<div className={isTimed ? 'isSecondary' : 'isPrimary'}>
{!left || isUndefined(progress.total)
@ -91,7 +89,7 @@ function CardSummary ({ children, className = '', help, label, progress }: Props
)
}
</Labelled>
{progress && <Progress {...progress} />}
{progress && !progress.hideGraph && <Progress {...progress} />}
</article>
);
}

View File

@ -34,7 +34,7 @@ export default React.memo(styled(Body)`
td {
border-bottom: 1px solid var(--border-table);
padding: 0.75rem 1rem;
padding: 0.5rem 1rem;
text-align: left;
vertical-align: middle;
@ -74,7 +74,7 @@ export default React.memo(styled(Body)`
}
&.button {
padding: 0.5rem;
padding: 0.25rem 0.5rem;
text-align: right;
white-space: nowrap;

View File

@ -63,7 +63,7 @@ export default React.memo(styled(Head)`
th {
font: var(--font-sans);
font-weight: var(--font-weight-normal);
padding: 0.75rem 1rem 0.25rem;
padding: 0.5rem 1rem 0.25rem;
text-align: right;
vertical-align: baseline;
white-space: nowrap;