Skip to content

Add context.log support for contractRegister#624

Merged
DZakh merged 3 commits into
mainfrom
dz/contract-register-context-log
Jul 7, 2025
Merged

Add context.log support for contractRegister#624
DZakh merged 3 commits into
mainfrom
dz/contract-register-context-log

Conversation

@DZakh

@DZakh DZakh commented Jul 7, 2025

Copy link
Copy Markdown
Member

Closes #620

Summary by CodeRabbit

  • New Features

    • Added contract registration context and proxy-based handler support to user context, enabling dynamic contract registration with logging capabilities.
    • Introduced a mapping from contract registration method names to contract names in the configuration for easier contract management.
  • Bug Fixes

    • Updated contract registration flow to require and utilize configuration context, ensuring correct context is passed throughout contract registration processes.
    • Added address validation and checksum enforcement for contract addresses during registration, improving error handling and data integrity.
  • Refactor

    • Removed legacy contract registration context from the dynamic template in favor of the new static implementation.
  • Style

    • Improved type safety for logging context in event handler tests.
  • Tests

    • Added tests verifying error handling for invalid contract addresses and checksum normalization for valid addresses during contract registration.

@coderabbitai

coderabbitai Bot commented Jul 7, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change deletes the old contract registration context implementation, adds a proxied context for contract registration that includes a log field, updates type definitions, and ensures the logger is surfaced on the contractRegistrations context. Function signatures and usages are updated to require configuration objects, and type checks are added in tests.

Changes

File(s) Change Summary
codegenerator/cli/templates/dynamic/codegen/src/ContextEnv.res.hbs Deleted file; removed old contract registration context and argument functions.
codegenerator/cli/templates/dynamic/codegen/src/TestHelpers_MockDb.res.hbs Updated call to ChainFetcher.runContractRegistersOrThrow to pass config argument.
codegenerator/cli/templates/dynamic/codegen/src/Types.res.hbs Added log: Envio.logger field to contractRegistrations type.
codegenerator/cli/templates/static/codegen/src/Config.res Added addContractNameToContractNameMapping field and logic to build this mapping in config t and make.
codegenerator/cli/templates/static/codegen/src/UserContext.res Added proxied contract registration context, traps, new types, and functions for contract registration.
codegenerator/cli/templates/static/codegen/src/eventFetching/ChainFetcher.res Updated runContractRegistersOrThrow to require and propagate config; switched to new context/args logic.
codegenerator/cli/templates/static/codegen/src/globalState/GlobalState.res Updated call to runContractRegistersOrThrow to pass config from state.
scenarios/test_codegen/src/EventHandlers.ts Added type assertion to ensure context.log is of type Logger in contract registration handler.
scenarios/test_codegen/test/EventHandler_test.ts Added tests for invalid address error and address checksum validation in contract registration.

Sequence Diagram(s)

sequenceDiagram
    participant GlobalState
    participant ChainFetcher
    participant UserContext
    participant ContractRegisterHandler

    GlobalState->>ChainFetcher: runContractRegistersOrThrow(~reversedWithContractRegister, ~config)
    ChainFetcher->>UserContext: getContractRegisterArgs(~onRegister, ~config)
    UserContext-->>ChainFetcher: contractRegisterArgs (includes context with log)
    ChainFetcher->>ContractRegisterHandler: contractRegister(contractRegisterArgs)
    ContractRegisterHandler->>ContractRegisterHandler: context.log.info()
Loading

Assessment against linked issues

Objective Addressed Explanation
Surface the ability to call context.log.info() on contractRegister() (#620)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Possibly related PRs

Poem

In the warren of code, a new log appears,
Now rabbits can register with fewer fears.
With context improved and logging in tow,
Contract events sparkle, their info will flow.
Hop along, dear devs, see what’s anew—
The log is now surfaced, just for you!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 11351ad and 063525f.

📒 Files selected for processing (3)
  • codegenerator/cli/templates/static/codegen/src/UserContext.res (1 hunks)
  • scenarios/test_codegen/src/EventHandlers.ts (3 hunks)
  • scenarios/test_codegen/test/EventHandler_test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • scenarios/test_codegen/src/EventHandlers.ts
  • codegenerator/cli/templates/static/codegen/src/UserContext.res
🧰 Additional context used
🧠 Learnings (1)
scenarios/test_codegen/test/EventHandler_test.ts (1)
Learnt from: JonoPrest
PR: enviodev/hyperindex#555
File: scenarios/test_codegen/test/lib_tests/EntityHistory_test.res:631-659
Timestamp: 2025-05-27T17:07:12.878Z
Learning: In isolated tests for EntityHistory rollbacks with controlled mock data setup, the ordering of getRollbackDiff results is deterministic and doesn't require sorting before comparison with deepStrictEqual.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build_and_test
🔇 Additional comments (2)
scenarios/test_codegen/test/EventHandler_test.ts (2)

310-327: LGTM: Address validation test is well-structured.

The test correctly validates that invalid contract addresses are rejected with an appropriate error message. The test structure follows the established patterns and the expected error message is specific and informative.


329-366: LGTM: Address checksumming test validates important functionality.

The test correctly verifies that lowercase addresses are properly checksummed to the expected mixed-case format during contract registration. The test comprehensively validates:

  1. The address transformation from lowercase to checksummed format
  2. The correct storage of the checksummed address in the dynamic contract registry
  3. All associated metadata fields in the registered contract entry

The test structure is consistent with existing tests and uses realistic address values for validation.

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
codegenerator/cli/templates/static/codegen/src/Config.res (1)

140-146: Consider contract name uniqueness across chains.

The mapping logic assumes contract names are unique across all chains. If multiple chains have contracts with the same name, later entries will overwrite earlier ones in the dictionary.

Consider implementing a more robust mapping strategy if contract name conflicts are possible:

-  let addContractNameToContractNameMapping = Js.Dict.empty()
-  chains->Array.forEach(chainConfig => {
-    chainConfig.contracts->Array.forEach(contract => {
-      let addKey = "add" ++ contract.name->Utils.String.capitalize
-      addContractNameToContractNameMapping->Js.Dict.set(addKey, contract.name)
-    })
-  })
+  let addContractNameToContractNameMapping = Js.Dict.empty()
+  chains->Array.forEach(chainConfig => {
+    chainConfig.contracts->Array.forEach(contract => {
+      let addKey = "add" ++ contract.name->Utils.String.capitalize
+      // Only set if not already present, or consider chain-specific keys
+      if !addContractNameToContractNameMapping->Js.Dict.get(addKey)->Option.isSome {
+        addContractNameToContractNameMapping->Js.Dict.set(addKey, contract.name)
+      }
+    })
+  })
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5952b06 and 11351ad.

📒 Files selected for processing (8)
  • codegenerator/cli/templates/dynamic/codegen/src/ContextEnv.res.hbs (0 hunks)
  • codegenerator/cli/templates/dynamic/codegen/src/TestHelpers_MockDb.res.hbs (1 hunks)
  • codegenerator/cli/templates/dynamic/codegen/src/Types.res.hbs (1 hunks)
  • codegenerator/cli/templates/static/codegen/src/Config.res (3 hunks)
  • codegenerator/cli/templates/static/codegen/src/UserContext.res (1 hunks)
  • codegenerator/cli/templates/static/codegen/src/eventFetching/ChainFetcher.res (2 hunks)
  • codegenerator/cli/templates/static/codegen/src/globalState/GlobalState.res (1 hunks)
  • scenarios/test_codegen/src/EventHandlers.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • codegenerator/cli/templates/dynamic/codegen/src/ContextEnv.res.hbs
🧰 Additional context used
🧠 Learnings (1)
scenarios/test_codegen/src/EventHandlers.ts (1)
Learnt from: JonoPrest
PR: enviodev/hyperindex#555
File: scenarios/test_codegen/test/lib_tests/EntityHistory_test.res:631-659
Timestamp: 2025-05-27T17:07:12.878Z
Learning: In isolated tests for EntityHistory rollbacks with controlled mock data setup, the ordering of getRollbackDiff results is deterministic and doesn't require sorting before comparison with deepStrictEqual.
🧬 Code Graph Analysis (1)
scenarios/test_codegen/src/EventHandlers.ts (1)
codegenerator/cli/npm/envio/src/Types.ts (1)
  • Logger (5-22)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build_and_test
🔇 Additional comments (13)
codegenerator/cli/templates/dynamic/codegen/src/Types.res.hbs (1)

9-9: LGTM: Logging field addition is correct.

The addition of the log field with type Envio.logger properly integrates logging capability into the contract registration context.

codegenerator/cli/templates/dynamic/codegen/src/TestHelpers_MockDb.res.hbs (1)

374-374: Confirmed runContractRegistersOrThrow Signature Requires ~config

The call in TestHelpers_MockDb.res.hbs correctly passes the ~config argument, matching the definition in ChainFetcher.res:

let runContractRegistersOrThrow = async (
  ~reversedWithContractRegister: array<Internal.eventItem>,
  ~config: Config.t,
  …
) => { … }

No changes needed. Approving this addition.

scenarios/test_codegen/src/EventHandlers.ts (2)

2-2: LGTM: Logger import addition is appropriate.

Adding Logger to the imports is necessary for the type assertion used in contract registration testing.


412-413: LGTM: Type assertion validates logging integration.

The type assertion confirms that context.log is properly typed as Logger in the contract registration context, ensuring type safety for the new logging functionality.

codegenerator/cli/templates/static/codegen/src/globalState/GlobalState.res (1)

577-577: LGTM: Config parameter addition maintains consistency.

The addition of ~config=state.config parameter ensures contract registration handlers have access to configuration data, including the new contract name mapping. This is consistent with the similar change in TestHelpers.

codegenerator/cli/templates/static/codegen/src/Config.res (2)

120-120: LGTM: Contract name mapping field addition.

The new field addContractNameToContractNameMapping properly supports dynamic contract registration functionality.


163-163: LGTM: Field inclusion in config record.

The contract name mapping is properly included in the configuration record.

codegenerator/cli/templates/static/codegen/src/eventFetching/ChainFetcher.res (2)

313-313: Function signature updated to include configuration parameter.

The addition of the ~config: Config.t parameter aligns with the new contract register context implementation that requires configuration data for contract name mapping and address validation.


358-358: Function call updated to use the new UserContext implementation.

The change from ContextEnv.getContractRegisterArgs to UserContext.getContractRegisterArgs with the added ~config parameter is consistent with the refactoring to move contract register context creation to a static implementation.

codegenerator/cli/templates/static/codegen/src/UserContext.res (4)

334-342: Well-structured type definition for contract register parameters.

The contractRegisterParams type properly encapsulates the necessary data for contract registration: event item, registration callback, and configuration. The callback function signature is well-typed with all required parameters.


344-376: Robust proxy traps implementation with proper validation.

The proxy traps implementation includes several good practices:

  • Proper logging support through the log property
  • Efficient contract name lookup using pre-built mapping
  • EVM address validation for address integrity
  • Comprehensive error handling for invalid property access

The implementation follows the established patterns in the codebase.


378-395: Clean helper functions following established patterns.

The getContractRegisterContext and getContractRegisterArgs functions follow the same patterns as other context creation functions in the file, ensuring consistency across the codebase. The function signatures are well-typed and the implementation is straightforward.


356-360: Address validation ensures data integrity.

The EVM address validation using Address.Evm.fromAddressOrThrow is a good security practice that ensures only valid addresses are registered for EVM ecosystems, preventing potential issues downstream.

@DZakh DZakh requested a review from moose-code July 7, 2025 07:20
@DZakh DZakh enabled auto-merge (squash) July 7, 2025 08:17

@moose-code moose-code left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

lgtm!!

@DZakh DZakh merged commit 3e1b5c6 into main Jul 7, 2025
2 checks passed
@DZakh DZakh deleted the dz/contract-register-context-log branch July 7, 2025 08:18
@coderabbitai coderabbitai Bot mentioned this pull request Dec 2, 2025
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.

Feature request: surface log on contractRegistrations context

2 participants