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

feat: add torii tokens functions to dojo sdk #339

Merged
merged 1 commit into from
Nov 26, 2024
Merged

Conversation

MartianGreed
Copy link
Collaborator

@MartianGreed MartianGreed commented Nov 26, 2024

Closes #

Introduced changes

Checklist

  • Linked relevant issue
  • Updated relevant documentation
  • Added relevant tests
  • Add a dedicated CI job for new examples
  • Performed self-review of the code

Summary by CodeRabbit

  • New Features
    • Introduced two asynchronous methods to the SDK:
      • getTokens: Fetches token data for specified contract addresses.
      • getTokenBalances: Retrieves token balances for specified accounts and contracts.

These enhancements improve the SDK's capability to manage and access token information efficiently.

Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

This pull request introduces two new asynchronous methods to the SDK's initialization function: getTokens and getTokenBalances. The getTokens method retrieves token data for specified contract addresses, while the getTokenBalances method fetches balance information for given account and contract addresses. Both methods are added to the object returned by the init function, enhancing the SDK's capabilities without altering existing functionalities or error handling.

Changes

File Path Change Summary
packages/sdk/src/index.ts Added methods: getTokens(contract_addresses: string[]): Promise<torii.Tokens> and getTokenBalances(account_addresses: string[], contract_addresses: string[]): Promise<torii.TokenBalances> to the init function.
packages/sdk/src/types.ts Updated SDK interface to include getTokens and getTokenBalances method signatures.

Possibly related PRs

🐰 In the meadow where tokens play,
New methods hop in bright array.
With balances and tokens near,
The SDK's charm now crystal clear!
Fetching data, swift and bright,
The rabbit's code brings pure delight! 🐇✨


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

@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 (1)
packages/sdk/src/types.ts (1)

310-323: LGTM! Consider enhancing the JSDoc documentation.

The new token-related methods are well-structured and properly typed. However, the JSDoc documentation could be more descriptive to help users better understand these methods.

Consider expanding the JSDoc documentation as follows:

     /**
+     * Retrieves token data for the specified contract addresses.
+     * 
      * @param {string[]} contract_addresses - Array of contract addresses to fetch token data from
+     * @throws {Error} If the token data cannot be retrieved
      * @returns {Promise<torii.Tokens>}
      */
     getTokens(contract_addresses: string[]): Promise<torii.Tokens>;
     /**
+     * Retrieves token balances for the specified accounts and contracts.
+     * 
      * @param {string[]} account_addresses - Array of account addresses to check balances for
      * @param {string[]} contract_addresses - Array of contract addresses to check balances from
+     * @throws {Error} If the token balances cannot be retrieved
      * @returns {Promise<torii.TokenBalances>}
      */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e7715f6 and be5c1a8.

📒 Files selected for processing (2)
  • packages/sdk/src/index.ts (1 hunks)
  • packages/sdk/src/types.ts (1 hunks)
🔇 Additional comments (1)
packages/sdk/src/index.ts (1)

159-183: Verify SDK interface type definitions

The implementation looks well-integrated with the existing code. However, we should verify that these new methods are properly defined in the SDK interface.

✅ Verification successful

Let me gather more information to verify the SDK interface definitions.


Let me try one more search with different patterns to locate the interface definitions.


SDK interface is properly defined

The verification is complete. The getTokens and getTokenBalances methods are correctly defined in the SDK interface in packages/sdk/src/types.ts (lines 441-454). The interface includes proper TypeScript types and matches the implementation in index.ts. The methods are also properly importing the required types from @dojoengine/torii-client.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the new methods are properly defined in the SDK interface
# Expected: Find type definitions for getTokens and getTokenBalances in the SDK interface

# Search for SDK interface definition and its token-related methods
ast-grep --pattern 'interface SDK {
  $$$
  getTokens($$$): $$$
  getTokenBalances($$$): $$$
  $$$
}'

# Verify torii.Tokens and torii.TokenBalances types are properly imported
rg -A 2 'import.*torii-client'

Length of output: 5835


Script:

#!/bin/bash
# Search for SDK interface definition in types.ts
ast-grep --pattern 'interface SDK {
  $$$
}'

# Also check for any type definitions related to tokens
rg -A 5 'type.*Token' packages/sdk/src/types.ts

Length of output: 96


Script:

#!/bin/bash
# Search for any interface definitions in types.ts
cat packages/sdk/src/types.ts

# Also check the index.ts file since it contains the implementation
cat packages/sdk/src/index.ts

Length of output: 17832

Comment on lines +160 to +168
/**
* @param {(string)[]} contract_addresses
* @returns {Promise<Tokens>}
*/
getTokens: async (
contract_addresses: string[]
): Promise<torii.Tokens> => {
return await client.getTokens(contract_addresses);
},
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance documentation and error handling for getTokens

The implementation looks good but could benefit from some improvements:

  1. JSDoc needs a proper description and complete param/return documentation
  2. Consider adding input validation for contract_addresses
  3. Add error handling wrapper similar to sendMessage method

Consider updating the implementation like this:

        /**
+        * Retrieves token data for specified contract addresses.
         * @param {string[]} contract_addresses - Array of contract addresses to fetch token data for
+        * @returns {Promise<torii.Tokens>} Promise resolving to token data for the specified contracts
+        * @throws {Error} If the token data fetch fails
         */
        getTokens: async (
            contract_addresses: string[]
        ): Promise<torii.Tokens> => {
+           if (!contract_addresses?.length) {
+               throw new Error("contract_addresses array cannot be empty");
+           }
+           try {
                return await client.getTokens(contract_addresses);
+           } catch (error) {
+               console.error("Failed to fetch tokens:", error);
+               throw error;
+           }
        },
📝 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
/**
* @param {(string)[]} contract_addresses
* @returns {Promise<Tokens>}
*/
getTokens: async (
contract_addresses: string[]
): Promise<torii.Tokens> => {
return await client.getTokens(contract_addresses);
},
/**
* Retrieves token data for specified contract addresses.
* @param {string[]} contract_addresses - Array of contract addresses to fetch token data for
* @returns {Promise<torii.Tokens>} Promise resolving to token data for the specified contracts
* @throws {Error} If the token data fetch fails
*/
getTokens: async (
contract_addresses: string[]
): Promise<torii.Tokens> => {
if (!contract_addresses?.length) {
throw new Error("contract_addresses array cannot be empty");
}
try {
return await client.getTokens(contract_addresses);
} catch (error) {
console.error("Failed to fetch tokens:", error);
throw error;
}
},

Comment on lines +170 to +183
/**
* @param {(string)[]} account_addresses
* @param {(string)[]} contract_addresses
* @returns {Promise<TokenBalances>}
*/
getTokenBalances: async (
account_addresses: string[],
contract_addresses: string[]
): Promise<torii.TokenBalances> => {
return await client.getTokenBalances(
account_addresses,
contract_addresses
);
},
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance documentation and error handling for getTokenBalances

Similar to getTokens, this implementation needs improvements in documentation and error handling:

  1. JSDoc needs a proper description and complete param/return documentation
  2. Consider adding input validation for both arrays
  3. Add error handling wrapper

Consider updating the implementation like this:

        /**
+        * Retrieves token balances for specified accounts and contracts.
         * @param {string[]} account_addresses - Array of account addresses to fetch balances for
         * @param {string[]} contract_addresses - Array of contract addresses to fetch balances from
+        * @returns {Promise<torii.TokenBalances>} Promise resolving to token balances for the specified accounts and contracts
+        * @throws {Error} If the balance fetch fails
         */
        getTokenBalances: async (
            account_addresses: string[],
            contract_addresses: string[]
        ): Promise<torii.TokenBalances> => {
+           if (!account_addresses?.length || !contract_addresses?.length) {
+               throw new Error("Both account_addresses and contract_addresses arrays must not be empty");
+           }
+           try {
                return await client.getTokenBalances(
                    account_addresses,
                    contract_addresses
                );
+           } catch (error) {
+               console.error("Failed to fetch token balances:", error);
+               throw error;
+           }
        },
📝 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
/**
* @param {(string)[]} account_addresses
* @param {(string)[]} contract_addresses
* @returns {Promise<TokenBalances>}
*/
getTokenBalances: async (
account_addresses: string[],
contract_addresses: string[]
): Promise<torii.TokenBalances> => {
return await client.getTokenBalances(
account_addresses,
contract_addresses
);
},
/**
* Retrieves token balances for specified accounts and contracts.
* @param {string[]} account_addresses - Array of account addresses to fetch balances for
* @param {string[]} contract_addresses - Array of contract addresses to fetch balances from
* @returns {Promise<torii.TokenBalances>} Promise resolving to token balances for the specified accounts and contracts
* @throws {Error} If the balance fetch fails
*/
getTokenBalances: async (
account_addresses: string[],
contract_addresses: string[]
): Promise<torii.TokenBalances> => {
if (!account_addresses?.length || !contract_addresses?.length) {
throw new Error("Both account_addresses and contract_addresses arrays must not be empty");
}
try {
return await client.getTokenBalances(
account_addresses,
contract_addresses
);
} catch (error) {
console.error("Failed to fetch token balances:", error);
throw error;
}
},

@MartianGreed MartianGreed merged commit b08d849 into main Nov 26, 2024
3 checks passed
@MartianGreed MartianGreed deleted the feat/torii-tokens branch November 26, 2024 17:21
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