Skip to content

add config in response#3

Merged
lmcmz merged 1 commit intomainfrom
fix-codgen
Aug 4, 2025
Merged

add config in response#3
lmcmz merged 1 commit intomainfrom
fix-codgen

Conversation

@lmcmz
Copy link
Contributor

@lmcmz lmcmz commented Aug 4, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a Cadence script to retrieve account balances for both Flow and EVM accounts from a list of addresses.
  • Improvements
    • Enhanced type resolution for Cadence files, improving nested type handling for both mainnet and testnet.
    • Updated TypeScript code generation to provide response interceptors with both request configuration and response data.
    • Improved struct name flattening for better handling of nested types in generated reports and TypeScript code.

@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

Walkthrough

The changes introduce new helper functions for flattening struct names and return types in the analyzer, update the CadenceService TypeScript generator to pass both config and response to response interceptors, and add a new Cadence script for retrieving balances from Flow and EVM accounts. Additionally, the Cadence file analysis step now attempts to resolve nested types if address information is available.

Changes

Cohort / File(s) Change Summary
Analyzer Struct Flattening
internal/analyzer/analyzer.go
Added flattenStructName and flattenReturnType helpers. Updated GetReport to flatten struct names and keys in the returned report.
TypeScript Generator Interceptors & Struct Name Flattening
internal/generator/typescript/generator.go
Updated response interceptor signatures to receive both config and response. Modified runResponseInterceptors accordingly. Improved flattenStructName to handle multiple dot separators.
Cadence File Analysis Nested Type Resolution
cmd/typescript.go
Added logic to resolve nested types after Cadence file analysis if address information is present, for both "mainnet" and "testnet". Errors are warned but do not halt the process.
New Cadence Balance Retrieval Script
example/Base/get_flow_balance_for_any_accounts.cdc
Added a script to retrieve balances for both Flow and EVM accounts given a list of addresses. Introduced getEVMBalance, getFlowBalance, and main functions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CadenceService (TypeScript)
    participant ResponseInterceptor
    User->>CadenceService (TypeScript): Call query/transaction function
    CadenceService (TypeScript)->>CadenceService (TypeScript): Execute request
    CadenceService (TypeScript)->>ResponseInterceptor: runResponseInterceptors(config, response)
    ResponseInterceptor-->>CadenceService (TypeScript): Processed response
    CadenceService (TypeScript)-->>User: Return final response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A bunny hopped through fields of code,
Flattening structs on every road.
TypeScript interceptors now see more,
With configs and responses at their core.
Cadence scripts for balances, neat and spry—
This rabbit’s work will surely fly!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-codgen

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 generate unit tests to generate unit tests for 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.

@lmcmz lmcmz merged commit c727690 into main Aug 4, 2025
1 of 2 checks passed
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

🧹 Nitpick comments (2)
internal/analyzer/analyzer.go (1)

107-137: Well-structured return type flattening logic.

The function correctly handles the complex cases of array types, optional types, and nested references. The logic properly preserves type markers while flattening the inner type names.

Consider adding a check for empty return types:

 func flattenReturnType(returnType string) string {
+	if returnType == "" {
+		return returnType
+	}
+	
 	// Handle array types like "[FlowIDTableStaking.DelegatorInfo]?"
cmd/typescript.go (1)

57-66: Good implementation of nested type resolution with proper error handling.

The code correctly attempts to resolve nested types when addresses are available, handles both major networks, and gracefully continues execution even when resolution fails. The placement after directory analysis is appropriate.

Consider making the networks configurable or allowing users to specify which networks to resolve:

+			networks := []string{"mainnet", "testnet"}
+			for _, network := range networks {
+				if err := a.ResolveNestedTypes(network); err != nil {
+					fmt.Printf("Warning: failed to resolve nested types for %s: %v\n", network, err)
+				}
+			}
-			// Try to resolve nested types for both mainnet and testnet
-			if err := a.ResolveNestedTypes("mainnet"); err != nil {
-				fmt.Printf("Warning: failed to resolve nested types for mainnet: %v\n", err)
-			}
-			if err := a.ResolveNestedTypes("testnet"); err != nil {
-				fmt.Printf("Warning: failed to resolve nested types for testnet: %v\n", err)
-			}

This would make it easier to add additional networks or make network selection configurable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 64c4560 and 4b202f7.

📒 Files selected for processing (4)
  • cmd/typescript.go (1 hunks)
  • example/Base/get_flow_balance_for_any_accounts.cdc (1 hunks)
  • internal/analyzer/analyzer.go (2 hunks)
  • internal/generator/typescript/generator.go (5 hunks)
🔇 Additional comments (9)
internal/analyzer/analyzer.go (3)

94-105: LGTM! Clean implementation of struct name flattening.

The function correctly handles nested struct names by removing all dots and concatenating the parts. The logic properly handles both single and multiple dot separators, and gracefully returns the original name when no dots are present.


154-161: Correct implementation of struct flattening in report generation.

The code properly creates flattened versions of both the map keys and the struct names while preserving all other struct properties. This ensures consistency between how structs are referenced and their internal names.


166-166: Clean integration of flattened structs.

The change correctly uses the flattened structs map in the report, maintaining consistency with the new flattening logic.

internal/generator/typescript/generator.go (4)

122-124: Correct implementation of updated response interceptor calls.

The query function now properly passes both config and response to the response interceptors, maintaining consistency with the updated type signature and method definition.


139-139: Consistent response interceptor implementation for transactions.

The transaction function correctly implements the updated response interceptor signature by passing both config and txId.


407-407: Method signature correctly updated to match type definition.

The runResponseInterceptors method now accepts both config and response parameters and properly forwards them to each interceptor in the chain.


211-216: Improved struct name flattening to handle multiple dots.

The updated function now correctly handles struct names with multiple dot separators by concatenating all parts, maintaining consistency with the analyzer's flattening logic.

example/Base/get_flow_balance_for_any_accounts.cdc (2)

4-6: Clean EVM balance retrieval implementation.

The function correctly converts string addresses to EVM addresses and retrieves balances in FLOW units. The optional return type appropriately handles potential conversion failures.


9-15: Proper Flow balance retrieval with good error handling.

The function correctly handles address conversion and uses availableBalance which is more practical than total balance. The nil return for invalid addresses is appropriate.

Comment on lines +17 to +31
access(all) fun main(addresses: [String]): {String: UFix64?} {
let res: {String: UFix64?} = {}

for addr in addresses {
let hex = addr[1] == "x" ? addr : "0x".concat(addr)
if let flowBalance = getFlowBalance(hex) {
res[hex] = flowBalance
} else {
if let evmBalance = getEVMBalance(hex) {
res[hex] = evmBalance
}
}
}
return res
} No newline at end of file
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address normalization has potential index out of bounds issue.

The main function logic is sound, but Line 21 has a potential runtime error when checking addr[1] == "x" for addresses shorter than 2 characters.

Apply this fix to handle short addresses safely:

-        let hex = addr[1] == "x" ? addr : "0x".concat(addr)
+        let hex = addr.length > 1 && addr[1] == "x" ? addr : "0x".concat(addr)

Alternatively, use a more robust approach:

-        let hex = addr[1] == "x" ? addr : "0x".concat(addr)
+        let hex = addr.slice(0, 2) == "0x" ? addr : "0x".concat(addr)
📝 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
access(all) fun main(addresses: [String]): {String: UFix64?} {
let res: {String: UFix64?} = {}
for addr in addresses {
let hex = addr[1] == "x" ? addr : "0x".concat(addr)
if let flowBalance = getFlowBalance(hex) {
res[hex] = flowBalance
} else {
if let evmBalance = getEVMBalance(hex) {
res[hex] = evmBalance
}
}
}
return res
}
access(all) fun main(addresses: [String]): {String: UFix64?} {
let res: {String: UFix64?} = {}
for addr in addresses {
let hex = addr.length > 1 && addr[1] == "x" ? addr : "0x".concat(addr)
if let flowBalance = getFlowBalance(hex) {
res[hex] = flowBalance
} else {
if let evmBalance = getEVMBalance(hex) {
res[hex] = evmBalance
}
}
}
return res
}
🤖 Prompt for AI Agents
In example/Base/get_flow_balance_for_any_accounts.cdc around lines 17 to 31, the
code checks addr[1] without verifying the length of addr, which can cause an
index out of bounds error for short addresses. Fix this by first checking if
addr length is greater than 1 before accessing addr[1], or use a safer method to
normalize the address string that handles short or malformed addresses
gracefully.

// 2. Output class header and interceptor related code
buffer.WriteString("type RequestInterceptor = (config: any) => any | Promise<any>;\n")
buffer.WriteString("type ResponseInterceptor = (response: any) => any | Promise<any>;\n\n")
buffer.WriteString("type ResponseInterceptor = (config: any, response: any) => any | Promise<any>;\n\n")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Breaking change: Response interceptor signature updated.

The ResponseInterceptor type now receives both config and response parameters, providing interceptors with access to the original request configuration. This is a breaking change for existing interceptors but adds valuable functionality.

Consider documenting this breaking change in the commit message or changelog, as existing response interceptors will need to be updated to handle the additional parameter.

🤖 Prompt for AI Agents
In internal/generator/typescript/generator.go at line 395, the
ResponseInterceptor type signature was changed to include both config and
response parameters, which is a breaking change. Update the commit message or
changelog to clearly document this change so users know they must update
existing interceptors to accept the additional config parameter.

zenabot27 pushed a commit to zenabot27/cadence-codegen that referenced this pull request Feb 15, 2026
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.

1 participant