Skip to content

Commit

Permalink
feat: add foreign assets support on asset hubs, such as MYTH on PAH (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Nick-1979 authored Oct 6, 2024
1 parent d50ac47 commit a77459a
Show file tree
Hide file tree
Showing 68 changed files with 954 additions and 702 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
"@polkadot/types-support": "^11.2.1",
"@polkadot/util": "^12.6.2",
"@polkadot/util-crypto": "^12.6.2",
"@polkagate/apps-config": "^0.140.3",
"@polkagate/apps-config": "^0.140.5",
"@substrate/connect": "^0.7.32",
"@vaadin/icons": "^23.2.3",
"babel-plugin-transform-import-meta": "^2.1.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/extension-polkagate/src/components/Assets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function Assets ({ address, assetId, label, onChange, setAssetId, style }: Props
return (
<Grid alignItems='flex-end' container justifyContent='space-between' sx={{ ...style }}>
<Select2
defaultValue={options?.[0]?.value}
defaultValue={options?.[0]?.text}
isItemsLoading={isLoading}
label={label}
onChange={onChange}
Expand Down
4 changes: 2 additions & 2 deletions packages/extension-polkagate/src/components/ChainLogo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ interface Props {

function ChainLogo ({ chainName, genesisHash, logo, size = 25 }: Props): React.ReactElement<Props> {
const theme = useTheme();
const mayBeUserAddedChainColor = useUserAddedChainColor(genesisHash);
const maybeUserAddedChainColor = useUserAddedChainColor(genesisHash);
const options = useContext(GenesisHashOptionsContext);

const foundChainName = options.find(({ text, value }) => value === genesisHash || text === chainName)?.text;
Expand Down Expand Up @@ -60,7 +60,7 @@ function ChainLogo ({ chainName, genesisHash, logo, size = 25 }: Props): React.R
</>
: <Avatar
sx={{
bgcolor: mayBeUserAddedChainColor,
bgcolor: maybeUserAddedChainColor,
borderRadius: '50%',
fontSize: size * 0.7,
height: size,
Expand Down
6 changes: 3 additions & 3 deletions packages/extension-polkagate/src/components/SignArea2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import { PButton, Progress, TwoButtons, Warning } from '.';

interface Props {
address: string;
mayBeApi?: ApiPromise;
maybeApi?: ApiPromise;
call: SubmittableExtrinsicFunction<'promise', AnyTuple> | undefined | SubmittableExtrinsic<'promise', ISubmittableResult>;
disabled?: boolean;
isPasswordError?: boolean;
Expand Down Expand Up @@ -65,13 +65,13 @@ interface Props {
* choose proxy or use other alternatives like signing using ledger
*
*/
export default function SignArea ({ address, call, disabled, extraInfo, isPasswordError, mayBeApi, onSecondaryClick, params, prevState, previousStep, primaryBtn, primaryBtnText, proxyModalHeight, proxyTypeFilter, secondaryBtnText, selectedProxy, setIsPasswordError, setRefresh, setSelectedProxy, setStep, setTxInfo, showBackButtonWithUseProxy = true, steps, token }: Props): React.ReactElement<Props> {
export default function SignArea ({ address, call, disabled, extraInfo, isPasswordError, maybeApi, onSecondaryClick, params, prevState, previousStep, primaryBtn, primaryBtnText, proxyModalHeight, proxyTypeFilter, secondaryBtnText, selectedProxy, setIsPasswordError, setRefresh, setSelectedProxy, setStep, setTxInfo, showBackButtonWithUseProxy = true, steps, token }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const theme = useTheme();
const { account, api: apiFromAddress, chain, formatted } = useInfo(address);

// To handle system chain apis like people chain
const api = mayBeApi || apiFromAddress;
const api = maybeApi || apiFromAddress;

const senderName = useAccountDisplay(address);
const selectedProxyName = useAccountDisplay(getSubstrateAddress(selectedProxy?.delegate));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ interface AddressDetailsProps {
pricesInCurrency: Prices | null | undefined;
selectedAsset: FetchedBalance | undefined;
setSelectedAsset: React.Dispatch<React.SetStateAction<FetchedBalance | undefined>>;
setAssetIdOnAssetHub: React.Dispatch<React.SetStateAction<number | undefined>>;
setAssetIdOnAssetHub: React.Dispatch<React.SetStateAction<number | string | undefined>>;
}

export const EyeIconFullScreen = ({ isHidden, onClick }: { isHidden: boolean | undefined, onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined }) => {
Expand Down Expand Up @@ -197,7 +197,7 @@ function AccountInformationForDetails ({ accountAssets, address, label, price, p
const showAOC = useMemo(() => !!(nonZeroSortedAssets === undefined || (nonZeroSortedAssets && nonZeroSortedAssets.length > 0)), [nonZeroSortedAssets]);

useEffect(() => {
/** if chain has been switched and its not among the selected chains */
/** if chain has been switched and its not among the accounts assets */
if (account?.genesisHash && !accountAssets?.find(({ genesisHash }) => genesisHash === account.genesisHash)) {
return setSelectedAsset(undefined);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ interface Props {
onChange: (value: number | string) => void;
label: string;
style: SxProps<Theme> | undefined;
assetId: number | undefined;
setAssetId: React.Dispatch<React.SetStateAction<number | undefined>>
assetId: number | string | undefined;
setAssetId: React.Dispatch<React.SetStateAction<number | string | undefined>>
}

function AssetSelect ({ address, assetId, label, onChange, setAssetId, style }: Props) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { popupNumbers } from '..';

interface Props {
address: string | undefined;
assetId: number | undefined;
assetId: number | string | undefined;
balance: BalancesInfo | FetchedBalance | undefined;
genesisHash: string | null | undefined;
setDisplayPopup: React.Dispatch<React.SetStateAction<number | undefined>>;
Expand Down Expand Up @@ -134,7 +134,7 @@ export default function CommonTasks ({ address, assetId, balance, genesisHash, s

const goToSend = useCallback(() => {
address && genesisHash &&
openOrFocusTab(`/send/${address}/${assetId || ''}`, true);
openOrFocusTab(`/send/${address}/${assetId}`, true);
}, [address, assetId, genesisHash]);

const goToReceive = useCallback(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,17 @@ export default function AccountDetails (): React.ReactElement {
const pricesInCurrency = usePrices();

const [refreshNeeded, setRefreshNeeded] = useState<boolean>(false);
const [assetIdOnAssetHub, setAssetIdOnAssetHub] = useState<number>();
const [assetIdOnAssetHub, setAssetIdOnAssetHub] = useState<number | string>();
const [selectedAsset, setSelectedAsset] = useState<FetchedBalance>();
const [displayPopup, setDisplayPopup] = useState<number | undefined>();
const [unlockInformation, setUnlockInformation] = useState<UnlockInformationType | undefined>();

const assetId = useMemo(() => assetIdOnAssetHub !== undefined ? assetIdOnAssetHub : selectedAsset?.assetId, [assetIdOnAssetHub, selectedAsset?.assetId]);
const assetId = useMemo(() =>
assetIdOnAssetHub !== undefined
? assetIdOnAssetHub
: selectedAsset?.assetId
, [assetIdOnAssetHub, selectedAsset?.assetId]);

const { price: currentPrice } = useTokenPrice(address, assetId);

const balances = useBalances(address, refreshNeeded, setRefreshNeeded, undefined, assetId || undefined);
Expand Down Expand Up @@ -116,7 +121,7 @@ export default function AccountDetails (): React.ReactElement {
}, [genesisHash]);

useEffect(() => {
if (selectedAsset !== undefined && paramAssetId && assetId !== undefined && assetId !== parseInt(paramAssetId)) {
if (selectedAsset !== undefined && paramAssetId && assetId !== undefined && String(assetId) !== paramAssetId) {
onAction(`/accountfs/${address}/${assetId}`);
}
}, [accountAssets, address, assetId, onAction, paramAssetId, selectedAsset]);
Expand All @@ -126,27 +131,21 @@ export default function AccountDetails (): React.ReactElement {
return;
}

const mayBeAssetIdSelectedInHomePage = assetId !== undefined ? assetId : parseInt(paramAssetId);
const maybeAssetIdSelectedInHomePage = assetId !== undefined ? assetId : paramAssetId;

if (mayBeAssetIdSelectedInHomePage >= 0 && accountAssets) {
const found = accountAssets.find(({ assetId, genesisHash: _genesisHash }) => assetId === mayBeAssetIdSelectedInHomePage && genesisHash === _genesisHash);
if (maybeAssetIdSelectedInHomePage as number >= 0 && accountAssets) {
const found = accountAssets.find(({ assetId, genesisHash: _genesisHash }) => String(assetId) === String(maybeAssetIdSelectedInHomePage) && genesisHash === _genesisHash);

found && setSelectedAsset(found);
}
}, [genesisHash, accountAssets, assetId, paramAssetId, selectedAsset]);

const onChangeAsset = useCallback((id: number | string) => {
if (id === -1) { // this is the id of native token
setAssetIdOnAssetHub(0);

return;
}

setAssetIdOnAssetHub(id as number); // this works for asset hubs atm
}, []);

const goToSend = useCallback(() => {
address && onAction(`/send/${address}/${assetId || ''}`);
address && onAction(`/send/${address}/${assetId}`);
}, [address, assetId, onAction]);

const goToSoloStaking = useCallback(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { logoBlack } from '../../assets/logos';
import { ActionContext, GenesisHashOptionsContext } from '../../components';
import { useInfo } from '../../hooks';
import { FullScreenChainSwitch, RemoteNodeSelectorWithSignals } from '../../partials';
import { EXTENSION_NAME, GOVERNANCE_CHAINS, IDENTITY_CHAINS, SOCIAL_RECOVERY_CHAINS, STAKING_CHAINS } from '../../util/constants';
import { EXTENSION_NAME, GOVERNANCE_CHAINS, IDENTITY_CHAINS, NATIVE_TOKEN_ASSET_ID, SOCIAL_RECOVERY_CHAINS, STAKING_CHAINS } from '../../util/constants';
import { openOrFocusTab } from '../accountDetails/components/CommonTasks';
import AddressDropdown from './components/AddressDropdown';
import ThemeChanger from './partials/ThemeChanger';
Expand Down Expand Up @@ -63,7 +63,7 @@ function FullScreenHeader ({ _otherComponents, noAccountDropDown = false, noChai
case 'accountDetails':
return onAction(`/accountfs/${selectedAddress}/0`);
case 'send':
return onAction(`/send/${selectedAddress}/`);
return onAction(`/send/${selectedAddress}/${NATIVE_TOKEN_ASSET_ID}`);
default:
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ export default function Chronology ({ address, currentTreasuryApprovalList, refe
const [treasuryAwardedBlock, setTreasuryAwardedBlock] = React.useState<number>();
const isTreasury = TREASURY_TRACKS.includes(toSnakeCase(referendum?.trackName) || '');
const isExecuted = referendum?.status === 'Executed';
const mayBeExecutionBlock = sortedHistory?.find((h) => h.status === 'Executed')?.block;
const mayBeBeneficiary = useMemo(() => {
const maybeExecutionBlock = sortedHistory?.find((h) => h.status === 'Executed')?.block;
const maybeBeneficiary = useMemo(() => {
if (referendum?.call && chain) {
return getBeneficiary(referendum, chain);
}
Expand All @@ -89,13 +89,13 @@ export default function Chronology ({ address, currentTreasuryApprovalList, refe
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chain, referendum?.call]);

const mayBeAwardedDate = useMemo(() =>
(currentBlockNumber && spendPeriod && mayBeExecutionBlock && getAwardedDate(currentBlockNumber, mayBeExecutionBlock, spendPeriod)) ||
const maybeAwardedDate = useMemo(() =>
(currentBlockNumber && spendPeriod && maybeExecutionBlock && getAwardedDate(currentBlockNumber, maybeExecutionBlock, spendPeriod)) ||
referendum?.timelinePA?.[1]?.statuses?.[1]?.timestamp
, [currentBlockNumber, mayBeExecutionBlock, spendPeriod, referendum]);
, [currentBlockNumber, maybeExecutionBlock, spendPeriod, referendum]);

/** in rare case as ref 160 the proposers are not the same! needs more research */
const isInTreasuryQueue = useMemo(() => isExecuted && currentTreasuryApprovalList && !!currentTreasuryApprovalList?.find((item) => String(item.value) === referendum.requested && item.beneficiary === mayBeBeneficiary), [currentTreasuryApprovalList, isExecuted, mayBeBeneficiary, referendum]);
const isInTreasuryQueue = useMemo(() => isExecuted && currentTreasuryApprovalList && !!currentTreasuryApprovalList?.find((item) => String(item.value) === referendum.requested && item.beneficiary === maybeBeneficiary), [currentTreasuryApprovalList, isExecuted, maybeBeneficiary, referendum]);
const isAwardedBasedOnPA = useMemo(() => referendum?.timelinePA?.[1]?.type === 'TreasuryProposal' && referendum?.timelinePA?.[1]?.statuses?.[1]?.status === 'Awarded', [referendum]);
const isTreasuryProposalBasedOnPA = useMemo(() => referendum?.timelinePA?.[1]?.type === 'TreasuryProposal', [referendum]);

Expand Down Expand Up @@ -146,7 +146,7 @@ export default function Chronology ({ address, currentTreasuryApprovalList, refe
<Timeline sx={{ [`& .${timelineOppositeContentClasses.root}`]: { flex: 0.3 }, m: 0, p: 0 }}>
<TimelineItem>
<TimelineOppositeContent color='text.primary' sx={{ fontSize: 16, fontWeight: 500, mt: '-7px' }}>
{toFormattedDate(mayBeAwardedDate)}
{toFormattedDate(maybeAwardedDate)}
</TimelineOppositeContent>
<TimelineSeparator>
<TimelineDot sx={{ borderColor: isAwardedBasedOnPA ? 'primary.main' : 'action.focus', borderWidth: '4px', height: '20px', width: '20px' }} variant='outlined' />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default function ReferendumDescription ({ address, currentTreasuryApprova

const [expanded, setExpanded] = useState<boolean>(false);

const mayBeBeneficiary = useMemo(() => {
const maybeBeneficiary = useMemo(() => {
if (referendum?.call && chain) {
return getBeneficiary(referendum, chain);
}
Expand All @@ -60,7 +60,7 @@ export default function ReferendumDescription ({ address, currentTreasuryApprova
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chain, referendum?.call]);

const mayBeTreasuryProposalId = useMemo(() => currentTreasuryApprovalList?.find((p) => p.beneficiary === mayBeBeneficiary)?.id, [currentTreasuryApprovalList, mayBeBeneficiary]);
const maybeTreasuryProposalId = useMemo(() => currentTreasuryApprovalList?.find((p) => p.beneficiary === maybeBeneficiary)?.id, [currentTreasuryApprovalList, maybeBeneficiary]);
const content = useMemo(() => {
const res = referendum?.content?.includes('login and tell us more about your proposal') ? t(DEFAULT_CONTENT) : referendum?.content;

Expand All @@ -82,10 +82,10 @@ export default function ReferendumDescription ({ address, currentTreasuryApprova

return (
<>
{mayBeTreasuryProposalId &&
{maybeTreasuryProposalId &&
<Paper elevation={1} sx={{ height: 36, mb: '2px', mt: '5px', pt: '5px', width: 'inherit' }}>
<Typography sx={{ fontSize: '18px', fontWeight: 500, textAlign: 'center' }}>
{t('This Referendum is now Treasury Proposal #{{proposalId}}', { replace: { proposalId: mayBeTreasuryProposalId } })}
{t('This Referendum is now Treasury Proposal #{{proposalId}}', { replace: { proposalId: maybeTreasuryProposalId } })}
</Typography>
</Paper>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export default function Metadata ({ address, decisionDepositPayer, referendum }:

const referendumLinkOnsSubscan = () => `https://${chainName}.subscan.io/referenda_v2/${String(referendum?.index)}`;

const mayBeBeneficiary = useMemo(() => {
const maybeBeneficiary = useMemo(() => {
if (referendum?.call && chain) {
return getBeneficiary(referendum, chain);
}
Expand Down Expand Up @@ -173,7 +173,7 @@ export default function Metadata ({ address, decisionDepositPayer, referendum }:
/>}
valueStyle={{ fontSize: 16, fontWeight: 500 }}
/>
{mayBeBeneficiary &&
{maybeBeneficiary &&
<>
<LabelValue
label={t('Requested for')}
Expand All @@ -187,23 +187,23 @@ export default function Metadata ({ address, decisionDepositPayer, referendum }:
/>}
valueStyle={{ fontSize: 16, fontWeight: 500 }}
/>
{mayBeBeneficiary &&
{maybeBeneficiary &&
<LabelValue
label={t('Beneficiary')}
labelStyle={{ minWidth: '20%' }}
style={{ justifyContent: 'flex-start' }}
value={
isValidAddress(mayBeBeneficiary)
isValidAddress(maybeBeneficiary)
? <Identity
api={api}
chain={chain}
formatted={mayBeBeneficiary}
formatted={maybeBeneficiary}
identiconSize={25}
showShortAddress
showSocial
style={{ fontSize: '16px', fontWeight: 500, maxWidth: '100%', minWidth: '35%' }}
/>
: <ShowValue value={mayBeBeneficiary} />
: <ShowValue value={maybeBeneficiary} />
}
valueStyle={{ maxWidth: '75%', width: 'fit-content' }}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export default function Cast({ address, notVoted, previousVote, refIndex, setSte

const [estimatedFee, setEstimatedFee] = useState<Balance>();
const [voteType, setVoteType] = useState<'Aye' | 'Nay' | 'Abstain' | undefined>(getVoteType(previousVote));
const mayBePreviousVote = amountToHuman(previousVote?.standard?.balance || previousVote?.splitAbstain?.abstain || (previousVote?.delegating?.voted ? previousVote?.delegating?.balance : undefined), decimal);
const maybePreviousVote = amountToHuman(previousVote?.standard?.balance || previousVote?.splitAbstain?.abstain || (previousVote?.delegating?.voted ? previousVote?.delegating?.balance : undefined), decimal);
const [voteAmount, setVoteAmount] = React.useState<string>('0');
const [conviction, setConviction] = useState<number>();

Expand Down Expand Up @@ -140,12 +140,12 @@ export default function Cast({ address, notVoted, previousVote, refIndex, setSte
}, [conviction, myDelegations, voteAmountAsBN]);

useEffect(() => {
if (mayBePreviousVote) {
setVoteAmount(mayBePreviousVote);
if (maybePreviousVote) {
setVoteAmount(maybePreviousVote);
previousVote?.standard && setConviction(getConviction(previousVote.standard.vote));
previousVote?.delegating && previousVote?.delegating?.voted && setConviction(getConviction(String(previousVote.delegating.conviction)));
}
}, [mayBePreviousVote, previousVote]);
}, [maybePreviousVote, previousVote]);

useEffect(() => {
convictionOptions === undefined && setConviction(1);
Expand Down Expand Up @@ -328,7 +328,7 @@ export default function Cast({ address, notVoted, previousVote, refIndex, setSte

return (
<Grid alignContent='flex-start' alignItems='flex-start' container justifyContent='center' sx={{ mt: '20px', position: 'relative' }}>
{mayBePreviousVote &&
{maybePreviousVote &&
<Warning
fontWeight={300}
marginTop={0}
Expand Down Expand Up @@ -405,7 +405,7 @@ export default function Cast({ address, notVoted, previousVote, refIndex, setSte
</Grid>
</Grid>
</Grid>
<Grid container height={mayBePreviousVote ? '85px' : '100px'} item>
<Grid container height={maybePreviousVote ? '85px' : '100px'} item>
{voteType !== 'Abstain' &&
<Convictions
address={address}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,22 +154,22 @@ export const blockToX = (block: BlockNumber, noUnit = false) => {
}

const b = Number(block);
const mayBeDays = b / DAY_BLOCK_COUNT;
const maybeDays = b / DAY_BLOCK_COUNT;

if (mayBeDays >= 1) {
return `${mayBeDays}` + (!noUnit ? ` ${mayBeDays > 1 ? 'days' : 'day'}` : '');
if (maybeDays >= 1) {
return `${maybeDays}` + (!noUnit ? ` ${maybeDays > 1 ? 'days' : 'day'}` : '');
}

const mayBeHours = b / HOUR_BLOCK_COUNT;
const maybeHours = b / HOUR_BLOCK_COUNT;

if (mayBeHours >= 1) {
return `${mayBeHours}` + (!noUnit ? ` ${mayBeHours > 1 ? 'hours' : 'hour'}` : '');
if (maybeHours >= 1) {
return `${maybeHours}` + (!noUnit ? ` ${maybeHours > 1 ? 'hours' : 'hour'}` : '');
}

const mayBeMins = b / MINUTE_BLOCK_COUNT;
const maybeMins = b / MINUTE_BLOCK_COUNT;

if (mayBeMins >= 1) {
return `${mayBeMins}` + (!noUnit ? ` ${mayBeMins > 1 ? 'mins' : 'min'}` : '');
if (maybeMins >= 1) {
return `${maybeMins}` + (!noUnit ? ` ${maybeMins > 1 ? 'mins' : 'min'}` : '');
}

return undefined;
Expand Down
Loading

0 comments on commit a77459a

Please sign in to comment.