Skip to content
This repository has been archived by the owner on Jan 15, 2021. It is now read-only.

Commit

Permalink
Merge branch 'master' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
W3stside committed Oct 13, 2020
2 parents d690973 + 7bc5f66 commit 9d85aab
Show file tree
Hide file tree
Showing 26 changed files with 184 additions and 78 deletions.
6 changes: 6 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = {
parser: '@typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'eslint:recommended',
'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
'plugin:@typescript-eslint/recommended', // Uses the recommended rules from @typescript-eslint/eslint-plugin
'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
Expand Down Expand Up @@ -44,4 +45,9 @@ module.exports = {
globals: {
VERSION: true,
},
env: {
browser: true,
node: true,
jest: true,
},
}
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gnosis.pm/dex-react",
"version": "1.5.0-0",
"version": "1.5.0",
"description": "",
"main": "src/index.js",
"sideEffects": false,
Expand Down
3 changes: 2 additions & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,11 @@ function createTcrApi(web3: Web3): TcrApi | undefined {
case 'none':
tcrApi = undefined
break
case 'multi-tcr':
case 'multi-tcr': {
const multiTcrApiConfig = CONFIG.tcr
tcrApi = new MultiTcrApiProxy({ web3, ...multiTcrApiConfig.config })
break
}

default:
throw new Error('Unknown implementation for DexPriceEstimatorApi: ' + type)
Expand Down
20 changes: 19 additions & 1 deletion src/api/tokenList/TokenListApi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TokenDetails } from 'types'
import { Network, TokenDetails } from 'types'
import { getTokensByNetwork } from './tokenList'
import { logDebug } from 'utils'
import GenericSubscriptions, { SubscriptionsInterface } from './Subscriptions'
Expand All @@ -20,6 +20,9 @@ const addOverrideToDisabledTokens = (networkId: number) => (token: TokenDetails)
}

export interface TokenList extends SubscriptionsInterface<TokenDetails[]> {
setListReady: (state: boolean, networkId?: Network) => void
getIsListReady: () => boolean
isListReady: boolean
getTokens: (networkId: number) => TokenDetails[]
addToken: (params: AddTokenParams) => void
addTokens: (params: AddTokensParams) => void
Expand Down Expand Up @@ -64,6 +67,10 @@ export class TokenListApiImpl extends GenericSubscriptions<TokenDetails[]> imple
private _tokensByNetwork: { [networkId: number]: TokenDetails[] }
private _tokenAddressNetworkSet: Set<string>

// token list flag - prevents stale/incorrect data
// from being presented during token list calculation
public isListReady = true

public constructor({ networkIds, initialTokenList }: TokenListApiParams) {
super()

Expand Down Expand Up @@ -93,6 +100,17 @@ export class TokenListApiImpl extends GenericSubscriptions<TokenDetails[]> imple
})
}

public setListReady(state: boolean, networkId?: Network): void {
this.isListReady = state
if (this.isListReady && networkId) {
this.triggerSubscriptions(this._tokensByNetwork[networkId])
}
}

public getIsListReady(): boolean {
return this.isListReady
}

public hasToken(params: HasTokenParams): boolean {
return this._tokenAddressNetworkSet.has(TokenListApiImpl.constructAddressNetworkKey(params))
}
Expand Down
10 changes: 10 additions & 0 deletions src/api/tokenList/TokenListApiMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,18 @@ import GenericSubscriptions from './Subscriptions'
export class TokenListApiMock extends GenericSubscriptions<TokenDetails[]> implements TokenList {
private _tokenList: TokenDetails[]

public isListReady = false

public constructor(tokenList: TokenDetails[]) {
super()

this._tokenList = tokenList
}

public getIsListReady(): boolean {
return this.isListReady
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public getTokens(_networkId: number): TokenDetails[] {
return this._tokenList
Expand All @@ -34,6 +40,10 @@ export class TokenListApiMock extends GenericSubscriptions<TokenDetails[]> imple
this._tokenList = tokenList
this.triggerSubscriptions(tokenList)
}

public setListReady(state: boolean): void {
this.isListReady = state
}
}

export default TokenListApiMock
3 changes: 2 additions & 1 deletion src/api/wallet/WalletApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export interface WalletApi {
export interface WalletInfo {
isConnected: boolean
userAddress?: string
networkId?: number
networkId?: Network
blockNumber?: number
}

Expand Down Expand Up @@ -338,6 +338,7 @@ export class WalletApiImpl implements WalletApi {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
provider.handleReadRequests = async function (payload: unknown): Promise<unknown> {
if (payload && typeof payload === 'object' && 'skipCache' in payload) delete payload['skipCache']
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (!this.http) {
Expand Down
15 changes: 7 additions & 8 deletions src/components/OrderBookBtn.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect } from 'react'
import React from 'react'
import styled from 'styled-components'
import Modal, { useModal } from 'components/common/Modal'

Expand Down Expand Up @@ -115,19 +115,18 @@ export const OrderBookBtn: React.FC<OrderBookBtnProps> = (props: OrderBookBtnPro
const { baseToken: baseTokenDefault, quoteToken: quoteTokenDefault, label, className } = props
const { networkIdOrDefault: networkId } = useWalletConnection()
// get all tokens
const tokenList = useTokenList({ networkId })
const { tokens: tokenList } = useTokenList({ networkId })
const [baseToken, setBaseToken] = useSafeState<TokenDetails>(baseTokenDefault)
const [quoteToken, setQuoteToken] = useSafeState<TokenDetails>(quoteTokenDefault)
const networkDescription = networkId !== Network.Mainnet ? ` (${getNetworkFromId(networkId)})` : ''

// Update if any of the base tokens change
useEffect(() => {
setBaseToken(baseTokenDefault)
setQuoteToken(quoteTokenDefault)
}, [baseTokenDefault, quoteTokenDefault, setBaseToken, setQuoteToken])

const [modalHook, toggleModal] = useModal({
...DEFAULT_MODAL_OPTIONS,
onShow: () => {
// Update if any of the base tokens change
setBaseToken(baseTokenDefault)
setQuoteToken(quoteTokenDefault)
},
onHide: () => {
// Reset the selection on close
setBaseToken(baseTokenDefault)
Expand Down
2 changes: 1 addition & 1 deletion src/components/PoolingWidget/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ const PoolingInterface: React.FC = () => {

const { networkId, networkIdOrDefault, userAddress } = useWalletConnection()
// Get all the tokens for the current network
const tokenList = useTokenList({ networkId: networkIdOrDefault })
const { tokens: tokenList } = useTokenList({ networkId: networkIdOrDefault })

const tokens = useMemo(() => {
return (
Expand Down
16 changes: 15 additions & 1 deletion src/components/Settings/WalletConnect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ const WCSettingsSchema = Joi.object({
rpc: Joi.object({
mainnet: RPCSchema,
rinkeby: RPCSchema,
xDAI: RPCSchema,
}).empty({
mainnet: '',
rinkeby: '',
xDAI: '',
}),
})
.oxor('infuraId', 'rpc')
Expand Down Expand Up @@ -192,7 +194,7 @@ export const WCSettings: React.FC<WCSettingsProps> = ({ register, errors }) => {
<Disclaimer>
<p>
Here you can set the <strong>InfuraId</strong> or <strong>RPC URL</strong> that will be used for connecting
the WalletConnect provider to Mainnet and/or Rinkeby. It is also possible to set a custom WalletConnect{' '}
the WalletConnect provider to Mainnet, Rinkeby and/or xDAI. It is also possible to set a custom WalletConnect{' '}
<strong>Bridge URL</strong> to use instead of the default one.
</p>
</Disclaimer>
Expand Down Expand Up @@ -240,6 +242,18 @@ export const WCSettings: React.FC<WCSettingsProps> = ({ register, errors }) => {
<small className="inputLabel">RINKEBY </small>
</InputBox>
</InputContainer>
<InputContainer>
<InputBox>
<Input
type="text"
className="movingLabel"
name="walletconnect.rpc.xDAI"
ref={register}
placeholder="https://xdai.node_url"
/>
<small className="inputLabel">xDAI </small>
</InputBox>
</InputContainer>
</FormField>
<WCError errors={errors} name="rpc" />
</InnerFormSection>
Expand Down
3 changes: 2 additions & 1 deletion src/components/TokenOptionItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ const generateMessage = ({
case TokenFromExchange.NOT_ERC20:
return <>Not a valid ERC20 token</>
// registered but not in list --> option to add
case TokenFromExchange.NOT_IN_TOKEN_LIST:
case TokenFromExchange.NOT_IN_TOKEN_LIST: {
if (!token || !('id' in token)) return <>{defaultText}</>

const handleAddToken: React.MouseEventHandler<HTMLButtonElement> = async (e) => {
Expand All @@ -201,6 +201,7 @@ const generateMessage = ({
<button onClick={handleAddToken}>Add Token</button>
</OptionItem>
)
}
default:
return <>{defaultText}</>
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/TradeWidget/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ const TradeWidgetContainer: React.FC = () => {
const sellTokenSymbol = decodeSymbol(encodedSellTokenSymbol || '')
const receiveTokenSymbol = decodeSymbol(decodeReceiveTokenSymbol || '')

const { sellToken: initialSellTokenDefaultNetwork, buyToken: initialReceiveTokenDefaultNetwork } =
const { sellToken: initialSellTokenDefaultNetwork, receiveToken: initialReceiveTokenDefaultNetwork } =
initialTokenSelection.networks[networkIdOrDefault] || {}

const sellTokenWithFallback = useMemo(
Expand Down
1 change: 1 addition & 0 deletions src/components/TradesWidget/TradeRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export const TradeRow: React.FC<TradeRowProps> = (params) => {
return `${fillPercentage} matched out of ${orderAmount} ${displayTokenSymbolOrLink(sellToken)}`
}
}
// falls through
case 'liquidity':
case 'unknown':
default:
Expand Down
2 changes: 1 addition & 1 deletion src/components/UserWallet/UserWallet.styled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ export const NetworkTitle = styled.div`
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 0.3rem;
top: -0.6rem;
top: -0.8rem;
white-space: nowrap;
`

Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useManageTokens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ const SearchInput: React.FC<SearchInputProps> = (props) => {
const ManageTokensContainer: React.FC = () => {
const { networkId, networkIdOrDefault } = useWalletConnection()
// get all tokens
const tokens = useTokenList({ networkId })
const { tokens } = useTokenList({ networkId })

const [search, setSearch] = useState('')
const { value: debouncedSearch, setImmediate: setDebouncedSearch } = useDebounce(search, 500)
Expand Down
16 changes: 13 additions & 3 deletions src/hooks/useOrders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import useGlobalState from './useGlobalState'
import { useWalletConnection } from './useWalletConnection'
import usePendingOrders from './usePendingOrders'
import { useCheckWhenTimeRemainingInBatch } from './useTimeRemainingInBatch'
import { useTokenList } from './useTokenList'

// Constants/Types
import { REFRESH_WHEN_SECONDS_LEFT } from 'const'
Expand All @@ -32,6 +33,12 @@ export function useOrders(): Result {
dispatch,
] = useGlobalState()

// TODO: check this - currently in use for subscription
// to change in token list to trigger update of orders
// and the incorrect state shown sometimes when loading app from
// fresh state and seeing incorrect token list Issue #1486
const { tokens, isListReady } = useTokenList({ networkId })

// Pending Orders
const pendingOrders = usePendingOrders()

Expand All @@ -41,9 +48,11 @@ export function useOrders(): Result {
useEffect(() => {
// continue loading new orders
// from current offset
setIsLoading(true)
// make sure token list is ready before setting
isListReady && setIsLoading(true)

// whenever new block is mined
}, [blockNumber, setIsLoading])
}, [blockNumber, isListReady, setIsLoading])

useEffect(() => {
let cancelled = false
Expand Down Expand Up @@ -140,7 +149,8 @@ export function useOrders(): Result {
}
forceOrdersRefresh()
dispatch(overwriteOrders([]))
}, [userAddress, networkId, forceOrdersRefresh, dispatch])
// Subscribe to tokens change to force orders refresh
}, [tokens, userAddress, networkId, forceOrdersRefresh, dispatch])

return {
orders,
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useTokenBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export const useTokenBalances = (passOnParams: Partial<UseTokenListParams> = {})
const [error, setError] = useSafeState(false)

// get all tokens, maybe without deprecated
const tokens = useTokenList({ networkId: walletInfo.networkId, ...passOnParams })
const { tokens } = useTokenList({ networkId: walletInfo.networkId, ...passOnParams })

// Get token balances
useEffect(() => {
Expand Down
11 changes: 8 additions & 3 deletions src/hooks/useTokenList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,25 @@ import { TokenDetails } from 'types'
import useSafeState from './useSafeState'
import { getTokens, subscribeToTokenList } from 'services'
import { EMPTY_ARRAY } from 'const'
import { tokenListApi } from 'api'

export interface UseTokenListParams {
networkId?: number
excludeDeprecated?: boolean
}

export const useTokenList = ({ networkId, excludeDeprecated }: UseTokenListParams = {}): TokenDetails[] => {
export const useTokenList = ({ networkId, excludeDeprecated }: UseTokenListParams = {}): {
tokens: TokenDetails[]
isListReady: boolean
} => {
// sync get tokenList
const unfilteredTokens = networkId === undefined ? EMPTY_ARRAY : getTokens(networkId)

const tokens = useMemo(() => {
if (!excludeDeprecated) return unfilteredTokens
const filteredList = unfilteredTokens.filter((token) => !token.disabled)

return unfilteredTokens.filter((token) => !token.disabled)
return filteredList
}, [excludeDeprecated, unfilteredTokens])

// force update with a new value each time
Expand All @@ -26,5 +31,5 @@ export const useTokenList = ({ networkId, excludeDeprecated }: UseTokenListParam
return subscribeToTokenList(() => forceUpdate({}))
}, [forceUpdate])

return tokens
return { tokens, isListReady: tokenListApi.getIsListReady() }
}
4 changes: 2 additions & 2 deletions src/hooks/useWalletConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { BlockchainUpdatePrompt, WalletInfo } from 'api/wallet/WalletApi'

interface PendingStateObject extends WalletInfo {
pending: true
networkIdOrDefault: number
networkIdOrDefault: Network
}

const PendingState: PendingStateObject = {
Expand All @@ -33,7 +33,7 @@ const constructPendingState = ({ chainId, account, blockHeader }: BlockchainUpda
}

export const useWalletConnection = ():
| (WalletInfo & { pending: false; networkIdOrDefault: number })
| (WalletInfo & { pending: false; networkIdOrDefault: Network })
| PendingStateObject => {
const [walletInfo, setWalletInfo] = useSafeState<WalletInfo | null>(null)

Expand Down
2 changes: 1 addition & 1 deletion src/pages/OrderBook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const OrderBookWrapper = styled.div`
const OrderBook: React.FC = () => {
const { networkIdOrDefault } = useWalletConnection()
// get all tokens
const tokenList = useTokenList({ networkId: networkIdOrDefault })
const { tokens: tokenList } = useTokenList({ networkId: networkIdOrDefault })
const [baseToken, setBaseToken] = useSafeState<TokenDetails | null>(null)
const [quoteToken, setQuoteToken] = useSafeState<TokenDetails | null>(null)
const [hops, setHops] = useSafeState(ORDER_BOOK_HOPS_DEFAULT)
Expand Down
Loading

0 comments on commit 9d85aab

Please sign in to comment.