From 21c7117e3dd396afb186bc179577db57abdf88b1 Mon Sep 17 00:00:00 2001 From: zqhxuyuan Date: Thu, 16 Mar 2023 19:07:15 +0800 Subject: [PATCH 1/6] dolphin Signed-off-by: zqhxuyuan --- packages/chain/index.ts | 5 +++- packages/chain/parachains.json | 24 +++++++++++++++ packages/token-lists/lists/dolphin.json | 39 +++++++++++++++++++++++++ packages/token-lists/lists/index.ts | 5 ++++ 4 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 packages/token-lists/lists/dolphin.json diff --git a/packages/chain/index.ts b/packages/chain/index.ts index 979373011..c21c9cbc5 100644 --- a/packages/chain/index.ts +++ b/packages/chain/index.ts @@ -55,6 +55,7 @@ export enum ParachainId { MOONRIVER = 2023, MOONBEAM = 2004, BIFROST_KUSAMA = 2001, + DOLPHIN = 2084 } export enum ChainKey { @@ -62,6 +63,7 @@ export enum ChainKey { MOONBEAM = 'Moonbeam', MOONRIVER = 'Moonriver', BIFROST_KUSAMA = 'Bifrost Kusama', + DOLPHIN = 'Dolphin' } export interface Chain { @@ -84,12 +86,13 @@ export interface Chain { network?: Network } -export const CHAIN_NAMES = ['Astar', 'Moonbeam', 'Moonriver', 'Bifrost Kusama'] +export const CHAIN_NAMES = ['Astar', 'Moonbeam', 'Moonriver', 'Bifrost Kusama', 'Dolphin'] export const PARACHAIN_ID_MAP: { [chainName: string]: number } = { 'Astar': 2006, 'Moonriver': 2023, 'Moonbeam': 2004, 'Bifrost Kusama': 2001, + 'Dolphin': 2084 } const CHAINS = [...json, ...parachains] .filter(chain => CHAIN_NAMES.includes(chain.name)) diff --git a/packages/chain/parachains.json b/packages/chain/parachains.json index abf56fd68..2f7ef3bf3 100644 --- a/packages/chain/parachains.json +++ b/packages/chain/parachains.json @@ -23,5 +23,29 @@ "standard": "none" } ] + }, + { + "name": "Dolphin", + "chain": "Dolphin", + "rpc": [ + "ws://127.0.0.1:9944" + ], + "faucets": [], + "nativeCurrency": { + "name": "Dolphin", + "symbol": "DOL", + "decimals": 18 + }, + "infoURL": "https://manta.network/", + "shortName": "dolphin", + "chainId": 2084, + "networkId": 208, + "explorers": [ + { + "name": "subscan", + "url": "https://bifrost-kusama.subscan.io", + "standard": "none" + } + ] } ] diff --git a/packages/token-lists/lists/dolphin.json b/packages/token-lists/lists/dolphin.json new file mode 100644 index 000000000..ef8448567 --- /dev/null +++ b/packages/token-lists/lists/dolphin.json @@ -0,0 +1,39 @@ +{ + "name": "dolphin", + "timestamp": "2022-12-21T12:02:57.229Z", + "tokens": [ + { + "networkId": 208, + "address": "2084-0-1", + "parachainId": 2084, + "ethereumChainId": 2084, + "assetType": 0, + "assetIndex": 1, + "symbol": "DOL", + "decimals": 18, + "name": "Dolphin" + }, + { + "networkId": 208, + "address": "2084-2-8", + "parachainId": 2084, + "ethereumChainId": 2084, + "assetType": 2, + "assetIndex": 8, + "symbol": "DOL8", + "decimals": 12, + "name": "Dolphin8" + }, + { + "networkId": 208, + "address": "2084-2-9", + "parachainId": 2084, + "ethereumChainId": 2084, + "assetType": 2, + "assetIndex": 9, + "symbol": "DOL9", + "decimals": 12, + "name": "Dolphin9" + } + ] +} diff --git a/packages/token-lists/lists/index.ts b/packages/token-lists/lists/index.ts index 492bd196e..42083e53d 100644 --- a/packages/token-lists/lists/index.ts +++ b/packages/token-lists/lists/index.ts @@ -3,12 +3,14 @@ import MOONBEAM_TOKEN_LIST from './moonbeam.json' import MOONRIVER_TOKEN_LIST from './moonriver.json' import ASTAR_TOKEN_LIST from './astar.json' import BIFROST_KUSAMA_TOKEN_LIST from './bifrost-kusama.json' +import DOLPHIN_TOKEN_LIST from './dolphin.json' export const DEFULT_TOKEN_LIST_MAP: Record = { 'astar': ASTAR_TOKEN_LIST, 'moonriver': MOONRIVER_TOKEN_LIST, 'moonbeam': MOONBEAM_TOKEN_LIST, 'bifrost-kusama': BIFROST_KUSAMA_TOKEN_LIST, + 'dolphin': DOLPHIN_TOKEN_LIST } export const ZENLINK_DEFAULT_TOKEN_LIST: TokenList[] = [ @@ -16,6 +18,7 @@ export const ZENLINK_DEFAULT_TOKEN_LIST: TokenList[] = [ MOONRIVER_TOKEN_LIST, ASTAR_TOKEN_LIST, BIFROST_KUSAMA_TOKEN_LIST, + DOLPHIN_TOKEN_LIST ] export const DEFAULT_LIST_OF_LISTS = [ @@ -23,6 +26,7 @@ export const DEFAULT_LIST_OF_LISTS = [ 'moonriver', 'moonbeam', 'bifrost-kusama', + 'dolphin' ] export const DEFAULT_ACTIVE_LIST = [ @@ -30,4 +34,5 @@ export const DEFAULT_ACTIVE_LIST = [ 'moonriver', 'moonbeam', 'bifrost-kusama', + 'dolphin' ] From d8b95ec8414b44ab74aa57f12cbbce8cfa60d99c Mon Sep 17 00:00:00 2001 From: zqhxuyuan Date: Thu, 16 Mar 2023 19:15:12 +0800 Subject: [PATCH 2/6] add parachain impl of dolphin Signed-off-by: zqhxuyuan --- packages/parachains-impl/dolphin/.eslintrc.js | 1 + .../parachains-impl/dolphin/SwapRouter.ts | 57 ++++++ .../NotificationCentre/Notification.tsx | 162 ++++++++++++++++ .../NotificationCentre/NotificationGroup.tsx | 34 ++++ .../components/NotificationCentre/index.ts | 2 + .../TokenListFilterByQuery.tsx | 66 +++++++ .../TokenListFilterByQuery/index.ts | 1 + .../TokenSelector/TokenListImportChecker.tsx | 10 + .../dolphin/components/TokenSelector/index.ts | 1 + .../dolphin/components/Wallet/Button.tsx | 69 +++++++ .../components/Wallet/Profile/Default.tsx | 134 +++++++++++++ .../components/Wallet/Profile/Profile.tsx | 97 ++++++++++ .../Wallet/Profile/Transactions.tsx | 49 +++++ .../components/Wallet/Profile/index.ts | 3 + .../dolphin/components/Wallet/index.ts | 5 + .../dolphin/components/index.ts | 4 + .../parachains-impl/dolphin/hooks/index.ts | 8 + .../hooks/useAddLiquidityStandardReview.ts | 132 +++++++++++++ .../dolphin/hooks/useBalance/index.ts | 1 + .../dolphin/hooks/useBalance/types.ts | 3 + .../dolphin/hooks/useBalance/useBalance.ts | 117 ++++++++++++ .../dolphin/hooks/usePairTotalSupply.ts | 36 ++++ .../parachains-impl/dolphin/hooks/usePairs.ts | 177 ++++++++++++++++++ .../hooks/useRemoveLiquidityStandardReview.ts | 109 +++++++++++ .../dolphin/hooks/useStablePools.ts | 24 +++ .../dolphin/hooks/useSwapReview.ts | 110 +++++++++++ .../dolphin/hooks/useTotalSupply.ts | 56 ++++++ packages/parachains-impl/dolphin/index.ts | 5 + .../dolphin/libs/constants/address.ts | 69 +++++++ .../dolphin/libs/constants/index.ts | 1 + .../dolphin/libs/formats/currency.ts | 77 ++++++++ .../dolphin/libs/formats/index.ts | 1 + .../parachains-impl/dolphin/libs/index.ts | 3 + .../parachains-impl/dolphin/libs/utils.ts | 8 + packages/parachains-impl/dolphin/package.json | 57 ++++++ .../dolphin/systems/Approve/Approve.tsx | 33 ++++ .../systems/Approve/TokenApproveButton.tsx | 5 + .../dolphin/systems/Approve/index.ts | 1 + .../dolphin/systems/Checker/Amounts.tsx | 65 +++++++ .../dolphin/systems/Checker/Connected.tsx | 21 +++ .../dolphin/systems/Checker/Network.tsx | 27 +++ .../dolphin/systems/Checker/index.ts | 16 ++ .../dolphin/systems/Checker/types.ts | 6 + .../parachains-impl/dolphin/systems/index.ts | 2 + .../parachains-impl/dolphin/tsconfig.json | 5 + packages/parachains-impl/dolphin/types.ts | 7 + 46 files changed, 1877 insertions(+) create mode 100644 packages/parachains-impl/dolphin/.eslintrc.js create mode 100644 packages/parachains-impl/dolphin/SwapRouter.ts create mode 100644 packages/parachains-impl/dolphin/components/NotificationCentre/Notification.tsx create mode 100644 packages/parachains-impl/dolphin/components/NotificationCentre/NotificationGroup.tsx create mode 100644 packages/parachains-impl/dolphin/components/NotificationCentre/index.ts create mode 100644 packages/parachains-impl/dolphin/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx create mode 100644 packages/parachains-impl/dolphin/components/TokenListFilterByQuery/index.ts create mode 100644 packages/parachains-impl/dolphin/components/TokenSelector/TokenListImportChecker.tsx create mode 100644 packages/parachains-impl/dolphin/components/TokenSelector/index.ts create mode 100644 packages/parachains-impl/dolphin/components/Wallet/Button.tsx create mode 100644 packages/parachains-impl/dolphin/components/Wallet/Profile/Default.tsx create mode 100644 packages/parachains-impl/dolphin/components/Wallet/Profile/Profile.tsx create mode 100644 packages/parachains-impl/dolphin/components/Wallet/Profile/Transactions.tsx create mode 100644 packages/parachains-impl/dolphin/components/Wallet/Profile/index.ts create mode 100644 packages/parachains-impl/dolphin/components/Wallet/index.ts create mode 100644 packages/parachains-impl/dolphin/components/index.ts create mode 100644 packages/parachains-impl/dolphin/hooks/index.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useAddLiquidityStandardReview.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useBalance/index.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useBalance/types.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts create mode 100644 packages/parachains-impl/dolphin/hooks/usePairTotalSupply.ts create mode 100644 packages/parachains-impl/dolphin/hooks/usePairs.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useRemoveLiquidityStandardReview.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useStablePools.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useSwapReview.ts create mode 100644 packages/parachains-impl/dolphin/hooks/useTotalSupply.ts create mode 100644 packages/parachains-impl/dolphin/index.ts create mode 100644 packages/parachains-impl/dolphin/libs/constants/address.ts create mode 100644 packages/parachains-impl/dolphin/libs/constants/index.ts create mode 100644 packages/parachains-impl/dolphin/libs/formats/currency.ts create mode 100644 packages/parachains-impl/dolphin/libs/formats/index.ts create mode 100644 packages/parachains-impl/dolphin/libs/index.ts create mode 100644 packages/parachains-impl/dolphin/libs/utils.ts create mode 100644 packages/parachains-impl/dolphin/package.json create mode 100644 packages/parachains-impl/dolphin/systems/Approve/Approve.tsx create mode 100644 packages/parachains-impl/dolphin/systems/Approve/TokenApproveButton.tsx create mode 100644 packages/parachains-impl/dolphin/systems/Approve/index.ts create mode 100644 packages/parachains-impl/dolphin/systems/Checker/Amounts.tsx create mode 100644 packages/parachains-impl/dolphin/systems/Checker/Connected.tsx create mode 100644 packages/parachains-impl/dolphin/systems/Checker/Network.tsx create mode 100644 packages/parachains-impl/dolphin/systems/Checker/index.ts create mode 100644 packages/parachains-impl/dolphin/systems/Checker/types.ts create mode 100644 packages/parachains-impl/dolphin/systems/index.ts create mode 100644 packages/parachains-impl/dolphin/tsconfig.json create mode 100644 packages/parachains-impl/dolphin/types.ts diff --git a/packages/parachains-impl/dolphin/.eslintrc.js b/packages/parachains-impl/dolphin/.eslintrc.js new file mode 100644 index 000000000..b5401b5c4 --- /dev/null +++ b/packages/parachains-impl/dolphin/.eslintrc.js @@ -0,0 +1 @@ +module.exports = require('@zenlink-interface/eslint-config') diff --git a/packages/parachains-impl/dolphin/SwapRouter.ts b/packages/parachains-impl/dolphin/SwapRouter.ts new file mode 100644 index 000000000..5f1977509 --- /dev/null +++ b/packages/parachains-impl/dolphin/SwapRouter.ts @@ -0,0 +1,57 @@ +import type { ApiPromise } from '@polkadot/api' +import type { SubmittableExtrinsic } from '@polkadot/api/types' +import type { Trade } from '@zenlink-interface/amm' +import type { ZenlinkProtocolPrimitivesAssetId } from '@zenlink-interface/format' +import { addressToZenlinkAssetId } from '@zenlink-interface/format' +import type { Percent } from '@zenlink-interface/math' + +export interface TradeOptions { + api: ApiPromise + /** + * How much the execution price is allowed to move unfavorably from the trade execution price. + */ + allowedSlippage: Percent + /** + * The account that should receive the output of the swap. + */ + recipient: string +} + +export interface TradeOptionsDeadline extends TradeOptions { + /** + * When the transaction expires. + * This is an atlernate to specifying the ttl, for when you do not want to use local time. + */ + deadline: number +} + +export interface SwapParameters { + extrinsic: SubmittableExtrinsic<'promise'>[] | null +} + +export abstract class SwapRouter { + /** + * Cannot be constructed. + */ + private constructor() {} + + public static swapCallParameters( + trade: Trade, + options: TradeOptionsDeadline, + ): SwapParameters { + const methodName = 'swapExactAssetsForAssets' + const args: [string, string, ZenlinkProtocolPrimitivesAssetId[], string, number] = [ + trade.inputAmount.quotient.toString(), + trade.minimumAmountOut(options.allowedSlippage).quotient.toString(), + trade.route.tokenPath.map(token => addressToZenlinkAssetId(token.address)), + options.recipient, + options.deadline, + ] + + return { + extrinsic: [ + options.api.tx.zenlinkProtocol[methodName](...args), + ], + } + } +} diff --git a/packages/parachains-impl/dolphin/components/NotificationCentre/Notification.tsx b/packages/parachains-impl/dolphin/components/NotificationCentre/Notification.tsx new file mode 100644 index 000000000..3e7d55674 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/NotificationCentre/Notification.tsx @@ -0,0 +1,162 @@ +import { Disclosure } from '@headlessui/react' +import { + ArrowDownTrayIcon, + ArrowRightIcon, + ArrowUpTrayIcon, + ArrowsUpDownIcon, + FireIcon, + LockOpenIcon, + PlusIcon, + UserPlusIcon, + UsersIcon, + XMarkIcon, +} from '@heroicons/react/24/solid' +import { ChevronDownIcon } from '@heroicons/react/20/solid' +import chains, { ParachainId, chainsChainIdToParachainId } from '@zenlink-interface/chain' +import type { NotificationData } from '@zenlink-interface/ui' +import { + Badge, + Dots, + IconButton, + Link, + Loader, + NetworkIcon, + TimeAgo, + Typography, + classNames, +} from '@zenlink-interface/ui' +import type { FC } from 'react' +import { useWaitForTransaction } from '@zenlink-interface/polkadot' + +export const Notification: FC<{ data: string; showExtra?: boolean; hideStatus?: boolean }> = ({ + data, + showExtra = false, + hideStatus = false, +}) => { + const notification: NotificationData = JSON.parse(data) + const { status } = useWaitForTransaction(notification.chainId, notification.txHash) + + if (!status) { + return ( +
+
+
+
+
+
+
+
+
+
+
+
+ ) + } + + return ( +
+ {showExtra && ( + + {({ open }) => { + return ( + + + + ) + }} + + )} + +
+ }> +
+ {!hideStatus + && (status === 'loading' + ? ( + + ) + : status === 'error' + ? ( + + ) + : ( + <> + ))} + {(status === 'success' || notification.summary.info) && notification.type === 'send' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'swap' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'approval' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'mint' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'burn' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'enterBar' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'leaveBar' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'generateCode' && ( + + )} + {(status === 'success' || notification.summary.info) && notification.type === 'setCode' && ( + + )} +
+
+
+
+ + {notification.summary.info + ? ( + notification.summary.info + ) + : ['loading'].includes(status) + ? ( + {notification.summary.pending} + ) + : status === 'error' + ? ( + notification.summary.failed + ) + : ( + notification.summary.completed + )} + +
+ + + +
+
+
+
+ ) +} diff --git a/packages/parachains-impl/dolphin/components/NotificationCentre/NotificationGroup.tsx b/packages/parachains-impl/dolphin/components/NotificationCentre/NotificationGroup.tsx new file mode 100644 index 000000000..92890055d --- /dev/null +++ b/packages/parachains-impl/dolphin/components/NotificationCentre/NotificationGroup.tsx @@ -0,0 +1,34 @@ +import { Disclosure } from '@headlessui/react' +import type { FC } from 'react' + +import { Notification } from './Notification' + +interface NotificationGroupProps { + notifications: string[] +} + +export const NotificationGroup: FC = ({ notifications }) => { + return ( + + {({ open }) => { + return ( +
+ {notifications.length > 1 && open && ( +
+ )} + 1} /> + {notifications.length > 1 && ( + + {notifications.map((el, idx) => { + if (idx > 0) + return + return <> + })} + + )} +
+ ) + }} + + ) +} diff --git a/packages/parachains-impl/dolphin/components/NotificationCentre/index.ts b/packages/parachains-impl/dolphin/components/NotificationCentre/index.ts new file mode 100644 index 000000000..45788b8d9 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/NotificationCentre/index.ts @@ -0,0 +1,2 @@ +export * from './Notification' +export * from './NotificationGroup' diff --git a/packages/parachains-impl/dolphin/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx b/packages/parachains-impl/dolphin/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx new file mode 100644 index 000000000..d06b55e71 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx @@ -0,0 +1,66 @@ +import type { ParachainId } from '@zenlink-interface/chain' +import type { Token, Type } from '@zenlink-interface/currency' +import { filterTokens, tokenComparator, useDebounce, useSortedTokensByQuery } from '@zenlink-interface/hooks' +import type { Fraction } from '@zenlink-interface/math' +import type { FC, RefObject } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' +import type { BalanceMap } from '../../hooks/useBalance/types' + +interface RenderProps { + currencies: Type[] + inputRef: RefObject + query: string + onInput(query: string): void + searching: boolean + queryToken: [Token | undefined] +} + +interface Props { + chainId?: ParachainId + tokenMap: Record + pricesMap?: Record + balancesMap?: BalanceMap + children(props: RenderProps): JSX.Element + includeNative?: boolean +} + +export const TokenListFilterByQuery: FC = ({ + children, + tokenMap, + balancesMap, + pricesMap, +}) => { + const tokenMapValues = useMemo(() => Object.values(tokenMap), [tokenMap]) + const inputRef = useRef(null) + const [query, setQuery] = useState('') + const debouncedQuery = useDebounce(query, 400) + const searching = useRef(false) + + useEffect(() => { + if (query.length > 0) + searching.current = true + }, [query]) + + const filteredTokens: Token[] = useMemo(() => { + const filtered = filterTokens(tokenMapValues, debouncedQuery) + searching.current = false + return filtered + }, [tokenMapValues, debouncedQuery]) + + const sortedTokens: Token[] = useMemo(() => { + return [...filteredTokens].sort(tokenComparator(balancesMap, pricesMap)) + }, [filteredTokens, pricesMap, balancesMap]) + + const filteredSortedTokens = useSortedTokensByQuery(sortedTokens, debouncedQuery) + + return useMemo(() => { + return children({ + currencies: filteredSortedTokens, + inputRef, + query, + onInput: setQuery, + searching: searching.current, + queryToken: [undefined], + }) + }, [children, filteredSortedTokens, query]) +} diff --git a/packages/parachains-impl/dolphin/components/TokenListFilterByQuery/index.ts b/packages/parachains-impl/dolphin/components/TokenListFilterByQuery/index.ts new file mode 100644 index 000000000..81f124de4 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/TokenListFilterByQuery/index.ts @@ -0,0 +1 @@ +export * from './TokenListFilterByQuery' diff --git a/packages/parachains-impl/dolphin/components/TokenSelector/TokenListImportChecker.tsx b/packages/parachains-impl/dolphin/components/TokenSelector/TokenListImportChecker.tsx new file mode 100644 index 000000000..7da752d06 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/TokenSelector/TokenListImportChecker.tsx @@ -0,0 +1,10 @@ +import type { FC, ReactNode } from 'react' + +interface TokenListImportCheckerProps { + children: ReactNode +} + +// Currently no token import checker on Bifrost chain +export const TokenListImportChecker: FC = ({ children }) => { + return <>{children} +} diff --git a/packages/parachains-impl/dolphin/components/TokenSelector/index.ts b/packages/parachains-impl/dolphin/components/TokenSelector/index.ts new file mode 100644 index 000000000..4ffe0c674 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/TokenSelector/index.ts @@ -0,0 +1 @@ +export * from './TokenListImportChecker' diff --git a/packages/parachains-impl/dolphin/components/Wallet/Button.tsx b/packages/parachains-impl/dolphin/components/Wallet/Button.tsx new file mode 100644 index 000000000..0306730fe --- /dev/null +++ b/packages/parachains-impl/dolphin/components/Wallet/Button.tsx @@ -0,0 +1,69 @@ +import { connectors } from '@zenlink-interface/polkadot' +import { useSettings } from '@zenlink-interface/shared' +import type { ButtonProps } from '@zenlink-interface/ui' +import { + AppearOnMount, + Menu, + PolkadotwalletIcon, + SubwalletIcon, + TalismanIcon, + Button as UIButton, +} from '@zenlink-interface/ui' +import type { ReactNode } from 'react' + +const Icons: Record = { + 'Polkadot-js': , + 'Subwallet': , + 'Talisman': , +} + +export type Props = ButtonProps & { + appearOnMount?: boolean +} + +export const Button = ({ + children, + appearOnMount = true, + ...rest +}: Props) => { + const [, { updatePolkadotConnector }] = useSettings() + + return ( + + {(isMounted) => { + if (isMounted) { + return ( + + {children || 'Connect Wallet'} + + } + > + +
+ {isMounted + && connectors.map(connector => ( + updatePolkadotConnector(connector.source)} + className="flex items-center gap-3 group" + > +
+ {Icons[connector.name] && Icons[connector.name]} +
{' '} + {connector.name} +
+ ))} +
+
+
+ ) + } + + return {children || 'Connect Wallet'} + }} +
+ ) +} diff --git a/packages/parachains-impl/dolphin/components/Wallet/Profile/Default.tsx b/packages/parachains-impl/dolphin/components/Wallet/Profile/Default.tsx new file mode 100644 index 000000000..e3638a796 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/Wallet/Profile/Default.tsx @@ -0,0 +1,134 @@ +import { ArrowLeftOnRectangleIcon, ArrowTopRightOnSquareIcon, DocumentDuplicateIcon } from '@heroicons/react/24/outline' +import { CheckIcon, ChevronRightIcon } from '@heroicons/react/24/solid' +import type { ParachainId } from '@zenlink-interface/chain' +import { chains } from '@zenlink-interface/chain' +import { Amount, Native } from '@zenlink-interface/currency' +import { shortenName } from '@zenlink-interface/format' +import { usePrices } from '@zenlink-interface/shared' +import type { Account } from '@zenlink-interface/polkadot' +import { useNativeBalancesAll } from '@zenlink-interface/polkadot' +import { CopyHelper, IconButton, JazzIcon, Select, Typography } from '@zenlink-interface/ui' +import type { Dispatch, FC, SetStateAction } from 'react' +import { useMemo } from 'react' +import { ProfileView } from './Profile' + +interface DefaultProps { + chainId: ParachainId + account: Account + setView: Dispatch> + allAccounts: Account[] + updatePolkadotAddress: (polkadotAddress: string | undefined) => void + disconnect: () => void +} + +export const Default: FC = ({ + chainId, + account, + setView, + allAccounts, + disconnect, + updatePolkadotAddress, +}) => { + const { data: prices } = usePrices({ chainId }) + const balancesAll = useNativeBalancesAll(chainId, account.address) + + const balance = useMemo( + () => Amount.fromRawAmount(Native.onChain(chainId), balancesAll ? balancesAll.freeBalance.toString() : '0'), + [balancesAll, chainId], + ) + + const balanceAsUsd = useMemo(() => { + return prices?.[Native.onChain(chainId).wrapped.address] + ? balance.multiply(prices?.[Native.onChain(chainId).wrapped.address]) + : balance.multiply('0') + }, [balance, chainId, prices]) + + return ( + <> +
+
+ + + +
+ + {isCopied => ( + + + + )} + + + + + { disconnect() }} className="p-0.5" description="Disconnect"> + + +
+
+
+ + {balance.toSignificant(6)} {Native.onChain(chainId).symbol} + + + ${balanceAsUsd?.toFixed(2)} + +
+
+
+
+
+
+ +
+ + ) +} diff --git a/packages/parachains-impl/dolphin/components/Wallet/Profile/Profile.tsx b/packages/parachains-impl/dolphin/components/Wallet/Profile/Profile.tsx new file mode 100644 index 000000000..bf2447fec --- /dev/null +++ b/packages/parachains-impl/dolphin/components/Wallet/Profile/Profile.tsx @@ -0,0 +1,97 @@ +import { Popover } from '@headlessui/react' +import type { ParachainId } from '@zenlink-interface/chain' +import { useAccount } from '@zenlink-interface/polkadot' +import { ChevronDownIcon } from '@heroicons/react/20/solid' +import { DEFAULT_INPUT_UNSTYLED, JazzIcon, classNames, useBreakpoint } from '@zenlink-interface/ui' +import type { FC } from 'react' +import { useCallback, useState } from 'react' +import ReactDOM from 'react-dom' +import { useSettings } from '@zenlink-interface/shared' +import { shortenName } from '@zenlink-interface/format' +import { Default, Transactions, Wallet } from '..' + +export enum ProfileView { + Default, + Transactions, +} + +interface ProfileProps { + parachainId: ParachainId + supportedNetworks: ParachainId[] + notifications: Record + clearNotifications(): void +} + +export const Profile: FC = ({ + notifications, + clearNotifications, + parachainId, +}) => { + const { isSm } = useBreakpoint('sm') + const [view, setView] = useState(ProfileView.Default) + const [{ polkadotConnector }, { updatePolkadotConnector, updatePolkadotAddress }] = useSettings() + const { account, allAccounts } = useAccount() + + const disconnect = useCallback(() => { + updatePolkadotAddress(undefined) + updatePolkadotConnector(undefined) + }, [updatePolkadotAddress, updatePolkadotConnector]) + + if (!polkadotConnector || !account) { + return ( + + ) + } + + if (account) { + const panel = ( + + {view === ProfileView.Default && ( + + )} + {view === ProfileView.Transactions && ( + + )} + + ) + + return ( + + {({ open }) => { + return ( + <> + + + {account.name && shortenName(account.name)}{' '} + + + {!isSm ? ReactDOM.createPortal(panel, document.body) : panel} + + ) + }} + + ) + } + + return +} diff --git a/packages/parachains-impl/dolphin/components/Wallet/Profile/Transactions.tsx b/packages/parachains-impl/dolphin/components/Wallet/Profile/Transactions.tsx new file mode 100644 index 000000000..29296bd3d --- /dev/null +++ b/packages/parachains-impl/dolphin/components/Wallet/Profile/Transactions.tsx @@ -0,0 +1,49 @@ +import { ChevronLeftIcon } from '@heroicons/react/24/solid' +import { Button, IconButton, Typography } from '@zenlink-interface/ui' +import type { Dispatch, FC, SetStateAction } from 'react' + +import { NotificationGroup } from '../../NotificationCentre' +import { ProfileView } from './Profile' + +interface TransactionsProps { + setView: Dispatch> + notifications: Record + clearNotifications(): void +} + +export const Transactions: FC = ({ setView, notifications, clearNotifications }) => { + return ( +
+
+
+ setView(ProfileView.Default)}> + + +
+ + Transactions + +
+ +
+
+
+ {Object.entries(notifications).length > 0 + ? ( + Object.entries(notifications) + .reverse() + .map(([, notifications], index) => { + return + }) + ) + : ( + + Your transactions will appear here + + )} +
+
+ ) +} diff --git a/packages/parachains-impl/dolphin/components/Wallet/Profile/index.ts b/packages/parachains-impl/dolphin/components/Wallet/Profile/index.ts new file mode 100644 index 000000000..b98c245ac --- /dev/null +++ b/packages/parachains-impl/dolphin/components/Wallet/Profile/index.ts @@ -0,0 +1,3 @@ +export * from './Default' +export * from './Profile' +export * from './Transactions' diff --git a/packages/parachains-impl/dolphin/components/Wallet/index.ts b/packages/parachains-impl/dolphin/components/Wallet/index.ts new file mode 100644 index 000000000..7043aad88 --- /dev/null +++ b/packages/parachains-impl/dolphin/components/Wallet/index.ts @@ -0,0 +1,5 @@ +import { Button } from './Button' + +export const Wallet = { Button } + +export * from './Profile' diff --git a/packages/parachains-impl/dolphin/components/index.ts b/packages/parachains-impl/dolphin/components/index.ts new file mode 100644 index 000000000..1b6a9807a --- /dev/null +++ b/packages/parachains-impl/dolphin/components/index.ts @@ -0,0 +1,4 @@ +export * from './NotificationCentre' +export * from './TokenListFilterByQuery' +export * from './TokenSelector' +export * from './Wallet' diff --git a/packages/parachains-impl/dolphin/hooks/index.ts b/packages/parachains-impl/dolphin/hooks/index.ts new file mode 100644 index 000000000..439107c43 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/index.ts @@ -0,0 +1,8 @@ +export * from './useAddLiquidityStandardReview' +export * from './useBalance' +export * from './usePairs' +export * from './usePairTotalSupply' +export * from './useRemoveLiquidityStandardReview' +export * from './useStablePools' +export * from './useSwapReview' +export * from './useTotalSupply' diff --git a/packages/parachains-impl/dolphin/hooks/useAddLiquidityStandardReview.ts b/packages/parachains-impl/dolphin/hooks/useAddLiquidityStandardReview.ts new file mode 100644 index 000000000..fba9239ef --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useAddLiquidityStandardReview.ts @@ -0,0 +1,132 @@ +import type { ParachainId } from '@zenlink-interface/chain' +import { Amount } from '@zenlink-interface/currency' +import type { Type } from '@zenlink-interface/currency' +import { Percent } from '@zenlink-interface/math' +import type { TransactionRequest } from '@zenlink-interface/polkadot' +import { useAccount, useApi, useBlockNumber, useSendTransaction } from '@zenlink-interface/polkadot' +import { useNotifications, useSettings } from '@zenlink-interface/shared' +import type { Dispatch, SetStateAction } from 'react' +import { useCallback, useMemo } from 'react' +import { calculateSlippageAmount } from '@zenlink-interface/amm' +import { addressToZenlinkAssetId } from '@zenlink-interface/format' +import { PairState } from './usePairs' + +interface UseAddLiquidityStandardReviewParams { + chainId: ParachainId + poolState: PairState + token0: Type | undefined + token1: Type | undefined + input0: Amount | undefined + input1: Amount | undefined + setOpen: Dispatch> +} + +type UseAddLiquidityStandardReview = (params: UseAddLiquidityStandardReviewParams) => { + isWritePending: boolean + sendTransaction: (() => void) | undefined + routerAddress: string | undefined +} + +export const useAddLiquidityStandardReview: UseAddLiquidityStandardReview = ({ + chainId, + token0, + token1, + input0, + input1, + setOpen, + poolState, +}) => { + const api = useApi(chainId) + const { account } = useAccount() + const [, { createPendingNotification }] = useNotifications(account?.address) + const blockNumber = useBlockNumber(chainId) + const [{ slippageTolerance }] = useSettings() + + const slippagePercent = useMemo(() => { + return new Percent(Math.floor(slippageTolerance * 100), 10_000) + }, [slippageTolerance]) + + const [minAmount0, minAmount1] = useMemo(() => { + return [ + input0 + ? poolState === PairState.NOT_EXISTS + ? input0 + : Amount.fromRawAmount(input0.currency, calculateSlippageAmount(input0, slippagePercent)[0]) + : undefined, + input1 + ? poolState === PairState.NOT_EXISTS + ? input1 + : Amount.fromRawAmount(input1.currency, calculateSlippageAmount(input1, slippagePercent)[0]) + : undefined, + ] + }, [poolState, input0, input1, slippagePercent]) + + const prepare = useCallback( + (setRequest: Dispatch>) => { + if ( + !chainId + || !api + || !token0 + || !token1 + || !input0 + || !input1 + || !account + || !minAmount0 + || !minAmount1 + ) + return + + // Deadline is currently default to next 20 blocks + try { + const deadline = blockNumber && blockNumber.toNumber() + 20 + const args = [ + addressToZenlinkAssetId(token0.wrapped.address), + addressToZenlinkAssetId(token1.wrapped.address), + input0.quotient.toString(), + input1.quotient.toString(), + minAmount0.quotient.toString(), + minAmount1.quotient.toString(), + deadline, + ] + const extrinsic = [api.tx.zenlinkProtocol.addLiquidity(...args)] + + const ts = new Date().getTime() + const notification: TransactionRequest['notification'] = { + type: 'mint', + chainId, + summary: { + pending: `Adding liquidity to the ${token0.symbol}/${token1.symbol} pair`, + completed: `Successfully added liquidity to the ${token0.symbol}/${token1.symbol} pair`, + failed: 'Something went wrong when adding liquidity', + }, + timestamp: ts, + groupTimestamp: ts, + } + + setRequest({ + extrinsic, + account, + notification, + }) + } + catch (e: unknown) {} + }, + [account, api, blockNumber, chainId, input0, input1, minAmount0, minAmount1, token0, token1], + ) + + const { sendTransaction, isLoading: isWritePending } = useSendTransaction({ + chainId, + createPendingNotification, + prepare, + onSuccess: (status) => { + if (status) + setOpen(false) + }, + }) + + return useMemo(() => ({ + isWritePending, + sendTransaction, + routerAddress: undefined, + }), [isWritePending, sendTransaction]) +} diff --git a/packages/parachains-impl/dolphin/hooks/useBalance/index.ts b/packages/parachains-impl/dolphin/hooks/useBalance/index.ts new file mode 100644 index 000000000..f449ac660 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useBalance/index.ts @@ -0,0 +1 @@ +export * from './useBalance' diff --git a/packages/parachains-impl/dolphin/hooks/useBalance/types.ts b/packages/parachains-impl/dolphin/hooks/useBalance/types.ts new file mode 100644 index 000000000..2557e74b1 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useBalance/types.ts @@ -0,0 +1,3 @@ +import type { Amount, Type } from '@zenlink-interface/currency' + +export type BalanceMap = Record | undefined> | undefined diff --git a/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts b/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts new file mode 100644 index 000000000..cf6cdb762 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts @@ -0,0 +1,117 @@ +import type { QueryableStorageEntry } from '@polkadot/api/types' +import type { ParachainId } from '@zenlink-interface/chain' +import type { Token, Type } from '@zenlink-interface/currency' +import { Amount } from '@zenlink-interface/currency' +import { isZenlinkAddress } from '@zenlink-interface/format' +import { JSBI } from '@zenlink-interface/math' +import { useAccount, useApi, useCallMulti, useNativeBalancesAll } from '@zenlink-interface/polkadot' +import type { OrmlAccountData } from '@zenlink-types/bifrost/interfaces' +import { useMemo } from 'react' +import { addressToNodeCurrency, isNativeCurrency } from '../../libs' +import type { NodePrimitivesCurrency } from '../../types' +import type { BalanceMap } from './types' + +interface UseBalancesParams { + account: string | undefined + currencies: (Type | undefined)[] + chainId?: ParachainId + enabled?: boolean +} + +type UseBalances = (params: UseBalancesParams) => { + data: BalanceMap + isLoading: boolean + isError: boolean +} + +export const useBalances: UseBalances = ({ + chainId, + account, + currencies, + enabled = true, +}) => { + const api = useApi(chainId) + const { isAccount } = useAccount() + const nativeBalancesAll = useNativeBalancesAll(chainId, account, enabled) + + const validatedTokens = useMemo( + () => + currencies.filter( + (currency): currency is Token => + !!chainId && !!currency && isZenlinkAddress(currency.wrapped.address), + ), + [chainId, currencies], + ) + + const balances = useCallMulti({ + chainId, + calls: (api && isAccount(account)) + ? validatedTokens + .map(currency => [api.query.tokens.accounts, [account, addressToNodeCurrency(currency.wrapped.address)]]) + .filter((call): call is [QueryableStorageEntry<'promise'>, [string, NodePrimitivesCurrency]] => Boolean(call[0])) + : [], + options: { enabled: enabled && Boolean(api && isAccount(account)) }, + }) + + const balanceMap: BalanceMap = useMemo(() => { + const result: BalanceMap = {} + if (balances.length !== validatedTokens.length) + return result + for (let i = 0; i < validatedTokens.length; i++) { + const value = balances[i]?.free.toString() + const amount = value ? JSBI.BigInt(value.toString()) : undefined + + if (!result[validatedTokens[i].address]) + result[validatedTokens[i].address] = Amount.fromRawAmount(validatedTokens[i], '0') + + if (amount) + result[validatedTokens[i].address] = Amount.fromRawAmount(validatedTokens[i], amount) + else + result[validatedTokens[i].address] = Amount.fromRawAmount(validatedTokens[i], '0') + + // BNC + if (isNativeCurrency(validatedTokens[i])) + result[validatedTokens[i].wrapped.address] = Amount.fromRawAmount(validatedTokens[i], nativeBalancesAll?.freeBalance.toString() || '0') + } + return result + }, [balances, nativeBalancesAll?.freeBalance, validatedTokens]) + + return useMemo(() => ({ + data: balanceMap, + isLoading: isAccount(account) && (!nativeBalancesAll || !balances.length), + isError: !isAccount(account), + }), [balanceMap, isAccount, account, nativeBalancesAll, balances.length]) +} + +interface UseBalanceParams { + account: string | undefined + currency: Type | undefined + chainId?: ParachainId + enabled?: boolean +} + +type UseBalance = (params: UseBalanceParams) => Pick, 'isError' | 'isLoading'> & { + data: Amount | undefined +} + +export const useBalance: UseBalance = ({ + chainId, + account, + currency, + enabled, +}) => { + const currencies = useMemo(() => [currency], [currency]) + const { data, isLoading, isError } = useBalances({ chainId, currencies, account, enabled }) + + return useMemo(() => { + const balance = currency + ? data?.[currency.wrapped.address] + : undefined + + return { + isError, + isLoading, + data: balance, + } + }, [isError, isLoading, currency, data]) +} diff --git a/packages/parachains-impl/dolphin/hooks/usePairTotalSupply.ts b/packages/parachains-impl/dolphin/hooks/usePairTotalSupply.ts new file mode 100644 index 000000000..a24b2106a --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/usePairTotalSupply.ts @@ -0,0 +1,36 @@ +import type { Pair } from '@zenlink-interface/amm' +import type { ParachainId } from '@zenlink-interface/chain' +import { Amount } from '@zenlink-interface/currency' +import { addressToZenlinkAssetId } from '@zenlink-interface/format' +import { useApi, useCall } from '@zenlink-interface/polkadot' +import type { ZenlinkAssetBalance, PairStatus as _PairStatus } from '@zenlink-types/bifrost/interfaces' +import { useMemo } from 'react' + +interface PairStatus extends Omit<_PairStatus, 'asTrading'> { + asTrading: { + totalSupply: ZenlinkAssetBalance + } +} + +export const usePairTotalSupply = (pair: Pair | undefined | null, chainId: ParachainId, enabled = true) => { + const api = useApi(chainId) + const pairStatus = useCall({ + chainId, + fn: api?.query.zenlinkProtocol.pairStatuses, + params: pair + ? [ + [ + addressToZenlinkAssetId(pair.token0.address), + addressToZenlinkAssetId(pair.token1.address), + ], + ] + : [], + options: { enabled: enabled && !!api }, + }) + + return useMemo(() => { + if (!pair || !pairStatus || pairStatus.isDisable || !pairStatus.isTrading) + return undefined + return Amount.fromRawAmount(pair.liquidityToken, pairStatus.asTrading.totalSupply.toHex()) + }, [pair, pairStatus]) +} diff --git a/packages/parachains-impl/dolphin/hooks/usePairs.ts b/packages/parachains-impl/dolphin/hooks/usePairs.ts new file mode 100644 index 000000000..8afdf2de5 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/usePairs.ts @@ -0,0 +1,177 @@ +import type { QueryableStorageEntry } from '@polkadot/api/types' +import type { Struct } from '@polkadot/types-codec' +import { Pair } from '@zenlink-interface/amm' +import type { Currency, Token, Type } from '@zenlink-interface/currency' +import { Amount } from '@zenlink-interface/currency' +import { addressToZenlinkAssetId } from '@zenlink-interface/format' +import { useApi, useCallMulti } from '@zenlink-interface/polkadot' +import type { AccountId, OrmlTokensAccountData, ZenlinkAssetBalance } from '@zenlink-types/bifrost/interfaces' +import type { FrameSystemAccountInfo } from '@polkadot/types/lookup' +import { useMemo } from 'react' +import { ParachainId } from '@zenlink-interface/chain' +import { PAIR_ADDRESSES, addressToNodeCurrency, isNativeCurrency } from '../libs' +import type { PairPrimitivesAssetId } from '../types' + +export enum PairState { + LOADING, + NOT_EXISTS, + EXISTS, + INVALID, +} + +export function getPairs(chainId: number | undefined, currencies: [Currency | undefined, Currency | undefined][]) { + return currencies + .filter((currencies): currencies is [Type, Type] => { + const [currencyA, currencyB] = currencies + return Boolean( + chainId + && chainId === ParachainId.DOLPHIN + && currencyA + && currencyB + && currencyA.chainId === currencyB.chainId + && chainId === currencyA.chainId + && !currencyA.wrapped.equals(currencyB.wrapped), + ) + }) + .reduce<[Token[], Token[], PairPrimitivesAssetId[]]>( + (acc, [currencyA, currencyB]) => { + const [token0, token1] = currencyA.wrapped.sortsBefore(currencyB.wrapped) + ? [currencyA.wrapped, currencyB.wrapped] + : [currencyB.wrapped, currencyA.wrapped] + + acc[0].push(token0) + acc[1].push(token1) + acc[2].push([ + addressToZenlinkAssetId(token0.address), + addressToZenlinkAssetId(token1.address), + ]) + return acc + }, + [[], [], []], + ) +} + +export function uniqePairKey(tokenA: Token, tokenB: Token): string { + return `${tokenA.address}-${tokenB.address}` +} + +interface UsePairsReturn { + isLoading: boolean + isError: boolean + data: [PairState, Pair | null][] +} + +export interface ZenlinkPairMetadata extends Struct { + readonly pairAccount: AccountId + readonly targetSupply: ZenlinkAssetBalance +} + +export function usePairs( + chainId: number | undefined, + currencies: [Currency | undefined, Currency | undefined][], + enabled = true, +): UsePairsReturn { + const api = useApi(chainId) + const [tokensA, tokensB] = useMemo(() => getPairs(chainId, currencies), [chainId, currencies]) + + const [validTokensA, validTokensB, reservesCalls] = useMemo( + () => tokensA.reduce<[Token[], Token[], [QueryableStorageEntry<'promise'>, ...unknown[]][]]>( + (acc, tokenA, i) => { + const tokenB = tokensB[i] + const pairKey = uniqePairKey(tokenA, tokenB) + const pairAccount = PAIR_ADDRESSES[pairKey]?.account + if (pairAccount && api) { + acc[0].push(tokenA) + acc[1].push(tokenB) + if (isNativeCurrency(tokenA)) + acc[2].push([api.query.system.account, pairAccount]) + else + acc[2].push([api.query.tokens.accounts, [pairAccount, addressToNodeCurrency(tokenA.address)]]) + + if (isNativeCurrency(tokenB)) + acc[2].push([api.query.system.account, pairAccount]) + else + acc[2].push([api.query.tokens.accounts, [pairAccount, addressToNodeCurrency(tokenB.address)]]) + } + return acc + }, + [[], [], []], + ), + [api, tokensA, tokensB], + ) + + const reserves = useCallMulti<(OrmlTokensAccountData | FrameSystemAccountInfo)[]>({ + chainId, + calls: reservesCalls, + options: { defaultValue: [], enabled: enabled && !!api }, + }) + + return useMemo(() => { + if (!reservesCalls.length) + return { isLoading: true, isError: false, data: [[PairState.NOT_EXISTS, null]] } + if (!reserves.length || reserves.length !== validTokensA.length * 2) { + return { + isLoading: true, + isError: false, + data: validTokensA.map(() => [PairState.LOADING, null]), + } + } + + return { + isLoading: Boolean(reserves.length), + isError: false, + data: validTokensA.map((tokenA, i) => { + const tokenB = validTokensB[i] + if (!tokenA || !tokenB || tokenA.equals(tokenB)) + return [PairState.INVALID, null] + + const pairKey = uniqePairKey(tokenA, tokenB) + const reserve0 = reserves[i * 2] + const reserve1 = reserves[i * 2 + 1] + const pairAddress = PAIR_ADDRESSES[pairKey]?.address + if (!reserve0 || !reserve1 || reserve0.isEmpty || reserve1.isEmpty || !pairAddress) + return [PairState.NOT_EXISTS, null] + + return [ + PairState.EXISTS, + new Pair( + Amount.fromRawAmount( + tokenA, + ((reserve0 as FrameSystemAccountInfo).data || reserve0).free.toString(), + ), + Amount.fromRawAmount( + tokenB, + ((reserve1 as FrameSystemAccountInfo).data || reserve1).free.toString(), + ), + pairAddress, + ), + ] + }), + } + }, [reserves, reservesCalls.length, validTokensA, validTokensB]) +} + +interface UsePairReturn { + isLoading: boolean + isError: boolean + data: [PairState, Pair | null] +} + +export function usePair( + chainId: number, + tokenA?: Currency, + tokenB?: Currency, + enabled?: boolean, +): UsePairReturn { + const inputs: [[Currency | undefined, Currency | undefined]] = useMemo(() => [[tokenA, tokenB]], [tokenA, tokenB]) + const { data, isLoading, isError } = usePairs(chainId, inputs, enabled) + + return useMemo( + () => ({ + isLoading, + isError, + data: data?.[0], + }), + [data, isError, isLoading], + ) +} diff --git a/packages/parachains-impl/dolphin/hooks/useRemoveLiquidityStandardReview.ts b/packages/parachains-impl/dolphin/hooks/useRemoveLiquidityStandardReview.ts new file mode 100644 index 000000000..71109802d --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useRemoveLiquidityStandardReview.ts @@ -0,0 +1,109 @@ +import type { Pair } from '@zenlink-interface/amm' +import type { ParachainId } from '@zenlink-interface/chain' +import type { Amount, Type } from '@zenlink-interface/currency' +import { addressToZenlinkAssetId } from '@zenlink-interface/format' +import type { Percent } from '@zenlink-interface/math' +import type { TransactionRequest } from '@zenlink-interface/polkadot' +import { useAccount, useApi, useBlockNumber, useSendTransaction } from '@zenlink-interface/polkadot' +import { useNotifications } from '@zenlink-interface/shared' +import type { Dispatch, SetStateAction } from 'react' +import { useCallback, useMemo } from 'react' + +interface UseRemoveLiquidityStandardReviewParams { + chainId: ParachainId + token0: Type + token1: Type + minAmount0: Amount | undefined + minAmount1: Amount | undefined + pool: Pair | null + percentToRemove: Percent + balance: Amount | undefined +} + +type UseRemoveLiquidityStandardReview = (params: UseRemoveLiquidityStandardReviewParams) => { + isWritePending: boolean + sendTransaction: (() => void) | undefined + routerAddress: string | undefined +} + +export const useRemoveLiquidityStandardReview: UseRemoveLiquidityStandardReview = ({ + chainId, + token0, + token1, + percentToRemove, + minAmount0, + minAmount1, + balance, + pool, +}) => { + const api = useApi(chainId) + const { account } = useAccount() + const [, { createPendingNotification }] = useNotifications(account?.address) + const blockNumber = useBlockNumber(chainId) + + const prepare = useCallback( + (setRequest: Dispatch>) => { + if ( + !chainId + || !api + || !pool + || !token0 + || !token1 + || !account + || !balance + || !minAmount0 + || !minAmount1 + ) + return + + // Deadline is currently default to next 20 blocks + try { + const deadline = blockNumber && blockNumber.toNumber() + 20 + const args = [ + addressToZenlinkAssetId(token0.wrapped.address), + addressToZenlinkAssetId(token1.wrapped.address), + balance.multiply(percentToRemove).quotient.toString(), + minAmount0.quotient.toString(), + minAmount1.quotient.toString(), + account.address, + deadline, + ] + const extrinsic = [api.tx.zenlinkProtocol.removeLiquidity(...args)] + + const ts = new Date().getTime() + const notification: TransactionRequest['notification'] = { + type: 'burn', + chainId: pool.chainId, + summary: { + pending: `Removing liquidity from the ${token0.symbol}/${token1.symbol} pair`, + completed: `Successfully removed liquidity from the ${token0.symbol}/${token1.symbol} pair`, + failed: 'Something went wrong when removing liquidity', + }, + timestamp: ts, + groupTimestamp: ts, + } + + setRequest({ + extrinsic, + account, + notification, + }) + } + catch (e: unknown) {} + }, + [account, api, balance, blockNumber, chainId, minAmount0, minAmount1, percentToRemove, pool, token0, token1], + ) + + const { sendTransaction, isLoading: isWritePending } = useSendTransaction({ + chainId, + createPendingNotification, + prepare, + onSuccess: () => {}, + }) + + return useMemo(() => ({ + isWritePending, + sendTransaction, + routerAddress: undefined, + }), [isWritePending, sendTransaction]) +} diff --git a/packages/parachains-impl/dolphin/hooks/useStablePools.ts b/packages/parachains-impl/dolphin/hooks/useStablePools.ts new file mode 100644 index 000000000..b08662969 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useStablePools.ts @@ -0,0 +1,24 @@ +import type { StableSwap } from '@zenlink-interface/amm' +import { useMemo } from 'react' + +export enum StablePoolState { + LOADING, + NOT_EXISTS, + EXISTS, + INVALID, +} + +// TODO: Bifrost Stable Pools +export function useGetStablePools(): { + isLoading: boolean + isError: boolean + data: [StablePoolState, StableSwap | null][] +} { + return useMemo(() => { + return { + isLoading: false, + isError: false, + data: [], + } + }, []) +} diff --git a/packages/parachains-impl/dolphin/hooks/useSwapReview.ts b/packages/parachains-impl/dolphin/hooks/useSwapReview.ts new file mode 100644 index 000000000..db96aafb2 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useSwapReview.ts @@ -0,0 +1,110 @@ +import type { Trade } from '@zenlink-interface/amm' +import { Percent } from '@zenlink-interface/math' +import type { TransactionRequest } from '@zenlink-interface/polkadot' +import { useAccount, useApi, useBlockNumber, useSendTransaction } from '@zenlink-interface/polkadot' +import { useNotifications, useSettings } from '@zenlink-interface/shared' +import type { Dispatch, SetStateAction } from 'react' +import { useCallback, useMemo } from 'react' +import { SwapRouter } from '../SwapRouter' + +const SWAP_DEFAULT_SLIPPAGE = new Percent(50, 10_000) // 0.50% + +interface UseSwapReviewParams { + chainId: number | undefined + trade: Trade | undefined + setOpen: Dispatch> + setError: Dispatch> + onSuccess(): void +} + +type UseSwapReview = (params: UseSwapReviewParams) => { + isWritePending: boolean + sendTransaction: (() => Promise) | undefined + routerAddress: string | undefined +} + +export const useSwapReview: UseSwapReview = ({ + chainId, + trade, + setOpen, + setError, + onSuccess, +}) => { + const api = useApi(chainId) + const { account } = useAccount() + const [, { createPendingNotification }] = useNotifications(account?.address) + const blockNumber = useBlockNumber(chainId) + const [{ slippageTolerance }] = useSettings() + + const allowedSlippage = useMemo( + () => (slippageTolerance ? new Percent(slippageTolerance * 100, 10_000) : SWAP_DEFAULT_SLIPPAGE), + [slippageTolerance], + ) + + const prepare = useCallback( + (setRequest: Dispatch>) => { + if (!chainId || !api || !trade || !account) + return + + // Deadline is currently default to next 20 blocks + try { + const deadline = blockNumber && blockNumber.toNumber() + 20 + if (trade && deadline) { + const { extrinsic } = SwapRouter.swapCallParameters( + trade, + { + api, + allowedSlippage, + recipient: account.address, + deadline, + }, + ) + + const ts = new Date().getTime() + const notification: TransactionRequest['notification'] = { + type: 'swap', + chainId, + summary: { + pending: `Swapping ${trade.inputAmount.toSignificant(6)} ${trade.inputAmount.currency.symbol + } for ${trade.outputAmount.toSignificant(6)} ${trade.outputAmount.currency.symbol}`, + completed: `Successfully swapped ${trade.inputAmount.toSignificant(6)} ${trade.inputAmount.currency.symbol + } for ${trade.outputAmount.toSignificant(6)} ${trade.outputAmount.currency.symbol}`, + failed: `Something went wrong when trying to swap ${trade.inputAmount.currency.symbol} for ${trade.outputAmount.currency.symbol}`, + }, + timestamp: ts, + groupTimestamp: ts, + } + + setRequest({ + extrinsic, + account, + notification, + }) + } + } + catch (e: any) { + setError(e?.message) + console.error(e) + } + }, + [account, allowedSlippage, api, blockNumber, chainId, setError, trade], + ) + + const { sendTransaction, isLoading: isWritePending } = useSendTransaction({ + chainId, + createPendingNotification, + prepare, + onSuccess: (status) => { + if (status) { + setOpen(false) + onSuccess() + } + }, + }) + + return useMemo(() => ({ + isWritePending, + sendTransaction, + routerAddress: undefined, + }), [isWritePending, sendTransaction]) +} diff --git a/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts b/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts new file mode 100644 index 000000000..24c27da22 --- /dev/null +++ b/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts @@ -0,0 +1,56 @@ +import type { ApiPromise } from '@polkadot/api' +import type { QueryableStorageMultiArg } from '@polkadot/api/types' +import type { Token } from '@zenlink-interface/currency' +import { Amount } from '@zenlink-interface/currency' +import { useApis } from '@zenlink-interface/polkadot' +import { useEffect, useMemo, useState } from 'react' +import { addressToNodeCurrency, isNativeCurrency } from '../libs' + +export const useMultipleTotalSupply = (tokens?: Token[], enabled = true): Record | undefined> | undefined => { + const apis = useApis() + const [results, setResults] = useState | undefined>>() + + const calls = useMemo( + () => { + const callsMap: Record[]]> = {} + ;(tokens || []).forEach((token) => { + const api = apis[token.chainId] + if (api) { + const [, _tokens, calls] = callsMap[token.chainId] || [api, [], []] + _tokens.push(token) + if (isNativeCurrency(token)) + calls.push(api.query.balances.totalIssuance) + else + calls.push([api.query.tokens.totalIssuance, addressToNodeCurrency(token.address)]) + callsMap[token.chainId] = [api, _tokens, calls] + } + }) + return callsMap + }, + [apis, tokens], + ) + + useEffect(() => { + if (enabled) { + Object.entries(calls).forEach(([, [api, tokens, calls]]) => { + api.queryMulti(calls).then((results) => { + results.forEach((result, i) => { + const token = tokens[i] + setResults(results => ({ + ...results, + [token.address]: result ? Amount.fromRawAmount(token, result.toHex()) : undefined, + })) + }) + }) + }) + } + }, [calls, enabled]) + + return results +} + +export const useTotalSupply = (token?: Token, enabled = true): Amount | undefined => { + const tokens = useMemo(() => (token ? [token] : undefined), [token]) + const resultMap = useMultipleTotalSupply(tokens, enabled) + return useMemo(() => (token ? resultMap?.[token.wrapped.address] : undefined), [resultMap, token]) +} diff --git a/packages/parachains-impl/dolphin/index.ts b/packages/parachains-impl/dolphin/index.ts new file mode 100644 index 000000000..ae3863fd2 --- /dev/null +++ b/packages/parachains-impl/dolphin/index.ts @@ -0,0 +1,5 @@ +export * from './components' +export * from './hooks' +export * from './SwapRouter' +export * from './systems' +export * from './types' diff --git a/packages/parachains-impl/dolphin/libs/constants/address.ts b/packages/parachains-impl/dolphin/libs/constants/address.ts new file mode 100644 index 000000000..ce64674ee --- /dev/null +++ b/packages/parachains-impl/dolphin/libs/constants/address.ts @@ -0,0 +1,69 @@ +import { addressToZenlinkAssetId, isZenlinkAddress } from '@zenlink-interface/format' +import type { PairPrimitivesAssetId } from '../../types' + +export const PAIR_ADDRESSES: Record = { + // BNC-KSM + '2001-0-0-2001-2-516': { + address: '2001-2-2216203126272', + account: 'eCSrvaystgdffuJxPVZUZmUBqiz2nXKWuUWHQBPqvJFeDh1', + }, + // KSM-AUSD + '2001-2-516-2001-2-770': { + address: '2001-2-3307158636032', + account: 'eCSrvaystgdffuJxPVTJc2eQMgp9PnuPh7mMaQ6KbTynFRM', + }, + // KSM-VSKSM + '2001-2-516-2001-2-1028': { + address: '2001-2-4415260198400', + account: 'eCSrvaystgdffuJxPVW4UMxAXMuTpU3jkCJeiqppyfoi6SG', + }, + // BNC-ZLK + '2001-0-0-2001-2-519': { + address: '2001-2-2229088028160', + account: 'eCSrvaystgdffuJxPVU5NQfnXRohvjWF9u8VaeUWRg1mn1y', + }, + // KAR-ZLK + '2001-2-518-2001-2-519': { + address: '2001-2-2229121975808', + account: 'eCSrvaystgdffuJxPVRWqnxeKZJ3dWu8qJYidgLLStXXkiG', + }, + // KSM-RMRK + '2001-2-516-2001-2-521': { + address: '2001-2-2237711779328', + account: 'eCSrvaystgdffuJxPVU9u7Vv2AVjXTAEwbuujLggS6t6HoE', + }, + // VKSM-KSM + '2001-2-260-2001-2-516': { + address: '2001-2-2216220165632', + account: 'eCSrvaystgdffuJxPVYKf8H8UYnHGNRdVGUvj1SWSiatWMq', + }, + // BNC-USDT + '2001-0-0-2001-2-2048': { + address: '2001-2-8796093023744', + account: 'eCSrvaystgdffuJxPVN8LrN9JeAtrYVV1usKGABuUhYdqYw', + }, + // BNC-VBNC + '2001-0-0-2001-2-257': { + address: '2001-2-1103806596608', + account: 'eCSrvaystgdffuJxPVZ7pEK8ZMmZ7Nwg2144eZYgWdx4g6v', + }, + // KSM-KBTC + '2001-2-516-2001-2-2050': { + address: '2001-2-8804716774912', + account: 'eCSrvaystgdffuJxPVPy4UFedBDC5ZVsx7jsR8jPLZkyno1', + }, + // vKSM-USDT + '2001-2-260-2001-2-2048': { + address: '2001-2-8796110063104', + account: 'eCSrvaystgdffuJxPVNFYzcsVNZLG9E8TgSkUG1GcjD519E', + }, +} + +export const pairAddressToAssets = Object.entries(PAIR_ADDRESSES) + .reduce>( + (acc, [assetsAddress, { address }]) => { + const addresses = (assetsAddress.match(/\d+(-\d+)(-\d+)/g) || []).filter(isZenlinkAddress) + const assetsId = addresses.map(addressToZenlinkAssetId) as PairPrimitivesAssetId + acc[address] = assetsId + return acc + }, {}) diff --git a/packages/parachains-impl/dolphin/libs/constants/index.ts b/packages/parachains-impl/dolphin/libs/constants/index.ts new file mode 100644 index 000000000..6f5a55683 --- /dev/null +++ b/packages/parachains-impl/dolphin/libs/constants/index.ts @@ -0,0 +1 @@ +export * from './address' diff --git a/packages/parachains-impl/dolphin/libs/formats/currency.ts b/packages/parachains-impl/dolphin/libs/formats/currency.ts new file mode 100644 index 000000000..d9f5b0c9d --- /dev/null +++ b/packages/parachains-impl/dolphin/libs/formats/currency.ts @@ -0,0 +1,77 @@ +import type { ZenlinkProtocolPrimitivesAssetId } from '@zenlink-interface/format' +import { addressToZenlinkAssetId, zenlinkAssetIdToAddress } from '@zenlink-interface/format' +import type { NodePrimitivesCurrency } from '../../types' +import { pairAddressToAssets } from '../constants' + +export const NodeCurrencyId: Record = { + 0: 'Native', + 1: 'VToken', + 2: 'Token', + 3: 'Stable', + 4: 'VSToken', + 5: 'VSBond', + 6: 'LPToken', + 7: 'ForeignAsset', + 8: 'Token2', + 9: 'VToken2', + 10: 'VSToken2', + 11: 'VSBond2', + 12: 'StableLpToken', +} + +export const NodeTokenSymbol: Record = { + 0: 'ASG', + 1: 'BNC', + 2: 'KUSD', + 3: 'DOT', + 4: 'KSM', + 5: 'ETH', + 6: 'KAR', + 7: 'ZLK', + 8: 'PHA', + 9: 'RMRK', + 10: 'MOVR', +} + +export const TokenType2 = [7, 8, 9, 10, 12] + +function parseAssetU8(assetIndex: number) { + return (assetIndex & 0x0000_0000_0000_FF00) >> 8 +} + +function parseAssetType(assetIndex: number) { + return assetIndex & 0x0000_0000_0000_000FF +} + +export function parseNodePrimitivesCurrency(asset: ZenlinkProtocolPrimitivesAssetId): NodePrimitivesCurrency { + const { assetIndex } = asset + const assetTypeU8 = parseAssetU8(assetIndex) + const nodeCurrencyId = NodeCurrencyId[assetTypeU8] + + if (!nodeCurrencyId) + throw new Error('invalid asset') + + if (TokenType2.includes(assetTypeU8)) + return { [nodeCurrencyId]: parseAssetType(assetIndex) } + + // LPToken + if (assetIndex.toString().length === 13) { + const [asset0, asset1] = pairAddressToAssets[zenlinkAssetIdToAddress(asset)] + const asset0U8 = parseAssetU8(asset0.assetIndex) + const asset1U8 = parseAssetU8(asset1.assetIndex) + return { + [nodeCurrencyId]: [ + NodeTokenSymbol[parseAssetType(asset0.assetIndex)], + asset0U8, + NodeTokenSymbol[parseAssetType(asset1.assetIndex)], + asset1U8, + ], + } + } + + return { [nodeCurrencyId]: NodeTokenSymbol[parseAssetType(assetIndex)] } +} + +export function addressToNodeCurrency(address: string): NodePrimitivesCurrency { + return parseNodePrimitivesCurrency(addressToZenlinkAssetId(address)) +} diff --git a/packages/parachains-impl/dolphin/libs/formats/index.ts b/packages/parachains-impl/dolphin/libs/formats/index.ts new file mode 100644 index 000000000..29b8a4d9c --- /dev/null +++ b/packages/parachains-impl/dolphin/libs/formats/index.ts @@ -0,0 +1 @@ +export * from './currency' diff --git a/packages/parachains-impl/dolphin/libs/index.ts b/packages/parachains-impl/dolphin/libs/index.ts new file mode 100644 index 000000000..9700d09e4 --- /dev/null +++ b/packages/parachains-impl/dolphin/libs/index.ts @@ -0,0 +1,3 @@ +export * from './constants' +export * from './formats' +export * from './utils' diff --git a/packages/parachains-impl/dolphin/libs/utils.ts b/packages/parachains-impl/dolphin/libs/utils.ts new file mode 100644 index 000000000..ca46134a2 --- /dev/null +++ b/packages/parachains-impl/dolphin/libs/utils.ts @@ -0,0 +1,8 @@ +import type { Type } from '@zenlink-interface/currency' +import { addressToZenlinkAssetId } from '@zenlink-interface/format' + +export function isNativeCurrency(currency: Type): boolean { + // BNC + const { assetType, assetIndex } = addressToZenlinkAssetId(currency.wrapped.address) + return assetType === 0 && assetIndex === 0 +} diff --git a/packages/parachains-impl/dolphin/package.json b/packages/parachains-impl/dolphin/package.json new file mode 100644 index 000000000..82a48c387 --- /dev/null +++ b/packages/parachains-impl/dolphin/package.json @@ -0,0 +1,57 @@ +{ + "name": "@zenlink-interface/parachains-dolphin", + "version": "0.0.0", + "private": true, + "description": "Zenlink Parachains Impl for Bifrost", + "author": "zenlinkpro", + "license": "MIT", + "keywords": [ + "zenlink", + "parachains-impl", + "dolphin" + ], + "sideEffects": false, + "main": "./index.ts", + "source": "./index.ts", + "scripts": { + "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist", + "lint": "TIMING=1 eslint . --fix" + }, + "peerDependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0" + }, + "dependencies": { + "@headlessui/react": "^1.7.13", + "@heroicons/react": "^2.0.16", + "@polkadot/api": "^9.14.2", + "@polkadot/types": "^9.14.2", + "@polkadot/types-codec": "^9.14.2", + "@zenlink-interface/amm": "workspace:*", + "@zenlink-interface/chain": "workspace:*", + "@zenlink-interface/currency": "workspace:*", + "@zenlink-interface/format": "workspace:*", + "@zenlink-interface/hooks": "workspace:*", + "@zenlink-interface/math": "workspace:*", + "@zenlink-interface/polkadot": "workspace:*", + "@zenlink-interface/shared": "workspace:*", + "@zenlink-interface/ui": "workspace:*", + "@zenlink-types/bifrost": "1.7.5" + }, + "devDependencies": { + "@types/react": "^18.0.28", + "@types/react-dom": "^18.0.11", + "@zenlink-interface/eslint-config": "workspace:*", + "@zenlink-interface/typescript-config": "workspace:*", + "eslint": "^8.36.0", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "tsup": "^6.6.3", + "typescript": "4.9.5" + }, + "nextBundleAnalysis": { + "budget": 460800, + "budgetPercentIncreaseRed": 20, + "showDetails": true + } +} diff --git a/packages/parachains-impl/dolphin/systems/Approve/Approve.tsx b/packages/parachains-impl/dolphin/systems/Approve/Approve.tsx new file mode 100644 index 000000000..186c958ca --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Approve/Approve.tsx @@ -0,0 +1,33 @@ +import { useIsMounted } from '@zenlink-interface/hooks' +import { classNames } from '@zenlink-interface/ui' +import type { FC, ReactNode } from 'react' +import { useMemo } from 'react' +import { TokenApproveButton } from './TokenApproveButton' + +interface Props { + className?: string + render({ isUnknown, approved }: { approved: boolean | undefined; isUnknown: boolean | undefined }): ReactNode +} + +const Controller: FC = ({ className, render }) => { + const isMounted = useIsMounted() + + const button = useMemo(() => { + return render({ approved: true, isUnknown: false }) + }, [render]) + + if (!isMounted) + return <>{render({ approved: true, isUnknown: true })} + + return ( +
+ {button} +
+ ) +} + +export const Approve: typeof Controller & { + Token: typeof TokenApproveButton +} = Object.assign(Controller, { + Token: TokenApproveButton, +}) diff --git a/packages/parachains-impl/dolphin/systems/Approve/TokenApproveButton.tsx b/packages/parachains-impl/dolphin/systems/Approve/TokenApproveButton.tsx new file mode 100644 index 000000000..46f27f9ab --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Approve/TokenApproveButton.tsx @@ -0,0 +1,5 @@ +import type { FC } from 'react' + +export const TokenApproveButton: FC = () => { + return <> +} diff --git a/packages/parachains-impl/dolphin/systems/Approve/index.ts b/packages/parachains-impl/dolphin/systems/Approve/index.ts new file mode 100644 index 000000000..f2e369979 --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Approve/index.ts @@ -0,0 +1 @@ +export * from './Approve' diff --git a/packages/parachains-impl/dolphin/systems/Checker/Amounts.tsx b/packages/parachains-impl/dolphin/systems/Checker/Amounts.tsx new file mode 100644 index 000000000..abf7aa5a7 --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Checker/Amounts.tsx @@ -0,0 +1,65 @@ +import type { Amount, Type } from '@zenlink-interface/currency' +import { ZERO } from '@zenlink-interface/math' +import { useAccount } from '@zenlink-interface/polkadot' +import { Button } from '@zenlink-interface/ui' +import type { FC } from 'react' +import { useMemo } from 'react' + +import { useBalances } from '../../hooks' +import type { CheckerButton } from './types' + +export interface AmountsProps extends CheckerButton { + chainId: number | undefined + amounts: (Amount | undefined)[] +} + +export const Amounts: FC = ({ + amounts, + chainId, + children, + className, + variant, + fullWidth, + as, + size, +}) => { + const { address } = useAccount() + const amountsAreDefined = useMemo(() => Boolean(amounts.length && amounts.every(el => el?.greaterThan(ZERO))), [amounts]) + const currencies = useMemo(() => amounts.map(amount => amount?.currency), [amounts]) + + const { data: balances } = useBalances({ + currencies, + chainId, + account: address, + }) + + const sufficientBalance = useMemo(() => { + return amounts?.every((amount) => { + if (!amount) + return true + return !balances + ?.[amount.currency.wrapped.address] + ?.lessThan(amount) + }) + }, [amounts, balances]) + + return useMemo(() => { + if (!amountsAreDefined) { + return ( + + ) + } + + if (!sufficientBalance) { + return ( + + ) + } + + return <>{children} + }, [amountsAreDefined, as, children, className, fullWidth, size, sufficientBalance, variant]) +} diff --git a/packages/parachains-impl/dolphin/systems/Checker/Connected.tsx b/packages/parachains-impl/dolphin/systems/Checker/Connected.tsx new file mode 100644 index 000000000..bf1d762c5 --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Checker/Connected.tsx @@ -0,0 +1,21 @@ +import { useIsMounted } from '@zenlink-interface/hooks' +import { useAccount } from '@zenlink-interface/polkadot' +import type { FC } from 'react' + +import { Wallet } from '../../components' +import type { CheckerButton } from './types' + +export const Connected: FC = ({ children, ...rest }) => { + const isMounted = useIsMounted() + const { address } = useAccount() + + if (isMounted && !address) { + return ( + + Connect Wallet + + ) + } + + return <>{children} +} diff --git a/packages/parachains-impl/dolphin/systems/Checker/Network.tsx b/packages/parachains-impl/dolphin/systems/Checker/Network.tsx new file mode 100644 index 000000000..c20e822ff --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Checker/Network.tsx @@ -0,0 +1,27 @@ +import { Chain } from '@zenlink-interface/chain' +import { useSettings } from '@zenlink-interface/shared' +import { Button } from '@zenlink-interface/ui' +import type { FC, ReactElement } from 'react' + +import type { CheckerButton } from './types' + +export interface NetworkProps extends CheckerButton { + chainId: number | undefined +} + +export const Network: FC = ({ chainId, children, ...rest }): ReactElement | null => { + const [{ parachainId }, { updateParachainId }] = useSettings() + + if (!chainId) + return null + + if (parachainId !== chainId) { + return ( + + ) + } + + return <>{children} +} diff --git a/packages/parachains-impl/dolphin/systems/Checker/index.ts b/packages/parachains-impl/dolphin/systems/Checker/index.ts new file mode 100644 index 000000000..e14a8c2ae --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Checker/index.ts @@ -0,0 +1,16 @@ +import type { FC } from 'react' + +import { Amounts } from './Amounts' +import type { AmountsProps } from './Amounts' +import { Connected } from './Connected' +import type { CheckerButton } from './types' +import type { NetworkProps } from './Network' +import { Network } from './Network' + +export interface CheckerProps { + Amounts: FC + Connected: FC + Network: FC +} + +export const Checker: CheckerProps = { Amounts, Connected, Network } diff --git a/packages/parachains-impl/dolphin/systems/Checker/types.ts b/packages/parachains-impl/dolphin/systems/Checker/types.ts new file mode 100644 index 000000000..6ae98455a --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/Checker/types.ts @@ -0,0 +1,6 @@ +import type { ButtonProps } from '@zenlink-interface/ui' +import type { ReactNode } from 'react' + +export interface CheckerButton extends ButtonProps<'button'> { + children: ReactNode +} diff --git a/packages/parachains-impl/dolphin/systems/index.ts b/packages/parachains-impl/dolphin/systems/index.ts new file mode 100644 index 000000000..ae6e6a2fd --- /dev/null +++ b/packages/parachains-impl/dolphin/systems/index.ts @@ -0,0 +1,2 @@ +export * from './Approve' +export * from './Checker' diff --git a/packages/parachains-impl/dolphin/tsconfig.json b/packages/parachains-impl/dolphin/tsconfig.json new file mode 100644 index 000000000..1be48c19d --- /dev/null +++ b/packages/parachains-impl/dolphin/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "@zenlink-interface/typescript-config/react-library.json", + "include": ["."], + "exclude": ["dist", "node_modules"] +} diff --git a/packages/parachains-impl/dolphin/types.ts b/packages/parachains-impl/dolphin/types.ts new file mode 100644 index 000000000..75777edbe --- /dev/null +++ b/packages/parachains-impl/dolphin/types.ts @@ -0,0 +1,7 @@ +import type { ZenlinkProtocolPrimitivesAssetId } from '@zenlink-interface/format' + +export interface NodePrimitivesCurrency { + [currencyId: string]: string | number | [string, number, string, number] +} + +export type PairPrimitivesAssetId = [ZenlinkProtocolPrimitivesAssetId, ZenlinkProtocolPrimitivesAssetId] From a3eba76adad2547f5badd12f413071bce9b2bd0f Mon Sep 17 00:00:00 2001 From: zqhxuyuan Date: Fri, 17 Mar 2023 12:45:34 +0800 Subject: [PATCH 3/6] add apps chain config Signed-off-by: zqhxuyuan --- apps/analytics/config.ts | 1 + apps/pool/config.ts | 1 + apps/referrals/config.ts | 1 + apps/swap/config.ts | 1 + packages/compat/config/chain.ts | 2 ++ packages/currency/src/constants.ts | 8 +++++ pnpm-lock.yaml | 53 ++++++++++++++++++++++++++++++ 7 files changed, 67 insertions(+) diff --git a/apps/analytics/config.ts b/apps/analytics/config.ts index 50efb1953..8b8951a4b 100644 --- a/apps/analytics/config.ts +++ b/apps/analytics/config.ts @@ -5,6 +5,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.MOONRIVER, ParachainId.MOONBEAM, ParachainId.BIFROST_KUSAMA, + ParachainId.DOLPHIN ] export const SUPPORTED_CHAIN_IDS = Array.from( diff --git a/apps/pool/config.ts b/apps/pool/config.ts index 724f815d3..64c140fcc 100644 --- a/apps/pool/config.ts +++ b/apps/pool/config.ts @@ -11,6 +11,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.MOONRIVER, ParachainId.MOONBEAM, ParachainId.BIFROST_KUSAMA, + ParachainId.DOLPHIN, ] export const SUPPORTED_CHAIN_IDS = Array.from( diff --git a/apps/referrals/config.ts b/apps/referrals/config.ts index a231e55cc..9a44b8b75 100644 --- a/apps/referrals/config.ts +++ b/apps/referrals/config.ts @@ -5,6 +5,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.MOONRIVER, ParachainId.MOONBEAM, ParachainId.BIFROST_KUSAMA, + ParachainId.DOLPHIN ] export const REFERRALS_ENABLED_NETWORKS = [ diff --git a/apps/swap/config.ts b/apps/swap/config.ts index b21a70803..eb048398b 100644 --- a/apps/swap/config.ts +++ b/apps/swap/config.ts @@ -5,6 +5,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.MOONRIVER, ParachainId.MOONBEAM, ParachainId.BIFROST_KUSAMA, + ParachainId.DOLPHIN ] export const AGGREGATOR_ENABLED_NETWORKS = [ diff --git a/packages/compat/config/chain.ts b/packages/compat/config/chain.ts index 2c98c4a82..599c6b99f 100644 --- a/packages/compat/config/chain.ts +++ b/packages/compat/config/chain.ts @@ -4,6 +4,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.ASTAR, ParachainId.MOONRIVER, ParachainId.MOONBEAM, + ParachainId.DOLPHIN, ] export const EVM_NETWORKS = [ @@ -14,6 +15,7 @@ export const EVM_NETWORKS = [ export const SUBSTRATE_NETWORKS = [ ParachainId.BIFROST_KUSAMA, + ParachainId.DOLPHIN ] export const SUPPORTED_CHAIN_IDS = Array.from(new Set([...AMM_ENABLED_NETWORKS])) diff --git a/packages/currency/src/constants.ts b/packages/currency/src/constants.ts index fb54603f6..d4e9952aa 100644 --- a/packages/currency/src/constants.ts +++ b/packages/currency/src/constants.ts @@ -7,6 +7,7 @@ export const WNATIVE_ADDRESS: Record = { [ParachainId.MOONBEAM]: '0xAcc15dC74880C9944775448304B263D191c6077F', [ParachainId.ASTAR]: '0xAeaaf0e2c81Af264101B9129C00F4440cCF0F720', [ParachainId.BIFROST_KUSAMA]: '2001-0-0', + [ParachainId.DOLPHIN]: '2084-0-0' } export const WNATIVE: Record = { @@ -38,6 +39,13 @@ export const WNATIVE: Record = { symbol: 'BNC', name: 'Bifrost', }), + [ParachainId.DOLPHIN]: new Token({ + chainId: ParachainId.DOLPHIN, + address: WNATIVE_ADDRESS[ParachainId.DOLPHIN], + decimals: 18, + symbol: 'DOL', + name: 'Dolphin', + }), } export const USDC_ADDRESS = { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ed7e7a62e..01f0f4391 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1024,6 +1024,59 @@ importers: tsup: 6.6.3_typescript@4.9.5 typescript: 4.9.5 + packages/parachains-impl/dolphin: + specifiers: + '@headlessui/react': ^1.7.13 + '@heroicons/react': ^2.0.16 + '@polkadot/api': ^9.14.2 + '@polkadot/types': ^9.14.2 + '@polkadot/types-codec': ^9.14.2 + '@types/react': ^18.0.28 + '@types/react-dom': ^18.0.11 + '@zenlink-interface/amm': workspace:* + '@zenlink-interface/chain': workspace:* + '@zenlink-interface/currency': workspace:* + '@zenlink-interface/eslint-config': workspace:* + '@zenlink-interface/format': workspace:* + '@zenlink-interface/hooks': workspace:* + '@zenlink-interface/math': workspace:* + '@zenlink-interface/polkadot': workspace:* + '@zenlink-interface/shared': workspace:* + '@zenlink-interface/typescript-config': workspace:* + '@zenlink-interface/ui': workspace:* + '@zenlink-types/bifrost': 1.7.5 + eslint: ^8.36.0 + react: ^18.2.0 + react-dom: ^18.2.0 + tsup: ^6.6.3 + typescript: 4.9.5 + dependencies: + '@headlessui/react': 1.7.13_biqbaboplfbrettd7655fr4n2y + '@heroicons/react': 2.0.16_react@18.2.0 + '@polkadot/api': 9.14.2 + '@polkadot/types': 9.14.2 + '@polkadot/types-codec': 9.14.2 + '@zenlink-interface/amm': link:../../amm + '@zenlink-interface/chain': link:../../chain + '@zenlink-interface/currency': link:../../currency + '@zenlink-interface/format': link:../../format + '@zenlink-interface/hooks': link:../../hooks + '@zenlink-interface/math': link:../../math + '@zenlink-interface/polkadot': link:../../polkadot + '@zenlink-interface/shared': link:../../shared + '@zenlink-interface/ui': link:../../ui + '@zenlink-types/bifrost': 1.7.5 + devDependencies: + '@types/react': 18.0.28 + '@types/react-dom': 18.0.11 + '@zenlink-interface/eslint-config': link:../../config/eslint + '@zenlink-interface/typescript-config': link:../../config/typescript + eslint: 8.36.0 + react: 18.2.0 + react-dom: 18.2.0_react@18.2.0 + tsup: 6.6.3_typescript@4.9.5 + typescript: 4.9.5 + packages/polkadot: specifiers: '@polkadot/api': ^9.14.2 From 41a191f4bf5099031cef2de301b37697c05f7446 Mon Sep 17 00:00:00 2001 From: zqhxuyuan Date: Fri, 17 Mar 2023 15:19:25 +0800 Subject: [PATCH 4/6] add dolphin Signed-off-by: zqhxuyuan --- .idea/.gitignore | 8 +++ .idea/codeStyles/Project.xml | 30 ++++++++++ .idea/codeStyles/codeStyleConfig.xml | 5 ++ .idea/inspectionProfiles/Project_Default.xml | 6 ++ .idea/libraries/test_package.xml | 9 +++ .idea/libraries/test_package1.xml | 9 +++ .idea/libraries/test_package2.xml | 9 +++ .idea/libraries/test_package3.xml | 9 +++ .idea/libraries/test_package4.xml | 9 +++ .../libraries/ts_commonjs_default_export.xml | 9 +++ .../libraries/ts_commonjs_default_export1.xml | 9 +++ .../libraries/ts_commonjs_default_export2.xml | 9 +++ .idea/misc.xml | 6 ++ .idea/modules.xml | 8 +++ .idea/vcs.xml | 6 ++ .idea/zenlink-interface.iml | 9 +++ apps/analytics/config.ts | 2 +- apps/referrals/config.ts | 2 +- apps/swap/config.ts | 2 +- packages/compat/config/chain.ts | 2 +- packages/compat/hooks/usePairs.ts | 11 +++- packages/compat/package.json | 1 + packages/config/polkadot/src/index.ts | 15 +++++ packages/currency/src/constants.ts | 2 +- .../parachains-impl/bifrost/hooks/usePairs.ts | 1 + .../parachains-impl/dolphin/hooks/usePairs.ts | 9 ++- .../dolphin/libs/constants/address.ts | 56 +------------------ .../dolphin/libs/formats/currency.ts | 9 ++- .../parachains-impl/dolphin/libs/utils.ts | 2 + packages/polkadot/components/ApiProvider.tsx | 2 + pnpm-lock.yaml | 2 + 31 files changed, 203 insertions(+), 65 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/codeStyles/Project.xml create mode 100644 .idea/codeStyles/codeStyleConfig.xml create mode 100644 .idea/inspectionProfiles/Project_Default.xml create mode 100644 .idea/libraries/test_package.xml create mode 100644 .idea/libraries/test_package1.xml create mode 100644 .idea/libraries/test_package2.xml create mode 100644 .idea/libraries/test_package3.xml create mode 100644 .idea/libraries/test_package4.xml create mode 100644 .idea/libraries/ts_commonjs_default_export.xml create mode 100644 .idea/libraries/ts_commonjs_default_export1.xml create mode 100644 .idea/libraries/ts_commonjs_default_export2.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 .idea/zenlink-interface.iml diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 000000000..13566b81b --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 000000000..732280ac7 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 000000000..79ee123c2 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 000000000..03d9549ea --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/libraries/test_package.xml b/.idea/libraries/test_package.xml new file mode 100644 index 000000000..6439ed1ae --- /dev/null +++ b/.idea/libraries/test_package.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/test_package1.xml b/.idea/libraries/test_package1.xml new file mode 100644 index 000000000..c66b2d197 --- /dev/null +++ b/.idea/libraries/test_package1.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/test_package2.xml b/.idea/libraries/test_package2.xml new file mode 100644 index 000000000..6533ffb36 --- /dev/null +++ b/.idea/libraries/test_package2.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/test_package3.xml b/.idea/libraries/test_package3.xml new file mode 100644 index 000000000..7b2f167c2 --- /dev/null +++ b/.idea/libraries/test_package3.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/test_package4.xml b/.idea/libraries/test_package4.xml new file mode 100644 index 000000000..8b3928771 --- /dev/null +++ b/.idea/libraries/test_package4.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/ts_commonjs_default_export.xml b/.idea/libraries/ts_commonjs_default_export.xml new file mode 100644 index 000000000..bece52d8e --- /dev/null +++ b/.idea/libraries/ts_commonjs_default_export.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/ts_commonjs_default_export1.xml b/.idea/libraries/ts_commonjs_default_export1.xml new file mode 100644 index 000000000..30cca0578 --- /dev/null +++ b/.idea/libraries/ts_commonjs_default_export1.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/libraries/ts_commonjs_default_export2.xml b/.idea/libraries/ts_commonjs_default_export2.xml new file mode 100644 index 000000000..e235b4094 --- /dev/null +++ b/.idea/libraries/ts_commonjs_default_export2.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 000000000..639900d13 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 000000000..970350ff2 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 000000000..35eb1ddfb --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/zenlink-interface.iml b/.idea/zenlink-interface.iml new file mode 100644 index 000000000..d6ebd4805 --- /dev/null +++ b/.idea/zenlink-interface.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/apps/analytics/config.ts b/apps/analytics/config.ts index 8b8951a4b..158bd81e6 100644 --- a/apps/analytics/config.ts +++ b/apps/analytics/config.ts @@ -5,7 +5,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.MOONRIVER, ParachainId.MOONBEAM, ParachainId.BIFROST_KUSAMA, - ParachainId.DOLPHIN + ParachainId.DOLPHIN, ] export const SUPPORTED_CHAIN_IDS = Array.from( diff --git a/apps/referrals/config.ts b/apps/referrals/config.ts index 9a44b8b75..c216a47f4 100644 --- a/apps/referrals/config.ts +++ b/apps/referrals/config.ts @@ -5,7 +5,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.MOONRIVER, ParachainId.MOONBEAM, ParachainId.BIFROST_KUSAMA, - ParachainId.DOLPHIN + ParachainId.DOLPHIN, ] export const REFERRALS_ENABLED_NETWORKS = [ diff --git a/apps/swap/config.ts b/apps/swap/config.ts index eb048398b..0c435a66b 100644 --- a/apps/swap/config.ts +++ b/apps/swap/config.ts @@ -5,7 +5,7 @@ export const AMM_ENABLED_NETWORKS = [ ParachainId.MOONRIVER, ParachainId.MOONBEAM, ParachainId.BIFROST_KUSAMA, - ParachainId.DOLPHIN + ParachainId.DOLPHIN, ] export const AGGREGATOR_ENABLED_NETWORKS = [ diff --git a/packages/compat/config/chain.ts b/packages/compat/config/chain.ts index 599c6b99f..272eb7a4d 100644 --- a/packages/compat/config/chain.ts +++ b/packages/compat/config/chain.ts @@ -15,7 +15,7 @@ export const EVM_NETWORKS = [ export const SUBSTRATE_NETWORKS = [ ParachainId.BIFROST_KUSAMA, - ParachainId.DOLPHIN + ParachainId.DOLPHIN, ] export const SUPPORTED_CHAIN_IDS = Array.from(new Set([...AMM_ENABLED_NETWORKS])) diff --git a/packages/compat/hooks/usePairs.ts b/packages/compat/hooks/usePairs.ts index 576f52c5a..bf50a2340 100644 --- a/packages/compat/hooks/usePairs.ts +++ b/packages/compat/hooks/usePairs.ts @@ -2,6 +2,7 @@ import type { Pair } from '@zenlink-interface/amm' import type { Currency } from '@zenlink-interface/currency' import { usePairs as useWagmiPairs } from '@zenlink-interface/wagmi' import { usePairs as useBifrostPairs } from '@zenlink-interface/parachains-bifrost' +import { usePairs as useDolphinPairs } from '@zenlink-interface/parachains-dolphin' import { useMemo } from 'react' import { isEvmNetwork, isSubstrateNetwork } from '../config' @@ -28,7 +29,11 @@ export function usePairs( }) const bifrostPairs = useBifrostPairs(chainId, currencies, Boolean(chainId && isSubstrateNetwork(chainId))) - + const dolphinPairs = useDolphinPairs(chainId, currencies, Boolean(chainId && isSubstrateNetwork(chainId))) + // if (currencies.length > 0) { + // console.log('chain and currencies', chainId, JSON.stringify(currencies)) + // console.log('paris:', JSON.stringify(dolphinPairs)) + // } return useMemo(() => { if (!chainId) { return { @@ -39,8 +44,8 @@ export function usePairs( } if (isEvmNetwork(chainId)) return wagmiPairs - return bifrostPairs - }, [bifrostPairs, chainId, wagmiPairs]) + return dolphinPairs + }, [dolphinPairs, chainId, wagmiPairs]) } interface UsePairReturn { diff --git a/packages/compat/package.json b/packages/compat/package.json index a1390e347..435a11c04 100644 --- a/packages/compat/package.json +++ b/packages/compat/package.json @@ -35,6 +35,7 @@ "@zenlink-interface/hooks": "workspace:*", "@zenlink-interface/math": "workspace:*", "@zenlink-interface/parachains-bifrost": "workspace:*", + "@zenlink-interface/parachains-dolphin": "workspace:*", "@zenlink-interface/polkadot": "workspace:*", "@zenlink-interface/redux-localstorage": "workspace:*", "@zenlink-interface/router-config": "workspace:*", diff --git a/packages/config/polkadot/src/index.ts b/packages/config/polkadot/src/index.ts index cca2aaed4..df8259edc 100644 --- a/packages/config/polkadot/src/index.ts +++ b/packages/config/polkadot/src/index.ts @@ -47,4 +47,19 @@ export const parachains: ParaChain[] = [ typesBundle: bifrostTypesBundle, }, }, + { + id: ParachainId.DOLPHIN, + name: 'Dolphin', + network: 'dolphin', + nativeCurrency: { name: 'Dolphin', symbol: 'DOL', decimals: 18 }, + endpoints: [ + 'ws://127.0.0.1:9944', + ], + blockExplorers: { + default: { + name: 'subscan', + url: 'https://dolphin.subscan.io', + }, + }, + }, ] diff --git a/packages/currency/src/constants.ts b/packages/currency/src/constants.ts index d4e9952aa..07073686a 100644 --- a/packages/currency/src/constants.ts +++ b/packages/currency/src/constants.ts @@ -7,7 +7,7 @@ export const WNATIVE_ADDRESS: Record = { [ParachainId.MOONBEAM]: '0xAcc15dC74880C9944775448304B263D191c6077F', [ParachainId.ASTAR]: '0xAeaaf0e2c81Af264101B9129C00F4440cCF0F720', [ParachainId.BIFROST_KUSAMA]: '2001-0-0', - [ParachainId.DOLPHIN]: '2084-0-0' + [ParachainId.DOLPHIN]: '2084-0-1' } export const WNATIVE: Record = { diff --git a/packages/parachains-impl/bifrost/hooks/usePairs.ts b/packages/parachains-impl/bifrost/hooks/usePairs.ts index 992861fdc..9bf1ed79e 100644 --- a/packages/parachains-impl/bifrost/hooks/usePairs.ts +++ b/packages/parachains-impl/bifrost/hooks/usePairs.ts @@ -80,6 +80,7 @@ export function usePairs( const tokenB = tokensB[i] const pairKey = uniqePairKey(tokenA, tokenB) const pairAccount = PAIR_ADDRESSES[pairKey]?.account + console.log('usePair tokens:', tokenA, tokenB, pairKey) if (pairAccount && api) { acc[0].push(tokenA) acc[1].push(tokenB) diff --git a/packages/parachains-impl/dolphin/hooks/usePairs.ts b/packages/parachains-impl/dolphin/hooks/usePairs.ts index 8afdf2de5..12a13e706 100644 --- a/packages/parachains-impl/dolphin/hooks/usePairs.ts +++ b/packages/parachains-impl/dolphin/hooks/usePairs.ts @@ -80,18 +80,23 @@ export function usePairs( const tokenB = tokensB[i] const pairKey = uniqePairKey(tokenA, tokenB) const pairAccount = PAIR_ADDRESSES[pairKey]?.account + // console.log('tokenA:' + JSON.stringify(tokenA)) + // console.log('tokenB:' + JSON.stringify(tokenB)) + console.log('use Pairs:' + pairKey + ',' + pairAccount) + console.log('api:' + api?.isReady) if (pairAccount && api) { acc[0].push(tokenA) acc[1].push(tokenB) if (isNativeCurrency(tokenA)) acc[2].push([api.query.system.account, pairAccount]) else - acc[2].push([api.query.tokens.accounts, [pairAccount, addressToNodeCurrency(tokenA.address)]]) + // acc[2].push([api.query.tokens.accounts, [pairAccount, addressToNodeCurrency(tokenA.address)]]) + acc[2].push([api.query.assets.account, [pairAccount, addressToNodeCurrency(tokenA.address)]]) if (isNativeCurrency(tokenB)) acc[2].push([api.query.system.account, pairAccount]) else - acc[2].push([api.query.tokens.accounts, [pairAccount, addressToNodeCurrency(tokenB.address)]]) + acc[2].push([api.query.assets.account, [pairAccount, addressToNodeCurrency(tokenB.address)]]) } return acc }, diff --git a/packages/parachains-impl/dolphin/libs/constants/address.ts b/packages/parachains-impl/dolphin/libs/constants/address.ts index ce64674ee..e3290de1a 100644 --- a/packages/parachains-impl/dolphin/libs/constants/address.ts +++ b/packages/parachains-impl/dolphin/libs/constants/address.ts @@ -3,59 +3,9 @@ import type { PairPrimitivesAssetId } from '../../types' export const PAIR_ADDRESSES: Record = { // BNC-KSM - '2001-0-0-2001-2-516': { - address: '2001-2-2216203126272', - account: 'eCSrvaystgdffuJxPVZUZmUBqiz2nXKWuUWHQBPqvJFeDh1', - }, - // KSM-AUSD - '2001-2-516-2001-2-770': { - address: '2001-2-3307158636032', - account: 'eCSrvaystgdffuJxPVTJc2eQMgp9PnuPh7mMaQ6KbTynFRM', - }, - // KSM-VSKSM - '2001-2-516-2001-2-1028': { - address: '2001-2-4415260198400', - account: 'eCSrvaystgdffuJxPVW4UMxAXMuTpU3jkCJeiqppyfoi6SG', - }, - // BNC-ZLK - '2001-0-0-2001-2-519': { - address: '2001-2-2229088028160', - account: 'eCSrvaystgdffuJxPVU5NQfnXRohvjWF9u8VaeUWRg1mn1y', - }, - // KAR-ZLK - '2001-2-518-2001-2-519': { - address: '2001-2-2229121975808', - account: 'eCSrvaystgdffuJxPVRWqnxeKZJ3dWu8qJYidgLLStXXkiG', - }, - // KSM-RMRK - '2001-2-516-2001-2-521': { - address: '2001-2-2237711779328', - account: 'eCSrvaystgdffuJxPVU9u7Vv2AVjXTAEwbuujLggS6t6HoE', - }, - // VKSM-KSM - '2001-2-260-2001-2-516': { - address: '2001-2-2216220165632', - account: 'eCSrvaystgdffuJxPVYKf8H8UYnHGNRdVGUvj1SWSiatWMq', - }, - // BNC-USDT - '2001-0-0-2001-2-2048': { - address: '2001-2-8796093023744', - account: 'eCSrvaystgdffuJxPVN8LrN9JeAtrYVV1usKGABuUhYdqYw', - }, - // BNC-VBNC - '2001-0-0-2001-2-257': { - address: '2001-2-1103806596608', - account: 'eCSrvaystgdffuJxPVZ7pEK8ZMmZ7Nwg2144eZYgWdx4g6v', - }, - // KSM-KBTC - '2001-2-516-2001-2-2050': { - address: '2001-2-8804716774912', - account: 'eCSrvaystgdffuJxPVPy4UFedBDC5ZVsx7jsR8jPLZkyno1', - }, - // vKSM-USDT - '2001-2-260-2001-2-2048': { - address: '2001-2-8796110063104', - account: 'eCSrvaystgdffuJxPVNFYzcsVNZLG9E8TgSkUG1GcjD519E', + '2084-2-8-2084-2-9': { + address: '2084-2-10', + account: 'dmwQify2twJu1L58gRy6uSeGCJQkUm8T2Rt9qSigbVneMTXHw', }, } diff --git a/packages/parachains-impl/dolphin/libs/formats/currency.ts b/packages/parachains-impl/dolphin/libs/formats/currency.ts index d9f5b0c9d..8fb46cf2c 100644 --- a/packages/parachains-impl/dolphin/libs/formats/currency.ts +++ b/packages/parachains-impl/dolphin/libs/formats/currency.ts @@ -48,8 +48,10 @@ export function parseNodePrimitivesCurrency(asset: ZenlinkProtocolPrimitivesAsse const assetTypeU8 = parseAssetU8(assetIndex) const nodeCurrencyId = NodeCurrencyId[assetTypeU8] - if (!nodeCurrencyId) + if (!nodeCurrencyId) { + console.log('invalid asset') throw new Error('invalid asset') + } if (TokenType2.includes(assetTypeU8)) return { [nodeCurrencyId]: parseAssetType(assetIndex) } @@ -73,5 +75,8 @@ export function parseNodePrimitivesCurrency(asset: ZenlinkProtocolPrimitivesAsse } export function addressToNodeCurrency(address: string): NodePrimitivesCurrency { - return parseNodePrimitivesCurrency(addressToZenlinkAssetId(address)) + console.log('address:' + address) + const zenlinkAsset = addressToZenlinkAssetId(address) + console.log('zenlink chain:' + zenlinkAsset.chainId + ',type:' + zenlinkAsset.assetType + ',index:' + zenlinkAsset.assetIndex) + return parseNodePrimitivesCurrency(zenlinkAsset) } diff --git a/packages/parachains-impl/dolphin/libs/utils.ts b/packages/parachains-impl/dolphin/libs/utils.ts index ca46134a2..e851bf3a2 100644 --- a/packages/parachains-impl/dolphin/libs/utils.ts +++ b/packages/parachains-impl/dolphin/libs/utils.ts @@ -3,6 +3,8 @@ import { addressToZenlinkAssetId } from '@zenlink-interface/format' export function isNativeCurrency(currency: Type): boolean { // BNC + console.log('address:' + currency.wrapped.address) const { assetType, assetIndex } = addressToZenlinkAssetId(currency.wrapped.address) + console.log('type:' + assetType + ',index:' + assetIndex) return assetType === 0 && assetIndex === 0 } diff --git a/packages/polkadot/components/ApiProvider.tsx b/packages/polkadot/components/ApiProvider.tsx index 17c79b3a3..602570278 100644 --- a/packages/polkadot/components/ApiProvider.tsx +++ b/packages/polkadot/components/ApiProvider.tsx @@ -143,6 +143,7 @@ async function createApi( const types = apiOptions.types || {} const typesBundle = apiOptions.typesBundle || {} try { + console.log('create api:' + endpoints) const provider = new WsProvider(endpoints) const api = new ApiPromise({ @@ -215,6 +216,7 @@ export const PolkadotApiProvider = ({ chains, children, store }: Props) => { api.on('error', onError) api.on('ready', () => { + console.log('api is ready:' + chain.endpoints) const injectedPromise = web3Enable('zenlink-interface') injectedPromise diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 01f0f4391..bfe7685c6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -643,6 +643,7 @@ importers: '@zenlink-interface/hooks': workspace:* '@zenlink-interface/math': workspace:* '@zenlink-interface/parachains-bifrost': workspace:* + '@zenlink-interface/parachains-dolphin': workspace:* '@zenlink-interface/polkadot': workspace:* '@zenlink-interface/redux-localstorage': workspace:* '@zenlink-interface/router-config': workspace:* @@ -671,6 +672,7 @@ importers: '@zenlink-interface/hooks': link:../hooks '@zenlink-interface/math': link:../math '@zenlink-interface/parachains-bifrost': link:../parachains-impl/bifrost + '@zenlink-interface/parachains-dolphin': link:../parachains-impl/dolphin '@zenlink-interface/polkadot': link:../polkadot '@zenlink-interface/redux-localstorage': link:../redux/localstorage '@zenlink-interface/router-config': link:../config/router From e020e1d00a09c66cff72ddcd8f89a0c10b7546ec Mon Sep 17 00:00:00 2001 From: zqhxuyuan Date: Fri, 17 Mar 2023 22:40:09 +0800 Subject: [PATCH 5/6] tokens to assets Signed-off-by: zqhxuyuan --- .../compat/hooks/useBalance/useBalance.ts | 8 ++++- packages/config/polkadot/package.json | 2 +- .../dolphin/hooks/useBalance/useBalance.ts | 11 ++++--- .../parachains-impl/dolphin/hooks/usePairs.ts | 16 ++++------ .../dolphin/hooks/useTotalSupply.ts | 8 +++-- .../dolphin/libs/constants/address.ts | 2 +- .../dolphin/libs/formats/currency.ts | 32 +++++++++---------- .../parachains-impl/dolphin/libs/utils.ts | 6 ++-- packages/polkadot/components/ApiProvider.tsx | 2 -- packages/shared/hooks/usePrices.ts | 2 +- 10 files changed, 46 insertions(+), 43 deletions(-) diff --git a/packages/compat/hooks/useBalance/useBalance.ts b/packages/compat/hooks/useBalance/useBalance.ts index adce6f835..2791d141d 100644 --- a/packages/compat/hooks/useBalance/useBalance.ts +++ b/packages/compat/hooks/useBalance/useBalance.ts @@ -3,6 +3,7 @@ import type { Address } from 'wagmi' import { AddressZero } from '@ethersproject/constants' import { useBalances as useWagmiBalances } from '@zenlink-interface/wagmi' import { useBalances as useBifrostBalances } from '@zenlink-interface/parachains-bifrost' +import { useBalances as useDolphinBalances } from '@zenlink-interface/parachains-dolphin' import type { Amount, Type } from '@zenlink-interface/currency' import { useMemo } from 'react' import { isEvmNetwork } from '../../config' @@ -37,7 +38,12 @@ export const useBalances: UseBalances = ({ watch, }) - const bifrostBalances = useBifrostBalances({ + // const bifrostBalances = useBifrostBalances({ + // chainId, + // account, + // currencies, + // }) + const bifrostBalances = useDolphinBalances({ chainId, account, currencies, diff --git a/packages/config/polkadot/package.json b/packages/config/polkadot/package.json index 4f294e2cb..16b035bc5 100644 --- a/packages/config/polkadot/package.json +++ b/packages/config/polkadot/package.json @@ -22,7 +22,7 @@ "clean": "rm -rf .turbo && rm -rf node_modules && rm -rf dist" }, "dependencies": { - "@polkadot/api": "^9.4.2", + "@polkadot/api": "^9.14.2", "@zenlink-interface/chain": "workspace:*", "@zenlink-types/bifrost": "1.7.5" }, diff --git a/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts b/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts index cf6cdb762..756fe5fcc 100644 --- a/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts +++ b/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts @@ -1,4 +1,5 @@ import type { QueryableStorageEntry } from '@polkadot/api/types' +import type { PalletAssetsAssetAccount } from '@polkadot/types/lookup' import type { ParachainId } from '@zenlink-interface/chain' import type { Token, Type } from '@zenlink-interface/currency' import { Amount } from '@zenlink-interface/currency' @@ -7,7 +8,7 @@ import { JSBI } from '@zenlink-interface/math' import { useAccount, useApi, useCallMulti, useNativeBalancesAll } from '@zenlink-interface/polkadot' import type { OrmlAccountData } from '@zenlink-types/bifrost/interfaces' import { useMemo } from 'react' -import { addressToNodeCurrency, isNativeCurrency } from '../../libs' +import { addressToCurrencyId, addressToNodeCurrency, isNativeCurrency } from '../../libs' import type { NodePrimitivesCurrency } from '../../types' import type { BalanceMap } from './types' @@ -43,12 +44,12 @@ export const useBalances: UseBalances = ({ [chainId, currencies], ) - const balances = useCallMulti({ + const balances = useCallMulti({ chainId, calls: (api && isAccount(account)) ? validatedTokens - .map(currency => [api.query.tokens.accounts, [account, addressToNodeCurrency(currency.wrapped.address)]]) - .filter((call): call is [QueryableStorageEntry<'promise'>, [string, NodePrimitivesCurrency]] => Boolean(call[0])) + .map(currency => [api.query.assets.account, [addressToCurrencyId(currency.wrapped.address), account]]) + // .filter((call): call is [QueryableStorageEntry<'promise'>, [number, string]] => Boolean(call[0])) : [], options: { enabled: enabled && Boolean(api && isAccount(account)) }, }) @@ -58,7 +59,7 @@ export const useBalances: UseBalances = ({ if (balances.length !== validatedTokens.length) return result for (let i = 0; i < validatedTokens.length; i++) { - const value = balances[i]?.free.toString() + const value = balances[i]?.balance const amount = value ? JSBI.BigInt(value.toString()) : undefined if (!result[validatedTokens[i].address]) diff --git a/packages/parachains-impl/dolphin/hooks/usePairs.ts b/packages/parachains-impl/dolphin/hooks/usePairs.ts index 12a13e706..51aa056f8 100644 --- a/packages/parachains-impl/dolphin/hooks/usePairs.ts +++ b/packages/parachains-impl/dolphin/hooks/usePairs.ts @@ -6,10 +6,10 @@ import { Amount } from '@zenlink-interface/currency' import { addressToZenlinkAssetId } from '@zenlink-interface/format' import { useApi, useCallMulti } from '@zenlink-interface/polkadot' import type { AccountId, OrmlTokensAccountData, ZenlinkAssetBalance } from '@zenlink-types/bifrost/interfaces' -import type { FrameSystemAccountInfo } from '@polkadot/types/lookup' +import type { FrameSystemAccountInfo, PalletAssetsAssetAccount } from '@polkadot/types/lookup' import { useMemo } from 'react' import { ParachainId } from '@zenlink-interface/chain' -import { PAIR_ADDRESSES, addressToNodeCurrency, isNativeCurrency } from '../libs' +import { PAIR_ADDRESSES, addressToCurrencyId, addressToNodeCurrency, isNativeCurrency } from '../libs' import type { PairPrimitivesAssetId } from '../types' export enum PairState { @@ -83,20 +83,18 @@ export function usePairs( // console.log('tokenA:' + JSON.stringify(tokenA)) // console.log('tokenB:' + JSON.stringify(tokenB)) console.log('use Pairs:' + pairKey + ',' + pairAccount) - console.log('api:' + api?.isReady) if (pairAccount && api) { acc[0].push(tokenA) acc[1].push(tokenB) if (isNativeCurrency(tokenA)) acc[2].push([api.query.system.account, pairAccount]) else - // acc[2].push([api.query.tokens.accounts, [pairAccount, addressToNodeCurrency(tokenA.address)]]) - acc[2].push([api.query.assets.account, [pairAccount, addressToNodeCurrency(tokenA.address)]]) + acc[2].push([api.query.assets.account, [addressToCurrencyId(tokenA.address), pairAccount]]) if (isNativeCurrency(tokenB)) acc[2].push([api.query.system.account, pairAccount]) else - acc[2].push([api.query.assets.account, [pairAccount, addressToNodeCurrency(tokenB.address)]]) + acc[2].push([api.query.assets.account, [addressToCurrencyId(tokenB.address), pairAccount]]) } return acc }, @@ -105,7 +103,7 @@ export function usePairs( [api, tokensA, tokensB], ) - const reserves = useCallMulti<(OrmlTokensAccountData | FrameSystemAccountInfo)[]>({ + const reserves = useCallMulti<(PalletAssetsAssetAccount | FrameSystemAccountInfo)[]>({ chainId, calls: reservesCalls, options: { defaultValue: [], enabled: enabled && !!api }, @@ -142,11 +140,11 @@ export function usePairs( new Pair( Amount.fromRawAmount( tokenA, - ((reserve0 as FrameSystemAccountInfo).data || reserve0).free.toString(), + (reserve0 as FrameSystemAccountInfo).data.free.toString() || (reserve0 as PalletAssetsAssetAccount).balance.toString(), ), Amount.fromRawAmount( tokenB, - ((reserve1 as FrameSystemAccountInfo).data || reserve1).free.toString(), + (reserve1 as FrameSystemAccountInfo).data.free.toString() || (reserve1 as PalletAssetsAssetAccount).balance.toString(), ), pairAddress, ), diff --git a/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts b/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts index 24c27da22..8fbceedec 100644 --- a/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts +++ b/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts @@ -1,10 +1,11 @@ import type { ApiPromise } from '@polkadot/api' import type { QueryableStorageMultiArg } from '@polkadot/api/types' +import type { PalletAssetsAssetDetails } from '@polkadot/types/lookup' import type { Token } from '@zenlink-interface/currency' import { Amount } from '@zenlink-interface/currency' import { useApis } from '@zenlink-interface/polkadot' import { useEffect, useMemo, useState } from 'react' -import { addressToNodeCurrency, isNativeCurrency } from '../libs' +import { addressToCurrencyId, addressToNodeCurrency, isNativeCurrency } from '../libs' export const useMultipleTotalSupply = (tokens?: Token[], enabled = true): Record | undefined> | undefined => { const apis = useApis() @@ -21,7 +22,7 @@ export const useMultipleTotalSupply = (tokens?: Token[], enabled = true): Record if (isNativeCurrency(token)) calls.push(api.query.balances.totalIssuance) else - calls.push([api.query.tokens.totalIssuance, addressToNodeCurrency(token.address)]) + calls.push([api.query.assets.asset, addressToCurrencyId(token.address)]) callsMap[token.chainId] = [api, _tokens, calls] } }) @@ -36,9 +37,10 @@ export const useMultipleTotalSupply = (tokens?: Token[], enabled = true): Record api.queryMulti(calls).then((results) => { results.forEach((result, i) => { const token = tokens[i] + const supply = (result as PalletAssetsAssetDetails).supply || result setResults(results => ({ ...results, - [token.address]: result ? Amount.fromRawAmount(token, result.toHex()) : undefined, + [token.address]: supply ? Amount.fromRawAmount(token, supply.toHex()) : undefined, })) }) }) diff --git a/packages/parachains-impl/dolphin/libs/constants/address.ts b/packages/parachains-impl/dolphin/libs/constants/address.ts index e3290de1a..810b33248 100644 --- a/packages/parachains-impl/dolphin/libs/constants/address.ts +++ b/packages/parachains-impl/dolphin/libs/constants/address.ts @@ -2,11 +2,11 @@ import { addressToZenlinkAssetId, isZenlinkAddress } from '@zenlink-interface/fo import type { PairPrimitivesAssetId } from '../../types' export const PAIR_ADDRESSES: Record = { - // BNC-KSM '2084-2-8-2084-2-9': { address: '2084-2-10', account: 'dmwQify2twJu1L58gRy6uSeGCJQkUm8T2Rt9qSigbVneMTXHw', }, + } export const pairAddressToAssets = Object.entries(PAIR_ADDRESSES) diff --git a/packages/parachains-impl/dolphin/libs/formats/currency.ts b/packages/parachains-impl/dolphin/libs/formats/currency.ts index 8fb46cf2c..243dd04f1 100644 --- a/packages/parachains-impl/dolphin/libs/formats/currency.ts +++ b/packages/parachains-impl/dolphin/libs/formats/currency.ts @@ -20,17 +20,10 @@ export const NodeCurrencyId: Record = { } export const NodeTokenSymbol: Record = { - 0: 'ASG', - 1: 'BNC', - 2: 'KUSD', - 3: 'DOT', - 4: 'KSM', - 5: 'ETH', - 6: 'KAR', - 7: 'ZLK', - 8: 'PHA', - 9: 'RMRK', - 10: 'MOVR', + 1: 'DOL', + 8: 'DOL8', + 9: 'DOL9', + 10: 'LP10', } export const TokenType2 = [7, 8, 9, 10, 12] @@ -48,10 +41,8 @@ export function parseNodePrimitivesCurrency(asset: ZenlinkProtocolPrimitivesAsse const assetTypeU8 = parseAssetU8(assetIndex) const nodeCurrencyId = NodeCurrencyId[assetTypeU8] - if (!nodeCurrencyId) { - console.log('invalid asset') + if (!nodeCurrencyId) throw new Error('invalid asset') - } if (TokenType2.includes(assetTypeU8)) return { [nodeCurrencyId]: parseAssetType(assetIndex) } @@ -75,8 +66,15 @@ export function parseNodePrimitivesCurrency(asset: ZenlinkProtocolPrimitivesAsse } export function addressToNodeCurrency(address: string): NodePrimitivesCurrency { - console.log('address:' + address) const zenlinkAsset = addressToZenlinkAssetId(address) - console.log('zenlink chain:' + zenlinkAsset.chainId + ',type:' + zenlinkAsset.assetType + ',index:' + zenlinkAsset.assetIndex) - return parseNodePrimitivesCurrency(zenlinkAsset) + // console.log('zenlink chain:' + zenlinkAsset.chainId + ',type:' + zenlinkAsset.assetType + ',index:' + zenlinkAsset.assetIndex) + // return parseNodePrimitivesCurrency(zenlinkAsset) + return { [NodeCurrencyId[zenlinkAsset.assetType]]: NodeTokenSymbol[zenlinkAsset.assetIndex] } +} + +export function addressToCurrencyId(address: string): number { + const zenlinkAsset = addressToZenlinkAssetId(address) + // console.log('zenlink chain:' + zenlinkAsset.chainId + ',type:' + zenlinkAsset.assetType + ',index:' + zenlinkAsset.assetIndex) + // return parseNodePrimitivesCurrency(zenlinkAsset) + return zenlinkAsset.assetIndex } diff --git a/packages/parachains-impl/dolphin/libs/utils.ts b/packages/parachains-impl/dolphin/libs/utils.ts index e851bf3a2..a3212145d 100644 --- a/packages/parachains-impl/dolphin/libs/utils.ts +++ b/packages/parachains-impl/dolphin/libs/utils.ts @@ -3,8 +3,8 @@ import { addressToZenlinkAssetId } from '@zenlink-interface/format' export function isNativeCurrency(currency: Type): boolean { // BNC - console.log('address:' + currency.wrapped.address) + // console.log('address:' + currency.wrapped.address) const { assetType, assetIndex } = addressToZenlinkAssetId(currency.wrapped.address) - console.log('type:' + assetType + ',index:' + assetIndex) - return assetType === 0 && assetIndex === 0 + // console.log('type:' + assetType + ',index:' + assetIndex) + return assetType === 0 && assetIndex === 1 } diff --git a/packages/polkadot/components/ApiProvider.tsx b/packages/polkadot/components/ApiProvider.tsx index 602570278..17c79b3a3 100644 --- a/packages/polkadot/components/ApiProvider.tsx +++ b/packages/polkadot/components/ApiProvider.tsx @@ -143,7 +143,6 @@ async function createApi( const types = apiOptions.types || {} const typesBundle = apiOptions.typesBundle || {} try { - console.log('create api:' + endpoints) const provider = new WsProvider(endpoints) const api = new ApiPromise({ @@ -216,7 +215,6 @@ export const PolkadotApiProvider = ({ chains, children, store }: Props) => { api.on('error', onError) api.on('ready', () => { - console.log('api is ready:' + chain.endpoints) const injectedPromise = web3Enable('zenlink-interface') injectedPromise diff --git a/packages/shared/hooks/usePrices.ts b/packages/shared/hooks/usePrices.ts index bc555d2c8..d41ee42d3 100644 --- a/packages/shared/hooks/usePrices.ts +++ b/packages/shared/hooks/usePrices.ts @@ -17,7 +17,7 @@ export const usePrices = ({ } = useQuery( queryKey, () => fetch(`https://token-price-ruby.vercel.app/v0/${chainId}`).then(response => response.json()), - { staleTime: 20000, enabled: Boolean(chainId) }, + { staleTime: 20000, enabled: false }, ) return useMemo(() => ({ From 06a9e6e1507f311aad6aed8fba0733a5bc89d7c4 Mon Sep 17 00:00:00 2001 From: zqhxuyuan Date: Sun, 19 Mar 2023 12:10:31 +0800 Subject: [PATCH 6/6] local token balance not work Signed-off-by: zqhxuyuan --- .../AggregatorTrade/useAggregatorTrade.ts | 2 +- .../compat/components/Profile/Profile.tsx | 2 +- .../TokenListFilterByQuery.tsx | 2 +- .../TokenSelector/TokenListImportChecker.tsx | 2 +- .../hooks/useAddLiquidityStandardReview.ts | 2 +- .../compat/hooks/useBalance/useBalance.ts | 2 +- packages/compat/hooks/usePairTotalSupply.ts | 2 +- packages/compat/hooks/usePairs.ts | 2 +- .../hooks/useRemoveLiquidityStandardReview.ts | 2 +- packages/compat/hooks/useStablePools.ts | 2 +- packages/compat/hooks/useSwapReview.ts | 2 +- packages/compat/package.json | 3 +- .../systems/Approve/TokenApproveButton.tsx | 2 +- packages/compat/systems/Checker/Amounts.tsx | 2 +- packages/compat/systems/Checker/Connected.tsx | 2 +- packages/compat/systems/Checker/Network.tsx | 2 +- packages/config/polkadot/package.json | 3 +- packages/config/polkadot/src/index.ts | 12 ++++ packages/currency/src/constants.ts | 2 +- .../dolphin/hooks/useBalance/useBalance.ts | 36 ++++++++-- .../parachains-impl/dolphin/hooks/usePairs.ts | 16 ++--- .../dolphin/hooks/useTotalSupply.ts | 2 +- .../dolphin/libs/constants/address.ts | 17 +++-- .../dolphin/libs/formats/currency.ts | 70 +++++++++---------- packages/parachains-impl/dolphin/package.json | 3 +- packages/polkadot/hooks/useCallMulti.ts | 6 +- pnpm-lock.yaml | 30 +++++++- renovate.json | 3 +- 28 files changed, 151 insertions(+), 82 deletions(-) diff --git a/apps/swap/lib/hooks/AggregatorTrade/useAggregatorTrade.ts b/apps/swap/lib/hooks/AggregatorTrade/useAggregatorTrade.ts index 0cc89bc7c..356561b76 100644 --- a/apps/swap/lib/hooks/AggregatorTrade/useAggregatorTrade.ts +++ b/apps/swap/lib/hooks/AggregatorTrade/useAggregatorTrade.ts @@ -66,7 +66,7 @@ function useAggregatorTradeQuery( return tradeValidator.parse(res) }, select, - refetchInterval: 12000, + refetchInterval: 120000, enabled: Boolean(enabled && chainId && fromToken && toToken && amount && gasPrice && fromToken && toToken), }, ) diff --git a/packages/compat/components/Profile/Profile.tsx b/packages/compat/components/Profile/Profile.tsx index 4c97cf33f..e65f6bd42 100644 --- a/packages/compat/components/Profile/Profile.tsx +++ b/packages/compat/components/Profile/Profile.tsx @@ -1,7 +1,7 @@ import type { ParachainId } from '@zenlink-interface/chain' import type { FC } from 'react' import { Profile as WagmiProfile } from '@zenlink-interface/wagmi' -import { Profile as BifrostProfile } from '@zenlink-interface/parachains-bifrost' +import { Profile as BifrostProfile } from '@zenlink-interface/parachains-dolphin' import { useSettings } from '@zenlink-interface/shared' import { isEvmNetwork, isSubstrateNetwork } from '../../config' diff --git a/packages/compat/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx b/packages/compat/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx index 1c9005457..0d2bd0f35 100644 --- a/packages/compat/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx +++ b/packages/compat/components/TokenListFilterByQuery/TokenListFilterByQuery.tsx @@ -3,7 +3,7 @@ import type { Token, Type } from '@zenlink-interface/currency' import type { Fraction } from '@zenlink-interface/math' import type { FC, RefObject } from 'react' import { TokenListFilterByQuery as WagmiTokenListFilterByQuery } from '@zenlink-interface/wagmi' -import { TokenListFilterByQuery as BifrostTokenListFilterByQuery } from '@zenlink-interface/parachains-bifrost' +import { TokenListFilterByQuery as BifrostTokenListFilterByQuery } from '@zenlink-interface/parachains-dolphin' import { isEvmNetwork } from '../../config' import type { BalanceMap } from '../../hooks/useBalance/types' diff --git a/packages/compat/components/TokenSelector/TokenListImportChecker.tsx b/packages/compat/components/TokenSelector/TokenListImportChecker.tsx index dabb90447..28e4f496d 100644 --- a/packages/compat/components/TokenSelector/TokenListImportChecker.tsx +++ b/packages/compat/components/TokenSelector/TokenListImportChecker.tsx @@ -2,7 +2,7 @@ import type { ParachainId } from '@zenlink-interface/chain' import type { Token } from '@zenlink-interface/currency' import type { FC, ReactNode } from 'react' import { TokenListImportChecker as WagmiTokenListImportChecker } from '@zenlink-interface/wagmi' -import { TokenListImportChecker as BifrostTokenListImportChecker } from '@zenlink-interface/parachains-bifrost' +import { TokenListImportChecker as BifrostTokenListImportChecker } from '@zenlink-interface/parachains-dolphin' import { isEvmNetwork } from '../../config' interface TokenListImportCheckerProps { diff --git a/packages/compat/hooks/useAddLiquidityStandardReview.ts b/packages/compat/hooks/useAddLiquidityStandardReview.ts index d5c90df7f..cdd7de67e 100644 --- a/packages/compat/hooks/useAddLiquidityStandardReview.ts +++ b/packages/compat/hooks/useAddLiquidityStandardReview.ts @@ -3,7 +3,7 @@ import type { Amount, Type } from '@zenlink-interface/currency' import type { Dispatch, SetStateAction } from 'react' import { useMemo } from 'react' import { useAddLiquidityStandardReview as useWagmiAddLiquidityStandardReview } from '@zenlink-interface/wagmi' -import { useAddLiquidityStandardReview as useBifrostAddLiquidityStandardReview } from '@zenlink-interface/parachains-bifrost' +import { useAddLiquidityStandardReview as useBifrostAddLiquidityStandardReview } from '@zenlink-interface/parachains-dolphin' import { isEvmNetwork } from '../config' import type { PairState } from './usePairs' diff --git a/packages/compat/hooks/useBalance/useBalance.ts b/packages/compat/hooks/useBalance/useBalance.ts index 2791d141d..9cd6516cd 100644 --- a/packages/compat/hooks/useBalance/useBalance.ts +++ b/packages/compat/hooks/useBalance/useBalance.ts @@ -2,7 +2,7 @@ import type { ParachainId } from '@zenlink-interface/chain' import type { Address } from 'wagmi' import { AddressZero } from '@ethersproject/constants' import { useBalances as useWagmiBalances } from '@zenlink-interface/wagmi' -import { useBalances as useBifrostBalances } from '@zenlink-interface/parachains-bifrost' +// import { useBalances as useBifrostBalances } from '@zenlink-interface/parachains-dolphin' import { useBalances as useDolphinBalances } from '@zenlink-interface/parachains-dolphin' import type { Amount, Type } from '@zenlink-interface/currency' import { useMemo } from 'react' diff --git a/packages/compat/hooks/usePairTotalSupply.ts b/packages/compat/hooks/usePairTotalSupply.ts index 0785e8ad1..018689bec 100644 --- a/packages/compat/hooks/usePairTotalSupply.ts +++ b/packages/compat/hooks/usePairTotalSupply.ts @@ -1,7 +1,7 @@ import type { Pair } from '@zenlink-interface/amm' import type { ParachainId } from '@zenlink-interface/chain' import { usePairTotalSupply as useWagmiPairTotalSupply } from '@zenlink-interface/wagmi' -import { usePairTotalSupply as useBifrostPairTotalSupply } from '@zenlink-interface/parachains-bifrost' +import { usePairTotalSupply as useBifrostPairTotalSupply } from '@zenlink-interface/parachains-dolphin' import { useMemo } from 'react' import { isEvmNetwork, isSubstrateNetwork } from '../config' diff --git a/packages/compat/hooks/usePairs.ts b/packages/compat/hooks/usePairs.ts index bf50a2340..ee88a92d7 100644 --- a/packages/compat/hooks/usePairs.ts +++ b/packages/compat/hooks/usePairs.ts @@ -1,7 +1,7 @@ import type { Pair } from '@zenlink-interface/amm' import type { Currency } from '@zenlink-interface/currency' import { usePairs as useWagmiPairs } from '@zenlink-interface/wagmi' -import { usePairs as useBifrostPairs } from '@zenlink-interface/parachains-bifrost' +import { usePairs as useBifrostPairs } from '@zenlink-interface/parachains-dolphin' import { usePairs as useDolphinPairs } from '@zenlink-interface/parachains-dolphin' import { useMemo } from 'react' import { isEvmNetwork, isSubstrateNetwork } from '../config' diff --git a/packages/compat/hooks/useRemoveLiquidityStandardReview.ts b/packages/compat/hooks/useRemoveLiquidityStandardReview.ts index 443f8c474..bd130f13d 100644 --- a/packages/compat/hooks/useRemoveLiquidityStandardReview.ts +++ b/packages/compat/hooks/useRemoveLiquidityStandardReview.ts @@ -3,7 +3,7 @@ import type { ParachainId } from '@zenlink-interface/chain' import type { Amount, Type } from '@zenlink-interface/currency' import type { Percent } from '@zenlink-interface/math' import { useRemoveLiquidityStandardReview as useWagmiRemoveLiquidityStandardReview } from '@zenlink-interface/wagmi' -import { useRemoveLiquidityStandardReview as useBifrostRemoveLiquidityStandardReview } from '@zenlink-interface/parachains-bifrost' +import { useRemoveLiquidityStandardReview as useBifrostRemoveLiquidityStandardReview } from '@zenlink-interface/parachains-dolphin' import { useMemo } from 'react' import { isEvmNetwork } from '../config' diff --git a/packages/compat/hooks/useStablePools.ts b/packages/compat/hooks/useStablePools.ts index 69c7d9e81..5b7abb31a 100644 --- a/packages/compat/hooks/useStablePools.ts +++ b/packages/compat/hooks/useStablePools.ts @@ -1,7 +1,7 @@ import type { StableSwap } from '@zenlink-interface/amm' import type { Token } from '@zenlink-interface/currency' import { useGetStablePools as useWagmiGetStablePools } from '@zenlink-interface/wagmi' -import { useGetStablePools as useBifrostGetStablePools } from '@zenlink-interface/parachains-bifrost' +import { useGetStablePools as useBifrostGetStablePools } from '@zenlink-interface/parachains-dolphin' import { useMemo } from 'react' import { isEvmNetwork } from '../config' import type { StableSwapWithBase } from '../types' diff --git a/packages/compat/hooks/useSwapReview.ts b/packages/compat/hooks/useSwapReview.ts index 7c1a7ed65..8acc68275 100644 --- a/packages/compat/hooks/useSwapReview.ts +++ b/packages/compat/hooks/useSwapReview.ts @@ -3,7 +3,7 @@ import { TradeVersion } from '@zenlink-interface/amm' import type { Dispatch, SetStateAction } from 'react' import { useMemo } from 'react' import { useSwapReview as useWagmiSwapReview } from '@zenlink-interface/wagmi' -import { useSwapReview as useBifrostSwapReview } from '@zenlink-interface/parachains-bifrost' +import { useSwapReview as useBifrostSwapReview } from '@zenlink-interface/parachains-dolphin' import { EVM_NETWORKS, isEvmNetwork } from '../config' interface UseSwapReviewParams { diff --git a/packages/compat/package.json b/packages/compat/package.json index 435a11c04..2cd5e04d1 100644 --- a/packages/compat/package.json +++ b/packages/compat/package.json @@ -34,7 +34,7 @@ "@zenlink-interface/format": "workspace:*", "@zenlink-interface/hooks": "workspace:*", "@zenlink-interface/math": "workspace:*", - "@zenlink-interface/parachains-bifrost": "workspace:*", + "@zenlink-interface/parachains-dolphin": "workspace:*", "@zenlink-interface/parachains-dolphin": "workspace:*", "@zenlink-interface/polkadot": "workspace:*", "@zenlink-interface/redux-localstorage": "workspace:*", @@ -43,6 +43,7 @@ "@zenlink-interface/ui": "workspace:*", "@zenlink-interface/wagmi": "workspace:*", "@zenlink-types/bifrost": "1.7.5", + "@manta-network/types": "1.0.1", "react-redux": "^8.0.5" }, "devDependencies": { diff --git a/packages/compat/systems/Approve/TokenApproveButton.tsx b/packages/compat/systems/Approve/TokenApproveButton.tsx index 9d027c440..815d0d81a 100644 --- a/packages/compat/systems/Approve/TokenApproveButton.tsx +++ b/packages/compat/systems/Approve/TokenApproveButton.tsx @@ -1,7 +1,7 @@ import type { Amount, Currency } from '@zenlink-interface/currency' import type { FC } from 'react' import { Approve as WagmiApprove } from '@zenlink-interface/wagmi' -import { Approve as BifrostApprove } from '@zenlink-interface/parachains-bifrost' +import { Approve as BifrostApprove } from '@zenlink-interface/parachains-dolphin' import { isEvmNetwork } from '../../config' import type { ApprovalButtonRenderProp, ApproveButton } from './types' diff --git a/packages/compat/systems/Checker/Amounts.tsx b/packages/compat/systems/Checker/Amounts.tsx index f377058eb..b96612e0f 100644 --- a/packages/compat/systems/Checker/Amounts.tsx +++ b/packages/compat/systems/Checker/Amounts.tsx @@ -2,7 +2,7 @@ import type { Amount, Type } from '@zenlink-interface/currency' import type { FC } from 'react' import { Checker as WagmiChecker } from '@zenlink-interface/wagmi' -import { Checker as BifrostChecker } from '@zenlink-interface/parachains-bifrost' +import { Checker as BifrostChecker } from '@zenlink-interface/parachains-dolphin' import { isEvmNetwork } from '../../config' import type { CheckerButton } from './types' diff --git a/packages/compat/systems/Checker/Connected.tsx b/packages/compat/systems/Checker/Connected.tsx index cfc48dc46..4209e4d1b 100644 --- a/packages/compat/systems/Checker/Connected.tsx +++ b/packages/compat/systems/Checker/Connected.tsx @@ -1,6 +1,6 @@ import type { FC } from 'react' import { Checker as WagmiChecker } from '@zenlink-interface/wagmi' -import { Checker as BifrostChecker } from '@zenlink-interface/parachains-bifrost' +import { Checker as BifrostChecker } from '@zenlink-interface/parachains-dolphin' import { isEvmNetwork } from '../../config' import type { CheckerButton } from './types' diff --git a/packages/compat/systems/Checker/Network.tsx b/packages/compat/systems/Checker/Network.tsx index 01d15bda5..46ae80ed4 100644 --- a/packages/compat/systems/Checker/Network.tsx +++ b/packages/compat/systems/Checker/Network.tsx @@ -1,7 +1,7 @@ import type { FC, ReactElement } from 'react' import { Checker as WagmiChecker } from '@zenlink-interface/wagmi' -import { Checker as BifrostChecker } from '@zenlink-interface/parachains-bifrost' +import { Checker as BifrostChecker } from '@zenlink-interface/parachains-dolphin' import { isEvmNetwork } from '../../config' import type { CheckerButton } from './types' diff --git a/packages/config/polkadot/package.json b/packages/config/polkadot/package.json index 16b035bc5..6f05cce41 100644 --- a/packages/config/polkadot/package.json +++ b/packages/config/polkadot/package.json @@ -24,7 +24,8 @@ "dependencies": { "@polkadot/api": "^9.14.2", "@zenlink-interface/chain": "workspace:*", - "@zenlink-types/bifrost": "1.7.5" + "@zenlink-types/bifrost": "1.7.5", + "@manta-network/types": "1.0.1" }, "devDependencies": { "@zenlink-interface/typescript-config": "workspace:*", diff --git a/packages/config/polkadot/src/index.ts b/packages/config/polkadot/src/index.ts index df8259edc..41c924945 100644 --- a/packages/config/polkadot/src/index.ts +++ b/packages/config/polkadot/src/index.ts @@ -5,6 +5,12 @@ import { types as bifrostTypes, typesBundle as bifrostTypesBundle, } from '@zenlink-types/bifrost' +import { + rpc as mantaRpc, + typesAlias as mantaTypeAlias, + types as mantaTypes, + typesBundle as mantaTypesBundle, +} from '@manta-network/types' import type { ApiOptions } from '@polkadot/api/types' interface BlockExplorer { @@ -61,5 +67,11 @@ export const parachains: ParaChain[] = [ url: 'https://dolphin.subscan.io', }, }, + apiOptions: { + rpc: mantaRpc, + types: mantaTypes, + typesAlias: mantaTypeAlias, + typesBundle: mantaTypesBundle, + }, }, ] diff --git a/packages/currency/src/constants.ts b/packages/currency/src/constants.ts index 07073686a..5880662f7 100644 --- a/packages/currency/src/constants.ts +++ b/packages/currency/src/constants.ts @@ -7,7 +7,7 @@ export const WNATIVE_ADDRESS: Record = { [ParachainId.MOONBEAM]: '0xAcc15dC74880C9944775448304B263D191c6077F', [ParachainId.ASTAR]: '0xAeaaf0e2c81Af264101B9129C00F4440cCF0F720', [ParachainId.BIFROST_KUSAMA]: '2001-0-0', - [ParachainId.DOLPHIN]: '2084-0-1' + [ParachainId.DOLPHIN]: '2084-0-1', } export const WNATIVE: Record = { diff --git a/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts b/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts index 756fe5fcc..9cd3baa24 100644 --- a/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts +++ b/packages/parachains-impl/dolphin/hooks/useBalance/useBalance.ts @@ -5,10 +5,10 @@ import type { Token, Type } from '@zenlink-interface/currency' import { Amount } from '@zenlink-interface/currency' import { isZenlinkAddress } from '@zenlink-interface/format' import { JSBI } from '@zenlink-interface/math' -import { useAccount, useApi, useCallMulti, useNativeBalancesAll } from '@zenlink-interface/polkadot' -import type { OrmlAccountData } from '@zenlink-types/bifrost/interfaces' -import { useMemo } from 'react' -import { addressToCurrencyId, addressToNodeCurrency, isNativeCurrency } from '../../libs' +import {useAccount, useApi, useCall, useCallMulti, useNativeBalancesAll} from '@zenlink-interface/polkadot' +// import type { OrmlAccountData } from '@zenlink-types/bifrost/interfaces' +import {useEffect, useMemo} from 'react' +import { addressToCurrencyId, isNativeCurrency } from '../../libs' import type { NodePrimitivesCurrency } from '../../types' import type { BalanceMap } from './types' @@ -44,21 +44,43 @@ export const useBalances: UseBalances = ({ [chainId, currencies], ) + // console.log('validate Account:' + account + ', Token sie' + validatedTokens.length + ',' + JSON.stringify(validatedTokens)) + // if (validatedTokens.length > 0) { + // for (let i = 0; i < validatedTokens.length; i++) { + // // eslint-disable-next-line react-hooks/rules-of-hooks + // useEffect(() => { + // const addr = validatedTokens[i].wrapped.address + // const assid = addressToCurrencyId(addr) + // const fetchBalance = async () => { + // // await api?.query.assets.account(assid, account) + // await api?.query.system.account(account) + // } + // const fetchRes = fetchBalance() + // console.log('fetch addr: '+ addr + ',' + assid + ',result:' + JSON.stringify(fetchRes)) + // }) + // } + // } + const balances = useCallMulti({ chainId, calls: (api && isAccount(account)) ? validatedTokens .map(currency => [api.query.assets.account, [addressToCurrencyId(currency.wrapped.address), account]]) - // .filter((call): call is [QueryableStorageEntry<'promise'>, [number, string]] => Boolean(call[0])) + .filter((call): call is [QueryableStorageEntry<'promise'>, ...any[]] => Boolean(call[0])) : [], options: { enabled: enabled && Boolean(api && isAccount(account)) }, }) - const balanceMap: BalanceMap = useMemo(() => { const result: BalanceMap = {} + // if (balances.length !== 0) + // console.log('balances size:' + balances.length + ',tokens size:' + validatedTokens.length + ',balance:' + JSON.stringify(balances)) + if (balances.length !== validatedTokens.length) return result + for (let i = 0; i < validatedTokens.length; i++) { + console.log('balance[' + i + ']:' + JSON.stringify(balances[i]) + ',addr:' + validatedTokens[i].address) + // const value = (balances[i] as PalletAssetsAssetAccount).balance const value = balances[i]?.balance const amount = value ? JSBI.BigInt(value.toString()) : undefined @@ -70,7 +92,6 @@ export const useBalances: UseBalances = ({ else result[validatedTokens[i].address] = Amount.fromRawAmount(validatedTokens[i], '0') - // BNC if (isNativeCurrency(validatedTokens[i])) result[validatedTokens[i].wrapped.address] = Amount.fromRawAmount(validatedTokens[i], nativeBalancesAll?.freeBalance.toString() || '0') } @@ -109,6 +130,7 @@ export const useBalance: UseBalance = ({ ? data?.[currency.wrapped.address] : undefined + // console.log('addr:' + currency.wrapped.address + ',bal:' + balance) return { isError, isLoading, diff --git a/packages/parachains-impl/dolphin/hooks/usePairs.ts b/packages/parachains-impl/dolphin/hooks/usePairs.ts index 51aa056f8..926ee22d5 100644 --- a/packages/parachains-impl/dolphin/hooks/usePairs.ts +++ b/packages/parachains-impl/dolphin/hooks/usePairs.ts @@ -5,11 +5,11 @@ import type { Currency, Token, Type } from '@zenlink-interface/currency' import { Amount } from '@zenlink-interface/currency' import { addressToZenlinkAssetId } from '@zenlink-interface/format' import { useApi, useCallMulti } from '@zenlink-interface/polkadot' -import type { AccountId, OrmlTokensAccountData, ZenlinkAssetBalance } from '@zenlink-types/bifrost/interfaces' +// import type { AccountId, OrmlTokensAccountData, ZenlinkAssetBalance } from '@zenlink-types/bifrost/interfaces' import type { FrameSystemAccountInfo, PalletAssetsAssetAccount } from '@polkadot/types/lookup' import { useMemo } from 'react' import { ParachainId } from '@zenlink-interface/chain' -import { PAIR_ADDRESSES, addressToCurrencyId, addressToNodeCurrency, isNativeCurrency } from '../libs' +import { PAIR_ADDRESSES, addressToCurrencyId, isNativeCurrency } from '../libs' import type { PairPrimitivesAssetId } from '../types' export enum PairState { @@ -61,10 +61,10 @@ interface UsePairsReturn { data: [PairState, Pair | null][] } -export interface ZenlinkPairMetadata extends Struct { - readonly pairAccount: AccountId - readonly targetSupply: ZenlinkAssetBalance -} +// export interface ZenlinkPairMetadata extends Struct { +// readonly pairAccount: AccountId +// readonly targetSupply: ZenlinkAssetBalance +// } export function usePairs( chainId: number | undefined, @@ -80,8 +80,6 @@ export function usePairs( const tokenB = tokensB[i] const pairKey = uniqePairKey(tokenA, tokenB) const pairAccount = PAIR_ADDRESSES[pairKey]?.account - // console.log('tokenA:' + JSON.stringify(tokenA)) - // console.log('tokenB:' + JSON.stringify(tokenB)) console.log('use Pairs:' + pairKey + ',' + pairAccount) if (pairAccount && api) { acc[0].push(tokenA) @@ -131,6 +129,8 @@ export function usePairs( const pairKey = uniqePairKey(tokenA, tokenB) const reserve0 = reserves[i * 2] const reserve1 = reserves[i * 2 + 1] + console.log('reserve0' + JSON.stringify(reserve0)) + console.log('reserve1' + JSON.stringify(reserve1)) const pairAddress = PAIR_ADDRESSES[pairKey]?.address if (!reserve0 || !reserve1 || reserve0.isEmpty || reserve1.isEmpty || !pairAddress) return [PairState.NOT_EXISTS, null] diff --git a/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts b/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts index 8fbceedec..0d026dbc1 100644 --- a/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts +++ b/packages/parachains-impl/dolphin/hooks/useTotalSupply.ts @@ -5,7 +5,7 @@ import type { Token } from '@zenlink-interface/currency' import { Amount } from '@zenlink-interface/currency' import { useApis } from '@zenlink-interface/polkadot' import { useEffect, useMemo, useState } from 'react' -import { addressToCurrencyId, addressToNodeCurrency, isNativeCurrency } from '../libs' +import { addressToCurrencyId, isNativeCurrency } from '../libs' export const useMultipleTotalSupply = (tokens?: Token[], enabled = true): Record | undefined> | undefined => { const apis = useApis() diff --git a/packages/parachains-impl/dolphin/libs/constants/address.ts b/packages/parachains-impl/dolphin/libs/constants/address.ts index 810b33248..4acbafc67 100644 --- a/packages/parachains-impl/dolphin/libs/constants/address.ts +++ b/packages/parachains-impl/dolphin/libs/constants/address.ts @@ -6,14 +6,13 @@ export const PAIR_ADDRESSES: Record>( - (acc, [assetsAddress, { address }]) => { - const addresses = (assetsAddress.match(/\d+(-\d+)(-\d+)/g) || []).filter(isZenlinkAddress) - const assetsId = addresses.map(addressToZenlinkAssetId) as PairPrimitivesAssetId - acc[address] = assetsId - return acc - }, {}) +// export const pairAddressToAssets = Object.entries(PAIR_ADDRESSES) +// .reduce>( +// (acc, [assetsAddress, { address }]) => { +// const addresses = (assetsAddress.match(/\d+(-\d+)(-\d+)/g) || []).filter(isZenlinkAddress) +// const assetsId = addresses.map(addressToZenlinkAssetId) as PairPrimitivesAssetId +// acc[address] = assetsId +// return acc +// }, {}) diff --git a/packages/parachains-impl/dolphin/libs/formats/currency.ts b/packages/parachains-impl/dolphin/libs/formats/currency.ts index 243dd04f1..fdb008735 100644 --- a/packages/parachains-impl/dolphin/libs/formats/currency.ts +++ b/packages/parachains-impl/dolphin/libs/formats/currency.ts @@ -1,7 +1,7 @@ import type { ZenlinkProtocolPrimitivesAssetId } from '@zenlink-interface/format' import { addressToZenlinkAssetId, zenlinkAssetIdToAddress } from '@zenlink-interface/format' import type { NodePrimitivesCurrency } from '../../types' -import { pairAddressToAssets } from '../constants' +// import { pairAddressToAssets } from '../constants' export const NodeCurrencyId: Record = { 0: 'Native', @@ -36,41 +36,41 @@ function parseAssetType(assetIndex: number) { return assetIndex & 0x0000_0000_0000_000FF } -export function parseNodePrimitivesCurrency(asset: ZenlinkProtocolPrimitivesAssetId): NodePrimitivesCurrency { - const { assetIndex } = asset - const assetTypeU8 = parseAssetU8(assetIndex) - const nodeCurrencyId = NodeCurrencyId[assetTypeU8] +// export function parseNodePrimitivesCurrency(asset: ZenlinkProtocolPrimitivesAssetId): NodePrimitivesCurrency { +// const { assetIndex } = asset +// const assetTypeU8 = parseAssetU8(assetIndex) +// const nodeCurrencyId = NodeCurrencyId[assetTypeU8] +// +// if (!nodeCurrencyId) +// throw new Error('invalid asset') +// +// if (TokenType2.includes(assetTypeU8)) +// return { [nodeCurrencyId]: parseAssetType(assetIndex) } +// +// // LPToken +// if (assetIndex.toString().length === 13) { +// const [asset0, asset1] = pairAddressToAssets[zenlinkAssetIdToAddress(asset)] +// const asset0U8 = parseAssetU8(asset0.assetIndex) +// const asset1U8 = parseAssetU8(asset1.assetIndex) +// return { +// [nodeCurrencyId]: [ +// NodeTokenSymbol[parseAssetType(asset0.assetIndex)], +// asset0U8, +// NodeTokenSymbol[parseAssetType(asset1.assetIndex)], +// asset1U8, +// ], +// } +// } +// +// return { [nodeCurrencyId]: NodeTokenSymbol[parseAssetType(assetIndex)] } +// } - if (!nodeCurrencyId) - throw new Error('invalid asset') - - if (TokenType2.includes(assetTypeU8)) - return { [nodeCurrencyId]: parseAssetType(assetIndex) } - - // LPToken - if (assetIndex.toString().length === 13) { - const [asset0, asset1] = pairAddressToAssets[zenlinkAssetIdToAddress(asset)] - const asset0U8 = parseAssetU8(asset0.assetIndex) - const asset1U8 = parseAssetU8(asset1.assetIndex) - return { - [nodeCurrencyId]: [ - NodeTokenSymbol[parseAssetType(asset0.assetIndex)], - asset0U8, - NodeTokenSymbol[parseAssetType(asset1.assetIndex)], - asset1U8, - ], - } - } - - return { [nodeCurrencyId]: NodeTokenSymbol[parseAssetType(assetIndex)] } -} - -export function addressToNodeCurrency(address: string): NodePrimitivesCurrency { - const zenlinkAsset = addressToZenlinkAssetId(address) - // console.log('zenlink chain:' + zenlinkAsset.chainId + ',type:' + zenlinkAsset.assetType + ',index:' + zenlinkAsset.assetIndex) - // return parseNodePrimitivesCurrency(zenlinkAsset) - return { [NodeCurrencyId[zenlinkAsset.assetType]]: NodeTokenSymbol[zenlinkAsset.assetIndex] } -} +// export function addressToNodeCurrency(address: string): NodePrimitivesCurrency { +// const zenlinkAsset = addressToZenlinkAssetId(address) +// // console.log('zenlink chain:' + zenlinkAsset.chainId + ',type:' + zenlinkAsset.assetType + ',index:' + zenlinkAsset.assetIndex) +// // return parseNodePrimitivesCurrency(zenlinkAsset) +// return { [NodeCurrencyId[zenlinkAsset.assetType]]: NodeTokenSymbol[zenlinkAsset.assetIndex] } +// } export function addressToCurrencyId(address: string): number { const zenlinkAsset = addressToZenlinkAssetId(address) diff --git a/packages/parachains-impl/dolphin/package.json b/packages/parachains-impl/dolphin/package.json index 82a48c387..4f59becc6 100644 --- a/packages/parachains-impl/dolphin/package.json +++ b/packages/parachains-impl/dolphin/package.json @@ -36,7 +36,8 @@ "@zenlink-interface/polkadot": "workspace:*", "@zenlink-interface/shared": "workspace:*", "@zenlink-interface/ui": "workspace:*", - "@zenlink-types/bifrost": "1.7.5" + "@zenlink-types/bifrost": "1.7.5", + "@manta-network/types": "1.0.1" }, "devDependencies": { "@types/react": "^18.0.28", diff --git a/packages/polkadot/hooks/useCallMulti.ts b/packages/polkadot/hooks/useCallMulti.ts index 26cf274dd..6e8d123f4 100644 --- a/packages/polkadot/hooks/useCallMulti.ts +++ b/packages/polkadot/hooks/useCallMulti.ts @@ -66,7 +66,10 @@ function subscribe( handleError(error as Error, tracker) } } - }).catch(error => handleError(error as Error, tracker)) + }).catch((error) => { + console.log('calls:' + JSON.stringify(filtered)) + handleError(error as Error, tracker) + }) } else { tracker.current.subscriber = null @@ -93,6 +96,7 @@ export function useCallMulti({ chainId, calls, options }: UseCallMultiOptions // check if we have a function & that we are mounted if (api && isMounted && calls) { const serialized = JSON.stringify(calls) + // console.log('useCallMulti:' + JSON.stringify(serialized)) if (serialized !== tracker.current.serialized) { tracker.current.serialized = serialized diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bfe7685c6..e6ba325c3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -632,6 +632,7 @@ importers: '@ethersproject/constants': ^5.7.0 '@headlessui/react': ^1.7.13 '@heroicons/react': ^2.0.16 + '@manta-network/types': 1.0.1 '@reduxjs/toolkit': ^1.9.3 '@types/react': ^18.0.28 '@types/react-dom': ^18.0.11 @@ -664,6 +665,7 @@ importers: '@ethersproject/constants': 5.7.0 '@headlessui/react': 1.7.13_biqbaboplfbrettd7655fr4n2y '@heroicons/react': 2.0.16_react@18.2.0 + '@manta-network/types': 1.0.1 '@reduxjs/toolkit': 1.9.3_k4ae6lp43ej6mezo3ztvx6pykq '@zenlink-interface/amm': link:../amm '@zenlink-interface/chain': link:../chain @@ -750,13 +752,15 @@ importers: packages/config/polkadot: specifiers: - '@polkadot/api': ^9.4.2 + '@manta-network/types': 1.0.1 + '@polkadot/api': ^9.14.2 '@zenlink-interface/chain': workspace:* '@zenlink-interface/typescript-config': workspace:* '@zenlink-types/bifrost': 1.7.5 tsup: ^6.6.3 typescript: 4.9.5 dependencies: + '@manta-network/types': 1.0.1 '@polkadot/api': 9.14.2 '@zenlink-interface/chain': link:../../chain '@zenlink-types/bifrost': 1.7.5 @@ -1030,6 +1034,7 @@ importers: specifiers: '@headlessui/react': ^1.7.13 '@heroicons/react': ^2.0.16 + '@manta-network/types': 1.0.1 '@polkadot/api': ^9.14.2 '@polkadot/types': ^9.14.2 '@polkadot/types-codec': ^9.14.2 @@ -1055,6 +1060,7 @@ importers: dependencies: '@headlessui/react': 1.7.13_biqbaboplfbrettd7655fr4n2y '@heroicons/react': 2.0.16_react@18.2.0 + '@manta-network/types': 1.0.1 '@polkadot/api': 9.14.2 '@polkadot/types': 9.14.2 '@polkadot/types-codec': 9.14.2 @@ -4393,6 +4399,28 @@ packages: dependencies: '@lit-labs/ssr-dom-shim': 1.0.0 + /@manta-network/type-definitions/1.0.0: + resolution: {integrity: sha512-HT2FeozCy0JSDOjqYTmPyAfGZiqdao/iuwsoekBGnu+Qw+17PMpybpJDCaFlyOVNvtOJbZvSivT3vNtF65xWOA==} + dependencies: + '@open-web3/orml-type-definitions': 0.9.4-38 + dev: false + + /@manta-network/types/1.0.1: + resolution: {integrity: sha512-udZ2Xmao5VWJ8Ju171paHIi18rv74V4sElfkFlNNKBcojy2gf9nFCmqdM3fIpHXF+m4J1jCnKFxqrp1bHaS7Kg==} + dependencies: + '@babel/runtime': 7.21.0 + '@manta-network/type-definitions': 1.0.0 + '@open-web3/api-mobx': 0.9.4-38_@polkadot+api@9.14.2 + '@open-web3/orml-types': 0.9.4-38_phzfalzjacdgekvhrwboab2hie + '@polkadot/api': 9.14.2 + '@polkadot/typegen': 9.14.2 + '@polkadot/types': 9.14.2 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + dev: false + /@metamask/safe-event-emitter/2.0.0: resolution: {integrity: sha512-/kSXhY692qiV1MXu6EeOZvg5nECLclxNXcKCxJ3cXQgYuRymRHpdx/t7JXfsK+JLjwA1e1c1/SBrlQYpusC29Q==} diff --git a/renovate.json b/renovate.json index 085137b1d..447ee7fb7 100644 --- a/renovate.json +++ b/renovate.json @@ -36,7 +36,8 @@ "@polkadot/keyring", "@polkadot/ui-keyring", "@polkadot/rpc-augment", - "@zenlink-types/bifrost" + "@zenlink-types/bifrost", + "@manta-network/types" ], "enabled": false }