-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanageService.js
83 lines (71 loc) · 2.57 KB
/
manageService.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
var redisPool = require("./redisPool")
var perRedisPool = require("./perRedisPool")
const conf = require('./config/config')
var Tx = require('ethereumjs-tx')
const {promisify} = require('util');
const getAsync = promisify(redisPool.get).bind(redisPool)
const getAsyncPer = promisify(redisPool.get).bind(perRedisPool)
const web3 = conf.getWeb3();
async function syncNonce(from) {
const key = 'NONCE:' + conf.debug + ':' + from
const nonce = await web3.eth.getTransactionCount(from)
console.log('syncing nonce: ', nonce)
redisPool.set(key, nonce, 'EX', 3600*24)
}
async function getNonce(from) {
const key = 'NONCE:' + conf.debug + ':' + from
const res = await getAsync(key)
if (!res) {
const nonce = await web3.eth.getTransactionCount(from)
redisPool.set(key, nonce, 'EX', 3600*24)
return nonce
} else {
return parseInt(res)
}
console.log('redis get error: ', err)
return -1
}
async function closeBetWithAddress(commit, pk, from, callback) {
// const reveal = await getAsync(commit)
const reveal = await getAsyncPer(commit)
if (!reveal) {
console.log('can not get reveal')
return
}
const gasPrice = await web3.eth.getGasPrice()
let nonce = await getNonce(from)
const nonceOnline = await web3.eth.getTransactionCount(from)
if (nonce < 0 || (nonce != 0 && !nonce) || nonce < nonceOnline || nonce - 5 > nonceOnline) {
console.log('redis nonce is not correct, sync nonce online', nonce, nonceOnline)
nonce = nonceOnline
const key = 'NONCE:' + conf.debug + ':' + from
redisPool.set(key, nonce, 'EX', 3600*24)
}
var privateKey = new Buffer(pk, 'hex')
var data = conf.casinoContract.methods.closeBet(reveal).encodeABI()
var rawTx = {
nonce: web3.utils.toHex(nonce),
gasPrice: web3.utils.toHex(Math.floor(gasPrice * 1.1)), // 2 Gwei 2000000000
gasLimit: web3.utils.toHex(60000),
from: from,
to: conf.casinoContract._address,
value: web3.utils.toHex(0),
data: data
}
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();
return web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), callback)
}
async function closeBet(commit, callback) {
const pk = conf.pk
const from = conf.address
return closeBetWithAddress(commit, pk, from, callback)
}
//syncNonce(conf.address)
//closeBet('0x36c3b7aa855b06e4c0d38c31b88edb823ca0af6dcc555cc208404e11877653c8', console.log)
//closeBet('0x' + 'bfbca8ab55b013bea34cb7ed0436b4069d90b00d271eee0d6b627514e0c117df', console.log)
module.exports = {
closeBet: closeBet,
closeBetWithAddress: closeBetWithAddress
}