/
eth.js
186 lines (151 loc) · 5.4 KB
/
eth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import helpers, { apiLooper, constants, api, cacheStorageGet, cacheStorageSet } from 'helpers'
import { getState } from 'redux/core'
import actions from 'redux/actions'
import web3 from 'helpers/web3'
import reducers from 'redux/core/reducers'
import config from 'app-config'
import referral from './referral'
import { web3Override } from 'keychain.js'
import { pubToAddress } from 'ethereumjs-util'
const login = (privateKey) => {
let data
if (privateKey) {
data = web3.eth.accounts.privateKeyToAccount(privateKey)
}
else {
console.info('Created account Ethereum ...')
data = web3.eth.accounts.create()
}
localStorage.setItem(constants.privateKeyNames.eth, data.privateKey)
web3.eth.accounts.wallet.add(data.privateKey)
reducers.user.setAuthData({ name: 'ethData', data })
window.getEthAddress = () => data.address
referral.newReferral(data.address)
console.info('Logged in with Ethereum', data)
return data.privateKey
}
const loginWithKeychain = async () => {
const web3OverrideFunctions = web3Override(web3)
web3.eth.accounts.sign = web3OverrideFunctions.sign
web3.eth.accounts.signTransaction = web3OverrideFunctions.signTransaction
const selectedKey = await actions.keychain.login('ETH')
if (!selectedKey) { // user cancelled key selection or other error
return null
}
const data = { privateKey: selectedKey, address: `0x${pubToAddress(`0x${selectedKey}`).toString('hex')}` }
reducers.user.setAuthData({ name: 'ethData', data })
localStorage.setItem(constants.privateKeyNames.ethKeychainPublicKey, selectedKey)
localStorage.removeItem(constants.privateKeyNames.eth)
window.getEthAddress = () => data.address
console.info('Logged in with Ethereum', data)
await getBalance()
await getReputation()
return selectedKey
}
const isETHAddress = (address) => {
const { user: { ethData } } = getState()
if (ethData && ethData.address && ethData.address.toLowerCase() === address.toLowerCase()) return ethData
}
const getBalance = () => {
const { user: { ethData: { address } } } = getState()
const balanceInCache = cacheStorageGet('currencyBalances', `eth_${address}`)
if (balanceInCache !== false) return balanceInCache
return web3.eth.getBalance(address)
.then(result => {
const amount = web3.utils.fromWei(result)
cacheStorageSet('currencyBalances', `eth_${address}`, amount, 30)
reducers.user.setBalance({ name: 'ethData', amount })
return amount
})
.catch((e) => {
reducers.user.setBalanceError({ name: 'ethData' })
})
}
const getReputation = () =>
new Promise(async (resolve, reject) => {
const { user: { ethData: { address, privateKey } } } = getState()
const addressOwnerSignature = web3.eth.accounts.sign(address, privateKey)
apiLooper.post('swapsExplorer', `/reputation`, {
json: true,
body: {
address,
addressOwnerSignature,
},
}).then((response) => {
const { reputation, reputationOracleSignature } = response
reducers.user.setReputation({ name: 'ethData', reputation, reputationOracleSignature })
resolve(reputation)
}).catch((error) => {
reject(error)
})
})
const fetchBalance = (address) =>
web3.eth.getBalance(address)
.then(result => Number(web3.utils.fromWei(result)))
.catch((e) => {
console.log('Web3 doesn\'t work please again later ', e.error)
})
const getInvoices = () => {
const { user: { ethData: { address } } } = getState()
return actions.invoices.getInvoices({
currency: 'ETH',
address,
})
}
const getTransaction = () =>
new Promise((resolve) => {
const { user: { ethData: { address } } } = getState()
const url = `?module=account&action=txlist&address=${address}&startblock=0&endblock=99999999&sort=asc&apikey=RHHFPNMAZMD6I4ZWBZBF6FA11CMW9AXZNM`
return apiLooper.get('etherscan', url)
.then((res) => {
const transactions = res.result
.filter((item) => item.value > 0).map((item) => ({
type: 'eth',
confirmations: item.confirmations,
hash: item.hash,
status: item.blockHash != null ? 1 : 0,
value: web3.utils.fromWei(item.value),
address: item.to,
date: item.timeStamp * 1000,
direction: address.toLowerCase() === item.to.toLowerCase() ? 'in' : 'out',
}))
resolve(transactions)
})
.catch(() => {
resolve([])
})
})
const send = ({ to, amount, gasPrice, gasLimit, speed } = {}) =>
new Promise(async (resolve, reject) => {
const { user: { ethData: { privateKey } } } = getState()
gasPrice = gasPrice || await helpers.eth.estimateGasPrice({ speed })
gasLimit = gasLimit || constants.defaultFeeRates.eth.limit.send
const params = {
to: String(to).trim(),
gasPrice,
gas: gasLimit,
value: web3.utils.toWei(String(amount)),
}
const result = await web3.eth.accounts.signTransaction(params, privateKey)
const receipt = web3.eth.sendSignedTransaction(result.rawTransaction)
.on('transactionHash', (hash) => {
const txId = `${config.link.etherscan}/tx/${hash}`
console.log('tx', txId)
actions.loader.show(true, { txId })
})
.on('error', (err) => {
reject(err)
})
resolve(receipt)
})
export default {
send,
login,
loginWithKeychain,
getBalance,
fetchBalance,
getTransaction,
getReputation,
getInvoices,
isETHAddress
}