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

Gateway localnet examples #189

Merged
merged 18 commits into from
Aug 31, 2024
Merged

Gateway localnet examples #189

merged 18 commits into from
Aug 31, 2024

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Aug 12, 2024

Summary by CodeRabbit

  • New Features

    • Introduced Hello contract for enhanced cross-chain interaction and structured revert handling.
    • Introduced RevertContract for improved revert scenario management.
    • Added ReceiverContract for event logging and Ether reception.
    • Added new Hardhat tasks, call-from-zetachain and deposit-and-call, facilitating seamless interactions with ZetaChain contracts.
  • Documentation

    • Enhanced documentation to guide users in utilizing new features and interacting with the ZetaChain contracts.
  • Chores

    • Improved project structure with new management files, contributing to better organization and maintenance.

Copy link

coderabbitai bot commented Aug 12, 2024

Warning

Rate limit exceeded

@fadeev has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 4 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between f1d8fb4 and 4095527.

Walkthrough

Walkthrough

The recent changes introduce new Solidity contracts aimed at enhancing cross-chain interactions with ZetaChain. These contracts include structured logging for successful calls and comprehensive error handling mechanisms. Additionally, new Hardhat tasks have been implemented to facilitate contract interactions, thereby improving the developer experience and ensuring robust error tracking across blockchain environments.

Changes

File Path Change Summary
universal/hello/contracts/Hello.sol, universal/hello/contracts/RevertContract.sol, universal/hello/contracts/ReceiverContract.sol New Solidity contracts added to manage cross-chain interactions, handle reverts, and log events, providing a structured approach to error management and communication.
universal/hello/tasks/callFromZetaChain.ts, universal/hello/tasks/depositAndCall.ts Two new Hardhat tasks implemented to streamline interactions with ZetaChain contracts, allowing for deposits and contract calls with specified parameters.
universal/hello/hardhat.config.ts New Hardhat configuration file established to support blockchain development, including network settings and Solidity compiler version specification.
universal/hello/package.json Newly created package.json file defining project metadata and specifying development dependencies for the Hardhat environment.
universal/hello/tasks/solana/gateway.json New JSON file defining a Solana-based gateway application structure, including instructions for token management and error handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Hardhat
    participant HelloContract

    User->>Hardhat: Execute call-from-zetachain task
    Hardhat->>HelloContract: Call onCrossChainCall with parameters
    HelloContract-->>Hardhat: Emit HelloEvent
    Hardhat-->>User: Display success message
Loading
sequenceDiagram
    participant User
    participant Hardhat
    participant RevertContract

    User->>Hardhat: Execute interact task
    Hardhat->>RevertContract: Call onRevert with context
    RevertContract-->>Hardhat: Emit ContextDataRevert
    Hardhat-->>User: Display revert context
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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

@fadeev fadeev marked this pull request as ready for review August 14, 2024 07:48
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: 2

Outside diff range, codebase verification and nitpick comments (5)
universal/hello/README.md (1)

7-9: Specify language for code block.

Add a language identifier to the fenced code block for improved syntax highlighting and readability.

- ```
+ ```sh
Tools
Markdownlint

7-7: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

universal/hello/hardhat.config.ts (1)

14-14: Incompatible Solidity Versions Detected

The Solidity version specified in hardhat.config.ts is "0.8.26". However, several contracts in the project use different versions, notably "0.8.7" and "0.5.16". This discrepancy could lead to compatibility issues.

  • Files using Solidity 0.8.7:

    • messaging/message/contracts/CrossChainMessage.sol
    • messaging/nft/contracts/CrossChainNFT.sol
    • omnichain/swap/contracts/Swap.sol
    • omnichain/swap/contracts/SwapToAnyToken.sol
    • omnichain/staking/contracts/Staking.sol
    • ... (and others)
  • Files using Solidity 0.5.16:

    • omnichain/swap/contracts/shared/TestUniswapCore.sol
    • omnichain/staking/contracts/shared/TestUniswapCore.sol
    • omnichain/multioutput/contracts/shared/TestUniswapCore.sol
    • omnichain/nft/contracts/shared/TestUniswapCore.sol

Recommended Action:
Review the contracts and consider updating their Solidity versions to align with "0.8.26" if feasible, or adjust the Hardhat configuration to accommodate the versions in use. Ensure thorough testing after making changes to prevent any potential issues.

Analysis chain

Verify Solidity version compatibility.

The Solidity version is set to "0.8.26". Ensure this version is compatible with all contracts and dependencies in the project.


Let's re-verify the Solidity version compatibility by correctly identifying Solidity files and checking their pragma statements.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify compatibility of Solidity version with contracts.

# Test: Search for all Solidity files and check their pragma statements.
rg --type solidity -A 1 $'pragma solidity' | grep -v '0.8.26'

Length of output: 93


Script:

#!/bin/bash
# Description: Find all Solidity files and check their pragma statements for compatibility with version 0.8.26.

# Find all Solidity files and check their pragma statements.
fd --extension sol --exec grep -H 'pragma solidity' {} | grep -v '0.8.26'

Length of output: 1701

universal/hello/tasks/interact.ts (1)

40-47: Task registration is correct, but improve parameter descriptions.

Ensure that parameter descriptions provide clear guidance on expected input values.

task("interact", "Calls a ZetaChain contract from an EVM account", main)
  .addParam("name", "Name to encode in the contract call")
  .addParam("contract", "Address of the universal app contract on ZetaChain")
  .addOptionalParam(
    "gatewayEVM",
    "Address of the gateway contract on EVM",
    "0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"
  );
universal/hello/package.json (2)

6-10: Update the test script and ensure comprehensive linting.

The test script is a placeholder and should be updated to include actual tests. Ensure the lint scripts cover all necessary file types.

"scripts": {
  "test": "mocha --require ts-node/register 'test/**/*.spec.ts'",
  "lint:fix": "npx eslint . --ext .js,.ts --fix",
  "lint": "npx eslint . --ext .js,.ts"
}

2-13: Fill in metadata fields for better documentation.

Consider providing a description, author information, and keywords to improve project documentation and clarity.

"description": "A template project for Ethereum smart contract development",
"author": "Your Name",
"keywords": ["Ethereum", "smart contracts", "ZetaChain"]
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b50991b and 27d8af1.

Files ignored due to path filters (1)
  • universal/hello/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (13)
  • omnichain/swap/tasks/deploy.ts (1 hunks)
  • universal/hello/.eslintignore (1 hunks)
  • universal/hello/.eslintrc.js (1 hunks)
  • universal/hello/.gitignore (1 hunks)
  • universal/hello/LICENSE (1 hunks)
  • universal/hello/README.md (1 hunks)
  • universal/hello/contracts/Hello.sol (1 hunks)
  • universal/hello/foundry.toml (1 hunks)
  • universal/hello/hardhat.config.ts (1 hunks)
  • universal/hello/package.json (1 hunks)
  • universal/hello/tasks/deploy.ts (1 hunks)
  • universal/hello/tasks/interact.ts (1 hunks)
  • universal/hello/tsconfig.json (1 hunks)
Files skipped from review due to trivial changes (4)
  • universal/hello/.eslintignore
  • universal/hello/.gitignore
  • universal/hello/LICENSE
  • universal/hello/foundry.toml
Additional context used
Markdownlint
universal/hello/README.md

7-7: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

Additional comments not posted (17)
universal/hello/tsconfig.json (6)

3-4: Appropriate module settings for Node.js ES modules.

The module and moduleResolution options set to nodenext are suitable for projects using ES modules in Node.js environments.


5-5: Enabling esModuleInterop for module compatibility.

The esModuleInterop option is correctly enabled to facilitate interoperability between CommonJS and ES modules.


6-6: Consistent casing in file names enforced.

The forceConsistentCasingInFileNames option is appropriately enabled to avoid issues on case-sensitive file systems.


7-7: Strict type-checking enabled.

The strict option is correctly enabled, ensuring comprehensive type-checking for improved code quality.


8-8: Skipping library type checks for performance.

The skipLibCheck option is enabled, which can improve build performance by skipping type checks of declaration files. Ensure this aligns with your project's quality requirements.


9-9: JSON module resolution enabled.

The resolveJsonModule option is enabled, allowing JSON files to be imported as modules, which is useful for configuration and data handling.

universal/hello/README.md (1)

11-15: Clear guidance for next steps.

The "Next Steps" section effectively guides users to further resources and tutorials.

universal/hello/hardhat.config.ts (2)

1-5: Relevant task and module imports.

The imports for custom tasks and third-party modules are appropriate for extending Hardhat's functionality in this project.


11-13: Dynamic network configuration.

Using getHardhatConfigNetworks() allows for flexible and dynamic network configurations, which is beneficial for different environments.

universal/hello/.eslintrc.js (1)

1-47: ESLint Configuration Looks Good.

The ESLint configuration is comprehensive, with TypeScript support and useful plugins for sorting and formatting. It aligns well with best practices.

universal/hello/contracts/Hello.sol (1)

1-46: Solidity Contract Implementation Looks Good.

The Hello contract is well-implemented, with appropriate event emissions and function overrides. Ensure the events are used correctly in the broader system.

Consider verifying that the emitted events are appropriately handled and logged in the system.

universal/hello/tasks/deploy.ts (1)

1-40: Deployment Script Looks Good.

The deployment script is well-structured, with appropriate error handling and flexible output options. Ensure the commented-out code is intentional and documented.

Consider verifying whether the commented-out code is necessary or if it can be removed.

universal/hello/tasks/interact.ts (2)

1-3: Imports are appropriate and necessary.

The imported modules and types are essential for defining the Hardhat task and interacting with the Ethereum contract.


14-17: Parameter validation for args.name.

Ensure that args.name is validated before encoding to prevent potential issues with unexpected input types.

if (typeof args.name !== "string") {
  throw new Error("Invalid parameter: 'name' must be a string.");
}
omnichain/swap/tasks/deploy.ts (2)

8-12: Reconsider commenting out network validation.

The removal of network validation allows deployments on any network, which may lead to unintended consequences. Consider re-enabling the validation or implementing a more flexible yet safe approach.

if (!/zeta_(testnet|mainnet)/.test(network)) {
  console.warn(`Deploying on an unverified network: ${network}. Proceed with caution.`);
}

Line range hint 13-50: Deployment script is generally well-structured.

The script correctly handles contract deployment and output formatting. Ensure signer retrieval is robust and consider handling scenarios where no signer is available.

universal/hello/package.json (1)

14-52: Dependencies are relevant and necessary.

The listed dependencies are appropriate for Ethereum development and TypeScript support.

Comment on lines 5 to 12
const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
const [signer] = await hre.ethers.getSigners();

const gateway = new hre.ethers.Contract(
args.gatewayEVM,
GatewayABI.abi,
signer
);
Copy link

Choose a reason for hiding this comment

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

Ensure signer retrieval handles errors gracefully.

While the current implementation assumes that getSigners() will return a valid signer, consider adding error handling to manage scenarios where no signer is available.

const signers = await hre.ethers.getSigners();
if (signers.length === 0) {
  throw new Error("No signers available. Please configure a signer.");
}
const [signer] = signers;

Comment on lines 18 to 37
try {
const callTx = await gateway.call(
args.contract,
message,
{
revertAddress: "0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82",
callOnRevert: true,
abortAddress: "0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82",
revertMessage: "0x",
},
{
gasPrice: 10000000000,
gasLimit: 6721975,
}
);
await callTx.wait();
console.log("Contract on ZetaChain called from EVM");
} catch (e) {
console.error("Error calling contract:", e);
}
Copy link

Choose a reason for hiding this comment

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

Enhance error handling for contract interaction.

Consider providing more context in the error message or rethrowing the error for better debugging.

try {
  const callTx = await gateway.call(
    args.contract,
    message,
    {
      revertAddress: "0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82",
      callOnRevert: true,
      abortAddress: "0x0DCd1Bf9A1b36cE34237eEaFef220932846BCD82",
      revertMessage: "0x",
    },
    {
      gasPrice: 10000000000,
      gasLimit: 6721975,
    }
  );
  await callTx.wait();
  console.log("Contract on ZetaChain called from EVM");
} catch (e) {
  console.error("Error calling contract:", e.message || e);
  throw e; // Rethrow to propagate the error
}

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, codebase verification and nitpick comments (2)
universal/hello/tasks/solana/interact.ts (1)

10-10: Add a description for the task.

The task "interact-solana" lacks a description. Adding a brief description would enhance clarity and usability.

-task("interact-solana", "", main)
+task("interact-solana", "Interacts with the Solana network to deposit SOL", main)
universal/hello/tasks/solana/deposit.ts (1)

52-54: Enhance error logging for better debugging.

Consider adding more context to the error logging to facilitate debugging.

- console.error("Transaction failed:", error);
+ console.error("Transaction failed during deposit:", error);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 27d8af1 and 7b76520.

Files ignored due to path filters (1)
  • universal/hello/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (9)
  • universal/hello/.gitignore (1 hunks)
  • universal/hello/contracts/Hello.sol (1 hunks)
  • universal/hello/foundry.toml (1 hunks)
  • universal/hello/hardhat.config.ts (1 hunks)
  • universal/hello/package.json (1 hunks)
  • universal/hello/tasks/interact.ts (1 hunks)
  • universal/hello/tasks/solana/deposit.ts (1 hunks)
  • universal/hello/tasks/solana/gateway.json (1 hunks)
  • universal/hello/tasks/solana/interact.ts (1 hunks)
Files skipped from review due to trivial changes (4)
  • universal/hello/.gitignore
  • universal/hello/foundry.toml
  • universal/hello/hardhat.config.ts
  • universal/hello/package.json
Files skipped from review as they are similar to previous changes (2)
  • universal/hello/contracts/Hello.sol
  • universal/hello/tasks/interact.ts
Additional comments not posted (1)
universal/hello/tasks/solana/gateway.json (1)

1-428: Verify IDL alignment with program implementation.

Ensure that the IDL accurately reflects the program's implementation, especially the instruction names, accounts, and error codes.

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, codebase verification and nitpick comments (5)
universal/hello/contracts/RevertContract.sol (2)

14-17: Consider implementing additional logic in onRevert.

The onRevert function currently only emits an event. Consider implementing additional logic to handle revert scenarios, such as logging more detailed information or triggering compensating actions.


16-16: Remove commented-out code or provide context.

The commented-out line for emitting RevertEvent should either be removed or accompanied by a comment explaining its intended use.

- // emit RevertEvent("Event from RevertContract!!!");
+ // Uncomment to emit a revert event with a custom message.
universal/hello/contracts/Hello.sol (3)

14-22: Clarify the purpose of the forced revert in onCrossChainCall.

The onCrossChainCall function contains a forced revert, which might be intentional for testing purposes. Ensure that this behavior is documented, or consider removing it for production use.

- revert("REVERTING!!!");
+ // Revert is intentional for testing purposes. Remove for production use.

22-25: Remove or document commented-out code.

The commented-out code for decoding a message should either be removed or documented to clarify its intended future use.

- // string memory decodedMessage;
- // if (message.length > 0) {
- //     decodedMessage = abi.decode(message, (string));
- // }
+ // Uncomment and use this code to decode messages when needed.

28-30: Consider additional logic in onRevert.

The onRevert function currently only emits an event. Consider implementing additional logic to handle revert scenarios, such as logging more detailed information or triggering compensating actions.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7b76520 and 7bfeadb.

Files selected for processing (3)
  • universal/hello/contracts/Hello.sol (1 hunks)
  • universal/hello/contracts/RevertContract.sol (1 hunks)
  • universal/hello/tasks/interact.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • universal/hello/tasks/interact.ts

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: 2

Outside diff range, codebase verification and nitpick comments (1)
universal/hello/tasks/callFromZetaChain.ts (1)

47-63: Improve parameter documentation for clarity.

The task parameters are defined, but additional comments explaining each parameter's purpose and expected format would enhance readability and usability for other developers.

.addParam("message", "A message to be sent to the contract")
.addParam("contract", "The address of the universal app on ZetaChain (must be a valid Ethereum address)")
// ... other parameters
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7bfeadb and f7d796b.

Files selected for processing (6)
  • universal/hello/contracts/Hello.sol (1 hunks)
  • universal/hello/contracts/RevertContract.sol (1 hunks)
  • universal/hello/hardhat.config.ts (1 hunks)
  • universal/hello/package.json (1 hunks)
  • universal/hello/tasks/callFromZetaChain.ts (1 hunks)
  • universal/hello/tasks/interact.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • universal/hello/hardhat.config.ts
Files skipped from review as they are similar to previous changes (4)
  • universal/hello/contracts/Hello.sol
  • universal/hello/contracts/RevertContract.sol
  • universal/hello/package.json
  • universal/hello/tasks/interact.ts

Comment on lines +5 to +13
const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
const [signer] = await hre.ethers.getSigners();

const contractArtifact = await hre.artifacts.readArtifact("Hello");
const contract = new hre.ethers.Contract(
args.contract,
contractArtifact.abi,
signer
);
Copy link

Choose a reason for hiding this comment

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

Consider validating input parameters.

While the function retrieves the signer and contract artifact correctly, it lacks validation for args.contract to ensure it is a valid Ethereum address. Consider adding validation to prevent runtime errors.

import { isAddress } from "ethers/lib/utils";

// Validate contract address
if (!isAddress(args.contract)) {
  throw new Error("Invalid contract address");
}

Comment on lines 22 to 44
try {
const tx = await contract.callFromZetaChain(
hre.ethers.utils.hexlify(args.receiver),
args.zrc20,
message,
args.gasLimit,
{
revertAddress: args.revertAddress,
callOnRevert: args.callOnRevert,
abortAddress: "0x0000000000000000000000000000000000000000", // not used
revertMessage: hre.ethers.utils.hexlify(revertMessageBytes),
},
{
gasPrice: 10000000000,
gasLimit: 7000000,
}
);

await tx.wait();
console.log("Successfully called the contract on ZetaChain!");
} catch (e) {
console.error("Error calling contract:", e);
}
Copy link

Choose a reason for hiding this comment

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

Enhance error handling with more informative messages.

The current error handling logs a generic error message. Consider providing more context or rethrowing the error with additional information to aid debugging.

try {
  const tx = await contract.callFromZetaChain(
    // ... parameters
  );
  await tx.wait();
  console.log("Successfully called the contract on ZetaChain!");
} catch (e) {
  console.error("Error calling contract on ZetaChain:", e.message);
  throw new Error(`Failed to call contract: ${e.message}`);
}

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f7d796b and 325de30.

Files selected for processing (2)
  • universal/hello/contracts/Hello.sol (1 hunks)
  • universal/hello/tasks/callFromZetaChain.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • universal/hello/contracts/Hello.sol
Files skipped from review as they are similar to previous changes (1)
  • universal/hello/tasks/callFromZetaChain.ts

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 325de30 and 04c14ab.

Files selected for processing (3)
  • universal/hello/contracts/RevertContract.sol (1 hunks)
  • universal/hello/tasks/callFromZetaChain.ts (1 hunks)
  • universal/hello/tasks/interact.ts (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • universal/hello/contracts/RevertContract.sol
  • universal/hello/tasks/callFromZetaChain.ts
  • universal/hello/tasks/interact.ts

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 04c14ab and 7fa205a.

Files selected for processing (1)
  • universal/hello/tasks/callFromZetaChain.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • universal/hello/tasks/callFromZetaChain.ts

@fadeev fadeev mentioned this pull request Aug 21, 2024
event HelloEvent(string, string);
event ContextDataRevert(RevertContext);

address constant gateway = 0x610178dA211FEF7D417bC0e6FeD39F05609AD788;
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: let's call it gatewayAddress

Copy link
Member Author

Choose a reason for hiding this comment

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

'🚨 Please use either "zeta_testnet" or "zeta_mainnet" network to deploy to ZetaChain.'
);
}
// if (!/zeta_(testnet|mainnet)/.test(network)) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

if it's no longer valid just delete it, let's try to keep code clean

Copy link
Member Author

Choose a reason for hiding this comment

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

Reverted, because it's still relevant: 4095527

const main = async (args: any, hre: HardhatRuntimeEnvironment) => {
const network = hre.network.name as ParamChainName;

// if (!/zeta_(testnet|mainnet)/.test(network)) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

remove unused code

Copy link
Member Author

Choose a reason for hiding this comment

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

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, codebase verification and nitpick comments (3)
universal/hello/flat (3)

46-74: Review deprecation and transition strategies.

The zContract interface is marked as deprecated, which is good for informing developers of upcoming changes. However, ensure that there is a clear transition strategy and timeline for developers to migrate to the UniversalContract to avoid disruptions.


83-117: Event documentation could be improved.

The events in IGatewayZEVMEvents are crucial for understanding cross-chain interactions. Consider adding more detailed comments explaining when each event should be expected and any important considerations regarding their parameters.


527-542: Enhance fallback and receive function documentation.

The ReceiverContract includes fallback and receive functions but lacks documentation. Adding comments explaining their purpose and any specific behaviors expected (e.g., logging received funds) would improve code clarity and maintainability.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7fa205a and f1d8fb4.

Files ignored due to path filters (1)
  • universal/hello/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (8)
  • universal/hello/contracts/Hello.sol (1 hunks)
  • universal/hello/contracts/ReceiverContract.sol (1 hunks)
  • universal/hello/flat (1 hunks)
  • universal/hello/hardhat.config.ts (1 hunks)
  • universal/hello/package.json (1 hunks)
  • universal/hello/tasks/callFromZetaChain.ts (1 hunks)
  • universal/hello/tasks/depositAndCall.ts (1 hunks)
  • universal/hello/tasks/solana/gateway.json (1 hunks)
Files skipped from review due to trivial changes (1)
  • universal/hello/package.json
Additional comments not posted (12)
universal/hello/hardhat.config.ts (1)

1-7: Imports and Configuration Settings are Correctly Implemented

The imports are well-organized and relevant to the project's needs. The configuration settings are appropriately set up, ensuring that the project is ready for development and deployment on ZetaChain and other networks.

Also applies to: 9-10, 12-16

universal/hello/contracts/ReceiverContract.sol (1)

9-23: Contract Implementation is Correct and Well-Designed

The ReceiverContract is well-structured with appropriate event declarations and function implementations for handling messages and revert scenarios. The inclusion of receive and fallback functions is a good practice for handling Ether transactions.

universal/hello/contracts/Hello.sol (1)

11-50: Contract Design and Implementation are Robust

The Hello contract is effectively designed for cross-chain interactions with appropriate event logging and error handling mechanisms. The implementation of functions for cross-chain calls and reverts is well-executed.

universal/hello/tasks/depositAndCall.ts (4)

1-3: Imports are correctly structured.

The import statements are appropriate for the task, ensuring that necessary modules and types are available.


5-12: Function setup is well-implemented.

The async function setup is correct, and the use of args and hre to interact with the blockchain environment is appropriate. The retrieval of the signer and the instantiation of the contract using GatewayABI are correctly implemented.


14-36: Encoding and transaction setup are secure and efficient.

The use of hre.ethers.utils for encoding and setting up transaction parameters is correctly implemented. The parameters for the transaction, including gasPrice, gasLimit, and value, are appropriately set, ensuring efficient and secure transactions.


47-58: Task registration is complete and well-documented.

The task is correctly registered with Hardhat, and all parameters are appropriately defined, including optional and required ones. The documentation for each parameter is clear, aiding developers in understanding their usage.

universal/hello/flat (3)

22-30: Ensure consistency in struct documentation.

The RevertContext struct is well-documented with @param tags. Ensure that all structs in the codebase follow a similar documentation standard to maintain consistency and clarity for developers.


32-38: Interface definition is clear and concise.

The Revertable interface is clearly defined with a single function onRevert. This is a good practice as it keeps interfaces focused and understandable.


119-157: Error handling is comprehensive, but ensure consistency.

The error interfaces in IGatewayZEVMErrors cover a wide range of potential issues. Ensure that these errors are consistently handled across all contracts that interact with the GatewayZEVM to prevent unhandled exceptions and enhance reliability.

universal/hello/tasks/callFromZetaChain.ts (1)

4-57: Review of the call-from-zetachain task implementation

  1. Input Validation: The existing comment about validating args.contract is still valid and should be implemented to prevent runtime errors. The same validation should be applied to args.zrc20 since it is also an Ethereum address.

  2. Error Handling: The existing comment about enhancing error handling with more informative messages remains relevant. It's crucial to provide detailed error messages to aid in debugging, especially in a blockchain context where transactions are irreversible.

  3. Gas Settings: The hardcoded gas price and limit (lines 31, 32, 48, 49) could be made configurable to adapt to different network conditions or user preferences. Consider adding parameters for these values or fetching them from a reliable source.

  4. Use of Hardcoded Address: The abortAddress is hardcoded as a zero address (line 44), which is typically used to indicate an unused parameter. If this is intentional, it should be clearly documented to avoid confusion.

  5. Logging: The success message in line 54 is clear, but consider also logging the transaction hash to provide a traceable reference for the operation.

  6. Function Signature and Encoding: The way the function signature and parameters are encoded (lines 19-27) is correct but ensure that the hello(string) function is implemented as expected on the smart contract side to match this encoding.

  7. Task Configuration: The task parameters are well-defined (lines 60-76). However, the use of types.int for gasLimit is appropriate, but ensure that all user inputs are validated, especially for optional parameters like zrc20.

Overall, the task script is well-structured and covers the essential functionalities required for interacting with the ZetaChain. Implementing the suggested improvements will enhance its robustness and usability.

The overall structure and logic of the task are sound, but the suggested improvements should be considered to enhance its functionality.

universal/hello/tasks/solana/gateway.json (1)

1-496: Review of the gateway.json configuration for Solana

  1. Instruction Definitions: Each instruction (e.g., deposit, withdraw) is well-defined with appropriate discriminators and account specifications. Ensure that the discriminators are unique and correctly map to the intended instructions in the Solana program.

  2. Error Definitions: The error codes and messages (lines 416-460) are clearly defined. It's important that these errors are handled appropriately in the client and contract code to provide meaningful feedback to the user.

  3. Account Specifications: The account configurations (e.g., lines 23-36 for deposit) are detailed, specifying whether accounts are writable or signers. This is crucial for ensuring the correct permissions and behavior during transaction execution.

  4. Type Definitions: The type definitions (lines 462-496) are crucial for ensuring that the data structures used in the program are well-understood and correctly implemented. The use of complex types like arrays and structs needs careful handling in the Solana program to avoid issues during serialization and deserialization.

  5. Documentation and Versioning: The metadata section (lines 3-8) provides basic information about the program. Consider including more detailed documentation, especially regarding the specific version compatibilities and any dependencies.

  6. Security Considerations: Given the nature of blockchain applications, ensure that all security aspects are thoroughly reviewed, especially concerning account permissions and transaction validations.

Overall, the JSON configuration is comprehensive and appears to be correctly structured for use with a Solana program. Further integration testing and security audits are recommended to ensure that it functions as expected in a live environment.

The configuration is well-structured and detailed, providing a solid foundation for the Solana program. Further testing and audits are advised to ensure robustness and security.

Comment on lines +11 to +50
contract Hello is UniversalContract {
event HelloEvent(string, string);
event ContextDataRevert(RevertContext);

address constant gatewayAddress =
0x610178dA211FEF7D417bC0e6FeD39F05609AD788;

function onCrossChainCall(
zContext calldata context,
address zrc20,
uint256 amount,
bytes calldata message
) external override {
string memory decodedMessage;
if (message.length > 0) {
decodedMessage = abi.decode(message, (string));
}
emit HelloEvent("Hello from a universal app", decodedMessage);
}

function callFromZetaChain(
bytes memory receiver,
address zrc20,
bytes calldata message,
uint256 gasLimit,
RevertOptions memory revertOptions
) external {
IZRC20(zrc20).approve(gatewayAddress, 1_000_000_000);
IGatewayZEVM(gatewayAddress).call(
receiver,
zrc20,
message,
gasLimit,
revertOptions
);
}

function onRevert(RevertContext calldata revertContext) external override {
emit ContextDataRevert(revertContext);
}
Copy link

Choose a reason for hiding this comment

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

Consider Renaming gatewayAddress for Clarity

The contract is well-implemented with comprehensive logging and error handling. However, consider renaming the constant gatewayAddress to gatewayAddressZEVM for better clarity and alignment with its usage within ZetaChain environments, as suggested in a previous review.

Comment on lines +20 to +44
try {
const callTx = await gateway[
"depositAndCall(address,bytes,(address,bool,address,bytes))"
](
args.contract,
message,
{
revertAddress: args.revertAddress,
callOnRevert: args.callOnRevert,
abortAddress: "0x0000000000000000000000000000000000000000", // not used
revertMessage: hre.ethers.utils.hexlify(revertMessageBytes),
},
{
gasPrice: 10000000000,
gasLimit: 7000000,
value: hre.ethers.utils.parseEther(args.amount),
}
);
await callTx.wait();
console.log(
`Contract on ZetaChain called from EVM with ${args.amount} ETH`
);
} catch (e) {
console.error("Error calling contract:", e);
}
Copy link

Choose a reason for hiding this comment

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

Enhance error handling and logging for better debugging support.

While the transaction execution and waiting mechanism are correctly implemented, the error handling could be enhanced by providing more detailed error messages. This would aid in debugging and maintaining the system.

Consider adding more detailed error logging, such as:

catch (e) {
  console.error(`Error calling contract with message: ${args.message} and amount: ${args.amount} ETH`, e);
}

Comment on lines +5 to +20
// File @zetachain/protocol-contracts/contracts/[email protected]

// Original license: SPDX_License_Identifier: MIT
pragma solidity 0.8.26;

/// @notice Struct containing revert options
/// @param revertAddress Address to receive revert.
/// @param callOnRevert Flag if onRevert hook should be called.
/// @param abortAddress Address to receive funds if aborted.
/// @param revertMessage Arbitrary data sent back in onRevert.
struct RevertOptions {
address revertAddress;
bool callOnRevert;
address abortAddress;
bytes revertMessage;
}
Copy link

Choose a reason for hiding this comment

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

Consider using a library for common structures to reduce redundancy and enhance maintainability.

The RevertOptions struct is defined early in the file. If this struct or similar ones are used across multiple contracts within the project, consider defining them in a common library or contract and importing them where needed. This approach promotes code reusability and maintainability.

Comment on lines +159 to +318

/// @notice Call a smart contract on an external chain without asset transfer.
/// @param receiver The receiver address on the external chain.
/// @param zrc20 Address of zrc20 to pay fees.
/// @param message The calldata to pass to the contract call.
/// @param gasLimit Gas limit.
/// @param revertOptions Revert options.
function call(
bytes memory receiver,
address zrc20,
bytes calldata message,
uint256 gasLimit,
RevertOptions calldata revertOptions
)
external;

/// @notice Deposit foreign coins into ZRC20.
/// @param zrc20 The address of the ZRC20 token.
/// @param amount The amount of tokens to deposit.
/// @param target The target address to receive the deposited tokens.
function deposit(address zrc20, uint256 amount, address target) external;

/// @notice Execute a user-specified contract on ZEVM.
/// @param context The context of the cross-chain call.
/// @param zrc20 The address of the ZRC20 token.
/// @param amount The amount of tokens to transfer.
/// @param target The target contract to call.
/// @param message The calldata to pass to the contract call.
function execute(
zContext calldata context,
address zrc20,
uint256 amount,
address target,
bytes calldata message
)
external;

/// @notice Deposit foreign coins into ZRC20 and call a user-specified contract on ZEVM.
/// @param context The context of the cross-chain call.
/// @param zrc20 The address of the ZRC20 token.
/// @param amount The amount of tokens to transfer.
/// @param target The target contract to call.
/// @param message The calldata to pass to the contract call.
function depositAndCall(
zContext calldata context,
address zrc20,
uint256 amount,
address target,
bytes calldata message
)
external;

/// @notice Deposit ZETA and call a user-specified contract on ZEVM.
/// @param context The context of the cross-chain call.
/// @param amount The amount of tokens to transfer.
/// @param target The target contract to call.
/// @param message The calldata to pass to the contract call.
function depositAndCall(
zContext calldata context,
uint256 amount,
address target,
bytes calldata message
)
external;

/// @notice Revert a user-specified contract on ZEVM.
/// @param context The context of the revert call.
/// @param zrc20 The address of the ZRC20 token.
/// @param amount The amount of tokens to revert.
/// @param target The target contract to call.
/// @param message The calldata to pass to the contract call.
/// @param revertContext Revert context to pass to onRevert.
function executeRevert(
zContext calldata context,
address zrc20,
uint256 amount,
address target,
bytes calldata message,
RevertContext calldata revertContext
)
external;

/// @notice Deposit foreign coins into ZRC20 and revert a user-specified contract on ZEVM.
/// @param context The context of the revert call.
/// @param zrc20 The address of the ZRC20 token.
/// @param amount The amount of tokens to revert.
/// @param target The target contract to call.
/// @param message The calldata to pass to the contract call.
/// @param revertContext Revert context to pass to onRevert.
function depositAndRevert(
zContext calldata context,
address zrc20,
uint256 amount,
address target,
bytes calldata message,
RevertContext calldata revertContext
)
external;
}

Copy link

Choose a reason for hiding this comment

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

Consider optimizing contract interfaces for gas efficiency.

The IGatewayZEVM interface defines multiple functions for withdrawing and calling contracts on external chains. Consider combining similar functions to reduce the contract size and potentially save on gas costs during deployment and interaction.

Comment on lines +479 to +518
contract Hello is UniversalContract {
event HelloEvent(string, string);
event ContextDataRevert(RevertContext);

address constant gateway = 0x610178dA211FEF7D417bC0e6FeD39F05609AD788;

function onCrossChainCall(
zContext calldata context,
address zrc20,
uint256 amount,
bytes calldata message
) external override {
string memory decodedMessage;
if (message.length > 0) {
decodedMessage = abi.decode(message, (string));
}
emit HelloEvent("Hello from a universal app", decodedMessage);
}

function callFromZetaChain(
bytes memory receiver,
address zrc20,
bytes calldata message,
uint256 gasLimit,
RevertOptions memory revertOptions
) external {
IZRC20(zrc20).approve(gateway, 1_000_000_000);
IGatewayZEVM(gateway).call(
receiver,
zrc20,
message,
gasLimit,
revertOptions
);
}

function onRevert(RevertContext calldata revertContext) external override {
emit ContextDataRevert(revertContext);
}
}
Copy link

Choose a reason for hiding this comment

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

Review and optimize cross-chain call handling in the Hello contract.

The Hello contract implements the UniversalContract interface. The handling of cross-chain calls in onCrossChainCall should be reviewed to ensure that it correctly decodes and logs messages. Additionally, consider adding error handling for cases where message decoding fails.

@fadeev
Copy link
Member Author

fadeev commented Aug 29, 2024

@andresaiello please, review again.

@fadeev fadeev merged commit cdb40f3 into main Aug 31, 2024
12 checks passed
@fadeev fadeev deleted the localnet-examples branch August 31, 2024 01:04
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.

3 participants