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

feat: Create proof of liveness smart contract #190

Merged

Conversation

andresaiello
Copy link
Collaborator

@andresaiello andresaiello commented Sep 25, 2024

Summary

  • Create proof of liveness smart contract
  • Deploy to athens

Summary by CodeRabbit

  • New Features

    • Introduced a smart contract, ProofOfLiveness, allowing users to prove their liveness once every 24 hours.
    • Added functionality to check proof history for the last five periods.
  • Data Updates

    • Added the ProofOfLiveness contract address to the addresses data file for both mainnet and testnet.
  • Deployment

    • New deployment script created for the ProofOfLiveness contract, facilitating its deployment and verification.
  • Testing

    • Implemented a comprehensive suite of tests for the ProofOfLiveness contract, covering various scenarios and edge cases.

Copy link

coderabbitai bot commented Sep 25, 2024

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes introduce a new smart contract, ProofOfLiveness, enabling users to prove their liveness once every 24 hours. It includes functions for liveness verification, eligibility checks, and proof history retrieval. Additionally, a deployment script for the contract is provided, along with updates to a JSON file to include the contract's address. These modifications enhance the application's functionality by implementing a structured approach to user liveness verification.

Changes

File Path Change Summary
packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol Introduced ProofOfLiveness contract with methods for proving liveness, checking eligibility, and retrieving proof history. Added event and custom error.
packages/zevm-app-contracts/data/addresses.json Added new entry for ProofOfLiveness contract address.
packages/zevm-app-contracts/scripts/proof-of-liveness/deploy.ts Created deployment script for ProofOfLiveness contract, including address logging and verification.
packages/zevm-app-contracts/test/proof-of-liveness/proof-of-liveness.ts Added test suite for ProofOfLiveness contract, covering various scenarios and expected behaviors.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ProofOfLiveness
    participant Blockchain

    User->>ProofOfLiveness: Call proveLiveness()
    ProofOfLiveness->>ProofOfLiveness: Check last proof timestamp
    alt If 24 hours have passed
        ProofOfLiveness->>Blockchain: Update timestamp
        ProofOfLiveness->>User: Emit LivenessProved event
    else If not 24 hours
        ProofOfLiveness-->>User: Revert with ProofWithinLast24Hours error
    end
Loading

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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 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 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

@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: 5

🧹 Outside diff range and nitpick comments (2)
packages/zevm-app-contracts/scripts/proof-of-liveness/deploy.ts (1)

10-23: deployProofOfLiveness function is well-structured, but error handling can be improved.

The function correctly deploys the ProofOfLiveness contract, saves its address, and verifies it. However, consider enhancing error handling for deployment and verification steps.

Consider wrapping the deployment and verification steps in try-catch blocks:

const deployProofOfLiveness = async () => {
  if (!isProtocolNetworkName(networkName)) throw new Error("Invalid network name");

  try {
    const ProofOfLivenessFactory = (await ethers.getContractFactory("ProofOfLiveness")) as ProofOfLiveness__factory;
    const ProofOfLiveness = await ProofOfLivenessFactory.deploy();
    await ProofOfLiveness.deployed();

    console.log("ProofOfLiveness deployed to:", ProofOfLiveness.address);
    saveAddress("ProofOfLiveness", ProofOfLiveness.address, networkName);

    try {
      await verifyContract(ProofOfLiveness.address, []);
    } catch (verifyError) {
      console.warn("Contract verification failed:", verifyError.message);
    }
  } catch (deployError) {
    console.error("Deployment failed:", deployError.message);
    throw deployError;
  }
};

This structure allows for more granular error handling and ensures that deployment errors are properly caught and re-thrown.

packages/zevm-app-contracts/data/addresses.json (1)

11-12: Approve changes with minor suggestion for consistency.

The addition of the "ProofOfLiveness" contract address is consistent with the PR objectives and maintains the existing file structure. However, for improved consistency and future-proofing, consider alphabetizing the contract entries within each network object.

Consider applying the following change for improved consistency:

 {
   "zevm": {
     "zeta_testnet": {
       "disperse": "0x23ce409Ea60c3d75827d04D9db3d52F3af62e44d",
-      "rewardDistributorFactory": "0xB9dc665610CF5109cE23aBBdaAc315B41FA094c1",
-      "zetaSwap": "0xA8168Dc495Ed61E70f5c1941e2860050AB902cEF",
-      "zetaSwapBtcInbound": "0x358E2cfC0E16444Ba7D3164Bbeeb6bEA7472c559",
       "invitationManager": "0x3649C03C472B698213926543456E9c21081e529d",
-      "withdrawERC20": "0xa349B9367cc54b47CAb8D09A95836AE8b4D1d84E",
-      "ZetaXP": "0x5c25b6f4D2b7a550a80561d3Bf274C953aC8be7d",
       "InstantRewards": "0x10DfEd4ba9b8F6a1c998E829FfC0325D533c80E3",
-      "ProofOfLiveness": "0x2aD64D83827D102FCBBdEb92DEA91fCAB168Cdc2"
+      "ProofOfLiveness": "0x2aD64D83827D102FCBBdEb92DEA91fCAB168Cdc2",
+      "rewardDistributorFactory": "0xB9dc665610CF5109cE23aBBdaAc315B41FA094c1",
+      "withdrawERC20": "0xa349B9367cc54b47CAb8D09A95836AE8b4D1d84E",
+      "ZetaXP": "0x5c25b6f4D2b7a550a80561d3Bf274C953aC8be7d",
+      "zetaSwap": "0xA8168Dc495Ed61E70f5c1941e2860050AB902cEF",
+      "zetaSwapBtcInbound": "0x358E2cfC0E16444Ba7D3164Bbeeb6bEA7472c559"
     },
     "zeta_mainnet": {
       // ... (unchanged)
     }
   }
 }

This change will enhance readability and make future additions more straightforward.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9e35108 and d653425.

📒 Files selected for processing (3)
  • packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol (1 hunks)
  • packages/zevm-app-contracts/data/addresses.json (1 hunks)
  • packages/zevm-app-contracts/scripts/proof-of-liveness/deploy.ts (1 hunks)
🔇 Additional comments not posted (3)
packages/zevm-app-contracts/scripts/proof-of-liveness/deploy.ts (1)

1-8: Imports and initial setup are appropriate.

The necessary modules and types are imported, and the network name is correctly extracted from the Hardhat environment. This setup provides a solid foundation for the deployment script.

packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol (2)

1-6: Contract declaration and state variable are well-defined.

The contract name accurately reflects its purpose, and the state variable lastProofTimestamp is correctly defined as a public mapping to store the last proof timestamp for each user.


8-12: Custom error and event declarations are appropriate.

The custom error ProofWithinLast24Hours provides a clear message and includes relevant data. The LivenessProved event is properly defined with an indexed parameter for efficient filtering.

Copy link

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d653425 and 0247c3b.

📒 Files selected for processing (1)
  • packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol (1 hunks)
🧰 Additional context used
GitHub Check: Slither
packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol

[notice] 18-32: Block timestamp
ProofOfLiveness.proveLiveness() (contracts/proof-of-liveness/ProofOfLiveness.sol#18-32) uses timestamp for comparisons
Dangerous comparisons:
- currentTime < lastProofTime + PROOF_PERIOD (contracts/proof-of-liveness/ProofOfLiveness.sol#23)


[notice] 35-38: Block timestamp
ProofOfLiveness.canProveLiveness(address) (contracts/proof-of-liveness/ProofOfLiveness.sol#35-38) uses timestamp for comparisons
Dangerous comparisons:
- currentTime >= lastProofTimestamp[user] + PROOF_PERIOD (contracts/proof-of-liveness/ProofOfLiveness.sol#37)


[notice] 41-62: Block timestamp
ProofOfLiveness.getLastPeriodsStatus(address) (contracts/proof-of-liveness/ProofOfLiveness.sol#41-62) uses timestamp for comparisons
Dangerous comparisons:
- lastProofTime >= periodEnd && lastProofTime < periodStart (contracts/proof-of-liveness/ProofOfLiveness.sol#54)


[warning] 45-45: Uninitialized local variables
ProofOfLiveness.getLastPeriodsStatus(address).proofStatus (contracts/proof-of-liveness/ProofOfLiveness.sol#45) is a local variable never initialized

🔇 Additional comments not posted (6)
packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol (6)

5-6: Constants are appropriately defined.

The use of PROOF_PERIOD and LAST_PERIODS_LENGTH as constants enhances code readability and maintainability.


9-9: Mapping lastProofTimestamp is correctly declared.

The mapping(address => uint256) public lastProofTimestamp; efficiently tracks the last proof timestamps for each user.


12-12: Custom error ProofWithinLast24Hours is well-defined.

Defining a custom error reduces gas costs when reverting transactions and provides clarity on the revert reason.


15-15: Event LivenessProved is properly declared.

Emitting LivenessProved events enables off-chain services to monitor and record liveness proofs effectively.


18-32: proveLiveness function is correctly implemented.

The function appropriately restricts users from proving liveness more than once within the PROOF_PERIOD, updates the timestamp, and emits the corresponding event.

🧰 Tools
GitHub Check: Slither

[notice] 18-32: Block timestamp
ProofOfLiveness.proveLiveness() (contracts/proof-of-liveness/ProofOfLiveness.sol#18-32) uses timestamp for comparisons
Dangerous comparisons:
- currentTime < lastProofTime + PROOF_PERIOD (contracts/proof-of-liveness/ProofOfLiveness.sol#23)


35-38: canProveLiveness function accurately determines eligibility.

The function provides an efficient way for users to check their ability to prove liveness without modifying state.

🧰 Tools
GitHub Check: Slither

[notice] 35-38: Block timestamp
ProofOfLiveness.canProveLiveness(address) (contracts/proof-of-liveness/ProofOfLiveness.sol#35-38) uses timestamp for comparisons
Dangerous comparisons:
- currentTime >= lastProofTimestamp[user] + PROOF_PERIOD (contracts/proof-of-liveness/ProofOfLiveness.sol#37)

@andresaiello andresaiello changed the title Create proof of liveness smart contract feat: Create proof of liveness smart contract Sep 25, 2024
Copy link

@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

🧹 Outside diff range and nitpick comments (4)
packages/zevm-app-contracts/test/proof-of-liveness/proof-of-liveness.ts (4)

1-9: Remove unused constant HARDHAT_CHAIN_ID

The constant HARDHAT_CHAIN_ID is defined but not utilized within the visible code. To maintain code cleanliness and prevent potential confusion, it is advisable to remove unused declarations.

Consider applying the following change:

-const HARDHAT_CHAIN_ID = 1337;

27-34: Enhance test coverage for "Should proof" test case

The current test case effectively verifies the event emission and its parameters. To further strengthen the test, consider adding an assertion to check if the liveness status has been updated correctly in the contract state.

Consider adding the following assertion after line 33:

expect(await proofOfLiveness.getLastPeriodsStatus(owner.address)).to.deep.equal([true, false, false, false, false]);

This addition will ensure that the contract's state is updated as expected after proving liveness.


36-78: Well-structured time-based tests with room for minor improvement

The test cases effectively verify the contract's behavior over multiple time periods, including scenarios with consistent proofs and a missed proof. The use of evm_increaseTime is appropriate for simulating time passage.

To enhance readability and maintainability, consider extracting the time manipulation logic into a separate helper function.

Consider adding a helper function for time manipulation:

async function advanceTime(seconds: number) {
  await ethers.provider.send("evm_increaseTime", [seconds]);
  await ethers.provider.send("evm_mine", []);
}

Then, replace the time advancement code in both test cases with:

await advanceTime(PROOF_PERIOD);

This refactoring will reduce code duplication and improve the tests' readability.


91-99: Effective revert test with room for consistency improvement

This test case successfully verifies that the contract reverts when attempting to prove liveness twice within 24 hours. The use of expect(...).to.be.revertedWith is appropriate for checking the specific error message.

To maintain consistency with the other test cases and improve readability, consider using a descriptive error message in the contract and reflecting it in the test.

Update the error message in the contract to be more descriptive:

require(lastProof + 24 hours <= block.timestamp, "Cannot prove liveness more than once in 24 hours");

Then, update the test assertion to match the new error message:

await expect(tx).to.be.revertedWith("Cannot prove liveness more than once in 24 hours");

This change will make the error message more informative and consistent with best practices.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0247c3b and 8ef87b0.

📒 Files selected for processing (3)
  • packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol (1 hunks)
  • packages/zevm-app-contracts/data/addresses.json (1 hunks)
  • packages/zevm-app-contracts/test/proof-of-liveness/proof-of-liveness.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/zevm-app-contracts/contracts/proof-of-liveness/ProofOfLiveness.sol
  • packages/zevm-app-contracts/data/addresses.json
🔇 Additional comments not posted (2)
packages/zevm-app-contracts/test/proof-of-liveness/proof-of-liveness.ts (2)

11-25: Test suite setup is well-structured

The test suite setup is comprehensive and follows testing best practices. The use of beforeEach to deploy a new contract instance before each test ensures a clean state, promoting test isolation and reliability.


80-89: Comprehensive edge case coverage

This test case effectively verifies the contract's behavior for a single proof, ensuring that only the most recent period is marked as true. The assertion correctly checks the expected outcome, providing valuable coverage for this edge case.

GMaiolo
GMaiolo previously approved these changes Sep 25, 2024
Copy link
Collaborator

@GMaiolo GMaiolo left a comment

Choose a reason for hiding this comment

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

Looks great!

Copy link

@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

🧹 Outside diff range and nitpick comments (1)
packages/zevm-app-contracts/data/addresses.json (1)

Missing Deployment Scripts and Documentation for ProofOfLiveness

The verification process revealed that there are no deployment scripts found for the ProofOfLiveness contract, and the relevant documentation has not been updated accordingly.

  • Deployment Scripts:

    • No deployment script found for ProofOfLiveness. Please ensure that a deployment script is created and located within packages/zevm-app-contracts/scripts/.
  • Documentation Updates:

    • No mentions of ProofOfLiveness found in README.md or within the docs/ directory. Please update the documentation to include details about the deployment and usage of the new contract.

Addressing these issues is crucial to maintain the integrity of the deployment process and to ensure that all team members are informed about the new contract integrations.

🔗 Analysis chain

Line range hint 1-26: Ensure proper documentation and deployment processes

While the additions to the addresses.json file are correct, it is crucial to ensure that the deployment process and documentation are updated accordingly.

To verify the completeness of the deployment process and documentation, please run the following script:

Additionally, please ensure that:

  1. The deployment process for the ProofOfLiveness contract is documented.
  2. Any necessary updates to other parts of the codebase that interact with this new contract are completed.
  3. The team is aware of the new contract addresses and their implications on the system.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for deployment scripts and documentation updates

# Check for deployment scripts
if grep -q "ProofOfLiveness" packages/zevm-app-contracts/scripts/deploy*.ts; then
  echo "Deployment script found for ProofOfLiveness."
else
  echo "Warning: No deployment script found for ProofOfLiveness. Please ensure it exists."
fi

# Check for documentation updates
if grep -q "ProofOfLiveness" README.md docs/*.md; then
  echo "Documentation mentioning ProofOfLiveness found."
else
  echo "Warning: No documentation updates found for ProofOfLiveness. Please update the relevant documentation."
fi

echo "Verification completed. Address any warnings if present."

Length of output: 756

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 43313b9 and ed6715d.

📒 Files selected for processing (1)
  • packages/zevm-app-contracts/data/addresses.json (2 hunks)
🔇 Additional comments (1)
packages/zevm-app-contracts/data/addresses.json (1)

22-23: New contract address added for ProofOfLiveness in zeta_mainnet

The addition of the ProofOfLiveness contract address for the zeta_mainnet environment is noted. The address format appears valid, and the entry follows the established naming convention.

To ensure the consistency and validity of this addition, please run the following verification script:

#!/bin/bash
# Verify the ProofOfLiveness contract address in zeta_mainnet

# Check if the address exists in the file
if grep -q '"ProofOfLiveness": "0x327c9837B183e69C522a30E6f91A42c86e057432"' packages/zevm-app-contracts/data/addresses.json; then
  echo "ProofOfLiveness address found in zeta_mainnet section."
else
  echo "Error: ProofOfLiveness address not found or incorrect in zeta_mainnet section."
  exit 1
fi

# Verify the address format
if [[ "0x327c9837B183e69C522a30E6f91A42c86e057432" =~ ^0x[a-fA-F0-9]{40}$ ]]; then
  echo "Address format is valid."
else
  echo "Error: Invalid address format for ProofOfLiveness in zeta_mainnet."
  exit 1
fi

echo "Verification completed successfully."

@andresaiello andresaiello merged commit b7ae18a into main Sep 26, 2024
11 of 12 checks passed
@andresaiello andresaiello deleted the andy/pd-6660-create-proof-of-liveness-smart-contract branch September 26, 2024 18:28
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