forked from MetaMask/eth-json-rpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wallet-parity.js
87 lines (73 loc) · 2.28 KB
/
wallet-parity.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
const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware')
const createScaffoldMiddleware = require('json-rpc-engine/src/createScaffoldMiddleware')
module.exports = createParityWalletMiddleware
function createParityWalletMiddleware({ walletMiddleware }){
const parityRequestCount = 0
const parityRequests = []
return createScaffoldMiddleware({
'parity_defaultAccount': createAsyncMiddleware(defaultAccount),
'parity_postTransaction': createAsyncMiddleware(postTransaction),
'parity_postSign': createAsyncMiddleware(postSign),
'parity_checkRequest': createAsyncMiddleware(checkRequest),
})
//
// parity wallet methods
//
async function defaultAccount (req, res) {
res.result = await callOnWalletMiddleware({ method: 'eth_coinbase', params: [] })
}
async function postTransaction (req, res) {
const reqId = createReqId()
res.result = reqId
// dont wait for result
setTimeout(async () => {
try {
const txHash = await callOnWalletMiddleware({ method: 'eth_sendTransaction', params: req.params })
parityRequests[reqId] = { result: txHash }
} catch (error) {
parityRequests[reqId] = { error }
}
})
}
async function postSign (req, res) {
const reqId = createReqId()
res.result = reqId
// dont wait for result
setTimeout(async () => {
try {
const sigResult = await callOnWalletMiddleware({ method: 'eth_sign', params: req.params })
parityRequests[reqId] = { result: sigResult }
} catch (error) {
parityRequests[reqId] = { error }
}
})
}
async function checkRequest (req, res) {
const result = parityRequests[reqId]
// request not handled yet
if (!result) {
res.result = null
return
}
// request resulted in error (e.g. tx was rejected)
if (result.error) {
throw result.error
}
// request was handled correctly
res.result = result
}
//
// utility
//
function createReqId() {
// get request id
const reqId = `0x${parityRequestCount.toString(16)}`
parityRequestCount++
return reqId
}
async function callOnWalletMiddleware(req) {
const res = {}
await new Promise(resolve => walletMiddleware(req, res, null, resolve))
return res.result
}
}