Skip to content

Commit a22ade0

Browse files
committed
chore: scripts simulation
1 parent 9badc57 commit a22ade0

File tree

2 files changed

+72
-50
lines changed

2 files changed

+72
-50
lines changed

contracts/scripts/simulations/tasks.ts

Lines changed: 62 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/* eslint-disable promise/param-names */
2-
import { BigNumber, utils } from "ethers";
2+
import { toBigInt, BigNumberish, AddressLike } from "ethers";
3+
import { ethers } from "ethers";
34
import { task } from "hardhat/config";
45
import {
56
Period,
@@ -34,7 +35,10 @@ task("simulate:approve", "Grants permission to KlerosCore to use your PNK tokens
3435

3536
// Approve PNK tokens for transfer to KlerosCore
3637
try {
37-
const approvePNKFunctionArgs: [string, BigNumber] = [core.address, utils.parseEther(pnkamount.toString())];
38+
const approvePNKFunctionArgs: [AddressLike, BigNumberish] = [
39+
await core.getAddress(),
40+
ethers.parseEther(pnkamount.toString()),
41+
];
3842
const resultApproveTx = await pnk.connect(wallet).approve(...approvePNKFunctionArgs, options);
3943
await resultApproveTx.wait();
4044
console.log(`Approved ${pnkamount} PNK tokens for transfer to KlerosCore from wallet ${wallet.address}`);
@@ -56,7 +60,7 @@ task("simulate:set-stake", "Stakes PNK tokens to participate in the Kleros dispu
5660

5761
// Stakes PNK tokens in the Court you specified as parameter of this task
5862
try {
59-
const setStakeFunctionArgs: [string, BigNumber] = [courtid, utils.parseEther(pnkamount.toString())];
63+
const setStakeFunctionArgs: [string, bigint] = [courtid, ethers.parseEther(pnkamount.toString())];
6064
const resultSetStakeTx = await core.connect(wallet).setStake(...setStakeFunctionArgs, options);
6165
await resultSetStakeTx.wait();
6266
console.log(`setStake wallet ${wallet.address}, txID: %s`, resultSetStakeTx?.hash);
@@ -73,15 +77,15 @@ task("simulate:create-court", "callable by Governor only. Create a new Court")
7377

7478
const { wallet } = await getWallet(hre, walletindex);
7579

76-
const parent = 1;
77-
const minStake = BigNumber.from(10).pow(20).mul(2);
78-
const alpha = 10000;
79-
const feeForJuror = BigNumber.from(10).pow(17);
80-
const jurorsForCourtJump = 3;
81-
const hiddenVotes = false;
82-
const timesPerPeriod = [300, 300, 300, 300] as any;
83-
const sortitionSumTreeK = 3;
84-
const supportedDisputeKits = [1]; // IDs of supported dispute kits
80+
const parent = toBigInt(1) as BigNumberish;
81+
const minStake = (toBigInt(10) ** toBigInt(20) * toBigInt(2)) as BigNumberish;
82+
const alpha = toBigInt(10000) as BigNumberish;
83+
const feeForJuror = (toBigInt(10) ** toBigInt(17)) as BigNumberish;
84+
const jurorsForCourtJump = toBigInt(3) as BigNumberish;
85+
const hiddenVotes = false as boolean;
86+
const timesPerPeriod = [300, 300, 300, 300] as [BigNumberish, BigNumberish, BigNumberish, BigNumberish];
87+
const sortitionSumTreeK = ethers.toBeHex(3);
88+
const supportedDisputeKits = [1] as BigNumberish[]; // IDs of supported dispute kits
8589
let courtID;
8690
try {
8791
const tx = await (
@@ -99,10 +103,10 @@ task("simulate:create-court", "callable by Governor only. Create a new Court")
99103
supportedDisputeKits
100104
)
101105
).wait();
102-
console.log("createCourt txID: %s", tx?.transactionHash);
106+
console.log("createCourt txID: %s", tx?.hash);
103107
// Get the court ID from the KlerosCore contract event logs
104108
const filter = core.filters.CourtCreated();
105-
const logs = await core.queryFilter(filter, tx.blockNumber, tx.blockNumber);
109+
const logs = await core.queryFilter(filter, tx?.blockNumber, tx?.blockNumber);
106110
const courtCreatedLog = logs[logs.length - 1];
107111
courtID = courtCreatedLog.args._courtID;
108112
console.log(
@@ -130,19 +134,12 @@ task("simulate:create-dispute", "Creates a dispute on an arbitrable contract")
130134
const { wallet } = await getWallet(hre, walletindex);
131135

132136
// Create a random evidence group ID
133-
const evidenceGroupID = ethers.BigNumber.from(ethers.utils.randomBytes(32)).toString();
137+
const evidenceGroupID = toBigInt(ethers.randomBytes(32)).toString();
134138

135139
let disputeID;
136-
137-
// Construct the arbitratorExtraData parameter
138-
const courtIdBytes = ethers.utils.defaultAbiCoder.encode(["uint256"], [courtid]);
139-
const minJurorsBytes = ethers.utils.defaultAbiCoder.encode(["uint256"], [3]); // default value for minimum jurors
140-
141-
const arbitratorExtraData = ethers.utils.hexConcat([courtIdBytes, minJurorsBytes]);
142-
143140
try {
144141
// Create a dispute on the arbitrable contract
145-
const tx = await arbitrable.connect(wallet).createDispute(nbofchoices, arbitratorExtraData, evidenceGroupID, {
142+
const tx = await arbitrable.connect(wallet)["createDispute(string)"]("hello world", {
146143
value: getArbitrationFees(hre, nbofjurors, feeforjuror),
147144
...options,
148145
});
@@ -151,7 +148,7 @@ task("simulate:create-dispute", "Creates a dispute on an arbitrable contract")
151148

152149
// Get the dispute ID from the KlerosCore contract event logs
153150
const filter = core.filters.DisputeCreation();
154-
const logs = await core.queryFilter(filter, tx.blockNumber, tx.blockNumber);
151+
const logs = await core.queryFilter(filter);
155152
disputeID = logs[logs.length - 1]?.args?._disputeID;
156153
console.log("Created Dispute %s on Court %s with evidenceGroupID %s", disputeID, courtid, evidenceGroupID);
157154
} catch (e) {
@@ -175,7 +172,7 @@ task("simulate:pass-phase", "Pass the phase of the SortitionModule")
175172
const before = await sortition.phase();
176173
try {
177174
const tx = await (await sortition.connect(wallet).passPhase(options)).wait();
178-
console.log("passPhaseCore txID: %s", tx?.transactionHash);
175+
console.log("passPhaseCore txID: %s", tx?.hash);
179176
} catch (e) {
180177
handleError(e);
181178
} finally {
@@ -189,6 +186,7 @@ task("simulate:wait-for-rng", "Waits for the RNG to be ready").setAction(async (
189186
const { wallet } = await getWallet(hre, walletIndex);
190187

191188
let ready: boolean;
189+
192190
try {
193191
ready = await isRngReady(wallet, hre);
194192
} catch (e) {
@@ -213,7 +211,7 @@ task("simulate:draw", "Draws jurors for a dispute on Kleros")
213211
console.log("Drawn jurors before: %O", info.drawnJurors);
214212
try {
215213
const tx = await (await core.connect(wallet).draw(disputeid, 10, options)).wait();
216-
console.log("draw txID: %s", tx?.transactionHash);
214+
console.log("draw txID: %s", tx?.hash);
217215
} catch (e) {
218216
handleError(e);
219217
} finally {
@@ -234,7 +232,7 @@ task("simulate:pass-period", "Passes the period of a dispute on Kleros Core")
234232

235233
try {
236234
const tx = await (await core.connect(wallet).passPeriod(disputeid, options)).wait();
237-
console.log("passPeriod txID: %s", tx?.transactionHash);
235+
console.log("passPeriod txID: %s", tx?.hash);
238236
} catch (e) {
239237
handleError(e);
240238
} finally {
@@ -256,8 +254,8 @@ task("simulate:cast-commit", "Casts a commit for a drawn juror")
256254
const salt = "123";
257255
console.log("salt used on juror %s is: %s", walletindex, salt);
258256
const generateCommit = (choice: number, justification: string) => {
259-
const hash = utils.solidityKeccak256(["string", "string", "string"], [choice, justification, salt]);
260-
return utils.hexlify(hash);
257+
const hash = ethers.solidityPackedKeccak256(["string", "string", "string"], [choice, justification, salt]);
258+
return ethers.toBeHex(hash);
261259
};
262260
const commitHash = generateCommit(choice, taskArgs.justification);
263261
const drawnJurors = await getDrawnJurors(hre, disputeid, getRoundId(taskArgs, hre, disputeid));
@@ -307,7 +305,7 @@ task("simulate:fund-appeal", "Funds an appeal on a dispute")
307305
const { disputeid, walletindex, appealchoice } = taskArgs;
308306
const { wallet } = await getWallet(hre, walletindex);
309307

310-
const fundAppealFunctionArgs: [number, number, { value: BigNumber }] = [
308+
const fundAppealFunctionArgs: [number, number, { value: BigNumberish }] = [
311309
disputeid,
312310
appealchoice,
313311
{ value: await getAppealCost(hre, disputeid) },
@@ -319,7 +317,7 @@ task("simulate:fund-appeal", "Funds an appeal on a dispute")
319317
await mineBlocks(numberOfBlocksToMine, hre.network);
320318
}
321319
const fundAppealTx = await (await disputeKitClassic.connect(wallet).fundAppeal(...fundAppealFunctionArgs)).wait();
322-
console.log("fundAppeal (in DisputeKitClassic) txID: %s", fundAppealTx?.transactionHash);
320+
console.log("fundAppeal (in DisputeKitClassic) txID: %s", fundAppealTx?.hash);
323321
} catch (e) {
324322
handleError(e);
325323
}
@@ -337,7 +335,7 @@ task("simulate:execute-ruling", "Executes the ruling for a dispute on KlerosCore
337335
let executeRulingTx;
338336
try {
339337
const executeTx = await (await connectedKlerosCore.execute(disputeid, 0, 10)).wait(); // redistribute
340-
console.log("txID execute: %s", executeTx?.transactionHash);
338+
console.log("txID execute: %s", executeTx?.hash);
341339

342340
executeRulingTx = await (await connectedKlerosCore.executeRuling(disputeid)).wait(); // rule
343341
console.log("txID executeRuling: %s", executeRulingTx?.transactionHash);
@@ -363,14 +361,20 @@ task("simulate:withdraw-fees-and-rewards", "Withdraws fees and rewards for peopl
363361
const { disputeid, walletindex, beneficiary, choice } = taskArgs;
364362

365363
const { wallet } = await getWallet(hre, walletindex);
366-
364+
// disputeid, beneficiary, getRoundId(taskArgs, hre, disputeid), choice
365+
// toBigInt(disputeid),
366+
// await ethers.getAddress(beneficiary),
367+
// getRoundId(taskArgs, hre, disputeid),
368+
// choice
369+
const _disputeId: BigNumberish = disputeid;
370+
const _beneficiary: AddressLike = beneficiary;
371+
const _coreRoundId: BigNumberish = await getRoundId(taskArgs, hre, disputeid);
372+
const _choice: BigNumberish = choice;
367373
try {
368374
const withdrawTx = await (
369-
await disputeKitClassic
370-
.connect(wallet)
371-
.withdrawFeesAndRewards(disputeid, beneficiary, getRoundId(taskArgs, hre, disputeid), choice)
375+
await disputeKitClassic.connect(wallet).withdrawFeesAndRewards(_disputeId, _beneficiary, _coreRoundId, _choice)
372376
).wait(); // redistribute
373-
console.log("txID withdrawFeesAndRewards: %s", withdrawTx?.transactionHash);
377+
console.log("txID withdrawFeesAndRewards: %s", withdrawTx?.hash);
374378
} catch (e) {
375379
handleError(e);
376380
}
@@ -408,7 +412,7 @@ task("simulate:to-freezing-and-generating-phase", "Pass phase from 'staking' to
408412
const { wallet } = await getWallet(hre, walletindex);
409413
const numberOfBlocksToMine = Number(await sortition.rngLookahead());
410414
await mineBlocks(numberOfBlocksToMine, hre.network);
411-
await randomizerMock.connect(wallet).relay(randomizerRng.address, 0, utils.randomBytes(32));
415+
await randomizerMock.connect(wallet).relay(randomizerRng.target, 0, ethers.randomBytes(32));
412416
}
413417
});
414418

@@ -431,7 +435,8 @@ task("simulate:split-pnk", "one wallet funds with PNK the other 4 wallets")
431435
const { pnk } = await getContracts(hre);
432436
const { walletindex, pnkperwallet } = taskArgs;
433437
const { wallet } = await getWallet(hre, walletindex);
434-
const amount = utils.parseUnits(pnkperwallet.toString(), "18");
438+
const amount = ethers.parseEther(pnkperwallet.toString());
439+
435440
const firstWallet = await (await getWallet(hre, 1)).wallet;
436441
const secondWallet = await (await getWallet(hre, 2)).wallet;
437442
const thirdWallet = await (await getWallet(hre, 3)).wallet;
@@ -450,14 +455,14 @@ task("simulate:submit-evidence", "Submits evidence to a dispute")
450455
.addParam("walletindex", "Index of the wallet to use for submitting evidence")
451456
.addParam("evidencegroupid", "The evidenceGroupID, which is linked to the dispute")
452457
.setAction(async (taskArgs, hre) => {
453-
const { disputeKitClassic } = await getContracts(hre);
458+
const { evidenceModule } = await getContracts(hre);
454459
const { walletindex, evidencegroupid } = taskArgs;
455460

456461
const { wallet } = await getWallet(hre, walletindex);
457462
const evidence = "/ipfs/QmaNEknCUEKDy74sDNLFXo8Vc3PqX7QC1ZyvUx4n7V6q1L/evidence.json";
458463
try {
459-
const tx = await (await disputeKitClassic.connect(wallet).submitEvidence(evidencegroupid, evidence)).wait();
460-
console.log("txID submitEvidence: %s", tx?.transactionHash);
464+
const tx = await (await evidenceModule.connect(wallet).submitEvidence(evidencegroupid, evidence)).wait();
465+
console.log("txID submitEvidence: %s", tx?.hash);
461466
} catch (e) {
462467
handleError(e);
463468
}
@@ -471,55 +476,64 @@ task("simulate:all", "Simulates arbitration activity to troubleshoot the subgrap
471476
const courtId = "1";
472477
const appealChoice = "1";
473478

479+
console.log("split pnk.....");
474480
await hre.run("simulate:split-pnk", { walletindex: operator.toString(), pnkperwallet: stake.toString() });
475481

482+
console.log("stake five jurors....");
476483
await hre.run("simulate:stake-five-jurors", {
477484
walletindexes: "0,1,2,3,4",
478485
pnkamounts: `${stake},${stake},${stake},${stake},${stake}`,
479486
courtid: courtId,
480487
});
481488

489+
console.log("create dispute....");
482490
const dispute = await hre.run("simulate:create-dispute", {
483491
walletindex: operator.toString(),
484492
courtid: courtId.toString(),
485493
nbofchoices: "2",
486494
nbofjurors: "3",
487-
feeforjuror: utils.parseEther("0.1").toString(),
495+
feeforjuror: ethers.parseEther("0.1").toString(),
488496
});
489497

490498
// Wait for minStakingTime
491499
const minStakingTime = await sortition.minStakingTime();
492-
await waitFor(minStakingTime.toNumber(), hre);
500+
await waitFor(ethers.getNumber(minStakingTime), hre);
493501

494502
// Phase Staking -> Generating
503+
console.log("to freezing and generating phase.....");
495504
await hre.run("simulate:to-freezing-and-generating-phase", { walletindex: operator.toString() });
496505

497506
// Wait for RNG
507+
console.log("wait for rng....");
498508
await hre.run("simulate:wait-for-rng");
499509

500510
// Phase: Generating -> Drawing
501511
// Draws
502512
// Phase: Drawing -> Staking
513+
console.log("pass phase draw unfreeze.....");
503514
await hre.run("simulate:pass-phase-draw-unfreeze", {
504515
walletindex: operator.toString(),
505516
disputeid: dispute.id.toString(),
506517
});
507518

508519
// Submit evidence
520+
console.log("submit evidence.....");
509521
await hre.run("simulate:submit-evidence", {
510522
walletindex: operator.toString(),
511523
evidencegroupid: dispute.evidenceGroupID,
512524
});
513525

514526
// Period: Evidence -> Vote
515527
await waitForPeriod(dispute.id, Period.Evidence, hre);
528+
console.log("pass period.....");
516529
await hre.run("simulate:pass-period", { walletindex: operator.toString(), disputeid: dispute.id.toString() });
517530

518531
// Find the first drawn juror and the corresponding wallet index
519532
const drawnJurors = await getDrawnJurors(hre, dispute.id, getLatestRoundId(hre, dispute.id));
520533
const firstDrawnJurorWalletIndex = (await findFirstDrawnJurorWalletIndex(hre, drawnJurors)) as number;
521534

522535
// Vote
536+
console.log("cast vote.....");
523537
await hre.run("simulate:cast-vote", {
524538
walletindex: firstDrawnJurorWalletIndex.toString(),
525539
disputeid: dispute.id.toString(),
@@ -529,9 +543,11 @@ task("simulate:all", "Simulates arbitration activity to troubleshoot the subgrap
529543

530544
// Period: Vote -> Appeal
531545
await waitForPeriod(dispute.id, Period.Vote, hre);
546+
console.log("pass period....");
532547
await hre.run("simulate:pass-period", { walletindex: operator.toString(), disputeid: dispute.id.toString() });
533548

534549
// Fund Appeal
550+
console.log("fund appeal....");
535551
await hre.run("simulate:fund-appeal", {
536552
walletindex: operator.toString(),
537553
disputeid: dispute.id.toString(),
@@ -540,9 +556,11 @@ task("simulate:all", "Simulates arbitration activity to troubleshoot the subgrap
540556

541557
// Period: Appeal -> Execution
542558
await waitForPeriod(dispute.id, Period.Appeal, hre);
559+
console.log("pass period....");
543560
await hre.run("simulate:pass-period", { walletindex: operator.toString(), disputeid: dispute.id.toString() });
544561

545562
// Execution
563+
console.log("execute ruling....");
546564
await hre.run("simulate:execute-ruling", { walletindex: operator.toString(), disputeid: dispute.id.toString() });
547565
}
548566
);

contracts/scripts/simulations/utils.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@ import {
55
DisputeKitClassic,
66
PNK,
77
RandomizerRNG,
8-
ArbitrableExampleEthFee,
9-
RandomizerOracle,
8+
EvidenceModule,
9+
ArbitrableExample,
10+
RandomizerMock,
1011
} from "../../typechain-types";
12+
import { toBigInt, ethers } from "ethers";
1113

1214
export enum Period {
1315
Evidence,
@@ -24,7 +26,8 @@ export const getContracts = async (hre) => {
2426
const disputeKitClassic = (await hre.ethers.getContract("DisputeKitClassic")) as DisputeKitClassic;
2527
const pnk = (await hre.ethers.getContract("PNK")) as PNK;
2628
const randomizerRng = (await hre.ethers.getContract("RandomizerRNG")) as RandomizerRNG;
27-
const arbitrable = (await hre.ethers.getContract("ArbitrableExampleEthFee")) as ArbitrableExampleEthFee;
29+
const arbitrable = (await hre.ethers.getContract("ArbitrableExample")) as ArbitrableExample;
30+
const evidenceModule = (await hre.ethers.getContract("EvidenceModule")) as EvidenceModule;
2831
const randomizerMock = (await hre.ethers.getContract("RandomizerOracle")) as RandomizerMock;
2932

3033
return {
@@ -34,6 +37,7 @@ export const getContracts = async (hre) => {
3437
pnk,
3538
randomizerRng,
3639
arbitrable,
40+
evidenceModule,
3741
randomizerMock,
3842
};
3943
};
@@ -54,7 +58,7 @@ export const getWallet = async (hre: any, walletIndex: number) => {
5458

5559
export const isRngReady = async (wallet, hre) => {
5660
const { randomizerRng, disputeKitClassic } = await getContracts(hre);
57-
const requesterID = await randomizerRng.connect(wallet).requesterToID(disputeKitClassic.address);
61+
const requesterID = await randomizerRng.connect(wallet).requesterToID(disputeKitClassic.target);
5862
const n = await randomizerRng.connect(wallet).randomNumbers(requesterID);
5963
if (Number(n) === 0) {
6064
console.log("rng is NOT ready.");
@@ -77,7 +81,7 @@ export const isNetworkLocal = (hre: any): boolean => {
7781

7882
export const getArbitrationFees = (hre, nbofjurors: bigint, feeforjuror: bigint) => {
7983
if (isNetworkLocal(hre)) {
80-
return hre.ethers.utils.parseUnits("1");
84+
return hre.ethers.parseEther("1");
8185
} else {
8286
return nbofjurors * feeforjuror;
8387
}
@@ -147,7 +151,7 @@ export const waitForPeriod = async (disputeId: number, period: Period, hre) => {
147151
const { lastPeriodChange, courtID } = await core.disputes(disputeId);
148152
const periodDuration = (await core.getTimesPerPeriod(courtID))[period];
149153
const now = await latest(hre.network);
150-
const remainingDuration = lastPeriodChange.add(periodDuration).sub(now).toNumber();
154+
const remainingDuration = ethers.getNumber(lastPeriodChange + toBigInt(periodDuration) - toBigInt(now));
151155
if (remainingDuration > 0) {
152156
await waitFor(remainingDuration, hre);
153157
}

0 commit comments

Comments
 (0)