@kleros/kleros-v2-contracts

Smart contracts for Kleros v2

Deployed Addresses

Refresh the list of deployed contracts by running ./scripts/generateDeploymentsMarkdown.sh.

Chiado

Goerli

Arbitrum Goerli

Getting Started

Install the Dependencies

yarn install

Run Tests

yarn test

Compile the Contracts

yarn build

Run Linter on Files

yarn lint

Fix Linter Issues on Files

yarn fix

Deploy Instructions

NOTICE: the commands below work only if you are inside the contracts/ directory.

0. Set the Environment Variables

Copy .env.example file as .env and edit it accordingly.

cp .env.example .env

The following env vars are required:

  • PRIVATE_KEY: the private key of the deployer account used for the testnets.
  • MAINNET_PRIVATE_KEY: the private key of the deployer account used for Mainnet.
  • INFURA_API_KEY: the API key for infura.

The ones below are optional:

  • ETHERSCAN_API_KEY: to verify the source of the newly deployed contracts on Etherscan.
  • ARBISCAN_API_KEY: to verify the source of the newly deployed contracts on Arbitrum.
  • GNOSISSCAN_API_KEY: to verify the source of the newly deployed contracts on Gnosis chain.

1. Update the Constructor Parameters (optional)

If some of the constructor parameters (such as the Meta Evidence) needs to change, you need to update the files in the deploy/ directory.

2. Deploy to a Local Network

The complete deployment is multi-chain, so a deployment to the local network can only simulate either the Home chain or the Foreign chain.

Shell 1: the node

yarn hardhat node --tags nothing

Shell 2: the deploy script

yarn deploy --network localhost --tags <Arbitration|VeaMock|ForeignGatewayOnEthereum|HomeGateway>

3. Deploy to Public Testnets

# ArbitrumGoerli to Chiado
yarn deploy --network arbitrumGoerli --tags Arbitration
yarn deploy --network chiado --tags ForeignGatewayOnGnosis
yarn deploy --network chiado --tags KlerosLiquidOnGnosis
yarn deploy --network arbitrumGoerli --tags HomeGatewayToGnosis

# Goerli
yarn deploy --network arbitrumGoerli --tags Arbitration
yarn deploy --network goerli --tags ForeignGatewayOnEthereum
yarn deploy --network arbitrumGoerli --tags HomeGatewayToEthereum

The deployed addresses should be displayed to the screen after the deployment is complete. If you missed them, you can always go to the deployments/<network> directory and look for the respective file.

Running Test Fixtures

Shell 1: the node

yarn hardhat node --tags Arbitration,VeaMock

Shell 2: the test scripts

yarn test --network localhost

4. Verify the Source Code

This must be done for each network separately.

# explorer
yarn etherscan-verify --network <arbitrumGoerli|arbitrum|chiado|gnosischain|goerli|mainnet>

# sourcify
yarn sourcify --network <arbitrumGoerli|arbitrum|chiado|gnosischain|goerli|mainnet>

Ad-hoc procedures

Populating the policy registry and courts

1/ Export the registry data from V1

for network in mainnet gnosischain
do
  yarn hardhat run scripts/getPoliciesV1.ts  --network $network | tee config/policies.v1.$network.json
  yarn hardhat run scripts/getCourtsV1.ts --network $network | tee config/courts.v1.$network.json
done

2/ Import the data to V2 - Local Network

:warning: By default this script populates from *.mainnet.json. To populate from *.gnosischain.json, set the variable USE_GNOSIS to true inside scripts/populateCourts.ts.

:warning: It is possible to switch to testnet-friendly court parameters by setting the variable TESTING_PARAMETERS to true inside scripts/populateCourts.ts.

Shell 1:

yarn hardhat node --tags Arbitration

Shell 2:

yarn hardhat run scripts/populatePolicyRegistry.ts --network localhost
yarn hardhat run scripts/populateCourts.ts --network localhost

3/ Import the data to V2 - Public Testnet

yarn hardhat run scripts/populatePolicyRegistry.ts --network arbitrumGoerli
yarn hardhat run scripts/populateCourts.ts --network arbitrumGoerli

Generate deployment artifacts for existing contracts

Usage

scripts/generateDeploymentArtifact.sh <network> <address>

Example: WETH on Gnosis chain

scripts/generateDeploymentArtifact.sh gnosischain 0xf8d1677c8a0c961938bf2f9adc3f3cfda759a9d9 > deployments/gnosischain/WETH.json

Push the contracts to a Tenderly project

Ensure that your $TENDERLY_PROJECT and $TENDERLY_USERNAME is set correctly in .env.

yarn hardhat --network goerli tenderly:push
yarn hardhat --network arbitrumGoerli tenderly:push

Contents

Contents

ArbitrableExample

Git Source

Inherits: IArbitrableV2

State Variables

governor

address public immutable governor;

arbitrator

IArbitratorV2 public arbitrator;

disputeTemplates

uint256 public disputeTemplates;

weth

ERC20 public immutable weth;

externalIDtoLocalID

mapping(uint256 => uint256) public externalIDtoLocalID;

disputes

DisputeStruct[] public disputes;

Functions

constructor

Constructor

constructor(IArbitratorV2 _arbitrator, string memory _templateData, ERC20 _weth);

Parameters

NameTypeDescription
_arbitratorIArbitratorV2The arbitrator to rule on created disputes.
_templateDatastringThe dispute template data.
_wethERC20The WETH token.

createDispute

Calls createDispute function of the specified arbitrator to create a dispute. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.

function createDispute(
    uint256 _templateId,
    string calldata _action,
    bytes calldata _arbitratorExtraData,
    uint256 _feeInWeth
) external payable returns (uint256 disputeID);

Parameters

NameTypeDescription
_templateIduint256The identifier of the dispute template. Should not be used with _templateUri.
_actionstringThe action that requires arbitration.
_arbitratorExtraDatabytesExtra data for the arbitrator.
_feeInWethuint256Amount of fees in WETH for the arbitrator.

Returns

NameTypeDescription
disputeIDuint256Dispute id (on arbitrator side) of the dispute created.

rule

To be called by the arbitrator of the dispute, to declare the winning ruling.

function rule(uint256 _externalDisputeID, uint256 _ruling) external override;

Parameters

NameTypeDescription
_externalDisputeIDuint256ID of the dispute in arbitrator contract.
_rulinguint256The ruling choice of the arbitration.

changeDisputeTemplate

function changeDisputeTemplate(string memory _templateData) external;

changeArbitrator

function changeArbitrator(IArbitratorV2 _arbitrator) external;

Events

Action

event Action(string indexed _action);

Structs

DisputeStruct

struct DisputeStruct {
    bool isRuled;
    uint256 ruling;
    uint256 numberOfRulingOptions;
}

ArbitrableExampleEthFee

Git Source

Inherits: IArbitrableV2

State Variables

governor

address public governor;

arbitrator

IArbitratorV2 public arbitrator;

disputeTemplates

uint256 public disputeTemplates;

externalIDtoLocalID

mapping(uint256 => uint256) public externalIDtoLocalID;

disputes

DisputeStruct[] public disputes;

Functions

constructor

Constructor

constructor(IArbitratorV2 _arbitrator, string memory _templateData);

Parameters

NameTypeDescription
_arbitratorIArbitratorV2The arbitrator to rule on created disputes.
_templateDatastringThe dispute template data.

createDispute

Calls createDispute function of the specified arbitrator to create a dispute. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.

function createDispute(uint256 _templateId, string calldata _action, bytes calldata _arbitratorExtraData)
    external
    payable
    returns (uint256 disputeID);

Parameters

NameTypeDescription
_templateIduint256The identifier of the dispute template. Should not be used with _templateUri.
_actionstringThe action that requires arbitration.
_arbitratorExtraDatabytesExtra data for the arbitrator.

Returns

NameTypeDescription
disputeIDuint256Dispute id (on arbitrator side) of the dispute created.

rule

To be called by the arbitrator of the dispute, to declare the winning ruling.

function rule(uint256 _externalDisputeID, uint256 _ruling) external override;

Parameters

NameTypeDescription
_externalDisputeIDuint256ID of the dispute in arbitrator contract.
_rulinguint256The ruling choice of the arbitration.

changeDisputeTemplate

function changeDisputeTemplate(string memory _templateData) external;

changeArbitrator

function changeArbitrator(IArbitratorV2 _arbitrator) external;

Events

Action

event Action(string indexed _action);

Structs

DisputeStruct

struct DisputeStruct {
    bool isRuled;
    uint256 ruling;
    uint256 numberOfRulingOptions;
}

DisputeResolver

Git Source

Inherits: IArbitrableV2

State Variables

governor

address public governor;

arbitrator

IArbitratorV2 public arbitrator;

disputes

DisputeStruct[] public disputes;

arbitratorDisputeIDToLocalID

mapping(uint256 => uint256) public arbitratorDisputeIDToLocalID;

Functions

constructor

Constructor

constructor(IArbitratorV2 _arbitrator);

Parameters

NameTypeDescription
_arbitratorIArbitratorV2Target global arbitrator for any disputes.

changeGovernor

Changes the governor.

function changeGovernor(address _governor) external;

Parameters

NameTypeDescription
_governoraddressThe address of the new governor.

changeArbitrator

function changeArbitrator(IArbitratorV2 _arbitrator) external;

createDisputeForTemplate

Calls createDispute function of the specified arbitrator to create a dispute. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.

function createDisputeForTemplate(
    bytes calldata _arbitratorExtraData,
    string calldata _disputeTemplate,
    uint256 _numberOfRulingOptions
) external payable returns (uint256 disputeID);

Parameters

NameTypeDescription
_arbitratorExtraDatabytesExtra data for the arbitrator of the dispute.
_disputeTemplatestringDispute template.
_numberOfRulingOptionsuint256Number of ruling options.

Returns

NameTypeDescription
disputeIDuint256Dispute id (on arbitrator side) of the created dispute.

createDisputeForTemplateUri

Calls createDispute function of the specified arbitrator to create a dispute. Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.

function createDisputeForTemplateUri(
    bytes calldata _arbitratorExtraData,
    string calldata _disputeTemplateUri,
    uint256 _numberOfRulingOptions
) external payable returns (uint256 disputeID);

Parameters

NameTypeDescription
_arbitratorExtraDatabytesExtra data for the arbitrator of the dispute.
_disputeTemplateUristringThe URI to the dispute template. For example on IPFS: starting with '/ipfs/'.
_numberOfRulingOptionsuint256Number of ruling options.

Returns

NameTypeDescription
disputeIDuint256Dispute id (on arbitrator side) of the created dispute.

rule

To be called by the arbitrator of the dispute, to declare the winning ruling.

function rule(uint256 _externalDisputeID, uint256 _ruling) external override;

Parameters

NameTypeDescription
_externalDisputeIDuint256ID of the dispute in arbitrator contract.
_rulinguint256The ruling choice of the arbitration.

_createDispute

function _createDispute(
    bytes calldata _arbitratorExtraData,
    string memory _disputeTemplate,
    string memory _disputeTemplateUri,
    uint256 _numberOfRulingOptions
) internal returns (uint256 disputeID);

Structs

DisputeStruct

struct DisputeStruct {
    bytes arbitratorExtraData;
    bool isRuled;
    uint256 ruling;
    uint256 numberOfRulingOptions;
}

Contents

BaseDisputeKit

Git Source

Inherits: IDisputeKit

State Variables

governor

address public governor;

core

KlerosCore public core;

Functions

onlyByGovernor

modifier onlyByGovernor();

onlyByCore

modifier onlyByCore();

constructor

Constructor.

constructor(address _governor, KlerosCore _core);

Parameters

NameTypeDescription
_governoraddressThe governor's address.
_coreKlerosCoreThe KlerosCore arbitrator.

executeGovernorProposal

Allows the governor to call anything on behalf of the contract.

function executeGovernorProposal(address _destination, uint256 _amount, bytes memory _data) external onlyByGovernor;

Parameters

NameTypeDescription
_destinationaddressThe destination of the call.
_amountuint256The value sent with the call.
_databytesThe data sent with the call.

_postDrawCheck

Checks that the chosen address satisfies certain conditions for being drawn.

function _postDrawCheck(uint256 _coreDisputeID, address _juror) internal virtual returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256ID of the dispute in the core contract.
_juroraddressChosen address.

Returns

NameTypeDescription
<none>boolWhether the address can be drawn or not.

DisputeKitClassic

Git Source

Inherits: BaseDisputeKit, IEvidence

State Variables

WINNER_STAKE_MULTIPLIER

uint256 public constant WINNER_STAKE_MULTIPLIER = 10000;

LOSER_STAKE_MULTIPLIER

uint256 public constant LOSER_STAKE_MULTIPLIER = 20000;

LOSER_APPEAL_PERIOD_MULTIPLIER

uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000;

ONE_BASIS_POINT

uint256 public constant ONE_BASIS_POINT = 10000;

disputes

Dispute[] public disputes;

coreDisputeIDToLocal

mapping(uint256 => uint256) public coreDisputeIDToLocal;

Functions

notJumped

modifier notJumped(uint256 _coreDisputeID);

constructor

Constructor.

constructor(address _governor, KlerosCore _core) BaseDisputeKit(_governor, _core);

Parameters

NameTypeDescription
_governoraddressThe governor's address.
_coreKlerosCoreThe KlerosCore arbitrator.

changeGovernor

Changes the governor storage variable.

function changeGovernor(address payable _governor) external onlyByGovernor;

Parameters

NameTypeDescription
_governoraddress payableThe new value for the governor storage variable.

changeCore

Changes the core storage variable.

function changeCore(address _core) external onlyByGovernor;

Parameters

NameTypeDescription
_coreaddressThe new value for the core storage variable.

createDispute

Creates a local dispute and maps it to the dispute ID in the Core contract. Note: Access restricted to Kleros Core only.

function createDispute(uint256 _coreDisputeID, uint256 _numberOfChoices, bytes calldata _extraData, uint256 _nbVotes)
    external
    override
    onlyByCore;

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.
_numberOfChoicesuint256Number of choices of the dispute
_extraDatabytesAdditional info about the dispute, for possible use in future dispute kits.
_nbVotesuint256Number of votes for this dispute.

draw

Draws the juror from the sortition tree. The drawn address is picked up by Kleros Core. Note: Access restricted to Kleros Core only.

function draw(uint256 _coreDisputeID)
    external
    override
    onlyByCore
    notJumped(_coreDisputeID)
    returns (address drawnAddress);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
drawnAddressaddressThe drawn address.

castCommit

Sets the caller's commit for the specified votes. It can be called multiple times during the commit period, each call overrides the commits of the previous one. O(n) where n is the number of votes.

function castCommit(uint256 _coreDisputeID, uint256[] calldata _voteIDs, bytes32 _commit)
    external
    notJumped(_coreDisputeID);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.
_voteIDsuint256[]The IDs of the votes.
_commitbytes32The commit. Note that justification string is a part of the commit.

castVote

Sets the caller's choices for the specified votes. O(n) where n is the number of votes.

function castVote(
    uint256 _coreDisputeID,
    uint256[] calldata _voteIDs,
    uint256 _choice,
    uint256 _salt,
    string memory _justification
) external notJumped(_coreDisputeID);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.
_voteIDsuint256[]The IDs of the votes.
_choiceuint256The choice.
_saltuint256The salt for the commit if the votes were hidden.
_justificationstringJustification of the choice.

fundAppeal

Manages contributions, and appeals a dispute if at least two choices are fully funded. Note that the surplus deposit will be reimbursed.

function fundAppeal(uint256 _coreDisputeID, uint256 _choice) external payable notJumped(_coreDisputeID);

Parameters

NameTypeDescription
_coreDisputeIDuint256Index of the dispute in Kleros Core.
_choiceuint256A choice that receives funding.

withdrawFeesAndRewards

Allows those contributors who attempted to fund an appeal round to withdraw any reimbursable fees or rewards after the dispute gets resolved.

function withdrawFeesAndRewards(
    uint256 _coreDisputeID,
    address payable _beneficiary,
    uint256 _coreRoundID,
    uint256 _choice
) external returns (uint256 amount);

Parameters

NameTypeDescription
_coreDisputeIDuint256Index of the dispute in Kleros Core contract.
_beneficiaryaddress payableThe address whose rewards to withdraw.
_coreRoundIDuint256The round in the Kleros Core contract the caller wants to withdraw from.
_choiceuint256The ruling option that the caller wants to withdraw from.

Returns

NameTypeDescription
amountuint256The withdrawn amount.

submitEvidence

Submits evidence for a dispute.

function submitEvidence(uint256 _externalDisputeID, string calldata _evidence) external;

Parameters

NameTypeDescription
_externalDisputeIDuint256Unique identifier for this dispute outside Kleros. It's the submitter responsability to submit the right evidence group ID.
_evidencestringIPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'.

getFundedChoices

function getFundedChoices(uint256 _coreDisputeID) public view returns (uint256[] memory fundedChoices);

currentRuling

Gets the current ruling of a specified dispute.

function currentRuling(uint256 _coreDisputeID)
    external
    view
    override
    returns (uint256 ruling, bool tied, bool overridden);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
rulinguint256The current ruling.
tiedboolWhether it's a tie or not.
overriddenboolWhether the ruling was overridden by appeal funding or not.

getDegreeOfCoherence

Gets the degree of coherence of a particular voter. This function is called by Kleros Core in order to determine the amount of the reward.

function getDegreeOfCoherence(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    override
    returns (uint256);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.
_voteIDuint256The ID of the vote.

Returns

NameTypeDescription
<none>uint256The degree of coherence in basis points.

getCoherentCount

Gets the number of jurors who are eligible to a reward in this round.

function getCoherentCount(uint256 _coreDisputeID, uint256 _coreRoundID) external view override returns (uint256);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.

Returns

NameTypeDescription
<none>uint256The number of coherent jurors.

areCommitsAllCast

Returns true if all of the jurors have cast their commits for the last round.

function areCommitsAllCast(uint256 _coreDisputeID) external view override returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
<none>boolWhether all of the jurors have cast their commits for the last round.

areVotesAllCast

Returns true if all of the jurors have cast their votes for the last round.

function areVotesAllCast(uint256 _coreDisputeID) external view override returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
<none>boolWhether all of the jurors have cast their votes for the last round.

isVoteActive

Returns true if the specified voter was active in this round.

function isVoteActive(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    override
    returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.
_voteIDuint256The ID of the voter.

Returns

NameTypeDescription
<none>boolWhether the voter was active or not.

getRoundInfo

function getRoundInfo(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _choice)
    external
    view
    override
    returns (
        uint256 winningChoice,
        bool tied,
        uint256 totalVoted,
        uint256 totalCommited,
        uint256 nbVoters,
        uint256 choiceCount
    );

getVoteInfo

function getVoteInfo(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    override
    returns (address account, bytes32 commit, uint256 choice, bool voted);

_postDrawCheck

Checks that the chosen address satisfies certain conditions for being drawn.

function _postDrawCheck(uint256 _coreDisputeID, address _juror) internal view override returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256ID of the dispute in the core contract.
_juroraddressChosen address.

Returns

NameTypeDescription
<none>boolWhether the address can be drawn or not.

Events

DisputeCreation

event DisputeCreation(uint256 indexed _coreDisputeID, uint256 _numberOfChoices, bytes _extraData);

CommitCast

event CommitCast(uint256 indexed _coreDisputeID, uint256[] _voteIDs, bytes32 _commit);

Contribution

event Contribution(
    uint256 indexed _coreDisputeID,
    uint256 indexed _coreRoundID,
    uint256 _choice,
    address indexed _contributor,
    uint256 _amount
);

Withdrawal

event Withdrawal(
    uint256 indexed _coreDisputeID,
    uint256 indexed _coreRoundID,
    uint256 _choice,
    address indexed _contributor,
    uint256 _amount
);

ChoiceFunded

event ChoiceFunded(uint256 indexed _coreDisputeID, uint256 indexed _coreRoundID, uint256 indexed _choice);

Structs

Dispute

struct Dispute {
    Round[] rounds;
    uint256 numberOfChoices;
    bool jumped;
    mapping(uint256 => uint256) coreRoundIDToLocal;
    bytes extraData;
}

Round

struct Round {
    Vote[] votes;
    uint256 winningChoice;
    mapping(uint256 => uint256) counts;
    bool tied;
    uint256 totalVoted;
    uint256 totalCommitted;
    mapping(uint256 => uint256) paidFees;
    mapping(uint256 => bool) hasPaid;
    mapping(address => mapping(uint256 => uint256)) contributions;
    uint256 feeRewards;
    uint256[] fundedChoices;
    uint256 nbVotes;
}

Vote

struct Vote {
    address account;
    bytes32 commit;
    uint256 choice;
    bool voted;
}

IProofOfHumanity

Git Source

Functions

isRegistered

Return true if the submission is registered and not expired.

function isRegistered(address _submissionID) external view returns (bool);

Parameters

NameTypeDescription
_submissionIDaddressThe address of the submission.

Returns

NameTypeDescription
<none>boolWhether the submission is registered or not.

DisputeKitSybilResistant

Git Source

Inherits: BaseDisputeKit, IEvidence

State Variables

WINNER_STAKE_MULTIPLIER

uint256 public constant WINNER_STAKE_MULTIPLIER = 10000;

LOSER_STAKE_MULTIPLIER

uint256 public constant LOSER_STAKE_MULTIPLIER = 20000;

LOSER_APPEAL_PERIOD_MULTIPLIER

uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000;

ONE_BASIS_POINT

uint256 public constant ONE_BASIS_POINT = 10000;

poh

IProofOfHumanity public poh;

disputes

Dispute[] public disputes;

coreDisputeIDToLocal

mapping(uint256 => uint256) public coreDisputeIDToLocal;

Functions

notJumped

modifier notJumped(uint256 _coreDisputeID);

constructor

Constructor.

constructor(address _governor, KlerosCore _core, IProofOfHumanity _poh) BaseDisputeKit(_governor, _core);

Parameters

NameTypeDescription
_governoraddressThe governor's address.
_coreKlerosCoreThe KlerosCore arbitrator.
_pohIProofOfHumanityProofOfHumanity contract.

changeGovernor

Changes the governor storage variable.

function changeGovernor(address payable _governor) external onlyByGovernor;

Parameters

NameTypeDescription
_governoraddress payableThe new value for the governor storage variable.

changeCore

Changes the core storage variable.

function changeCore(address _core) external onlyByGovernor;

Parameters

NameTypeDescription
_coreaddressThe new value for the core storage variable.

changePoh

Changes the poh storage variable.

function changePoh(address _poh) external onlyByGovernor;

Parameters

NameTypeDescription
_pohaddressThe new value for the poh storage variable.

createDispute

Creates a local dispute and maps it to the dispute ID in the Core contract. Note: Access restricted to Kleros Core only.

function createDispute(uint256 _coreDisputeID, uint256 _numberOfChoices, bytes calldata _extraData, uint256 _nbVotes)
    external
    override
    onlyByCore;

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.
_numberOfChoicesuint256Number of choices of the dispute
_extraDatabytesAdditional info about the dispute, for possible use in future dispute kits.
_nbVotesuint256Number of votes for this dispute.

draw

Draws the juror from the sortition tree. The drawn address is picked up by Kleros Core. Note: Access restricted to Kleros Core only.

function draw(uint256 _coreDisputeID)
    external
    override
    onlyByCore
    notJumped(_coreDisputeID)
    returns (address drawnAddress);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
drawnAddressaddressThe drawn address.

castCommit

Sets the caller's commit for the specified votes. It can be called multiple times during the commit period, each call overrides the commits of the previous one. O(n) where n is the number of votes.

function castCommit(uint256 _coreDisputeID, uint256[] calldata _voteIDs, bytes32 _commit)
    external
    notJumped(_coreDisputeID);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.
_voteIDsuint256[]The IDs of the votes.
_commitbytes32The commit. Note that justification string is a part of the commit.

castVote

Sets the caller's choices for the specified votes. O(n) where n is the number of votes.

function castVote(
    uint256 _coreDisputeID,
    uint256[] calldata _voteIDs,
    uint256 _choice,
    uint256 _salt,
    string memory _justification
) external notJumped(_coreDisputeID);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.
_voteIDsuint256[]The IDs of the votes.
_choiceuint256The choice.
_saltuint256The salt for the commit if the votes were hidden.
_justificationstringJustification of the choice.

fundAppeal

Manages contributions, and appeals a dispute if at least two choices are fully funded. Note that the surplus deposit will be reimbursed.

function fundAppeal(uint256 _coreDisputeID, uint256 _choice) external payable notJumped(_coreDisputeID);

Parameters

NameTypeDescription
_coreDisputeIDuint256Index of the dispute in Kleros Core.
_choiceuint256A choice that receives funding.

withdrawFeesAndRewards

Allows those contributors who attempted to fund an appeal round to withdraw any reimbursable fees or rewards after the dispute gets resolved.

function withdrawFeesAndRewards(
    uint256 _coreDisputeID,
    address payable _beneficiary,
    uint256 _coreRoundID,
    uint256 _choice
) external returns (uint256 amount);

Parameters

NameTypeDescription
_coreDisputeIDuint256Index of the dispute in Kleros Core contract.
_beneficiaryaddress payableThe address whose rewards to withdraw.
_coreRoundIDuint256The round in the Kleros Core contract the caller wants to withdraw from.
_choiceuint256The ruling option that the caller wants to withdraw from.

Returns

NameTypeDescription
amountuint256The withdrawn amount.

submitEvidence

Submits evidence for a dispute.

function submitEvidence(uint256 _externalDisputeID, string calldata _evidence) external;

Parameters

NameTypeDescription
_externalDisputeIDuint256Unique identifier for this dispute outside Kleros. It's the submitter responsability to submit the right evidence group ID.
_evidencestringIPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'.

getFundedChoices

function getFundedChoices(uint256 _coreDisputeID) public view returns (uint256[] memory fundedChoices);

currentRuling

Gets the current ruling of a specified dispute.

function currentRuling(uint256 _coreDisputeID)
    external
    view
    override
    returns (uint256 ruling, bool tied, bool overridden);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
rulinguint256The current ruling.
tiedboolWhether it's a tie or not.
overriddenboolWhether the ruling was overridden by appeal funding or not.

getDegreeOfCoherence

Gets the degree of coherence of a particular voter. This function is called by Kleros Core in order to determine the amount of the reward.

function getDegreeOfCoherence(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    override
    returns (uint256);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.
_voteIDuint256The ID of the vote.

Returns

NameTypeDescription
<none>uint256The degree of coherence in basis points.

getCoherentCount

Gets the number of jurors who are eligible to a reward in this round.

function getCoherentCount(uint256 _coreDisputeID, uint256 _coreRoundID) external view override returns (uint256);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.

Returns

NameTypeDescription
<none>uint256The number of coherent jurors.

areCommitsAllCast

Returns true if all of the jurors have cast their commits for the last round.

function areCommitsAllCast(uint256 _coreDisputeID) external view override returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
<none>boolWhether all of the jurors have cast their commits for the last round.

areVotesAllCast

Returns true if all of the jurors have cast their votes for the last round.

function areVotesAllCast(uint256 _coreDisputeID) external view override returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core.

Returns

NameTypeDescription
<none>boolWhether all of the jurors have cast their votes for the last round.

isVoteActive

Returns true if the specified voter was active in this round.

function isVoteActive(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    override
    returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.
_voteIDuint256The ID of the voter.

Returns

NameTypeDescription
<none>boolWhether the voter was active or not.

getRoundInfo

function getRoundInfo(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _choice)
    external
    view
    override
    returns (
        uint256 winningChoice,
        bool tied,
        uint256 totalVoted,
        uint256 totalCommited,
        uint256 nbVoters,
        uint256 choiceCount
    );

getVoteInfo

function getVoteInfo(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    override
    returns (address account, bytes32 commit, uint256 choice, bool voted);

_postDrawCheck

Checks that the chosen address satisfies certain conditions for being drawn.

function _postDrawCheck(uint256 _coreDisputeID, address _juror) internal view override returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256ID of the dispute in the core contract.
_juroraddressChosen address.

Returns

NameTypeDescription
<none>boolWhether the address can be drawn or not.

_proofOfHumanity

Checks if an address belongs to the Proof of Humanity registry.

function _proofOfHumanity(address _address) internal view returns (bool);

Parameters

NameTypeDescription
_addressaddressThe address to check.

Returns

NameTypeDescription
<none>boolregistered True if registered.

Events

DisputeCreation

event DisputeCreation(uint256 indexed _coreDisputeID, uint256 _numberOfChoices, bytes _extraData);

CommitCast

event CommitCast(uint256 indexed _coreDisputeID, uint256[] _voteIDs, bytes32 _commit);

Contribution

event Contribution(
    uint256 indexed _coreDisputeID,
    uint256 indexed _coreRoundID,
    uint256 _choice,
    address indexed _contributor,
    uint256 _amount
);

Withdrawal

event Withdrawal(
    uint256 indexed _coreDisputeID,
    uint256 indexed _coreRoundID,
    uint256 _choice,
    address indexed _contributor,
    uint256 _amount
);

ChoiceFunded

event ChoiceFunded(uint256 indexed _coreDisputeID, uint256 indexed _coreRoundID, uint256 indexed _choice);

Structs

Dispute

struct Dispute {
    Round[] rounds;
    uint256 numberOfChoices;
    bool jumped;
    mapping(uint256 => uint256) coreRoundIDToLocal;
    bytes extraData;
}

Round

struct Round {
    Vote[] votes;
    uint256 winningChoice;
    mapping(uint256 => uint256) counts;
    bool tied;
    uint256 totalVoted;
    uint256 totalCommitted;
    mapping(uint256 => uint256) paidFees;
    mapping(uint256 => bool) hasPaid;
    mapping(address => mapping(uint256 => uint256)) contributions;
    uint256 feeRewards;
    uint256[] fundedChoices;
    uint256 nbVotes;
    mapping(address => bool) alreadyDrawn;
}

Vote

struct Vote {
    address account;
    bytes32 commit;
    uint256 choice;
    bool voted;
}

CentralizedArbitrator

Git Source

Inherits: IArbitrator

This is a centralized arbitrator deciding alone on the result of disputes. It illustrates how IArbitrator interface can be implemented. Note that this contract supports appeals. The ruling given by the arbitrator can be appealed by crowdfunding a desired choice.

State Variables

WINNER_STAKE_MULTIPLIER

uint256 public constant WINNER_STAKE_MULTIPLIER = 10000;

LOSER_STAKE_MULTIPLIER

uint256 public constant LOSER_STAKE_MULTIPLIER = 20000;

LOSER_APPEAL_PERIOD_MULTIPLIER

uint256 public constant LOSER_APPEAL_PERIOD_MULTIPLIER = 5000;

MULTIPLIER_DIVISOR

uint256 public constant MULTIPLIER_DIVISOR = 10000;

owner

address public owner = msg.sender;

appealDuration

uint256 public appealDuration;

arbitrationFee

uint256 private arbitrationFee;

appealFee

uint256 public appealFee;

disputes

DisputeStruct[] public disputes;

disputeIDtoRoundArray

mapping(uint256 => Round[]) public disputeIDtoRoundArray;

Functions

onlyOwner

modifier onlyOwner();

constructor

Constructor.

constructor(uint256 _arbitrationFee, uint256 _appealDuration, uint256 _appealFee);

Parameters

NameTypeDescription
_arbitrationFeeuint256Amount to be paid for arbitration.
_appealDurationuint256Duration of the appeal period.
_appealFeeuint256Amount to be paid to fund one of the appeal choices, not counting the additional fee stake amount.

setArbitrationFee

Set the arbitration fee. Only callable by the owner.

function setArbitrationFee(uint256 _arbitrationFee) external onlyOwner;

Parameters

NameTypeDescription
_arbitrationFeeuint256Amount to be paid for arbitration.

setAppealDuration

Set the duration of the appeal period. Only callable by the owner.

function setAppealDuration(uint256 _appealDuration) external onlyOwner;

Parameters

NameTypeDescription
_appealDurationuint256New duration of the appeal period.

setAppealFee

Set the appeal fee. Only callable by the owner.

function setAppealFee(uint256 _appealFee) external onlyOwner;

Parameters

NameTypeDescription
_appealFeeuint256Amount to be paid for appeal.

createDispute

Create a dispute. Must be called by the arbitrable contract. Must be paid at least arbitrationCost().

function createDispute(uint256 _choices, bytes calldata _extraData)
    external
    payable
    override
    returns (uint256 disputeID);

Parameters

NameTypeDescription
_choicesuint256Amount of choices the arbitrator can make in this dispute.
_extraDatabytesCan be used to give additional info on the dispute to be created.

Returns

NameTypeDescription
disputeIDuint256ID of the dispute created.

fundAppeal

Manages contributions, and appeals a dispute if at least two choices are fully funded. This function allows the appeals to be crowdfunded. Note that the surplus deposit will be reimbursed.

function fundAppeal(uint256 _disputeID, uint256 _choice) external payable;

Parameters

NameTypeDescription
_disputeIDuint256Index of the dispute to appeal.
_choiceuint256A choice that receives funding.

giveRuling

Give a ruling to a dispute. Once it's given the dispute can be appealed, and after the appeal period has passed this function should be called again to finalize the ruling. Accounts for the situation where the winner loses a case due to paying less appeal fees than expected.

function giveRuling(uint256 _disputeID, uint256 _ruling) external onlyOwner;

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute to rule.
_rulinguint256Ruling given by the arbitrator. Note that 0 means that arbitrator chose "Refused to rule".

withdrawFeesAndRewards

Allows to withdraw any reimbursable fees or rewards after the dispute gets resolved.

function withdrawFeesAndRewards(uint256 _disputeID, address payable _beneficiary, uint256 _round, uint256 _choice)
    external
    returns (uint256 amount);

Parameters

NameTypeDescription
_disputeIDuint256Index of the dispute in disputes array.
_beneficiaryaddress payableThe address which rewards to withdraw.
_rounduint256The round the caller wants to withdraw from.
_choiceuint256The ruling option that the caller wants to withdraw from.

Returns

NameTypeDescription
amountuint256The withdrawn amount.

arbitrationCost

Cost of arbitration.

function arbitrationCost(bytes calldata) public view override returns (uint256 fee);

Returns

NameTypeDescription
feeuint256The required amount.

fundingStatus

Return the funded amount and funding goal for one of the choices.

function fundingStatus(uint256 _disputeID, uint256 _choice) external view returns (uint256 funded, uint256 goal);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute to appeal.
_choiceuint256The choice to check the funding status of.

Returns

NameTypeDescription
fundeduint256The amount funded so far for this choice in wei.
goaluint256The amount to fully fund this choice in wei.

appealPeriod

Compute the start and end of the dispute's appeal period, if possible. If the dispute is not appealble return (0, 0).

function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end);

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute.

Returns

NameTypeDescription
startuint256The start of the period.
enduint256The end of the period.

Events

AppealPossible

To be emitted when a dispute can be appealed.

event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);

AppealDecision

To be emitted when the current ruling is appealed.

event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);

Contribution

Raised when a contribution is made, inside fundAppeal function.

event Contribution(
    uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount
);

Withdrawal

Raised when a contributor withdraws a non-zero value.

event Withdrawal(
    uint256 indexed _disputeID, uint256 indexed _round, uint256 _choice, address indexed _contributor, uint256 _amount
);

ChoiceFunded

To be raised when a choice is fully funded for appeal.

event ChoiceFunded(uint256 indexed _disputeID, uint256 indexed _round, uint256 indexed _choice);

Structs

DisputeStruct

struct DisputeStruct {
    IArbitrable arbitrated;
    bytes arbitratorExtraData;
    uint256 choices;
    uint256 appealPeriodStart;
    uint256 arbitrationFee;
    uint256 ruling;
    DisputeStatus status;
}

Round

struct Round {
    mapping(uint256 => uint256) paidFees;
    mapping(uint256 => bool) hasPaid;
    mapping(address => mapping(uint256 => uint256)) contributions;
    uint256 feeRewards;
    uint256[] fundedChoices;
}

Enums

DisputeStatus

enum DisputeStatus {
    Waiting,
    Appealable,
    Solved
}

IArbitrableV2

Git Source

Arbitrable interface. When developing arbitrable contracts, we need to:

  • Define the action taken when a ruling is received by the contract.
  • Allow dispute creation. For this a function must call arbitrator.createDispute{value: _fee}(_choices,_extraData);

Functions

rule

Give a ruling for a dispute. Must be called by the arbitrator. The purpose of this function is to ensure that the address calling it has the right to rule on the contract.

function rule(uint256 _disputeID, uint256 _ruling) external;

Parameters

NameTypeDescription
_disputeIDuint256The identifier of the dispute in the Arbitrator contract.
_rulinguint256Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".

Events

DisputeTemplate

To be emitted when a new dispute template is created.

event DisputeTemplate(uint256 indexed _templateId, string indexed _templateTag, string _templateData);

DisputeRequest

To be emitted when a dispute is created to link the correct meta-evidence to the disputeID.

event DisputeRequest(
    IArbitratorV2 indexed _arbitrator,
    uint256 indexed _arbitrableDisputeID,
    uint256 _externalDisputeID,
    uint256 _templateId,
    string _templateUri
);

Ruling

To be raised when a ruling is given.

event Ruling(IArbitratorV2 indexed _arbitrator, uint256 indexed _disputeID, uint256 _ruling);

IArbitratorV2

Git Source

Functions

createDispute

Create a dispute. Must be called by the arbitrable contract. Must pay at least arbitrationCost(_extraData).

function createDispute(uint256 _choices, bytes calldata _extraData) external payable returns (uint256 disputeID);

Parameters

NameTypeDescription
_choicesuint256Amount of choices the arbitrator can make in this dispute.
_extraDatabytesCan be used to give additional info on the dispute to be created.

Returns

NameTypeDescription
disputeIDuint256The identifier of the dispute created.

arbitrationCost

Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.

function arbitrationCost(bytes calldata _extraData) external view returns (uint256 cost);

Parameters

NameTypeDescription
_extraDatabytesCan be used to give additional info on the dispute to be created.

Returns

NameTypeDescription
costuint256Required cost of arbitration.

currentRuling

Return the current ruling of a dispute. This is useful for parties to know if they should appeal.

function currentRuling(uint256 _disputeID) external view returns (uint256 ruling);

Parameters

NameTypeDescription
_disputeIDuint256The identifer of the dispute.

Returns

NameTypeDescription
rulinguint256The ruling which has been given or the one which will be given if there is no appeal.

Events

DisputeCreation

To be emitted when a dispute is created.

event DisputeCreation(uint256 indexed _disputeID, IArbitrableV2 indexed _arbitrable);

Ruling

To be raised when a ruling is given.

event Ruling(IArbitrableV2 indexed _arbitrable, uint256 indexed _disputeID, uint256 _ruling);

IDisputeKit

Git Source

Functions

createDispute

Creates a local dispute and maps it to the dispute ID in the Core contract. Note: Access restricted to Kleros Core only.

function createDispute(uint256 _coreDisputeID, uint256 _numberOfChoices, bytes calldata _extraData, uint256 _nbVotes)
    external;

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_numberOfChoicesuint256Number of choices of the dispute
_extraDatabytesAdditional info about the dispute, for possible use in future dispute kits.
_nbVotesuint256

draw

Draws the juror from the sortition tree. The drawn address is picked up by Kleros Core. Note: Access restricted to Kleros Core only.

function draw(uint256 _coreDisputeID) external returns (address drawnAddress);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.

Returns

NameTypeDescription
drawnAddressaddressThe drawn address.

currentRuling

Gets the current ruling of a specified dispute.

function currentRuling(uint256 _coreDisputeID) external view returns (uint256 ruling, bool tied, bool overridden);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.

Returns

NameTypeDescription
rulinguint256The current ruling.
tiedboolWhether it's a tie or not.
overriddenboolWhether the ruling was overridden by appeal funding or not.

getDegreeOfCoherence

Gets the degree of coherence of a particular voter. This function is called by Kleros Core in order to determine the amount of the reward.

function getDegreeOfCoherence(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    returns (uint256);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.
_voteIDuint256The ID of the vote.

Returns

NameTypeDescription
<none>uint256The degree of coherence in basis points.

getCoherentCount

Gets the number of jurors who are eligible to a reward in this round.

function getCoherentCount(uint256 _coreDisputeID, uint256 _coreRoundID) external view returns (uint256);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.

Returns

NameTypeDescription
<none>uint256The number of coherent jurors.

areCommitsAllCast

Returns true if all of the jurors have cast their commits for the last round.

function areCommitsAllCast(uint256 _coreDisputeID) external view returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.

Returns

NameTypeDescription
<none>boolWhether all of the jurors have cast their commits for the last round.

areVotesAllCast

Returns true if all of the jurors have cast their votes for the last round.

function areVotesAllCast(uint256 _coreDisputeID) external view returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.

Returns

NameTypeDescription
<none>boolWhether all of the jurors have cast their votes for the last round.

isVoteActive

Returns true if the specified voter was active in this round.

function isVoteActive(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID) external view returns (bool);

Parameters

NameTypeDescription
_coreDisputeIDuint256The ID of the dispute in Kleros Core, not in the Dispute Kit.
_coreRoundIDuint256The ID of the round in Kleros Core, not in the Dispute Kit.
_voteIDuint256The ID of the voter.

Returns

NameTypeDescription
<none>boolWhether the voter was active or not.

getRoundInfo

function getRoundInfo(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _choice)
    external
    view
    returns (
        uint256 winningChoice,
        bool tied,
        uint256 totalVoted,
        uint256 totalCommited,
        uint256 nbVoters,
        uint256 choiceCount
    );

getVoteInfo

function getVoteInfo(uint256 _coreDisputeID, uint256 _coreRoundID, uint256 _voteID)
    external
    view
    returns (address account, bytes32 commit, uint256 choice, bool voted);

Events

Justification

Emitted when casting a vote to provide the justification of juror's choice.

event Justification(
    uint256 indexed _coreDisputeID, address indexed _juror, uint256 indexed _choice, string _justification
);

ISortitionModule

Git Source

Functions

createTree

function createTree(bytes32 _key, bytes memory _extraData) external;

setStake

function setStake(address _account, uint96 _courtID, uint256 _value) external;

setJurorInactive

function setJurorInactive(address _account) external;

notifyRandomNumber

function notifyRandomNumber(uint256 _drawnNumber) external;

draw

function draw(bytes32 _court, uint256 _coreDisputeID, uint256 _voteID) external view returns (address);

preStakeHook

function preStakeHook(address _account, uint96 _courtID, uint256 _stake, uint256 _penalty)
    external
    returns (preStakeHookResult);

createDisputeHook

function createDisputeHook(uint256 _disputeID, uint256 _roundID) external;

postDrawHook

function postDrawHook(uint256 _disputeID, uint256 _roundID) external;

Events

NewPhase

event NewPhase(Phase _phase);

Enums

Phase

enum Phase {
    staking,
    generating,
    drawing
}

preStakeHookResult

enum preStakeHookResult {
    ok,
    delayed,
    failed
}

KlerosCore

Git Source

Inherits: IArbitrator

State Variables

FORKING_COURT

uint96 public constant FORKING_COURT = 0;

GENERAL_COURT

uint96 public constant GENERAL_COURT = 1;

NULL_DISPUTE_KIT

uint256 public constant NULL_DISPUTE_KIT = 0;

DISPUTE_KIT_CLASSIC

uint256 public constant DISPUTE_KIT_CLASSIC = 1;

DEFAULT_NB_OF_JURORS

uint256 public constant DEFAULT_NB_OF_JURORS = 3;

ALPHA_DIVISOR

uint256 public constant ALPHA_DIVISOR = 1e4;

NON_PAYABLE_AMOUNT

uint256 public constant NON_PAYABLE_AMOUNT = (2 ** 256 - 2) / 2;

SEARCH_ITERATIONS

uint256 public constant SEARCH_ITERATIONS = 10;

governor

address public governor;

pinakion

IERC20 public pinakion;

jurorProsecutionModule

address public jurorProsecutionModule;

sortitionModule

ISortitionModule public sortitionModule;

courts

Court[] public courts;

disputeKitNodes

DisputeKitNode[] public disputeKitNodes;

disputes

Dispute[] public disputes;

jurors

mapping(address => Juror) internal jurors;

Functions

onlyByGovernor

modifier onlyByGovernor();

constructor

Constructor.

constructor(
    address _governor,
    IERC20 _pinakion,
    address _jurorProsecutionModule,
    IDisputeKit _disputeKit,
    bool _hiddenVotes,
    uint256[4] memory _courtParameters,
    uint256[4] memory _timesPerPeriod,
    bytes memory _sortitionExtraData,
    ISortitionModule _sortitionModuleAddress
);

Parameters

NameTypeDescription
_governoraddressThe governor's address.
_pinakionIERC20The address of the token contract.
_jurorProsecutionModuleaddressThe address of the juror prosecution module.
_disputeKitIDisputeKitThe address of the default dispute kit.
_hiddenVotesboolThe hiddenVotes property value of the general court.
_courtParametersuint256[4]Numeric parameters of General court (minStake, alpha, feeForJuror and jurorsForCourtJump respectively).
_timesPerPerioduint256[4]The timesPerPeriod property value of the general court.
_sortitionExtraDatabytesThe extra data for sortition module.
_sortitionModuleAddressISortitionModuleThe sortition module responsible for sortition of the jurors.

executeGovernorProposal

Allows the governor to call anything on behalf of the contract.

function executeGovernorProposal(address _destination, uint256 _amount, bytes memory _data) external onlyByGovernor;

Parameters

NameTypeDescription
_destinationaddressThe destination of the call.
_amountuint256The value sent with the call.
_databytesThe data sent with the call.

changeGovernor

Changes the governor storage variable.

function changeGovernor(address payable _governor) external onlyByGovernor;

Parameters

NameTypeDescription
_governoraddress payableThe new value for the governor storage variable.

changePinakion

Changes the pinakion storage variable.

function changePinakion(IERC20 _pinakion) external onlyByGovernor;

Parameters

NameTypeDescription
_pinakionIERC20The new value for the pinakion storage variable.

changeJurorProsecutionModule

Changes the jurorProsecutionModule storage variable.

function changeJurorProsecutionModule(address _jurorProsecutionModule) external onlyByGovernor;

Parameters

NameTypeDescription
_jurorProsecutionModuleaddressThe new value for the jurorProsecutionModule storage variable.

changeSortitionModule

Changes the _sortitionModule storage variable. Note that the new module should be initialized for all courts.

function changeSortitionModule(ISortitionModule _sortitionModule) external onlyByGovernor;

Parameters

NameTypeDescription
_sortitionModuleISortitionModuleThe new value for the sortitionModule storage variable.

addNewDisputeKit

Add a new supported dispute kit module to the court.

function addNewDisputeKit(IDisputeKit _disputeKitAddress, uint256 _parent) external onlyByGovernor;

Parameters

NameTypeDescription
_disputeKitAddressIDisputeKitThe address of the dispute kit contract.
_parentuint256The ID of the parent dispute kit. It is left empty when root DK is created. Note that the root DK must be supported by the general court.

createCourt

Creates a court under a specified parent court.

function createCourt(
    uint96 _parent,
    bool _hiddenVotes,
    uint256 _minStake,
    uint256 _alpha,
    uint256 _feeForJuror,
    uint256 _jurorsForCourtJump,
    uint256[4] memory _timesPerPeriod,
    bytes memory _sortitionExtraData,
    uint256[] memory _supportedDisputeKits
) external onlyByGovernor;

Parameters

NameTypeDescription
_parentuint96The parent property value of the court.
_hiddenVotesboolThe hiddenVotes property value of the court.
_minStakeuint256The minStake property value of the court.
_alphauint256The alpha property value of the court.
_feeForJuroruint256The feeForJuror property value of the court.
_jurorsForCourtJumpuint256The jurorsForCourtJump property value of the court.
_timesPerPerioduint256[4]The timesPerPeriod property value of the court.
_sortitionExtraDatabytesExtra data for sortition module.
_supportedDisputeKitsuint256[]Indexes of dispute kits that this court will support.

changeCourtMinStake

Changes the minStake property value of a specified court. Don't set to a value lower than its parent's minStake property value.

function changeCourtMinStake(uint96 _courtID, uint256 _minStake) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_minStakeuint256The new value for the minStake property value.

changeCourtAlpha

Changes the alpha property value of a specified court.

function changeCourtAlpha(uint96 _courtID, uint256 _alpha) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_alphauint256The new value for the alpha property value.

changeCourtJurorFee

Changes the feeForJuror property value of a specified court.

function changeCourtJurorFee(uint96 _courtID, uint256 _feeForJuror) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_feeForJuroruint256The new value for the feeForJuror property value.

changeCourtJurorsForJump

Changes the jurorsForCourtJump property value of a specified court.

function changeCourtJurorsForJump(uint96 _courtID, uint256 _jurorsForCourtJump) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_jurorsForCourtJumpuint256The new value for the jurorsForCourtJump property value.

changeCourtHiddenVotes

Changes the hiddenVotes property value of a specified court.

function changeCourtHiddenVotes(uint96 _courtID, bool _hiddenVotes) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_hiddenVotesboolThe new value for the hiddenVotes property value.

changeCourtTimesPerPeriod

Changes the timesPerPeriod property value of a specified court.

function changeCourtTimesPerPeriod(uint96 _courtID, uint256[4] memory _timesPerPeriod) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_timesPerPerioduint256[4]The new value for the timesPerPeriod property value.

enableDisputeKits

Adds/removes court's support for specified dispute kits.

function enableDisputeKits(uint96 _courtID, uint256[] memory _disputeKitIDs, bool _enable) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_disputeKitIDsuint256[]The IDs of dispute kits which support should be added/removed.
_enableboolWhether add or remove the dispute kits from the court.

setStake

Sets the caller's stake in a court.

function setStake(uint96 _courtID, uint256 _stake) external;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court.
_stakeuint256The new stake.

setStakeBySortitionModule

function setStakeBySortitionModule(address _account, uint96 _courtID, uint256 _stake, uint256 _penalty) external;

createDispute

Creates a dispute. Must be called by the arbitrable contract.

function createDispute(uint256 _numberOfChoices, bytes memory _extraData)
    external
    payable
    override
    returns (uint256 disputeID);

Parameters

NameTypeDescription
_numberOfChoicesuint256Number of choices for the jurors to choose from.
_extraDatabytesAdditional info about the dispute. We use it to pass the ID of the dispute's court (first 32 bytes), the minimum number of jurors required (next 32 bytes) and the ID of the specific dispute kit (last 32 bytes).

Returns

NameTypeDescription
disputeIDuint256The ID of the created dispute.

passPeriod

Passes the period of a specified dispute.

function passPeriod(uint256 _disputeID) external;

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

draw

Draws jurors for the dispute. Can be called in parts.

function draw(uint256 _disputeID, uint256 _iterations) external;

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.
_iterationsuint256The number of iterations to run.

appeal

Appeals the ruling of a specified dispute. Note: Access restricted to the Dispute Kit for this disputeID.

function appeal(uint256 _disputeID, uint256 _numberOfChoices, bytes memory _extraData) external payable;

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.
_numberOfChoicesuint256Number of choices for the dispute. Can be required during court jump.
_extraDatabytesExtradata for the dispute. Can be required during court jump.

execute

Distribute tokens and ETH for the specific round of the dispute. Can be called in parts.

function execute(uint256 _disputeID, uint256 _round, uint256 _iterations) external;

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.
_rounduint256The appeal round.
_iterationsuint256The number of iterations to run.

_executePenalties

Distribute the tokens and ETH for the specific round of the dispute, penalties only.

function _executePenalties(ExecuteParams memory _params) internal returns (uint256);

Parameters

NameTypeDescription
_paramsExecuteParamsThe parameters for the execution, see ExecuteParams.

Returns

NameTypeDescription
<none>uint256penaltiesInRoundCache The updated penalties in round cache.

_executeRewards

Distribute the tokens and ETH for the specific round of the dispute, rewards only.

function _executeRewards(ExecuteParams memory _params) internal;

Parameters

NameTypeDescription
_paramsExecuteParamsThe parameters for the execution, see ExecuteParams.

executeRuling

Executes a specified dispute's ruling.

function executeRuling(uint256 _disputeID) external;

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

arbitrationCost

Gets the cost of arbitration in a specified court.

function arbitrationCost(bytes memory _extraData) public view override returns (uint256 cost);

Parameters

NameTypeDescription
_extraDatabytesAdditional info about the dispute. We use it to pass the ID of the court to create the dispute in (first 32 bytes) and the minimum number of jurors required (next 32 bytes).

Returns

NameTypeDescription
costuint256The arbitration cost.

appealCost

Gets the cost of appealing a specified dispute.

function appealCost(uint256 _disputeID) public view returns (uint256 cost);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

Returns

NameTypeDescription
costuint256The appeal cost.

appealPeriod

Gets the start and the end of a specified dispute's current appeal period.

function appealPeriod(uint256 _disputeID) public view returns (uint256 start, uint256 end);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

Returns

NameTypeDescription
startuint256The start of the appeal period.
enduint256The end of the appeal period.

currentRuling

Gets the current ruling of a specified dispute.

function currentRuling(uint256 _disputeID) public view returns (uint256 ruling, bool tied, bool overridden);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

Returns

NameTypeDescription
rulinguint256The current ruling.
tiedboolWhether it's a tie or not.
overriddenboolWhether the ruling was overridden by appeal funding or not.

getRoundInfo

function getRoundInfo(uint256 _disputeID, uint256 _round)
    external
    view
    returns (
        uint256 tokensAtStakePerJuror,
        uint256 totalFeesForJurors,
        uint256 repartitions,
        uint256 penalties,
        address[] memory drawnJurors,
        uint256 disputeKitID,
        uint256 sumRewardPaid,
        uint256 sumTokenRewardPaid
    );

getNumberOfRounds

function getNumberOfRounds(uint256 _disputeID) external view returns (uint256);

getJurorBalance

function getJurorBalance(address _juror, uint96 _courtID)
    external
    view
    returns (uint256 staked, uint256 locked, uint256 nbCourts);

isSupported

function isSupported(uint96 _courtID, uint256 _disputeKitID) external view returns (bool);

getDisputeKitChildren

Gets non-primitive properties of a specified dispute kit node.

function getDisputeKitChildren(uint256 _disputeKitID) external view returns (uint256[] memory);

Parameters

NameTypeDescription
_disputeKitIDuint256The ID of the dispute kit.

Returns

NameTypeDescription
<none>uint256[]children Indexes of children of this DK.

getTimesPerPeriod

Gets the timesPerPeriod array for a given court.

function getTimesPerPeriod(uint96 _courtID) external view returns (uint256[4] memory timesPerPeriod);

Parameters

NameTypeDescription
_courtIDuint96The ID of the court to get the times from.

Returns

NameTypeDescription
timesPerPerioduint256[4]The timesPerPeriod array for the given court.

getNumberOfVotes

Gets the number of votes permitted for the specified dispute in the latest round.

function getNumberOfVotes(uint256 _disputeID) external view returns (uint256);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

isDisputeKitJumping

Returns true if the dispute kit will be switched to a parent DK.

function isDisputeKitJumping(uint256 _disputeID) external view returns (bool);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

Returns

NameTypeDescription
<none>boolWhether DK will be switched or not.

getDisputeKitNodesLength

function getDisputeKitNodesLength() external view returns (uint256);

getDisputeKit

Gets the dispute kit for a specific _disputeKitID.

function getDisputeKit(uint256 _disputeKitID) external view returns (IDisputeKit);

Parameters

NameTypeDescription
_disputeKitIDuint256The ID of the dispute kit.

getJurorCourtIDs

Gets the court identifiers where a specific _juror has staked.

function getJurorCourtIDs(address _juror) public view returns (uint96[] memory);

Parameters

NameTypeDescription
_juroraddressThe address of the juror.

_enableDisputeKit

Toggles the dispute kit support for a given court.

function _enableDisputeKit(uint96 _courtID, uint256 _disputeKitID, bool _enable) internal;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court to toggle the support for.
_disputeKitIDuint256The ID of the dispute kit to toggle the support for.
_enableboolWhether to enable or disable the support.

_setStakeForAccount

Sets the specified juror's stake in a court. O(n + p * log_k(j)) where n is the number of courts the juror has staked in, p is the depth of the court tree, k is the minimum number of children per node of one of these courts' sortition sum tree, and j is the maximum number of jurors that ever staked in one of these courts simultaneously.

function _setStakeForAccount(address _account, uint96 _courtID, uint256 _stake, uint256 _penalty)
    internal
    returns (bool succeeded);

Parameters

NameTypeDescription
_accountaddressThe address of the juror.
_courtIDuint96The ID of the court.
_stakeuint256The new stake.
_penaltyuint256Penalized amount won't be transferred back to juror when the stake is lowered.

Returns

NameTypeDescription
succeededboolTrue if the call succeeded, false otherwise.

_extraDataToCourtIDMinJurorsDisputeKit

Gets a court ID, the minimum number of jurors and an ID of a dispute kit from a specified extra data bytes array. Note that if extradata contains an incorrect value then this value will be switched to default.

function _extraDataToCourtIDMinJurorsDisputeKit(bytes memory _extraData)
    internal
    view
    returns (uint96 courtID, uint256 minJurors, uint256 disputeKitID);

Parameters

NameTypeDescription
_extraDatabytesThe extra data bytes array. The first 32 bytes are the court ID, the next are the minimum number of jurors and the last are the dispute kit ID.

Returns

NameTypeDescription
courtIDuint96The court ID.
minJurorsuint256The minimum number of jurors required.
disputeKitIDuint256The ID of the dispute kit.

_safeTransfer

Calls transfer() without reverting.

function _safeTransfer(address _to, uint256 _value) internal returns (bool);

Parameters

NameTypeDescription
_toaddressRecepient address.
_valueuint256Amount transferred.

Returns

NameTypeDescription
<none>boolWhether transfer succeeded or not.

_safeTransferFrom

Calls transferFrom() without reverting.

function _safeTransferFrom(address _from, address _to, uint256 _value) internal returns (bool);

Parameters

NameTypeDescription
_fromaddressSender address.
_toaddressRecepient address.
_valueuint256Amount transferred.

Returns

NameTypeDescription
<none>boolWhether transfer succeeded or not.

Events

StakeSet

event StakeSet(address indexed _address, uint256 _courtID, uint256 _amount);

StakeDelayed

event StakeDelayed(address indexed _address, uint256 _courtID, uint256 _amount, uint256 _penalty);

NewPeriod

event NewPeriod(uint256 indexed _disputeID, Period _period);

AppealPossible

event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);

AppealDecision

event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable);

Draw

event Draw(address indexed _address, uint256 indexed _disputeID, uint256 _roundID, uint256 _voteID);

CourtCreated

event CourtCreated(
    uint256 indexed _courtID,
    uint96 indexed _parent,
    bool _hiddenVotes,
    uint256 _minStake,
    uint256 _alpha,
    uint256 _feeForJuror,
    uint256 _jurorsForCourtJump,
    uint256[4] _timesPerPeriod,
    uint256[] _supportedDisputeKits
);

CourtModified

event CourtModified(uint96 indexed _courtID, string _param);

DisputeKitCreated

event DisputeKitCreated(uint256 indexed _disputeKitID, IDisputeKit indexed _disputeKitAddress, uint256 indexed _parent);

DisputeKitEnabled

event DisputeKitEnabled(uint96 indexed _courtID, uint256 indexed _disputeKitID, bool indexed _enable);

CourtJump

event CourtJump(uint256 indexed _disputeID, uint256 indexed _roundID, uint96 indexed _fromCourtID, uint96 _toCourtID);

DisputeKitJump

event DisputeKitJump(
    uint256 indexed _disputeID, uint256 indexed _roundID, uint256 indexed _fromDisputeKitID, uint256 _toDisputeKitID
);

TokenAndETHShift

event TokenAndETHShift(
    address indexed _account,
    uint256 indexed _disputeID,
    uint256 indexed _roundID,
    uint256 _degreeOfCoherency,
    int256 _tokenAmount,
    int256 _ethAmount
);

LeftoverRewardSent

event LeftoverRewardSent(
    uint256 indexed _disputeID, uint256 indexed _roundID, uint256 _tokenAmount, uint256 _ethAmount
);

Structs

Court

struct Court {
    uint96 parent;
    bool hiddenVotes;
    uint256[] children;
    uint256 minStake;
    uint256 alpha;
    uint256 feeForJuror;
    uint256 jurorsForCourtJump;
    uint256[4] timesPerPeriod;
    mapping(uint256 => bool) supportedDisputeKits;
    bool disabled;
}

Dispute

struct Dispute {
    uint96 courtID;
    IArbitrable arbitrated;
    Period period;
    bool ruled;
    uint256 lastPeriodChange;
    Round[] rounds;
}

Round

struct Round {
    uint256 disputeKitID;
    uint256 tokensAtStakePerJuror;
    uint256 totalFeesForJurors;
    uint256 nbVotes;
    uint256 repartitions;
    uint256 penalties;
    address[] drawnJurors;
    uint256 sumRewardPaid;
    uint256 sumTokenRewardPaid;
}

Juror

struct Juror {
    uint96[] courtIDs;
    mapping(uint96 => uint256) stakedTokens;
    mapping(uint96 => uint256) lockedTokens;
}

DisputeKitNode

struct DisputeKitNode {
    uint256 parent;
    uint256[] children;
    IDisputeKit disputeKit;
    uint256 depthLevel;
    bool disabled;
}

ExecuteParams

struct ExecuteParams {
    uint256 disputeID;
    uint256 round;
    uint256 coherentCount;
    uint256 numberOfVotesInRound;
    uint256 penaltiesInRound;
    uint256 repartition;
}

Enums

Period

enum Period {
    evidence,
    commit,
    vote,
    appeal,
    execution
}

KlerosGovernor

Git Source

Inherits: IArbitrableV2

State Variables

arbitrator

IArbitratorV2 public arbitrator;

arbitratorExtraData

bytes public arbitratorExtraData;

disputeTemplates

uint256 public disputeTemplates;

submissionBaseDeposit

uint256 public submissionBaseDeposit;

submissionTimeout

uint256 public submissionTimeout;

executionTimeout

uint256 public executionTimeout;

withdrawTimeout

uint256 public withdrawTimeout;

lastApprovalTime

uint256 public lastApprovalTime;

reservedETH

uint256 public reservedETH;

submissions

Submission[] public submissions;

sessions

Session[] public sessions;

Functions

duringSubmissionPeriod

modifier duringSubmissionPeriod();

duringApprovalPeriod

modifier duringApprovalPeriod();

onlyByGovernor

modifier onlyByGovernor();

constructor

Constructor.

constructor(
    IArbitratorV2 _arbitrator,
    bytes memory _arbitratorExtraData,
    string memory _templateData,
    uint256 _submissionBaseDeposit,
    uint256 _submissionTimeout,
    uint256 _executionTimeout,
    uint256 _withdrawTimeout
);

Parameters

NameTypeDescription
_arbitratorIArbitratorV2The arbitrator of the contract.
_arbitratorExtraDatabytesExtra data for the arbitrator.
_templateDatastringThe dispute template data.
_submissionBaseDeposituint256The base deposit required for submission.
_submissionTimeoutuint256Time in seconds allocated for submitting transaction list.
_executionTimeoutuint256Time in seconds after approval that allows to execute transactions of the approved list.
_withdrawTimeoutuint256Time in seconds after submission that allows to withdraw submitted list.

changeSubmissionDeposit

Changes the value of the base deposit required for submitting a list.

function changeSubmissionDeposit(uint256 _submissionBaseDeposit) external onlyByGovernor;

Parameters

NameTypeDescription
_submissionBaseDeposituint256The new value of the base deposit, in wei.

changeSubmissionTimeout

Changes the time allocated for submission. Note that it can't be changed during approval period because there can be an active dispute in the old arbitrator contract and prolonging submission timeout might switch it back to submission period.

function changeSubmissionTimeout(uint256 _submissionTimeout) external onlyByGovernor duringSubmissionPeriod;

Parameters

NameTypeDescription
_submissionTimeoutuint256The new duration of the submission period, in seconds.

changeExecutionTimeout

Changes the time allocated for list's execution.

function changeExecutionTimeout(uint256 _executionTimeout) external onlyByGovernor;

Parameters

NameTypeDescription
_executionTimeoutuint256The new duration of the execution timeout, in seconds.

changeWithdrawTimeout

Changes list withdrawal timeout. Note that withdrawals are only possible in the first half of the submission period.

function changeWithdrawTimeout(uint256 _withdrawTimeout) external onlyByGovernor;

Parameters

NameTypeDescription
_withdrawTimeoutuint256The new duration of withdraw period, in seconds.

changeArbitrator

Changes the arbitrator of the contract. Note that it can't be changed during approval period because there can be an active dispute in the old arbitrator contract.

function changeArbitrator(IArbitratorV2 _arbitrator, bytes memory _arbitratorExtraData)
    external
    onlyByGovernor
    duringSubmissionPeriod;

Parameters

NameTypeDescription
_arbitratorIArbitratorV2The new trusted arbitrator.
_arbitratorExtraDatabytesThe extra data used by the new arbitrator.

changeDisputeTemplate

Update the dispute template data.

function changeDisputeTemplate(string memory _templateData) external onlyByGovernor;

Parameters

NameTypeDescription
_templateDatastringThe new dispute template data.

submitList

Creates transaction list based on input parameters and submits it for potential approval and execution. Transactions must be ordered by their hash.

function submitList(
    address[] memory _target,
    uint256[] memory _value,
    bytes memory _data,
    uint256[] memory _dataSize,
    string memory _description
) external payable duringSubmissionPeriod;

Parameters

NameTypeDescription
_targetaddress[]List of addresses to call.
_valueuint256[]List of values required for respective addresses.
_databytesConcatenated calldata of all transactions of this list.
_dataSizeuint256[]List of lengths in bytes required to split calldata for its respective targets.
_descriptionstringString in CSV format that describes list's transactions.

withdrawTransactionList

Withdraws submitted transaction list. Reimburses submission deposit. Withdrawal is only possible during the first half of the submission period and during withdrawTimeout after the submission is made.

function withdrawTransactionList(uint256 _submissionID, bytes32 _listHash) external;

Parameters

NameTypeDescription
_submissionIDuint256Submission's index in the array of submitted lists of the current sesssion.
_listHashbytes32Hash of a withdrawing list.

executeSubmissions

Approves a transaction list or creates a dispute if more than one list was submitted. If nothing was submitted changes session.

function executeSubmissions() external duringApprovalPeriod;

rule

Gives a ruling for a dispute. Must be called by the arbitrator.

function rule(uint256 _disputeID, uint256 _ruling) external override;

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute in the Arbitrator contract.
_rulinguint256Ruling given by the arbitrator. Note that 0 is reserved for "Refuse to arbitrate". Note If the final ruling is "0" nothing is approved and deposits will stay locked in the contract.

executeTransactionList

Executes selected transactions of the list.

function executeTransactionList(uint256 _listID, uint256 _cursor, uint256 _count) external;

Parameters

NameTypeDescription
_listIDuint256The index of the transaction list in the array of lists.
_cursoruint256Index of the transaction from which to start executing.
_countuint256Number of transactions to execute. Executes until the end if set to "0" or number higher than number of transactions in the list.

receive

Receive function to receive funds for the execution of transactions.

receive() external payable;

getExpendableFunds

Gets the sum of contract funds that are used for the execution of transactions.

function getExpendableFunds() public view returns (uint256);

Returns

NameTypeDescription
<none>uint256Contract balance without reserved ETH.

getTransactionInfo

Gets the info of the specific transaction in the specific list.

function getTransactionInfo(uint256 _listID, uint256 _transactionIndex)
    external
    view
    returns (address target, uint256 value, bytes memory data, bool executed);

Parameters

NameTypeDescription
_listIDuint256The index of the transaction list in the array of lists.
_transactionIndexuint256The index of the transaction.

Returns

NameTypeDescription
targetaddressThe target of the transaction.
valueuint256The value of the transaction.
databytesThe data of the transaction.
executedboolWhether the transaction was executed or not.

getSubmittedLists

Gets the array of submitted lists in the session. Note that this function is O(n), where n is the number of submissions in the session. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts.

function getSubmittedLists(uint256 _session) external view returns (uint256[] memory submittedLists);

Parameters

NameTypeDescription
_sessionuint256The ID of the session.

Returns

NameTypeDescription
submittedListsuint256[]Indexes of lists that were submitted during the session.

getNumberOfTransactions

Gets the number of transactions in the list.

function getNumberOfTransactions(uint256 _listID) external view returns (uint256 txCount);

Parameters

NameTypeDescription
_listIDuint256The index of the transaction list in the array of lists.

Returns

NameTypeDescription
txCountuint256The number of transactions in the list.

getNumberOfCreatedLists

Gets the number of lists created in contract's lifetime.

function getNumberOfCreatedLists() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The number of created lists.

getCurrentSessionNumber

Gets the number of the ongoing session.

function getCurrentSessionNumber() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The number of the ongoing session.

Events

ListSubmitted

Emitted when a new list is submitted.

event ListSubmitted(uint256 indexed _listID, address indexed _submitter, uint256 indexed _session, string _description);

Structs

Session

struct Session {
    uint256 ruling;
    uint256 disputeID;
    uint256[] submittedLists;
    uint256 sumDeposit;
    Status status;
    mapping(bytes32 => bool) alreadySubmitted;
    uint256 durationOffset;
}

Transaction

struct Transaction {
    address target;
    uint256 value;
    bytes data;
    bool executed;
}

Submission

struct Submission {
    address payable submitter;
    uint256 deposit;
    Transaction[] txs;
    bytes32 listHash;
    uint256 submissionTime;
    bool approved;
    uint256 approvalTime;
}

Enums

Status

enum Status {
    NoDispute,
    DisputeCreated,
    Resolved
}

PolicyRegistry

Git Source

Author: Enrique Piqueras - epiquerass@gmail.com

A contract to maintain a policy for each court.

State Variables

governor

address public governor;

policies

mapping(uint256 => string) public policies;

Functions

onlyByGovernor

Requires that the sender is the governor.

modifier onlyByGovernor();

constructor

Constructs the PolicyRegistry contract.

constructor(address _governor);

Parameters

NameTypeDescription
_governoraddressThe governor's address.

changeGovernor

Changes the governor storage variable.

function changeGovernor(address _governor) external onlyByGovernor;

Parameters

NameTypeDescription
_governoraddressThe new value for the governor storage variable.

setPolicy

Sets the policy for the specified court.

function setPolicy(uint256 _courtID, string calldata _courtName, string calldata _policy) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint256The ID of the specified court.
_courtNamestringThe name of the specified court.
_policystringThe URI of the policy JSON.

Events

PolicyUpdate

Emitted when a policy is updated.

event PolicyUpdate(uint256 indexed _courtID, string _courtName, string _policy);

SortitionModule

Git Source

Inherits: ISortitionModule

A factory of trees that keeps track of staked values for sortition.

State Variables

MAX_STAKE_PATHS

uint256 public constant MAX_STAKE_PATHS = 4;

DEFAULT_K

uint256 public constant DEFAULT_K = 6;

governor

address public governor;

core

KlerosCore public core;

phase

Phase public phase;

minStakingTime

uint256 public minStakingTime;

maxDrawingTime

uint256 public maxDrawingTime;

lastPhaseChange

uint256 public lastPhaseChange;

randomNumberRequestBlock

uint256 public randomNumberRequestBlock;

disputesWithoutJurors

uint256 public disputesWithoutJurors;

rng

RNG public rng;

randomNumber

uint256 public randomNumber;

rngLookahead

uint256 public rngLookahead;

delayedStakeWriteIndex

uint256 public delayedStakeWriteIndex;

delayedStakeReadIndex

uint256 public delayedStakeReadIndex = 1;

sortitionSumTrees

mapping(bytes32 => SortitionSumTree) sortitionSumTrees;

delayedStakes

mapping(uint256 => DelayedStake) public delayedStakes;

Functions

onlyByGovernor

modifier onlyByGovernor();

onlyByCore

modifier onlyByCore();

constructor

Constructor.

constructor(
    address _governor,
    KlerosCore _core,
    uint256 _minStakingTime,
    uint256 _maxDrawingTime,
    RNG _rng,
    uint256 _rngLookahead
);

Parameters

NameTypeDescription
_governoraddress
_coreKlerosCoreThe KlerosCore.
_minStakingTimeuint256Minimal time to stake
_maxDrawingTimeuint256Time after which the drawing phase can be switched
_rngRNGThe random number generator.
_rngLookaheaduint256Lookahead value for rng.

changeMinStakingTime

Changes the minStakingTime storage variable.

function changeMinStakingTime(uint256 _minStakingTime) external onlyByGovernor;

Parameters

NameTypeDescription
_minStakingTimeuint256The new value for the minStakingTime storage variable.

changeMaxDrawingTime

Changes the maxDrawingTime storage variable.

function changeMaxDrawingTime(uint256 _maxDrawingTime) external onlyByGovernor;

Parameters

NameTypeDescription
_maxDrawingTimeuint256The new value for the maxDrawingTime storage variable.

changeRandomNumberGenerator

Changes the _rng and _rngLookahead storage variables.

function changeRandomNumberGenerator(RNG _rng, uint256 _rngLookahead) external onlyByGovernor;

Parameters

NameTypeDescription
_rngRNGThe new value for the RNGenerator storage variable.
_rngLookaheaduint256The new value for the rngLookahead storage variable.

passPhase

function passPhase() external;

createTree

Create a sortition sum tree at the specified key.

function createTree(bytes32 _key, bytes memory _extraData) external override onlyByCore;

Parameters

NameTypeDescription
_keybytes32The key of the new tree.
_extraDatabytesExtra data that contains the number of children each node in the tree should have.

executeDelayedStakes

Executes the next delayed stakes.

function executeDelayedStakes(uint256 _iterations) external;

Parameters

NameTypeDescription
_iterationsuint256The number of delayed stakes to execute.

preStakeHook

function preStakeHook(address _account, uint96 _courtID, uint256 _stake, uint256 _penalty)
    external
    override
    onlyByCore
    returns (preStakeHookResult);

createDisputeHook

function createDisputeHook(uint256, uint256) external override onlyByCore;

postDrawHook

function postDrawHook(uint256, uint256) external override onlyByCore;

notifyRandomNumber

Saves the random number to use it in sortition. Not used by this contract because the storing of the number is inlined in passPhase().

function notifyRandomNumber(uint256 _randomNumber) public override;

Parameters

NameTypeDescription
_randomNumberuint256Random number returned by RNG contract.

setStake

Sets the value for a particular court and its parent courts.

function setStake(address _account, uint96 _courtID, uint256 _value) external override onlyByCore;

Parameters

NameTypeDescription
_accountaddressAddress of the juror. O(log_k(n)) where k is the maximum number of children per node in the tree, and n is the maximum number of nodes ever appended.
_courtIDuint96ID of the court.
_valueuint256The new value.

setJurorInactive

Unstakes the inactive juror from all courts. O(n * (p * log_k(j)) ) where n is the number of courts the juror has staked in, p is the depth of the court tree, k is the minimum number of children per node of one of these courts' sortition sum tree, and j is the maximum number of jurors that ever staked in one of these courts simultaneously.

function setJurorInactive(address _account) external override onlyByCore;

Parameters

NameTypeDescription
_accountaddressThe juror to unstake.

draw

Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.

function draw(bytes32 _key, uint256 _coreDisputeID, uint256 _voteID)
    public
    view
    override
    returns (address drawnAddress);

Parameters

NameTypeDescription
_keybytes32The key of the tree.
_coreDisputeIDuint256Index of the dispute in Kleros Core.
_voteIDuint256ID of the voter.

Returns

NameTypeDescription
drawnAddressaddressThe drawn address. O(k * log_k(n)) where k is the maximum number of children per node in the tree, and n is the maximum number of nodes ever appended.

_updateParents

Update all the parents of a node.

function _updateParents(bytes32 _key, uint256 _treeIndex, bool _plusOrMinus, uint256 _value) private;

Parameters

NameTypeDescription
_keybytes32The key of the tree to update.
_treeIndexuint256The index of the node to start from.
_plusOrMinusboolWhether to add (true) or substract (false).
_valueuint256The value to add or substract. O(log_k(n)) where k is the maximum number of children per node in the tree, and n is the maximum number of nodes ever appended.

_stakePathIDToAccount

Retrieves a juror's address from the stake path ID.

function _stakePathIDToAccount(bytes32 _stakePathID) internal pure returns (address account);

Parameters

NameTypeDescription
_stakePathIDbytes32The stake path ID to unpack.

Returns

NameTypeDescription
accountaddressThe account.

_extraDataToTreeK

function _extraDataToTreeK(bytes memory _extraData) internal pure returns (uint256 K);

_set

Set a value in a tree.

function _set(bytes32 _key, uint256 _value, bytes32 _ID) internal;

Parameters

NameTypeDescription
_keybytes32The key of the tree.
_valueuint256The new value.
_IDbytes32The ID of the value. O(log_k(n)) where k is the maximum number of children per node in the tree, and n is the maximum number of nodes ever appended.

_accountAndCourtIDToStakePathID

Packs an account and a court ID into a stake path ID.

function _accountAndCourtIDToStakePathID(address _account, uint96 _courtID)
    internal
    pure
    returns (bytes32 stakePathID);

Parameters

NameTypeDescription
_accountaddressThe address of the juror to pack.
_courtIDuint96The court ID to pack.

Returns

NameTypeDescription
stakePathIDbytes32The stake path ID.

Structs

SortitionSumTree

struct SortitionSumTree {
    uint256 K;
    uint256[] stack;
    uint256[] nodes;
    mapping(bytes32 => uint256) IDsToNodeIndexes;
    mapping(uint256 => bytes32) nodeIndexesToIDs;
}

DelayedStake

struct DelayedStake {
    address account;
    uint96 courtID;
    uint256 stake;
    uint256 penalty;
}

Contents

EvidenceModule

Git Source

State Variables

arbitrator

IArbitrator public arbitrator;

Functions

constructor

constructor(IArbitrator _arbitrator);

submitEvidence

Submits evidence.

function submitEvidence(uint256 _evidenceGroupID, string calldata _evidence) external;

Parameters

NameTypeDescription
_evidenceGroupIDuint256Unique identifier of the evidence group the evidence belongs to. It's the submitter responsability to submit the right evidence group ID.
_evidencestringIPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'.

Events

Evidence

event Evidence(
    IArbitrator indexed _arbitrator, uint256 indexed _evidenceGroupID, address indexed _party, string _evidence
);

IEvidence

Git Source

Events

Evidence

To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations).

event Evidence(uint256 indexed _externalDisputeID, address indexed _party, string _evidence);

ModeratedEvidenceModule

Git Source

Inherits: IArbitrableV2

State Variables

AMOUNT_OF_CHOICES

uint256 public constant AMOUNT_OF_CHOICES = 2;

MULTIPLIER_DIVISOR

uint256 public constant MULTIPLIER_DIVISOR = 10000;

evidences

mapping(bytes32 => EvidenceData) evidences;

disputeIDtoEvidenceID

mapping(uint256 => bytes32) public disputeIDtoEvidenceID;

arbitratorDataList

ArbitratorData[] public arbitratorDataList;

arbitrator

IArbitratorV2 public immutable arbitrator;

governor

address public governor;

bondTimeout

uint256 public bondTimeout;

totalCostMultiplier

uint256 public totalCostMultiplier;

initialDepositMultiplier

uint256 public initialDepositMultiplier;

Functions

onlyGovernor

modifier onlyGovernor();

constructor

Constructor.

constructor(
    IArbitratorV2 _arbitrator,
    address _governor,
    uint256 _totalCostMultiplier,
    uint256 _initialDepositMultiplier,
    uint256 _bondTimeout,
    bytes memory _arbitratorExtraData,
    string memory _templateData
);

Parameters

NameTypeDescription
_arbitratorIArbitratorV2The trusted arbitrator to resolve potential disputes.
_governoraddressThe trusted governor of the contract.
_totalCostMultiplieruint256Multiplier of arbitration fees that must be ultimately paid as fee stake. In basis points.
_initialDepositMultiplieruint256Multiplier of arbitration fees that must be paid as initial stake for submitting evidence. In basis points.
_bondTimeoutuint256The time in seconds during which the last moderation status can be challenged.
_arbitratorExtraDatabytesExtra data for the trusted arbitrator contract.
_templateDatastringThe dispute template data.

changeGovernor

Change the governor of the contract.

function changeGovernor(address _governor) external onlyGovernor;

Parameters

NameTypeDescription
_governoraddressThe address of the new governor.

changeInitialDepositMultiplier

Change the proportion of arbitration fees that must be paid as fee stake by parties when there is no winner or loser (e.g. when the arbitrator refused to rule).

function changeInitialDepositMultiplier(uint256 _initialDepositMultiplier) external onlyGovernor;

Parameters

NameTypeDescription
_initialDepositMultiplieruint256Multiplier of arbitration fees that must be paid as fee stake. In basis points.

changeTotalCostMultiplier

Change the proportion of arbitration fees that must be paid as fee stake by the winner of the previous round.

function changeTotalCostMultiplier(uint256 _totalCostMultiplier) external onlyGovernor;

Parameters

NameTypeDescription
_totalCostMultiplieruint256Multiplier of arbitration fees that must be paid as fee stake. In basis points.

changeBondTimeout

Change the the time window within which evidence submissions and removals can be contested. Ongoing moderations will start using the latest bondTimeout available after calling moderate() again.

function changeBondTimeout(uint256 _bondTimeout) external onlyGovernor;

Parameters

NameTypeDescription
_bondTimeoutuint256Multiplier of arbitration fees that must be paid as fee stake. In basis points.

changeDisputeTemplate

Update the dispute template data.

function changeDisputeTemplate(string calldata _templateData) external onlyGovernor;

Parameters

NameTypeDescription
_templateDatastringThe new dispute template data.

changeArbitratorExtraData

Change the arbitrator to be used for disputes that may be raised in the next requests. The arbitrator is trusted to support appeal period and not reenter.

function changeArbitratorExtraData(bytes calldata _arbitratorExtraData) external onlyGovernor;

Parameters

NameTypeDescription
_arbitratorExtraDatabytesThe extra data used by the new arbitrator.

submitEvidence

Submits evidence.

function submitEvidence(uint256 _evidenceGroupID, string calldata _evidence) external payable;

Parameters

NameTypeDescription
_evidenceGroupIDuint256Unique identifier of the evidence group the evidence belongs to. It's the submitter responsability to submit the right evidence group ID.
_evidencestringIPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'.

moderate

Moderates an evidence submission. Requires the contester to at least double the accumulated stake of the oposing party. Optimization opportunity: use bytes calldata args and compress _evidenceID and _side (only for optimistic rollups).

function moderate(bytes32 _evidenceID, Party _side) external payable;

Parameters

NameTypeDescription
_evidenceIDbytes32Unique identifier of the evidence submission.
_sidePartyThe side to contribute to.

resolveModerationMarket

Resolves a moderation event once the timeout has passed.

function resolveModerationMarket(bytes32 _evidenceID) external;

Parameters

NameTypeDescription
_evidenceIDbytes32Unique identifier of the evidence submission.

contribute

Make a fee contribution.

function contribute(
    Moderation storage _moderation,
    Party _side,
    address payable _contributor,
    uint256 _amount,
    uint256 _totalRequired
) internal returns (uint256);

Parameters

NameTypeDescription
_moderationModerationThe moderation to contribute to.
_sidePartyThe side to contribute to.
_contributoraddress payableThe contributor.
_amountuint256The amount contributed.
_totalRequireduint256The total amount required for this side.

Returns

NameTypeDescription
<none>uint256The amount of fees contributed.

calculateContribution

Returns the contribution value and remainder from available ETH and required amount.

function calculateContribution(uint256 _available, uint256 _requiredAmount)
    internal
    pure
    returns (uint256 taken, uint256 remainder);

Parameters

NameTypeDescription
_availableuint256The amount of ETH available for the contribution.
_requiredAmountuint256The amount of ETH required for the contribution.

Returns

NameTypeDescription
takenuint256The amount of ETH taken.
remainderuint256The amount of ETH left from the contribution.

withdrawFeesAndRewards

Withdraws contributions of moderations. Reimburses contributions if the appeal was not fully funded. If the appeal was fully funded, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. Optimization opportunity: use bytes calldata args and compress _evidenceID and _moderationID (only for optimistic rollups).

function withdrawFeesAndRewards(address payable _beneficiary, bytes32 _evidenceID, uint256 _moderationID)
    external
    returns (uint256 reward);

Parameters

NameTypeDescription
_beneficiaryaddress payableThe address that made contributions.
_evidenceIDbytes32The ID of the associated evidence submission.
_moderationIDuint256The ID of the moderatino occurence.

rule

Give a ruling for a dispute. Must be called by the arbitrator to enforce the final ruling. The purpose of this function is to ensure that the address calling it has the right to rule on the contract.

function rule(uint256 _disputeID, uint256 _ruling) public override;

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute in the Arbitrator contract.
_rulinguint256Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".

getNumberOfModerations

Gets the number of moderation events of the specific evidence submission.

function getNumberOfModerations(bytes32 _evidenceID) external view returns (uint256);

Parameters

NameTypeDescription
_evidenceIDbytes32The ID of the evidence submission.

Returns

NameTypeDescription
<none>uint256The number of moderations.

getContributions

Gets the contributions made by a party for a given moderation.

function getContributions(bytes32 _evidenceID, uint256 _moderationID, address _contributor)
    external
    view
    returns (uint256[3] memory contributions);

Parameters

NameTypeDescription
_evidenceIDbytes32The ID of the evidence submission.
_moderationIDuint256The ID of the moderation occurence.
_contributoraddressThe address of the contributor.

Returns

NameTypeDescription
contributionsuint256[3]The contributions.

getModerationInfo

Gets the information of a moderation event.

function getModerationInfo(bytes32 _evidenceID, uint256 _moderationID)
    external
    view
    returns (uint256[3] memory paidFees, Party currentWinner, uint256 feeRewards);

Parameters

NameTypeDescription
_evidenceIDbytes32The ID of the evidence submission.
_moderationIDuint256The ID of the moderation occurence.

Returns

NameTypeDescription
paidFeesuint256[3]currentWinner feeRewards The moderation information.
currentWinnerParty
feeRewardsuint256

getCurrentArbitratorIndex

Gets the last arbitrator data index, which is used for current new submissions.

function getCurrentArbitratorIndex() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The last arbitrator data index.

Events

ModeratedEvidence

To be raised when a moderated evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations).

event ModeratedEvidence(
    IArbitratorV2 indexed _arbitrator, uint256 indexed _externalDisputeID, address indexed _party, string _evidence
);

ModerationStatusChanged

Indicate that a party has to pay a fee or would otherwise be considered as losing.

event ModerationStatusChanged(bytes32 indexed _evidenceID, Party _currentWinner);

Structs

EvidenceData

struct EvidenceData {
    address payable submitter;
    bool disputed;
    Party ruling;
    uint256 disputeID;
    Moderation[] moderations;
}

Moderation

struct Moderation {
    uint256[3] paidFees;
    uint256 feeRewards;
    mapping(address => uint256[3]) contributions;
    bool closed;
    Party currentWinner;
    uint256 bondDeadline;
    uint256 arbitratorDataID;
}

ArbitratorData

struct ArbitratorData {
    uint256 disputeTemplateId;
    bytes arbitratorExtraData;
}

Enums

Party

enum Party {
    None,
    Submitter,
    Moderator
}

Contents

Contents

IForeignGateway

Git Source

Inherits: IArbitratorV2, IReceiverGateway

Functions

relayRule

Relay the rule call from the home gateway to the arbitrable.

function relayRule(address _messageSender, bytes32 _disputeHash, uint256 _ruling, address _forwarder) external;

withdrawFees

function withdrawFees(bytes32 _disputeHash) external;

disputeHashToForeignID

function disputeHashToForeignID(bytes32 _disputeHash) external view returns (uint256);

createDisputeERC20

function createDisputeERC20(uint256 _choices, bytes calldata _extraData, uint256 _amount)
    external
    returns (uint256 disputeID);

Events

CrossChainDisputeOutgoing

To be emitted when a dispute is sent to the IHomeGateway.

event CrossChainDisputeOutgoing(
    bytes32 _foreignBlockHash,
    address indexed _foreignArbitrable,
    uint256 indexed _foreignDisputeID,
    uint256 _choices,
    bytes _extraData
);

IHomeGateway

Git Source

Inherits: IArbitrableV2, ISenderGateway

Functions

relayCreateDispute

Provide the same parameters as on the foreignChain while creating a dispute. Providing incorrect parameters will create a different hash than on the foreignChain and will not affect the actual dispute/arbitrable's ruling.

function relayCreateDispute(RelayCreateDisputeParams memory _params) external payable;

Parameters

NameTypeDescription
_paramsRelayCreateDisputeParamsThe parameters of the dispute, see RelayCreateDisputeParams.

disputeHashToHomeID

Looks up the local home disputeID for a disputeHash.

function disputeHashToHomeID(bytes32 _disputeHash) external view returns (uint256);

Parameters

NameTypeDescription
_disputeHashbytes32dispute hash

Returns

NameTypeDescription
<none>uint256disputeID dispute identifier on the home chain

Events

CrossChainDisputeIncoming

To be emitted when a dispute is received from the IForeignGateway.

event CrossChainDisputeIncoming(
    IArbitratorV2 indexed _arbitrator,
    uint256 _arbitrableChainId,
    address indexed _arbitrable,
    uint256 indexed _arbitrableDisputeID,
    uint256 _externalDisputeID,
    uint256 _templateId,
    string _templateUri
);

Structs

RelayCreateDisputeParams

struct RelayCreateDisputeParams {
    bytes32 foreignBlockHash;
    uint256 foreignChainID;
    address foreignArbitrable;
    uint256 foreignDisputeID;
    uint256 externalDisputeID;
    uint256 templateId;
    string templateUri;
    uint256 choices;
    bytes extraData;
}

Contents

VeaMock

Git Source

Inherits: IVeaOutboxOnL1, IVeaInbox

Functions

sendMessage

Sends an arbitrary message to receiving chain. Note: Calls authenticated by receiving gateway checking the sender argument.

function sendMessage(address _to, bytes4 _fnSelector, bytes memory _data) external returns (uint64 msgId);

Parameters

NameTypeDescription
_toaddressThe cross-domain contract address which receives the calldata.
_fnSelectorbytes4The function selector of the receiving contract.
_databytesThe message calldata, abi.encode(...)

Returns

NameTypeDescription
msgIduint64The index of the message in the inbox, as a message Id, needed to relay the message.

saveSnapshot

Snapshots can be saved a maximum of once per epoch. Saves snapshot of state root. O(log(count)) where count number of messages in the inbox.

function saveSnapshot() external;

sendMessage

Verifies and relays the message. Note: Gateways expect first argument of message call to be the arbitrum message sender, used for authentication.

function sendMessage(bytes32[] calldata _proof, uint64 _msgId, address _to, bytes calldata _message) external;

Parameters

NameTypeDescription
_proofbytes32[]The merkle proof to prove the message.
_msgIduint64The zero based index of the message in the inbox.
_toaddressThe address to send the message to.
_messagebytesThe message to relay.

resolveDisputedClaim

Resolves any challenge of the optimistic claim for 'epoch' using the canonical bridge. Note: Access restricted to canonical bridge.

function resolveDisputedClaim(uint256 _epoch, bytes32 _stateRoot, Claim memory _claim) external;

Parameters

NameTypeDescription
_epochuint256The epoch to verify.
_stateRootbytes32The true state root for the epoch.
_claimClaimThe claim associated with the epoch.

ForeignGateway

Git Source

Inherits: IForeignGateway

State Variables

DEFAULT_NB_OF_JURORS

uint256 public constant DEFAULT_NB_OF_JURORS = 3;

localDisputeID

uint256 internal localDisputeID = 1;

feeForJuror

mapping(uint96 => uint256) public feeForJuror;

governor

address public governor;

veaOutbox

address public veaOutbox;

senderChainID

uint256 public immutable senderChainID;

senderGateway

address public override senderGateway;

deprecatedVeaOutbox

address public deprecatedVeaOutbox;

deprecatedVeaOutboxExpiration

uint256 public deprecatedVeaOutboxExpiration;

disputeHashtoDisputeData

mapping(bytes32 => DisputeData) public disputeHashtoDisputeData;

Functions

onlyFromVea

modifier onlyFromVea(address _messageSender);

onlyByGovernor

modifier onlyByGovernor();

constructor

constructor(address _governor, address _veaOutbox, address _senderGateway, uint256 _senderChainID);

changeGovernor

Changes the governor.

function changeGovernor(address _governor) external;

Parameters

NameTypeDescription
_governoraddressThe address of the new governor.

changeVea

Changes the outbox.

function changeVea(address _veaOutbox, uint256 _gracePeriod) external onlyByGovernor;

Parameters

NameTypeDescription
_veaOutboxaddressThe address of the new outbox.
_gracePerioduint256The duration to accept messages from the deprecated bridge (if at all).

changeReceiverGateway

Changes the sender gateway.

function changeReceiverGateway(address _senderGateway) external;

Parameters

NameTypeDescription
_senderGatewayaddressThe address of the new sender gateway.

changeCourtJurorFee

Changes the feeForJuror property value of a specified court.

function changeCourtJurorFee(uint96 _courtID, uint256 _feeForJuror) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court on the v2 arbitrator. Not to be confused with the courtID on KlerosLiquid.
_feeForJuroruint256The new value for the feeForJuror property value.

createDispute

function createDispute(uint256 _choices, bytes calldata _extraData)
    external
    payable
    override
    returns (uint256 disputeID);

createDisputeERC20

function createDisputeERC20(uint256, bytes calldata, uint256) external override returns (uint256);

arbitrationCost

function arbitrationCost(bytes calldata _extraData) public view override returns (uint256 cost);

relayRule

Relay the rule call from the home gateway to the arbitrable.

function relayRule(address _messageSender, bytes32 _disputeHash, uint256 _ruling, address _relayer)
    external
    override
    onlyFromVea(_messageSender);

withdrawFees

function withdrawFees(bytes32 _disputeHash) external override;

disputeHashToForeignID

function disputeHashToForeignID(bytes32 _disputeHash) external view override returns (uint256);

currentRuling

function currentRuling(uint256 _disputeID) external view returns (uint256 ruling);

extraDataToCourtIDMinJurors

function extraDataToCourtIDMinJurors(bytes memory _extraData)
    internal
    view
    returns (uint96 courtID, uint256 minJurors);

Events

ArbitrationCostModified

event ArbitrationCostModified(uint96 indexed _courtID, uint256 _feeForJuror);

Structs

DisputeData

struct DisputeData {
    uint248 id;
    bool ruled;
    address arbitrable;
    uint256 paid;
    address relayer;
}

ForeignGatewayOnGnosis

Git Source

Inherits: IForeignGateway

State Variables

DEFAULT_NB_OF_JURORS

uint256 public constant DEFAULT_NB_OF_JURORS = 3;

weth

IERC20 public immutable weth;

localDisputeID

uint256 internal localDisputeID = 1;

feeForJuror

mapping(uint96 => uint256) public feeForJuror;

governor

address public governor;

veaOutbox

address public veaOutbox;

senderChainID

uint256 public immutable senderChainID;

senderGateway

address public override senderGateway;

deprecatedVeaOutbox

address public deprecatedVeaOutbox;

deprecatedVeaOutboxExpiration

uint256 public deprecatedVeaOutboxExpiration;

disputeHashtoDisputeData

mapping(bytes32 => DisputeData) public disputeHashtoDisputeData;

Functions

onlyFromVea

modifier onlyFromVea(address _messageSender);

onlyByGovernor

modifier onlyByGovernor();

constructor

constructor(address _governor, address _veaOutbox, address _senderGateway, uint256 _senderChainID, IERC20 _weth);

changeGovernor

Changes the governor.

function changeGovernor(address _governor) external;

Parameters

NameTypeDescription
_governoraddressThe address of the new governor.

changeVea

Changes the outbox.

function changeVea(address _veaOutbox, uint256 _gracePeriod) external onlyByGovernor;

Parameters

NameTypeDescription
_veaOutboxaddressThe address of the new outbox.
_gracePerioduint256The duration to accept messages from the deprecated bridge (if at all).

changeReceiverGateway

Changes the sender gateway.

function changeReceiverGateway(address _senderGateway) external;

Parameters

NameTypeDescription
_senderGatewayaddressThe address of the new sender gateway.

changeCourtJurorFee

Changes the feeForJuror property value of a specified court.

function changeCourtJurorFee(uint96 _courtID, uint256 _feeForJuror) external onlyByGovernor;

Parameters

NameTypeDescription
_courtIDuint96The ID of the court on the v2 arbitrator. Not to be confused with the courtID on KlerosLiquid.
_feeForJuroruint256The new value for the feeForJuror property value.

createDispute

function createDispute(uint256, bytes calldata) external payable override returns (uint256 disputeID);

createDisputeERC20

function createDisputeERC20(uint256 _choices, bytes calldata _extraData, uint256 _amount)
    external
    override
    returns (uint256 disputeID);

arbitrationCost

function arbitrationCost(bytes calldata _extraData) public view override returns (uint256 cost);

relayRule

Relay the rule call from the home gateway to the arbitrable.

function relayRule(address _messageSender, bytes32 _disputeHash, uint256 _ruling, address _relayer)
    external
    override
    onlyFromVea(_messageSender);

withdrawFees

function withdrawFees(bytes32 _disputeHash) external override;

disputeHashToForeignID

function disputeHashToForeignID(bytes32 _disputeHash) external view override returns (uint256);

currentRuling

function currentRuling(uint256 _disputeID) external view returns (uint256 ruling);

extraDataToCourtIDMinJurors

function extraDataToCourtIDMinJurors(bytes memory _extraData)
    internal
    view
    returns (uint96 courtID, uint256 minJurors);

Events

ArbitrationCostModified

event ArbitrationCostModified(uint96 indexed _courtID, uint256 _feeForJuror);

Structs

DisputeData

struct DisputeData {
    uint248 id;
    bool ruled;
    address arbitrable;
    uint256 paid;
    address relayer;
}

HomeGateway

Git Source

Inherits: IHomeGateway

State Variables

governor

address public governor;

arbitrator

IArbitratorV2 public arbitrator;

veaInbox

IVeaInbox public veaInbox;

receiverGateway

address public override receiverGateway;

receiverChainID

uint256 public immutable receiverChainID;

disputeIDtoHash

mapping(uint256 => bytes32) public disputeIDtoHash;

disputeHashtoID

mapping(bytes32 => uint256) public disputeHashtoID;

disputeHashtoRelayedData

mapping(bytes32 => RelayedData) public disputeHashtoRelayedData;

Functions

constructor

constructor(
    address _governor,
    IArbitratorV2 _arbitrator,
    IVeaInbox _veaInbox,
    address _receiverGateway,
    uint256 _receiverChainID
);

changeGovernor

Changes the governor.

function changeGovernor(address _governor) external;

Parameters

NameTypeDescription
_governoraddressThe address of the new governor.

changeArbitrator

Changes the arbitrator.

function changeArbitrator(IArbitratorV2 _arbitrator) external;

Parameters

NameTypeDescription
_arbitratorIArbitratorV2The address of the new arbitrator.

changeVea

Changes the vea inbox, useful to increase the claim deposit.

function changeVea(IVeaInbox _veaInbox) external;

Parameters

NameTypeDescription
_veaInboxIVeaInboxThe address of the new vea inbox.

changeReceiverGateway

Changes the receiver gateway.

function changeReceiverGateway(address _receiverGateway) external;

Parameters

NameTypeDescription
_receiverGatewayaddressThe address of the new receiver gateway.

relayCreateDispute

Provide the same parameters as on the foreignChain while creating a dispute. Providing incorrect parameters will create a different hash than on the foreignChain and will not affect the actual dispute/arbitrable's ruling.

function relayCreateDispute(RelayCreateDisputeParams memory _params) external payable override;

Parameters

NameTypeDescription
_paramsRelayCreateDisputeParamsThe parameters of the dispute, see RelayCreateDisputeParams.

rule

Give a ruling for a dispute. Must be called by the arbitrator. The purpose of this function is to ensure that the address calling it has the right to rule on the contract.

function rule(uint256 _disputeID, uint256 _ruling) external override;

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute in the Arbitrator contract.
_rulinguint256Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".

disputeHashToHomeID

Looks up the local home disputeID for a disputeHash. For cross-chain Evidence standard.

function disputeHashToHomeID(bytes32 _disputeHash) external view override returns (uint256);

Parameters

NameTypeDescription
_disputeHashbytes32dispute hash

Structs

RelayedData

struct RelayedData {
    uint256 arbitrationCost;
    address relayer;
}

Contents

Contents

IArbitrableV1

Git Source

Functions

rule

Give a ruling for a dispute. Must be called by the arbitrator. The purpose of this function is to ensure that the address calling it has the right to rule on the contract.

function rule(uint256 _disputeID, uint256 _ruling) external;

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute in the Arbitrator contract.
_rulinguint256Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".

Events

Ruling

To be raised when a ruling is given.

event Ruling(IArbitratorV1 indexed _arbitrator, uint256 indexed _disputeID, uint256 _ruling);

IArbitratorV1

Git Source

Functions

createDispute

Create a dispute. Must be called by the arbitrable contract. Must be paid at least arbitrationCost(_extraData).

function createDispute(uint256 _choices, bytes calldata _extraData) external payable returns (uint256 disputeID);

Parameters

NameTypeDescription
_choicesuint256Amount of choices the arbitrator can make in this dispute.
_extraDatabytesCan be used to give additional info on the dispute to be created.

Returns

NameTypeDescription
disputeIDuint256ID of the dispute created.

arbitrationCost

Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.

function arbitrationCost(bytes calldata _extraData) external view returns (uint256 cost);

Parameters

NameTypeDescription
_extraDatabytesCan be used to give additional info on the dispute to be created.

Returns

NameTypeDescription
costuint256Amount to be paid.

appeal

Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule.

function appeal(uint256 _disputeID, bytes calldata _extraData) external payable;

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute to be appealed.
_extraDatabytesCan be used to give extra info on the appeal.

appealCost

Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation.

function appealCost(uint256 _disputeID, bytes calldata _extraData) external view returns (uint256 cost);

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute to be appealed.
_extraDatabytesCan be used to give additional info on the dispute to be created.

Returns

NameTypeDescription
costuint256Amount to be paid.

appealPeriod

Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0).

function appealPeriod(uint256 _disputeID) external view returns (uint256 start, uint256 end);

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute.

Returns

NameTypeDescription
startuint256The start of the period.
enduint256The end of the period.

disputeStatus

Return the status of a dispute.

function disputeStatus(uint256 _disputeID) external view returns (DisputeStatus status);

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute to rule.

Returns

NameTypeDescription
statusDisputeStatusThe status of the dispute.

currentRuling

Return the current ruling of a dispute. This is useful for parties to know if they should appeal.

function currentRuling(uint256 _disputeID) external view returns (uint256 ruling);

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute.

Returns

NameTypeDescription
rulinguint256The ruling which has been given or the one which will be given if there is no appeal.

Events

DisputeCreation

To be emitted when a dispute is created.

event DisputeCreation(uint256 indexed _disputeID, IArbitrableV1 indexed _arbitrable);

AppealPossible

To be emitted when a dispute can be appealed.

event AppealPossible(uint256 indexed _disputeID, IArbitrableV1 indexed _arbitrable);

AppealDecision

To be emitted when the current ruling is appealed.

event AppealDecision(uint256 indexed _disputeID, IArbitrableV1 indexed _arbitrable);

Enums

DisputeStatus

enum DisputeStatus {
    Waiting,
    Appealable,
    Solved
}

IEvidenceV1

Git Source

Events

MetaEvidence

To be emitted when meta-evidence is submitted.

event MetaEvidence(uint256 indexed _metaEvidenceID, string _evidence);

Evidence

To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations).

event Evidence(
    IArbitratorV1 indexed _arbitrator, uint256 indexed _evidenceGroupID, address indexed _party, string _evidence
);

Dispute

To be emitted when a dispute is created to link the correct meta-evidence to the disputeID.

event Dispute(
    IArbitratorV1 indexed _arbitrator, uint256 indexed _disputeID, uint256 _metaEvidenceID, uint256 _evidenceGroupID
);

IKlerosLiquid

Git Source

Inherits: IArbitratorV1

Functions

courts

function courts(uint256 _index)
    external
    view
    returns (
        uint96 parent,
        bool hiddenVotes,
        uint256 minStake,
        uint256 alpha,
        uint256 feeForJuror,
        uint256 jurorsForCourtJump
    );

phase

function phase() external view returns (Phase);

lockInsolventTransfers

function lockInsolventTransfers() external view returns (bool);

minStakingTime

function minStakingTime() external view returns (uint256);

pinakion

function pinakion() external view returns (address);

disputes

function disputes(uint256 _index) external view returns (Dispute memory);

jurors

function jurors(address _account) external view returns (Juror memory);

changeSubcourtTimesPerPeriod

function changeSubcourtTimesPerPeriod(uint96 _subcourtID, uint256[4] calldata _timesPerPeriod) external;

executeGovernorProposal

function executeGovernorProposal(address _destination, uint256 _amount, bytes calldata _data) external;

getVote

function getVote(uint256 _disputeID, uint256 _appeal, uint256 _voteID)
    external
    view
    returns (address account, bytes32 commit, uint256 choice, bool voted);

getDispute

function getDispute(uint256 _disputeID)
    external
    view
    returns (
        uint256[] memory votesLengths,
        uint256[] memory tokensAtStakePerJuror,
        uint256[] memory totalFeesForJurors,
        uint256[] memory votesInEachRound,
        uint256[] memory repartitionsInEachRound,
        uint256[] memory penaltiesInEachRound
    );

getSubcourt

function getSubcourt(uint96 _subcourtID)
    external
    view
    returns (uint256[] memory children, uint256[4] memory timesPerPeriod);

Structs

Court

struct Court {
    uint96 parent;
    uint256[] children;
    bool hiddenVotes;
    uint256 minStake;
    uint256 alpha;
    uint256 feeForJuror;
    uint256 jurorsForCourtJump;
    uint256[4] timesPerPeriod;
}

Dispute

struct Dispute {
    uint96 subcourtID;
    address arbitrated;
    uint256 numberOfChoices;
    Period period;
    uint256 lastPeriodChange;
    uint256 drawsInRound;
    uint256 commitsInRound;
    bool ruled;
}

Juror

struct Juror {
    uint256 stakedTokens;
    uint256 lockedTokens;
}

Enums

Period

enum Period {
    evidence,
    commit,
    vote,
    appeal,
    execution
}

Phase

enum Phase {
    staking,
    generating,
    drawing
}

ITokenController

Git Source

The token controller contract must implement these functions. See https://github.com/Giveth/minime/blob/master/contracts/TokenController.sol

Functions

proxyPayment

Called when _owner sends ether to the MiniMe Token contract

function proxyPayment(address _owner) external payable returns (bool);

Parameters

NameTypeDescription
_owneraddressThe address that sent the ether to create tokens

Returns

NameTypeDescription
<none>boolTrue if the ether is accepted, false if it throws

onTransfer

Notifies the controller about a token transfer allowing the controller to react if desired

function onTransfer(address _from, address _to, uint256 _amount) external returns (bool);

Parameters

NameTypeDescription
_fromaddressThe origin of the transfer
_toaddressThe destination of the transfer
_amountuint256The amount of the transfer

Returns

NameTypeDescription
<none>boolFalse if the controller does not authorize the transfer

onApprove

Notifies the controller about an approval allowing the controller to react if desired

function onApprove(address _owner, address _spender, uint256 _amount) external returns (bool);

Parameters

NameTypeDescription
_owneraddressThe address that calls approve()
_spenderaddressThe spender in the approve() call
_amountuint256The amount in the approve() call

Returns

NameTypeDescription
<none>boolFalse if the controller does not authorize the approval

Contents

IPinakion

Git Source

Functions

balanceOf

function balanceOf(address who) external view returns (uint256);

KlerosLiquidToV2Governor

Git Source

Inherits: IArbitrableV2, ITokenController

State Variables

foreignGateway

IArbitratorV2 public immutable foreignGateway;

klerosLiquid

IKlerosLiquid public immutable klerosLiquid;

governor

address public governor;

klerosLiquidDisputeIDtoGatewayDisputeID

mapping(uint256 => uint256) public klerosLiquidDisputeIDtoGatewayDisputeID;

disputes

mapping(uint256 => DisputeData) public disputes;

frozenTokens

mapping(address => uint256) public frozenTokens;

isDisputeNotified

mapping(uint256 => mapping(uint256 => bool)) public isDisputeNotified;

Functions

onlyByGovernor

modifier onlyByGovernor();

constructor

Constructor. Before this contract is made the new governor of KlerosLiquid, the evidence period of all subcourts has to be set to uint(-1).

constructor(IKlerosLiquid _klerosLiquid, address _governor, IArbitratorV2 _foreignGateway);

Parameters

NameTypeDescription
_klerosLiquidIKlerosLiquidThe trusted arbitrator to resolve potential disputes.
_governoraddressThe trusted governor of the contract.
_foreignGatewayIArbitratorV2The trusted gateway that acts as an arbitrator, relaying disputes to v2.

executeGovernorProposal

Lets the governor call anything on behalf of the contract.

function executeGovernorProposal(address _destination, uint256 _amount, bytes calldata _data) external onlyByGovernor;

Parameters

NameTypeDescription
_destinationaddressThe destination of the call.
_amountuint256The value sent with the call.
_databytesThe data sent with the call.

changeGovernor

Changes the governor storage variable.

function changeGovernor(address _governor) external onlyByGovernor;

Parameters

NameTypeDescription
_governoraddressThe new value for the governor storage variable.

relayDispute

Relays disputes from KlerosLiquid to Kleros v2. Only disputes in the evidence period of the initial round can be realyed.

function relayDispute(uint256 _disputeID) external;

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute as defined in KlerosLiquid.

rule

Give a ruling for a dispute. Must be called by the arbitrator. The purpose of this function is to ensure that the address calling it has the right to rule on the contract.

function rule(uint256 _disputeID, uint256 _ruling) public override;

Parameters

NameTypeDescription
_disputeIDuint256The identifier of the dispute in the Arbitrator contract.
_rulinguint256Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".

notifyFrozenTokens

Registers jurors' tokens which where locked due to relaying a given dispute. These tokens don't count as locked.

function notifyFrozenTokens(uint256 _disputeID) external;

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute as defined in KlerosLiquid.

proxyPayment

Called when _owner sends ether to the MiniMe Token contract

function proxyPayment(address) external payable override returns (bool allowed);

Parameters

NameTypeDescription
<none>address

Returns

NameTypeDescription
allowedboolTrue if the ether is accepted, false if it throws

onTransfer

Notifies the controller about a token transfer allowing the controller to react if desired

function onTransfer(address _from, address, uint256 _amount) external view override returns (bool allowed);

Parameters

NameTypeDescription
_fromaddressThe origin of the transfer
<none>address
_amountuint256The amount of the transfer

Returns

NameTypeDescription
allowedboolFalse if the controller does not authorize the transfer

onApprove

Notifies the controller about an approval allowing the controller to react if desired

function onApprove(address, address, uint256) external pure override returns (bool allowed);

Parameters

NameTypeDescription
<none>address
<none>address
<none>uint256

Returns

NameTypeDescription
allowedboolFalse if the controller does not authorize the approval

receive

This contract should be able to receive arbitration fees from KlerosLiquid.

receive() external payable;

Structs

DisputeData

struct DisputeData {
    uint256 klerosLiquidDisputeID;
    bool ruled;
}

Contents

Contents

IERC677

Git Source

Functions

transfer

function transfer(address _to, uint256 _value) external returns (bool);

transferFrom

function transferFrom(address _from, address _to, uint256 _value) external returns (bool);

approve

function approve(address _spender, uint256 _value) external returns (bool);

IRandomAuRa

Git Source

Functions

currentSeed

function currentSeed() external view returns (uint256);

isCommitPhase

function isCommitPhase() external view returns (bool);

nextCommitPhaseStartBlock

function nextCommitPhaseStartBlock() external view returns (uint256);

collectRoundLength

function collectRoundLength() external view returns (uint256);

ITokenBridge

Git Source

Functions

relayTokens

function relayTokens(IERC677 token, address _receiver, uint256 _value) external;

WrappedPinakion

Git Source

Inherits: Initializable

State Variables

balances

mapping(address => uint256) private balances;

allowance

mapping(address => mapping(address => uint256)) public allowance;

totalSupply

Total supply of the token. Equals the total xPinakion deposit into the contract.

uint256 public totalSupply;

name

Name of the token.

string public name;

symbol

Symbol of the token.

string public symbol;

decimals

Number of decimals of the token.

uint8 public decimals;

controller

The token's controller.

address public controller;

xPinakion

Bridged PNK on xDai to be wrapped. This token is upgradeable.

IERC677 public xPinakion;

tokenBridge

xDai Token Bridge. The Token Bridge is upgradeable.

ITokenBridge public tokenBridge;

Functions

onlyController

Verifies that the sender has ability to modify controlled parameters.

modifier onlyController();

initialize

Initializer.

function initialize(string memory _name, string memory _symbol, IERC677 _xPinakion, ITokenBridge _tokenBridge)
    public
    initializer;

Parameters

NameTypeDescription
_namestringfor the wrapped PNK on the home chain.
_symbolstringfor wrapped PNK ticker on the home chain.
_xPinakionIERC677the home PNK contract which is already bridged to the foreign PNK contract.
_tokenBridgeITokenBridgethe TokenBridge contract.

changeController

function changeController(address _controller) external onlyController;

Parameters

NameTypeDescription
_controlleraddressThe new controller of the contract

deposit

Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid.

function deposit(uint256 _amount) external;

Parameters

NameTypeDescription
_amountuint256The amount of wrapped pinakions to mint.

onTokenBridged

IERC20 Receiver functionality.

Converts bridged PNK (xPinakion) into wrapped PNK which can be staked in KlerosLiquid. If the tokenBridge is calling this function, then this contract has already received the xPinakion tokens. Notice that the Home bridge calls onTokenBridge as a result of someone invoking relayTokensAndCall() on the Foreign bridge contract.

function onTokenBridged(address _token, uint256 _amount, bytes calldata _data) external;

Parameters

NameTypeDescription
_tokenaddressThe token address the _amount belongs to.
_amountuint256The amount of wrapped PNK to mint.
_databytesCalldata containing the address of the recipient. Notice that the address has to be padded to the right 32 bytes.

withdraw

Converts wrapped PNK back into bridged PNK (xPinakion).

function withdraw(uint256 _amount) external;

Parameters

NameTypeDescription
_amountuint256The amount of bridged PNK to withdraw.

withdrawAndConvertToPNK

Converts wrapped PNK back into PNK using the Token Bridge.

This function is not strictly needed, but it provides a good UX to users who want to get their Mainnet's PNK back. What normally takes 3 transactions, here is done in one go. Notice that the PNK have to be claimed on Mainnet's TokenBridge by the receiver.

function withdrawAndConvertToPNK(uint256 _amount, address _receiver) external;

Parameters

NameTypeDescription
_amountuint256The amount of PNK to withdraw.
_receiveraddressThe address which will receive the PNK back in the foreign chain.

transfer

Moves _amount tokens from the caller's account to _recipient.

function transfer(address _recipient, uint256 _amount) public returns (bool);

Parameters

NameTypeDescription
_recipientaddressThe entity receiving the funds.
_amountuint256The amount to tranfer in base units.

Returns

NameTypeDescription
<none>boolTrue on success.

transferFrom

Moves _amount tokens from _sender to _recipient using the allowance mechanism. _amount is then deducted from the caller's allowance.

function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool);

Parameters

NameTypeDescription
_senderaddressThe entity to take the funds from.
_recipientaddressThe entity receiving the funds.
_amountuint256The amount to tranfer in base units.

Returns

NameTypeDescription
<none>boolTrue on success.

approve

Approves _spender to spend _amount.

function approve(address _spender, uint256 _amount) public returns (bool);

Parameters

NameTypeDescription
_spenderaddressThe entity allowed to spend funds.
_amountuint256The amount of base units the entity will be allowed to spend.

Returns

NameTypeDescription
<none>boolTrue on success.

increaseAllowance

Increases the _spender allowance by _addedValue.

function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool);

Parameters

NameTypeDescription
_spenderaddressThe entity allowed to spend funds.
_addedValueuint256The amount of extra base units the entity will be allowed to spend.

Returns

NameTypeDescription
<none>boolTrue on success.

decreaseAllowance

Decreases the _spender allowance by _subtractedValue.

function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool);

Parameters

NameTypeDescription
_spenderaddressThe entity whose spending allocation will be reduced.
_subtractedValueuint256The reduction of spending allocation in base units.

Returns

NameTypeDescription
<none>boolTrue on success.

_mint

Internal function that mints an amount of the token and assigns it to an account. This encapsulates the modification of balances such that the proper events are emitted.

function _mint(address _recipient, uint256 _amount) internal;

Parameters

NameTypeDescription
_recipientaddressThe address which will receive the minted tokens.
_amountuint256The amount that will be created.

_burn

Destroys _amount tokens from the caller. Cannot burn locked tokens.

function _burn(uint256 _amount) internal;

Parameters

NameTypeDescription
_amountuint256The quantity of tokens to burn in base units.

isContract

Internal function to determine if an address is a contract.

function isContract(address _addr) internal view returns (bool);

Parameters

NameTypeDescription
_addraddressThe address being queried.

Returns

NameTypeDescription
<none>boolTrue if _addr is a contract.

balanceOf

Gets the balance of the specified address.

function balanceOf(address _owner) public view returns (uint256);

Parameters

NameTypeDescription
_owneraddressThe address to query the balance of.

Returns

NameTypeDescription
<none>uint256uint256 value representing the amount owned by the passed address.

Events

Transfer

Emitted when value tokens are moved from one account (from) to another (to).

Notice that value may be zero.

event Transfer(address indexed from, address indexed to, uint256 value);

Approval

Emitted when the allowance of a spender for an owner is set by a call to {approve}. value is the new allowance.

event Approval(address indexed owner, address indexed spender, uint256 value);

xKlerosLiquidV2

Git Source

Inherits: Initializable, ITokenController, IArbitratorV2

This contract is an adaption of Mainnet's KlerosLiquid (https://github.com/kleros/kleros/blob/69cfbfb2128c29f1625b3a99a3183540772fda08/contracts/kleros/KlerosLiquid.sol) for xDai chain. Notice that variables referring to ETH values in this contract, will hold the native token values of the chain on which xKlerosLiquid is deployed. When this contract gets deployed on xDai chain, ETH variables will hold xDai values.

State Variables

MAX_STAKE_PATHS

uint256 public constant MAX_STAKE_PATHS = 4;

DEFAULT_NB_OF_JURORS

uint256 public constant DEFAULT_NB_OF_JURORS = 3;

NON_PAYABLE_AMOUNT

uint256 public constant NON_PAYABLE_AMOUNT = (2 ** 256 - 2) / 2;

ALPHA_DIVISOR

uint256 public constant ALPHA_DIVISOR = 1e4;

governor

address public governor;

pinakion

WrappedPinakion public pinakion;

RNGenerator

IRandomAuRa public RNGenerator;

phase

Phase public phase;

lastPhaseChange

uint256 public lastPhaseChange;

disputesWithoutJurors

uint256 public disputesWithoutJurors;

RNBlock

uint256 public RNBlock;

RN

uint256 public RN;

minStakingTime

uint256 public minStakingTime;

maxDrawingTime

uint256 public maxDrawingTime;

lockInsolventTransfers

bool public lockInsolventTransfers;

courts

Court[] public courts;

sortitionSumTrees

SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees;

delayedSetStakes

mapping(uint256 => DelayedSetStake) public delayedSetStakes;

nextDelayedSetStake

uint256 public nextDelayedSetStake;

lastDelayedSetStake

uint256 public lastDelayedSetStake;

disputes

mapping(uint256 => Dispute) public disputes;

totalDisputes

uint256 public totalDisputes;

jurors

mapping(address => Juror) public jurors;

foreignGateway

IForeignGateway public foreignGateway;

weth

IERC20 public weth;

disputesRuling

mapping(uint256 => uint256) public disputesRuling;

Functions

onlyDuringPhase

Requires a specific phase.

modifier onlyDuringPhase(Phase _phase);

Parameters

NameTypeDescription
_phasePhaseThe required phase.

onlyDuringPeriod

Requires a specific period in a dispute.

modifier onlyDuringPeriod(uint256 _disputeID, Period _period);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.
_periodPeriodThe required period.

onlyByGovernor

Requires that the sender is the governor. Note that the governor is expected to not be malicious.

modifier onlyByGovernor();

initialize

Constructs the KlerosLiquid contract.

function initialize(
    address _governor,
    WrappedPinakion _pinakion,
    IRandomAuRa _RNGenerator,
    uint256 _minStakingTime,
    uint256 _maxDrawingTime,
    bool _hiddenVotes,
    uint256[4] memory _courtParameters,
    uint256[4] memory _timesPerPeriod,
    uint256 _sortitionSumTreeK,
    IForeignGateway _foreignGateway,
    IERC20 _weth
) public initializer;

Parameters

NameTypeDescription
_governoraddressThe governor's address.
_pinakionWrappedPinakionThe address of the token contract.
_RNGeneratorIRandomAuRaThe address of the random number generator contract.
_minStakingTimeuint256The minimum time that the staking phase should last.
_maxDrawingTimeuint256The maximum time that the drawing phase should last.
_hiddenVotesboolThe hiddenVotes property value of the general court.
_courtParametersuint256[4]MinStake, alpha, feeForJuror and jurorsForCourtJump respectively.
_timesPerPerioduint256[4]The timesPerPeriod property value of the general court.
_sortitionSumTreeKuint256The number of children per node of the general court's sortition sum tree.
_foreignGatewayIForeignGatewayForeign gateway on xDai.
_wethIERC20Weth contract.

executeGovernorProposal

Lets the governor call anything on behalf of the contract.

function executeGovernorProposal(address _destination, uint256 _amount, bytes memory _data) external onlyByGovernor;

Parameters

NameTypeDescription
_destinationaddressThe destination of the call.
_amountuint256The value sent with the call.
_databytesThe data sent with the call.

changeGovernor

Changes the governor storage variable.

function changeGovernor(address _governor) external onlyByGovernor;

Parameters

NameTypeDescription
_governoraddressThe new value for the governor storage variable.

changePinakion

Changes the pinakion storage variable.

function changePinakion(WrappedPinakion _pinakion) external onlyByGovernor;

Parameters

NameTypeDescription
_pinakionWrappedPinakionThe new value for the pinakion storage variable.

changeRNGenerator

Changes the RNGenerator storage variable.

function changeRNGenerator(IRandomAuRa _RNGenerator) external onlyByGovernor;

Parameters

NameTypeDescription
_RNGeneratorIRandomAuRaThe new value for the RNGenerator storage variable.

changeMinStakingTime

Changes the minStakingTime storage variable.

function changeMinStakingTime(uint256 _minStakingTime) external onlyByGovernor;

Parameters

NameTypeDescription
_minStakingTimeuint256The new value for the minStakingTime storage variable.

changeMaxDrawingTime

Changes the maxDrawingTime storage variable.

function changeMaxDrawingTime(uint256 _maxDrawingTime) external onlyByGovernor;

Parameters

NameTypeDescription
_maxDrawingTimeuint256The new value for the maxDrawingTime storage variable.

changeForeignGateway

Changes the foreignGateway storage variable.

function changeForeignGateway(IForeignGateway _foreignGateway) external onlyByGovernor;

Parameters

NameTypeDescription
_foreignGatewayIForeignGatewayThe new value for the foreignGateway storage variable.

changeWethAddress

Changes the weth storage variable.

function changeWethAddress(IERC20 _weth) external onlyByGovernor;

Parameters

NameTypeDescription
_wethIERC20The new value for the weth storage variable.

createSubcourt

Creates a subcourt under a specified parent court.

function createSubcourt(
    uint96 _parent,
    bool _hiddenVotes,
    uint256 _minStake,
    uint256 _alpha,
    uint256 _feeForJuror,
    uint256 _jurorsForCourtJump,
    uint256[4] memory _timesPerPeriod,
    uint256 _sortitionSumTreeK
) external onlyByGovernor;

Parameters

NameTypeDescription
_parentuint96The parent property value of the subcourt.
_hiddenVotesboolThe hiddenVotes property value of the subcourt.
_minStakeuint256The minStake property value of the subcourt.
_alphauint256The alpha property value of the subcourt.
_feeForJuroruint256The feeForJuror property value of the subcourt.
_jurorsForCourtJumpuint256The jurorsForCourtJump property value of the subcourt.
_timesPerPerioduint256[4]The timesPerPeriod property value of the subcourt.
_sortitionSumTreeKuint256The number of children per node of the subcourt's sortition sum tree.

changeSubcourtMinStake

Changes the minStake property value of a specified subcourt. Don't set to a value lower than its parent's minStake property value.

function changeSubcourtMinStake(uint96 _subcourtID, uint256 _minStake) external onlyByGovernor;

Parameters

NameTypeDescription
_subcourtIDuint96The ID of the subcourt.
_minStakeuint256The new value for the minStake property value.

changeSubcourtAlpha

Changes the alpha property value of a specified subcourt.

function changeSubcourtAlpha(uint96 _subcourtID, uint256 _alpha) external onlyByGovernor;

Parameters

NameTypeDescription
_subcourtIDuint96The ID of the subcourt.
_alphauint256The new value for the alpha property value.

changeSubcourtJurorFee

Changes the feeForJuror property value of a specified subcourt.

function changeSubcourtJurorFee(uint96 _subcourtID, uint256 _feeForJuror) external onlyByGovernor;

Parameters

NameTypeDescription
_subcourtIDuint96The ID of the subcourt.
_feeForJuroruint256The new value for the feeForJuror property value.

changeSubcourtJurorsForJump

Changes the jurorsForCourtJump property value of a specified subcourt.

function changeSubcourtJurorsForJump(uint96 _subcourtID, uint256 _jurorsForCourtJump) external onlyByGovernor;

Parameters

NameTypeDescription
_subcourtIDuint96The ID of the subcourt.
_jurorsForCourtJumpuint256The new value for the jurorsForCourtJump property value.

changeSubcourtTimesPerPeriod

Changes the timesPerPeriod property value of a specified subcourt.

function changeSubcourtTimesPerPeriod(uint96 _subcourtID, uint256[4] memory _timesPerPeriod) external onlyByGovernor;

Parameters

NameTypeDescription
_subcourtIDuint96The ID of the subcourt.
_timesPerPerioduint256[4]The new value for the timesPerPeriod property value.

setStake

Sets the caller's stake in a subcourt.

function setStake(uint96 _subcourtID, uint128 _stake) external;

Parameters

NameTypeDescription
_subcourtIDuint96The ID of the subcourt.
_stakeuint128The new stake.

executeDelayedSetStakes

Executes the next delayed set stakes. O(n) where n is the number of iterations to run.

function executeDelayedSetStakes(uint256 _iterations) external onlyDuringPhase(Phase.staking);

Parameters

NameTypeDescription
_iterationsuint256The number of delayed set stakes to execute.

rule

Receive the ruling from foreign gateway which technically is an arbitrator of this contract.

function rule(uint256 _disputeID, uint256 _ruling) external;

Parameters

NameTypeDescription
_disputeIDuint256ID of the dispute.
_rulinguint256Ruling given by V2 court and relayed by foreign gateway.

createDispute

Public

Creates a dispute. Must be called by the arbitrable contract.

function createDispute(uint256 _numberOfChoices, bytes memory _extraData)
    public
    payable
    override
    returns (uint256 disputeID);

Parameters

NameTypeDescription
_numberOfChoicesuint256Number of choices to choose from in the dispute to be created.
_extraDatabytesAdditional info about the dispute to be created. We use it to pass the ID of the subcourt to create the dispute in (first 32 bytes) and the minimum number of jurors required (next 32 bytes).

Returns

NameTypeDescription
disputeIDuint256The ID of the created dispute.

proxyPayment

DEPRECATED. Called when _owner sends ETH to the Wrapped Token contract.

function proxyPayment(address _owner) public payable override returns (bool allowed);

Parameters

NameTypeDescription
_owneraddressThe address that sent the ETH to create tokens.

Returns

NameTypeDescription
allowedboolWhether the operation should be allowed or not.

onTransfer

Notifies the controller about a token transfer allowing the controller to react if desired.

function onTransfer(address _from, address _to, uint256 _amount) public override returns (bool allowed);

Parameters

NameTypeDescription
_fromaddressThe origin of the transfer.
_toaddressThe destination of the transfer.
_amountuint256The amount of the transfer.

Returns

NameTypeDescription
allowedboolWhether the operation should be allowed or not.

onApprove

Notifies the controller about an approval allowing the controller to react if desired.

function onApprove(address _owner, address _spender, uint256 _amount) public override returns (bool allowed);

Parameters

NameTypeDescription
_owneraddressThe address that calls approve().
_spenderaddressThe spender in the approve() call.
_amountuint256The amount in the approve() call.

Returns

NameTypeDescription
allowedboolWhether the operation should be allowed or not.

_setStake

Sets the specified juror's stake in a subcourt. O(n + p * log_k(j)) where n is the number of subcourts the juror has staked in, p is the depth of the subcourt tree, k is the minimum number of children per node of one of these subcourts' sortition sum tree, and j is the maximum number of jurors that ever staked in one of these subcourts simultaneously.

function _setStake(address _account, uint96 _subcourtID, uint128 _stake) internal returns (bool succeeded);

Parameters

NameTypeDescription
_accountaddressThe address of the juror.
_subcourtIDuint96The ID of the subcourt.
_stakeuint128The new stake.

Returns

NameTypeDescription
succeededboolTrue if the call succeeded, false otherwise.

extraDataToSubcourtIDAndMinJurors

Gets a subcourt ID and the minimum number of jurors required from a specified extra data bytes array.

function extraDataToSubcourtIDAndMinJurors(bytes memory _extraData)
    internal
    view
    returns (uint96 subcourtID, uint256 minJurors);

Parameters

NameTypeDescription
_extraDatabytesThe extra data bytes array. The first 32 bytes are the subcourt ID and the next 32 bytes are the minimum number of jurors.

Returns

NameTypeDescription
subcourtIDuint96The subcourt ID.
minJurorsuint256The minimum number of jurors required.

accountAndSubcourtIDToStakePathID

Packs an account and a subcourt ID into a stake path ID.

function accountAndSubcourtIDToStakePathID(address _account, uint96 _subcourtID)
    internal
    pure
    returns (bytes32 stakePathID);

Parameters

NameTypeDescription
_accountaddressThe account to pack.
_subcourtIDuint96The subcourt ID to pack.

Returns

NameTypeDescription
stakePathIDbytes32The stake path ID.

arbitrationCost

Gets the cost of arbitration in a specified subcourt.

function arbitrationCost(bytes memory _extraData) public view override returns (uint256 cost);

Parameters

NameTypeDescription
_extraDatabytesAdditional info about the dispute. We use it to pass the ID of the subcourt to create the dispute in (first 32 bytes) and the minimum number of jurors required (next 32 bytes).

Returns

NameTypeDescription
costuint256The cost.

currentRuling

Gets the current ruling of a specified dispute.

function currentRuling(uint256 _disputeID) public view returns (uint256 ruling);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

Returns

NameTypeDescription
rulinguint256The current ruling.

getSubcourt

Gets a specified subcourt's non primitive properties.

function getSubcourt(uint96 _subcourtID)
    external
    view
    returns (uint256[] memory children, uint256[4] memory timesPerPeriod);

Parameters

NameTypeDescription
_subcourtIDuint96The ID of the subcourt.

Returns

NameTypeDescription
childrenuint256[]The subcourt's child court list.
timesPerPerioduint256[4]The subcourt's time per period.

getVote

Gets a specified vote for a specified appeal in a specified dispute.

function getVote(uint256 _disputeID, uint256 _appeal, uint256 _voteID)
    external
    view
    returns (address account, bytes32 commit, uint256 choice, bool voted);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.
_appealuint256The appeal.
_voteIDuint256The ID of the vote.

Returns

NameTypeDescription
accountaddressThe account for vote.
commitbytes32The commit for vote.
choiceuint256The choice for vote.
votedboolTrue if the account voted, False otherwise.

getVoteCounter

Gets the vote counter for a specified appeal in a specified dispute. Note: This function is only to be used by the interface and it won't work if the number of choices is too high.

function getVoteCounter(uint256 _disputeID, uint256 _appeal)
    external
    view
    returns (uint256 winningChoice, uint256[] memory counts, bool tied);

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.
_appealuint256The appeal.

Returns

NameTypeDescription
winningChoiceuint256The winning choice.
countsuint256[]The count.
tiedboolWhether the vote tied. O(n) where n is the number of choices of the dispute.

getDispute

Gets a specified dispute's non primitive properties.

function getDispute(uint256 _disputeID)
    external
    view
    returns (
        uint256[] memory votesLengths,
        uint256[] memory tokensAtStakePerJuror,
        uint256[] memory totalFeesForJurors,
        uint256[] memory votesInEachRound,
        uint256[] memory repartitionsInEachRound,
        uint256[] memory penaltiesInEachRound
    );

Parameters

NameTypeDescription
_disputeIDuint256The ID of the dispute.

Returns

NameTypeDescription
votesLengthsuint256[]The dispute's vote length.
tokensAtStakePerJuroruint256[]The dispute's required tokens at stake per Juror.
totalFeesForJurorsuint256[]The dispute's total fees for Jurors.
votesInEachRounduint256[]The dispute's counter of votes made in each round.
repartitionsInEachRounduint256[]The dispute's counter of vote reward repartitions made in each round.
penaltiesInEachRounduint256[]The dispute's amount of tokens collected from penalties in each round. O(a) where a is the number of appeals of the dispute.

getJuror

Gets a specified juror's non primitive properties.

function getJuror(address _account) external view returns (uint96[] memory subcourtIDs);

Parameters

NameTypeDescription
_accountaddressThe address of the juror.

Returns

NameTypeDescription
subcourtIDsuint96[]The juror's IDs of subcourts where the juror has stake path.

stakeOf

Gets the stake of a specified juror in a specified subcourt.

function stakeOf(address _account, uint96 _subcourtID) external view returns (uint256 stake);

Parameters

NameTypeDescription
_accountaddressThe address of the juror.
_subcourtIDuint96The ID of the subcourt.

Returns

NameTypeDescription
stakeuint256The stake.

Events

NewPhase

Emitted when we pass to a new phase.

event NewPhase(Phase _phase);

NewPeriod

Emitted when a dispute passes to a new period.

event NewPeriod(uint256 indexed _disputeID, Period _period);

StakeSet

Emitted when a juror's stake is set.

event StakeSet(address indexed _address, uint256 _subcourtID, uint128 _stake, uint256 _newTotalStake);

Draw

Emitted when a juror is drawn.

event Draw(address indexed _address, uint256 indexed _disputeID, uint256 _appeal, uint256 _voteID);

TokenAndETHShift

Emitted when a juror wins or loses tokens and ETH from a dispute.

event TokenAndETHShift(address indexed _address, uint256 indexed _disputeID, int256 _tokenAmount, int256 _ETHAmount);

Structs

Court

struct Court {
    uint96 parent;
    uint256[] children;
    bool hiddenVotes;
    uint256 minStake;
    uint256 alpha;
    uint256 feeForJuror;
    uint256 jurorsForCourtJump;
    uint256[4] timesPerPeriod;
}

DelayedSetStake

struct DelayedSetStake {
    address account;
    uint96 subcourtID;
    uint128 stake;
}

Vote

struct Vote {
    address account;
    bytes32 commit;
    uint256 choice;
    bool voted;
}

VoteCounter

struct VoteCounter {
    uint256 winningChoice;
    mapping(uint256 => uint256) counts;
    bool tied;
}

Dispute

struct Dispute {
    uint96 subcourtID;
    IArbitrableV2 arbitrated;
    uint256 numberOfChoices;
    Period period;
    uint256 lastPeriodChange;
    Vote[][] votes;
    VoteCounter[] voteCounters;
    uint256[] tokensAtStakePerJuror;
    uint256[] totalFeesForJurors;
    uint256 drawsInRound;
    uint256 commitsInRound;
    uint256[] votesInEachRound;
    uint256[] repartitionsInEachRound;
    uint256[] penaltiesInEachRound;
    bool ruled;
}

Juror

struct Juror {
    uint96[] subcourtIDs;
    uint256 stakedTokens;
    uint256 lockedTokens;
}

Enums

Phase

enum Phase {
    staking,
    generating,
    drawing
}

Period

enum Period {
    evidence,
    commit,
    vote,
    appeal,
    execution
}

Contents

CappedMath

Git Source

Math operations with caps for under and overflow.

State Variables

UINT_MAX

uint256 private constant UINT_MAX = type(uint256).max;

Functions

addCap

Adds two unsigned integers, returns 2^256 - 1 on overflow.

function addCap(uint256 _a, uint256 _b) internal pure returns (uint256);

subCap

Subtracts two integers, returns 0 on underflow.

function subCap(uint256 _a, uint256 _b) internal pure returns (uint256);

mulCap

Multiplies two unsigned integers, returns 2^256 - 1 on overflow.

function mulCap(uint256 _a, uint256 _b) internal pure returns (uint256);

SortitionSumTreeFactory

Git Source

Author: Enrique Piqueras - epiquerass@gmail.com

A factory of trees that keep track of staked values for sortition.

Functions

createTree

Public

Create a sortition sum tree at the specified key.

function createTree(SortitionSumTrees storage self, bytes32 _key, uint256 _K) public;

Parameters

NameTypeDescription
selfSortitionSumTrees
_keybytes32The key of the new tree.
_Kuint256The number of children each node in the tree should have.

set

Set a value of a tree.

function set(SortitionSumTrees storage self, bytes32 _key, uint256 _value, bytes32 _ID) public;

Parameters

NameTypeDescription
selfSortitionSumTrees
_keybytes32The key of the tree.
_valueuint256The new value.
_IDbytes32The ID of the value. O(log_k(n)) where k is the maximum number of childs per node in the tree, and n is the maximum number of nodes ever appended.

queryLeafs

Public Views

Query the leaves of a tree. Note that if startIndex == 0, the tree is empty and the root node will be returned.

function queryLeafs(SortitionSumTrees storage self, bytes32 _key, uint256 _cursor, uint256 _count)
    public
    view
    returns (uint256 startIndex, uint256[] memory values, bool hasMore);

Parameters

NameTypeDescription
selfSortitionSumTrees
_keybytes32The key of the tree to get the leaves from.
_cursoruint256The pagination cursor.
_countuint256The number of items to return.

Returns

NameTypeDescription
startIndexuint256The index at which leaves start.
valuesuint256[]The values of the returned leaves.
hasMoreboolWhether there are more for pagination. O(n) where n is the maximum number of nodes ever appended.

draw

Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.

function draw(SortitionSumTrees storage self, bytes32 _key, uint256 _drawnNumber) public view returns (bytes32 ID);

Parameters

NameTypeDescription
selfSortitionSumTrees
_keybytes32The key of the tree.
_drawnNumberuint256The drawn number.

Returns

NameTypeDescription
IDbytes32The drawn ID. O(k * log_k(n)) where k is the maximum number of childs per node in the tree, and n is the maximum number of nodes ever appended.

stakeOf

Gets a specified ID's associated value.

function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) public view returns (uint256 value);

Parameters

NameTypeDescription
selfSortitionSumTrees
_keybytes32The key of the tree.
_IDbytes32The ID of the value.

Returns

NameTypeDescription
valueuint256The associated value.

updateParents

Private

Update all the parents of a node.

function updateParents(
    SortitionSumTrees storage self,
    bytes32 _key,
    uint256 _treeIndex,
    bool _plusOrMinus,
    uint256 _value
) private;

Parameters

NameTypeDescription
selfSortitionSumTrees
_keybytes32The key of the tree to update.
_treeIndexuint256The index of the node to start from.
_plusOrMinusboolWether to add (true) or substract (false).
_valueuint256The value to add or substract. O(log_k(n)) where k is the maximum number of childs per node in the tree, and n is the maximum number of nodes ever appended.

Structs

SortitionSumTree

Structs

struct SortitionSumTree {
    uint256 K;
    uint256[] stack;
    uint256[] nodes;
    mapping(bytes32 => uint256) IDsToNodeIndexes;
    mapping(uint256 => bytes32) nodeIndexesToIDs;
}

SortitionSumTrees

Storage

struct SortitionSumTrees {
    mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}

Contents

Contents

RandomizerMock

Git Source

Inherits: IRandomizer

State Variables

id

uint256 private id;

Functions

request

function request(uint256 callbackGasLimit) external override returns (uint256);

clientWithdrawTo

function clientWithdrawTo(address _to, uint256 _amount) external override;

relay

function relay(RandomizerRNG _rng, uint256 _id, bytes32 _value) external;

BlockHashRNG

Git Source

Inherits: RNG

Author: Clément Lesaege - clement@lesaege.com

Random Number Generator returning the blockhash with a fallback behaviour. In case no one called it within the 256 blocks, it returns the previous blockhash. This contract must be used when returning 0 is a worse failure mode than returning another blockhash. Allows saving the random number for use in the future. It allows the contract to still access the blockhash even after 256 blocks.*

State Variables

randomNumbers

mapping(uint256 => uint256) public randomNumbers;

Functions

requestRandomness

Request a random number.

function requestRandomness(uint256 _block) external override;

Parameters

NameTypeDescription
_blockuint256Block the random number is linked to.

receiveRandomness

Return the random number. If it has not been saved and is still computable compute it.

function receiveRandomness(uint256 _block) external override returns (uint256 randomNumber);

Parameters

NameTypeDescription
_blockuint256Block the random number is linked to.

Returns

NameTypeDescription
randomNumberuint256The random number or 0 if it is not ready or has not been requested.

IRandomizer

Git Source

Functions

request

function request(uint256 callbackGasLimit) external returns (uint256);

clientWithdrawTo

function clientWithdrawTo(address _to, uint256 _amount) external;

IncrementalNG

Git Source

Inherits: RNG

Author: JayBuidl jb@kleros.io

A Random Number Generator which returns a number incremented by 1 each time. Useful as a fallback method.

State Variables

number

uint256 public number;

Functions

constructor

constructor(uint256 _start);

requestRandomness

Request a random number.

function requestRandomness(uint256 _block) external override;

Parameters

NameTypeDescription
_blockuint256Block the random number is linked to.

receiveRandomness

Get the "random number" (which is always the same).

function receiveRandomness(uint256 _block) external override returns (uint256 randomNumber);

Parameters

NameTypeDescription
_blockuint256Block the random number is linked to.

Returns

NameTypeDescription
randomNumberuint256The random number or 0 if it is not ready or has not been requested.

RNG

Git Source

Functions

requestRandomness

Request a random number.

function requestRandomness(uint256 _block) external;

Parameters

NameTypeDescription
_blockuint256Block linked to the request.

receiveRandomness

Receive the random number.

function receiveRandomness(uint256 _block) external returns (uint256 randomNumber);

Parameters

NameTypeDescription
_blockuint256Block the random number is linked to.

Returns

NameTypeDescription
randomNumberuint256Random Number. If the number is not ready or has not been required 0 instead.

RandomizerRNG

Git Source

Inherits: RNG

State Variables

governor

address public governor;

callbackGasLimit

uint256 public callbackGasLimit = 50000;

randomizer

IRandomizer public randomizer;

randomNumbers

mapping(uint256 => uint256) public randomNumbers;

requesterToID

mapping(address => uint256) public requesterToID;

Functions

onlyByGovernor

modifier onlyByGovernor();

constructor

Constructor.

constructor(IRandomizer _randomizer, address _governor);

Parameters

NameTypeDescription
_randomizerIRandomizerRandomizer contract.
_governoraddressGovernor of the contract.

changeGovernor

Changes the governor of the contract.

function changeGovernor(address _governor) external onlyByGovernor;

Parameters

NameTypeDescription
_governoraddressThe new governor.

setCallbackGasLimit

Change the Randomizer callback gas limit.

function setCallbackGasLimit(uint256 _callbackGasLimit) external onlyByGovernor;

Parameters

NameTypeDescription
_callbackGasLimituint256the new limit.

setRandomizer

Change the Randomizer address.

function setRandomizer(address _randomizer) external onlyByGovernor;

Parameters

NameTypeDescription
_randomizeraddressthe new Randomizer address.

randomizerWithdraw

Allows the governor to withdraw randomizer funds.

function randomizerWithdraw(uint256 _amount) external onlyByGovernor;

Parameters

NameTypeDescription
_amountuint256Amount to withdraw in wei.

requestRandomness

Request a random number. The id of the request is tied to the sender.

function requestRandomness(uint256) external override;

randomizerCallback

Callback function called by the randomizer contract when the random value is generated.

function randomizerCallback(uint256 _id, bytes32 _value) external;

receiveRandomness

Return the random number.

function receiveRandomness(uint256) external view override returns (uint256 randomNumber);

Returns

NameTypeDescription
randomNumberuint256The random number or 0 if it is not ready or has not been requested.

Contents

Faucet

Git Source

State Variables

token

IERC20 public token;

withdrewAlready

mapping(address => bool) public withdrewAlready;

Functions

constructor

constructor(IERC20 _token);

balance

function balance() public view returns (uint256);

request

function request() public;

PNK

Git Source

Inherits: ERC20

Functions

constructor

constructor() ERC20("Pinakion", "PNK");

WETH

Git Source

Inherits: ERC20

Functions

constructor

constructor() ERC20("Wrapped ETH", "WETH");

WrappedPinakionV2

Git Source

Inherits: ERC20

Functions

constructor

constructor() ERC20("Staking PNK on xDai", "stPNK");