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

[FH-2] Open Frames Implementation (#163) #202

Merged
merged 7 commits into from
Oct 21, 2024
Merged

[FH-2] Open Frames Implementation (#163) #202

merged 7 commits into from
Oct 21, 2024

Conversation

ryanjshaw
Copy link
Collaborator

@ryanjshaw ryanjshaw commented Oct 10, 2024

Closes #163

Sample post on hey.xyz / Lens

Link

image

Sample convo with XMTP

image

Frames.js debugger verification

image

image

image

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new module for validating and standardizing frame payloads from various protocols (Farcaster, Lens, XMTP).
    • Enhanced payload handling with selective logging based on payload types.
  • Bug Fixes

    • Improved validation processes for incoming requests, ensuring only relevant payloads are validated.
  • Chores

    • Updated dependencies, including the frames.js package to a newer version.
  • Documentation

    • Clarified type definitions for frame payloads to enhance understanding and context.

Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on the restructuring of payload validation and type definitions. Key updates include renaming types from FramePayload to FarcasterFramePayload and modifying import statements for validation functions. New validation logic has been added in a newly created module, while some existing validation functions have been removed. Additionally, the package.json file reflects an updated version of the frames.js dependency. These changes enhance clarity and improve the handling of different frame payloads.

Changes

File Change Summary
app/(app)/f/[frameId]/[handler]/[[...query]]/route.ts Updated imports for payload handling; conditional check added for isFarcasterFrameActionPayload.
app/api/compose/[templateId]/route.ts Updated import for payload validation function; utilized new validation function in validatedPayload.
lib/farcaster.ts Renamed FramePayload to FarcasterFramePayload and FramePayloadValidated to FarcasterFramePayloadValidated.
lib/serve.ts Removed validatePayload and validatePayloadAirstack functions; expanded metadata in buildFrame.
lib/validate.ts Introduced new module for validating frame payloads; added new types and validation functions.
package.json Updated dependency version for frames.js from ^0.11.0 to ^0.19.3.
templates/figma/handlers/click.ts Updated import for FramePayloadValidated and changed parameter type for body.

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.

Copy link
Contributor

@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 (9)
templates/figma/handlers/click.ts (1)

Line range hint 1-24: Summary of changes and potential impact

The changes in this file appear to be part of a larger refactoring effort:

  1. The import source for FramePayloadValidated has been updated.
  2. The body parameter type in the click function has been changed to FramePayloadValidated.
  3. The way the button index is accessed has been modified.

These changes improve type safety and consistency. However, they may have broader implications across the codebase.

Consider the following recommendations:

  1. Ensure that all files importing FramePayloadValidated have been updated.
  2. Verify that the new structure of FramePayloadValidated is consistently used across all relevant functions.
  3. Update any documentation or comments that might reference the old structure.
  4. If this is part of a breaking change, ensure it's properly communicated to other developers and update the version number accordingly.
app/api/compose/[templateId]/route.ts (1)

Line range hint 1-89: Summary: Farcaster-specific validation refactoring looks good.

The changes in this file are minimal and focused on updating the validation function to be Farcaster-specific. This refactoring improves the clarity and specificity of the code. The overall structure and logic of the file remain intact, which is good.

Consider the following architectural advice:

  1. Ensure that this change is part of a consistent pattern across the codebase, where Farcaster-specific logic is separated from general frame handling.
  2. If there are other frame types (e.g., for different platforms), consider creating a factory or strategy pattern for validation to make it easier to add new frame types in the future.
  3. Update any relevant documentation or comments to reflect these changes, especially if there are architectural diagrams or API specifications that mention the validation process.
app/(app)/f/[frameId]/[handler]/[[...query]]/route.ts (3)

166-166: Address the TODO comment regarding interaction logging

There's a TODO comment indicating uncertainty about supporting interaction logging for non-Farcaster frames:

// TODO Do we want to support interaction logging for non-Farcaster frames?

Clarify whether interaction logging should be supported for non-Farcaster frames. If so, consider implementing the necessary logic; if not, you might want to document this decision for future reference.

Would you like assistance in implementing interaction logging for non-Farcaster frames or creating a GitHub issue to track this task?


172-172: Replace console.log with a proper logging mechanism

Using console.log in production code can expose sensitive information and is generally not recommended. Consider using a logging library or framework that allows you to control log levels and outputs.

Apply this diff to replace console.log:

-    console.log(JSON.stringify(airstackPayloadValidated, null, 2))
+    // Use a proper logging mechanism instead of console.log
+    logger.debug('Validated Airstack payload:', airstackPayloadValidated)

Ensure that logger is appropriately configured in your application.


181-182: Validate optional fields before accessing properties

When accessing optional properties like inputText and state, ensure they are validated or handle cases where they might be undefined or null to prevent potential runtime errors.

Consider adding checks or using optional chaining:

-    inputText: airstackPayloadValidated.message.data.frameActionBody.inputText || undefined,
-    state: airstackPayloadValidated.message.data.frameActionBody.state || undefined,
+    inputText: airstackPayloadValidated.message.data.frameActionBody?.inputText,
+    state: airstackPayloadValidated.message.data.frameActionBody?.state,
lib/validate.ts (4)

107-107: Remove unnecessary console.log statement

The console.log(r.action) statement in the validatePayloadFarcaster function may expose sensitive information and clutter the console output in production environments. It's advisable to remove this statement or use a proper logging mechanism with appropriate log levels.

Apply this diff to remove the console log:

@@ -107,1 +107,0 @@
-    console.log(r.action)

20-21: Update inputText type definition

There's a TODO comment indicating that inputText should use NeynarValidatedFrameActionResponse['action']['input']['text']:

// TODO inputText: NeynarValidatedFrameActionResponse['action']['input']['text']
inputText: string,

Updating the type definition will ensure consistency with the validated response and improve type safety.

Would you like assistance in updating the type definition for inputText to reflect the correct type?


189-190: Implement user details retrieval for Lens protocol

The userName and userIcon for the Lens protocol are currently placeholders with TODO comments:

userName: userId, // TODO use lensclient?
userIcon: undefined, // TODO use lensclient?

Integrating lensclient to fetch these details will enhance the completeness of the standardized payload.

I can help integrate lensclient to retrieve the user's name and icon. Would you like me to draft the implementation or open a GitHub issue to track this task?


209-210: Retrieve user details using XMTP client

The userName and userIcon fields for XMTP are set to default values, with TODO comments suggesting the use of an XMTP client:

userName: userId, // TODO use xmtp client?
userIcon: undefined, // TODO use xmtp client?

Fetching user details using the XMTP client would improve the payload's accuracy and usefulness.

Would you like assistance in integrating the XMTP client to obtain the user's name and icon?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c12bb56 and ed28aec.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • app/(app)/f/[frameId]/[handler]/[[...query]]/route.ts (2 hunks)
  • app/api/compose/[templateId]/route.ts (2 hunks)
  • lib/farcaster.ts (2 hunks)
  • lib/serve.ts (1 hunks)
  • lib/validate.ts (1 hunks)
  • package.json (1 hunks)
  • templates/figma/handlers/click.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (6)
templates/figma/handlers/click.ts (2)

17-17: Verify the correctness of the new button index access.

The way the button index is accessed has changed from body.tapped_button.index to body.buttonIndex.toString(). This reflects a structural change in the FramePayloadValidated type.

Let's verify the consistency of this change and its impact on the function's logic:

#!/bin/bash
# Description: Check for consistency in button index access across the codebase

# Test 1: Search for any remaining usages of the old button index access pattern
echo "Checking for any remaining usages of body.tapped_button.index:"
rg --type typescript "body\.tapped_button\.index"

# Test 2: Verify the new button index access pattern is used consistently
echo "Verifying the usage of body.buttonIndex:"
rg --type typescript "body\.buttonIndex"

# Test 3: Check if buttonIndex is consistently treated as a number
echo "Checking if buttonIndex is consistently treated as a number:"
rg --type typescript "body\.buttonIndex(\.toString\(\)|\.toFixed\(|\.toNumber\()"

Please ensure that this change doesn't break any existing logic related to button handling in the function.


Line range hint 7-15: LGTM! Verify usage of body within the function.

The type of the body parameter has been updated to FramePayloadValidated, which aligns with the import change. This is a good practice for type safety.

Let's verify that the usage of body within the function is consistent with this type change:

#!/bin/bash
# Description: Check the usage of 'body' within the click function

# Test: Search for all usages of 'body' within the click function
echo "Checking usages of 'body' within the click function:"
ast-grep --lang typescript --pattern $'function click({
  $$$
}: {
  body: FramePayloadValidated
  $$$
}) {
  $$$
  $body$
  $$$
}'
app/api/compose/[templateId]/route.ts (2)

38-38: LGTM! Ensure the new validation function behaves as expected.

The update to use validatePayloadFarcaster is consistent with the import change and improves the specificity of the validation for Farcaster frames.

To ensure the new validation function behaves as expected, please verify its implementation and run appropriate tests. You can use the following script to check the implementation:

#!/bin/bash
# Description: Check the implementation of validatePayloadFarcaster

# Test: Display the content of the file containing validatePayloadFarcaster
fd --type f --full-path '.*farcaster.*' | xargs rg -A 10 'export.*function validatePayloadFarcaster'

3-3: LGTM! Verify the impact of this change across the codebase.

The update to import validatePayloadFarcaster from '@/lib/farcaster' looks good. This change appears to be part of a refactoring to make the validation more specific to Farcaster frames.

To ensure this change doesn't introduce any issues, please run the following script to check for any remaining usage of the old validatePayload function:

package.json (1)

67-67: Approved: frames.js dependency updated. Verify compatibility and review changelog.

The update of frames.js from ^0.11.0 to ^0.19.3 is a significant version jump, which aligns with the PR objectives for "Open Frames Implementation". This change is approved, but please consider the following:

  1. Verify that this update is compatible with the rest of your codebase, especially any components or functions that directly use frames.js.
  2. Review the changelog for frames.js between versions 0.11.0 and 0.19.3 to be aware of any breaking changes or new features that might affect your implementation.

To help verify the impact of this change, you can run the following script:

This script will help identify areas of the codebase that might be affected by the frames.js update and remind you to check the official changelog.

lib/validate.ts (1)

139-140: Verify Farcaster timestamp conversion logic

In standardizeFarcasterPayload, the timestamp is calculated using a custom epoch:

const farcasterEpoch = new Date('2021-01-01T00:00:00Z').getTime();
const timestampInMs = farcasterEpoch + (Number(payload.timestamp) * 1000);

Ensure that this conversion accurately represents the intended timestamp. Miscalculations could lead to incorrect time data, affecting time-sensitive features.

Comment on lines +2 to +3
import type { BuildFrameData } from '@/lib/farcaster'
import type { FramePayloadValidated } from '@/lib/validate'
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistent import of FramePayloadValidated detected.

The import source for FramePayloadValidated has not been updated consistently across the codebase. Please update the following files to import from @/lib/validate:

  • templates/swap/handlers/more.ts
  • templates/swap/handlers/success.ts
  • templates/swap/handlers/estimate.ts
  • templates/swap/handlers/txData.ts
  • templates/quizlet/handlers/success.ts
  • templates/quizlet/handlers/review.ts
  • templates/quizlet/handlers/page.ts
  • templates/presentation/handlers/cover.ts
  • templates/quizlet/handlers/answer.ts
  • templates/presentation/handlers/slide.ts
  • templates/substack/handlers/page.ts
  • templates/presentation-v1/handlers/page.ts
  • templates/quizlet/handlers/results.ts
  • templates/luma/handlers/success.ts
  • templates/poll/handlers/vote.ts
  • templates/luma/handlers/register.ts
  • templates/form/handlers/success.ts
  • templates/form/handlers/field.ts
  • templates/fundraiser/handlers/about.ts
  • templates/fundraiser/handlers/confirmation.ts
  • templates/fundraiser/handlers/txData.ts
  • templates/form-v1/handlers/input.ts
  • templates/fundraiser/handlers/status.ts
  • templates/fundraiser/handlers/success.ts
  • templates/gated/handlers/page.ts
  • templates/beehiiv/handlers/page.ts
  • templates/cal/handlers/duration.ts
  • templates/cal/handlers/month.ts
  • templates/contract/handlers/confirm.ts
  • templates/figma/handlers/slide.ts
  • templates/cal/handlers/day.ts
  • templates/cal/handlers/confirm.ts
  • templates/cal/handlers/hour.ts
  • app/(app)/p/[frameId]/[handler]/[[...query]]/route.ts
🔗 Analysis chain

Verify the impact of the import change across the codebase.

The import source for FramePayloadValidated has been changed from '@/lib/farcaster' to '@/lib/validate'. This change suggests a restructuring of the project's modules.

Let's verify that this change has been consistently applied across the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining imports of FramePayloadValidated from @/lib/farcaster

# Test 1: Search for imports of FramePayloadValidated from @/lib/farcaster
echo "Checking for imports of FramePayloadValidated from @/lib/farcaster:"
rg --type typescript "import.*FramePayloadValidated.*from\s+['\"]@/lib/farcaster['\"]"

# Test 2: Verify the new import is used consistently
echo "Verifying the new import of FramePayloadValidated from @/lib/validate:"
rg --type typescript "import.*FramePayloadValidated.*from\s+['\"]@/lib/validate['\"]"

Length of output: 775


Script:

#!/bin/bash
# Description: Check for any remaining imports of FramePayloadValidated from @/lib/farcaster and verify the new import from @/lib/validate

# Test 1: Search for imports of FramePayloadValidated from @/lib/farcaster
echo "Checking for imports of FramePayloadValidated from '@/lib/farcaster':"
rg --type ts "import\s+.*FramePayloadValidated.*from\s+['\"]@/lib/farcaster['\"]"

# Test 2: Verify the new import is used consistently from @/lib/validate
echo "Verifying the new import of FramePayloadValidated from '@/lib/validate':"
rg --type ts "import\s+.*FramePayloadValidated.*from\s+['\"]@/lib/validate['\"]"

Length of output: 4644

Comment on lines +32 to +33
export type FarcasterFramePayload = FramesJSFrameActionPayload
export type FarcasterFramePayloadValidated = NeynarValidatedFrameActionResponse['action']
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Remaining references to old type names found

The verification script detected instances of FramePayload and FramePayloadValidated that were not updated to FarcasterFramePayload and FarcasterFramePayloadValidated:

  • lib/validate.ts
  • app/(app)/f/[frameId]/[handler]/[[...query]]/route.ts

Please update these occurrences to maintain consistency and avoid potential conflicts.

🔗 Analysis chain

Approve renaming of FramePayload and FramePayloadValidated types

The renaming of FramePayload to FarcasterFramePayload and FramePayloadValidated to FarcasterFramePayloadValidated improves code clarity and consistency. This change:

  1. Explicitly associates these types with Farcaster, reducing ambiguity.
  2. Aligns with the naming convention of other Farcaster-related types in the file.
  3. Potentially reduces naming conflicts with similar types from other libraries.

The underlying type definitions remain unchanged, ensuring no functional impact.

To ensure this change doesn't introduce any issues, please verify that all references to these types throughout the codebase have been updated accordingly. Run the following script to check for any remaining occurrences of the old type names:

If the script returns any results, those occurrences should be updated to use the new type names.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining occurrences of the old type names

# Test: Search for old type names. Expect: No results
rg --type typescript "type (FramePayload|FramePayloadValidated)\b"

Length of output: 103


Script:

#!/bin/bash
# Description: Check for any remaining occurrences of the old type names in .ts and .tsx files

# Test: Search for old type names. Expect: No results
rg "type\s+(FramePayload|FramePayloadValidated)\b" --glob "*.ts" --glob "*.tsx"

Length of output: 358

Comment on lines +3 to +6
import type { BuildFrameData, FarcasterFramePayload } from '@/lib/farcaster'
import { updateFrameStorage } from '@/lib/frame'
import { buildFramePage, validatePayload, validatePayloadAirstack } from '@/lib/serve'
import { buildFramePage } from '@/lib/serve'
import { isFarcasterFrameActionPayload, validatePayload, validatePayloadAirstack, type FramePayload } from '@/lib/validate'
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure consistent use of payload types and imports

There appears to be a mix of FramePayload and FarcasterFramePayload imports:

  • Line 3 imports FarcasterFramePayload from '@/lib/farcaster'.
  • Line 6 imports type FramePayload from '@/lib/validate'.

This could lead to confusion or type mismatches when handling payloads. Consider standardizing the payload type across the module to ensure consistency.

Apply this diff to update the import and usage:

 import { isFarcasterFrameActionPayload, validatePayload, validatePayloadAirstack, type FramePayload } from '@/lib/validate'
+import type { FarcasterFramePayload } from '@/lib/farcaster'
 
 // Replace all instances of FramePayload with FarcasterFramePayload in this file
-const payload = (await request.json()) as FramePayload
+const payload = (await request.json()) as FarcasterFramePayload

Committable suggestion was skipped due to low confidence.

Comment on lines +168 to +171
const airstackKey = frame.config?.airstackKey || process.env.AIRSTACK_API_KEY

const airstackPayloadValidated = await validatePayloadAirstack(payload as FarcasterFramePayload, airstackKey)

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

airstackKey Configuration Missing

The airstackKey is not set in any frame configurations, and the AIRSTACK_API_KEY environment variable is also missing. This will lead to runtime errors when airstackKey is undefined.

🔗 Analysis chain

Ensure airstackKey is properly configured

The variable airstackKey is obtained from frame.config?.airstackKey or environment variables. Ensure that this key is correctly configured and that missing or invalid keys are appropriately handled to prevent runtime errors.

Run the following script to check for the presence of airstackKey in configuration:

Ensure that frames have airstackKey configured or that the environment variable AIRSTACK_API_KEY is set.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that 'airstackKey' is set in frame configurations or environment variables.

# Test: Search for frames missing 'airstackKey' in configurations
jq '.config | select(.airstackKey == null)' frames/*.json

# Test: Check if 'AIRSTACK_API_KEY' is set in environment variables
if [[ -z "${AIRSTACK_API_KEY}" ]]; then
  echo "AIRSTACK_API_KEY is not set in environment variables."
else
  echo "AIRSTACK_API_KEY is set."
fi

Length of output: 264

Comment on lines +174 to +189
await client
.insert(interactionTable)
.values({
frame: frame.id,
fid: airstackPayloadValidated.message.data.fid.toString(),
buttonIndex:
airstackPayloadValidated.message.data.frameActionBody.buttonIndex.toString(),
inputText: airstackPayloadValidated.message.data.frameActionBody.inputText || undefined,
state: airstackPayloadValidated.message.data.frameActionBody.state || undefined,
transactionHash:
airstackPayloadValidated.message.data.frameActionBody.transactionId || undefined,
castFid: airstackPayloadValidated.message.data.frameActionBody.castId.fid.toString(),
castHash: airstackPayloadValidated.message.data.frameActionBody.castId.hash,
createdAt: new Date(),
})
.run()
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential database insertion errors

While inserting data into the interactionTable, there is no error handling in case the database operation fails. Unhandled promise rejections could lead to application crashes or inconsistent state.

Wrap the database insertion in a try-catch block to handle potential errors:

+    try {
         await client
             .insert(interactionTable)
             .values({
                 frame: frame.id,
                 fid: airstackPayloadValidated.message.data.fid.toString(),
                 buttonIndex:
                     airstackPayloadValidated.message.data.frameActionBody.buttonIndex.toString(),
                 inputText: airstackPayloadValidated.message.data.frameActionBody.inputText || undefined,
                 state: airstackPayloadValidated.message.data.frameActionBody.state || undefined,
                 transactionHash:
                     airstackPayloadValidated.message.data.frameActionBody.transactionId || undefined,
                 castFid: airstackPayloadValidated.message.data.frameActionBody.castId.fid.toString(),
                 castHash: airstackPayloadValidated.message.data.frameActionBody.castId.hash,
                 createdAt: new Date(),
             })
             .run()
+    } catch (e) {
+        // Handle the error appropriately
+        logger.error('Database insertion failed:', e)
+    }

Ensure you have a logging mechanism (logger) configured to capture the error details.

Committable suggestion was skipped due to low confidence.

Comment on lines +243 to +249
metadata['of:version'] = 'vNext'

// Lens Protocol Open Frames version the handler supports
metadata['of:accepts:lens'] = '1.0.0'

// XMTP Open Frames version the handler supports
metadata['of:accepts:xmtp'] = 'vNext'
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Define version constants for maintainability

Currently, the version strings 'vNext' and '1.0.0' are hardcoded. Consider defining them as constants at the beginning of the file or in a configuration file. This improves maintainability and makes it easier to update versions in the future.

Apply this diff to define version constants:

+const OPEN_FRAMES_VERSION = 'vNext';
+const LENS_PROTOCOL_VERSION = '1.0.0';
+const XMTP_VERSION = 'vNext';

...

-    metadata['of:version'] = 'vNext';
+    metadata['of:version'] = OPEN_FRAMES_VERSION;

-    metadata['of:accepts:lens'] = '1.0.0';
+    metadata['of:accepts:lens'] = LENS_PROTOCOL_VERSION;

-    metadata['of:accepts:xmtp'] = 'vNext';
+    metadata['of:accepts:xmtp'] = XMTP_VERSION;

Committable suggestion was skipped due to low confidence.

Comment on lines +255 to +276
const openFrameEquivalentTags: Record<string, string> = {
'fc:frame:state': 'of:state',
'fc:frame:image': 'of:image',
'fc:frame:image:aspect_ratio': 'of:image:aspect_ratio',
'fc:frame:post_url': 'of:post_url',
'fc:frame:input:text': 'of:input:text',
'fc:frame:button:1': 'of:button:1',
'fc:frame:button:1:action': 'of:button:1:action',
'fc:frame:button:1:target': 'of:button:1:target',
'fc:frame:button:1:post_url': 'of:button:1:post_url',
'fc:frame:button:2': 'of:button:2',
'fc:frame:button:2:action': 'of:button:2:action',
'fc:frame:button:2:target': 'of:button:2:target',
'fc:frame:button:2:post_url': 'of:button:2:post_url',
'fc:frame:button:3': 'of:button:3',
'fc:frame:button:3:action': 'of:button:3:action',
'fc:frame:button:3:target': 'of:button:3:target',
'fc:frame:button:3:post_url': 'of:button:3:post_url',
'fc:frame:button:4': 'of:button:4',
'fc:frame:button:4:action': 'of:button:4:action',
'fc:frame:button:4:target': 'of:button:4:target',
'fc:frame:button:4:post_url': 'of:button:4:post_url',
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Generate button tag mappings dynamically to reduce duplication

The mappings for button tags are hardcoded for buttons 1 to 4. To enhance scalability and reduce code duplication, consider generating these mappings dynamically. This approach simplifies the code and makes it easier to support more buttons in the future.

Here's how you can modify the code to generate button tag mappings dynamically:

 const openFrameEquivalentTags: Record<string, string> = {
     'fc:frame:state': 'of:state',
     'fc:frame:image': 'of:image',
     'fc:frame:image:aspect_ratio': 'of:image:aspect_ratio',
     'fc:frame:post_url': 'of:post_url',
     'fc:frame:input:text': 'of:input:text',
 };

+// Dynamically generate button tag mappings
+const maxButtons = 4; // Adjust if needed
+for (let i = 1; i <= maxButtons; i++) {
+    openFrameEquivalentTags[`fc:frame:button:${i}`] = `of:button:${i}`;
+    openFrameEquivalentTags[`fc:frame:button:${i}:action`] = `of:button:${i}:action`;
+    openFrameEquivalentTags[`fc:frame:button:${i}:target`] = `of:button:${i}:target`;
+    openFrameEquivalentTags[`fc:frame:button:${i}:post_url`] = `of:button:${i}:post_url`;
+}
📝 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 openFrameEquivalentTags: Record<string, string> = {
'fc:frame:state': 'of:state',
'fc:frame:image': 'of:image',
'fc:frame:image:aspect_ratio': 'of:image:aspect_ratio',
'fc:frame:post_url': 'of:post_url',
'fc:frame:input:text': 'of:input:text',
'fc:frame:button:1': 'of:button:1',
'fc:frame:button:1:action': 'of:button:1:action',
'fc:frame:button:1:target': 'of:button:1:target',
'fc:frame:button:1:post_url': 'of:button:1:post_url',
'fc:frame:button:2': 'of:button:2',
'fc:frame:button:2:action': 'of:button:2:action',
'fc:frame:button:2:target': 'of:button:2:target',
'fc:frame:button:2:post_url': 'of:button:2:post_url',
'fc:frame:button:3': 'of:button:3',
'fc:frame:button:3:action': 'of:button:3:action',
'fc:frame:button:3:target': 'of:button:3:target',
'fc:frame:button:3:post_url': 'of:button:3:post_url',
'fc:frame:button:4': 'of:button:4',
'fc:frame:button:4:action': 'of:button:4:action',
'fc:frame:button:4:target': 'of:button:4:target',
'fc:frame:button:4:post_url': 'of:button:4:post_url',
const openFrameEquivalentTags: Record<string, string> = {
'fc:frame:state': 'of:state',
'fc:frame:image': 'of:image',
'fc:frame:image:aspect_ratio': 'of:image:aspect_ratio',
'fc:frame:post_url': 'of:post_url',
'fc:frame:input:text': 'of:input:text',
};
// Dynamically generate button tag mappings
const maxButtons = 4; // Adjust if needed
for (let i = 1; i <= maxButtons; i++) {
openFrameEquivalentTags[`fc:frame:button:${i}`] = `of:button:${i}`;
openFrameEquivalentTags[`fc:frame:button:${i}:action`] = `of:button:${i}:action`;
openFrameEquivalentTags[`fc:frame:button:${i}:target`] = `of:button:${i}:target`;
openFrameEquivalentTags[`fc:frame:button:${i}:post_url`] = `of:button:${i}:post_url`;
}

Copy link
Contributor

@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 and nitpick comments (2)
lib/validate.ts (2)

20-20: Address TODO comment for inputText

There's a TODO comment regarding the inputText property. Consider implementing the correct type for inputText using NeynarValidatedFrameActionResponse['action']['input']['text'] as suggested in the comment.


189-190: Address TODO comments for user information in Lens and XMTP

There are TODO comments regarding userName and userIcon in both the Lens and XMTP standardization functions. Consider implementing these fields using the respective protocol clients (Lens client and XMTP client) to provide more complete user information.

Also applies to: 209-210

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ed28aec and 2cf19b0.

📒 Files selected for processing (1)
  • lib/validate.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
lib/validate.ts (5)

1-53: LGTM: Import statements and type definitions

The import statements and type definitions are well-structured and comprehensive. They cover all the necessary protocols (Farcaster, Lens, and XMTP) and provide a clear structure for the validated frame payload.


55-72: LGTM: validatePayload function

The validatePayload function is well-structured and handles different protocols appropriately. It correctly delegates to protocol-specific validation functions and provides a clear error message for unsupported protocols.


80-110: LGTM: validatePayloadFarcaster function

The validatePayloadFarcaster function is well-implemented. It properly handles API communication, error cases, and validity checks. The use of an environment variable for the API key is a good security practice.


137-212: LGTM: Standardization functions

The standardization functions for Farcaster, Lens, and XMTP are well-implemented. They correctly map protocol-specific payloads to the common FramePayloadValidated type, ensuring consistency across different protocols. The additional protocol-specific information in the Farcaster function provides valuable context.


1-212: Overall assessment: Well-implemented multi-protocol frame validation system

The lib/validate.ts file implements a comprehensive and well-structured system for validating and standardizing frame payloads across multiple protocols (Farcaster, Lens, and XMTP). The code is generally well-organized and follows good practices.

Key strengths:

  1. Clear type definitions for frame payloads
  2. Protocol-specific validation functions
  3. Standardization functions to ensure consistency across protocols

Areas for improvement:

  1. Enhance Farcaster payload detection logic
  2. Add validity check for Airstack response
  3. Address TODO comments for user information in Lens and XMTP standardization
  4. Implement the correct type for inputText in FramePayloadValidated

Addressing these minor issues will further improve the robustness and completeness of the implementation.

Comment on lines +76 to +78
export function isFarcasterFrameActionPayload(framePayload: FramePayload): boolean {
return !framePayload.clientProtocol
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance Farcaster payload detection logic

The current implementation of isFarcasterFrameActionPayload assumes that any payload with an undefined clientProtocol is a Farcaster payload. This approach might lead to false positives if clientProtocol is undefined for other reasons. Consider adding additional checks or a more explicit identifier for Farcaster payloads to improve accuracy.

Comment on lines +112 to +135
export async function validatePayloadAirstack(
body: FarcasterFramePayload,
airstackKey: string
): Promise<any> {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'x-airstack-hubs': airstackKey,
},
body: new Uint8Array(
body.trustedData.messageBytes.match(/.{1,2}/g)!.map((byte) => Number.parseInt(byte, 16))
),
}

const r = await fetch('https://hubs.airstack.xyz/v1/validateMessage', options)
.then((response) => response.json())
.catch((err) => {
console.error(err)
throw new Error('AIRSTACK_PAYLOAD_COULD_NOT_BE_VALIDATED')
})

return r
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validity check for Airstack response

The validatePayloadAirstack function successfully sends a request to the Airstack API and handles potential errors. However, unlike validatePayloadFarcaster, it doesn't check if the response indicates a valid payload. Consider adding a validity check to ensure the Airstack validation was successful before returning the response.

Example:

if (!r.valid) {
  throw new Error('AIRSTACK_PAYLOAD_NOT_VALID');
}

@FTCHD FTCHD changed the base branch from dev to fh-2 October 21, 2024 13:54
@FTCHD FTCHD merged commit 2e12c96 into fh-2 Oct 21, 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.

[FH-2] Open Frames Implementation
2 participants