Skip to content

chore: switch to context sender/senderEVM #257

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

Merged
merged 5 commits into from
May 6, 2025
Merged

chore: switch to context sender/senderEVM #257

merged 5 commits into from
May 6, 2025

Conversation

fadeev
Copy link
Member

@fadeev fadeev commented Apr 30, 2025

Depends on ZetaChain CLI with localnet that supports running in background and sender/senderEVM changes and on a stable version of protocol contracts.

  • Updated protocol contracts to v13
  • Updated zetachain CLI to v3 (which includes localnet v10)
  • Switched from Hardhat to ZetaChain CLI for running tests (disabled Solana for now as there is a bug Solana init fail when running localnet inside CLI localnet#165)
  • Replaced sleep 15 inside tests with a loop that checks when localnet.json becomes available

Summary by CodeRabbit

  • New Features

    • Updated dependencies to the latest versions and added the Zetachain CLI for improved localnet management.
  • Refactor

    • Transitioned localnet management scripts from Hardhat commands to Zetachain CLI commands, enhancing readiness checks and error handling.
    • Modified the Swap contract to use a flexible bytes type for sender addresses, improving compatibility and event handling.

Copy link

coderabbitai bot commented Apr 30, 2025

📝 Walkthrough

Walkthrough

This update transitions localnet management scripts across multiple example projects from Hardhat-based commands to the Zetachain CLI, introduces readiness checks for localnet startup, and updates dependencies to use the latest Zetachain packages. The Swap.sol contract now represents sender addresses as bytes instead of address, affecting event signatures and function interfaces.

Changes

File(s) Change Summary
examples/call/package.json,
examples/hello/package.json,
examples/swap/package.json
Updated @zetachain/protocol-contracts dependency from 12.0.0-rc1 to 13.0.0. Added new dependency zetachain at version ^3.0.0. No other modifications to scripts or metadata.
examples/call/scripts/localnet.sh,
examples/hello/scripts/localnet.sh,
examples/swap/scripts/localnet.sh
Replaced all Hardhat-based localnet management commands (npx hardhat ...) with Zetachain CLI equivalents (yarn zetachain ...). Introduced a readiness loop that waits for the creation of localnet.json before proceeding. Improved error handling by enabling pipefail in hello. Commented out or removed unnecessary or deprecated steps.
examples/swap/contracts/Swap.sol Changed all sender parameters and event fields from type address to bytes. Updated event signature, function parameters, ABI encoding/decoding, and revert handling logic accordingly. Adjusted internal logic to handle bytes sender representation, including casting and encoding where necessary.

Sequence Diagram(s)

Swap Contract: Token Swap and Revert Flow

sequenceDiagram
    participant User
    participant SwapContract
    participant Gateway

    User->>SwapContract: swap(params)
    SwapContract->>Gateway: emit TokenSwap(bytes sender, ...)
    Note right of SwapContract: sender is now bytes

    alt Revert Occurs
        Gateway->>SwapContract: onRevert(context)
        SwapContract->>Gateway: withdraw(..., bytes sender, ...)
        Note right of SwapContract: sender decoded as bytes and cast as needed
    end
Loading

Localnet Startup and Readiness Check (Script Flow)

sequenceDiagram
    participant Script
    participant ZetachainCLI

    Script->>ZetachainCLI: localnet start --skip sui,ton,solana --exit-on-error
    loop until localnet.json exists
        Script->>Script: sleep 1
    end
    Script->>ZetachainCLI: localnet check
    Script->>ZetachainCLI: localnet stop
Loading

Issue Highlight:
The migration from address to bytes for sender representation in the smart contract is a breaking change and requires thorough downstream audit for compatibility. Additionally, scripts now depend on the Zetachain CLI, which must be ensured present and properly configured in all environments.

Recommendation:
For production-grade robustness, validate bytes sender inputs for expected length and format, and centralize readiness checks into a reusable shell function to eliminate duplication and potential inconsistencies across scripts.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@fadeev fadeev marked this pull request as ready for review May 6, 2025 09:55
@fadeev fadeev requested a review from a team as a code owner May 6, 2025 09:55
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 comments (3)
examples/swap/scripts/localnet.sh (1)

244-244: 🛠️ Refactor suggestion

Wait for CLI shutdown.

After stopping the localnet, explicitly wait on the background PID:

yarn zetachain localnet stop
wait $LOCALNET_PID

This ensures the process fully exits before the script terminates.

examples/swap/contracts/Swap.sol (2)

261-265: ⚠️ Potential issue

Compile error – IWETH9 is neither imported nor required here
IWETH9 is referenced, but the contract only imports IZRC20/IERC20.
Unless you deliberately depend on a wrapped-Zeta interface, this line will not compile.
Using IZRC20 (already imported) is sufficient because it exposes transfer.

-            bool success = IWETH9(params.target).transfer(
+            bool success = IZRC20(params.target).transfer(
                 address(uint160(bytes20(params.to))),
                 out
             );

317-318: ⚠️ Potential issue

Undefined interface – replace IUniswapV2Router01 with IUniswapV2Router02
IUniswapV2Router01 is not imported, while Router 02 is. Casting to the imported interface resolves the compile error and keeps the behaviour identical.

-        address zeta = IUniswapV2Router01(uniswapRouter).WETH();
+        address zeta = IUniswapV2Router02(uniswapRouter).WETH();
🧹 Nitpick comments (4)
examples/call/scripts/localnet.sh (1)

39-242: DRY out repeated readiness checks.

The script invokes yarn zetachain localnet check over a dozen times. Extract this into a helper function for clarity and maintainability:

check_localnet() {
  yarn zetachain localnet check
}

# Then replace each invocation with:
check_localnet
examples/swap/scripts/localnet.sh (2)

38-136: Factor out the repeated localnet check calls.

You invoke yarn zetachain localnet check many times; extract it into a function:

run_check() {
  yarn zetachain localnet check
}

# Then replace each occurrence with:
run_check

This reduces duplication and improves readability.


86-96: Clean up obsolete commented code.

There’s a block of commented Hardhat and localnet commands for SUI/Solana flows. If they’re not needed, remove or archive them to keep the script concise.

examples/swap/contracts/Swap.sol (1)

118-126: Consider indexing the sender field or emitting both forms
Changing sender from address indexed to bytes makes filtering for a specific sender in logs harder (bytes is not index-able).
If off-chain consumers still need efficient queries, emit an auxiliary event or keep the field indexed when the length is exactly 20 bytes.

No diff provided – design choice.

Also applies to: 156-164

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b3876a2 and 3096a26.

⛔ Files ignored due to path filters (3)
  • examples/call/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • examples/hello/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • examples/swap/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (7)
  • examples/call/package.json (1 hunks)
  • examples/call/scripts/localnet.sh (20 hunks)
  • examples/hello/package.json (1 hunks)
  • examples/hello/scripts/localnet.sh (2 hunks)
  • examples/swap/contracts/Swap.sol (6 hunks)
  • examples/swap/package.json (1 hunks)
  • examples/swap/scripts/localnet.sh (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: slither (examples/swap, swap.sarif)
  • GitHub Check: slither (examples/call, call.sarif)
  • GitHub Check: slither (examples/hello, hello.sarif)
🔇 Additional comments (4)
examples/call/package.json (1)

61-64: Dependency version upgrades are consistent.

The bump of @zetachain/protocol-contracts to 13.0.0 and addition of zetachain@^3.0.0 align with the other examples. Ensure that the @zetachain/networks package remaining at 13.0.0-rc1 is intentional and compatible with these stable versions.

examples/hello/package.json (1)

60-62: Dependencies match the overall upgrade.

The update to @zetachain/[email protected] and addition of zetachain@^3.0.0 mirror the other example projects. No further changes needed here.

examples/swap/package.json (1)

60-63: Confirm runtime versus dev dependency for @zetachain/toolkit.

Unlike the other examples, swap places @zetachain/[email protected] in dependencies. Verify if it’s required at runtime; otherwise, consider moving it to devDependencies to reduce bundle size.

examples/hello/scripts/localnet.sh (1)

3-5: Ensure clean shutdown with a trap
The localnet is started in the background (&) but the script does not guarantee that it is stopped if the script exits early (e.g., on error or CTRL-C). This can leave orphaned processes listening on the same ports and flake subsequent runs.

 set -e
 set -x
 set -o pipefail
+
+cleanup() {
+  # Stop localnet gracefully; ignore errors if it is already stopped
+  yarn zetachain localnet stop || true
+}
+trap cleanup EXIT

[ suggest_essential_refactor ]

Also applies to: 25-27

yarn zetachain localnet stop
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure graceful shutdown.

After yarn zetachain localnet stop, wait on the background process to avoid race conditions:

yarn zetachain localnet stop
wait $LOCALNET_PID

Comment on lines +7 to +9
yarn zetachain localnet start --skip sui ton solana --exit-on-error &

while [ ! -f "localnet.json" ]; do sleep 1; done
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Capture and trap the background process.

Running the CLI in the background without tracking its PID can lead to orphaned processes. Consider:

yarn zetachain localnet start --skip sui ton solana --exit-on-error &
LOCALNET_PID=$!
trap "kill $LOCALNET_PID" EXIT

This ensures proper cleanup on script exit.

Comment on lines +7 to +9
yarn zetachain localnet start --skip sui ton solana --exit-on-error &

while [ ! -f "localnet.json" ]; do sleep 1; done
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Manage the background CLI process.

Similar to the call example, capture the PID and trap cleanup:

yarn zetachain localnet start --skip sui ton solana --exit-on-error &
LOCALNET_PID=$!
trap "kill $LOCALNET_PID" EXIT

This prevents orphaned processes if the script is aborted.

Comment on lines +7 to +9
yarn zetachain localnet start --skip sui ton solana --exit-on-error &

while [ ! -f "localnet.json" ]; do sleep 1; done
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 a timeout / readiness guard to avoid hanging forever
The loop waits indefinitely for localnet.json. If yarn zetachain localnet start fails or the file is written elsewhere, the script will block forever and the CI job (or developer terminal) will never complete.

-while [ ! -f "localnet.json" ]; do sleep 1; done
+# Wait up to 90 s for the localnet to become ready
+MAX_WAIT=90
+elapsed=0
+until [ -f "localnet.json" ] || [ "$elapsed" -ge "$MAX_WAIT" ]; do
+  sleep 1
+  elapsed=$((elapsed+1))
+done
+
+if [ ! -f "localnet.json" ]; then
+  echo "❌ localnet did not start in time" >&2
+  exit 1
+fi
📝 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
yarn zetachain localnet start --skip sui ton solana --exit-on-error &
while [ ! -f "localnet.json" ]; do sleep 1; done
yarn zetachain localnet start --skip sui ton solana --exit-on-error &
# Wait up to 90 s for the localnet to become ready
MAX_WAIT=90
elapsed=0
until [ -f "localnet.json" ] || [ "$elapsed" -ge "$MAX_WAIT" ]; do
sleep 1
elapsed=$((elapsed+1))
done
if [ ! -f "localnet.json" ]; then
echo "❌ localnet did not start in time" >&2
exit 1
fi

Comment on lines +294 to 296
revertAddress: address(bytes20(sender)),
callOnRevert: false,
abortAddress: address(0),
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate sender length before casting to address
address(bytes20(sender)) silently truncates/zero-pads if sender.length ≠ 20, which could mis-route funds on revert.

-                revertAddress: address(bytes20(sender)),
+                revertAddress: sender.length == 20
+                    ? address(bytes20(sender))
+                    : address(0), // fallback / sentinel

Add a require/revert if an unexpected length is encountered to fail fast.

📝 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
revertAddress: address(bytes20(sender)),
callOnRevert: false,
abortAddress: address(0),
revertAddress: sender.length == 20
? address(bytes20(sender))
: address(0), // fallback / sentinel
callOnRevert: false,
abortAddress: address(0),

"@zetachain/protocol-contracts": "12.0.0-rc1",
"@zetachain/protocol-contracts-solana": "2.0.0-rc1"
"@zetachain/protocol-contracts": "13.0.0",
"@zetachain/protocol-contracts-solana": "2.0.0-rc1",
Copy link
Collaborator

Choose a reason for hiding this comment

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

we are already on 3.0.0 here so might be worth checking to upgrade this as well in separate PR

Copy link
Member Author

Choose a reason for hiding this comment

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

Will do!

npx hardhat compile --force --quiet

ZRC20_ETHEREUM=$(jq -r '.addresses[] | select(.type=="ZRC-20 ETH on 5") | .address' localnet.json)
USDC_ETHEREUM=$(jq -r '.addresses[] | select(.type=="ERC-20 USDC" and .chain=="ethereum") | .address' localnet.json)
ZRC20_USDC=$(jq -r '.addresses[] | select(.type=="ZRC-20 USDC on 97") | .address' localnet.json)
ZRC20_BNB=$(jq -r '.addresses[] | select(.type=="ZRC-20 BNB on 97") | .address' localnet.json)
ZRC20_SOL=$(jq -r '.addresses[] | select(.type=="ZRC-20 SOL on 901") | .address' localnet.json)
# ZRC20_SOL=$(jq -r '.addresses[] | select(.type=="ZRC-20 SOL on 901") | .address' localnet.json)
Copy link
Collaborator

Choose a reason for hiding this comment

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

just to double check if this should be commented out, same for other sol related commented 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.

It should yes. I'll enable Solana tests after I figure out why it's failing when running in the CLI.

@fadeev fadeev merged commit a7fef3d into main May 6, 2025
17 checks passed
@fadeev fadeev deleted the context-sender branch May 6, 2025 11:38
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