Skip to content

Commit

Permalink
Fetch chaindata from Talisman chaindata (#64)
Browse files Browse the repository at this point in the history
* Fetch chaindata from Talisman chaindata

* fix linter errors

* add graphql

* Native asset transfers

* increase performance

* add chain logo

* revert accidental change

* revert

* add logo on tranfer page

* v-center logo

* fix ui bug

* fix: don't query all chains

* nit fixes

* fixes & toast result

* Update src/pages/transfer.tsx

Co-authored-by: cute0laf <OliverLim818@gmail.com>

* fix

---------

Co-authored-by: cute0laf <oliverlim818@gmail.com>
  • Loading branch information
Szegoo and cuteolaf authored Sep 7, 2023
1 parent dfcb1e1 commit 39fdd5c
Show file tree
Hide file tree
Showing 13 changed files with 197 additions and 73 deletions.
120 changes: 94 additions & 26 deletions chaindata/index.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,107 @@
import { gql, request } from 'graphql-request';
import { RELAY_CHAIN } from "@/consts";
import { gql, request } from "graphql-request"

const graphqlUrl = 'https://squid.subsquid.io/chaindata/v/v4/graphql';
const graphqlUrl = "https://squid.subsquid.io/chaindata/v/v4/graphql"

/// NOTE: this file is copied from the talisman chaindata.
type Chain = {
id: string;
name: string;
paraId: number | null;
relay: {
id: string
} | null;
rpcs: Array<{ url: string }>,
logo: string
}

const chainsQuery = gql`
query chains {
chains(orderBy: sortIndex_ASC) {
type Token = {
data: {
id: string;
logo: string;
assetId?: any;
onChainId?: any;
type: string;
symbol: string;
decimals: number;
isTestnet: boolean;
evmNetwork?: {
id: string;
};
themeColor: string;
coingeckoId: string;
}
}

const chainQuery = gql`
query ChainByRelay($paraId: Int!, $relayId: String!) {
chains(
where: {
paraId_eq: $paraId
relay: { id_eq: $relayId }
}
) {
id
name
paraId
relay {
id
name
paraId
relay {
id
}
rpcs {
url
}
}
rpcs {
url
}
logo
}
}
`;

const tokensQuery = gql`
query tokens {
tokens(orderBy: id_ASC) {
data
const relayQuery = gql`
query ChainByParaIdAndRelay($relayId: String!) {
chains(where: {paraId_isNull: true, id_eq: $relayId}) {
id
name
relay {
id
}
rpcs {
url
}
logo
}
}
`;

export const getChains = async (): Promise<Array<any>> => {
const result: any = await request(graphqlUrl, chainsQuery);
return result.chains;
};
const tokensQuery = gql`
query tokens {
tokens(orderBy: id_ASC) {
data
}
}
`;

export class Chaindata {
private tokens: Array<Token> = [];

public async load(): Promise<void> {
const tokensResult: any = await request(graphqlUrl, tokensQuery);
this.tokens = tokensResult.tokens;
}

export const getTokens = async (): Promise<Array<any>> => {
const result: any = await request(graphqlUrl, tokensQuery);
return result.tokens;
};
public async getChain(chainId: number): Promise<Chain> {
if (chainId === 0) {
const result: any = await request(graphqlUrl, relayQuery, {
relayId: RELAY_CHAIN
});
return result.chains[0];
} else {
const result: any = await request(graphqlUrl, chainQuery, {
paraId: chainId,
relayId: RELAY_CHAIN
});
return result.chains[0];
}
}

public getTokens(): Array<Token> {
return this.tokens;
}
}
2 changes: 1 addition & 1 deletion chaindata/ss58registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ const ss58registry = async (chainName: string): Promise<number | null> => {
return result.prefix;
}

export default ss58registry;
export default ss58registry;
12 changes: 8 additions & 4 deletions src/components/Modals/AddAddress/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import {
FormControl,
FormHelperText,
FormLabel,
ListItemIcon,
MenuItem,
TextField,
} from '@mui/material';
import { contractTx, useInkathon } from '@scio-labs/use-inkathon';
import Image from 'next/image';
import { useEffect, useState } from 'react';

import { isValidAddress } from '@/utils';
Expand Down Expand Up @@ -91,10 +93,9 @@ export const AddAddressModal = ({ open, onClose }: AddAddressModalProps) => {
onClose();
} catch (e: any) {
toastError(
`Failed to add address. Error: ${
e.errorMessage === 'Error'
? 'Please check your balance.'
: e.errorMessage
`Failed to add address. Error: ${e.errorMessage === 'Error'
? 'Please check your balance.'
: e.errorMessage
}`
);
setWorking(false);
Expand Down Expand Up @@ -125,6 +126,9 @@ export const AddAddressModal = ({ open, onClose }: AddAddressModalProps) => {
>
{Object.entries(chains).map(([id, chain], index) => (
<MenuItem value={id} key={index}>
<ListItemIcon>
<Image src={chain.logo} alt='logo' width={32} height={32} />
</ListItemIcon>
{chain.name}
</MenuItem>
))}
Expand Down
31 changes: 12 additions & 19 deletions src/contracts/identity/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
useContract,
useInkathon,
} from '@scio-labs/use-inkathon';
import { getChains } from 'chaindata';
import { Chaindata } from 'chaindata';
import ss58registry from 'chaindata/ss58registry';
import {
createContext,
Expand All @@ -17,7 +17,6 @@ import {
useState,
} from 'react';

import { RELAY_CHAIN } from '@/consts';
import { useToast } from '@/contexts/Toast';

import { IdentityMetadata } from '.';
Expand Down Expand Up @@ -107,33 +106,27 @@ const IdentityContractProvider = ({ children }: Props) => {
const rpcIndex = Math.min(Math.floor(Math.random() * count), count - 1);
const rpc = rpcUrls[rpcIndex];

const chaindata = new Chaindata();

try {
const chainData = (await getChains()).find((chain) =>
chain.paraId
? chain.paraId === chainId && chain.relay.id === RELAY_CHAIN
: chainId === 0 && chain.id === RELAY_CHAIN
);
const chain = await chaindata.getChain(chainId);

if (!chainData) {
if (!chain) {
return null;
}

const ss58Result = await ss58registry(chainData.id);
const ss58Result = await ss58registry(chain.id);

const rpcCount = chainData.rpcs.length;
const rpcIndex = Math.min(
Math.floor(Math.random() * rpcCount),
rpcCount - 1
);
const rpcCount = chain.rpcs.length;
const rpcIndex = Math.min(Math.floor(Math.random() * rpcCount), rpcCount - 1);

const ss58Prefix = ss58Result
? ss58Result
: await fetchSs58Prefix(chainData.rpcs[rpcIndex].url);
const ss58Prefix = ss58Result ? ss58Result : await fetchSs58Prefix(chain.rpcs[rpcIndex].url);

return {
name: chainData.name,
name: chain.name,
ss58Prefix: ss58Prefix,
paraId: chainId,
logo: chain.logo
};
} catch (e) {
toastError && toastError(`Failed to get chain info for ${rpc}`);
Expand All @@ -153,7 +146,7 @@ const IdentityContractProvider = ({ children }: Props) => {
await api.disconnect();

return ss58Prefix;
};
}

setLoadingChains(true);
try {
Expand Down
1 change: 1 addition & 0 deletions src/contracts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export type ChainConsts = {
name: string;
ss58Prefix: number;
paraId: number;
logo: string;
}

export type ChainInfo = ChainConsts & {
Expand Down
50 changes: 36 additions & 14 deletions src/pages/transfer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@ import {
CircularProgress,
FormControl,
FormLabel,
ListItem,
ListItemIcon,
ListItemText,
MenuItem,
Select,
TextField,
} from '@mui/material';
import { ApiPromise, Keyring, WsProvider } from '@polkadot/api';
import { useInkathon } from '@scio-labs/use-inkathon';
import styles from '@styles/pages/transfer.module.scss';
import { getChains, getTokens } from 'chaindata';
import { Chaindata } from 'chaindata';
import Image from 'next/image';
import { useCallback, useEffect, useState } from 'react';
import { AccountType } from 'types/types-arguments/identity';

Expand All @@ -39,7 +43,7 @@ const TransferPage = () => {
loading: loadingIdentity,
} = useIdentity();
const { activeAccount, activeSigner } = useInkathon();
const { toastError } = useToast();
const { toastError, toastSuccess } = useToast();
const { identities } = useAddressBook();

const [sourceChainId, setSourceChainId] = useState<number>();
Expand Down Expand Up @@ -95,17 +99,15 @@ const TransferPage = () => {
setAssets(_assets);
}
} else {
const chainData = (await getChains()).find(
(chain) => chain.paraId ?
chain.paraId === sourceChainId && chain.relay.id === RELAY_CHAIN
:
sourceChainId === 0 && chain.id === RELAY_CHAIN
);
const chaindata = new Chaindata();
const chain = await chaindata.getChain(sourceChainId);

await chaindata.load();

const _assets = [];
if (chainData) {
const tokens = (await getTokens()).filter((token) => {
const prefix = `${chainData.id}-${token.data.type}`;
if (chain) {
const tokens = chaindata.getTokens().filter((token) => {
const prefix = `${chain.id}-${token.data.type}`;
const isPartOfSourceChain = token.data.id.startsWith(prefix);
return isPartOfSourceChain;
});
Expand Down Expand Up @@ -258,6 +260,7 @@ const TransferPage = () => {
amount * Math.pow(10, selectedAsset.decimals),
activeSigner
);
toastSuccess(`Transfer succeeded`);
} catch (e: any) {
toastError(`Transfer failed. Error: ${e.toString()}`);
} finally {
Expand Down Expand Up @@ -316,6 +319,7 @@ const TransferPage = () => {
},
activeSigner
);
toastSuccess(`Transfer succeded`);
} catch (e: any) {
toastError(`Transfer failed. Error: ${e.toString()}`);
}
Expand Down Expand Up @@ -369,8 +373,19 @@ const TransferPage = () => {
onChange={(e) => setSourceChainId(Number(e.target.value))}
>
{Object.entries(chains).map(([chainId, network], index) => (
<MenuItem value={chainId} key={index}>
{network.name}
<MenuItem
value={chainId}
key={index}
sx={{ display: 'flex', alignItems: 'center' }}
>
<ListItem >
<ListItemIcon sx={{ mr: '8px' }}>
<Image src={network.logo} alt='logo' width={32} height={32} />
</ListItemIcon>
<ListItemText>
{network.name}
</ListItemText>
</ListItem>
</MenuItem>
))}
</TextField>
Expand All @@ -387,7 +402,14 @@ const TransferPage = () => {
>
{Object.entries(chains).map(([chainId, network], index) => (
<MenuItem value={chainId} key={index}>
{network.name}
<ListItem>
<ListItemIcon sx={{ mr: '8px' }}>
<Image src={network.logo} alt='logo' width={32} height={32} />
</ListItemIcon>
<ListItemText>
{network.name}
</ListItemText>
</ListItem>
</MenuItem>
))}
</TextField>
Expand Down
6 changes: 5 additions & 1 deletion src/utils/nativeTransfer/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ class SubstrateAssets {
const unsub = await transferCall.signAndSend(account, (result: any) => {
if (result.status.isFinalized) {
unsub();
resolve();
if (result.dispatchError !== undefined) {
reject(result.dispatchError)
} else {
resolve(result)
}
}
})
} catch (e) {
Expand Down
6 changes: 5 additions & 1 deletion src/utils/nativeTransfer/native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ class SubstrateNative {
const unsub = await transferCall.signAndSend(account, (result: any) => {
if (result.status.isFinalized) {
unsub();
resolve();
if (result.dispatchError !== undefined) {
reject(result.dispatchError)
} else {
resolve(result)
}
}
});
} catch (e) {
Expand Down
Loading

0 comments on commit 39fdd5c

Please sign in to comment.