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

Added gateway call to examples #200

Merged
merged 2 commits into from
Oct 3, 2024
Merged

Added gateway call to examples #200

merged 2 commits into from
Oct 3, 2024

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Sep 27, 2024

  • Added gatewayCall function to Hello to showcase how you can run gateway.call from a universal app
  • Added gateway-call task
  • Updated localnet
  • Imported Solana deposit task from toolkit

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a gatewayCall function in the Hello contract for cross-chain interactions.
    • Added a Hardhat task gateway-call to facilitate calling the gatewayCall function.
  • Bug Fixes

    • Updated dependency version for @zetachain/localnet to ensure compatibility and improvements.
  • Removals

    • Removed outdated Solana-related tasks and configurations to streamline the project.

Copy link

coderabbitai bot commented Sep 27, 2024

📝 Walkthrough

Walkthrough

The pull request introduces a new function gatewayCall to the Hello contract, enabling cross-chain interactions. It includes modifications to the Hardhat configuration and the addition of a new Hardhat task for executing the gatewayCall function. Several files related to Solana interactions, including tasks and configuration files, have been deleted, streamlining the project by removing outdated functionality. Additionally, dependency versions in the package.json files have been updated to ensure compatibility with the latest features.

Changes

File Path Change Summary
examples/hello/contracts/Hello.sol Added method gatewayCall(bytes memory receiver, address zrc20, bytes calldata message, uint256 gasLimit, RevertOptions memory revertOptions) in Hello contract.
examples/hello/hardhat.config.ts Removed import of interact module; added import of gatewayCall module.
examples/hello/package.json Updated dependency version: @zetachain/localnet from 3.0.3 to ^3.0.4.
examples/hello/tasks/gatewayCall.ts Added new Hardhat task gateway-call for executing gatewayCall function in the Hello contract.
examples/hello/tasks/solana/deposit.ts Removed file containing the deposit function for Solana.
examples/hello/tasks/solana/gateway.json Deleted file containing configuration for Solana-based gateway application.
examples/hello/tasks/solana/interact.ts Removed Hardhat task interact-solana.
examples/swap/package.json Updated dependency version: @zetachain/localnet from 3.0.2 to ^3.0.4.
examples/swap/tasks/solana/deposit.ts Removed file containing the deposit function for Solana.
examples/swap/tasks/solana/gateway.json Deleted file containing configuration for Solana-based gateway application.
examples/swap/tasks/solana/interact.ts Removed Hardhat task interact-solana.

Possibly related PRs

Suggested reviewers

  • andresaiello

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.

Comment on lines +33 to +43
function gatewayCall(
bytes memory receiver,
address zrc20,
bytes calldata message,
uint256 gasLimit,
RevertOptions memory revertOptions
) external {
(, uint256 gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit);
IZRC20(zrc20).approve(address(gateway), gasFee);
gateway.call(receiver, zrc20, message, gasLimit, revertOptions);
}

Check warning

Code scanning / Slither

Unused return Medium

Comment on lines +33 to +43
function gatewayCall(
bytes memory receiver,
address zrc20,
bytes calldata message,
uint256 gasLimit,
RevertOptions memory revertOptions
) external {
(, uint256 gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit);
IZRC20(zrc20).approve(address(gateway), gasFee);
gateway.call(receiver, zrc20, message, gasLimit, revertOptions);
}

Check warning

Code scanning / Slither

Unused return Medium

@fadeev fadeev marked this pull request as ready for review October 2, 2024 14:03
@fadeev fadeev requested a review from andresaiello as a code owner October 2, 2024 14:03
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: 8

🧹 Outside diff range and nitpick comments (2)
examples/hello/tasks/gatewayCall.ts (2)

31-37: Simplify and enhance boolean value parsing

Using JSON.parse for boolean conversion can be unreliable. A direct comparison offers clarity and reduces potential errors.

Refactor the boolean parsing logic:

if (type === "bool") {
-  try {
-    return JSON.parse(value.toLowerCase());
-  } catch (e) {
-    throw new Error(`Invalid boolean value: ${value}`);
-  }
+  const lowerValue = value.toLowerCase();
+  if (lowerValue === "true") {
+    return true;
+  } else if (lowerValue === "false") {
+    return false;
+  } else {
+    throw new Error(`Invalid boolean value: ${value}`);
+  }

89-89: Correct typographical error in parameter description

There's a duplication in the description of the gasLimit parameter.

Amend the description for clarity:

-    "Gas limit for for a cross-chain call",
+    "Gas limit for a cross-chain call",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8421cef and d96433b.

⛔ Files ignored due to path filters (2)
  • examples/hello/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • examples/swap/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (11)
  • examples/hello/contracts/Hello.sol (1 hunks)
  • examples/hello/hardhat.config.ts (1 hunks)
  • examples/hello/package.json (2 hunks)
  • examples/hello/tasks/gatewayCall.ts (1 hunks)
  • examples/hello/tasks/solana/deposit.ts (0 hunks)
  • examples/hello/tasks/solana/gateway.json (0 hunks)
  • examples/hello/tasks/solana/interact.ts (0 hunks)
  • examples/swap/package.json (1 hunks)
  • examples/swap/tasks/solana/deposit.ts (0 hunks)
  • examples/swap/tasks/solana/gateway.json (0 hunks)
  • examples/swap/tasks/solana/interact.ts (0 hunks)
💤 Files with no reviewable changes (6)
  • examples/hello/tasks/solana/deposit.ts
  • examples/hello/tasks/solana/gateway.json
  • examples/hello/tasks/solana/interact.ts
  • examples/swap/tasks/solana/deposit.ts
  • examples/swap/tasks/solana/gateway.json
  • examples/swap/tasks/solana/interact.ts
✅ Files skipped from review due to trivial changes (1)
  • examples/hello/hardhat.config.ts
🧰 Additional context used
🪛 GitHub Check: Slither
examples/hello/contracts/Hello.sol

[warning] 33-43: Unused return
Hello.gatewayCall(bytes,address,bytes,uint256,RevertOptions) (contracts/Hello.sol#33-43) ignores return value by (None,gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit) (contracts/Hello.sol#40)


[warning] 33-43: Unused return
Hello.gatewayCall(bytes,address,bytes,uint256,RevertOptions) (contracts/Hello.sol#33-43) ignores return value by IZRC20(zrc20).approve(address(gateway),gasFee) (contracts/Hello.sol#41)

🔇 Additional comments (2)
examples/swap/package.json (1)

31-31: Verify implications of @zetachain/localnet version update

The @zetachain/localnet dependency has been updated from version "3.0.2" to "^3.0.4". This change allows for minor version updates, which may introduce new features or bug fixes.

To ensure this update aligns with the project's stability requirements:

  1. Review the changelog for @zetachain/localnet versions 3.0.3 and 3.0.4.
  2. Verify that no breaking changes are introduced.
  3. Consider the potential impact on the local development environment.

If the changes are deemed acceptable, this update is appropriate. Otherwise, consider pinning the version to "3.0.2" or updating to a specific newer version.

examples/hello/tasks/gatewayCall.ts (1)

67-67: Confirm the format of 'args.receiver'

Using ethers.utils.hexlify on args.receiver assumes it's in the correct format. If args.receiver is already a hexadecimal address string, this may not be necessary.

Ensure that args.receiver is appropriately formatted. If it's a standard address, consider removing ethers.utils.hexlify:

-    ethers.utils.hexlify(args.receiver),
+    args.receiver,

If a byte array or specific encoding is required, verify that hexlify is the correct method.

@@ -28,7 +28,7 @@
"@types/node": ">=12.0.0",
"@typescript-eslint/eslint-plugin": "^5.59.9",
"@typescript-eslint/parser": "^5.59.9",
"@zetachain/localnet": "3.0.3",
"@zetachain/localnet": "^3.0.4",
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistent @zetachain/localnet Dependency Versions Detected

The @zetachain/localnet dependency has differing versions across the project:

  • examples/hello/package.json: "^3.0.4"
  • examples/swap/package.json: "^3.0.4"
  • omnichain/swap/package.json: "^1.0.1"

Please update omnichain/swap/package.json to use @zetachain/localnet version "^3.0.4" to ensure consistency and compatibility throughout the project.

🔗 Analysis chain

Approved: @zetachain/localnet dependency update.

The update of @zetachain/localnet from "3.0.3" to "^3.0.4" is appropriate. The use of the caret (^) allows for compatible updates, which is a recommended practice for dependencies.

To ensure consistency across the project, please run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify @zetachain/localnet version consistency across the project

# Test: Search for @zetachain/localnet dependency in all package.json files
rg --type json '"@zetachain/localnet":\s*"[^"]+"' -g 'package.json'

Length of output: 261

Comment on lines +33 to +43
function gatewayCall(
bytes memory receiver,
address zrc20,
bytes calldata message,
uint256 gasLimit,
RevertOptions memory revertOptions
) external {
(, uint256 gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit);
IZRC20(zrc20).approve(address(gateway), gasFee);
gateway.call(receiver, zrc20, message, gasLimit, revertOptions);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate Input Parameters to Enhance Security and Reliability

The gatewayCall function does not perform validation on its input parameters. It's recommended to add checks to ensure:

  • receiver is a valid non-empty value.
  • zrc20 is a valid contract address implementing the IZRC20 interface.
  • gasLimit is within acceptable bounds to prevent excessive gas consumption.

Implementing input validation enhances the security and reliability of the contract.

Apply the following diff to add input validation:

 function gatewayCall(
     bytes memory receiver,
     address zrc20,
     bytes calldata message,
     uint256 gasLimit,
     RevertOptions memory revertOptions
 ) external [onlyOwner] {
+    require(receiver.length > 0, "Invalid receiver");
+    require(zrc20 != address(0), "Invalid ZRC20 address");
+    require(gasLimit > 0, "Gas limit must be greater than zero");

     (, uint256 gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit);
     IZRC20(zrc20).approve(address(gateway), gasFee);
     gateway.call(receiver, zrc20, message, gasLimit, revertOptions);
 }

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 GitHub Check: Slither

[warning] 33-43: Unused return
Hello.gatewayCall(bytes,address,bytes,uint256,RevertOptions) (contracts/Hello.sol#33-43) ignores return value by (None,gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit) (contracts/Hello.sol#40)


[warning] 33-43: Unused return
Hello.gatewayCall(bytes,address,bytes,uint256,RevertOptions) (contracts/Hello.sol#33-43) ignores return value by IZRC20(zrc20).approve(address(gateway),gasFee) (contracts/Hello.sol#41)


⚠️ Potential issue

Add Access Control to 'gatewayCall' Function to Prevent Unauthorized Access

The gatewayCall function is marked as external and can be invoked by any account. To enhance security and prevent unauthorized usage, consider adding access control mechanisms, such as an onlyOwner modifier, to restrict access to authorized users.

Apply the following diff to implement access control using OpenZeppelin's Ownable contract:

+import "@openzeppelin/contracts/access/Ownable.sol";

 contract Hello is UniversalContract, Ownable {
     GatewayZEVM public gateway;

     constructor(address payable gatewayAddress) {
         gateway = GatewayZEVM(gatewayAddress);
     }

     ...

     function gatewayCall(
         bytes memory receiver,
         address zrc20,
         bytes calldata message,
         uint256 gasLimit,
         RevertOptions memory revertOptions
-    ) external {
+    ) external onlyOwner {
         (, uint256 gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit);
         IZRC20(zrc20).approve(address(gateway), gasFee);
         gateway.call(receiver, zrc20, message, gasLimit, revertOptions);
     }
 }

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 GitHub Check: Slither

[warning] 33-43: Unused return
Hello.gatewayCall(bytes,address,bytes,uint256,RevertOptions) (contracts/Hello.sol#33-43) ignores return value by (None,gasFee) = IZRC20(zrc20).withdrawGasFeeWithGasLimit(gasLimit) (contracts/Hello.sol#40)


[warning] 33-43: Unused return
Hello.gatewayCall(bytes,address,bytes,uint256,RevertOptions) (contracts/Hello.sol#33-43) ignores return value by IZRC20(zrc20).approve(address(gateway),gasFee) (contracts/Hello.sol#41)

Comment on lines +26 to +27
const types = JSON.parse(args.types);

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for JSON parsing of 'args.types'

Currently, the code assumes that args.types is a valid JSON string. If it's malformed, JSON.parse will throw an exception, potentially causing the task to fail unexpectedly.

Implement error handling to manage parsing exceptions gracefully:

+let types;
+try {
+  types = JSON.parse(args.types);
+} catch (error) {
+  throw new Error(`Invalid JSON string for 'types' parameter: ${error.message}`);
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const types = JSON.parse(args.types);
let types;
try {
types = JSON.parse(args.types);
} catch (error) {
throw new Error(`Invalid JSON string for 'types' parameter: ${error.message}`);
}

Comment on lines +37 to +38
} else if (type.startsWith("uint") || type.startsWith("int")) {
return ethers.BigNumber.from(value);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement error handling for numeric value conversion

Converting value to a BigNumber may throw an error if the input is invalid. It's prudent to handle such exceptions.

Add a try-catch block to manage conversion errors:

} else if (type.startsWith("uint") || type.startsWith("int")) {
-  return ethers.BigNumber.from(value);
+  try {
+    return ethers.BigNumber.from(value);
+  } catch (error) {
+    throw new Error(`Invalid numeric value for type '${type}': ${value}`);
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} else if (type.startsWith("uint") || type.startsWith("int")) {
return ethers.BigNumber.from(value);
} else if (type.startsWith("uint") || type.startsWith("int")) {
try {
return ethers.BigNumber.from(value);
} catch (error) {
throw new Error(`Invalid numeric value for type '${type}': ${value}`);
}

Comment on lines +54 to +61
const [, gasFee] = await zrc20.withdrawGasFeeWithGasLimit(gasLimit);
const zrc20TransferTx = await zrc20.transfer(
args.contract,
gasFee,
txOptions
);

await zrc20TransferTx.wait();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for contract interactions with ZRC20

Operations like withdrawGasFeeWithGasLimit and transfer can fail due to various reasons. Ensuring these failures are caught will enhance the robustness of the task.

Wrap the contract calls in try-catch blocks:

+try {
  const [, gasFee] = await zrc20.withdrawGasFeeWithGasLimit(gasLimit);
+} catch (error) {
+  throw new Error(`Failed to withdraw gas fee: ${error.message}`);
+}

+try {
  const zrc20TransferTx = await zrc20.transfer(
    args.contract,
    gasFee,
    txOptions
  );

  await zrc20TransferTx.wait();
+} catch (error) {
+  throw new Error(`Failed to transfer gas fee: ${error.message}`);
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [, gasFee] = await zrc20.withdrawGasFeeWithGasLimit(gasLimit);
const zrc20TransferTx = await zrc20.transfer(
args.contract,
gasFee,
txOptions
);
await zrc20TransferTx.wait();
try {
const [, gasFee] = await zrc20.withdrawGasFeeWithGasLimit(gasLimit);
} catch (error) {
throw new Error(`Failed to withdraw gas fee: ${error.message}`);
}
try {
const zrc20TransferTx = await zrc20.transfer(
args.contract,
gasFee,
txOptions
);
await zrc20TransferTx.wait();
} catch (error) {
throw new Error(`Failed to transfer gas fee: ${error.message}`);
}

Comment on lines +66 to +77
const tx = await contract.gatewayCall(
ethers.utils.hexlify(args.receiver),
args.zrc20,
message,
gasLimit,
revertOptions,
txOptions
);

console.log(`Transaction hash: ${tx.hash}`);
await tx.wait();
console.log("gatewayCall executed successfully");
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure proper error handling for the 'gatewayCall' transaction

The invocation of gatewayCall may encounter errors. Implementing error handling will prevent unhandled promise rejections and provide clearer error messaging.

Encapsulate the transaction in a try-catch block:

+try {
  const tx = await contract.gatewayCall(
    ethers.utils.hexlify(args.receiver),
    args.zrc20,
    message,
    gasLimit,
    revertOptions,
    txOptions
  );

  console.log(`Transaction hash: ${tx.hash}`);
  await tx.wait();
  console.log("gatewayCall executed successfully");
+} catch (error) {
+  throw new Error(`Failed to execute 'gatewayCall': ${error.message}`);
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const tx = await contract.gatewayCall(
ethers.utils.hexlify(args.receiver),
args.zrc20,
message,
gasLimit,
revertOptions,
txOptions
);
console.log(`Transaction hash: ${tx.hash}`);
await tx.wait();
console.log("gatewayCall executed successfully");
try {
const tx = await contract.gatewayCall(
ethers.utils.hexlify(args.receiver),
args.zrc20,
message,
gasLimit,
revertOptions,
txOptions
);
console.log(`Transaction hash: ${tx.hash}`);
await tx.wait();
console.log("gatewayCall executed successfully");
} catch (error) {
throw new Error(`Failed to execute 'gatewayCall': ${error.message}`);
}


const types = JSON.parse(args.types);

const valuesArray = args.values.map((value: any, index: number) => {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate that 'types' and 'values' arrays have the same length

To prevent runtime errors, ensure that the types array and args.values have the same length before proceeding.

Add a length check after parsing types:

const types = JSON.parse(args.types);

+if (types.length !== args.values.length) {
+  throw new Error(
+    `Mismatch between number of types (${types.length}) and values (${args.values.length})`
+  );
+}

Committable suggestion was skipped due to low confidence.

@fadeev fadeev merged commit 2f1b130 into main Oct 3, 2024
10 checks passed
@fadeev fadeev deleted the gateway-call branch October 3, 2024 06:51
@coderabbitai coderabbitai bot mentioned this pull request Oct 3, 2024
This was referenced Oct 14, 2024
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