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

Commit

Permalink
Merge branch 'develop' of github.com:gnosis/dex-react into walletconn…
Browse files Browse the repository at this point in the history
…ect_update
  • Loading branch information
Velenir committed Jun 1, 2020
2 parents 1211069 + 619a3ef commit afe80dd
Show file tree
Hide file tree
Showing 51 changed files with 1,691 additions and 1,007 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ Develop:
 
[![Coverage Status](https://coveralls.io/repos/github/gnosis/dex-react/badge.svg?branch=develop)](https://coveralls.io/github/gnosis/dex-react?branch=develop)

# Mesa - a dapp for Gnosis Protocol
# Gnosis Protocol Web

<img align="right" width="350" src="./docs/screenshot.png">

Mesa is the first dapp built on the [Gnosis Protocol](https://docs.gnosis.io/protocol).
`Gnosis Protocol Web` is the first dapp built on the [Gnosis Protocol](https://docs.gnosis.io/protocol).

Gnosis Protocol is a fully permissionless DEX that enables ring trades to maximize liquidity.

Mesa allows users to:
`Gnosis Protocol Web` allows users to:

- Create orders in [Gnosis Protocol](https://docs.gnosis.io/protocol)
- See the balances for any token: available in their wallet and on the exchange
Expand Down Expand Up @@ -124,7 +124,7 @@ Both JSON and YAML formats are supported.

Simply replace any config found on [config-default](./config-default.yaml).

> NOTE: If you are forking the project, you might want to delete the [custom/.gitignore](custom/.gitignore) file so you
> **NOTE**: If you are forking the project, you might want to delete the [custom/.gitignore](custom/.gitignore) file so you
> can commit a config file and components inside the custom directory.
Below we provide details for each config.
Expand Down
3 changes: 1 addition & 2 deletions config-default.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
# - You can override in the custom file any config that is defined here
# - For redefining components, or for more information, follow the instructions in ./README.md

# TODO: Rename Dapp into Gnosis Protocol DApp
name: Mesa - Gnosis Protocol DApp
name: Gnosis Protocol Web

logoPath: './src/assets/img/logo.svg'

Expand Down
12 changes: 7 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gnosis.pm/dex-react",
"version": "0.11.1",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"sideEffects": false,
Expand Down Expand Up @@ -29,7 +29,7 @@
"@fortawesome/free-solid-svg-icons": "^5.12.0",
"@fortawesome/react-fontawesome": "^0.1.8",
"@gnosis.pm/dapp-ui": "^0.5.3",
"@gnosis.pm/dex-js": "0.3.0-RC.0",
"@gnosis.pm/dex-js": "^0.4.0",
"@hapi/joi": "^17.1.1",
"@hot-loader/react-dom": "^16.11.0",
"@popperjs/core": "^2.0.6",
Expand All @@ -42,6 +42,8 @@
"combine-reducers": "^1.0.0",
"date-fns": "^2.9.0",
"detect-browser": "^5.1.0",
"eth-json-rpc-middleware": "^4.4.1",
"json-rpc-engine": "^5.1.8",
"modali": "^1.2.0",
"node-cache": "^5.1.0",
"qrcode.react": "^1.0.0",
Expand All @@ -57,12 +59,12 @@
"web3": "^1.2.8"
},
"devDependencies": {
"@babel/core": "^7.8.4",
"@babel/core": "^7.9.4",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.8.3",
"@babel/preset-env": "^7.8.4",
"@babel/preset-react": "^7.8.3",
"@babel/preset-env": "^7.9.4",
"@babel/preset-react": "^7.9.4",
"@babel/register": "^7.8.3",
"@fortawesome/fontawesome-common-types": "^0.2.26",
"@types/bn.js": "^4.11.6",
Expand Down
17 changes: 4 additions & 13 deletions src/api/deposit/DepositApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,17 @@ export interface PendingFlux {

export interface DepositApiDependencies {
web3: Web3
fetchGasPrice(): Promise<string | undefined>
}

export class DepositApiImpl implements DepositApi {
protected _contractPrototype: BatchExchangeContract
protected web3: Web3
protected static _contractsCache: { [network: number]: BatchExchangeContract } = {}

protected fetchGasPrice: DepositApiDependencies['fetchGasPrice']

public constructor(injectedDependencies: DepositApiDependencies) {
Object.assign(this, injectedDependencies)

this._contractPrototype = new this.web3.eth.Contract(batchExchangeAbi) as BatchExchangeContract
this._contractPrototype = (new this.web3.eth.Contract(batchExchangeAbi) as unknown) as BatchExchangeContract

// TODO remove later
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -142,9 +139,7 @@ export class DepositApiImpl implements DepositApi {
}: DepositParams): Promise<Receipt> {
const contract = await this._getContract(networkId)
// TODO: Remove temporal fix for web3. See https://github.com/gnosis/dex-react/issues/231
const tx = contract.methods
.deposit(tokenAddress, amount.toString())
.send({ from: userAddress, gasPrice: await this.fetchGasPrice() })
const tx = contract.methods.deposit(tokenAddress, amount.toString()).send({ from: userAddress })

if (txOptionalParams?.onSentTransaction) {
tx.once('transactionHash', txOptionalParams.onSentTransaction)
Expand All @@ -163,9 +158,7 @@ export class DepositApiImpl implements DepositApi {
}: RequestWithdrawParams): Promise<Receipt> {
const contract = await this._getContract(networkId)
// TODO: Remove temporal fix for web3. See https://github.com/gnosis/dex-react/issues/231
const tx = contract.methods
.requestWithdraw(tokenAddress, amount.toString())
.send({ from: userAddress, gasPrice: await this.fetchGasPrice() })
const tx = contract.methods.requestWithdraw(tokenAddress, amount.toString()).send({ from: userAddress })

if (txOptionalParams?.onSentTransaction) {
tx.once('transactionHash', txOptionalParams.onSentTransaction)
Expand All @@ -179,9 +172,7 @@ export class DepositApiImpl implements DepositApi {

public async withdraw({ userAddress, tokenAddress, networkId, txOptionalParams }: WithdrawParams): Promise<Receipt> {
const contract = await this._getContract(networkId)
const tx = contract.methods
.withdraw(userAddress, tokenAddress)
.send({ from: userAddress, gasPrice: await this.fetchGasPrice() })
const tx = contract.methods.withdraw(userAddress, tokenAddress).send({ from: userAddress })

if (txOptionalParams?.onSentTransaction) {
tx.once('transactionHash', txOptionalParams.onSentTransaction)
Expand Down
24 changes: 24 additions & 0 deletions src/api/earmark.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { logDebug } from 'utils'

// 0.1 Gwei, reasonable gasPrice that would still allow flags replacement
export const MIN_GAS_PRICE = (1e8).toString(10)

export const earmarkGasPrice = (gasPrice: string, userPrint: string): string => {
if (!userPrint) return gasPrice

// don't replace 8000 -> 1201, only if most significant digit is untouched
// 80000 -> 81201
if (userPrint.length >= gasPrice.length) {
// if flags still don't fit even in MIN_GAS_PRICE
if (userPrint.length >= MIN_GAS_PRICE.length) return gasPrice
gasPrice = MIN_GAS_PRICE
}

const markedGasPrice = gasPrice.slice(0, -userPrint.length) + userPrint

logDebug('Gas price', gasPrice, '->', markedGasPrice)
return markedGasPrice
}

// simple concatenation, with '0x' for empty data to have `0x<userPrint>` at the least
export const earmarkTxData = (data = '0x', userPrint: string): string => data + userPrint
10 changes: 2 additions & 8 deletions src/api/erc20/Erc20Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { TxOptionalParams, Receipt } from 'types'
import { ZERO } from 'const'
import { toBN } from 'utils'

import ERC20_DETAILS from './erc20Details.json'
import ERC20_DETAILS from 'api/erc20/erc20Details.json'

import Web3 from 'web3'

Expand Down Expand Up @@ -80,7 +80,6 @@ export interface Erc20Api {

export interface Erc20ApiDependencies {
web3: Web3
fetchGasPrice(): Promise<string | undefined>
}

/**
Expand All @@ -93,8 +92,6 @@ export class Erc20ApiImpl implements Erc20Api {

private static _contractsCache: { [network: number]: { [address: string]: Erc20Contract } } = {}

private fetchGasPrice: Erc20ApiDependencies['fetchGasPrice']

public constructor(injectedDependencies: Erc20ApiDependencies) {
Object.assign(this, injectedDependencies)

Expand All @@ -103,7 +100,7 @@ export class Erc20ApiImpl implements Erc20Api {
// and return symbol/name as bytes32 as opposed to string
this.localErc20Details = ERC20_DETAILS

this._contractPrototype = new this.web3.eth.Contract(erc20Abi as AbiItem[]) as Erc20Contract
this._contractPrototype = (new this.web3.eth.Contract(erc20Abi as AbiItem[]) as unknown) as Erc20Contract

// TODO remove later
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -186,7 +183,6 @@ export class Erc20ApiImpl implements Erc20Api {
// TODO: Remove temporal fix for web3. See https://github.com/gnosis/dex-react/issues/231
const tx = erc20.methods.approve(spenderAddress, amount.toString()).send({
from: userAddress,
gasPrice: await this.fetchGasPrice(),
})

if (txOptionalParams?.onSentTransaction) {
Expand All @@ -209,7 +205,6 @@ export class Erc20ApiImpl implements Erc20Api {
// TODO: Remove temporal fix for web3. See https://github.com/gnosis/dex-react/issues/231
const tx = erc20.methods.transfer(toAddress, amount.toString()).send({
from: userAddress,
gasPrice: await this.fetchGasPrice(),
})

if (txOptionalParams?.onSentTransaction) {
Expand All @@ -232,7 +227,6 @@ export class Erc20ApiImpl implements Erc20Api {

const tx = erc20.methods.transferFrom(userAddress, toAddress, amount.toString()).send({
from: fromAddress,
gasPrice: await this.fetchGasPrice(),
})

if (txOptionalParams?.onSentTransaction) {
Expand Down
8 changes: 4 additions & 4 deletions src/api/exchange/ExchangeApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ export class ExchangeApiImpl extends DepositApiImpl implements ExchangeApi {

public async addToken({ userAddress, tokenAddress, networkId, txOptionalParams }: AddTokenParams): Promise<Receipt> {
const contract = await this._getContract(networkId)
const tx = contract.methods.addToken(tokenAddress).send({ from: userAddress, gasPrice: await this.fetchGasPrice() })
const tx = contract.methods.addToken(tokenAddress).send({ from: userAddress })

if (txOptionalParams?.onSentTransaction) {
tx.once('transactionHash', txOptionalParams.onSentTransaction)
Expand Down Expand Up @@ -219,7 +219,7 @@ export class ExchangeApiImpl extends DepositApiImpl implements ExchangeApi {
// TODO: Remove temporal fix for web3. See https://github.com/gnosis/dex-react/issues/231
const tx = contract.methods
.placeOrder(buyTokenId, sellTokenId, validUntil, buyAmount.toString(), sellAmount.toString())
.send({ from: userAddress, gasPrice: await this.fetchGasPrice() })
.send({ from: userAddress })

if (txOptionalParams?.onSentTransaction) {
tx.once('transactionHash', txOptionalParams.onSentTransaction)
Expand Down Expand Up @@ -260,7 +260,7 @@ export class ExchangeApiImpl extends DepositApiImpl implements ExchangeApi {

const tx = contract.methods
.placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmountsStr, sellAmountsStr)
.send({ from: userAddress, gasPrice: await this.fetchGasPrice() })
.send({ from: userAddress })

if (txOptionalParams?.onSentTransaction) {
tx.once('transactionHash', txOptionalParams.onSentTransaction)
Expand All @@ -286,7 +286,7 @@ export class ExchangeApiImpl extends DepositApiImpl implements ExchangeApi {
txOptionalParams,
}: CancelOrdersParams): Promise<Receipt> {
const contract = await this._getContract(networkId)
const tx = contract.methods.cancelOrders(orderIds).send({ from: userAddress, gasPrice: await this.fetchGasPrice() })
const tx = contract.methods.cancelOrders(orderIds).send({ from: userAddress })

if (txOptionalParams?.onSentTransaction) {
tx.once('transactionHash', txOptionalParams.onSentTransaction)
Expand Down
25 changes: 2 additions & 23 deletions src/api/gasStation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { WalletApi } from './wallet/WalletApi'
import { logDebug } from 'utils'

const GAS_STATIONS = {
1: 'https://safe-relay.gnosis.pm/api/v1/gas-station/',
Expand Down Expand Up @@ -27,26 +26,6 @@ interface GasStationResponse {
fastest: string
}

// 0.1 Gwei, reasonable gasPrice that would still allow flags replacement
export const MIN_GAS_PRICE = (1e8).toString(10)

export const earmarkGasPrice = (gasPrice: string, userPrint: string): string => {
if (!userPrint) return gasPrice

// don't replace 8000 -> 1201, only if most significant digit is untouched
// 80000 -> 81201
if (userPrint.length >= gasPrice.length) {
// if flags still don't fit even in MIN_GAS_PRICE
if (userPrint.length >= MIN_GAS_PRICE.length) return gasPrice
gasPrice = MIN_GAS_PRICE
}

const markedGasPrice = gasPrice.slice(0, -userPrint.length) + userPrint

logDebug('Gas price', gasPrice, '->', markedGasPrice)
return markedGasPrice
}

const fetchGasPriceFactory = (walletApi: WalletApi) => async (): Promise<string | undefined> => {
const { blockchainState } = walletApi

Expand All @@ -57,7 +36,7 @@ const fetchGasPriceFactory = (walletApi: WalletApi) => async (): Promise<string
// only fetch new gasPrice when chainId or blockNumber changed
const key = constructKey({ chainId, blockNumber: blockHeader && blockHeader.number })
if (key === cacheKey) {
return earmarkGasPrice(cachedGasPrice, await walletApi.userPrintAsync)
return cachedGasPrice
}

const gasStationURL = GAS_STATIONS[chainId]
Expand All @@ -73,7 +52,7 @@ const fetchGasPriceFactory = (walletApi: WalletApi) => async (): Promise<string
cacheKey = key
cachedGasPrice = gasPrice

return earmarkGasPrice(gasPrice, await walletApi.userPrintAsync)
return gasPrice
}
} catch (error) {
console.error('[api:gasStation] Error fetching gasPrice from', gasStationURL, error)
Expand Down
6 changes: 1 addition & 5 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import {
} from '../../test/data'
import Web3 from 'web3'
import { ETH_NODE_URL } from 'const'
import fetchGasPriceFactory from './gasStation'

// TODO connect to mainnet if we need AUTOCONNECT at all
export const getDefaultProvider = (): string | null => (process.env.NODE_ENV === 'test' ? null : ETH_NODE_URL)
Expand Down Expand Up @@ -183,10 +182,7 @@ function createTcrApi(web3: Web3): TcrApi | undefined {
export const web3: Web3 = createWeb3Api()
export const walletApi: WalletApi = createWalletApi(web3)

const injectedDependencies = {
web3,
fetchGasPrice: fetchGasPriceFactory(walletApi),
}
const injectedDependencies = { web3 }

export const erc20Api: Erc20Api = createErc20Api(injectedDependencies)
export const wethApi: WethApi = createWethApi(injectedDependencies)
Expand Down
2 changes: 1 addition & 1 deletion src/api/tcr/MultiTcrApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class MultiTcrApi implements TcrApi {

this.web3 = web3

const contractPrototype = new this.web3.eth.Contract(tcrAbi as AbiItem[]) as TcrContract
const contractPrototype = (new this.web3.eth.Contract(tcrAbi as AbiItem[]) as unknown) as TcrContract

lists.forEach(list => {
const contract = contractPrototype.clone()
Expand Down
3 changes: 1 addition & 2 deletions src/api/tokenList/TokenListApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,10 @@ export class TokenListApiImpl extends GenericSubscriptions<TokenDetails[]> imple
public addTokens({ tokens, networkId }: AddTokensParams): void {
const addedTokens: TokenDetails[] = []
tokens.forEach(token => {
logDebug('[TokenListApi]: Added new Token to userlist', token)

const key = TokenListApiImpl.constructAddressNetworkKey({ tokenAddress: token.address, networkId })

if (this._tokenAddressNetworkSet.has(key)) return
logDebug('[TokenListApi]: Added new Token to userlist', token)

this._tokenAddressNetworkSet.add(key)
addedTokens.push(token)
Expand Down
14 changes: 11 additions & 3 deletions src/api/wallet/WalletApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ import {
Subscriptions,
} from '@gnosis.pm/dapp-ui'

import { logDebug, toBN, gasPriceEncoder } from 'utils'
import { logDebug, toBN, txDataEncoder } from 'utils'
import { INFURA_ID } from 'const'

import { subscribeToWeb3Event } from './subscriptionHelpers'
import { getMatchingScreenSize, subscribeToScreenSizeChange } from 'utils/mediaQueries'
import { composeProvider } from './composeProvider'
import fetchGasPriceFactory from 'api/gasStation'
import { earmarkTxData } from 'api/earmark'

export interface WalletApi {
isConnected(): boolean | Promise<boolean>
Expand Down Expand Up @@ -244,8 +247,13 @@ export class WalletApiImpl implements WalletApi {

closeOpenWebSocketConnection(this._web3)

const fetchGasPrice = fetchGasPriceFactory(this)
const earmarkingFunction = async (data?: string): Promise<string> => earmarkTxData(data, await this.userPrintAsync)

const composedProvider = composeProvider(provider, { fetchGasPrice, earmarkTxData: earmarkingFunction })

// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._web3.setProvider(provider as any)
this._web3.setProvider(composedProvider as any)
logDebug('[WalletApiImpl] Connected')

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -471,7 +479,7 @@ export class WalletApiImpl implements WalletApi {
screenSize,
}

const encoded = gasPriceEncoder(flagObject)
const encoded = txDataEncoder(flagObject)

logDebug('Encoded object', flagObject)
logDebug('User Wallet print', encoded)
Expand Down
Loading

0 comments on commit afe80dd

Please sign in to comment.