This repository has been archived by the owner on Sep 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
httpApi.js
905 lines (797 loc) · 32.6 KB
/
httpApi.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
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
let Web3 = require('web3')
let { randomHex } = require('web3-utils')
let fs = require('fs')
let sleep = require('util').promisify(setTimeout)
var config = require('./config.json')
let axios = require('axios')
const TOTAL_SUPPLY = 1000000000
let infuraKey = config.infuraKey
let provider = config.geth.httpProvider
let networkid = config.networkid
let numBlocks = config.numBlocks
let gethProvider = config.geth.httpProvider
let infuraHttpProvider = config.infura.httpProvider
const poktHttpProvider = config.pokt.httpProvider
// let provider = 'http://35.188.201.171:8545'
// let provider = 'https://rinkeby.infura.io/v3/' + infuraKey
// let networkid = '420' // testnet
// let networkid = '4' // rinkeby
// let web3 = new Web3(provider, null, {})
let merkle = require('@razor-network/merkle')
let stakeManagerAbi = require('@razor-network/contracts/abi/StakeManager.json')
let stateManagerAbi = require('@razor-network/contracts/abi/StateManager.json')
let blockManagerAbi = require('@razor-network/contracts/abi/BlockManager.json')
let voteManagerAbi = require('@razor-network/contracts/abi/VoteManager.json')
let jobManagerAbi = require('@razor-network/contracts/abi/JobManager.json')
let delegatorAbi = require('@razor-network/contracts/abi/Delegator.json')
let constantsAbi = require('@razor-network/contracts/abi/Constants.json')
let randomAbi = require('@razor-network/contracts/abi/Random.json')
let simpleTokenAbi = require('@razor-network/contracts/abi/SchellingCoin.json')
let addresses = require('./addresses.json')
const getProviderURL = (provider = "geth") => {
switch(provider) {
case "geth":
return gethProvider;
case "infura":
return infuraHttpProvider;
case "pokt":
return poktHttpProvider;
default:
return gethProvider;
}
}
const getWeb3Instance = async (provider = "geth") => {
const providerURL = getProviderURL(provider);
return web3 = new Web3(providerURL, null, {});
}
const options = {
transactionConfirmationBlocks: 1,
gas: 8000000,
gasPrice: 20000000000
}
// Provider wrapper
const getStakeManager = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(stakeManagerAbi, addresses["StakeManager"], options)
}
const getStateManager = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(stateManagerAbi, addresses["StateManager"], options)
}
const getBlockManager = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(blockManagerAbi, addresses["BlockManager"], options)
}
const getVoteManager = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(voteManagerAbi, addresses["VoteManager"], options)
}
const getJobManager = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(jobManagerAbi, addresses["JobManager"], options)
}
const getConstants = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(constantsAbi, addresses["Constants"], options)
}
const getRandom = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(randomAbi, addresses["Random"], options)
}
const getSimpleToken = async (provider) => {
const web3 = await getWeb3Instance(provider);
return new web3.eth.Contract(simpleTokenAbi, addresses["SchellingCoin"], options)
}
async function login (address, password) {
let web3 = await getWeb3Instance()
await web3.eth.accounts.wallet.create(0, randomHex(32))
let rawdata = await fs.readFileSync('keys/' + address + '.json')
let keystoreArray = JSON.parse(rawdata)
let wall = await web3.eth.accounts.wallet.decrypt([keystoreArray], password)
let pk = wall[0].privateKey
let account = await web3.eth.accounts.privateKeyToAccount(pk)
await web3.eth.accounts.wallet.add(account)
let from = await wall[0].address
console.log(from, ' unlocked')
return ([from, pk])
}
async function createJob (url, selector, repeat, eth, account) {
let web3 = await getWeb3Instance()
let jobManager = await getJobManager()
let nonce = await web3.eth.getTransactionCount(account, 'pending')
return jobManager.methods.createJob(url, selector, repeat).send({from: account, nonce: String(nonce), value: eth})
}
async function getActiveJobs () {
let jobManager = await getJobManager()
let stateManager = await getStateManager()
let numJobs = Number(await jobManager.methods.numJobs().call())
let job
let jobs = []
let epoch = Number(await stateManager.methods.getEpoch().call())
for (let i = 1; i <= numJobs; i++) {
job = await jobManager.methods.jobs(i).call()
if (!job.fulfilled && Number(job.epoch) < epoch) {
jobs.push(job)
}
}
return jobs
}
async function getJobs (provider) {
let jobManager = await getJobManager(provider)
let numJobs = Number(await jobManager.methods.numJobs().call())
let job
let jobs = [] // let epoch = Number(await stateManager.methods.getEpoch().call())
for (let i = 1; i <= numJobs; i++) {
job = await jobManager.methods.getJob(i).call()
job.id = i
jobs.push(job)
}
return jobs
}
async function getNumJobs () {
let jobManager = await getJobManager()
let numJobs = Number(await jobManager.methods.numJobs().call())
return numJobs
}
async function getResult (id) {
let jobManager = await getJobManager()
let result = Number(await jobManager.methods.getResult(id).call())
return result
}
async function getJob (id) {
let jobManager = await getJobManager()
let result = await jobManager.methods.getJob(id).call()
return result
}
async function getStakers () {
let stakeManager = await getStakeManager()
let numStakers = Number(await stakeManager.methods.getNumStakers().call())
let res = []
// let epoch = Number(await stateManager.methods.getEpoch().call())
for (let i = 1; i <= numStakers; i++) {
staker = await stakeManager.methods.getStaker(i).call()
res.push({'stakerId': staker[0],
'address': staker[1],
'stake': staker[2]
})
}
return res
}
async function getJobValues (jobId, provider) {
let jobManager = await getJobManager(provider)
let web3 = await getWeb3Instance(provider)
let blockNumber = await web3.eth.getBlockNumber()
let fulfills = await jobManager.getPastEvents('JobReported', {
fromBlock: Math.max(0, Number(blockNumber) - 1000),
toBlock: 'latest'
})
// console.log('fulfills', fulfills)
let values = []
for (let i = 0; i < fulfills.length; i++) {
if (Number(fulfills[i].returnValues.id) === Number(jobId)) values.push(fulfills[i].returnValues)
}
return values
}
async function getVotesLastEpoch (jobId, provider) {
let web3 = await getWeb3Instance(provider)
let stakeManager = await getStakeManager(provider)
let voteManager = await getVoteManager(provider)
let blockNumber = await web3.eth.getBlockNumber()
let epoch = Number(await getEpoch(provider)) - 1
let numStakers = Number(await stakeManager.methods.getNumStakers().call())
let vote
let votes = []
let staker
for (let i = 1; i <= numStakers; i++) {
vote = await voteManager.methods.getVote(epoch, i, jobId - 1).call()
staker = (await stakeManager.methods.getStaker(i).call())
// console.log(staker)
if (Number(vote.value) > 0) {
votes.push({staker: staker._address, id: staker.id, value: Number(vote.value), weight: vote.weight})
}
}
return votes
}
async function getVotingEvents (jobId, provider) {
let web3 = await getWeb3Instance(provider)
let stakeManager = await getStakeManager(provider)
let voteManager = await getVoteManager(provider)
let blockNumber = await web3.eth.getBlockNumber()
// let epoch = Number(await getEpoch()) - 1
let events = await voteManager.getPastEvents('allEvents', {
fromBlock: Math.max(0, Number(blockNumber) - 1000),
toBlock: 'latest'
})
// console.log(events[2].returnValues)
let res = []
let value
let staker
let timestamp
for (let i = 0; i < events.length; i++) {
staker = (await stakeManager.methods.getStaker(events[i].returnValues.stakerId).call())[1]
timestamp = events[i].returnValues.timestamp
if (events[i].event === 'Committed') {
value = events[i].returnValues.commitment
res.push({epoch: events[i].returnValues.epoch, staker: staker, action: events[i].event, value: value, timestamp: timestamp })
} else if (events[i].event === 'Revealed') {
value = events[i].returnValues.values
if (jobId) {
res.push({epoch: events[i].returnValues.epoch, staker: staker, action: events[i].event, value: value[jobId - 1], timestamp: timestamp })
} else {
res.push({epoch: events[i].returnValues.epoch, staker: staker, action: events[i].event, value: value, timestamp: timestamp })
}
}
}
return res
}
async function getStakingEvents (provider) {
let web3 = await getWeb3Instance(provider)
let stakeManager = await getStakeManager(provider)
let blockNumber = await web3.eth.getBlockNumber()
// let epoch = Number(await getEpoch()) - 1
let events = await stakeManager.getPastEvents('allEvents', {
fromBlock: Math.max(0, Number(blockNumber) - 1000),
// fromBlock: 0,
toBlock: 'latest'
})
// event Staked(uint256 epoch, uint256 stakerId, uint256 amount, uint256 timestamp)
// event Unstaked(uint256 epoch, uint256 stakerId, uint256 amount, uint256 timestamp)
// event Withdrew(uint256 epoch, uint256 stakerId, uint256 amount, uint256 timestamp)
// console.log(events[2].returnValues)
let res = []
let value
let staker
let timestamp
for (let i = 0; i < events.length; i++) {
if (events[i].event === 'WriterAdded' || events[i].event === 'StakeGettingRewardChange') continue
if (events[i].returnValues.stakerId !== undefined) {
staker = (await stakeManager.methods.getStaker(events[i].returnValues.stakerId).call())[1]
}
let data = events[i].returnValues
if (events[i].event === 'StakeChange') {
res.push({epoch: data.epoch, staker: staker, action: data.reason, previousStake: data.previousStake, newStake: data.newStake, timestamp: data.timestamp })
} else if (events[i].event === 'RewardPoolChange') {
res.push({epoch: data.epoch, action: events[i].event, previousStake: data.prevRewardPool, newStake: data.rewardPool, timestamp: data.timestamp })
} else if (events[i].event === 'StakeGettingRewardChange') {
res.push({epoch: data.epoch, action: events[i].event, previousStake: data.prevStakeGettingReward, newStake: data.stakeGettingReward, timestamp: data.timestamp })
} else {
res.push({epoch: data.epoch, staker: staker, action: events[i].event, previousStake: data.previousStake, newStake: data.newStake, timestamp: data.timestamp })
}
// emit RewardPoolChange(epoch, prevRewardPool, rewardPool, now)
//
// emit StakeGettingRewardChange(epoch, prevStakeGettingReward, stakeGettingReward, now)
}
// emit StakeChange(_id, _stake, _reason)
return res
}
async function getStakerEvents (_address) {
let web3 = await getWeb3Instance()
let stakeManager = await getStakeManager()
let blockNumber = await web3.eth.getBlockNumber()
// let epoch = Number(await getEpoch()) - 1
let stakerId = String(await stakeManager.methods.stakerIds(_address).call())
console.log('stakerId', stakerId)
let events = await stakeManager.getPastEvents('allEvents', {
fromBlock: Math.max(0, Number(blockNumber) - 1000),
// filter: {stakerId: stakerId},
// fromBlock: 0,
toBlock: 'latest'
})
// console.log(events[3])
// event Staked(uint256 epoch, uint256 stakerId, uint256 amount, uint256 timestamp)
// event Unstaked(uint256 epoch, uint256 stakerId, uint256 amount, uint256 timestamp)
// event Withdrew(uint256 epoch, uint256 stakerId, uint256 amount, uint256 timestamp)
// console.log(events[2].returnValues)
let res = []
let value
let staker
let timestamp
for (let i = 0; i < events.length; i++) {
if (events[i].returnValues.stakerId !== stakerId) continue
if (events[i].event === 'WriterAdded') continue
if (events[i].returnValues.stakerId !== undefined) {
staker = (await stakeManager.methods.getStaker(events[i].returnValues.stakerId).call())[1]
}
let data = events[i].returnValues
if (events[i].event === 'StakeChange') {
res.push({epoch: data.epoch, staker: staker, action: data.reason, previousStake: data.previousStake, newStake: data.newStake, timestamp: data.timestamp })
// } else if (events[i].event === 'RewardPoolChange') {
// // res.push({epoch: data.epoch, action: events[i].event, previousStake: data.prevRewardPool, newStake: data.rewardPool, timestamp: data.timestamp })
//
// } else if (events[i].event === 'StakeGettingRewardChange') {
// // res.push({epoch: data.epoch, action: events[i].event, previousStake: data.prevStakeGettingReward, newStake: data.stakeGettingReward, timestamp: data.timestamp })
//
// } else {
// res.push({epoch: data.epoch, staker: staker, action: events[i].event, previousStake: data.previousStake, newStake: data.newStake, timestamp: data.timestamp })
}
// emit RewardPoolChange(epoch, prevRewardPool, rewardPool, now)
//
// emit StakeGettingRewardChange(epoch, prevStakeGettingReward, stakeGettingReward, now)
}
// emit StakeChange(_id, _stake, _reason)
return res
}
async function getPoolChanges () {
let web3 = await getWeb3Instance()
let stakeManager = await getStakeManager()
let blockNumber = await web3.eth.getBlockNumber()
// let epoch = Number(await getEpoch()) - 1
let events = await stakeManager.getPastEvents('allEvents', {
fromBlock: Math.max(0, Number(blockNumber) - 1000),
// fromBlock: 0,
toBlock: 'latest'
})
// console.log(events[2].returnValues)
let res = []
let value
let staker
let timestamp
for (let i = 0; i < events.length; i++) {
// staker = (await stakeManager.methods.getStaker(events[i].returnValues.stakerId).call())[1]
let data = events[i].returnValues
console.log(events[i].event)
// event RewardPoolChange(uint256 epoch, uint256 value, uint256 timestamp)
// event StakeGettingRewardChange(uint256 epoch, uint256 value, uint256 timestamp)
if (events[i].event === 'RewardPoolChanges' || events[i].event === 'StakeGettingRewardChange') {
res.push({epoch: data.epoch, value: data.value, action: events[i].event, timestamp: data.timestamp })
// } else {
// res.push({epoch: data.epoch, value: data.value, action: events[i].event, timestamp: data.timestamp })
}
}
// emit StakeChange(_id, _stake, _reason)
return res
}
async function getBlockEvents (provider) {
let web3 = await getWeb3Instance(provider)
let blockManager = await getBlockManager(provider)
let stakeManager = await getStakeManager(provider)
let blockNumber = await web3.eth.getBlockNumber()
let epoch = Number(await getEpoch(provider)) - 1
let events = await blockManager.getPastEvents('allEvents', {
fromBlock: Math.max(0, Number(blockNumber) - 1000),
toBlock: 'latest'
})
// event BlockConfirmed(uint256 epoch,
// uint256 stakerId,
// uint256[] medians,
// uint256[] jobIds,
// uint256 timestamp)
// emit Proposed(epoch, proposerId, jobIds, medians, lowerCutoffs, higherCutoffs, iteration, biggestStakerId, now)
// console.log(events[0])
let res = []
let value
let staker
let timestamp
for (let i = 0; i < events.length; i++) {
if (events[i].event === 'WriterAdded' || events[i].event === 'DebugUint256') continue
// console.log(events[i])
staker = (await stakeManager.methods.getStaker(events[i].returnValues.stakerId).call())[1]
let data = events[i].returnValues
if (events[i].event === 'Proposed') {
res.push({epoch: data.epoch,
staker: staker,
action: events[i].event,
medians: data.medians,
lowerCutoffs: data.lowerCutoffs,
higherCutoffs: data.higherCutoffs,
jobIds: data.jobIds,
timestamp: data.timestamp,
iteration: data.iteration,
biggestStakerId: data.biggestStakerId})
} else {
res.push({epoch: data.epoch,
staker: staker,
action: events[i].event,
medians: data.medians,
lowerCutoffs: data.lowerCutoffs,
higherCutoffs: data.higherCutoffs,
jobIds: data.jobIds,
timestamp: data.timestamp,
iteration: '',
biggestStakerId: ''})
}
}
return res
}
async function getJobEvents (provider) {
let web3 = await getWeb3Instance(provider)
let jobManager = await getJobManager(provider)
let blockNumber = await web3.eth.getBlockNumber()
// let epoch = Number(await getEpoch()) - 1
let events = await jobManager.getPastEvents('allEvents', {
fromBlock: Math.max(0, Number(blockNumber) - 1000),
toBlock: 'latest'
})
// event JobCreated(uint256 id, uint256 epoch, string url, string selector, bool repeat,
// address creator, uint256 credit, uint256 timestamp)
//
// event JobReported(uint256 id, uint256 value, uint256 epoch,
// string url, string selector, bool repeat,
// address creator, uint256 credit, bool fulfilled, uint256 timestamp)
//
// console.log(events[2].returnValues)
let res = []
let value
let staker
let timestamp
for (let i = 0; i < events.length; i++) {
// staker = (await stakeManager.methods.getStaker(events[i].returnValues.stakerId).call())[1]
let data = events[i].returnValues
if (events[i].event === 'WriterAdded') continue
res.push({epoch: data.epoch, id: data.id, action: events[i].event, url: data.url, selector: data.selector, name: data.name, repeat: data.repeat,
creator: data.creator, credit: data.credit, timestamp: data.timestamp })
}
return res
}
async function commit (votes, secret, account) {
let web3 = await getWeb3Instance()
let stateManager = await getStateManager()
let stakeManager = await getStakeManager()
let voteManager = await getVoteManager()
if (Number(await stateManager.methods.getState().call()) != 0) {
throw ('Not commit state')
}
// let votes = [100, 200, 300, 400, 500, 600, 700, 800, 900]
// console.log(votes)
let tree = merkle('keccak256').sync(votes)
// console.log(tree.root())
let root = tree.root()
let stakerId = Number(await stakeManager.methods.stakerIds(account).call())
let epoch = Number(await stateManager.methods.getEpoch().call())
if ((await voteManager.methods.commitments(epoch, stakerId).call()) != 0) {
throw ('Already Committed')
}
let commitment = web3.utils.soliditySha3(epoch, root, secret)
let nonce = await web3.eth.getTransactionCount(account, 'pending')
console.log(' committing epoch, root, commitment, secret, account, nonce', epoch, root, commitment, secret, account, nonce)
let tx = await voteManager.methods.commit(epoch, commitment).send({'from': account, 'nonce': nonce})
return tx
}
async function reveal (votes, secret, commitAccount, account) {
let web3 = await getWeb3Instance()
let stateManager = await getStateManager()
let stakeManager = await getStakeManager()
let voteManager = await getVoteManager()
if (Number(await stateManager.methods.getState().call()) != 1) {
throw new Error('Not reveal state')
}
let stakerId = Number(await stakeManager.methods.stakerIds(account).call())
let epoch = Number(await stateManager.methods.getEpoch().call())
console.log('stakerId', stakerId)
if ((await voteManager.methods.commitments(epoch, stakerId).call()) === 0) {
throw new Error('Did not commit')
}
let revealed = await voteManager.methods.votes(epoch, stakerId, 0).call()
// console.log('revealed', revealed)
let voted = revealed.vote
// console.log('voted', voted)
if (voted !== undefined) {
throw new Error('Already Revealed', voted)
}
let tree = merkle('keccak256').sync(votes)
// console.log(tree.root())
let root = tree.root()
let proof = []
for (let i = 0; i < votes.length; i++) {
proof.push(tree.getProofPath(i, true, true))
}
// console.log('epoch', epoch)
console.log('revealing vote for epoch', Number(await stateManager.methods.getEpoch().call()), 'votes', votes, 'root', root, 'proof', proof, 'secret', secret, 'commitAccount', commitAccount)
let nonce = await web3.eth.getTransactionCount(account, 'pending')
let tx = await voteManager.methods.reveal(epoch, root, votes, proof, secret, commitAccount).send({'from': account, 'nonce': nonce})
// await voteManager.reveal(1, tree.root(), votes, proof,
// '0x727d5c9e6d18ed15ce7ac8d3cce6ec8a0e9c02481415c0823ea49d847ccb9ddd',
// accounts[1], { 'from': accounts[1] })
return tx
}
async function getBlock (epoch) {
let blockManager = await getBlockManager()
let block = await blockManager.methods.blocks(epoch).call()
return (block)
}
async function propose (account) {
let web3 = await getWeb3Instance()
let stateManager = await getStateManager()
let stakeManager = await getStakeManager()
let blockManager = await getBlockManager()
let random = await getRandom()
if (Number(await stateManager.methods.getState().call()) != 2) {
throw ('Not propose state')
}
let stakerId = Number(await stakeManager.methods.stakerIds(account).call())
let epoch = Number(await stateManager.methods.getEpoch().call())
// console.log('epoch', epoch)
// let getBlock = await blockManager.methods.proposedBlocks(epoch).call()
// if (getBlock) {
// let proposerId = Number(getBlock.proposerId)
// // console.log('proposerId', proposerId)
// if (proposerId === stakerId) {
// throw new Error('Already proposed')
// }
// }
// let numStakers = Number(await blockManager.methods.numStakers().call())
// console.log('numStakers', numStakers)
let staker = await stakeManager.methods.getStaker(stakerId).call()
let numStakers = await stakeManager.methods.getNumStakers().call()
let stake = Number(staker.stake)
console.log('stake', stake)
let biggestStake = (await getBiggestStakeAndId(stakeManager))[0]
console.log('biggestStake', biggestStake)
let biggestStakerId = (await getBiggestStakeAndId(stakeManager))[1]
console.log('biggestStakerId', biggestStakerId)
let blockHashes = await random.methods.blockHashes(numBlocks).call()
console.log(' biggestStake, stake, stakerId, numStakers, blockHashes', biggestStake, stake, stakerId, numStakers, blockHashes)
let iteration = await getIteration(random, biggestStake, stake, stakerId, numStakers, blockHashes)
console.log('iteration1', iteration)
let nonce = await web3.eth.getTransactionCount(account, 'pending')
let block = await makeBlock()
let jobs = await getActiveJobs()
let jobIds = []
for (let i = 0; i < jobs.length; i++) {
jobIds.push(Number(jobs[i].id))
}
console.log('epoch, block, jobIds, iteration, biggestStakerId', epoch, block, jobIds, iteration, biggestStakerId)
let tx = await blockManager.methods.propose(epoch, block, jobIds, iteration, biggestStakerId).send({'from': account, 'nonce': nonce})
return tx
//
//
// let res = await getIteration()
// let electedProposer = res[0]
// let iteration = res[1]
// let biggestStakerId = res[2]
// // console.log('biggestStakerId', biggestStakerId)
// // console.log('electedProposer, iteration', electedProposer, iteration)
// let block = await makeBlock()
// // console.log('block', block)
// let median = block
// console.log('epoch, median, electedProposer, iteration, biggestStakerId', epoch, median, electedProposer, iteration, biggestStakerId)
// const nonce = await web3.eth.getTransactionCount(account, 'pending')
// let tx = await blockManager.methods.propose(epoch, medians, iteration, biggestStakerId).send({'from': account, 'nonce': nonce})
// return tx
}
// automatically calculate alternative block and submit
async function dispute (account) {
let web3 = await getWeb3Instance()
let stateManager = await getStateManager()
let blockManager = await getBlockManager()
let epoch = Number(await stateManager.methods.getEpoch().call())
let res = await getSortedVotes()
let sortedVotes = res[0]
let iter = Math.ceil(sortedVotes.length / 1000)
for (let i = 0; i < iter; i++) {
console.log(epoch, sortedVotes.slice(i * 1000, (i * 1000) + 1000))
await blockManager.methods.giveSorted(epoch, sortedVotes.slice(i * 1000, (i * 1000) + 1000)).send({from: account,
nonce: String(nonce)})
}
const nonce = await web3.eth.getTransactionCount(account, 'pending')
return blockManager.methods.proposeAlt(epoch).send({from: account,
nonce: String(nonce)})
}
async function getState () {
let stateManager = await getStateManager()
return Number(await stateManager.methods.getState().call())
}
async function getEpoch (provider) {
let stateManager = await getStateManager(provider)
return Number(await stateManager.methods.getEpoch().call())
}
async function getStakerId (address) {
let stakeManager = await getStakeManager()
return Number(await stakeManager.methods.stakerIds(address).call())
}
async function getMinStake () {
let constants = await getConstants()
return Number((await constants.methods.minStake().call()))
}
async function getStaker (stakerId) {
let stakeManager = await getStakeManager()
return (await stakeManager.methods.stakers(stakerId).call())
}
async function getBiggestStakeAndId (stakeManager) {
// async function getBiggestStakeAndId (schelling) {
let biggestStake = 0
let biggestStakerId = 0
let numStakers = await stakeManager.methods.numStakers().call()
for (let i = 1; i <= numStakers; i++) {
let stake = Number((await stakeManager.methods.stakers(i).call()).stake)
if (stake > biggestStake) {
biggestStake = stake
biggestStakerId = i
}
}
return ([biggestStake, biggestStakerId])
}
async function prng (seed, max, blockHashes) {
let web3 = await getWeb3Instance()
let hashh = await prngHash(seed, blockHashes)
let sum = web3.utils.toBN(hashh)
max = web3.utils.toBN(max)
return (sum.mod(max))
}
// pseudo random hash generator based on block hashes.
async function prngHash (seed, blockHashes) {
let web3 = await getWeb3Instance()
// let sum = blockHashes(numBlocks)
let sum = await web3.utils.soliditySha3(blockHashes, seed)
// console.log('prngHash', sum)
return (sum)
}
async function getIteration (random, biggestStake, stake, stakerId, numStakers, blockHashes) {
let j = 0
console.log(blockHashes)
for (let i = 0; i < 10000000000; i++) {
// console.log('iteration ', i)
let isElected = await isElectedProposer(random, i, biggestStake, stake, stakerId, numStakers, blockHashes)
if (isElected) return (i)
}
}
async function isElectedProposer (random, iteration, biggestStake, stake, stakerId, numStakers, blockHashes) {
let web3 = await getWeb3Instance()
// rand = 0 -> totalStake-1
// add +1 since prng returns 0 to max-1 and staker start from 1
let seed = await web3.utils.soliditySha3(iteration)
// console.log('seed', seed)
if ((Number(await prng(seed, numStakers, blockHashes)) + 1) !== stakerId) return (false)
let seed2 = await web3.utils.soliditySha3(stakerId, iteration)
let randHash = await prngHash(seed2, blockHashes)
let rand = Number((await web3.utils.toBN(randHash)).mod(await web3.utils.toBN(2 ** 32)))
// let biggestStake = stakers[biggestStake].stake
if (rand * (biggestStake) > stake * (2 ** 32)) return (false)
return (true)
}
async function makeBlock () {
let stateManager = await getStateManager()
let voteManager = await getVoteManager()
let medians = []
let jobs = await getActiveJobs()
for (let assetId = 0; assetId < jobs.length; assetId++) {
let res = await getSortedVotes(assetId)
let sortedVotes = res[1]
// console.log('sortedVotes', sortedVotes)
let epoch = Number(await stateManager.methods.getEpoch().call())
let totalStakeRevealed = Number(await voteManager.methods.totalStakeRevealed(epoch, assetId).call())
// console.log('totalStakeRevealed', totalStakeRevealed)
let medianWeight = Math.floor(totalStakeRevealed / 2)
// console.log('medianWeight', medianWeight)
let i = 0
let median = 0
let weight = 0
for (i = 0; i < sortedVotes.length; i++) {
weight += sortedVotes[i][1]
// console.log('weight', weight)
if (weight > medianWeight && median === 0) median = sortedVotes[i][0]
}
medians.push(median)
}
return (medians)
}
async function getSortedVotes (assetId) {
let stateManager = await getStateManager()
let stakeManager = await getStakeManager()
let voteManager = await getVoteManager()
let epoch = Number(await stateManager.methods.getEpoch().call())
let numStakers = Number(await stakeManager.methods.numStakers().call())
let values = []
let voteWeights = []
// get all values that stakers voted.
for (let i = 1; i <= numStakers; i++) {
let vote = Number((await voteManager.methods.votes(epoch, i, assetId).call()).value)
// console.log(i, 'voted', vote)
if (vote === 0) continue // didnt vote
if (values.indexOf(vote) === -1) values.push(vote)
}
values.sort(function (a, b) { return a - b })
// get weights of those values
for (let val of values) {
let weight = Number(await voteManager.methods.voteWeights(epoch, assetId, val).call())
voteWeights.push([val, weight])
}
return [values, voteWeights]
}
async function getBiggestStakerId (stakeManager) {
let numStakers = Number(await stakeManager.methods.numStakers().call())
// console.log('numStakers', numStakers)
let biggestStake = 0
let biggestStakerId = 0
for (let i = 1; i <= numStakers; i++) {
let stake = Number((await stakeManager.methods.stakers(i).call()).stake)
if (stake > biggestStake) {
biggestStake = stake
biggestStakerId = i
}
}
return biggestStakerId
}
async function getStake (stakerId) {
let stakeManager = await getStakeManager()
return String((await stakeManager.methods.stakers(stakerId).call()).stake)
}
async function getProposedBlockMedians (epoch, proposedBlock) {
let blockManager = await getBlockManager()
return (await blockManager.methods.getProposedBlockMedians(epoch, proposedBlock).call())
}
async function getProposedBlock (epoch, proposedBlock) {
let blockManager = await getBlockManager()
return (await blockManager.methods.getProposedBlock(epoch, proposedBlock).call())
}
async function getNumProposedBlocks (epoch) {
let blockManager = await getBlockManager()
return (await blockManager.methods.getNumProposedBlocks(epoch).call())
}
async function getSchBalance (address) {
let simpleToken = await getSimpleToken()
return String(await simpleToken.methods.balanceOf(address).call())
}
async function getRazorBalance (address) {
const etherscanKey = fs.readFileSync('.etherscan').toString().trim()
const tokenAddress = fs.readFileSync('.tokenAddress').toString().trim()
const url = `https://api.etherscan.io/api?module=account&action=tokenbalance&contractaddress=${tokenAddress}&address=${address}&tag=latest&apikey=${etherscanKey}`
try {
response = await axios.get(url, {timeout: 60000})
return response.data.result/1000000000000000000
} catch (e) {
console.error(e)
}
}
async function getCirculatingSupply() {
const addresses = fs.readFileSync('.lockedTokenAddresses').toString().trim().split("\n")
let lockedValue = 0
for(let i=0; i<addresses.length; i++) {
lockedValue = lockedValue + await getRazorBalance(addresses[i])
}
return (TOTAL_SUPPLY - lockedValue)
}
async function getEthBalance (address) {
let web3 = await getWeb3Instance()
return String(await web3.eth.getBalance(address))
}
async function sign (input, account) {
let web3 = await getWeb3Instance()
return await web3.eth.sign(input, account)
}
module.exports = {
login: login,
sign: sign,
// transfer: transfer,
// approve: approve,
// stake: stake,
commit: commit,
reveal: reveal,
propose: propose,
dispute: dispute,
getState: getState,
getEpoch: getEpoch,
getStakerId: getStakerId,
getMinStake: getMinStake,
getStaker: getStaker,
getStake: getStake,
getBiggestStakerId: getBiggestStakerId,
getBiggestStakeAndId: getBiggestStakeAndId,
getBlock: getBlock,
prng: prng,
prngHash: prngHash,
getIteration: getIteration,
isElectedProposer: isElectedProposer,
makeBlock: makeBlock,
getProposedBlockMedians: getProposedBlockMedians,
getProposedBlock: getProposedBlock,
getNumProposedBlocks: getNumProposedBlocks,
createJob: createJob,
getActiveJobs: getActiveJobs,
getJobValues: getJobValues,
getJobs: getJobs,
getResult: getResult,
getJob: getJob,
getNumJobs: getNumJobs,
getVotesLastEpoch: getVotesLastEpoch,
getVotingEvents: getVotingEvents,
getStakingEvents: getStakingEvents,
getJobEvents: getJobEvents,
getBlockEvents: getBlockEvents,
getStakers: getStakers,
getPoolChanges: getPoolChanges,
getStakerEvents: getStakerEvents,
getEthBalance: getEthBalance,
getSchBalance: getSchBalance,
getCirculatingSupply: getCirculatingSupply
}