Skip to content
This repository was archived by the owner on Feb 18, 2020. It is now read-only.

Commit d0fa016

Browse files
authored
Merge pull request #53 from gnosis/refactor/dutchX
Refactor/dutch x
2 parents c0accc8 + f79f224 commit d0fa016

File tree

23 files changed

+790
-449
lines changed

23 files changed

+790
-449
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@
6464
]
6565
},
6666
"dependencies": {
67+
"@types/bignumber.js": "^4.0.3",
6768
"autobind-decorator": "^2.1.0",
6869
"await-delay": "^1.0.0",
6970
"babel-polyfill": "^6.23.0",

src/actions/balance.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,15 @@
11
/* eslint no-console: 0 */
22
// import thunk from 'redux-thunk'
33
import { createAction } from 'redux-actions'
4-
import { getDutchXConnection } from '../api/dutchx'
4+
import { getCurrentBalance } from '../api'
55

66
export const getBalanceBase: Function = createAction('GET_CONTRACT_BALANCE')
77

8-
export const getBalance = (contract: string, address: string) => async (dispatch: Function) => {
8+
export const getBalance = (address: string) => async (dispatch: Function) => {
99
// console.log(contract)
10-
let inst
11-
let dutchX
1210

1311
try {
14-
dutchX = await getDutchXConnection()
15-
inst = await dutchX[contract]
16-
const reqBalance = await inst.getBalance.call(address)
12+
const reqBalance = (await getCurrentBalance(address)).toString()
1713
console.log(`Success! Balance for ${address} = `, reqBalance)
1814
dispatch(getBalanceBase({ success: true, reqBalance }))
1915
} catch (err) {

src/actions/blockchain.ts

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,27 @@
22
import {
33
getCurrentBalance,
44
getCurrentAccount,
5-
initDutchXConnection,
5+
// initDutchXConnection,
66
getTokenBalances,
77
// tokenPairSelect,
88
postSellOrder,
99
closingPrice,
10-
} from 'api/dutchx'
10+
} from 'api'
1111

1212
import { setClosingPrice } from 'actions/ratioPairs'
1313
import { setTokenBalance } from 'actions/tokenBalances'
1414
import { setSellTokenAmount } from 'actions/tokenPair'
1515

16-
import { timeoutCondition, getDutchXOptions } from '../utils/helpers'
16+
import {
17+
timeoutCondition,
18+
// getDutchXOptions,
19+
} from '../utils/helpers'
1720
// import { GAS_COST } from 'utils/constants'
1821
import { createAction } from 'redux-actions'
1922
import { push } from 'connected-react-router'
2023
import { findDefaultProvider } from 'selectors/blockchain'
2124

22-
import { TokenBalances } from 'types'
25+
import { TokenBalances, Account, Balance, TokenCode } from 'types'
2326

2427
export enum TypeKeys {
2528
SET_GNOSIS_CONNECTION = 'SET_GNOSIS_CONNECTION',
@@ -39,7 +42,7 @@ export const setConnectionStatus = createAction<{ connected?: boolean }>('SET_CO
3942
export const setActiveProvider = createAction<{ provider?: string }>('SET_ACTIVE_PROVIDER')
4043
export const registerProvider = createAction<{ provider?: string, data?: Object }>('REGISTER_PROVIDER')
4144
export const updateProvider = createAction<{ provider?: string, data?: Object }>('UPDATE_PROVIDER')
42-
export const setCurrentBalance = createAction<{ provider?: string, currentBalance?: number }>('SET_CURRENT_BALANCE')
45+
export const setCurrentBalance = createAction<{ provider?: string, currentBalance?: Balance }>('SET_CURRENT_BALANCE')
4346
export const setCurrentAccountAddress =
4447
createAction<{ provider?: string, currentAccount?: Object }>('SET_CURRENT_ACCOUNT_ADDRESS')
4548
export const fetchTokens = createAction<{ tokens?: TokenBalances }>('FETCH_TOKENS')
@@ -59,13 +62,13 @@ export const initDutchX = () => async (dispatch: Function, getState: any) => {
5962
const state = getState()
6063

6164
// determine new provider
62-
const newProvider = findDefaultProvider(state)
65+
const newProvider: any = findDefaultProvider(state)
6366
if (newProvider) {
6467
await dispatch(setActiveProvider(newProvider.name))
6568

6669
// init DutchX connection
67-
const opts = getDutchXOptions(newProvider)
68-
await initDutchXConnection(opts)
70+
// const opts = getDutchXOptions(newProvider)
71+
// await initDutchXConnection(opts)
6972
dispatch(setDutchXInitialized({ initialized: true }))
7073
// await requestEtherTokens()
7174
}
@@ -76,16 +79,19 @@ export const initDutchX = () => async (dispatch: Function, getState: any) => {
7679

7780
// connect
7881
try {
79-
let account: any
80-
let currentBalance: any
81-
let tokenBalance: any
82+
let account: Account
83+
let currentBalance: Balance
84+
let tokenBalances: { name: TokenCode, balance: Balance }[]
8285

8386
// runs test executions on gnosisjs
8487
const getConnection = async () => {
8588
try {
8689
account = await getCurrentAccount()
87-
currentBalance = await getCurrentBalance(account)
88-
tokenBalance = await getTokenBalances(account)
90+
currentBalance = (await getCurrentBalance(account)).toString()
91+
// TODO: pass a list of tokens from state or globals, for now ['ETH', 'GNO'] is default
92+
tokenBalances = (await getTokenBalances(undefined, account))
93+
.map(({ name, balance }) => ({ name, balance: balance.toString() }))
94+
console.log(tokenBalances)
8995
await dispatch(getClosingPrice())
9096
} catch (e) {
9197
console.log(e)
@@ -98,7 +104,7 @@ export const initDutchX = () => async (dispatch: Function, getState: any) => {
98104
await dispatch(setCurrentBalance({ currentBalance }))
99105

100106
// Grab each TokenBalance and dispatch
101-
tokenBalance.forEach(async (token: any) =>
107+
tokenBalances.forEach(async token =>
102108
await dispatch(setTokenBalance({ tokenName: token.name, balance: token.balance })))
103109

104110
return dispatch(setConnectionStatus({ connected: true }))
@@ -132,12 +138,12 @@ export const submitSellOrder = (proceedTo: string) => async (dispatch: Function,
132138

133139
console.log('Submit order receipt', receipt)
134140

135-
// TODO: function to get specific Token's balance, also actions for such functions
136-
const tokenBalances = await getTokenBalances(currentAccount)
141+
// TODO: pass a list of tokens from state or globals, for now ['ETH', 'GNO'] is default
142+
const tokenBalances = await getTokenBalances(undefined, currentAccount)
137143
const { name, balance } = tokenBalances.find(({ name }) => name === sell)
138144

139145
// new balance for the token just sold
140-
dispatch(setTokenBalance({ tokenName: name, balance }))
146+
dispatch(setTokenBalance({ tokenName: name, balance: balance.toString() }))
141147

142148
// proceed to /auction/0x03494929349594
143149
dispatch(push(proceedTo))

src/actions/tokenOverlay.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { createAction } from 'redux-actions'
22
import { TokenMod, TokenCode, TokenPair } from 'types'
33

4-
import { closingPrice } from 'api/dutchx'
4+
import { closingPrice } from 'api/'
55
import { setClosingPrice } from 'actions/ratioPairs'
66

77
export const openOverlay = createAction<{ mod: TokenMod }>('OPEN_OVERLAY')
@@ -13,7 +13,7 @@ export const selectTokenPairAndRatioPair = (props: any) => async (dispatch: Func
1313
const { tokenPair } = getState()
1414
const { code, mod } = props
1515
const { sell, buy }: TokenPair = { ...tokenPair, [mod]: code }
16-
16+
1717
try {
1818
const price = (await closingPrice(sell, buy)).toString()
1919

src/actions/tokenPair.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { createAction } from 'redux-actions'
22
import { TokenPair } from 'types'
33

4-
import { closingPrice } from 'api/dutchx'
4+
import { closingPrice } from 'api/'
55
import { setClosingPrice } from 'actions/ratioPairs'
66

77
export const selectTokenPair = createAction<TokenPair>('SELECT_TOKEN_PAIR')

src/api/DutchX.ts

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
import { promisedContractsMap } from './contracts'
2+
import { promisedWeb3 } from './web3Provider'
3+
import { DutchExchange } from './types'
4+
import { TokenPair, Account, Balance } from 'types'
5+
6+
export const promisedDutchX = init()
7+
8+
const getCurrentAccount = async () => {
9+
const web3 = await promisedWeb3
10+
11+
return web3.getCurrentAccount()
12+
}
13+
14+
async function init(): Promise<DutchExchange> {
15+
const contractsMap = await promisedContractsMap
16+
17+
const getExchange = ({ sell, buy }: TokenPair) => {
18+
const exchange = contractsMap[`DutchExchange${sell}${buy}`]
19+
20+
if (!exchange) throw new Error(`No DutchExchange contract for ${sell}->${buy} token pair`)
21+
22+
return exchange
23+
}
24+
25+
const fillDefaultIndexAndAccount = (pair: TokenPair, index: number, account: Account) => Promise.all([
26+
index === undefined ? getAuctionIndex(pair) : index,
27+
account === undefined ? getCurrentAccount() : account,
28+
])
29+
30+
const getAddress = (pair: TokenPair) => getExchange(pair).address
31+
32+
const getAuctionIndex = async (pair: TokenPair) => getExchange(pair).auctionIndex()
33+
34+
const getAuctionStart = async (pair: TokenPair) => getExchange(pair).auctionStart()
35+
36+
const getClosingPrice = async (pair: TokenPair, index?: number) => {
37+
if (index === undefined) index = await getAuctionIndex(pair) - 1
38+
39+
return getExchange(pair).closingPrices(index)
40+
}
41+
42+
const getPrice = async (pair: TokenPair, index?: number) => {
43+
if (index === undefined) index = await getAuctionIndex(pair)
44+
45+
return getExchange(pair).getPrice(index)
46+
}
47+
48+
const getSellVolumeCurrent = async (pair: TokenPair) => getExchange(pair).sellVolumeCurrent()
49+
50+
const getSellVolumeNext = (pair: TokenPair) => getExchange(pair).sellVolumeNext()
51+
52+
const getBuyVolume = async (pair: TokenPair, index?: number) => {
53+
if (index === undefined) index = await getAuctionIndex(pair)
54+
55+
return getExchange(pair).buyVolumes(index)
56+
}
57+
58+
const getSellerBalance = async (pair: TokenPair, index?: number, account?: Account) => {
59+
[index, account] = await fillDefaultIndexAndAccount(pair, index, account)
60+
61+
return getExchange(pair).sellerBalances(index, account)
62+
}
63+
64+
const getBuyerBalance = async (pair: TokenPair, index?: number, account?: Account) => {
65+
[index, account] = await fillDefaultIndexAndAccount(pair, index, account)
66+
67+
return getExchange(pair).buyerBalances(index, account)
68+
}
69+
70+
const getClaimedAmount = async (pair: TokenPair, index?: number, account?: Account) => {
71+
[index, account] = await fillDefaultIndexAndAccount(pair, index, account)
72+
73+
return getExchange(pair).claimedAmounts(index, account)
74+
}
75+
76+
const postSellOrder = async (pair: TokenPair, amount: Balance, account?: Account) => {
77+
if (account === undefined) account = await getCurrentAccount()
78+
79+
return getExchange(pair).postSellOrder(amount, { from: account, gas: 4712388 })
80+
}
81+
82+
const postBuyOrder = async (pair: TokenPair, amount: Balance, index?: number, account?: Account) => {
83+
[index, account] = await fillDefaultIndexAndAccount(pair, index, account)
84+
85+
return getExchange(pair).postBuyOrder(amount, index, { from: account, gas: 4712388 })
86+
}
87+
88+
const postBuyOrderAndClaim = async (pair: TokenPair, amount: Balance, index?: number, account?: Account) => {
89+
[index, account] = await fillDefaultIndexAndAccount(pair, index, account)
90+
91+
return getExchange(pair).postBuyorderAndClaim(amount, index, { from: account, gas: 4712388 })
92+
}
93+
94+
const claimSellerFunds = async (pair: TokenPair, index?: number, account?: Account) => {
95+
[index, account] = await fillDefaultIndexAndAccount(pair, index, account)
96+
97+
return getExchange(pair).claimSellerFunds(index, { from: account })
98+
}
99+
100+
const claimBuyerFunds = async (pair: TokenPair, index?: number, account?: Account) => {
101+
[index, account] = await fillDefaultIndexAndAccount(pair, index, account)
102+
103+
return getExchange(pair).claimBuyerFunds(index, { from: account })
104+
}
105+
106+
return {
107+
getAddress,
108+
getAuctionIndex,
109+
getAuctionStart,
110+
getClosingPrice,
111+
getPrice,
112+
getSellVolumeCurrent,
113+
getSellVolumeNext,
114+
getBuyVolume,
115+
getSellerBalance,
116+
getBuyerBalance,
117+
getClaimedAmount,
118+
postSellOrder,
119+
postBuyOrder,
120+
postBuyOrderAndClaim,
121+
claimSellerFunds,
122+
claimBuyerFunds,
123+
}
124+
}

src/api/Tokens.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { TokensInterface, TransactionObject } from './types'
2+
import { Account, Balance, TokenCode } from 'types'
3+
import { promisedContractsMap } from './contracts'
4+
5+
export const promisedTokens = init()
6+
7+
async function init(): Promise<TokensInterface> {
8+
9+
const contractsMap = await promisedContractsMap
10+
11+
const getToken = (code: TokenCode) => {
12+
const token = contractsMap[`Token${code}`]
13+
14+
if (!token) throw new Error(`No Token contract for ${code} token`)
15+
16+
return token
17+
}
18+
19+
const getTokenBalance = async (code: TokenCode, account: Account) => getToken(code).balanceOf(account)
20+
21+
const getTotalSupply = async (code: TokenCode) => getToken(code).getTotalSupply()
22+
23+
const transfer = (code: TokenCode, to: Account, value: Balance, tx: TransactionObject) =>
24+
getToken(code).transfer(to, value, tx)
25+
26+
const transferFrom = (code: TokenCode, from: Account, to: Account, value: Balance, tx: TransactionObject) =>
27+
getToken(code).transferFrom(from, to, value, tx)
28+
29+
const approve = (code: TokenCode, spender: Account, value: Balance, tx: TransactionObject) =>
30+
getToken(code).approve(spender, value, tx)
31+
32+
const allowance = async (code: TokenCode, owner: Account, spender: Account) =>
33+
getToken(code).allowance(owner, spender)
34+
35+
return {
36+
getTokenBalance,
37+
getTotalSupply,
38+
transfer,
39+
transferFrom,
40+
approve,
41+
allowance,
42+
}
43+
}

src/api/contracts.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import TruffleContract from 'truffle-contract'
2+
import { promisedWeb3 } from './web3Provider'
3+
4+
const contractNames = [
5+
'DutchExchange',
6+
'DutchExchangeETHGNO',
7+
'DutchExchangeGNOETH',
8+
'Token',
9+
'TokenETH',
10+
'TokenGNO',
11+
]
12+
13+
type ContractName = 'DutchExchange' |
14+
'DutchExchangeETHGNO' |
15+
'DutchExchangeGNOETH' |
16+
'Token' |
17+
'TokenETH' |
18+
'TokenGNO'
19+
20+
type ContractsMap = {[P in ContractName]: any}
21+
22+
const Contracts = contractNames.map(name => TruffleContract(require(`../../build/contracts/${name}.json`)))
23+
24+
// name => contract mapping
25+
export const contractsMap = contractNames.reduce((acc, name, i) => {
26+
acc[name] = Contracts[i]
27+
return acc
28+
}, {}) as ContractsMap
29+
30+
export const setProvider = (provider: any) => Contracts.forEach((contract) => {
31+
contract.setProvider(provider)
32+
})
33+
34+
const getPromisedIntances = () => Promise.all(Contracts.map(contr => contr.deployed()))
35+
36+
export const promisedContractsMap = init()
37+
38+
async function init() {
39+
const { currentProvider } = await promisedWeb3
40+
setProvider(currentProvider)
41+
42+
const instances = await getPromisedIntances()
43+
44+
// name => contract instance mapping
45+
// e.g. TokenETH => deployed TokenETH contract
46+
return contractNames.reduce((acc, name, i) => {
47+
acc[name] = instances[i]
48+
return acc
49+
}, {}) as ContractsMap
50+
}

0 commit comments

Comments
 (0)