### Start Frontend
Source: https://github.com/kleros/kleros-v2/blob/dev/web/README.md
Navigate to the web directory and run the start command to launch the frontend development server.
```bash
cd kleros-v2/web
yarn start
```
--------------------------------
### Policy URI Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Example of the 'uri' property, an IPFS path pointing to the policy JSON file. It must start with '/ipfs/'.
```json
"/ipfs/QmRwmJAF8NK1r3fAS8dHofbTKsuhWSd3LruzkjrpNNBprC"
```
--------------------------------
### Install Dependencies
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Run this command to install all necessary project dependencies.
```bash
yarn install
```
--------------------------------
### Start Local Graph Node
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Starts the local Graph node indexer. Requires Docker Desktop to be installed and running. The output indicates successful connection to IPFS, Postgres, and Ethereum.
```bash
$ yarn workspace @kleros/kleros-v2-subgraph start-local-indexer
...
graph-node-graph-node-1 | INFO Successfully connected to IPFS node at: http://ipfs:5001/
graph-node-graph-node-1 | INFO Pool successfully connected to Postgres, pool: main, shard: primary, component: Store
...
graph-node-graph-node-1 | INFO Connected to Ethereum, capabilities: archive, traces, network_version: 31337, provider: mainnet-rpc-0
```
--------------------------------
### Start Local Frontend
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Starts the Kleros V2 frontend development server, pointing to the local subgraph. Ensure kleros-app is built first if necessary.
```bash
$ yarn workspace @kleros/kleros-v2-web start-local
✔ Parse Configuration
✔ Generate outputs
✔ Validating plugins
✔ Resolving contracts
✔ Running plugins
✔ Writing to src/hooks/contracts/generated.ts
Server running at http://localhost:1234
✨ Built in 2.35s
```
--------------------------------
### Start Local Full Stack Deployment
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Starts the complete local development stack for Kleros V2 using a single command with tmux.
```bash
$ yarn local-stack
```
--------------------------------
### Copy Environment File
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Copy the example environment file to `.env` to configure deployment settings.
```bash
cp .env.example .env
```
--------------------------------
### Start Local Hardhat Node
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Starts a local Hardhat network node. Use the `--tags` option to specify which contracts to load.
```bash
yarn hardhat node --tags nothing
```
--------------------------------
### Example Graph Node Docker Run
Source: https://github.com/kleros/kleros-v2/blob/dev/services/graph-node/README.md
An example of running the Graph Node Docker image with specific host, user, password, database, IPFS, and Ethereum network details.
```sh
docker run -it \
-e postgres_host=host.docker.internal:5432
-e postgres_user=graph-node \
-e postgres_pass=oh-hello \
-e postgres_db=graph-node \
-e ipfs=host.docker.internal:5001 \
-e ethereum=mainnet:http://localhost:8545/ \
graphprotocol/graph-node:latest
```
--------------------------------
### Start Local RPC with Contracts Deployed
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Starts the local RPC server with Kleros V2 contracts deployed. The server will be accessible at http://127.0.0.1:8545/. Wait for deployment to complete.
```bash
$ yarn workspace @kleros/kleros-v2-contracts start-local
...
Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/
```
--------------------------------
### Install Kleros App Library
Source: https://github.com/kleros/kleros-v2/blob/dev/kleros-app/README.md
Install the Kleros App library using yarn. This command adds the necessary package to your project dependencies.
```bash
yarn install @kleros/kleros-app
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Installs project dependencies using Yarn and updates Git submodules for Foundry libraries.
```bash
$ yarn install
# Foundry libraries
$ git submodule update --init --recursive -j 4
```
--------------------------------
### Start Graph Node with Docker Compose
Source: https://github.com/kleros/kleros-v2/blob/dev/services/graph-node/README.md
Run this command to start IPFS, Postgres, and Graph Node using Docker Compose. This will create persistent data directories.
```sh
docker-compose up
```
--------------------------------
### Policy Rules Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Example of the 'rules' property, outlining juror guidelines. Use markdown, starting headings from '###', and bullet points for clarity.
```markdown
"- All policies of a court also apply to all of its child subcourts.\n- Jurors should cast their vote with a suitable verification.\n\n### Special Cases\nFor cases involving privacy coins..."
```
--------------------------------
### Policy Purpose Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Example of the 'purpose' property, detailing the court's function and scope. Use markdown for formatting, starting headings from '###'.
```markdown
"The General court exists as the top court in the hierarchy.\n\nAll appeals made in subcourts will make their way to the General Court.\n\n### Example\nA case appealed from the Blockchain court."
```
--------------------------------
### Example Evidence JSON
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/evidence-format.md
A complete example of an evidence submission object, including all properties. This JSON string is emitted in the Evidence event.
```json
{
"name": "Evidence",
"description": "The respondent failed to deliver the agreed-upon services...",
"fileURI": "/ipfs/QmWQV5ZFFhEJiW8Lm7ay2zLxC2XS4wx1b2W7FfdrLMyQQc"
}
```
--------------------------------
### Start Blockscout Docker Compose Stack
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Start the Blockscout Docker Compose stack using the provided hardhat-network.yml configuration. This command runs Blockscout locally, accessible at http://localhost.
```bash
docker-compose -f hardhat-network.yml up -d
```
--------------------------------
### Install Hardhat CLI Auto-completion
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Installs Hardhat CLI auto-completion globally and configures it for the bash shell. Requires restarting the shell or executing 'exec bash' to activate.
```bash
$ npm i -g hardhat-shorthand
$ hardhat-completion install
✔ Which Shell do you use ? · bash
✔ We will install completion to ~/.bashrc, is it ok ? (y/N) · true
$ exec bash
```
--------------------------------
### Setup AtlasProvider for Kleros App
Source: https://github.com/kleros/kleros-v2/blob/dev/kleros-app/README.md
Configure and wrap your application with AtlasProvider. Ensure it's nested within WagmiProvider and QueryClientProvider. Set the Atlas backend URI, signup product, IPFS product, and Wagmi configuration.
```typescript
import { WagmiProvider } from 'wagmi'
import { config } from './config'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { AtlasProvider, SignupProduct, IpfsProduct } from "@kleros/kleros-app";
import { useConfig } from 'wagmi'
const queryClient = new QueryClient()
function App() {
const wagmiConfig = useConfig()
return (
...
)
}
```
--------------------------------
### Simulate Arbitration Activity
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Runs a simulation of arbitration activity on the local Kleros V2 setup.
```bash
$ yarn workspace @kleros/kleros-v2-contracts simulate-local
```
--------------------------------
### Run Test Fixtures with Local Node
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Starts a local Hardhat node with specific tags and runs tests against it.
```bash
yarn hardhat node --tags Arbitration,VeaMock
```
```bash
yarn test --network localhost
```
--------------------------------
### Implement User Authentication with AtlasProvider
Source: https://github.com/kleros/kleros-v2/blob/dev/kleros-app/README.md
Use the useAtlasProvider hook to manage user authentication. This example conditionally renders children based on verification status and provides a button to initiate the authorization process.
```typescript
import React, { useCallback } from "react";
import { useAccount } from "wagmi";
import { useAtlasProvider } from "@kleros/kleros-app";
import { Button } from "@kleros/ui-components-library";
interface IEnsureAuth {
children: React.ReactElement;
className?: string;
}
const EnsureAuth: React.FC = ({ children, className }) => {
const { address } = useAccount();
const { isVerified, isSigningIn, authoriseUser } = useAtlasProvider();
const handleClick = useCallback(() => {
// authorise a user
authoriseUser()
.then((res) => { console.log(res)})
.catch((err) => {
console.log(err);
});
}, [authoriseUser]);
return isVerified ? (
children
) : (
);
};
export default EnsureAuth;
```
--------------------------------
### Specialized Court Policy Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Defines the structure for a Specialized Court policy, including name, purpose, rules, required skills, court ID, and IPFS URI. This example illustrates a 'Solidity Court'.
```json
{
"name": "Solidity Court",
"purpose": "",
"rules": "If the disputed code is of significant size (> 500 code lines), parties in the dispute should point out specific parts of the content which are being disputed. Otherwise, jurors should refuse to arbitrate.",
"requiredSkills": "This court requires a good level of solidity. Jurors who are not solidity intermediate developers are advised to stake into this court only if they also know how to make relatively simple contracts, know the main solidity hacks and can compute the complexity of simple functions.",
"court": 26,
"uri": "/ipfs/QmPRckaaNLj9ycZH6otChTwbkDsBnhkNrXnarF5vD6rXKy"
}
```
--------------------------------
### Policy Name Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Example of the 'name' property for a court policy. This string represents the official designation of the court.
```json
"General Court"
```
--------------------------------
### Example Dispute Template: Residential Lease Dispute
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrable.md
An example of a dispute template for a residential lease case, illustrating how to populate the fields with specific dispute details and answer options.
```json
{
"title": "Ms. Jamie Zachreson v. Mr. Craig Veale: Appeal of Prior Decision",
"description": "Appeal of a residential lease dispute regarding lease violation and rent refund...",
"question": "Did Mr. Craig Veale violate the terms of the lease agreement in a way that justified Ms. Jamie Zachreson terminating the tenancy and withholding the rent and deposit?",
"category": "Residential lease",
"answers": [
{
"title": "Yes",
"id": "0x1",
"description": "In favor of Ms. Jamie Zachreson: The lease included a valid and enforceable clause..."
},
{
"title": "No",
"id": "0x2",
"description": "In favor of Mr. Craig Veale: The lease did not include the disputed clause..."
},
{
"title": "Partially",
"id": "0x3",
"description": "Split Responsibility: Return partial payment..."
},
{
"title": "Not enough evidence",
"id": "0x4",
"description": "Insufficient evidence to determine..."
},
{
"title": "Refuse to arbitrate",
"id": "0x5",
"description": "Case ineligible for arbitration..."
}
],
"version": "1.0",
"policyURI": "/ipfs/QmcDrvCaXtae4o6KgXYhi4yLKm5JYQSRQdZ9itbnASbsb9",
"arbitratorAddress": "0x991d2df165670b9cac3B022f4B68D65b664222ea",
"arbitratorChainID": "42161"
}
```
--------------------------------
### New Appeal Request Functions in DisputeKitClassic
Source: https://github.com/kleros/kleros-v2/blob/dev/kleros-sdk/config/v2-disputetemplate/README.md
DisputeKit implementations now handle appeal requests. This example shows functions from DisputeKitClassic for funding appeals and retrieving funded choices.
```solidity
// DisputeKitClassic.sol
function fundAppeal(uint256 _coreDisputeID, uint256 _choice) payable;
function getFundedChoices(uint256 _coreDisputeID) view returns (uint256[] memory fundedChoices);
```
--------------------------------
### Example Court Configuration JSON
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/courts.md
This JSON object represents a typical configuration for a general court, including parameters like minimum stake, juror fees, and timing periods. It is used for initializing and defining court properties.
```json
{
"name": "General Court",
"id": 1,
"parent": 1,
"hiddenVotes": true,
"minStake": "2300000000000000000000",
"feeForJuror": "5000000000000000",
"alpha": "10000",
"jurorsForCourtJump": "511",
"timesPerPeriod": [280800, 583200, 583200, 388800]
}
```
--------------------------------
### Populate Local Contracts
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Populates local Kleros V2 contracts by pulling devnet courts. This command should be run in a new terminal after starting the local RPC.
```bash
$ yarn workspace @kleros/kleros-v2-contracts populate:local
```
--------------------------------
### General Court Policy Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Defines the structure for a General Court policy, including its name, purpose, rules, court ID, and IPFS URI.
```json
{
"name": "General Court",
"purpose": "The General court exists as the top court in the hierarchy.\n\nAll appeals made in subcourts will make their way to the General Court.",
"rules": "- All policies of a court also apply to all of its child subcourts.\n- Jurors should cast their vote with a suitable verification.",
"court": 1,
"uri": "/ipfs/QmRwmJAF8NK1r3fAS8dHofbTKsuhWSd3LruzkjrpNNBprC"
}
```
--------------------------------
### Policy Required Skills Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Example of the optional 'requiredSkills' property, specifying juror qualifications. Markdown is used for formatting, with headings starting from '###'.
```markdown
"This court requires a good level of solidity. Jurors who are not solidity intermediate developers are advised to stake into this court only if they also know how to make relatively simple contracts.\n\n### Technical Skills\n- Smart contract development\n- Security auditing"
```
--------------------------------
### Compile Contracts
Source: https://github.com/kleros/kleros-v2/blob/dev/web/README.md
Navigate to the contracts directory and run the build command to compile the smart contracts.
```bash
cd kleros-v2/contracts
yarn build
```
--------------------------------
### Policy Court Identifier Example
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/policy-format.md
Example of the 'court' property, which is a unique positive integer identifier for the court.
```json
1
```
--------------------------------
### Deploy Home Gateway to Ethereum Sepolia
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys the Home Gateway contract to Ethereum Sepolia testnet.
```bash
yarn deploy --network arbitrumSepolia --tags HomeGatewayToEthereum
```
--------------------------------
### Clone Blockscout Repository
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Clone the Blockscout repository to your local machine. This is the first step to setting up the local explorer.
```bash
git clone https://github.com/blockscout/blockscout.git
```
--------------------------------
### Scenario 2: Stake Decrease Then Increase
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/sortition-module.md
Demonstrates decreasing a stake and then increasing it, showing how token transfers are handled.
```Solidity
// First delayed stake (decrease from 500 to 200)
delayedStakes[++delayedStakeWriteIndex] = DelayedStake({
account: _account,
courtID: _courtID,
stake: 200,
alreadyTransferred: false // No PNK transferred yet
});
latestDelayedStakeIndex[_account][_courtID] = delayedStakeWriteIndex;
// Second delayed stake (increase to 800)
// 1. Previous delayed stake is found and deleted
// 2. Since it was a decrease with no tokens transferred:
// No token operations needed to reverse it
// 3. New delayed stake stored
delayedStakes[++delayedStakeWriteIndex] = DelayedStake({
account: _account,
courtID: _courtID,
stake: 800,
alreadyTransferred: true // PNK transferred immediately
});
```
--------------------------------
### Lint Files
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Run this command to lint all project files.
```bash
yarn lint
```
--------------------------------
### Scenario 1: Stake Increase Then Decrease
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/sortition-module.md
Illustrates the process of increasing a stake and then decreasing it, including token transfer reversals.
```Solidity
// First delayed stake (increase from 100 to 500)
delayedStakes[++delayedStakeWriteIndex] = DelayedStake({
account: _account,
courtID: _courtID,
stake: 500,
alreadyTransferred: true // PNK transferred immediately
});
latestDelayedStakeIndex[_account][_courtID] = delayedStakeWriteIndex;
// Second delayed stake (decrease to 200)
// 1. Previous delayed stake is found and deleted
// 2. Since it was an increase with tokens transferred:
uint256 amountToWithdraw = 500 - sortitionStake; // 500 - 100 = 400
juror.stakedPnk -= amountToWithdraw; // Reverse the previous increase
// 3. New delayed stake stored
delayedStakes[++delayedStakeWriteIndex] = DelayedStake({
account: _account,
courtID: _courtID,
stake: 200,
alreadyTransferred: false // No immediate PNK transfer
});
```
--------------------------------
### Deploy Foreign Gateway to Ethereum Sepolia
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys the Foreign Gateway contract to Ethereum Sepolia testnet.
```bash
yarn deploy --network sepolia --tags ForeignGatewayOnEthereum
```
--------------------------------
### Populating Reality Template with TypeScript
Source: https://github.com/kleros/kleros-v2/blob/dev/kleros-sdk/config/v2-disputetemplate/reality/kip-99.md
Illustrates how to populate the Reality template using a TypeScript function, requiring specific libraries.
```typescript
rc_question = require("@reality.eth/reality-eth-lib/formatters/question.js");
rc_question.populatedJSONForTemplate(LogNewTemplate.question_text, LogNewQuestion.question);
```
--------------------------------
### Get Current Ruling for a Dispute
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrator.md
Retrieves the current ruling, tie status, and override status for a given dispute ID. Useful for checking the latest state of a dispute.
```Solidity
function currentRuling(
uint256 _disputeID
) external view returns (uint256 ruling, bool tied, bool overridden)
```
--------------------------------
### Generate Deployment Artifacts for Contracts
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Generate deployment artifacts for existing contracts by providing the network and contract address. The output is redirected to a JSON file in the deployments directory.
```bash
scripts/generateDeploymentArtifact.sh
```
```bash
scripts/generateDeploymentArtifact.sh gnosischain 0xf8d1677c8a0c961938bf2f9adc3f3cfda759a9d9 > deployments/gnosischain/WETH.json
```
--------------------------------
### Get Docker Host IP for Linux
Source: https://github.com/kleros/kleros-v2/blob/dev/services/graph-node/README.md
On Linux with Docker v20.10+, use this command to find the Docker host's IP address for use in docker-compose.yml when host.docker.internal is not supported.
```sh
CONTAINER_ID=$(docker container ls | grep graph-node | cut -d' ' -f1)
docker exec $CONTAINER_ID /bin/bash -c 'ip route | awk
'/^default via /{print $3}''
```
--------------------------------
### Create Dispute using Template URI
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrable.md
Use this function to create a dispute by referencing a template via a URI. Arbitration fees must be sent, and a minimum of two ruling options is required.
```Solidity
function createDisputeForTemplateUri(
bytes calldata _arbitratorExtraData,
string calldata _disputeTemplateUri,
uint256 _numberOfRulingOptions
) external payable returns (uint256 disputeID)
```
--------------------------------
### Deploy Foreign Arbitrable to Ethereum Sepolia
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys the Foreign Arbitrable contract to Ethereum Sepolia testnet.
```bash
yarn deploy --network sepolia --tags ForeignArbitrable
```
--------------------------------
### Deploy Subgraph Version
Source: https://github.com/kleros/kleros-v2/blob/dev/subgraph/README.md
Bump the package version and deploy the new subgraph version to the specified network. Remember to commit the version change.
```bash
# bump the package version number
yarn version patch
# deploy the new version
yarn deploy:arbitrum-sepolia-devnet
# commit the new version number
git commit -m "chore: subgraph deployment"
```
--------------------------------
### Live Contract Deployment and Verification
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/DEVNET_REDEPLOY.md
Commands for deploying, verifying contracts on Etherscan, and updating documentation for the arbitrumSepoliaDevnet network.
```shell
yarn clean
yarn deploy --network arbitrumSepoliaDevnet --tags Resolver
yarn deploy --network arbitrumSepoliaDevnet --tags ArbitrationRuler
# Contracts verification, marking proxies
yarn etherscan-verify --network arbitrumSepoliaDevnet
yarn etherscan-verify-proxies
# Docs update
./scripts/populateReadme.sh
```
--------------------------------
### Get Appeal Cost
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrator.md
Retrieves the cost required to appeal a specific dispute. The cost varies based on whether the appeal stays in the current court, moves to a parent court, or is for the General Court. Appeal fees must be paid in ETH.
```Solidity
function appealCost(uint256 _disputeID) public view returns (uint256 cost)
```
--------------------------------
### Run Data Mappings Tests
Source: https://github.com/kleros/kleros-v2/blob/dev/kleros-sdk/README.md
Execute the data mappings tests for the Kleros SDK. This command should be run from the root folder of the project.
```bash
yarn test
```
--------------------------------
### Import V1 Data to Kleros V2 Public Testnet
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Import the exported V1 policy and court data into the Kleros V2 Public Testnet. Ensure the `--from v2_testnet` flag is used and specify the target network.
```bash
yarn hardhat populate:courts --from v2_testnet --max-number-of-courts 3 --network arbitrumSepolia
yarn hardhat populate:policy-registry --from v2_testnet --network arbitrumSepolia
```
--------------------------------
### Configure Courts and Policies
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/DEVNET_REDEPLOY.md
Commands to populate the courts structure and policy registry for the arbitrumSepoliaDevnet network using Hardhat.
```shell
yarn hardhat populate:courts --from v2_devnet --network arbitrumSepoliaDevnet
yarn hardhat populate:policy-registry --from v2_devnet --network arbitrumSepoliaDevnet
```
--------------------------------
### Deploy to Local Network
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys contracts to a local network. Specify the network and tags for deployment.
```bash
yarn deploy --network localhost --tags
```
--------------------------------
### Initialize Dark Mode
Source: https://github.com/kleros/kleros-v2/blob/dev/web/src/index.html
This script must run synchronously in the of the HTML document before the first paint. It checks the user's theme preference stored in localStorage and applies a dark background color if the theme is not explicitly set to 'light', preventing a white flash.
```javascript
Kleros · Court // Prevent white flash on page load for dark mode users. // Must run synchronously in before first paint. // localStorage stores the theme as JSON (e.g. "dark" or "light"). if (JSON.parse(localStorage.getItem("theme")) !== "light") { document.documentElement.style.backgroundColor = "#1B003F"; }
```
--------------------------------
### Deploy Resolver to Arbitrum Sepolia
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys the Resolver contract to Arbitrum Sepolia testnet.
```bash
yarn deploy --network arbitrumSepolia --tags Resolver
```
--------------------------------
### Sortition Module Phase Transitions
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/sortition-module.md
This diagram illustrates the sequence of calls for managing phase transitions within the Sortition Module, including staking, generating randomness, and drawing jurors. It shows interactions between the Bot, SortitionModule, KlerosCore, and RNG.
```mermaid
sequenceDiagram
participant Bot
participant SortitionModule
participant KlerosCore
participant RNG
Note over Bot,RNG: Staking → Generating Phase
Bot->>SortitionModule: passPhase()
activate SortitionModule
SortitionModule->>SortitionModule: Check phase == Staking
SortitionModule->>SortitionModule: Check minStakingTime elapsed
SortitionModule->>SortitionModule: Check disputesWithoutJurors > 0
SortitionModule->>RNG: requestRandomness(block.number + rngLookahead)
SortitionModule->>SortitionModule: Set phase = Generating
SortitionModule->>SortitionModule: Store randomNumberRequestBlock
SortitionModule-->>Bot: Emit NewPhase(Generating)
deactivate SortitionModule
Note over Bot,RNG: Generating → Drawing Phase
Bot->>SortitionModule: passPhase()
activate SortitionModule
SortitionModule->>SortitionModule: Check phase == Generating
SortitionModule->>RNG: receiveRandomness(randomNumberRequestBlock + rngLookahead)
RNG-->>SortitionModule: Return randomNumber
SortitionModule->>SortitionModule: Store randomNumber
SortitionModule->>SortitionModule: Set phase = Drawing
SortitionModule-->>Bot: Emit NewPhase(Drawing)
deactivate SortitionModule
Note over Bot,RNG: Drawing, see diagram below
Note over Bot,RNG: Drawing → Staking Phase
Bot->>SortitionModule: passPhase()
activate SortitionModule
SortitionModule->>SortitionModule: Check phase == Drawing
alt All disputes have jurors
SortitionModule->>SortitionModule: Check disputesWithoutJurors == 0
else Max time elapsed
SortitionModule->>SortitionModule: Check maxDrawingTime elapsed
end
SortitionModule->>SortitionModule: Set phase = Staking
SortitionModule-->>Bot: Emit NewPhase(Staking)
deactivate SortitionModule
Note over Bot,RNG: Stake Management
KlerosCore->>SortitionModule: setStake()
activate SortitionModule
SortitionModule->>SortitionModule: Check phase
alt Staking Phase
SortitionModule->>SortitionModule: Update tree immediately
else Other Phases
SortitionModule->>SortitionModule: Store delayed stake
end
SortitionModule->>KlerosCore: setStakeBySortitionModule()
deactivate SortitionModule
Note over Bot,RNG: Delayed Stakes Execution
Bot->>SortitionModule: executeDelayedStakes()
activate SortitionModule
SortitionModule->>SortitionModule: Check phase == Staking
loop For each delayed stake
SortitionModule->>KlerosCore: setStakeBySortitionModule()
KlerosCore->>KlerosCore: Update juror stakes
end
deactivate SortitionModule
```
--------------------------------
### Dry Run Contract Deployment
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/DEVNET_REDEPLOY.md
Commands for setting up a local fork node using Anvil and deploying contracts for arbitrumSepoliaDevnet. Remember to delete artifacts after each dry run.
```shell
anvil --fork-url https://sepolia-rollup.arbitrum.io/rpc
```
```shell
export ARBITRUM_SEPOLIA_RPC=http://127.0.0.1:8545
yarn clean
yarn deploy --network arbitrumSepoliaDevnet --tags Resolver
yarn deploy --network arbitrumSepoliaDevnet --tags ArbitrationRuler
unset ARBITRUM_SEPOLIA_RPC
```
--------------------------------
### Deploy Home Gateway to Gnosis Chain
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys the Home Gateway contract to Gnosis Chain testnet (Chiado).
```bash
yarn deploy --network arbitrumSepolia --tags HomeGatewayToGnosis
```
--------------------------------
### Deploy to Arbitrum Sepolia
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys arbitration-related contracts to Arbitrum Sepolia testnet.
```bash
yarn deploy --network arbitrumSepolia --tags Arbitration
```
--------------------------------
### Run Graph Node Docker Image
Source: https://github.com/kleros/kleros-v2/blob/dev/services/graph-node/README.md
Use this command to run the Graph Node Docker image, configuring essential environment variables for PostgreSQL and Ethereum connections.
```sh
docker run -it \
-e postgres_host=[:] \
-e postgres_user= \
-e postgres_pass= \
-e postgres_db= \
-e ipfs=: \
-e ethereum=: \
graphprotocol/graph-node:latest
```
--------------------------------
### Create Dispute using Template
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrable.md
Use this function to create a dispute based on a predefined template. Ensure arbitration fees are included and at least two ruling options are specified.
```Solidity
function createDisputeForTemplate(
bytes calldata _arbitratorExtraData,
string calldata _disputeTemplate,
string memory _disputeTemplateDataMappings,
uint256 _numberOfRulingOptions
) external payable returns (uint256 disputeID)
```
--------------------------------
### Dispute Creation Flow Sequence Diagram
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrable.md
Illustrates the sequence of interactions between User, DisputeResolver, Arbitrator, and TemplateRegistry during dispute creation.
```mermaid
sequenceDiagram
participant User
participant DisputeResolver
participant Arbitrator
participant TemplateRegistry
User->>DisputeResolver: createDisputeForTemplate()
activate DisputeResolver
Note over DisputeResolver: Validate parameters
DisputeResolver->>Arbitrator: createDispute()
Arbitrator-->>DisputeResolver: Return disputeID
DisputeResolver->>TemplateRegistry: setDisputeTemplate()
TemplateRegistry-->>DisputeResolver: Return templateId
DisputeResolver-->>User: Return arbitratorDisputeID
deactivate DisputeResolver
DisputeResolver->>DisputeResolver: Emit DisputeRequest
```
--------------------------------
### Authenticate Subgraph Deployment
Source: https://github.com/kleros/kleros-v2/blob/dev/subgraph/README.md
Authenticate your local environment with The Graph Studio using an API key. This is required before deploying the subgraph.
```bash
$ yarn run graph auth --studio
```
--------------------------------
### Generate Typed Contract Bindings
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Regenerates typed wagmi/viem contract bindings for the frontend. This is necessary whenever contracts are redeployed or their ABIs change.
```bash
yarn workspace @kleros/kleros-v2-contracts viem:generate-hardhat
```
--------------------------------
### Update Subgraph Artifacts and Build
Source: https://github.com/kleros/kleros-v2/blob/dev/subgraph/README.md
Update subgraph.yml with contract deployment artifacts, generate code, and build the subgraph. This is a prerequisite for deployment.
```bash
# update subgraph.yml using the contract deployment artifacts
$ yarn update:arbitrum-sepolia-devnet
$ yarn codegen
$ yarn build
```
--------------------------------
### Push Contracts to Tenderly for Verification
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Push your contracts to a Tenderly project for verification. Ensure your Tenderly project and username are set in the `.env` file using the `$TENDERLY_PROJECT` and `$TENDERLY_USERNAME` environment variables.
```bash
yarn tenderly-verify --network sepolia
```
```bash
yarn tenderly-verify --network arbitrumSepolia
```
--------------------------------
### Verify Contracts with Sourcify
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Verifies deployed contract source code using Sourcify for various networks. Use `--network` to specify the target network.
```bash
yarn sourcify --network
```
--------------------------------
### createDisputeForTemplateUri
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrable.md
Creates a dispute using a URI pointing to a template. Requires arbitration fees and at least two ruling options. Emits a DisputeRequest event.
```APIDOC
## createDisputeForTemplateUri
### Description
Creates a dispute using a URI that points to a template. Requires arbitration fees to be sent with the call and at least two ruling options must be specified. Emits a `DisputeRequest` event with template information.
### Method
`createDisputeForTemplateUri(
bytes calldata _arbitratorExtraData,
string calldata _disputeTemplateUri,
uint256 _numberOfRulingOptions
)`
### Parameters
- **_arbitratorExtraData** (bytes) - Description not specified in source.
- **_disputeTemplateUri** (string) - The URI pointing to the dispute template.
- **_numberOfRulingOptions** (uint256) - The number of ruling options available (must be at least 2).
### Payable
This function is payable, meaning it accepts ether.
```
--------------------------------
### Update Contract SDK Artifacts
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/DEVNET_REDEPLOY.md
Commands to refresh Viem and Hardhat artifacts for the development network.
```shell
# Viem artifacts
yarn viem:generate-devnet
# Hardhat artifacts
yarn export:devnet
```
--------------------------------
### Sortition Module Phase Transition Flow
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/sortition-module.md
Illustrates the sequence of events and conditions for transitioning between the Staking, Generating, and Drawing phases in the Sortition Module. Each transition emits a NewPhase event.
```mermaid
sequenceDiagram
participant Staking
participant Generating
participant Drawing
Note over Staking: Initial Phase
Note over Staking: Staking → Generating
Staking->>Staking: Check block.timestamp - lastPhaseChange >= minStakingTime
Staking->>Staking: Check disputesWithoutJurors > 0
Staking-->Generating: passPhase()
Note over Generating: Request RNG at block.number + rngLookahead
Note over Generating: Generating → Drawing
Generating->>Generating: Check randomNumber from RNG
Generating->>Generating: Verify randomNumber != 0
Generating-->Drawing: passPhase()
Note over Drawing: Store randomNumber for drawing
Note over Drawing: Drawing → Staking
alt No disputes need jurors
Drawing->>Drawing: Check disputesWithoutJurors == 0
else Max time reached
Drawing->>Drawing: Check block.timestamp - lastPhaseChange >= maxDrawingTime
end
Drawing-->Staking: passPhase()
Note over Staking: Update lastPhaseChange = block.timestamp
Note over Staking,Drawing: Each transition emits NewPhase(phase)
```
--------------------------------
### Classic DisputeCreation Event
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/dispute-kit-classic.md
Emitted when a new dispute is created. Tracks the dispute ID, number of choices, and extra configuration data.
```solidity
event DisputeCreation(uint256 indexed _coreDisputeID, uint256 _numberOfChoices, bytes _extraData);
```
--------------------------------
### Rebuild and Deploy Local Subgraph
Source: https://github.com/kleros/kleros-v2/blob/dev/README.md
Rebuilds and deploys the local subgraph. This action modifies subgraph.yaml and creates a backup. It provides the IPFS hash and the GraphQL endpoint for the deployed subgraph.
```bash
$ yarn workspace @kleros/kleros-v2-subgraph rebuild-deploy:local
...
✔ Upload subgraph to IPFS
Build completed: QmZVaZQ9qcXPia9YnFEKk7D1dEDHbfyDiJi1sqJ6E1NydB
Deployed to http://localhost:8000/subgraphs/name/kleros/kleros-v2-core-local
Subgraph endpoints:
Queries (HTTP): http://localhost:8000/subgraphs/name/kleros/kleros-v2-core-local
```
--------------------------------
### createDisputeForTemplate
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/specifications/arbitrable.md
Creates a dispute using a predefined template. Requires arbitration fees and at least two ruling options. Emits a DisputeRequest event.
```APIDOC
## createDisputeForTemplate
### Description
Creates a dispute using a predefined template. Requires arbitration fees to be sent with the call and at least two ruling options must be specified. Emits a `DisputeRequest` event with template information.
### Method
`createDisputeForTemplate(
bytes calldata _arbitratorExtraData,
string calldata _disputeTemplate,
string memory _disputeTemplateDataMappings,
uint256 _numberOfRulingOptions
)`
### Parameters
- **_arbitratorExtraData** (bytes) - Description not specified in source.
- **_disputeTemplate** (string) - The dispute template to use.
- **_disputeTemplateDataMappings** (string) - Mappings for the dispute template data.
- **_numberOfRulingOptions** (uint256) - The number of ruling options available (must be at least 2).
### Payable
This function is payable, meaning it accepts ether.
```
--------------------------------
### Default ESLint Configuration Usage
Source: https://github.com/kleros/kleros-v2/blob/dev/eslint-config/README.md
Use this snippet in your `eslint.config.mjs` file to apply the default ESLint configuration for workspaces that do not require custom rules.
```javascript
export { default } from "@kleros/kleros-v2-eslint-config/flat.config.mjs";
```
--------------------------------
### Deploy Foreign Gateway to Gnosis Chain
Source: https://github.com/kleros/kleros-v2/blob/dev/contracts/README.md
Deploys the Foreign Gateway contract to Gnosis Chain testnet (Chiado).
```bash
yarn deploy --network chiado --tags ForeignGatewayOnGnosis
```