-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
1748 lines (1567 loc) · 64.1 KB
/
Copy pathserver.js
File metadata and controls
1748 lines (1567 loc) · 64.1 KB
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const validation = require("./validation.js");
const log = require("./log/log.js");
// const timer = require("./timer.js");
const responceData = require("./responceData.js");
// log.saveLog();
const app = require('express')();
const serverConfig = require('./config/serverConfig.json');
const path = require('path');
const http = require('http');
// 模块:对http请求所带的数据进行解析 https://www.cnblogs.com/whiteMu/p/5986297.html
const querystring = require('querystring');
const contract = require('truffle-contract');
// const web3Coder = require('truffle-contract/node_modules/web3/lib/solidity/coder.js');
const Web3 = require('web3');
// 解决Error:Web3ProviderEngine does not support synchronous requests
const Promise = require('bluebird');
// 生成钱包
//const HDWalletProvider = require("truffle-hdwallet-provider");
const walletConfig = require('./config/walletConfig.json');
// 签名之前构造rawTransaction用
var Tx = require('ethereumjs-tx');
const keystore = require(walletConfig.keystore);
//console.log('keystore ', keystore);
const infura_url = {
mainnet: "https://mainnet.infura.io/v3/",
ropsten: "https://ropsten.infura.io/v3/",
rinkeby: "https://rinkeby.infura.io/v3/"
};
// 用户操作
const operation = ["getDepositAddr", "createDepositAddr", "withdraw", "withdrawTo", "freezeToken"];
const abiPath = './contractAbi/';
const abiPath_external = './external/';
// 智能合约
const DRCWalletMgr_artifacts = require(abiPath + 'DRCWalletManager.json');
// 合约发布地址
const contractAT = DRCWalletMgr_artifacts.networks['4'].address;
// 合约abi
const contractABI = DRCWalletMgr_artifacts.abi;
// 初始化合约实例
let DRCWalletMgrContract;
// 调用合约的账号
let account;
// Token智能合约
const DRCToken_artifacts = require(abiPath_external + 'DRCToken.json');
// Token合约发布地址
const DRCToken_contractAT = DRCToken_artifacts.networks['4'].address;
// Token合约abi
const DRCToken_contractABI = DRCToken_artifacts.abi;
// 初始化Token合约实例
let DRCTokenContract;
// 智能合约
const DRCWalletMgrParams_artifacts = require(abiPath + 'DRCWalletMgrParams.json');
// 合约发布地址
const DRCWalletMgrParams_contractAT = DRCWalletMgrParams_artifacts.networks['4'].address;
// 合约abi
const DRCWalletMgrParams_contractABI = DRCWalletMgrParams_artifacts.abi;
// 初始化合约实例
let DRCWalletMgrParamsContract;
// 智能合约
const DRCWalletStorage_artifacts = require(abiPath + 'DRCWalletStorage.json');
// 合约发布地址
const DRCWalletStorage_contractAT = DRCWalletStorage_artifacts.networks['4'].address;
// 合约abi
const DRCWalletStorage_contractABI = DRCWalletStorage_artifacts.abi;
// 初始化合约实例
let DRCWalletStorageContract;
const GAS_LIMIT = 4700000; // default gas limit
const SAFE_GAS_PRICE = 41; // default gas price (unit is gwei)
const ADDR_ZERO = "0x0000000000000000000000000000000000000000";
const gasPricePromote = {
GT_30: 1.25,
GT_20: 1.2,
GT_10: 1.15,
GT_3: 1.12,
DEFAULT: 1.1
};
const transactionType = {
WITHDRAW: 'withdraw',
CREATE_DEPOSIT: 'createDeposit',
DO_DEPOSIT: 'doDeposit',
NORMAL: 'normal'
};
const intervals = {
retryTx: 300000,
retryGasPrice: 910000,
retryTxTimes: 3,
retryTimes: 10
};
const decimals = {
default: 1e18,
fixedWidth: 1e7,
leftWidth: 1e11
};
// Add headers
app.use((req, res, next) => {
req.setEncoding('utf8');
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', false);
// Pass to next layer of middleware
next();
});
// 新建initWeb3Provider连接
function initWeb3Provider() {
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider(infura_url.rinkeby + walletConfig.infuraAPIkey));
}
// 解决Error:TypeError: Cannot read property 'kdf' of undefined
account = web3.eth.accounts.decrypt(JSON.parse(JSON.stringify(keystore).toLowerCase()), walletConfig.password);
web3.eth.defaultAccount = account.address;
console.log('web3.eth.defaultAccount : ', web3.eth.defaultAccount);
if (typeof web3.eth.getAccountsPromise === 'undefined') {
//console.log('解决 Error: Web3ProviderEngine does not support synchronous requests.');
Promise.promisifyAll(web3.eth, {
suffix: 'Promise'
});
}
}
// let gasPrice;
let currentNonce = -1;
// 获取账户余额 警告 要大于 0.001Eth
const getBalance = (callback, dataObject = {}) => {
web3.eth.getBalance(web3.eth.defaultAccount, (error, balance) => {
if (error) {
if (dataObject != {}) {
dataObject.res.end(JSON.stringify(responceData.evmError));
}
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.evmError);
return;
}
console.log('balance =>', balance);
if (balance && web3.utils.fromWei(balance, "ether") < 0.001) {
// 返回failed 附带message
if (dataObject.res) {
dataObject.res.end(JSON.stringify(responceData.lowBalance));
}
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.lowBalance);
return;
}
callback(dataObject);
});
}
// 获取data部分的nonce
const getNonce = () => {
return new Promise((resolve, reject) => {
const handle = setInterval(() => {
web3.eth.getTransactionCount(web3.eth.defaultAccount, (error, result) => {
if (error) {
clearInterval(handle);
reject(error);
}
if (result) {
clearInterval(handle);
console.log('current nonce is: ', currentNonce);
console.log('current transaction count is: ', result);
if (currentNonce < result) currentNonce = result;
else currentNonce += 1;
resolve(web3.utils.toHex(currentNonce)); // make sure the nonce is different
}
});
}, 5000);
})
.catch(err => {
console.log("catch error when getNonce");
return new Promise.reject(err);
});
}
// 获取data部分的gasPrice
const getGasPrice = () => {
return new Promise((resolve, reject) => {
const handle = setInterval(() => {
web3.eth.getGasPrice((error, result) => {
if (error) {
clearInterval(handle);
reject(error);
}
//resolve(web3.utils.toHex(result));
if (result) {
clearInterval(handle);
let gasPrice = web3.utils.fromWei(result, "gwei");
console.log('gasPrice ', gasPrice + 'gwei');
if (gasPrice >= 30) gasPrice *= gasPricePromote.GT_30;
else if (gasPrice >= 20) gasPrice *= gasPricePromote.GT_20;
else if (gasPrice >= 10) gasPrice *= gasPricePromote.GT_10;
else if (gasPrice >= 3) gasPrice *= gasPricePromote.GT_3;
else gasPrice *= gasPricePromote.DEFAULT;
// resolve(web3.utils.toHex(Math.round(result)));
resolve(gasPrice.toFixed(2));
}
});
}, 5000);
})
.catch(err => {
console.log("catch error when getGasPrice");
return new Promise.reject(err);
});
};
// 获取estimated gasLimit
const getGasLimit = (callObject) => {
return new Promise((resolve, reject) => {
const handle = setInterval(() => {
web3.eth.estimateGas(callObject, (error, result) => {
if (error) {
clearInterval(handle);
reject(error);
}
//resolve(web3.utils.toHex(result));
if (result) {
clearInterval(handle);
console.log('estimated gasLimit ', result);
resolve(Math.round(result * 1.1));
}
});
}, 5000);
})
.catch(err => {
console.log("catch error when getGasLimit");
return new Promise.reject(err);
});
};
const txReplaceRecs = new Map();
let retrySendTransaction = (rawTx, origTxHash) => {
let newRawTx = rawTx;
let currTxHash = origTxHash;
let prevTxHash = origTxHash;
let iCount = 0;
let finished = false;
const handle = setInterval(() => {
if (finished) {
clearInterval(handle);
console.log('retry TX succeed: ', currTxHash);
}
iCount++;
if (iCount > intervals.retryTimes) {
clearInterval(handle);
console.log('has retry 10 times of retrying transactions...');
return new Promise.reject(Error('Failed to retry transactions for too many times!'));
}
Promise.all([getGasPrice()])
.then(values => {
/**
* internal retry will only take 3 times, if Tx cannot succeed, then
* the base gasPrice is not correct, so retry another base gasPrice.
*/
let iCountInternal = 0;
const handleInternal = setInterval(() => {
iCountInternal++;
if (iCountInternal > intervals.retryTxTimes) {
clearInterval(handleInternal);
console.log('the base gasPrice is not appropriate, need to change...');
} else {
console.log('current retry gasPrice: ', values[0]);
newRawTx.gasPrice = web3.utils.toHex(web3.utils.toWei(values[0].toString(), "gwei"));
let tx = new Tx(newRawTx);
// 解决 RangeError: private key length is invalid
tx.sign(new Buffer(account.privateKey.slice(2), 'hex'));
let serializedTx = tx.serialize();
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('transactionHash', (hash) => {
console.log('current TX hash: ', currTxHash);
console.log('retry TX hash: ', hash);
txReplaceRecs.set(currTxHash, hash); // save this replaced Tx hash
prevTxHash = currTxHash;
currTxHash = hash;
})
.on('receipt', (receipt) => {
console.log('retry transaction succeed at ', receipt.transactionHash);
txReplaceRecs.set(prevTxHash, receipt.transactionHash); // save this replaced Tx hash
console.log('get receipt after retry sending transaction: ', receipt);
clearInterval(handle);
finished = true;
})
.on('error', (err, receipt) => {
console.error('catch an error after retry sendTransaction... ', err);
if (err) {
if (receipt && receipt.status) {
console.log('the retry tx has already got the receipt: ', receipt);
txReplaceRecs.set(prevTxHash, receipt.transactionHash); // save this replaced Tx hash
clearInterval(handle);
}
if (err.message.includes('not mined within')) {
console.log("retry tx met error of not mined within 50 blocks or 750 seconds...");
} else {
if (err.message.includes('out of gas')) {
console.error("account doesn't have enough gas or TX has been reverted in retry...");
} else {
console.error('retry tx met other exceptions...');
}
clearInterval(handle); // this exception will cause not retrying the Tx submission
return new Promise.reject(err);
}
}
});
values[0] = (values[0] * gasPricePromote.GT_10).toFixed(2); // add 15% gasPrice
}
}, intervals.retryTx);
});
}, intervals.retryGasPrice);
};
// 给tx签名,并且发送上链
const sendTransaction = (rawTx, txType) => {
return new Promise((resolve, reject) => {
let tx = new Tx(rawTx);
// 解决 RangeError: private key length is invalid
tx.sign(new Buffer(account.privateKey.slice(2), 'hex'));
let serializedTx = tx.serialize();
// a simple function to add the real gas Price to the receipt data
let finalReceipt = (receipt) => {
let res = receipt;
res.gasPrice = rawTx.gasPrice;
return res;
};
// 签好的tx发送到链上
let txHash;
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('transactionHash', (hash) => {
if (hash) {
console.log(txType + ' TX hash: ', hash);
txHash = hash;
if (txType != transactionType.NORMAL) {
return resolve(txHash); // maybe there are other type of transaction not need this
}
}
})
.on('receipt', (receipt) => {
console.log(txType + ' get receipt after send transaction: ', receipt);
if (txType == transactionType.NORMAL) return resolve(finalReceipt(receipt));
})
.on('confirmation', (confirmationNumber, receipt) => {
console.log(txType + ' confirmation number: ', confirmationNumber);
if (confirmationNumber == 24 && receipt) {
console.log(txType + 'confirmation receipt', receipt);
return resolve(finalReceipt(receipt));
}
})
.on('error', (err, receipt) => {
console.error(txType + ' catch an error after sendTransaction... ', err);
if (!txHash) {
console.log('TX has not been created and error occurred...');
currentNonce -= 1; // next Tx will take this currentNonce value;
}
if (err) {
if (receipt && receipt.status) {
console.log('the real tx has already got the receipt: ', receipt);
if (txType == transactionType.NORMAL) return resolve(finalReceipt(receipt));
}
// if (err.message.includes('not mined within 50 blocks')
// || err.message.includes('not mined within750 seconds')) {
if (txHash && err.message.includes('not mined within')) {
console.log("met error of not mined within 50 blocks or 750 seconds...");
// keep trying to get TX receipt
let iCount = 0;
const handle = setInterval(() => {
iCount += 1;
web3.eth.getTransactionReceipt(txHash)
.then((resp) => {
if (resp != null && resp.blockNumber > 0) {
console.log('get Tx receipt from error handling: ', resp);
clearInterval(handle);
if (txType == transactionType.NORMAL) return resolve(finalReceipt(resp));
}
if (iCount >= 60) {
console.log('has checked if TX had been mined for 5 minutes...');
clearInterval(handle); // not check any more after 300 minutes
// throw('Tx had not been mined for more than 5 minutes...');
console.log('retrying tx: ', txHash);
retrySendTransaction(rawTx, txHash);
}
})
.catch(err => {
console.log('met error when getting TX receipt from error handling');
clearInterval(handle);
reject(err);
})
}, 5000);
// const TIME_OUT = 1800000; // 30 minutes timeout
// setTimeout(() => {
// clearTimeout(handle);
// }, TIME_OUT);
} else if (err.message.includes('out of gas')) {
console.error("account doesn't have enough gas or TX has been reverted...");
// console.log('TX receipt, ', receipt);
} else {
console.log('met other exceptions when send transaction...');
// retrySendTransaction(rawTx, txHash);
}
reject(err);
}
});
})
.catch(e => {
console.error(txType + " catch error when sendTransaction: ", e);
return new Promise.reject(e);
});
};
let TxExecution = function(contractAT, encodeData, resultCallback, dataObject = {}, txType = 'normal') {
// 上链结果响应到请求方
// const returnResult = (result) => {
// resultCallback(result);
// }
let callback = (dataObject) => {
let returnObject = {};
let callObject = {
to: contractAT,
data: encodeData
};
let txSubmited = false;
Promise.all([getNonce(), getGasPrice(), getGasLimit(callObject)])
.then(values => {
// gasPrice = web3.utils.fromWei(values[1], "gwei");
console.log('current gasPrice: ', values[1] + "gwei");
console.log('current gasLimit: ', values[2]);
// if current gas price is too high, then cancel the transaction
if (values[1] > SAFE_GAS_PRICE) {
if (dataObject != {}) {
dataObject.res.end(JSON.stringify(responceData.gasPriceTooHigh));
}
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, gasPrice, 0, responceData.evmError);
return;
}
let rawTx = {
nonce: values[0],
to: contractAT,
gasPrice: web3.utils.toHex(web3.utils.toWei(values[1].toString(), "gwei")), // values[1],
gasLimit: web3.utils.toHex(values[2]), //web3.utils.toHex(GAS_LIMIT),
data: encodeData
};
return rawTx;
})
.then((rawTx) => {
let res = sendTransaction(rawTx, txType);
txSubmited = true;
return res;
})
.then((result) => {
// console.log("data object is ", dataObject);
if (dataObject.res) {
resultCallback(result, returnObject, dataObject);
} else {
resultCallback(result, returnObject);
}
})
.catch(e => {
if (e) {
console.error('evm error', e);
if (!txSubmited) {
currentNonce -= 1; // tx hadn't succeed submitting, so nonce should not increase
}
if (dataObject != {}) {
dataObject.res.end(JSON.stringify(responceData.transactionError));
}
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, gasPrice, 0, responceData.evmError);
return;
}
});
};
getBalance(callback, dataObject);
};
let realValue = (value) => {
var temp = value.toFixed(7);
// web3.utils.toBN(requestObject.value).mul(wb3.utils.toBN(decimals.default));
return web3.utils.toBN(Number.parseInt(temp * decimals.fixedWidth)).mul(web3.utils.toBN(decimals.leftWidth)).toString();
}
var Actions = {
// 初始化:拿到web3提供的地址, 利用json文件生成合约··
start: function() {
DRCWalletMgrContract = new web3.eth.Contract(contractABI, contractAT, {});
DRCTokenContract = new web3.eth.Contract(DRCToken_contractABI, DRCToken_contractAT, {});
DRCWalletMgrParamsContract = new web3.eth.Contract(DRCWalletMgrParams_contractABI, DRCWalletMgrParams_contractAT, {});
DRCWalletStorageContract = new web3.eth.Contract(DRCWalletStorage_contractABI, DRCWalletStorage_contractAT, {});
DRCWalletMgrContract.setProvider(web3.currentProvider);
DRCTokenContract.setProvider(web3.currentProvider);
DRCWalletMgrParamsContract.setProvider(web3.currentProvider);
DRCWalletStorageContract.setProvider(web3.currentProvider);
// console.log(DRCWalletMgrContract);
// console.log(contractABI);
// bind token address
DRCWalletMgrContract.methods.tk().call()
.then(result => {
var bindTk = web3.utils.toHex(result);
console.log(bindTk);
DRCWalletMgrContract.methods.walletStorage().call()
.then(storageRes => {
var storageAddr = web3.utils.toHex(storageRes);
console.log(storageAddr);
DRCWalletMgrContract.methods.params().call()
.then(paramsRes => {
var params = web3.utils.toHex(paramsRes);
console.log(params);
if (bindTk == ADDR_ZERO ||
storageAddr != DRCWalletStorage_contractAT ||
params != DRCWalletMgrParams_contractAT) {
// 拿到rawTx里面的data部分
console.log(DRCToken_contractAT);
let encodeData_param = web3.eth.abi.encodeParameters(
['address', 'address', 'address'], [DRCToken_contractAT,
DRCWalletMgrParams_contractAT.slice(2),
DRCWalletStorage_contractAT.slice(2)
]
);
console.log(encodeData_param);
let encodeData_function = web3.eth.abi.encodeFunctionSignature('initialize(address,address,address)');
console.log(encodeData_function);
let encodeData = encodeData_function + encodeData_param.slice(2);
console.log(encodeData);
let processResult = (result, returnObject) => {
// returnObject = {
// from: contractAT
// };
returnObject.txHash = result.transactionHash;
returnObject.gasUsed = result.gasUsed;
returnObject.gasPrice = result.gasPrice;
console.log(returnObject);
logObject = result.logs[0];
console.log(logObject);
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, gasPrice, result.gasUsed, responceData.createDepositAddrSuccess);
};
TxExecution(contractAT, encodeData, processResult);
if (storageAddr != DRCWalletStorage_contractAT) {
let encodeData_param_2 = web3.eth.abi.encodeParameters(
['address'], [contractAT]
);
console.log(encodeData_param_2);
let encodeData_function_2;
let encodeData_function_3;
let calledContract;
DRCWalletStorageContract.methods.owner().call()
.then(result => {
if (result != web3.eth.defaultAccount) {
calledContract = result;
encodeData_function_2 = web3.eth.abi.encodeFunctionSignature('changeOwnershipto(address)');
encodeData_function_3 = web3.eth.abi.encodeFunctionSignature('ownedOwnershipTransferred()');
} else {
calledContract = DRCWalletStorage_contractAT;
encodeData_function_2 = web3.eth.abi.encodeFunctionSignature('transferOwnership(address)');
}
console.log(encodeData_function_2);
let encodeData_2 = encodeData_function_2 + encodeData_param_2.slice(2);
console.log(encodeData_2);
TxExecution(calledContract, encodeData_2, processResult);
})
.catch(e => {
if (e) {
console.log('program error', e);
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.evmError);
return;
}
});
const handle = setInterval(() => {
DRCWalletStorageContract.methods.pendingOwner().call()
.then(result => {
var pending = web3.utils.toHex(result);
console.log(pending);
if (pending != contractAT) {
console.log('pending owner is still not ', contractAT);
} else {
clearInterval(handle);
console.log('now pending owner is ', pending);
if (encodeData_function_3) {
console.log(encodeData_function_3);
TxExecution(calledContract, encodeData_function_3, processResult);
}
let encodeData_param_4 = web3.eth.abi.encodeParameters(
['address'], [DRCWalletStorage_contractAT]
);
console.log(encodeData_param_4);
let encodeData_function_4 = web3.eth.abi.encodeFunctionSignature('bindContract(address)');
console.log(encodeData_function_4);
let encodeData_4 = encodeData_function_4 + encodeData_param_4.slice(2);
console.log(encodeData_4);
TxExecution(contractAT, encodeData_4, processResult);
}
})
.catch(e => {
if (e) {
console.log('program error', e);
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.evmError);
return;
}
});
}, 15000);
}
}
})
.catch(e => {
if (e) {
console.log('program error', e);
// 重置
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.evmError);
return;
}
});
});
});
},
// 往链上存数据
createDepositAddr: function(data) {
let dataObject = data;
// first check address is valid
if (!web3.utils.isAddress(dataObject.data)) {
console.log("the wallet address is not vaild...");
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.addressError));
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.addressError);
return;
}
// 上链步骤:查询没有结果之后再上链
DRCWalletMgrContract.methods.getDepositAddress(dataObject.data).call((error, result) => {
if (error) {
console.log(responceData.evmError);
// 以太坊虚拟机的异常
dataObject.res.end(JSON.stringify(responceData.evmError));
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, 0, 0, responceData.evmError);
return;
}
console.log(' 充值地址查询结果 \n', result);
console.log(' 充值地址详细查询结果 \n', result['0']);
// get the numberstring to compare
var resultValue = web3.utils.hexToNumberString(result);
console.log(resultValue);
if (resultValue != "0") {
let returnObject = {};
returnObject = responceData.depositAlreadyExist;
returnObject.txHash = '0'; // to compatible with other tx hash value
returnObject.gasPrice = 0;
returnObject.gasUsed = 0;
returnObject.depositAddr = result;
dataObject.res.end(JSON.stringify(returnObject));
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, 0, 0, responceData.depositAlreadyExist);
return;
}
if (resultValue == "0") {
// let gasPrice;
// 拿到rawTx里面的data部分
console.log(dataObject.data);
let encodeData_param = web3.eth.abi.encodeParameters(['address'], [dataObject.data]);
let encodeData_function = web3.eth.abi.encodeFunctionSignature('createDepositContract(address)');
console.log(encodeData_function);
let encodeData = encodeData_function + encodeData_param.slice(2);
console.log(encodeData);
// 上链结果响应到请求方
const returnResult = (result, returnObject, dataObject) => {
// 新return对象,作为http请求的返回值
returnObject = responceData.createDepositAddrSuccess;
if (result.transactionHash) {
returnObject.txHash = result.transactionHash;
returnObject.gasUsed = result.gasUsed;
returnObject.gasPrice = result.gasPrice;
let logObject = result.logs[0];
console.log(logObject);
returnObject.depositAddr = web3.utils.numberToHex(web3.utils.hexToNumberString(logObject.data));
} else {
returnObject.txHash = result;
returnObject.gasPrice = 0;
returnObject.gasUsed = 0;
returnObject.depositAddr = ADDR_ZERO;
}
console.log('create deposit address final return object: ', returnObject);
// 返回success 附带message
dataObject.res.end(JSON.stringify(returnObject));
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, gasPrice, result.gasUsed, responceData.createDepositAddrSuccess);
}
TxExecution(contractAT, encodeData, returnResult, dataObject, transactionType.CREATE_DEPOSIT);
}
})
.catch(e => {
if (e) {
console.log('program error', e);
dataObject.res.end(JSON.stringify(responceData.programError));
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.evmError);
return;
}
});
return;
},
// 往链上存数据
doDeposit: function(data) {
let dataObject = data;
let requestObject = dataObject.data;
// first check address is valid
if (!web3.utils.isAddress(requestObject.depositAddress)) {
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.addressError));
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.addressError);
return;
}
// 上链步骤:查询没有结果之后再上链
DRCWalletMgrContract.methods.getDepositWithdrawCount(requestObject.depositAddress).call((error, result) => {
if (error) {
// 以太坊虚拟机的异常
dataObject.res.end(JSON.stringify(responceData.evmError));
// 保存log
// log.saveLog(operation[2], new Date().toLocaleString(), qs.depositAddress, 0, 0, responceData.evmError);
return;
}
console.log("Deposit binded wallets number: ", result);
return result;
})
.then((withdrawAddrCount) => {
if (withdrawAddrCount == 0) {
// 返回failed 附带message, deposit address doesn't exist
dataObject.res.end(JSON.stringify(responceData.addressError));
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.addressError);
return;
}
// 拿到rawTx里面的data部分
console.log(requestObject);
console.log("real deposit value is ", realValue(requestObject.value));
let encodeData_params = web3.eth.abi.encodeParameters(
['address', 'bool', 'uint256'], [requestObject.depositAddress.slice(2),
requestObject.increase,
realValue(requestObject.value)
]
);
console.log(encodeData_params);
let encodeData_function = web3.eth.abi.encodeFunctionSignature('doDeposit(address,bool,uint256)');
console.log(encodeData_function);
let encodeData = encodeData_function + encodeData_params.slice(2);
console.log(encodeData);
// 上链结果响应到请求方
let processResult = (result, returnObject, dataObject) => {
// status = web3.utils.hexToNumber(web3.utils.toHex(result.status));
console.log("doDeposit tx: ", result);
if (!result) {
// console.log(dataObject);
dataObject.res.end(JSON.stringify(responceData.doDepositFailed));
// log.saveLog(operation[2], new Date().toLocaleString(), qs.withdrawAddress, gasPrice, result.gasUsed, responceData.withdrawFailed);
return;
}
returnObject = responceData.doDepositTxSuccess;
if (!result.transactionHash) {
returnObject.txHash = result;
} else {
returnObject.txHash = result.transactionHash;
returnObject.gasUsed = result.gasUsed;
returnObject.gasPrice = result.gasPrice;
let logObject = result.logs[0];
console.log(logObject);
}
console.log("doDepoist return object is: ", returnObject);
// 返回success 附带message
// console.log(dataObject);
dataObject.res.end(JSON.stringify(returnObject));
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[2], new Date().toLocaleString(), qs.withdrawAddress, gasPrice, result.gasUsed, responceData.createDepositAddrSuccess);
}
// console.log("data Object outside is ", dataObject);
TxExecution(contractAT, encodeData, processResult, dataObject, transactionType.NORMAL);
})
.catch(e => {
if (e) {
console.log('program error', e);
dataObject.res.end(JSON.stringify(responceData.programError));
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, 0, 0, responceData.evmError);
return;
}
});
return;
},
// 去链上查询结果
getEthStatus: function(data) {
let dataObject = data;
console.log('data in getEthStatus is: ', dataObject.data);
if (typeof dataObject.data != 'string' || dataObject.data != 'getEthStatus') {
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.dataError));
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, 0, 0, responceData.addressError);
return;
}
Promise.all([getGasPrice()])
.then(values => {
console.log('current gasPrice: ', values[0] + 'gwei');
// let gasPrice = web3.utils.toWei(values[0].toString(), "gwei");
// if current gas price is too high, then cancel the transaction
if (values[0] > SAFE_GAS_PRICE) {
dataObject.res.end(JSON.stringify(responceData.gasPriceTooHigh));
// 重置
// returnObject = {};
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, gasPrice, 0, responceData.evmError);
} else {
console.log('EVM status is fine...');
dataObject.res.end(JSON.stringify(responceData.ethStatusSuccess));
}
return;
})
.catch(err => {
console.log('met error get ethereum status: ', err);
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.evmError));
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, responceData.selectHashFailed);
return;
});
},
// 去链上查询结果
getDepositAddr: function(data) {
let dataObject = data;
if (!web3.utils.isAddress(dataObject.data)) {
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.addressError));
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, 0, 0, responceData.addressError);
return;
}
DRCWalletMgrContract.methods.wallletDeposits(dataObject.data).call((err, result) => {
var resultValue = web3.utils.hexToNumberString(result);
if (err || resultValue == "0") {
console.log(err);
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.getDepositAddrFailed));
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, responceData.getDepositAddrFailed);
return;
}
let returnObject = responceData.getDepositAddrSuccess;
returnObject.data = result;
// 返回success 附带message
dataObject.res.end(JSON.stringify(returnObject));
// 重置
returnObject = {};
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, responceData.selectHashSuccess);
});
},
getDepositInfo: function(data) {
let dataObject = data;
if (!web3.utils.isAddress(dataObject.data)) {
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.addressError));
// 保存log
// log.saveLog(operation[0], new Date().toLocaleString(), qs.hash, 0, 0, responceData.addressError);
return;
}
DRCWalletMgrContract.methods.getDepositInfo(dataObject.data).call((err, result) => {
if (err) {
// 返回failed 附带message
dataObject.res.end(JSON.stringify(responceData.getDepositInfoFailed));
// 保存log
// log.saveLog(operation[1], new Date().toLocaleString(), qs.hash, responceData.selectHashFailed);
return;
}
let returnObject = responceData.getDepositInfoSuccess;
console.log(result);
returnObject.balance = result["0"];
returnObject.frozenAmount = result["1"];
// 返回success 附带message
dataObject.res.end(JSON.stringify(returnObject));
// 重置
returnObject = {};