-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathdraw.ts
478 lines (420 loc) · 17.9 KB
/
draw.ts
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
import { anyValue } from "@nomicfoundation/hardhat-chai-matchers/withArgs";
import { deployments, ethers, getNamedAccounts, network } from "hardhat";
import { BigNumber, ContractReceipt, ContractTransaction, Wallet } from "ethers";
import {
PNK,
KlerosCore,
ArbitrableExample,
HomeGateway,
DisputeKitClassic,
SortitionModule,
VRFConsumerV2,
VRFCoordinatorV2Mock,
} from "../../typechain-types";
import { expect } from "chai";
import { DrawEvent } from "../../typechain-types/src/kleros-v1/kleros-liquid-xdai/XKlerosLiquidV2";
import { Courts } from "../../deploy/utils";
/* eslint-disable no-unused-vars */
/* eslint-disable no-unused-expressions */ // https://github.com/standard/standard/issues/690#issuecomment-278533482
describe("Draw Benchmark", async () => {
const ONE_TENTH_ETH = BigNumber.from(10).pow(17);
const ONE_THOUSAND_PNK = BigNumber.from(10).pow(21);
const enum Period {
evidence, // Evidence can be submitted. This is also when drawing has to take place.
commit, // Jurors commit a hashed vote. This is skipped for courts without hidden votes.
vote, // Jurors reveal/cast their vote depending on whether the court has hidden votes or not.
appeal, // The dispute can be appealed.
execution, // Tokens are redistributed and the ruling is executed.
}
const enum Phase {
staking, // Stake can be updated during this phase.
freezing, // Phase during which the dispute kits can undergo the drawing process. Staking is not allowed during this phase.
}
const enum DisputeKitPhase {
resolving, // No disputes that need drawing.
generating, // Waiting for a random number. Pass as soon as it is ready.
drawing, // Jurors can be drawn.
}
let deployer;
let relayer;
let disputeKit;
let pnk;
let core;
let arbitrable;
let homeGateway;
let sortitionModule;
let rng;
let parentCourtMinStake: BigNumber;
let childCourtMinStake: BigNumber;
const RANDOM = BigNumber.from("61688911660239508166491237672720926005752254046266901728404745669596507231249");
const PARENT_COURT = 1;
const CHILD_COURT = 2;
let vrfConsumer;
let vrfCoordinator;
beforeEach("Setup", async () => {
({ deployer, relayer } = await getNamedAccounts());
await deployments.fixture(["Arbitration", "VeaMock"], {
fallbackToGlobal: true,
keepExistingDeployments: false,
});
disputeKit = (await ethers.getContract("DisputeKitClassic")) as DisputeKitClassic;
pnk = (await ethers.getContract("PNK")) as PNK;
core = (await ethers.getContract("KlerosCore")) as KlerosCore;
homeGateway = (await ethers.getContract("HomeGatewayToEthereum")) as HomeGateway;
arbitrable = (await ethers.getContract("ArbitrableExample")) as ArbitrableExample;
sortitionModule = (await ethers.getContract("SortitionModule")) as SortitionModule;
vrfConsumer = (await ethers.getContract("VRFConsumerV2")) as VRFConsumerV2;
vrfCoordinator = (await ethers.getContract("VRFCoordinatorV2Mock")) as VRFCoordinatorV2Mock;
parentCourtMinStake = await core.courts(Courts.GENERAL).then((court) => court.minStake);
childCourtMinStake = BigNumber.from(10).pow(20).mul(3); // 300 PNK
// Make the tests more deterministic with this dummy RNG
rng = await deployments.deploy("IncrementalNG", {
from: deployer,
args: [RANDOM],
log: true,
});
await sortitionModule.changeRandomNumberGenerator(rng.address);
// CourtId 2 = CHILD_COURT
const minStake = BigNumber.from(10).pow(20).mul(3); // 300 PNK
const alpha = 10000;
const feeForJuror = BigNumber.from(10).pow(17);
await core.createCourt(
1,
false,
minStake,
alpha,
feeForJuror,
256,
[0, 0, 0, 10], // evidencePeriod, commitPeriod, votePeriod, appealPeriod
ethers.utils.hexlify(5), // Extra data for sortition module will return the default value of K)
[1]
);
});
type CountedDraws = { [address: string]: number };
type SetStake = (wallet: Wallet) => Promise<void>;
type ExpectFromDraw = (drawTx: Promise<ContractTransaction>) => Promise<void>;
const draw = async (
stake: SetStake,
createDisputeCourtId: number,
expectFromDraw: ExpectFromDraw,
unstake: SetStake
) => {
const arbitrationCost = ONE_TENTH_ETH.mul(3);
const [bridger] = await ethers.getSigners();
const wallets: Wallet[] = [];
// Stake some jurors
for (let i = 0; i < 16; i++) {
const wallet = ethers.Wallet.createRandom().connect(ethers.provider);
wallets.push(wallet);
await bridger.sendTransaction({
to: wallet.address,
value: ethers.utils.parseEther("10"),
});
expect(await wallet.getBalance()).to.equal(ethers.utils.parseEther("10"));
await pnk.transfer(wallet.address, ONE_THOUSAND_PNK.mul(10));
expect(await pnk.balanceOf(wallet.address)).to.equal(ONE_THOUSAND_PNK.mul(10));
await pnk.connect(wallet).approve(core.address, ONE_THOUSAND_PNK.mul(10), { gasLimit: 300000 });
await stake(wallet);
}
// Create a dispute
const tx = await arbitrable.functions["createDispute(string)"]("future of france", {
value: arbitrationCost,
});
const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
const [disputeId] = ethers.utils.defaultAbiCoder.decode(["uint"], `0x${trace.returnValue}`);
const lastBlock = await ethers.provider.getBlock(tx.blockNumber - 1);
// Relayer tx
const tx2 = await homeGateway
.connect(await ethers.getSigner(relayer))
.functions["relayCreateDispute((bytes32,uint256,address,uint256,uint256,uint256,string,uint256,bytes))"](
{
foreignBlockHash: lastBlock.hash,
foreignChainID: 31337,
foreignArbitrable: arbitrable.address,
foreignDisputeID: disputeId,
externalDisputeID: ethers.utils.keccak256(ethers.utils.toUtf8Bytes("future of france")),
templateId: 0,
templateUri: "",
choices: 2,
extraData: `0x000000000000000000000000000000000000000000000000000000000000000${createDisputeCourtId}0000000000000000000000000000000000000000000000000000000000000003`,
},
{ value: arbitrationCost }
);
await network.provider.send("evm_increaseTime", [2000]); // Wait for minStakingTime
await network.provider.send("evm_mine");
await sortitionModule.passPhase(); // Staking -> Generating
await sortitionModule.passPhase(); // Generating -> Drawing
await expectFromDraw(core.draw(0, 20, { gasLimit: 1000000 }));
await network.provider.send("evm_increaseTime", [2000]); // Wait for maxDrawingTime
await sortitionModule.passPhase(); // Drawing -> Staking
expect(await sortitionModule.phase()).to.equal(Phase.staking);
// Unstake jurors
for (const wallet of wallets) {
await unstake(wallet);
}
};
const countDraws = async (blockNumber: number) => {
const draws: Array<DrawEvent> = await core.queryFilter(core.filters.Draw(), blockNumber, blockNumber);
return draws.reduce((acc: { [address: string]: number }, draw) => {
const address = draw.args._address;
acc[address] = acc[address] ? acc[address] + 1 : 1;
return acc;
}, {});
};
it("Stakes in parent court and should draw jurors in parent court", async () => {
const stake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(PARENT_COURT, ONE_THOUSAND_PNK.mul(5), { gasLimit: 5000000 });
expect(await core.getJurorBalance(wallet.address, 1)).to.deep.equal([
ONE_THOUSAND_PNK.mul(5), // totalStaked
0, // totalLocked
ONE_THOUSAND_PNK.mul(5), // stakedInCourt
PARENT_COURT, // nbOfCourts
]);
};
let countedDraws: CountedDraws;
const expectFromDraw = async (drawTx: Promise<ContractTransaction>) => {
expect(await core.getRoundInfo(0, 0).then((round) => round.drawIterations)).to.equal(3);
const tx = await (await drawTx).wait();
expect(tx)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 0)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 1)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 2);
countedDraws = await countDraws(tx.blockNumber);
for (const [address, draws] of Object.entries(countedDraws)) {
expect(await core.getJurorBalance(address, PARENT_COURT)).to.deep.equal([
ONE_THOUSAND_PNK.mul(5), // totalStaked
parentCourtMinStake.mul(draws), // totalLocked
ONE_THOUSAND_PNK.mul(5), // stakedInCourt
1, // nbOfCourts
]);
expect(await core.getJurorBalance(address, CHILD_COURT)).to.deep.equal([
ONE_THOUSAND_PNK.mul(5), // totalStaked
parentCourtMinStake.mul(draws), // totalLocked
0, // stakedInCourt
1, // nbOfCourts
]);
}
};
const unstake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(PARENT_COURT, 0, { gasLimit: 5000000 });
const locked = parentCourtMinStake.mul(countedDraws[wallet.address] ?? 0);
expect(
await core.getJurorBalance(wallet.address, PARENT_COURT),
"Drawn jurors have a locked stake in the parent court"
).to.deep.equal([
0, // totalStaked
locked, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
expect(
await core.getJurorBalance(wallet.address, CHILD_COURT),
"No locked stake in the child court"
).to.deep.equal([
0, // totalStaked
locked, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
};
await draw(stake, PARENT_COURT, expectFromDraw, unstake);
});
it("Stakes in parent court and should draw nobody in subcourt", async () => {
const stake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(PARENT_COURT, ONE_THOUSAND_PNK.mul(5), { gasLimit: 5000000 });
};
const expectFromDraw = async (drawTx: Promise<ContractTransaction>) => {
expect(await core.getRoundInfo(0, 0).then((round) => round.drawIterations)).to.equal(20);
expect(await drawTx).to.not.emit(core, "Draw");
};
const unstake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(PARENT_COURT, 0, { gasLimit: 5000000 });
expect(
await core.getJurorBalance(wallet.address, PARENT_COURT),
"No locked stake in the parent court"
).to.deep.equal([
0, // totalStaked
0, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
expect(
await core.getJurorBalance(wallet.address, CHILD_COURT),
"No locked stake in the child court"
).to.deep.equal([
0, // totalStaked
0, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
};
await draw(stake, CHILD_COURT, expectFromDraw, unstake);
});
it("Stakes in subcourt and should draw jurors in parent court", async () => {
const stake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(CHILD_COURT, ONE_THOUSAND_PNK.mul(5), { gasLimit: 5000000 });
};
let countedDraws: CountedDraws;
const expectFromDraw = async (drawTx: Promise<ContractTransaction>) => {
expect(await core.getRoundInfo(0, 0).then((round) => round.drawIterations)).to.equal(3);
const tx = await (await drawTx).wait();
expect(tx)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 0)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 1)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 2);
countedDraws = await countDraws(tx.blockNumber);
for (const [address, draws] of Object.entries(countedDraws)) {
expect(await core.getJurorBalance(address, PARENT_COURT)).to.deep.equal([
ONE_THOUSAND_PNK.mul(5), // totalStaked
parentCourtMinStake.mul(draws), // totalLocked
0, // stakedInCourt
1, // nbOfCourts
]);
expect(await core.getJurorBalance(address, CHILD_COURT)).to.deep.equal([
ONE_THOUSAND_PNK.mul(5), // totalStaked
parentCourtMinStake.mul(draws), // totalLocked
ONE_THOUSAND_PNK.mul(5), // stakedInCourt
1, // nbOfCourts
]);
}
};
const unstake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(CHILD_COURT, 0, { gasLimit: 5000000 });
const locked = parentCourtMinStake.mul(countedDraws[wallet.address] ?? 0);
expect(
await core.getJurorBalance(wallet.address, PARENT_COURT),
"No locked stake in the parent court"
).to.deep.equal([
0, // totalStaked
locked, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
expect(
await core.getJurorBalance(wallet.address, CHILD_COURT),
"Drawn jurors have a locked stake in the child court"
).to.deep.equal([
0, // totalStaked
locked, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
};
await draw(stake, PARENT_COURT, expectFromDraw, unstake);
});
it("Stakes in subcourt and should draw jurors in subcourt", async () => {
const stake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(CHILD_COURT, ONE_THOUSAND_PNK.mul(5), { gasLimit: 5000000 });
};
let countedDraws: CountedDraws;
const expectFromDraw = async (drawTx: Promise<ContractTransaction>) => {
expect(await core.getRoundInfo(0, 0).then((round) => round.drawIterations)).to.equal(3);
const tx = await (await drawTx).wait();
expect(tx)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 0)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 1)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 2);
countedDraws = await countDraws(tx.blockNumber);
for (const [address, draws] of Object.entries(countedDraws)) {
expect(await core.getJurorBalance(address, PARENT_COURT)).to.deep.equal([
ONE_THOUSAND_PNK.mul(5), // totalStaked
childCourtMinStake.mul(draws), // totalLocked
0, // stakedInCourt
1, // nbOfCourts
]);
expect(await core.getJurorBalance(address, CHILD_COURT)).to.deep.equal([
ONE_THOUSAND_PNK.mul(5), // totalStaked
childCourtMinStake.mul(draws), // totalLocked
ONE_THOUSAND_PNK.mul(5), // stakedInCourt
1, // nbOfCourts
]);
}
};
const unstake = async (wallet: Wallet) => {
await core.connect(wallet).setStake(CHILD_COURT, 0, { gasLimit: 5000000 });
const locked = childCourtMinStake.mul(countedDraws[wallet.address] ?? 0);
expect(
await core.getJurorBalance(wallet.address, PARENT_COURT),
"No locked stake in the parent court"
).to.deep.equal([
0, // totalStaked
locked, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
expect(
await core.getJurorBalance(wallet.address, CHILD_COURT),
"Drawn jurors have a locked stake in the child court"
).to.deep.equal([
0, // totalStaked
locked, // totalLocked
0, // stakedInCourt
0, // nbOfCourts
]);
};
await draw(stake, CHILD_COURT, expectFromDraw, unstake);
});
it("Draw Benchmark - Chainlink VRF v2", async () => {
const arbitrationCost = ONE_TENTH_ETH.mul(3);
const [bridger] = await ethers.getSigners();
await sortitionModule.changeRandomNumberGenerator(vrfConsumer.address);
// Stake some jurors
for (let i = 0; i < 16; i++) {
const wallet = ethers.Wallet.createRandom().connect(ethers.provider);
await bridger.sendTransaction({
to: wallet.address,
value: ethers.utils.parseEther("10"),
});
expect(await wallet.getBalance()).to.equal(ethers.utils.parseEther("10"));
await pnk.transfer(wallet.address, ONE_THOUSAND_PNK.mul(10));
expect(await pnk.balanceOf(wallet.address)).to.equal(ONE_THOUSAND_PNK.mul(10));
await pnk.connect(wallet).approve(core.address, ONE_THOUSAND_PNK.mul(10), { gasLimit: 300000 });
await core.connect(wallet).setStake(1, ONE_THOUSAND_PNK.mul(10), { gasLimit: 5000000 });
}
// Create a dispute
const tx = await arbitrable.functions["createDispute(string)"]("RNG test", {
value: arbitrationCost,
});
const trace = await network.provider.send("debug_traceTransaction", [tx.hash]);
const [disputeId] = ethers.utils.defaultAbiCoder.decode(["uint"], `0x${trace.returnValue}`);
const lastBlock = await ethers.provider.getBlock(tx.blockNumber - 1);
// Relayer tx
const tx2 = await homeGateway
.connect(await ethers.getSigner(relayer))
.functions["relayCreateDispute((bytes32,uint256,address,uint256,uint256,uint256,string,uint256,bytes))"](
{
foreignBlockHash: lastBlock.hash,
foreignChainID: 31337,
foreignArbitrable: arbitrable.address,
foreignDisputeID: disputeId,
externalDisputeID: ethers.utils.keccak256(ethers.utils.toUtf8Bytes("RNG test")),
templateId: 0,
templateUri: "",
choices: 2,
extraData: `0x00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000003`, // General Court, 3 jurors
},
{ value: arbitrationCost }
);
await network.provider.send("evm_increaseTime", [2000]); // Wait for minStakingTime
await network.provider.send("evm_mine");
await sortitionModule.passPhase(); // Staking -> Generating
const requestId = await vrfConsumer.lastRequestId(); // Needed as we emulate the vrfCoordinator manually
await vrfCoordinator.fulfillRandomWords(requestId, vrfConsumer.address); // The callback calls sortitionModule.passPhase(); // Generating -> Drawing
await expect(core.draw(0, 1000, { gasLimit: 1000000 }))
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 0)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 1)
.to.emit(core, "Draw")
.withArgs(anyValue, 0, 0, 2);
});
});