Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: indications for the template and data mappings #95

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

kemuru
Copy link
Contributor

@kemuru kemuru commented Jan 13, 2025

PR-Codex overview

This PR focuses on updating the Escrow contract and related scripts to enhance dispute handling, including changes to dispute templates and mappings, and the introduction of a new EscrowUniversal contract.

Detailed summary

  • Removed old disputeTemplate and mapping constants.
  • Introduced extraData using ethers.AbiCoder.
  • Updated deploy function to use EscrowUniversal.
  • Created new dispute template and mapping functions.
  • Updated setDisputeTemplate task to use new parameters and handle errors.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • Configuration Updates

    • Removed static dispute template and mapping constants; replaced with dynamic configuration.
    • Introduced new parameters for network-specific settings in the dispute template.
  • Bug Fixes

    • Enhanced error handling for missing parameters in dispute template generation.
  • Documentation

    • Added comments to clarify new dynamic dispute template generation process.
  • Refactor

    • Updated the Escrow class to EscrowUniversal.
    • Revised the method for invoking dispute template changes to accommodate new dynamic structure.

Copy link
Contributor

coderabbitai bot commented Jan 13, 2025

Walkthrough

The pull request modifies the escrow dispute template and mapping configurations in two TypeScript files. In 00-escrow.ts, constants related to dispute templates and mappings are removed and replaced with dynamic configurations. The extraData constant is redefined to encode parameters using ethers.AbiCoder. In setDisputeTemplate.ts, the static disputeTemplate is replaced with a dynamic parameters object, and a new function generates the dispute template based on network parameters. The overall structure remains, but the approach to setting parameters is significantly updated.

Changes

File Change Summary
contracts/deploy/00-escrow.ts - Removed constants disputeTemplate and mapping
- Redefined extraData to use ethers.AbiCoder for dynamic encoding
- Added logic for setting token value caps using changeAmountCap method
contracts/scripts/setDisputeTemplate.ts - Removed original disputeTemplate and replaced it with a new parameters object
- Introduced disputeTemplateFn for dynamic template generation
- Added mappingFn for creating mapping configuration
- Updated changeDisputeTemplate invocation to use new template structure
- Enhanced error handling for missing parameters

Poem

🐰 In the meadow where templates bloom,
Dynamic changes chase away the gloom,
With parameters set for every chain,
A rabbit hops through code, no strain,
Encoding values, bright and clear,
A joyful leap, the future's near! 🌟

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Jan 13, 2025

Deploy Preview for kleros-escrow-v2 ready!

Name Link
🔨 Latest commit 08a5201
🔍 Latest deploy log https://app.netlify.com/sites/kleros-escrow-v2/deploys/6787ba682bebc800087d7ada
😎 Deploy Preview https://deploy-preview-95--kleros-escrow-v2.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
contracts/deploy/00-escrow.ts (2)

20-20: Ensure consistent configuration across files

The arbitrator configuration and policy URI are duplicated in both files. Consider extracting these values to a shared configuration file to avoid inconsistencies.

Example structure:

// config/arbitrator.ts
export const ARBITRATOR_CONFIG = {
  chainId: "42161",
  address: "0x991d2df165670b9cac3B022f4B68D65b664222ea",
  policyUri: "/ipfs/XxxxxXXX/escrow-general-policy.pdf"
};

Also applies to: 26-27


Line range hint 5-42: Consider validating template variables

The template uses various placeholder variables (e.g., {{buyer}}, {{seller}}, {{amount}}), but there's no validation to ensure all required variables are provided.

Consider adding a type definition and validation for the template variables:

interface DisputeTemplateVariables {
  buyer: string;
  seller: string;
  amount: string;
  token: string;
  deadline: string;
  escrowTitle: string;
  deliverableText: string;
  extraDescriptionUri: string;
  transactionUri: string;
  externalDisputeID: string;
}

function validateTemplateVariables(variables: DisputeTemplateVariables): void {
  // Add validation logic
}

Also applies to: 43-63

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c5907b and 2ce2242.

📒 Files selected for processing (2)
  • contracts/deploy/00-escrow.ts (3 hunks)
  • contracts/scripts/setDisputeTemplate.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules - kleros-escrow-v2
  • GitHub Check: Header rules - kleros-escrow-v2
  • GitHub Check: Pages changed - kleros-escrow-v2
🔇 Additional comments (5)
contracts/scripts/setDisputeTemplate.ts (4)

19-19: TODO: Policy URI needs to be updated

The IPFS hash is currently a placeholder (XxxxxXXX). This needs to be updated with the actual IPFS hash of the general escrow policy document.

Please confirm if the policy document has been created and provide the correct IPFS hash.


36-36: TODO: Specification field needs clarification

The comment indicates uncertainty about the specification field. This should be clarified before deployment.

Please confirm if this field should reference a specific KIP (Kleros Improvement Proposal) or if it should be removed.


50-51: Empty mapping JSON might need attention

The mappingJson is set to an empty object ("{}"), but the deployment file contains a detailed mapping configuration.

Please confirm if this empty mapping is intentional or if it should match the mapping configuration in the deployment file.


24-26: Verify the arbitrator configuration

The arbitrator configuration has been updated with:

  • Chain ID: 42161 (Arbitrum One)
  • Arbitrator address: 0x991d2df165670b9cac3B022f4B68D65b664222ea

Please confirm these are the correct production values for Arbitrum One mainnet. Run this script to verify:

✅ Verification successful

✓ Arbitrator configuration verified

The arbitrator configuration is correctly set for Arbitrum One mainnet:

  • Contract exists and is deployed at the specified address
  • Address is consistently used across deployment configurations
  • Frontend URL points to the production environment
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the arbitrator address exists on Arbitrum One
# and has the expected interface

# Check if the address has contract code
curl -s -X POST \
  -H "Content-Type: application/json" \
  --data "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getCode\",\"params\":[\"0x991d2df165670b9cac3B022f4B68D65b664222ea\", \"latest\"],\"id\":1}" \
  "https://arb1.arbitrum.io/rpc"

Length of output: 614


Script:

#!/bin/bash
# Search for references to this arbitrator address in the codebase
rg -i "0x991d2df165670b9cac3B022f4B68D65b664222ea"

# Look for IArbitrator interface definition to understand expected methods
ast-grep --pattern 'interface IArbitrator {
  $$$
}'

Length of output: 315

contracts/deploy/00-escrow.ts (1)

49-49: TODO: Subgraph deployment needed

The comment indicates that a subgraph needs to be created in Arbitrum One. This is a blocking issue for deployment.

Please confirm if the subgraph has been created and update the ID accordingly.

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 13, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
contracts/scripts/setDisputeTemplate.ts (1)

11-13: Consider enhancing error handling.

While the transaction receipt logging is good, consider adding more detailed error handling and logging of the actual template values being set.

   const tx = await escrow.changeDisputeTemplate(disputeTemplate, mapping);
+  console.log('Setting dispute template:', { disputeTemplate, mapping });
   await tx.wait().then((receipt) => {
     console.log(`Transaction receipt: ${JSON.stringify(receipt)}`);
-  });
+  }).catch((error) => {
+    console.error('Failed to set dispute template:', error);
+    throw error;
+  });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ce2242 and 2b5c9d2.

📒 Files selected for processing (2)
  • contracts/deploy/00-escrow.ts (4 hunks)
  • contracts/scripts/setDisputeTemplate.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • contracts/deploy/00-escrow.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Redirect rules - kleros-escrow-v2
  • GitHub Check: Redirect rules - kleros-escrow-v2
  • GitHub Check: Header rules - kleros-escrow-v2
  • GitHub Check: Header rules - kleros-escrow-v2
  • GitHub Check: Pages changed - kleros-escrow-v2
  • GitHub Check: Pages changed - kleros-escrow-v2
🔇 Additional comments (2)
contracts/scripts/setDisputeTemplate.ts (2)

10-10: Verify contract function parameter types.

The change from JSON.stringify to direct object passing needs verification against the contract's ABI to ensure type compatibility.


4-4: Verify imported dispute template matches requirements.

The centralization of template configuration is good for maintainability. However, let's verify that the imported template contains the required updates mentioned in the PR objectives.

✅ Verification successful

Import changes are correctly implemented and configured

The imported dispute template and mapping from contracts/deploy/00-escrow.ts contain:

  • Correct Arbitrum chain ID (42161)
  • Valid arbitrator address
  • Proper metadata fields structure
  • Complete GraphQL mapping configuration
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the imported disputeTemplate and mapping contain the required updates

# Check for the updated arbitrator chain ID and address
rg -A 10 "arbitratorChainID.*42161" "../deploy/00-escrow.ts"
rg -A 10 "arbitratorAddress" "../deploy/00-escrow.ts"

# Check for the template string format and metadata fields
rg -A 20 "disputeTemplate.*=.*\`" "../deploy/00-escrow.ts"
rg -A 10 "metadata.*amount.*token" "../deploy/00-escrow.ts"

Length of output: 482


Script:

#!/bin/bash
# First, let's find the escrow deployment file
fd -t f "00-escrow.ts"

# Let's also check for any files containing disputeTemplate
rg -l "disputeTemplate"

# And check for files containing arbitrator configuration
rg -l "arbitratorChainID|arbitratorAddress"

Length of output: 287


Script:

#!/bin/bash
# Check the content of the escrow deployment file
echo "=== Dispute Template and Mapping ==="
rg -A 20 "export const disputeTemplate|export const mapping" contracts/deploy/00-escrow.ts

echo -e "\n=== Arbitrator Configuration ==="
rg -A 5 "arbitratorChainID|arbitratorAddress" contracts/deploy/00-escrow.ts

echo -e "\n=== Full File Context ==="
cat contracts/deploy/00-escrow.ts

Length of output: 6128

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 15, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 15, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
contracts/deploy/00-escrow.ts (2)

19-20: Add comments explaining the encoded parameters.

The encoded parameters [1, 3] represent important configuration values. Consider adding comments to explain their significance:

  // General court, 3 jurors
+ // Parameters: [courtId: 1 (General Court), numberOfJurors: 3]
  const extraData = ethers.AbiCoder.defaultAbiCoder().encode(["uint96", "uint96"], [1, 3]);

36-48: Consider environment-specific configurations for value caps.

The hardcoded value caps might need to vary across different environments. Consider:

  1. Moving these values to a configuration file
  2. Adding comments explaining the USD equivalence
+ // Value caps in token units, approximately USD 1000 equivalent
+ const VALUE_CAPS = {
+   [ethers.ZeroAddress]: {
+     amount: "0.3",  // Native token (e.g., ETH)
+     decimals: 18
+   },
+   [WETH.address]: {
+     amount: "0.3",  // WETH
+     decimals: 18
+   },
+   [DAI.address]: {
+     amount: "1000", // DAI
+     decimals: 18
+   }
+ };

  for (const [token, cap] of Object.entries(caps)) {
    console.log("Setting cap for", token, cap);
    await escrow.changeAmountCap(token, cap);
  }
contracts/scripts/setDisputeTemplate.ts (2)

81-90: Enhance error message specificity.

The current error message doesn't indicate which parameter is missing.

-  if (!chainId || !klerosCore || !subgraphEndpoint) {
-    throw new Error("Missing parameters");
+  const missingParams = [
+    ['chainId', chainId],
+    ['klerosCore', klerosCore],
+    ['subgraphEndpoint', subgraphEndpoint]
+  ].filter(([_, value]) => !value).map(([name]) => name);
+
+  if (missingParams.length > 0) {
+    throw new Error(`Missing required parameters: ${missingParams.join(', ')}`);
   }

Line range hint 92-102: Add transaction status monitoring.

Consider adding more detailed transaction status monitoring and error handling.

   const tx = await escrow.changeDisputeTemplate(disputeTemplate, mapping);
+  console.log(`Transaction submitted: ${tx.hash}`);
   await tx.wait().then((receipt) => {
+    if (receipt.status === 0) {
+      throw new Error(`Transaction failed: ${tx.hash}`);
+    }
     console.log(`Transaction receipt: ${JSON.stringify(receipt)}`);
   });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1683ac and 08a5201.

📒 Files selected for processing (2)
  • contracts/deploy/00-escrow.ts (2 hunks)
  • contracts/scripts/setDisputeTemplate.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Redirect rules - kleros-escrow-v2
  • GitHub Check: Redirect rules - kleros-escrow-v2
  • GitHub Check: Header rules - kleros-escrow-v2
  • GitHub Check: Header rules - kleros-escrow-v2
  • GitHub Check: Pages changed - kleros-escrow-v2
  • GitHub Check: Pages changed - kleros-escrow-v2
🔇 Additional comments (3)
contracts/deploy/00-escrow.ts (1)

27-28: LGTM! Good separation of concerns.

Moving the template configuration to a separate step improves maintainability and follows the single responsibility principle.

contracts/scripts/setDisputeTemplate.ts (2)

61-78: LGTM! Well-structured data mapping.

The mapping function effectively combines GraphQL and IPFS data sources with clear data flow and field population.


5-19: Address TODO placeholders before deployment.

The configuration contains TODO placeholders for subgraph endpoints in arbitrumSepoliaTestnet and arbitrum networks.

Let's verify the existing endpoint:

✅ Verification successful

Template pattern for Graph API endpoints is correct, configure before deployment

The {{{graphApiKey}}} placeholder pattern is consistently used across the codebase for Graph API authentication. The TODOs for arbitrumSepoliaTestnet and arbitrum networks should follow the same pattern:

  • Replace TODOs with the correct subgraph endpoints including the {{{graphApiKey}}} placeholder
  • Ensure proper API key configuration is available during deployment
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the arbitrumSepoliaDevnet subgraph endpoint
curl -s "https://gateway-arbitrum.network.thegraph.com/api/test/subgraphs/id/3aZxYcZpZL5BuVhuUupqVrCV8VeNyZEvjmPXibyPHDFQ" \
  -H "Content-Type: application/json" \
  -d '{"query": "{ _meta { block { number } } }"}'

Length of output: 264


Script:

#!/bin/bash
# Check for similar template patterns and configuration documentation
echo "Searching for graphApiKey references:"
rg -i "graphApiKey" -A 2 -B 2

echo -e "\nChecking for environment or configuration files:"
fd -e env -e config -e yaml -e json

Length of output: 3867

Comment on lines +21 to +59
const disputeTemplateFn = (chainId: number, klerosCore: string) => `{
"$schema": "../NewDisputeTemplate.schema.json",
"title": "Escrow dispute: {{escrowTitle}}",
"description": "{{deliverableText}}",
"question": "Which party abided by the terms of the contract?",
"answers": [
{
title: "Refund the Buyer",
description: "Select this to return the funds to the Buyer.",
"title": "Refund the Buyer",
"description": "Select this to return the funds to the Buyer."
},
{
title: "Pay the Seller",
description: "Select this to release the funds to the Seller.",
},
"title": "Pay the Seller",
"description": "Select this to release the funds to the Seller."
}
],
policyURI: "ipfs://TODO",
attachment: {
label: "Transaction Terms",
uri: "{{extraDescriptionUri}}",
"policyURI": "/ipfs/QmTaZuQjJT9NZCYsqyRmEwLb1Vt3gme1a6BS4NQLiWXtH2", // General policy for escrows in progress
"attachment": {
"label": "Transaction Terms",
"uri": "{{{extraDescriptionUri}}}"
},
frontendUrl: "https://escrow-v2.kleros.builders/#/myTransactions/{{transactionId}}",
arbitrableChainID: "421614",
arbitrableAddress: "0x250AB0477346aDFC010585b58FbF61cff1d8f3ea",
arbitratorChainID: "421614",
arbitratorAddress: "0xA54e7A16d7460e38a8F324eF46782FB520d58CE8",
metadata: {
buyer: "{{address}}",
seller: "{{sendingRecipientAddress}}",
amount: "{{sendingQuantity}}",
asset: "{{asset}}",
deadline: "{{deadline}}",
transactionUri: "{{transactionUri}}",
"frontendUrl": "https://escrow-v2.kleros.builders/#/transactions/{{externalDisputeID}}",
"arbitratorChainID": "${chainId}",
"arbitratorAddress": "${klerosCore}",
"metadata": {
"buyer": "{{buyer}}",
"seller": "{{seller}}",
"amount": "{{amount}}",
"token": "{{token}}",
"deadline": "{{deadline}}",
"transactionUri": "{{{transactionUri}}}"
},
category: "Escrow",
specification: "KIPXXX",
aliases: {
Buyer: "{{address}}",
Seller: "{{sendingRecipientAddress}}",
"category": "Escrow",
"aliases": {
"Buyer": "{{buyer}}",
"Seller": "{{seller}}"
},
version: "1.0",
};
"version": "1.0"
}
`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Consider configurable values for environment-specific settings

The review comment is valid. The codebase shows a consistent pattern of making deployment-specific values configurable through environment variables (e.g., REACT_APP_IPFS_GATEWAY). The hardcoded policy URI and frontend URL should follow this pattern:

  • Move the policy URI to environment config as it may differ between deployments (as seen in deployment JSON using a different value)
  • Make the frontend URL configurable to support different environments (devnet, testnet, mainnet)

This aligns with the project's existing configuration patterns and allows for easier environment management.

🔗 Analysis chain

Consider configurable values for environment-specific settings.

The template contains hardcoded values that might need to change:

  1. Policy URI (QmTaZuQjJT9NZCYsqyRmEwLb1Vt3gme1a6BS4NQLiWXtH2)
  2. Frontend URL (https://escrow-v2.kleros.builders)

Let's verify the IPFS content:

Consider moving these values to the network parameters:

 const parameters = {
   arbitrumSepoliaDevnet: {
     arbitrator: "KlerosCore",
     subgraphEndpoint: "...",
+    policyUri: "QmTaZuQjJT9NZCYsqyRmEwLb1Vt3gme1a6BS4NQLiWXtH2",
+    frontendUrl: "https://escrow-v2.kleros.builders"
   },
   // ...
 };
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify IPFS content availability
curl -s "https://ipfs.io/ipfs/QmTaZuQjJT9NZCYsqyRmEwLb1Vt3gme1a6BS4NQLiWXtH2"

Length of output: 120


Script:

#!/bin/bash
# Check for configuration patterns and network parameters
rg -g '!{dist,node_modules}' -A 5 "parameters = {" 

# Look for similar IPFS hashes or URLs to understand the pattern
rg -g '!{dist,node_modules}' "QmT|https://escrow-v2.kleros"

Length of output: 2048


Script:

#!/bin/bash
# Search for environment configuration patterns
rg -g '!{dist,node_modules}' "process\.env\.|\.env|config\." -A 2

# Look for deployment-related configuration files
fd -g "*.config.{js,ts,json}"

Length of output: 9047

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants