From 5cb88d48444f1cfd51bc07532489cef93e3dbfcf Mon Sep 17 00:00:00 2001 From: Jordan Prince Date: Thu, 6 May 2021 15:58:31 -0500 Subject: [PATCH 01/95] Fixes for governance --- packages/common/src/utils/ids.ts | 2 +- .../src/actions/depositSourceTokensAndVote.ts | 5 ++--- packages/governance/src/actions/execute.ts | 11 +++++++---- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/common/src/utils/ids.ts b/packages/common/src/utils/ids.ts index 37697a3f..db142ab0 100644 --- a/packages/common/src/utils/ids.ts +++ b/packages/common/src/utils/ids.ts @@ -107,7 +107,7 @@ export const PROGRAM_IDS = [ { name: 'devnet', governance: () => ({ - programId: new PublicKey('A9KW1nhwZUr1kMX8C6rgzZvAE9AwEEUi2C77SiVvEiuN'), + programId: new PublicKey('C3FdFYAwoAanUUHrtxnnzN8A6R13RmRoDRWmLbcpZATp'), }), wormhole: () => ({ pubkey: new PublicKey('WormT3McKhFJ2RkiGpdw9GKvNCrB2aB54gb2uV9MfQC'), diff --git a/packages/governance/src/actions/depositSourceTokensAndVote.ts b/packages/governance/src/actions/depositSourceTokensAndVote.ts index 608d431c..f7678452 100644 --- a/packages/governance/src/actions/depositSourceTokensAndVote.ts +++ b/packages/governance/src/actions/depositSourceTokensAndVote.ts @@ -28,7 +28,7 @@ import { createEmptyGovernanceVotingRecordInstruction } from '../models/createEm import { voteInstruction } from '../models/vote'; const { createTokenAccount } = actions; -const { sendTransactions } = contexts.Connection; +const { sendTransactions, SequenceType } = contexts.Connection; const { notify } = utils; const { approve } = models; @@ -199,8 +199,7 @@ export const depositSourceTokensAndVote = async ( wallet, [depositInstructions, voteInstructions], [depositSigners, voteSigners], - true, - true, + SequenceType.Sequential, ); notify({ diff --git a/packages/governance/src/actions/execute.ts b/packages/governance/src/actions/execute.ts index e08b04bc..ab274cae 100644 --- a/packages/governance/src/actions/execute.ts +++ b/packages/governance/src/actions/execute.ts @@ -4,7 +4,12 @@ import { Message, TransactionInstruction, } from '@solana/web3.js'; -import { contexts, utils, ParsedAccount } from '@oyster/common'; +import { + contexts, + utils, + ParsedAccount, + sendTransactionWithRetry, +} from '@oyster/common'; import { Proposal, @@ -14,7 +19,6 @@ import { import { executeInstruction } from '../models/execute'; import { LABELS } from '../constants'; import { getMessageAccountInfos } from '../utils/transactions'; -const { sendTransaction } = contexts.Connection; const { notify } = utils; export const execute = async ( @@ -47,12 +51,11 @@ export const execute = async ( }); try { - let tx = await sendTransaction( + let tx = await sendTransactionWithRetry( connection, wallet, instructions, signers, - true, ); notify({ From 4b1d3cfdab5f27b9d4c16f546687f4f2b63aff71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Diego=20Garc=C3=ADa?= Date: Fri, 7 May 2021 16:29:06 -0500 Subject: [PATCH 02/95] fixed firefox and safari svg compatibility (#109) --- packages/bridge/public/home/main-logo.svg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/bridge/public/home/main-logo.svg b/packages/bridge/public/home/main-logo.svg index 226f4440..1153d677 100644 --- a/packages/bridge/public/home/main-logo.svg +++ b/packages/bridge/public/home/main-logo.svg @@ -12,7 +12,7 @@ - + From cf8f124f8f3c9ad443d1fcb7839fdac0028720d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Diego=20Garc=C3=ADa?= Date: Sat, 8 May 2021 15:48:08 -0500 Subject: [PATCH 03/95] Added MathWallet Provider (#110) * fixed ledger wallet and filtering out sollet tokens * sanity check for token amounts * added wallet adapter * added math wallet to available wallet * fixed string case * lint common package --- .../bridge/src/components/Layout/index.tsx | 7 +- .../RecentTransactionsTable/index.tsx | 5 +- .../src/components/TokenSelectModal/index.tsx | 3 +- .../bridge/src/components/Transfer/index.tsx | 9 +- .../bridge/src/hooks/useWormholeAccounts.tsx | 8 +- packages/bridge/src/utils/assets.ts | 4 +- packages/bridge/src/views/help/index.tsx | 8 +- .../common/src/components/AppBar/index.tsx | 8 +- .../src/components/ConnectButton/index.tsx | 43 +++-- .../src/components/CurrentUserBadge/index.tsx | 73 ++++---- .../src/components/EtherscanLink/index.tsx | 2 +- packages/common/src/components/Icons/info.tsx | 6 +- .../common/src/components/Identicon/index.tsx | 4 +- .../common/src/components/Input/numeric.tsx | 14 +- .../common/src/components/Settings/index.tsx | 32 ++-- .../common/src/components/TokenIcon/index.tsx | 4 +- packages/common/src/constants/math.ts | 2 +- packages/common/src/contexts/accounts.tsx | 4 +- packages/common/src/contexts/wallet.tsx | 165 +++++++++++------- packages/common/src/hooks/useAccountByMint.ts | 4 +- packages/common/src/hooks/useTokenName.ts | 3 +- packages/common/src/models/tokenSwap.ts | 88 ++++++---- packages/common/src/types/buffer-layout.d.ts | 4 +- .../common/src/types/sol-wallet-adapter.d.ts | 2 +- packages/common/src/utils/eventEmitter.ts | 10 +- packages/common/src/utils/notifications.tsx | 18 +- .../src/wallet-adapters/mathWallet/index.tsx | 92 ++++++++++ .../src/wallet-adapters/solong/index.tsx | 16 +- .../src/wallet-adapters/solong_adapter.tsx | 14 +- .../src/wallet-adapters/torus/index.tsx | 64 ++++--- 30 files changed, 452 insertions(+), 264 deletions(-) create mode 100644 packages/common/src/wallet-adapters/mathWallet/index.tsx diff --git a/packages/bridge/src/components/Layout/index.tsx b/packages/bridge/src/components/Layout/index.tsx index 69034b88..02fe1828 100644 --- a/packages/bridge/src/components/Layout/index.tsx +++ b/packages/bridge/src/components/Layout/index.tsx @@ -24,9 +24,10 @@ export const AppLayout = React.memo((props: any) => { {props.children}
-
- -
+
diff --git a/packages/bridge/src/components/RecentTransactionsTable/index.tsx b/packages/bridge/src/components/RecentTransactionsTable/index.tsx index a11efe9e..86466f79 100644 --- a/packages/bridge/src/components/RecentTransactionsTable/index.tsx +++ b/packages/bridge/src/components/RecentTransactionsTable/index.tsx @@ -34,7 +34,9 @@ export const RecentTransactionsTable = (props: { showUserTransactions?: boolean; tokenAccounts: TokenAccount[]; }) => { - const { loading: loadingTransfers, transfers } = useWormholeTransactions(props.tokenAccounts); + const { loading: loadingTransfers, transfers } = useWormholeTransactions( + props.tokenAccounts, + ); const { provider } = useEthereum(); const bridge = useBridge(); @@ -338,7 +340,6 @@ export const RecentTransactionsTable = (props: { scrollToFirstRowOnChange: false, x: 900, }} - dataSource={transfers.sort((a, b) => b.date - a.date)} columns={userColumns} loading={loadingTransfers} diff --git a/packages/bridge/src/components/TokenSelectModal/index.tsx b/packages/bridge/src/components/TokenSelectModal/index.tsx index f31d86ce..c5c1afc2 100644 --- a/packages/bridge/src/components/TokenSelectModal/index.tsx +++ b/packages/bridge/src/components/TokenSelectModal/index.tsx @@ -36,7 +36,8 @@ export const TokenSelectModal = (props: { return tokens.filter(token => { return ( (token.tags?.indexOf('longList') || -1) < 0 && - token.symbol.includes(search.toUpperCase()) + (token.symbol.toLowerCase().includes(search.toLowerCase()) || + token.name.toLowerCase().includes(search.toLowerCase())) ); }); } diff --git a/packages/bridge/src/components/Transfer/index.tsx b/packages/bridge/src/components/Transfer/index.tsx index f3e179b3..57924aee 100644 --- a/packages/bridge/src/components/Transfer/index.tsx +++ b/packages/bridge/src/components/Transfer/index.tsx @@ -54,8 +54,6 @@ export const Transfer = () => { setLastTypedAccount, } = useTokenChainPairState(); - - const [request, setRequest] = useState({ from: ASSET_CHAIN.Ethereum, to: ASSET_CHAIN.Solana, @@ -85,8 +83,11 @@ export const Transfer = () => { }); }, [A, B, mintAddress, A.info]); - - const tokenAccounts = useMemo(() => userAccounts.filter(u => u.info.mint.toBase58() === request.info?.mint), [request.info?.mint]) + const tokenAccounts = useMemo( + () => + userAccounts.filter(u => u.info.mint.toBase58() === request.info?.mint), + [request.info?.mint], + ); return ( <> diff --git a/packages/bridge/src/hooks/useWormholeAccounts.tsx b/packages/bridge/src/hooks/useWormholeAccounts.tsx index f192eb02..cf2efcd7 100644 --- a/packages/bridge/src/hooks/useWormholeAccounts.tsx +++ b/packages/bridge/src/hooks/useWormholeAccounts.tsx @@ -157,7 +157,7 @@ const queryWrappedMetaAccounts = async ( if (asset.mint) { asset.amount = asset.mint?.info.supply.toNumber() / - Math.pow(10, asset.mint?.info.decimals) || 0; + Math.pow(10, asset.mint?.info.decimals || 0) ; if (!asset.mint) { throw new Error('missing mint'); @@ -167,7 +167,11 @@ const queryWrappedMetaAccounts = async ( connection.onAccountChange(asset.mint?.pubkey, acc => { cache.add(key, acc); asset.mint = cache.get(key); - asset.amount = asset.mint?.info.supply.toNumber() || 0; + if (asset.mint) { + asset.amount = + asset.mint?.info.supply.toNumber() / + Math.pow(10, asset.mint?.info.decimals || 0); + } setExternalAssets([...assets.values()]); }); diff --git a/packages/bridge/src/utils/assets.ts b/packages/bridge/src/utils/assets.ts index 9920dc11..d10f7ab2 100644 --- a/packages/bridge/src/utils/assets.ts +++ b/packages/bridge/src/utils/assets.ts @@ -54,7 +54,9 @@ const EXCLUDED_SPL_TOKENS = ['sol', 'srm', ...EXCLUDED_COMMON_TOKENS]; export const filterModalSolTokens = (tokens: TokenInfo[]) => { return tokens.filter( - token => EXCLUDED_SPL_TOKENS.indexOf(token.symbol.toLowerCase()) < 0, + token => + EXCLUDED_SPL_TOKENS.indexOf(token.symbol.toLowerCase()) < 0 && + !token.name.includes('(Sollet)'), ); }; const EXCLUDED_ETH_TOKENS = [...EXCLUDED_COMMON_TOKENS]; diff --git a/packages/bridge/src/views/help/index.tsx b/packages/bridge/src/views/help/index.tsx index 575f5ba5..833c968d 100644 --- a/packages/bridge/src/views/help/index.tsx +++ b/packages/bridge/src/views/help/index.tsx @@ -29,8 +29,12 @@ export const HelpView = () => { - diff --git a/packages/common/src/components/AppBar/index.tsx b/packages/common/src/components/AppBar/index.tsx index d1e79bf3..cd4a072b 100644 --- a/packages/common/src/components/AppBar/index.tsx +++ b/packages/common/src/components/AppBar/index.tsx @@ -18,11 +18,9 @@ export const AppBar = (props: { const TopBar = (
{props.left} - {connected ? - ( - - ) - : ( + {connected ? ( + + ) : ( { +export interface ConnectButtonProps + extends ButtonProps, + React.RefAttributes { allowWalletChange?: boolean; } -export const ConnectButton = ( - props: ConnectButtonProps -) => { +export const ConnectButton = (props: ConnectButtonProps) => { const { connected, connect, select, provider } = useWallet(); const { onClick, children, disabled, allowWalletChange, ...rest } = props; @@ -17,25 +17,30 @@ export const ConnectButton = ( const menu = ( - Change Wallet + + Change Wallet + ); - if(!provider || !allowWalletChange) { - return ; + if (!provider || !allowWalletChange) { + return ( + + ); } return ( + onClick={connected ? onClick : connect} + disabled={connected && disabled} + overlay={menu} + > Connect ); diff --git a/packages/common/src/components/CurrentUserBadge/index.tsx b/packages/common/src/components/CurrentUserBadge/index.tsx index e2908c79..df1e2692 100644 --- a/packages/common/src/components/CurrentUserBadge/index.tsx +++ b/packages/common/src/components/CurrentUserBadge/index.tsx @@ -9,7 +9,11 @@ import './styles.css'; import { Popover } from 'antd'; import { Settings } from '../Settings'; -export const CurrentUserBadge = (props: { showBalance?: boolean, showAddress?: boolean, iconSize?: number }) => { +export const CurrentUserBadge = (props: { + showBalance?: boolean; + showAddress?: boolean; + iconSize?: number; +}) => { const { wallet } = useWallet(); const { account } = useNativeAccount(); @@ -17,54 +21,59 @@ export const CurrentUserBadge = (props: { showBalance?: boolean, showAddress?: b return null; } - const iconStyle: React.CSSProperties = props.showAddress ? - { - marginLeft: '0.5rem', - display: 'flex', - width: props.iconSize, - borderRadius: 50, + const iconStyle: React.CSSProperties = props.showAddress + ? { + marginLeft: '0.5rem', + display: 'flex', + width: props.iconSize, + borderRadius: 50, + } + : { + display: 'flex', + width: props.iconSize, + paddingLeft: 0, + borderRadius: 50, + }; - } :{ - display: 'flex', - width: props.iconSize, - paddingLeft: 0, - borderRadius: 50, + const baseWalletKey: React.CSSProperties = { + height: props.iconSize, + cursor: 'pointer', + userSelect: 'none', }; - - const baseWalletKey: React.CSSProperties = { height: props.iconSize, cursor: 'pointer', userSelect: 'none' }; - const walletKeyStyle: React.CSSProperties = props.showAddress ? - baseWalletKey - :{ ...baseWalletKey, paddingLeft: 0 }; + const walletKeyStyle: React.CSSProperties = props.showAddress + ? baseWalletKey + : { ...baseWalletKey, paddingLeft: 0 }; let name = props.showAddress ? shortenAddress(`${wallet.publicKey}`) : ''; const unknownWallet = wallet as any; - if(unknownWallet.name) { + if (unknownWallet.name) { name = unknownWallet.name; } - let image = ; + let image = ( + + ); - if(unknownWallet.image) { + if (unknownWallet.image) { image = ; } return (
- {props.showBalance && - {formatNumber.format((account?.lamports || 0) / LAMPORTS_PER_SOL)} SOL - } + {props.showBalance && ( + + {formatNumber.format((account?.lamports || 0) / LAMPORTS_PER_SOL)} SOL + + )} } - trigger="click" - > + placement="topRight" + title="Settings" + content={} + trigger="click" + >
- {name && ({name})} + {name && {name}} {image}
diff --git a/packages/common/src/components/EtherscanLink/index.tsx b/packages/common/src/components/EtherscanLink/index.tsx index 321febb8..745daf30 100644 --- a/packages/common/src/components/EtherscanLink/index.tsx +++ b/packages/common/src/components/EtherscanLink/index.tsx @@ -3,7 +3,7 @@ import { Typography } from 'antd'; import { shortenAddress } from '../../utils/utils'; export const EtherscanLink = (props: { - address: string ; + address: string; type: string; code?: boolean; style?: React.CSSProperties; diff --git a/packages/common/src/components/Icons/info.tsx b/packages/common/src/components/Icons/info.tsx index 4bb0e3a0..6ef9758e 100644 --- a/packages/common/src/components/Icons/info.tsx +++ b/packages/common/src/components/Icons/info.tsx @@ -1,7 +1,7 @@ -import { Button, Popover } from "antd"; -import React from "react"; +import { Button, Popover } from 'antd'; +import React from 'react'; -import { InfoCircleOutlined } from "@ant-design/icons"; +import { InfoCircleOutlined } from '@ant-design/icons'; export const Info = (props: { text: React.ReactElement; diff --git a/packages/common/src/components/Identicon/index.tsx b/packages/common/src/components/Identicon/index.tsx index 0c9f4764..55d824c9 100644 --- a/packages/common/src/components/Identicon/index.tsx +++ b/packages/common/src/components/Identicon/index.tsx @@ -20,7 +20,6 @@ export const Identicon = (props: { useEffect(() => { if (address && ref.current) { try { - ref.current.innerHTML = ''; ref.current.className = className || ''; ref.current.appendChild( @@ -29,9 +28,8 @@ export const Identicon = (props: { parseInt(bs58.decode(address).toString('hex').slice(5, 15), 16), ), ); - } catch (err) { - // TODO + // TODO } } }, [address, style, className]); diff --git a/packages/common/src/components/Input/numeric.tsx b/packages/common/src/components/Input/numeric.tsx index c307e3e9..84ebc771 100644 --- a/packages/common/src/components/Input/numeric.tsx +++ b/packages/common/src/components/Input/numeric.tsx @@ -1,11 +1,11 @@ -import React from "react"; -import { Input } from "antd"; +import React from 'react'; +import { Input } from 'antd'; export class NumericInput extends React.Component { onChange = (e: any) => { const { value } = e.target; const reg = /^-?\d*(\.\d*)?$/; - if (reg.test(value) || value === "" || value === "-") { + if (reg.test(value) || value === '' || value === '-') { this.props.onChange(value); } }; @@ -17,14 +17,14 @@ export class NumericInput extends React.Component { if (value === undefined || value === null) return; if ( value.charAt && - (value.charAt(value.length - 1) === "." || value === "-") + (value.charAt(value.length - 1) === '.' || value === '-') ) { valueTemp = value.slice(0, -1); } - if (value.startsWith && (value.startsWith(".") || value.startsWith("-."))) { - valueTemp = valueTemp.replace(".", "0."); + if (value.startsWith && (value.startsWith('.') || value.startsWith('-.'))) { + valueTemp = valueTemp.replace('.', '0.'); } - if (valueTemp.replace) onChange?.(valueTemp.replace(/0*(\d+)/, "$1")); + if (valueTemp.replace) onChange?.(valueTemp.replace(/0*(\d+)/, '$1')); if (onBlur) { onBlur(); } diff --git a/packages/common/src/components/Settings/index.tsx b/packages/common/src/components/Settings/index.tsx index 6e97706d..0ca0c740 100644 --- a/packages/common/src/components/Settings/index.tsx +++ b/packages/common/src/components/Settings/index.tsx @@ -3,9 +3,7 @@ import { Button, Select } from 'antd'; import { useWallet } from '../../contexts/wallet'; import { ENDPOINTS, useConnectionConfig } from '../../contexts/connection'; import { shortenAddress } from '../../utils'; -import { - CopyOutlined -} from '@ant-design/icons'; +import { CopyOutlined } from '@ant-design/icons'; export const Settings = ({ additionalSettings, @@ -33,18 +31,28 @@ export const Settings = ({ {connected && ( <> Wallet: - {wallet?.publicKey && ()} + {wallet?.publicKey && ( + + )} - - diff --git a/packages/common/src/components/TokenIcon/index.tsx b/packages/common/src/components/TokenIcon/index.tsx index 21da7ecd..c70a793f 100644 --- a/packages/common/src/components/TokenIcon/index.tsx +++ b/packages/common/src/components/TokenIcon/index.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { PublicKey } from '@solana/web3.js'; -import {getTokenIcon, KnownTokenMap} from '../../utils'; +import { getTokenIcon, KnownTokenMap } from '../../utils'; import { useConnectionConfig } from '../../contexts/connection'; import { Identicon } from '../Identicon'; @@ -9,7 +9,7 @@ export const TokenIcon = (props: { style?: React.CSSProperties; size?: number; className?: string; - tokenMap?: KnownTokenMap, + tokenMap?: KnownTokenMap; }) => { let icon: string | undefined = ''; if (props.tokenMap) { diff --git a/packages/common/src/constants/math.ts b/packages/common/src/constants/math.ts index d0b48657..6e062935 100644 --- a/packages/common/src/constants/math.ts +++ b/packages/common/src/constants/math.ts @@ -1,4 +1,4 @@ -import BN from "bn.js"; +import BN from 'bn.js'; export const TEN = new BN(10); export const HALF_WAD = TEN.pow(new BN(18)); diff --git a/packages/common/src/contexts/accounts.tsx b/packages/common/src/contexts/accounts.tsx index f4e84f95..f4813581 100644 --- a/packages/common/src/contexts/accounts.tsx +++ b/packages/common/src/contexts/accounts.tsx @@ -341,7 +341,7 @@ const UseNativeAccount = () => { return; } - const account = await connection.getAccountInfo(wallet.publicKey) + const account = await connection.getAccountInfo(wallet.publicKey); updateAccount(account); subId = connection.onAccountChange(wallet.publicKey, updateAccount); @@ -351,7 +351,7 @@ const UseNativeAccount = () => { if (subId) { connection.removeAccountChangeListener(subId); } - } + }; }, [setNativeAccount, wallet, wallet?.publicKey, connection, updateCache]); return { nativeAccount }; diff --git a/packages/common/src/contexts/wallet.tsx b/packages/common/src/contexts/wallet.tsx index 8a506e82..8061e004 100644 --- a/packages/common/src/contexts/wallet.tsx +++ b/packages/common/src/contexts/wallet.tsx @@ -1,42 +1,57 @@ -import { WalletAdapter } from "@solana/wallet-base"; - -import Wallet from "@project-serum/sol-wallet-adapter"; -import { Button, Modal } from "antd"; -import React, { useCallback, useContext, useEffect, useMemo, useState } from "react"; -import { notify } from "./../utils/notifications"; -import { useConnectionConfig } from "./connection"; -import { useLocalStorageState } from "../utils/utils"; -import { LedgerProvider } from "@solana/wallet-ledger"; -import { SolongWalletAdapter } from "../wallet-adapters/solong"; -import { PhantomWalletAdapter } from "../wallet-adapters/phantom"; -import { TorusWalletAdapter } from "../wallet-adapters/torus"; -import { useLocation } from "react-router"; - -const ASSETS_URL = 'https://raw.githubusercontent.com/solana-labs/oyster/main/assets/wallets/'; +import { WalletAdapter } from '@solana/wallet-base'; + +import Wallet from '@project-serum/sol-wallet-adapter'; +import { Button, Modal } from 'antd'; +import React, { + useCallback, + useContext, + useEffect, + useMemo, + useState, +} from 'react'; +import { notify } from './../utils/notifications'; +import { useConnectionConfig } from './connection'; +import { useLocalStorageState } from '../utils/utils'; +import { SolongWalletAdapter } from '../wallet-adapters/solong'; +import { PhantomWalletAdapter } from '../wallet-adapters/phantom'; +import { TorusWalletAdapter } from '../wallet-adapters/torus'; +import { useLocation } from 'react-router'; +import { LedgerWalletAdapter } from '@solana/wallet-ledger'; +import {MathWalletAdapter} from "../wallet-adapters/mathWallet"; + +const ASSETS_URL = + 'https://raw.githubusercontent.com/solana-labs/oyster/main/assets/wallets/'; export const WALLET_PROVIDERS = [ { - name: "Phantom", - url: "https://www.phantom.app", + name: 'Phantom', + url: 'https://www.phantom.app', icon: `https://www.phantom.app/img/logo.png`, adapter: PhantomWalletAdapter, }, - LedgerProvider, { - name: "Sollet", - url: "https://www.sollet.io", + name: 'Ledger', + url: 'https://www.ledger.com', + icon: `${ASSETS_URL}ledger.svg`, + adapter: LedgerWalletAdapter, + }, + { + name: 'Sollet', + url: 'https://www.sollet.io', icon: `${ASSETS_URL}sollet.svg`, - }, { - name: "Solong", - url: "https://solongwallet.com", + }, + { + name: 'Solong', + url: 'https://solongwallet.com', icon: `${ASSETS_URL}solong.png`, adapter: SolongWalletAdapter, }, // TODO: enable when fully functional - // { - // name: "MathWallet", - // url: "https://mathwallet.org", - // icon: `${ASSETS_URL}mathwallet.svg`, - // }, + { + name: 'MathWallet', + url: 'https://mathwallet.org', + icon: `${ASSETS_URL}mathwallet.svg`, + adapter: MathWalletAdapter, + }, // { // name: 'Torus', // url: 'https://tor.us', @@ -53,60 +68,79 @@ export const WALLET_PROVIDERS = [ ]; const WalletContext = React.createContext<{ - wallet: WalletAdapter | undefined, - connected: boolean, - select: () => void, - provider: typeof WALLET_PROVIDERS[number] | undefined, + wallet: WalletAdapter | undefined; + connected: boolean; + select: () => void; + provider: typeof WALLET_PROVIDERS[number] | undefined; }>({ wallet: undefined, connected: false, - select() { }, + select() {}, provider: undefined, }); export function WalletProvider({ children = null as any }) { const { endpoint } = useConnectionConfig(); const location = useLocation(); - const [autoConnect, setAutoConnect] = useState(location.pathname.indexOf('result=') >= 0 || false); - const [providerUrl, setProviderUrl] = useLocalStorageState("walletProvider"); + const [autoConnect, setAutoConnect] = useState( + location.pathname.indexOf('result=') >= 0 || false, + ); + const [providerUrl, setProviderUrl] = useLocalStorageState('walletProvider'); - const provider = useMemo(() => WALLET_PROVIDERS.find(({ url }) => url === providerUrl), [providerUrl]); + const provider = useMemo( + () => WALLET_PROVIDERS.find(({ url }) => url === providerUrl), + [providerUrl], + ); - const wallet = useMemo(function () { - if (provider) { - return new (provider.adapter || Wallet)(providerUrl, endpoint) as WalletAdapter; - } - }, [provider, providerUrl, endpoint]); + const wallet = useMemo( + function () { + if (provider) { + try { + return new (provider.adapter || Wallet)( + providerUrl, + endpoint, + ) as WalletAdapter; + } catch (e) { + console.log(`Error connecting to wallet ${provider.name}: ${e}`); + return undefined; + } + } + }, + [provider, providerUrl, endpoint], + ); const [connected, setConnected] = useState(false); useEffect(() => { if (wallet) { - wallet.on("connect", () => { + wallet.on('connect', () => { if (wallet.publicKey) { setConnected(true); const walletPublicKey = wallet.publicKey.toBase58(); const keyToDisplay = walletPublicKey.length > 20 - ? `${walletPublicKey.substring(0, 7)}.....${walletPublicKey.substring( - walletPublicKey.length - 7, - walletPublicKey.length - )}` + ? `${walletPublicKey.substring( + 0, + 7, + )}.....${walletPublicKey.substring( + walletPublicKey.length - 7, + walletPublicKey.length, + )}` : walletPublicKey; notify({ - message: "Wallet update", - description: "Connected to wallet " + keyToDisplay, + message: 'Wallet update', + description: 'Connected to wallet ' + keyToDisplay, }); } }); - wallet.on("disconnect", () => { + wallet.on('disconnect', () => { setConnected(false); // setProviderUrl(null) notify({ - message: "Wallet update", - description: "Disconnected from wallet", + message: 'Wallet update', + description: 'Disconnected from wallet', }); }); } @@ -126,7 +160,7 @@ export function WalletProvider({ children = null as any }) { setAutoConnect(false); } - return () => { } + return () => {}; }, [wallet, autoConnect]); const [isModalVisible, setIsModalVisible] = useState(false); @@ -148,21 +182,22 @@ export function WalletProvider({ children = null as any }) { title="Select Wallet" okText="Connect" visible={isModalVisible} - okButtonProps={{ style: { display: "none" } }} + okButtonProps={{ style: { display: 'none' } }} onCancel={close} - width={400}> + width={400} + > {WALLET_PROVIDERS.map((provider, idx) => { const onClick = function () { setProviderUrl(provider.url); setAutoConnect(true); close(); - } + }; return ( - ) + }} + > + {provider.name} + + ); })} @@ -199,4 +238,4 @@ export const useWallet = () => { wallet?.disconnect(); }, }; -} +}; diff --git a/packages/common/src/hooks/useAccountByMint.ts b/packages/common/src/hooks/useAccountByMint.ts index e0ae165b..0271d943 100644 --- a/packages/common/src/hooks/useAccountByMint.ts +++ b/packages/common/src/hooks/useAccountByMint.ts @@ -5,7 +5,9 @@ export const useAccountByMint = (mint?: string | PublicKey) => { const { userAccounts } = useUserAccounts(); const mintAddress = typeof mint === 'string' ? mint : mint?.toBase58(); - const index = userAccounts.findIndex((acc) => acc.info.mint.toBase58() === mintAddress); + const index = userAccounts.findIndex( + acc => acc.info.mint.toBase58() === mintAddress, + ); if (index !== -1) { return userAccounts[index]; diff --git a/packages/common/src/hooks/useTokenName.ts b/packages/common/src/hooks/useTokenName.ts index 2bcdcc5d..b4a6b60a 100644 --- a/packages/common/src/hooks/useTokenName.ts +++ b/packages/common/src/hooks/useTokenName.ts @@ -4,6 +4,7 @@ import { getTokenName } from '../utils/utils'; export function useTokenName(mintAddress?: string | PublicKey) { const { tokenMap } = useConnectionConfig(); - const address = typeof mintAddress === 'string' ? mintAddress : mintAddress?.toBase58(); + const address = + typeof mintAddress === 'string' ? mintAddress : mintAddress?.toBase58(); return getTokenName(tokenMap, address); } diff --git a/packages/common/src/models/tokenSwap.ts b/packages/common/src/models/tokenSwap.ts index e095ddda..a5017abb 100644 --- a/packages/common/src/models/tokenSwap.ts +++ b/packages/common/src/models/tokenSwap.ts @@ -14,7 +14,7 @@ const FEE_LAYOUT = BufferLayout.struct( BufferLayout.nu64('hostFeeNumerator'), BufferLayout.nu64('hostFeeDenominator'), ], - 'fees' + 'fees', ); export const TokenSwapLayoutLegacyV0 = BufferLayout.struct([ @@ -27,42 +27,58 @@ export const TokenSwapLayoutLegacyV0 = BufferLayout.struct([ uint64('feesDenominator'), ]); -export const TokenSwapLayoutV1: typeof BufferLayout.Structure = BufferLayout.struct([ - BufferLayout.u8('isInitialized'), - BufferLayout.u8('nonce'), - publicKey('tokenProgramId'), - publicKey('tokenAccountA'), - publicKey('tokenAccountB'), - publicKey('tokenPool'), - publicKey('mintA'), - publicKey('mintB'), - publicKey('feeAccount'), - BufferLayout.u8('curveType'), - uint64('tradeFeeNumerator'), - uint64('tradeFeeDenominator'), - uint64('ownerTradeFeeNumerator'), - uint64('ownerTradeFeeDenominator'), - uint64('ownerWithdrawFeeNumerator'), - uint64('ownerWithdrawFeeDenominator'), - BufferLayout.blob(16, 'padding'), -]); +export const TokenSwapLayoutV1: typeof BufferLayout.Structure = BufferLayout.struct( + [ + BufferLayout.u8('isInitialized'), + BufferLayout.u8('nonce'), + publicKey('tokenProgramId'), + publicKey('tokenAccountA'), + publicKey('tokenAccountB'), + publicKey('tokenPool'), + publicKey('mintA'), + publicKey('mintB'), + publicKey('feeAccount'), + BufferLayout.u8('curveType'), + uint64('tradeFeeNumerator'), + uint64('tradeFeeDenominator'), + uint64('ownerTradeFeeNumerator'), + uint64('ownerTradeFeeDenominator'), + uint64('ownerWithdrawFeeNumerator'), + uint64('ownerWithdrawFeeDenominator'), + BufferLayout.blob(16, 'padding'), + ], +); -const CURVE_NODE = BufferLayout.union(BufferLayout.u8(), BufferLayout.blob(32), 'curve'); +const CURVE_NODE = BufferLayout.union( + BufferLayout.u8(), + BufferLayout.blob(32), + 'curve', +); CURVE_NODE.addVariant(0, BufferLayout.struct([]), 'constantProduct'); -CURVE_NODE.addVariant(1, BufferLayout.struct([BufferLayout.nu64('token_b_price')]), 'constantPrice'); +CURVE_NODE.addVariant( + 1, + BufferLayout.struct([BufferLayout.nu64('token_b_price')]), + 'constantPrice', +); CURVE_NODE.addVariant(2, BufferLayout.struct([]), 'stable'); -CURVE_NODE.addVariant(3, BufferLayout.struct([BufferLayout.nu64('token_b_offset')]), 'offset'); +CURVE_NODE.addVariant( + 3, + BufferLayout.struct([BufferLayout.nu64('token_b_offset')]), + 'offset', +); -export const TokenSwapLayout: typeof BufferLayout.Structure = BufferLayout.struct([ - BufferLayout.u8('isInitialized'), - BufferLayout.u8('nonce'), - publicKey('tokenProgramId'), - publicKey('tokenAccountA'), - publicKey('tokenAccountB'), - publicKey('tokenPool'), - publicKey('mintA'), - publicKey('mintB'), - publicKey('feeAccount'), - FEE_LAYOUT, - CURVE_NODE, -]); +export const TokenSwapLayout: typeof BufferLayout.Structure = BufferLayout.struct( + [ + BufferLayout.u8('isInitialized'), + BufferLayout.u8('nonce'), + publicKey('tokenProgramId'), + publicKey('tokenAccountA'), + publicKey('tokenAccountB'), + publicKey('tokenPool'), + publicKey('mintA'), + publicKey('mintB'), + publicKey('feeAccount'), + FEE_LAYOUT, + CURVE_NODE, + ], +); diff --git a/packages/common/src/types/buffer-layout.d.ts b/packages/common/src/types/buffer-layout.d.ts index ded59a53..32e44d0e 100644 --- a/packages/common/src/types/buffer-layout.d.ts +++ b/packages/common/src/types/buffer-layout.d.ts @@ -1,9 +1,9 @@ -declare module "buffer-layout" { +declare module 'buffer-layout' { const bl: any; export = bl; } -declare module "jazzicon" { +declare module 'jazzicon' { const jazzicon: any; export = jazzicon; } diff --git a/packages/common/src/types/sol-wallet-adapter.d.ts b/packages/common/src/types/sol-wallet-adapter.d.ts index 6464233b..41acf5df 100644 --- a/packages/common/src/types/sol-wallet-adapter.d.ts +++ b/packages/common/src/types/sol-wallet-adapter.d.ts @@ -1,4 +1,4 @@ -declare module "@project-serum/sol-wallet-adapter" { +declare module '@project-serum/sol-wallet-adapter' { const adapter: any; export = adapter; } diff --git a/packages/common/src/utils/eventEmitter.ts b/packages/common/src/utils/eventEmitter.ts index 1111bee6..ee31a717 100644 --- a/packages/common/src/utils/eventEmitter.ts +++ b/packages/common/src/utils/eventEmitter.ts @@ -1,7 +1,7 @@ -import { EventEmitter as Emitter } from "eventemitter3"; +import { EventEmitter as Emitter } from 'eventemitter3'; export class CacheUpdateEvent { - static type = "CacheUpdate"; + static type = 'CacheUpdate'; id: string; parser: any; isNew: boolean; @@ -13,7 +13,7 @@ export class CacheUpdateEvent { } export class CacheDeleteEvent { - static type = "CacheUpdate"; + static type = 'CacheUpdate'; id: string; constructor(id: string) { this.id = id; @@ -21,7 +21,7 @@ export class CacheDeleteEvent { } export class MarketUpdateEvent { - static type = "MarketUpdate"; + static type = 'MarketUpdate'; ids: Set; constructor(ids: Set) { this.ids = ids; @@ -50,7 +50,7 @@ export class EventEmitter { raiseCacheUpdated(id: string, isNew: boolean, parser: any) { this.emitter.emit( CacheUpdateEvent.type, - new CacheUpdateEvent(id, isNew, parser) + new CacheUpdateEvent(id, isNew, parser), ); } diff --git a/packages/common/src/utils/notifications.tsx b/packages/common/src/utils/notifications.tsx index ae1dc158..a6d2ad81 100644 --- a/packages/common/src/utils/notifications.tsx +++ b/packages/common/src/utils/notifications.tsx @@ -1,13 +1,13 @@ -import React from "react"; -import { notification } from "antd"; +import React from 'react'; +import { notification } from 'antd'; // import Link from '../components/Link'; export function notify({ - message = "", + message = '', description = undefined as any, - txid = "", - type = "info", - placement = "bottomLeft", + txid = '', + type = 'info', + placement = 'bottomLeft', }) { if (txid) { // ; } (notification as any)[type]({ - message: {message}, + message: {message}, description: ( - {description} + {description} ), placement, style: { - backgroundColor: "white", + backgroundColor: 'white', }, }); } diff --git a/packages/common/src/wallet-adapters/mathWallet/index.tsx b/packages/common/src/wallet-adapters/mathWallet/index.tsx new file mode 100644 index 00000000..ffe246e5 --- /dev/null +++ b/packages/common/src/wallet-adapters/mathWallet/index.tsx @@ -0,0 +1,92 @@ +import EventEmitter from 'eventemitter3'; +import { PublicKey, Transaction } from '@solana/web3.js'; +import { WalletAdapter } from '@solana/wallet-base'; +import { notify } from '../../utils/notifications'; + +export class MathWalletAdapter extends EventEmitter implements WalletAdapter { + _publicKey: PublicKey | null; + _onProcess: boolean; + _connected: boolean; + constructor() { + super(); + this._publicKey = null; + this._onProcess = false; + this._connected = false; + this.connect = this.connect.bind(this); + } + + get publicKey() { + return this._publicKey; + } + + get connected() { + return this._connected; + } + + get autoApprove() { + return false; + } + + // eslint-disable-next-line + async signAllTransactions( + transactions: Transaction[], + ): Promise { + if (!this._provider) { + return transactions; + } + + return this._provider.signAllTransactions(transactions); + } + + private get _provider() { + if ((window as any)?.solana?.isMathWallet) { + return (window as any).solana; + } + return undefined; + } + + signTransaction(transaction: Transaction) { + if (!this._provider) { + return transaction; + } + + return this._provider.signTransaction(transaction); + } + + connect() { + if (this._onProcess) { + return; + } + if (!this._provider) { + notify({ + message: 'MathWallet Error', + description: + 'Please install and initialize Math wallet extension from Chrome first', + }); + return; + } + + this._onProcess = true; + this._provider + .getAccount() + .then((account: any) => { + this._publicKey = new PublicKey(account); + this._connected = true; + this.emit('connect', this._publicKey); + }) + .catch(() => { + this.disconnect(); + }) + .finally(() => { + this._onProcess = false; + }); + } + + disconnect() { + if (this._publicKey) { + this._publicKey = null; + this._connected = false; + this.emit('disconnect'); + } + } +} diff --git a/packages/common/src/wallet-adapters/solong/index.tsx b/packages/common/src/wallet-adapters/solong/index.tsx index 4f2bcc66..d773d0e7 100644 --- a/packages/common/src/wallet-adapters/solong/index.tsx +++ b/packages/common/src/wallet-adapters/solong/index.tsx @@ -1,7 +1,7 @@ -import EventEmitter from "eventemitter3"; -import {PublicKey, Transaction} from "@solana/web3.js"; -import { WalletAdapter } from "@solana/wallet-base"; -import { notify } from "../../utils/notifications"; +import EventEmitter from 'eventemitter3'; +import { PublicKey, Transaction } from '@solana/web3.js'; +import { WalletAdapter } from '@solana/wallet-base'; +import { notify } from '../../utils/notifications'; export class SolongWalletAdapter extends EventEmitter implements WalletAdapter { _publicKey: PublicKey | null; @@ -32,8 +32,8 @@ export class SolongWalletAdapter extends EventEmitter implements WalletAdapter { if ((window as any).solong === undefined) { notify({ - message: "Solong Error", - description: "Please install solong wallet from Chrome ", + message: 'Solong Error', + description: 'Please install solong wallet from Chrome ', }); return; } @@ -43,7 +43,7 @@ export class SolongWalletAdapter extends EventEmitter implements WalletAdapter { .selectAccount() .then((account: any) => { this._publicKey = new PublicKey(account); - this.emit("connect", this._publicKey); + this.emit('connect', this._publicKey); }) .catch(() => { this.disconnect(); @@ -56,7 +56,7 @@ export class SolongWalletAdapter extends EventEmitter implements WalletAdapter { disconnect() { if (this._publicKey) { this._publicKey = null; - this.emit("disconnect"); + this.emit('disconnect'); } } } diff --git a/packages/common/src/wallet-adapters/solong_adapter.tsx b/packages/common/src/wallet-adapters/solong_adapter.tsx index aef7dd64..f050a44f 100644 --- a/packages/common/src/wallet-adapters/solong_adapter.tsx +++ b/packages/common/src/wallet-adapters/solong_adapter.tsx @@ -1,6 +1,6 @@ -import EventEmitter from "eventemitter3"; -import { PublicKey } from "@solana/web3.js"; -import { notify } from "../utils/notifications"; +import EventEmitter from 'eventemitter3'; +import { PublicKey } from '@solana/web3.js'; +import { notify } from '../utils/notifications'; export class SolongAdapter extends EventEmitter { _publicKey: any; @@ -27,8 +27,8 @@ export class SolongAdapter extends EventEmitter { if ((window as any).solong === undefined) { notify({ - message: "Solong Error", - description: "Please install solong wallet from Chrome ", + message: 'Solong Error', + description: 'Please install solong wallet from Chrome ', }); return; } @@ -38,7 +38,7 @@ export class SolongAdapter extends EventEmitter { .selectAccount() .then((account: any) => { this._publicKey = new PublicKey(account); - this.emit("connect", this._publicKey); + this.emit('connect', this._publicKey); }) .catch(() => { this.disconnect(); @@ -51,7 +51,7 @@ export class SolongAdapter extends EventEmitter { disconnect() { if (this._publicKey) { this._publicKey = null; - this.emit("disconnect"); + this.emit('disconnect'); } } } diff --git a/packages/common/src/wallet-adapters/torus/index.tsx b/packages/common/src/wallet-adapters/torus/index.tsx index 7d1e1578..39495bd4 100644 --- a/packages/common/src/wallet-adapters/torus/index.tsx +++ b/packages/common/src/wallet-adapters/torus/index.tsx @@ -1,13 +1,13 @@ -import EventEmitter from "eventemitter3" -import { Account, PublicKey, Transaction } from "@solana/web3.js" -import { WalletAdapter } from "@solana/wallet-base" -import OpenLogin from "@toruslabs/openlogin" -import { getED25519Key } from "@toruslabs/openlogin-ed25519" +import EventEmitter from 'eventemitter3'; +import { Account, PublicKey, Transaction } from '@solana/web3.js'; +import { WalletAdapter } from '@solana/wallet-base'; +import OpenLogin from '@toruslabs/openlogin'; +import { getED25519Key } from '@toruslabs/openlogin-ed25519'; -const getSolanaPrivateKey = (openloginKey: string)=>{ - const { sk } = getED25519Key(openloginKey) - return sk -} +const getSolanaPrivateKey = (openloginKey: string) => { + const { sk } = getED25519Key(openloginKey); + return sk; +}; export class TorusWalletAdapter extends EventEmitter implements WalletAdapter { _provider: OpenLogin | undefined; @@ -18,19 +18,21 @@ export class TorusWalletAdapter extends EventEmitter implements WalletAdapter { name: string = ''; constructor(providerUrl: string, endpoint: string) { - super() - this.connect = this.connect.bind(this) + super(); + this.connect = this.connect.bind(this); this.endpoint = endpoint; this.providerUrl = providerUrl; } - async signAllTransactions(transactions: Transaction[]): Promise { - if(this.account) { + async signAllTransactions( + transactions: Transaction[], + ): Promise { + if (this.account) { let account = this.account; transactions.forEach(t => t.partialSign(account)); } - return transactions + return transactions; } get publicKey() { @@ -38,25 +40,27 @@ export class TorusWalletAdapter extends EventEmitter implements WalletAdapter { } async signTransaction(transaction: Transaction) { - if(this.account) { - transaction.partialSign(this.account) + if (this.account) { + transaction.partialSign(this.account); } - return transaction + return transaction; } connect = async () => { - const clientId = process.env.REACT_APP_CLIENT_ID || 'BNxdRWx08cSTPlzMAaShlM62d4f8Tp6racfnCg_gaH0XQ1NfSGo3h5B_IkLtgSnPMhlxsSvhqugWm0x8x-VkUXA'; + const clientId = + process.env.REACT_APP_CLIENT_ID || + 'BNxdRWx08cSTPlzMAaShlM62d4f8Tp6racfnCg_gaH0XQ1NfSGo3h5B_IkLtgSnPMhlxsSvhqugWm0x8x-VkUXA'; this._provider = new OpenLogin({ clientId, - network: "testnet", // mainnet, testnet, development - uxMode: 'popup' + network: 'testnet', // mainnet, testnet, development + uxMode: 'popup', }); try { await this._provider.init(); } catch (ex) { - console.error('init failed', ex) + console.error('init failed', ex); } console.error(this._provider?.state.store); @@ -67,28 +71,30 @@ export class TorusWalletAdapter extends EventEmitter implements WalletAdapter { this.account = new Account(secretKey); } else { try { - const { privKey } = await this._provider.login({ loginProvider: "unselected"} as any); + const { privKey } = await this._provider.login({ + loginProvider: 'unselected', + } as any); const secretKey = getSolanaPrivateKey(privKey); this.account = new Account(secretKey); - } catch(ex) { + } catch (ex) { console.error('login failed', ex); } } - this.name = this._provider?.state.store.get('name');; + this.name = this._provider?.state.store.get('name'); this.image = this._provider?.state.store.get('profileImage'); debugger; - this.emit("connect"); - } + this.emit('connect'); + }; disconnect = async () => { - console.log("Disconnecting...") + console.log('Disconnecting...'); if (this._provider) { await this._provider.logout(); await this._provider._cleanup(); this._provider = undefined; - this.emit("disconnect"); + this.emit('disconnect'); } - } + }; } From 3c66d0c624262f51c235009287725ab81e4b1742 Mon Sep 17 00:00:00 2001 From: bartosz-lipinski <264380+bartosz-lipinski@users.noreply.github.com> Date: Sat, 22 May 2021 15:32:56 -0500 Subject: [PATCH 04/95] feat: improve style and filter duplicate tokens --- .../bridge/src/components/Input/style.less | 5 +- .../src/components/TokenSelectModal/index.tsx | 71 ++++++++++++------- .../bridge/src/components/Transfer/index.tsx | 1 - .../bridge/src/components/Transfer/style.less | 11 ++- packages/bridge/src/utils/assets.ts | 10 ++- packages/bridge/src/views/help/index.less | 2 +- 6 files changed, 64 insertions(+), 36 deletions(-) diff --git a/packages/bridge/src/components/Input/style.less b/packages/bridge/src/components/Input/style.less index 6333a1c5..e6cbe969 100644 --- a/packages/bridge/src/components/Input/style.less +++ b/packages/bridge/src/components/Input/style.less @@ -119,7 +119,6 @@ font-weight: normal; font-size: 16px; line-height: 21px; - color: @tungsten-40; } .input-chain{ margin-top: 13px; @@ -151,7 +150,9 @@ padding: 0 36px 0 36px; font-size: 32px; line-height: 39px; - color: @tungsten-80; + ::placeholder { + color: @tungsten-40; + } height: 100%; } .input-select { diff --git a/packages/bridge/src/components/TokenSelectModal/index.tsx b/packages/bridge/src/components/TokenSelectModal/index.tsx index c5c1afc2..c53e2f06 100644 --- a/packages/bridge/src/components/TokenSelectModal/index.tsx +++ b/packages/bridge/src/components/TokenSelectModal/index.tsx @@ -9,6 +9,7 @@ import { TokenDisplay } from '../TokenDisplay'; import { ASSET_CHAIN } from '../../utils/assets'; import { useConnectionConfig } from '@oyster/common'; import { filterModalEthTokens, filterModalSolTokens } from '../../utils/assets'; +import { TokenInfo } from '@solana/spl-token-registry'; export const TokenSelectModal = (props: { onSelectToken: (token: string) => void; @@ -24,10 +25,18 @@ export const TokenSelectModal = (props: { const inputRef = useRef(null); const tokens = useMemo( - () => [ - ...filterModalEthTokens(ethTokens), - ...filterModalSolTokens(solTokens), - ], + () => { + const ethAddresses = ethTokens.reduce((set, t) => { + if(t.address) { + set.add(t.address.toLowerCase()); + } + return set; + }, new Set()); + return [ + ...filterModalEthTokens(ethTokens), + ...filterModalSolTokens(solTokens).filter(t => !ethAddresses.has((t?.extensions?.address || '').toLowerCase())), + ]; + }, [ethTokens, solTokens], ); @@ -62,15 +71,29 @@ export const TokenSelectModal = (props: { setSearch(val); }); + const getTokenInfo = (token: TokenInfo | undefined, chain: ASSET_CHAIN | undefined) => { + let name = token?.name || ''; + let symbol = token?.symbol || ''; + if (token && chain !== ASSET_CHAIN.Solana) { + if((token.tags || []).indexOf('wormhole') >= 0) { + name = name.replace('(Wormhole)', '').trim(); + symbol = symbol.startsWith('w') ? symbol.slice(1, symbol.length) : symbol; + } + } + + return { name, symbol }; + } + const rowRender = (rowProps: { index: number; key: string; style: any }) => { const token = tokenList[rowProps.index]; const mint = token.address; return [ASSET_CHAIN.Solana, ASSET_CHAIN.Ethereum].map((chain, index) => { + const { name , symbol } = getTokenInfo(token, chain); return (
{ props.onSelectToken(mint); props.onChain(chain); @@ -92,8 +115,8 @@ export const TokenSelectModal = (props: { className="multichain-option-name" style={{ marginLeft: '20px' }} > - {token.symbol} - {token.name} + {symbol} + {name}
@@ -101,27 +124,25 @@ export const TokenSelectModal = (props: { }); }; + const { name , symbol } = getTokenInfo(firstToken, props.chain); return ( <> - {firstToken ? ( -
showModal()} - style={{ cursor: 'pointer' }} - > -
- -
-
{firstToken.symbol}
- +
showModal()} + style={{ cursor: 'pointer' }} + > +
+
- ) : null} +
{symbol}
+ +
hideModal()} diff --git a/packages/bridge/src/components/Transfer/index.tsx b/packages/bridge/src/components/Transfer/index.tsx index 57924aee..8bacd441 100644 --- a/packages/bridge/src/components/Transfer/index.tsx +++ b/packages/bridge/src/components/Transfer/index.tsx @@ -113,7 +113,6 @@ export const Transfer = () => { className={'left'} /> - ); - else if (playing === Playstate.Playing) - return ; - else if (playing === Playstate.Error) - return ( - - ); - else return ; -} diff --git a/packages/governance/src/components/Proposal/MintSourceTokens.tsx b/packages/governance/src/components/Proposal/MintSourceTokens.tsx deleted file mode 100644 index 291f1d60..00000000 --- a/packages/governance/src/components/Proposal/MintSourceTokens.tsx +++ /dev/null @@ -1,280 +0,0 @@ -import { ParsedAccount } from '@oyster/common'; -import { Button, Modal, Input, Form, Progress, InputNumber, Radio } from 'antd'; -import React, { useState } from 'react'; -import { Governance } from '../../models/governance'; -import { utils, contexts } from '@oyster/common'; -import { PublicKey } from '@solana/web3.js'; -import { LABELS } from '../../constants'; -import { - SourceEntryInterface, - mintSourceTokens, -} from '../../actions/mintSourceTokens'; - -const { notify } = utils; -const { TextArea } = Input; -const { useWallet } = contexts.Wallet; -const { useConnection } = contexts.Connection; -const { deserializeAccount, useMint } = contexts.Accounts; - -const layout = { - labelCol: { span: 5 }, - wrapperCol: { span: 19 }, -}; - -export default function MintSourceTokens({ - governance, - useGovernance, -}: { - governance: ParsedAccount; - useGovernance: boolean; -}) { - const PROGRAM_IDS = utils.programIds(); - const wallet = useWallet(); - const connection = useConnection(); - const mintKey = useGovernance - ? governance.info.governanceMint - : governance.info.councilMint!; - const mint = useMint(mintKey); - const [saving, setSaving] = useState(false); - - const [isModalVisible, setIsModalVisible] = useState(false); - const [bulkModeVisible, setBulkModeVisible] = useState(false); - const [savePerc, setSavePerc] = useState(0); - const [failedSources, setFailedSources] = useState([]); - const [form] = Form.useForm(); - - const onSubmit = async (values: { - sourceHolders: string; - failedSources: string; - singleSourceHolder: string; - singleSourceCount: number; - }) => { - const { singleSourceHolder, singleSourceCount } = values; - const sourceHoldersAndCounts = values.sourceHolders - ? values.sourceHolders.split(',').map(s => s.trim()) - : []; - const sourceHolders: SourceEntryInterface[] = []; - let failedSourcesHold: SourceEntryInterface[] = []; - const zeroKey = PROGRAM_IDS.system; - sourceHoldersAndCounts.forEach((value: string, index: number) => { - if (index % 2 === 0) - sourceHolders.push({ - owner: value ? new PublicKey(value) : zeroKey, - tokenAmount: 0, - sourceAccount: undefined, - }); - else - sourceHolders[sourceHolders.length - 1].tokenAmount = parseInt(value); - }); - //console.log(sourceHolders); - - if (singleSourceHolder) - sourceHolders.push({ - owner: singleSourceHolder ? new PublicKey(singleSourceHolder) : zeroKey, - tokenAmount: singleSourceCount, - sourceAccount: undefined, - }); - - if (!sourceHolders.find(v => v.owner !== zeroKey)) { - notify({ - message: LABELS.ENTER_AT_LEAST_ONE_PUB_KEY, - type: 'error', - }); - return; - } - - if (sourceHolders.find(v => v.tokenAmount === 0)) { - notify({ - message: LABELS.CANT_GIVE_ZERO_TOKENS, - type: 'error', - }); - setSaving(false); - return; - } - - setSaving(true); - - const failedSourceCatch = (index: number, error: any) => { - if (error) console.error(error); - failedSourcesHold.push(sourceHolders[index]); - notify({ - message: sourceHolders[index].owner?.toBase58() + LABELS.PUB_KEY_FAILED, - type: 'error', - }); - }; - - const sourceHoldersToRun = []; - for (let i = 0; i < sourceHolders.length; i++) { - try { - if (sourceHolders[i].owner) { - const tokenAccounts = await connection.getTokenAccountsByOwner( - sourceHolders[i].owner || PROGRAM_IDS.governance, - { - programId: PROGRAM_IDS.token, - }, - ); - const specificToThisMint = tokenAccounts.value.find( - a => - deserializeAccount(a.account.data).mint.toBase58() === - mintKey.toBase58(), - ); - sourceHolders[i].sourceAccount = specificToThisMint?.pubkey; - sourceHoldersToRun.push(sourceHolders[i]); - } - } catch (e) { - failedSourceCatch(i, e); - } - } - - try { - await mintSourceTokens( - connection, - wallet.wallet, - governance, - useGovernance, - sourceHoldersToRun, - setSavePerc, - index => failedSourceCatch(index, null), - ); - } catch (e) { - console.error(e); - failedSourcesHold = sourceHolders; - } - - setFailedSources(failedSourcesHold); - setSaving(false); - setSavePerc(0); - setIsModalVisible(failedSourcesHold.length > 0); - if (failedSourcesHold.length === 0) form.resetFields(); - }; - return ( - <> - {mint?.mintAuthority?.toBase58() === - wallet.wallet?.publicKey?.toBase58() ? ( - - ) : null} - { - if (!saving) setIsModalVisible(false); - }} - > -
- {!saving && ( - <> - - - setBulkModeVisible(e.target.value === LABELS.BULK) - } - > - {LABELS.BULK} - - {LABELS.SINGLE} - - - - {!bulkModeVisible && ( - <> - - - - - - - - )} - {bulkModeVisible && ( - -