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

I init zora collections API. #2

Merged
merged 6 commits into from
Jul 28, 2024
Merged

Conversation

SweetmanTech
Copy link
Owner

@SweetmanTech SweetmanTech commented Jul 28, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new GET API endpoint for retrieving and formatting logs related to new contract setups.
    • Added a utility function for processing log data to enhance display and handling consistency.
    • Expanded API functionality with an additional endpoint for collections.
    • Implemented a client creation function for connecting to blockchain networks.
  • Bug Fixes

    • Improved error handling and response clarity for log retrieval operations.
  • Documentation

    • Updated endpoint list with new routes for better data retrieval options.
  • Refactor

    • Organized exports from the viem module for streamlined imports and better maintainability.

Copy link

vercel bot commented Jul 28, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
onchain-magic-api ✅ Ready (Inspect) Visit Preview Jul 28, 2024 4:15am
onchain-magic-api-yvyz ✅ Ready (Inspect) Visit Preview Jul 28, 2024 4:15am

Copy link

coderabbitai bot commented Jul 28, 2024

Warning

Rate limit exceeded

@SweetmanTech has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 26 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between d293855 and f3eb200.

Walkthrough

The recent updates introduce several utility functions and constants that enhance the application’s ability to interact with the Zora blockchain. Key features include formatting log data for better usability, retrieving contract setup logs, and establishing network configurations. The new code modularizes these functionalities, improving both error handling and the overall structure of API interactions, paving the way for a more robust blockchain integration.

Changes

File Path Change Summary
app/api/zora/collections/... Added formatLogs utility to transform log entries; implemented a new GET endpoint for fetching logs.
lib/consts.tsx Introduced constants for Zora blockchain integration including CHAIN, CHAIN_ID, and addresses.
lib/getEndpointsList.tsx Expanded the endpoints array to include a new GET request for the /api/zora/collections route.
lib/viem/... Added getViemNetwork function to map chain IDs; created index and getPublicClient for client instances.
lib/zora/getSetupNewContractLogs.tsx Implemented a function to fetch setup logs from the Zora protocol using a public client.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant ContractLogs

    Client->>API: GET /api/zora/collections
    API->>ContractLogs: Fetch logs
    ContractLogs-->>API: Return logs
    API->>Client: JSON response with formatted logs
Loading

Poem

🐇 In fields of code, a rabbit hops,
With logs and chains, the magic pops!
New routes to dance, constants to cheer,
Zora's whispers, crystal clear.
So let us leap through bytes and strings,
For in this world, a coder sings! ✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@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, codebase verification and nitpick comments (4)
lib/viem/viem.tsx (2)

1-3: Organize imports for readability.

Consider grouping imports from the same module together for better readability.

-import { PublicClient, createPublicClient, http } from "viem";
-import getViemNetwork from "./getViemNetwork";
-import { zora } from "viem/chains";
+import { PublicClient, createPublicClient, http, zora } from "viem";
+import getViemNetwork from "./getViemNetwork";

5-14: Consider adding explicit error handling for invalid chain IDs in getViemNetwork.

Currently, the function defaults to mainnet for any unrecognized chainId, which could lead to confusion. Adding explicit error handling or logging for invalid chain IDs would improve the robustness and clarity of the function.

  • lib/viem/getViemNetwork.tsx: Add error handling or logging in the default case of the switch statement.
Analysis chain

LGTM! Ensure proper error handling.

The function looks good and correctly handles different chain IDs.

However, consider adding error handling for cases where getViemNetwork returns an invalid network configuration.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `getViemNetwork` returns valid network configurations for all supported chain IDs.

# Test: Search for the function usage and ensure valid configurations are returned.
rg --type python -A 5 $'getViemNetwork'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify that `getViemNetwork` returns valid network configurations for all supported chain IDs.

# Test: Search for the function usage and ensure valid configurations are returned.
rg --type ts -A 5 'getViemNetwork'

Length of output: 923


Script:

#!/bin/bash
# Description: Verify that `getViemNetwork` handles all chain IDs correctly and includes error handling for invalid IDs.

# Display the complete implementation of `getViemNetwork` function.
rg --type ts 'const getViemNetwork = ' -A 20

Length of output: 1122


Script:

#!/bin/bash
# Description: Verify the complete implementation of `getViemNetwork` function, focusing on the default case handling.

# Display the remaining lines of the `getViemNetwork` function to understand the default case handling.
rg --type ts 'const getViemNetwork = ' -A 30

Length of output: 1320

lib/zora/getSetupNewContractLogs.tsx (1)

1-7: Organize imports for readability.

Consider grouping imports from the same module together for better readability.

-import { CHAIN_ID, NEWTRO_ARTS_ADDRESS, NEWTRO_FIRST_ZORA_BLOCK } from '../consts';
-import {
-  zoraCreator1155FactoryImplAddress,
-  zoraCreator1155FactoryImplABI,
-} from '@zoralabs/protocol-deployments';
-import { getPublicClient } from '../viem';
+import { 
+  CHAIN_ID, 
+  NEWTRO_ARTS_ADDRESS, 
+  NEWTRO_FIRST_ZORA_BLOCK 
+} from '../consts';
+import { 
+  zoraCreator1155FactoryImplAddress, 
+  zoraCreator1155FactoryImplABI 
+} from '@zoralabs/protocol-deployments';
+import { getPublicClient } from '../viem';
lib/viem/getViemNetwork.tsx (1)

1-11: Organize imports for readability.

Consider grouping imports from the same module together for better readability.

-import {
-  goerli,
-  mainnet,
-  optimism,
-  polygon,
-  polygonMumbai,
-  sepolia,
-  baseSepolia,
-  optimismSepolia,
-  base,
-} from "viem/chains"
+import { 
+  goerli, 
+  mainnet, 
+  optimism, 
+  polygon, 
+  polygonMumbai, 
+  sepolia, 
+  baseSepolia, 
+  optimismSepolia, 
+  base 
+} from "viem/chains";
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 662abf2 and d293855.

Files selected for processing (8)
  • app/api/zora/collections/formatLogs.tsx (1 hunks)
  • app/api/zora/collections/route.ts (1 hunks)
  • lib/consts.tsx (2 hunks)
  • lib/getEndpointsList.tsx (1 hunks)
  • lib/viem/getViemNetwork.tsx (1 hunks)
  • lib/viem/index.tsx (1 hunks)
  • lib/viem/viem.tsx (1 hunks)
  • lib/zora/getSetupNewContractLogs.tsx (1 hunks)
Files skipped from review due to trivial changes (1)
  • lib/viem/index.tsx
Additional comments not posted (7)
lib/getEndpointsList.tsx (1)

1-4: LGTM! Added endpoint is consistent and correct.

The new endpoint for /api/zora/collections is correctly added and follows the same structure as the existing endpoint.

lib/zora/getSetupNewContractLogs.tsx (1)

8-21: LGTM! Ensure proper error handling.

The function looks good and correctly retrieves contract setup logs.

However, consider adding error handling for cases where getPublicClient or getContractEvents fails.

lib/viem/getViemNetwork.tsx (1)

13-35: LGTM! Ensure proper error handling.

The function looks good and correctly handles different chain IDs.

However, consider adding error handling for cases where an unsupported chain ID is provided.

lib/consts.tsx (4)

4-4: Import statement for zora looks good.

The import statement correctly imports zora from viem/chains.


28-28: Declaration of CHAIN looks good.

The CHAIN constant is correctly assigned the value of zora.


29-29: Declaration of CHAIN_ID looks good.

The CHAIN_ID constant is correctly assigned the value of zora.id.


30-31: Declarations of NEWTRO_ARTS_ADDRESS and NEWTRO_FIRST_ZORA_BLOCK look good.

The NEWTRO_ARTS_ADDRESS constant is correctly assigned the value '0x33912a0d6bEFf5Fb8e5B70688CE858D5e7E8104E' and NEWTRO_FIRST_ZORA_BLOCK is correctly assigned the BigInt value 2671653.

Comment on lines +1 to +11
export const formatLogs = (logs: any[]) =>
logs.map((log) => ({
...log,
blockNumber: log.blockNumber.toString(),
transactionIndex: log.transactionIndex.toString(),
logIndex: log.logIndex.toString(),
topics: log.topics.map((topic: any) => topic.toString()),
blockHash: log.blockHash,
transactionHash: log.transactionHash,
removed: log.removed,
}));
Copy link

Choose a reason for hiding this comment

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

Ensure type safety by specifying types.

The function uses any[] and any which can lead to type safety issues. Consider specifying the types for better type safety and readability.

interface Log {
  blockNumber: number;
  transactionIndex: number;
  logIndex: number;
  topics: any[];
  blockHash: string;
  transactionHash: string;
  removed: boolean;
}

export const formatLogs = (logs: Log[]) =>
  logs.map((log) => ({
    ...log,
    blockNumber: log.blockNumber.toString(),
    transactionIndex: log.transactionIndex.toString(),
    logIndex: log.logIndex.toString(),
    topics: log.topics.map((topic: any) => topic.toString()),
    blockHash: log.blockHash,
    transactionHash: log.transactionHash,
    removed: log.removed,
  }));

Comment on lines +1 to +13
import getSetupNewContractLogs from "@/lib/zora/getSetupNewContractLogs";
import { formatLogs } from "./formatLogs";

export async function GET() {
try {
const logs = await getSetupNewContractLogs()
const formattedLogs = formatLogs(logs);
return Response.json({ message: 'success', data: formattedLogs });
} catch (error) {
console.error('Error:', error);
return Response.json({ message: 'failed' }, { status: 400 });
}
}
Copy link

Choose a reason for hiding this comment

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

Improve error response.

The error response should include the error message for better debugging.

-    return Response.json({ message: 'failed' }, { status: 400 });
+    return Response.json({ message: 'failed', error: error.message }, { status: 400 });
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
import getSetupNewContractLogs from "@/lib/zora/getSetupNewContractLogs";
import { formatLogs } from "./formatLogs";
export async function GET() {
try {
const logs = await getSetupNewContractLogs()
const formattedLogs = formatLogs(logs);
return Response.json({ message: 'success', data: formattedLogs });
} catch (error) {
console.error('Error:', error);
return Response.json({ message: 'failed' }, { status: 400 });
}
}
import getSetupNewContractLogs from "@/lib/zora/getSetupNewContractLogs";
import { formatLogs } from "./formatLogs";
export async function GET() {
try {
const logs = await getSetupNewContractLogs()
const formattedLogs = formatLogs(logs);
return Response.json({ message: 'success', data: formattedLogs });
} catch (error) {
console.error('Error:', error);
return Response.json({ message: 'failed', error: error.message }, { status: 400 });
}
}

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