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

Publish rc15 #215

Merged
merged 3 commits into from
Jul 2, 2024
Merged

Publish rc15 #215

merged 3 commits into from
Jul 2, 2024

Conversation

edisonz0718
Copy link
Contributor

@edisonz0718 edisonz0718 commented Jul 2, 2024

Summary by CodeRabbit

  • New Features

    • Introduced StoryProvider context and custom hooks for enhanced Story Protocol integration.
    • Added new React hooks for managing disputes, IP accounts, IP assets, licenses, NFTs, permissions, and royalties.
  • Bug Fixes

    • Updated parameters and functionalities for dispute management methods.
  • Chores

    • Updated package versions and configurations.
    • Added new environment variables and ESLint configurations.
  • Tests

    • Added and refactored extensive test cases for various React hooks and functionalities.

bonnie57 added 3 commits June 18, 2024 11:07
* Modify calling signTypedData by wallet client

* Upload pnpm-lock.yaml

* Remove useless type

* Delete StoryAPI and related tests

* Remove utils useless function

* Refactor client unit test

* Refactor dispute unit tests

* Refactor ipAccount tests

* Refactor nftClient tests

* Add address validation for signature

* Export PermissionSignatureResponse type

* bump up package version to 1.0.0-rc.15
* Modify calling signTypedData by wallet client

* Upload pnpm-lock.yaml

* Generator resource files

* Generate index file

* Add some config

* Add comments for method

* Fix react bundle issue

* Update README.md

* Update bundle config

* Update core-sdk version in order to solve linking react-sdk

* reset core-sdk version

* Link core sdk

* Modify core-sdk reference

* Cancel fix code command

* Set link-workspace-packages false

* Modify pnpm-lock file

* test

* Rename StoryProtocolContext

* Add comments about npmrc

* Modify package.json

* Add getPermissionSignature and export the related types

* Update README.md
* Modify calling signTypedData by wallet client

* Upload pnpm-lock.yaml

* Remove useless code

* Set up test env

* Modify error handle logic

* Modify timeout time

* Add util methods and wrapper

* Add dispute integration test

* Make test serially execute

* Add ipAsset integration test

* Add ipAccount integration

* Add useLicense integration test

* Add permission, royalty, nftClient integration test in react sdk

* Modify test description

* Add nftClient integration test

* Move babel config into package.json

* Return false when license Terms are already attached to IP Asset
Copy link

coderabbitai bot commented Jul 2, 2024

Walkthrough

The changes introduce significant updates to the core-sdk and a new react-sdk, involving version updates, reorganization of types, and functional improvements across various aspects, particularly in the dispute, IP account, license, and NFT handling areas. Additionally, a new ESLint configuration, environment variables, TypeScript setup, and integration tests are added to the react-sdk. The updates streamline existing workflows and enhance the integration of new features.

Changes

File(s) Change Summary
.npmrc Added configuration to disable linking of workspace packages post-publish.
packages/core-sdk/package.json Updated version from 1.0.0-rc.14 to 1.0.0-rc.15.
packages/core-sdk/src/index.ts Reordered and adjusted types, particularly related to permission signatures.
packages/core-sdk/src/resources/dispute.ts, packages/core-sdk/src/resources/ipAccount.ts, packages/core-sdk/src/resources/license.ts Modified functionalities and imports for dispute handling, IP accounts, and license terms.
packages/core-sdk/src/types/... Modified and restructured type definitions and imports.
packages/core-sdk/src/utils/... Refactored utility functions, especially getPermissionSignature.
packages/core-sdk/test/integration/... Modified test initializations and descriptions for disputes and IP accounts.
packages/core-sdk/test/unit/... Consolidated, refactored, and removed imports and tests for various client modules.
packages/react-sdk/.env.example, packages/react-sdk/.eslintrc.cjs Added environment variables and ESLint configuration for a TypeScript project.
packages/react-sdk/README.md Provided documentation for the Story Protocol React SDK.
packages/react-sdk/generator/... Introduced generator scripts and templates for TypeScript code.
packages/react-sdk/src/... Introduced context provider, custom hooks, and various utility functions.
packages/react-sdk/test/... Added and refactored integration and unit tests for disputes, IP accounts, licenses, NFT clients, permissions, and royalties.
packages/react-sdk/test/integration/utils/... Added util functions and a wrapper component for integration tests.
packages/react-sdk/test/jest-environment-jsdom.ts, packages/react-sdk/test/jest-setup.ts Set up Jest environment and configuration for testing.
packages/react-sdk/tsconfig.json Added TypeScript configuration.

Poem

🐇
In code's vast garden, we dance and delight,
New changes bloom with brilliance and light.
🎨 Disputes resolved and licenses anew,
The core's perfected, React SDK too.
Through types and tests, so elegantly planned,
We hop to progress, all code at hand.
🌈✨


Tip

Early access features: enabled

We are currently testing the following features in early access:

  • OpenAI gpt-4o model for code reviews and chat: OpenAI claims that this model is better at understanding and generating code than the previous models. We seek your feedback over the next few weeks before making it generally available.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues.
  • OSS projects are currently opted into early access features by default.

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 Configration 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: 23

Outside diff range and nitpick comments (7)
packages/core-sdk/src/utils/utils.ts (1)

Line range hint 56-56: Remove the unnecessary continue statement.

The continue statement is unnecessary and can be removed for cleaner code.

-      continue;
packages/core-sdk/src/utils/sign.ts (1)

Line range hint 85-85: Fix the use of isNaN.

The use of isNaN is unsafe as it attempts a type coercion. Use Number.isNaN instead.

-  if (deadline && (isNaN(Number(deadline)) || BigInt(deadline) < 0n)) {
+  if (deadline && (Number.isNaN(Number(deadline)) || BigInt(deadline) < 0n)) {
packages/core-sdk/src/resources/license.ts (5)

Line range hint 75-77: Remove unnecessary else clause.

The else clause is unnecessary because the previous branches break early.

      if (request?.txOptions?.waitForTransaction) {
        const txReceipt = await this.rpcClient.waitForTransactionReceipt({ hash: txHash });
        const targetLogs = this.licenseTemplateClient.parseTxLicenseTermsRegisteredEvent(txReceipt);
        return { txHash: txHash, licenseTermsId: targetLogs[0].licenseTermsId };
      } 
-     else {
-       return { txHash: txHash };
-     }
+     return { txHash: txHash };

Line range hint 109-111: Remove unnecessary else clause.

The else clause is unnecessary because the previous branches break early.

      if (request.txOptions?.waitForTransaction) {
        const txReceipt = await this.rpcClient.waitForTransactionReceipt({ hash: txHash });
        const targetLogs = this.licenseTemplateClient.parseTxLicenseTermsRegisteredEvent(txReceipt);
        return { txHash: txHash, licenseTermsId: targetLogs[0].licenseTermsId };
      } 
-     else {
-       return { txHash: txHash };
-     }
+     return { txHash: txHash };

Line range hint 145-147: Remove unnecessary else clause.

The else clause is unnecessary because the previous branches break early.

      if (request.txOptions?.waitForTransaction) {
        const txReceipt = await this.rpcClient.waitForTransactionReceipt({ hash: txHash });
        const targetLogs = this.licenseTemplateClient.parseTxLicenseTermsRegisteredEvent(txReceipt);
        return { txHash: txHash, licenseTermsId: targetLogs[0].licenseTermsId };
      } 
-     else {
-       return { txHash: txHash };
-     }
+     return { txHash: txHash };

Line range hint 199-201: Remove unnecessary else clause.

The else clause is unnecessary because the previous branches break early.

      if (request.txOptions?.waitForTransaction) {
        await this.rpcClient.waitForTransactionReceipt({ hash: txHash });
        return { txHash: txHash, success: true };
      } 
-     else {
-       return { txHash: txHash };
-     }
+     return { txHash: txHash };

Line range hint 280-282: Remove unnecessary else clause.

The else clause is unnecessary because the previous branches break early.

      if (request.txOptions?.waitForTransaction) {
        const txReceipt = await this.rpcClient.waitForTransactionReceipt({ hash: txHash });
        const targetLogs = this.licensingModuleClient.parseTxLicenseTokensMintedEvent(txReceipt);
        const startLicenseTokenId = targetLogs[0].startLicenseTokenId;
        const licenseTokenIds = [];
        for (let i = 0; i < amount; i++) {
          licenseTokenIds.push(startLicenseTokenId + BigInt(i));
        }
        return { txHash: txHash, licenseTokenIds: licenseTokenIds };
      } 
-     else {
-       return { txHash: txHash };
-     }
+     return { txHash: txHash };
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d7367a0 and 2629456.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (51)
  • .npmrc (1 hunks)
  • packages/core-sdk/package.json (1 hunks)
  • packages/core-sdk/src/index.ts (4 hunks)
  • packages/core-sdk/src/resources/dispute.ts (3 hunks)
  • packages/core-sdk/src/resources/ipAccount.ts (1 hunks)
  • packages/core-sdk/src/resources/license.ts (1 hunks)
  • packages/core-sdk/src/types/common.ts (2 hunks)
  • packages/core-sdk/src/types/resources/dispute.ts (2 hunks)
  • packages/core-sdk/src/utils/sign.ts (5 hunks)
  • packages/core-sdk/src/utils/utils.ts (3 hunks)
  • packages/core-sdk/test/integration/dispute.test.ts (3 hunks)
  • packages/core-sdk/test/integration/ipAccount.test.ts (2 hunks)
  • packages/core-sdk/test/integration/nftClient.test.ts (1 hunks)
  • packages/core-sdk/test/integration/utils/util.ts (1 hunks)
  • packages/core-sdk/test/unit/client.test.ts (2 hunks)
  • packages/core-sdk/test/unit/resources/dispute.test.ts (3 hunks)
  • packages/core-sdk/test/unit/resources/ipAccount.test.ts (4 hunks)
  • packages/core-sdk/test/unit/resources/license.test.ts (1 hunks)
  • packages/core-sdk/test/unit/resources/nftClient.test.ts (2 hunks)
  • packages/core-sdk/test/unit/resources/permission.test.ts (1 hunks)
  • packages/core-sdk/test/unit/utils/utils.test.ts (3 hunks)
  • packages/react-sdk/.env.example (1 hunks)
  • packages/react-sdk/.eslintrc.cjs (1 hunks)
  • packages/react-sdk/README.MD (1 hunks)
  • packages/react-sdk/generator/index.js (1 hunks)
  • packages/react-sdk/generator/templates/index.js (1 hunks)
  • packages/react-sdk/generator/templates/resource.js (1 hunks)
  • packages/react-sdk/jest.config.js (1 hunks)
  • packages/react-sdk/package.json (1 hunks)
  • packages/react-sdk/src/StoryProtocolContext.tsx (1 hunks)
  • packages/react-sdk/src/index.ts (1 hunks)
  • packages/react-sdk/src/resources/useDispute.ts (1 hunks)
  • packages/react-sdk/src/resources/useIpAccount.ts (1 hunks)
  • packages/react-sdk/src/resources/useIpAsset.ts (1 hunks)
  • packages/react-sdk/src/resources/useLicense.ts (1 hunks)
  • packages/react-sdk/src/resources/useNftClient.ts (1 hunks)
  • packages/react-sdk/src/resources/usePermission.ts (1 hunks)
  • packages/react-sdk/src/resources/useRoyalty.ts (1 hunks)
  • packages/react-sdk/src/util.ts (1 hunks)
  • packages/react-sdk/test/integration/useDispute.test.ts (1 hunks)
  • packages/react-sdk/test/integration/useIpAccount.test.ts (1 hunks)
  • packages/react-sdk/test/integration/useIpAsset.test.ts (1 hunks)
  • packages/react-sdk/test/integration/useLicense.test.ts (1 hunks)
  • packages/react-sdk/test/integration/useNftClient.test.ts (1 hunks)
  • packages/react-sdk/test/integration/usePermission.test.ts (1 hunks)
  • packages/react-sdk/test/integration/useRoyalty.test.ts (1 hunks)
  • packages/react-sdk/test/integration/utils/Wrapper.tsx (1 hunks)
  • packages/react-sdk/test/integration/utils/util.ts (1 hunks)
  • packages/react-sdk/test/jest-environment-jsdom.ts (1 hunks)
  • packages/react-sdk/test/jest-setup.ts (1 hunks)
  • packages/react-sdk/tsconfig.json (1 hunks)
Files not reviewed due to errors (2)
  • packages/react-sdk/test/integration/useIpAsset.test.ts (no review received)
  • packages/react-sdk/src/resources/usePermission.ts (no review received)
Files skipped from review due to trivial changes (7)
  • .npmrc
  • packages/core-sdk/package.json
  • packages/core-sdk/test/unit/resources/permission.test.ts
  • packages/react-sdk/.env.example
  • packages/react-sdk/jest.config.js
  • packages/react-sdk/test/jest-setup.ts
  • packages/react-sdk/tsconfig.json
Additional context used
Biome
packages/react-sdk/src/util.ts

[error] 4-6: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

packages/react-sdk/test/jest-environment-jsdom.ts

[error] 32-47: The constructor should not return a value.

The constructor is here:

Returning a value from a constructor is ignored.

(lint/correctness/noConstructorReturn)


[error] 36-38: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


[error] 43-45: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

packages/core-sdk/src/utils/utils.ts

[error] 56-56: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)

packages/core-sdk/src/utils/sign.ts

[error] 85-85: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

packages/core-sdk/src/resources/license.ts

[error] 75-77: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


[error] 109-111: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


[error] 145-147: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


[error] 199-201: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


[error] 280-282: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

Gitleaks
packages/core-sdk/test/unit/resources/nftClient.test.ts

16-16: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

Additional comments not posted (115)
packages/react-sdk/.eslintrc.cjs (1)

1-7: ESLint configuration looks good.

The ESLint configuration is correctly set up to extend the custom ESLint configuration and specify the TypeScript project.

packages/react-sdk/test/integration/utils/Wrapper.tsx (1)

1-18: Ensure the environment variable is securely managed.

The SEPOLIA_WALLET_PRIVATE_KEY environment variable is used directly. Ensure it is securely managed and not exposed.

packages/react-sdk/generator/templates/index.js (1)

1-13: Template generation looks good.

The template correctly generates export statements for the specified types and resources.

packages/core-sdk/src/types/common.ts (4)

1-1: Import statement looks good.

The import of Address, Hex, and WalletClient from viem is appropriate and follows the correct syntax.


12-13: Ensure consistent type usage for nonce and deadline.

Using string | number | bigint for both nonce and deadline is flexible but could lead to inconsistencies. Consider standardizing the types to avoid potential issues.

Are there specific reasons for allowing multiple types, or could these be standardized to a single type?


15-15: Type usage for chainId looks good.

Allowing string | number | bigint for chainId is acceptable given the varied representations of chain IDs.


19-20: Export statement for PermissionSignatureResponse looks good.

The type alias for Hex is correctly exported.

packages/react-sdk/src/StoryProtocolContext.tsx (6)

1-2: Import statements look good.

The import of necessary modules from react and @story-protocol/core-sdk is appropriate and follows the correct syntax.


4-7: Type definition for Props looks good.

The Props type correctly defines the expected properties for the StoryProvider component.


9-9: Context creation looks good.

The StoryContext is correctly created with a default value of an empty StoryClient.


11-16: Component implementation looks good.

The StoryProvider component correctly initializes the StoryClient and provides it via context to its children.


17-19: Custom hook implementation looks good.

The useStoryContext custom hook correctly retrieves the StoryClient from context.


20-20: Export statements look good.

The useStoryContext and StoryProvider are correctly exported.

packages/core-sdk/test/integration/nftClient.test.ts (3)

1-3: Import statements look good.

The import of expect from chai and StoryClient from the local src directory is appropriate and follows the correct syntax.


5-9: Test setup looks good.

The describe block and before hook correctly initialize the StoryClient for the tests.


10-20: Test case implementation looks good.

The test case for createNFTCollection correctly verifies the creation of an NFT collection and checks the nftContract field.

packages/core-sdk/src/types/resources/dispute.ts (2)

Line range hint 1-1: Import statement looks good.

The import of Address from viem is appropriate and follows the correct syntax.


Line range hint 3-38: Type definitions look good.

The type definitions for various dispute-related requests and responses are correctly structured and maintainable.

packages/react-sdk/test/integration/useNftClient.test.ts (2)

1-1: Add a blank line after imports.

Adding a blank line after the import statements improves readability.

import { renderHook } from "@testing-library/react";
import { useNftClient } from "../../src";
import Wrapper from "./utils/Wrapper";
import { act } from "react";

+ 
describe("useNftClient Functions", () => {

11-11: Typographical error in test description.

Correct the typographical error in the test description.

-  it("should success when create nft collection", async () => {
+  it("should succeed when creating an NFT collection", async () => {
packages/react-sdk/test/integration/utils/util.ts (1)

1-1: Add a blank line after imports.

Adding a blank line after the import statements improves readability.

import { privateKeyToAccount } from "viem/accounts";
import {
  http,
  createPublicClient,
  createWalletClient,
  Hex,
  Address,
  Chain,
} from "viem";
import { sepolia } from "viem/chains";

+ 
import { SupportedChainIds } from "@story-protocol/core-sdk";
packages/react-sdk/test/integration/useDispute.test.ts (1)

1-6: Ensure consistent import ordering.

Consider grouping and ordering imports logically (e.g., external libraries, internal modules, utilities).

packages/react-sdk/src/resources/useNftClient.ts (1)

1-8: Ensure consistent import ordering.

Consider grouping and ordering imports logically (e.g., external libraries, internal modules, utilities).

packages/react-sdk/generator/templates/resource.js (1)

21-35: Ensure consistent import ordering in generated code.

Consider grouping and ordering imports logically (e.g., external libraries, internal modules, utilities).

packages/react-sdk/src/index.ts (3)

64-76: Ensure the correct and consistent export of local hooks.

The export of various hooks from local resources seems correct. Ensure that these hooks are defined and correctly used within the project.

Verification successful

Verification successful: The local hooks are correctly defined and exported.

The hooks useDispute, useIpAccount, useIpAsset, useLicense, useNftClient, usePermission, and useRoyalty are all correctly defined and exported from their respective files.

  • useDispute in packages/react-sdk/src/resources/useDispute.ts
  • useIpAccount in packages/react-sdk/src/resources/useIpAccount.ts
  • useIpAsset in packages/react-sdk/src/resources/useIpAsset.ts
  • useLicense in packages/react-sdk/src/resources/useLicense.ts
  • useNftClient in packages/react-sdk/src/resources/useNftClient.ts
  • usePermission in packages/react-sdk/src/resources/usePermission.ts
  • useRoyalty in packages/react-sdk/src/resources/useRoyalty.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the existence and correctness of the local hooks
rg --type ts 'useDispute|useIpAccount|useIpAsset|useLicense|useNftClient|usePermission|useRoyalty' packages/react-sdk/src

Length of output: 1873


2-6: Verify the integrity of core-sdk exports.

Ensure that the exports from @story-protocol/core-sdk are correctly imported and used within the project.

Verification successful

The integrity of core-sdk exports has been verified.

The exports getPermissionSignature, AccessPermission, and PIL_TYPE from @story-protocol/core-sdk are correctly imported and used within the react-sdk package.

  • packages/react-sdk/src/index.ts
  • packages/react-sdk/test/integration/useIpAccount.test.ts
  • packages/react-sdk/test/integration/useIpAsset.test.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the existence and correctness of the core-sdk exports
rg --type ts 'getPermissionSignature|AccessPermission|PIL_TYPE' packages/core-sdk/src

Length of output: 3402



Script:

#!/bin/bash
# Verify the usage of the core-sdk exports in the react-sdk package
rg --type ts 'getPermissionSignature|AccessPermission|PIL_TYPE' packages/react-sdk

Length of output: 1298


7-62: Ensure the correct and consistent export of types from core-sdk.

The export of various types from @story-protocol/core-sdk seems correct. Ensure that these types are defined and correctly used within the project.

Verification successful

Verified the correct and consistent export of types from core-sdk.

All types listed in the review comment are defined and correctly used within the project.

  • packages/core-sdk/src/index.ts
  • packages/core-sdk/src/utils/utils.ts
  • packages/core-sdk/src/utils/sign.ts
  • packages/core-sdk/src/resources/license.ts
  • packages/core-sdk/src/types/common.ts
  • packages/core-sdk/src/types/config.ts
  • packages/core-sdk/src/types/resources/dispute.ts
  • packages/core-sdk/src/types/resources/royalty.ts
  • packages/core-sdk/src/types/resources/permission.ts
  • packages/core-sdk/src/types/resources/nftClient.ts
  • packages/core-sdk/src/types/resources/ipAsset.ts
  • packages/core-sdk/src/types/resources/ipAccount.ts
  • packages/core-sdk/src/resources/ipAccount.ts
  • packages/core-sdk/src/resources/dispute.ts
  • packages/core-sdk/src/resources/nftClient.ts
  • packages/core-sdk/src/resources/royalty.ts
  • packages/core-sdk/src/resources/permission.ts
  • packages/core-sdk/src/resources/ipAsset.ts
  • packages/core-sdk/src/client.ts
  • packages/core-sdk/src/abi/generated.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the existence and correctness of the core-sdk types
rg --type ts 'PermissionSignatureRequest|StoryConfig|SupportedChainIds|RaiseDisputeRequest|RaiseDisputeResponse|CancelDisputeRequest|CancelDisputeResponse|ResolveDisputeRequest|ResolveDisputeResponse|IPAccountExecuteRequest|IPAccountExecuteResponse|IPAccountExecuteWithSigRequest|IPAccountExecuteWithSigResponse|IpAccountImplStateResponse|RegisterRequest|RegisterIpResponse|RegisterDerivativeRequest|RegisterDerivativeResponse|RegisterDerivativeWithLicenseTokensRequest|RegisterDerivativeWithLicenseTokensResponse|CreateIpAssetWithPilTermsRequest|CreateIpAssetWithPilTermsResponse|RegisterIpAndAttachPilTermsRequest|RegisterIpAndAttachPilTermsResponse|RegisterIpAndMakeDerivativeRequest|RegisterIpAndMakeDerivativeResponse|RegisterNonComSocialRemixingPILRequest|RegisterPILResponse|RegisterCommercialUsePILRequest|RegisterCommercialRemixPILRequest|AttachLicenseTermsRequest|AttachLicenseTermsResponse|MintLicenseTokensRequest|MintLicenseTokensResponse|LicenseTermsId|PiLicenseTemplateGetLicenseTermsResponse|CreateNFTCollectionRequest|CreateNFTCollectionResponse|SetPermissionsRequest|SetPermissionsResponse|CreateSetPermissionSignatureRequest|SetAllPermissionsRequest|SetBatchPermissionsRequest|CreateBatchPermissionSignatureRequest|CollectRoyaltyTokensRequest|CollectRoyaltyTokensResponse|PayRoyaltyOnBehalfRequest|PayRoyaltyOnBehalfResponse|ClaimableRevenueRequest|ClaimableRevenueResponse|ClaimRevenueRequest|ClaimRevenueResponse|SnapshotRequest|SnapshotResponse' packages/core-sdk/src

Length of output: 33466

packages/core-sdk/src/index.ts (2)

91-91: Ensure the correct and consistent export of PermissionSignatureRequest and PermissionSignatureResponse.

The export of these types from ./types/common seems correct. Ensure that these types are defined and correctly used within the project.

Verification successful

The export of PermissionSignatureRequest and PermissionSignatureResponse is correct and consistent.

The types are defined in packages/core-sdk/src/types/common.ts and are correctly used within the project, particularly in packages/core-sdk/src/utils/sign.ts.

  • packages/core-sdk/src/types/common.ts
  • packages/core-sdk/src/utils/sign.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the existence and correctness of the common types
rg --type ts 'PermissionSignatureRequest|PermissionSignatureResponse' packages/core-sdk/src/types/common.ts

Length of output: 199



Script:

#!/bin/bash
# Verify the usage of PermissionSignatureRequest and PermissionSignatureResponse in the codebase
rg 'PermissionSignatureRequest|PermissionSignatureResponse' --type ts

Length of output: 1948


16-16: Ensure the correct and consistent export of types from ipAsset.

The export of various types from ./types/resources/ipAsset seems correct. Ensure that these types are defined and correctly used within the project.

Verification successful

Ensure the correct and consistent export of types from ipAsset.

The types from ipAsset.ts are correctly defined. Verify that all these types are exported from packages/core-sdk/src/index.ts.


The export of types from ipAsset is correct and consistent.

The types from ipAsset.ts are correctly defined and consistently exported from packages/core-sdk/src/index.ts.

  • RegisterRequest
  • RegisterIpResponse
  • RegisterDerivativeResponse
  • RegisterDerivativeRequest
  • RegisterDerivativeWithLicenseTokensRequest
  • RegisterDerivativeWithLicenseTokensResponse
  • CreateIpAssetWithPilTermsRequest
  • CreateIpAssetWithPilTermsResponse
  • RegisterIpAndMakeDerivativeRequest
  • RegisterIpAndMakeDerivativeResponse
  • RegisterIpAndAttachPilTermsRequest
  • RegisterIpAndAttachPilTermsResponse
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the existence and correctness of the ipAsset types
rg --type ts 'RegisterRequest|RegisterIpResponse|RegisterDerivativeResponse|RegisterDerivativeRequest|RegisterDerivativeWithLicenseTokensRequest|RegisterDerivativeWithLicenseTokensResponse|CreateIpAssetWithPilTermsRequest|CreateIpAssetWithPilTermsResponse|RegisterIpAndMakeDerivativeRequest|RegisterIpAndMakeDerivativeResponse|RegisterIpAndAttachPilTermsRequest|RegisterIpAndAttachPilTermsResponse' packages/core-sdk/src/types/resources/ipAsset.ts

Length of output: 1025



Script:

#!/bin/bash
# Verify the export statements in packages/core-sdk/src/index.ts for the types from ipAsset
rg --type ts 'RegisterRequest|RegisterIpResponse|RegisterDerivativeResponse|RegisterDerivativeRequest|RegisterDerivativeWithLicenseTokensRequest|RegisterDerivativeWithLicenseTokensResponse|CreateIpAssetWithPilTermsRequest|CreateIpAssetWithPilTermsResponse|RegisterIpAndMakeDerivativeRequest|RegisterIpAndMakeDerivativeResponse|RegisterIpAndAttachPilTermsRequest|RegisterIpAndAttachPilTermsResponse' packages/core-sdk/src/index.ts

Length of output: 851

packages/react-sdk/README.MD (4)

1-3: Clarify the purpose of the SDK.

The introduction is brief and could benefit from a more detailed explanation of what the SDK does and its key features.

- The react-sdk is a library that provides a set of hooks to interact with the SDK. It is designed to be used in a React application.
+ The Story Protocol React SDK is a library that provides a set of hooks to interact with the Story Protocol SDK. It is designed to be used in a React application, enabling seamless integration with Story Protocol's features such as IP asset registration, license management, and more.

7-25: LGTM!

The instructions for generating the React SDK are clear and concise.


27-47: Improve code formatting for readability.

The JSX code block could be formatted for better readability.

- <StoryProvider
-  config={{
-    chainId: "sepolia",
-    transport: http("RPC_URL"),
-    wallet: walletClient,
-  }}
-  </StoryProvider>
+ <StoryProvider
+   config={{
+     chainId: "sepolia",
+     transport: http("RPC_URL"),
+     wallet: walletClient,
+   }}
+ >
+ </StoryProvider>

57-84: LGTM!

The instructions for building and testing the SDK locally are clear and concise.

packages/core-sdk/test/integration/ipAccount.test.ts (3)

Line range hint 12-28: LGTM!

The before hook correctly initializes the client and registers an IP asset.


Line range hint 30-34: LGTM!

The test case for the execute method correctly verifies the expected behavior.


Line range hint 36-55: LGTM!

The test case for the executeWithSig method correctly verifies the expected behavior.

packages/core-sdk/test/unit/resources/nftClient.test.ts (4)

29-40: LGTM!

The test case for the mint fee error correctly verifies the expected behavior.


44-54: LGTM!

The test case for the invalid mint fee token correctly verifies the expected behavior.


59-70: LGTM!

The test case for successful NFT collection creation correctly verifies the expected behavior.


72-86: LGTM!

The test case for successful NFT collection creation with transaction waiting correctly verifies the expected behavior.

packages/core-sdk/test/unit/client.test.ts (2)

Line range hint 7-45: LGTM!

The constructor tests correctly verify the expected behavior for various configurations.


88-95: LGTM!

The getter method tests correctly verify that the StoryClient modules are initialized and not null.

packages/core-sdk/src/utils/sign.ts (1)

Line range hint 20-79: LGTM! But verify the function usage in the codebase.

The code changes are approved. The use of getAddress ensures proper address formatting.

However, ensure that all function calls to getPermissionSignature handle the permissions parameter correctly.

Verification successful

Function usage verified

The permissions parameter in all instances of getPermissionSignature usage is handled correctly.

  • packages/react-sdk/test/integration/useIpAccount.test.ts
  • packages/core-sdk/src/resources/permission.ts
  • packages/core-sdk/src/resources/ipAsset.ts
  • packages/core-sdk/test/integration/ipAccount.test.ts
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `getPermissionSignature` handle the `permissions` parameter correctly.

# Test: Search for the function usage. Expect: Only occurances with the correct parameter handling.
rg --type ts 'getPermissionSignature'

Length of output: 2536



Script:

#!/bin/bash
# Description: Extract and review the usage of `getPermissionSignature` in identified files to confirm the correct handling of the `permissions` parameter.

# List of files to inspect
files=(
  "packages/react-sdk/test/integration/useIpAccount.test.ts"
  "packages/react-sdk/src/index.ts"
  "packages/core-sdk/src/index.ts"
  "packages/core-sdk/test/unit/utils/sign.test.ts"
  "packages/core-sdk/src/resources/permission.ts"
  "packages/core-sdk/src/resources/ipAsset.ts"
  "packages/core-sdk/test/integration/ipAccount.test.ts"
)

# Extract lines where `getPermissionSignature` is called and show surrounding context for better understanding
for file in "${files[@]}"; do
  echo "File: $file"
  rg -C 5 'getPermissionSignature' "$file"
  echo "----------------------------------------"
done

Length of output: 10049

packages/core-sdk/src/resources/ipAccount.ts (3)

Line range hint 24-43: LGTM!

The function handles transaction execution and error handling correctly.


Line range hint 108-115: LGTM!

The function retrieves the IPAccount's internal nonce for transaction ordering correctly.


Line range hint 80-87: LGTM! But verify the function usage in the codebase.

The code changes are approved. The use of getAddress ensures proper address formatting.

However, ensure that all function calls to executeWithSig handle the to and signer parameters correctly.

packages/react-sdk/generator/index.js (3)

1-7: LGTM!

The imports and initial setup appear to be correct.


10-123: LGTM!

The helper functions and main logic appear to be correct and follow best practices.


125-125: LGTM!

The final steps and console output appear to be correct.

packages/react-sdk/test/integration/useIpAccount.test.ts (2)

90-105: LGTM!

The execute test case appears to be correct and follows best practices.


107-148: LGTM!

The executeWithSig test case appears to be correct and follows best practices.

packages/react-sdk/src/resources/useIpAccount.ts (3)

35-50: Ensure comprehensive error handling.

The function handles errors by setting the error state and rethrowing the error. Consider logging the error for better debugging.

+ console.error(e);

63-78: Ensure comprehensive error handling.

The function handles errors by setting the error state and rethrowing the error. Consider logging the error for better debugging.

+ console.error(e);

84-99: Ensure comprehensive error handling.

The function handles errors by setting the error state and rethrowing the error. Consider logging the error for better debugging.

+ console.error(e);
packages/react-sdk/test/integration/useLicense.test.ts (6)

16-30: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await act(async () => {
+     await expect(
+       licenseHook.registerNonComSocialRemixingPIL({
+         txOptions: {
+           waitForTransaction: true,
+         },
+       })
+     ).resolves.toEqual(
+       expect.objectContaining({
+         licenseTermsId: expect.any(BigInt),
+       })
+     );
+   });
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

32-48: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await act(async () => {
+     await expect(
+       licenseHook.registerCommercialUsePIL({
+         mintingFee: "1",
+         currency: mockERC20Address,
+         txOptions: {
+           waitForTransaction: true,
+         },
+       })
+     ).resolves.toEqual(
+       expect.objectContaining({
+         licenseTermsId: expect.any(BigInt),
+       })
+     );
+   });
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

50-67: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await act(async () => {
+     await expect(
+       licenseHook.registerCommercialRemixPIL({
+         mintingFee: "1",
+         commercialRevShare: 100,
+         currency: mockERC20Address,
+         txOptions: {
+           waitForTransaction: true,
+         },
+       })
+     ).resolves.toEqual(
+       expect.objectContaining({
+         licenseTermsId: expect.any(BigInt),
+       })
+     );
+   });
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

98-115: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await act(async () => {
+     await expect(
+       licenseHook.attachLicenseTerms({
+         ipId: ipId,
+         licenseTermsId: licenseId,
+         txOptions: {
+           waitForTransaction: true,
+         },
+       })
+     ).resolves.toEqual(
+       expect.objectContaining({
+         txHash: expect.any(String),
+         success: expect.any(Boolean),
+       })
+     );
+   });
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

117-134: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await act(async () => {
+     await expect(
+       licenseHook.mintLicenseTokens({
+         licenseTermsId: licenseId,
+         licensorIpId: ipId,
+         txOptions: {
+           waitForTransaction: true,
+         },
+       })
+     ).resolves.toEqual(
+       expect.objectContaining({
+         txHash: expect.any(String),
+         licenseTokenIds: expect.any(Array),
+       })
+     );
+   });
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

136-142: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await act(async () => {
+     await expect(licenseHook.getLicenseTerms(licenseId)).resolves.toEqual(
+       expect.any(Object)
+     );
+   });
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }
packages/core-sdk/test/unit/resources/ipAccount.test.ts (6)

Line range hint 14-44: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await ipAccountClient.execute(request);
+ } catch (err) {
+   expect((err as Error).message).equal(
+     "Failed to execute the IP Account transaction: request.ipId address is invalid: 0x123, Address must be a hex value of 20 bytes (40 hex characters) and match its checksum counterpart.",
+   );
+ }

44-53: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   const result = await ipAccountClient.execute({
+     ipId: "0x1daAE3197Bc469Cb97B917aa460a12dD95c6627c",
+     to: zeroAddress,
+     value: 2,
+     data: "0x11111111111111111111111111111",
+   });
+   expect(result.txHash).to.equal(txHash);
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

56-67: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   const result = await ipAccountClient.execute({
+     ipId: "0x1daAE3197Bc469Cb97B917aa460a12dD95c6627c",
+     to: zeroAddress,
+     value: 2,
+     data: "0x11111111111111111111111111111",
+     txOptions: {
+       waitForTransaction: true,
+     },
+   });
+   expect(result.txHash).to.equal(txHash);
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

93-105: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   await ipAccountClient.executeWithSig(request);
+ } catch (err) {
+   expect((err as Error).message).equal(
+     "Failed to execute with signature for the IP Account transaction: request.ipId address is invalid: 0x123, Address must be a hex value of 20 bytes (40 hex characters) and match its checksum counterpart.",
+   );
+ }

Line range hint 108-122: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   const result = await ipAccountClient.executeWithSig({
+     ipId: "0x1daAE3197Bc469Cb97B917aa460a12dD95c6627c",
+     to: zeroAddress,
+     value: 2,
+     data: "0x11111111111111111111111111111",
+     signer: zeroAddress,
+     deadline: 20,
+     signature: zeroAddress,
+     txOptions: {
+       waitForTransaction: true,
+     },
+   });
+   expect(result.txHash).to.equal(txHash);
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }

Line range hint 122-127: Ensure proper error handling in tests.

The test case should handle potential errors to provide better debugging information.

+ try {
+   const state = await ipAccountClient.getIpAccountNonce(
+     "0x73fcb515cee99e4991465ef586cfe2b072ebb512",
+   );
+   expect(state).to.equal(1n);
+ } catch (error) {
+   console.error(error);
+   throw error;
+ }
packages/react-sdk/test/integration/usePermission.test.ts (6)

1-3: Consider organizing imports alphabetically.

Organizing imports alphabetically can improve readability and maintainability.


71-91: Ensure environment variable is set for the test.

The test relies on process.env.SEPOLIA_TEST_WALLET_ADDRESS. Ensure this environment variable is set during testing to avoid unexpected errors.


93-124: Ensure environment variable is set for the test.

The test relies on process.env.SEPOLIA_TEST_WALLET_ADDRESS. Ensure this environment variable is set during testing to avoid unexpected errors.


51-69: Ensure environment variable is set for the test.

The test relies on process.env.SEPOLIA_TEST_WALLET_ADDRESS. Ensure this environment variable is set during testing to avoid unexpected errors.


30-49: Ensure environment variable is set for the test.

The test relies on process.env.SEPOLIA_TEST_WALLET_ADDRESS. Ensure this environment variable is set during testing to avoid unexpected errors.


126-159: Ensure environment variable is set for the test.

The test relies on process.env.SEPOLIA_TEST_WALLET_ADDRESS. Ensure this environment variable is set during testing to avoid unexpected errors.

packages/core-sdk/test/unit/resources/dispute.test.ts (7)

28-39: Consider verifying error message format.

The error message format should be consistent with the actual implementation. Verify that the error message matches the expected format.

Verification successful

Verified error message format.

The error message format in the test case matches the expected format in the implementation.

  • packages/core-sdk/test/unit/resources/dispute.test.ts (line 39)
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the error message format for `raiseDispute`.

# Test: Check the error message format. Expect: The error message matches the expected format.
rg --type ts 'Failed to raise dispute: request.targetIpId address is invalid'

Length of output: 310


43-52: Ensure the stubbed method returns correct value.

The stubbed method raiseDispute should return the correct txHash value.

Verification successful

Confirmed: The stubbed method raiseDispute returns the correct txHash value.

The test case correctly stubs the raiseDispute method using sinon.stub and ensures that the returned value matches the expected txHash.

  • packages/core-sdk/test/unit/resources/dispute.test.ts: Lines 43-52
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the return value of the stubbed method `raiseDispute`.

# Test: Check the return value of the stubbed method. Expect: The return value matches the expected `txHash`.
rg --type ts 'raiseDispute'

Length of output: 3525


127-134: Ensure the stubbed method returns correct value.

The stubbed method resolveDispute should return the correct txHash value.

Verification successful

The stubbed method resolveDispute returns the correct txHash value.

The txHash is correctly defined as 0x063834efe214f4199b1ad7181ce8c5ced3e15d271c8e866da7c89e86ee629cfb and is used appropriately in the test case for resolveDispute.

  • packages/core-sdk/test/unit/resources/dispute.test.ts, line 127
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the return value of the stubbed method `resolveDispute`.

# Test: Check the return value of the stubbed method. Expect: The return value matches the expected `txHash`.
rg --type ts 'resolveDispute'

Length of output: 2921



Script:

#!/bin/bash
# Search for the definition and usage of txHash in dispute.test.ts
rg --type ts 'txHash' packages/core-sdk/test/unit/resources/dispute.test.ts

Length of output: 1520


93-100: Ensure the stubbed method returns correct value.

The stubbed method cancelDispute should return the correct txHash value.

Verification successful

The stubbed method returns the correct value.

The stubbed method cancelDispute correctly returns the expected txHash value in the test.

  • txHash is defined as const txHash = "0x063834efe214f4199b1ad7181ce8c5ced3e15d271c8e866da7c89e86ee629cfb";.
  • The test correctly verifies that cancelDispute returns this txHash.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the return value of the stubbed method `cancelDispute`.

# Test: Check the return value of the stubbed method. Expect: The return value matches the expected `txHash`.
rg --type ts 'cancelDispute'

Length of output: 3533



Script:

#!/bin/bash
# Search for the definition and usage of `txHash` in the test file to verify its correctness.
rg 'txHash' packages/core-sdk/test/unit/resources/dispute.test.ts

Length of output: 1510


55-77: Ensure the stubbed method returns correct values.

The stubbed methods raiseDispute and parseTxDisputeRaisedEvent should return the correct values.

Verification successful

Ensure the stubbed method returns correct values.

The stubbed methods raiseDispute and parseTxDisputeRaisedEvent return the correct values as per their definitions:

  • raiseDispute resolves with txHash.

  • parseTxDisputeRaisedEvent returns an array with an object containing disputeId and other relevant properties.

  • packages/core-sdk/test/unit/resources/dispute.test.ts, lines 55-77

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the return values of the stubbed methods `raiseDispute` and `parseTxDisputeRaisedEvent`.

# Test: Check the return values of the stubbed methods. Expect: The return values match the expected values.
rg --type ts 'raiseDispute'
rg --type ts 'parseTxDisputeRaisedEvent'

Length of output: 3919



Script:

#!/bin/bash
# Description: Verify the return values of the stubbed methods `raiseDispute` and `parseTxDisputeRaisedEvent`.

# Locate the definitions of the methods to verify their expected return values.
ast-grep --lang typescript --pattern 'raiseDispute($_)' 
ast-grep --lang typescript --pattern 'parseTxDisputeRaisedEvent($_)'

Length of output: 128



Script:

#!/bin/bash
# Description: Verify the return values of the stubbed methods `raiseDispute` and `parseTxDisputeRaisedEvent`.

# Locate the definitions of the methods to verify their expected return values.
rg 'raiseDispute' --type ts -A 10
rg 'parseTxDisputeRaisedEvent' --type ts -A 10

Length of output: 19102


82-89: Consider verifying error message format.

The error message format should be consistent with the actual implementation. Verify that the error message matches the expected format.

Verification successful

Verified error message format.

The handleError function formats the error message as ${msg}: ${error.message}, which matches the expected format "Failed to cancel dispute: 500" used in the test case.

  • handleError function implementation:
    export function handleError(error: unknown, msg: string): never {
      if (error instanceof Error) {
        throw new Error(`${msg}: ${error.message}`);
      }
      throw new Error(`${msg}: Unknown error type`);
    }

This confirms that the error message format in the test case is consistent with the actual implementation.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the error message format for `cancelDispute`.

# Test: Check the error message format. Expect: The error message matches the expected format.
rg --type ts 'Failed to cancel dispute:'

Length of output: 173



Script:

#!/bin/bash
# Locate the implementation of the `cancelDispute` method
ast-grep --lang typescript --pattern 'cancelDispute($_) { $$$ }'

Length of output: 514



Script:

#!/bin/bash
# Locate the implementation of the `cancelDispute` method using ast-grep
ast-grep --lang typescript --pattern 'function cancelDispute($_) { $$$ }'

# Locate the implementation of the `cancelDispute` method using rg as a fallback
rg 'cancelDispute' --type ts

Length of output: 3609



Script:

#!/bin/bash
# Extract the implementation of the `cancelDispute` method from dispute.ts
ast-grep --lang typescript --pattern 'public async cancelDispute($_) { $$$ }' packages/core-sdk/src/resources/dispute.ts

Length of output: 583



Script:

#!/bin/bash
# Extract the implementation of the `cancelDispute` method from dispute.ts using rg and sed
rg 'public async cancelDispute' -A 20 packages/core-sdk/src/resources/dispute.ts

Length of output: 832



Script:

#!/bin/bash
# Locate the implementation of the `handleError` function
rg 'function handleError' --type ts

Length of output: 141



Script:

#!/bin/bash
# Extract the implementation of the `handleError` function from errors.ts
rg 'export function handleError' -A 10 packages/core-sdk/src/utils/errors.ts

Length of output: 280


115-123: Consider verifying error message format.

The error message format should be consistent with the actual implementation. Verify that the error message matches the expected format.

Verification successful

Verified: The error message format is consistent with the implementation.

The error message "Failed to resolve dispute: 500" in the test case matches the format produced by the handleError function in the implementation.

  • packages/core-sdk/src/resources/dispute.ts:

    handleError(error, "Failed to resolve dispute");
  • packages/core-sdk/src/utils/errors.ts:

    export function handleError(error: unknown, msg: string): never {
      if (error instanceof Error) {
        throw new Error(`${msg}: ${error.message}`);
      }
      throw new Error(`${msg}: Unknown error type`);
    }
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the error message format for `resolveDispute`.

# Test: Check the error message format. Expect: The error message matches the expected format.
rg --type ts 'Failed to resolve dispute:'

Length of output: 175



Script:

#!/bin/bash
# Description: Locate and display the implementation of the `resolveDispute` method.

# Find the implementation of the `resolveDispute` method.
ast-grep --lang typescript --pattern 'resolveDispute($_) { $$$ }'

Length of output: 516



Script:

#!/bin/bash
# Description: Locate and display the implementation of the `resolveDispute` method.

# Find the implementation of the `resolveDispute` method with a corrected pattern.
ast-grep --lang typescript --pattern 'function resolveDispute($_) { $$$ }'

Length of output: 76



Script:

#!/bin/bash
# Description: Locate and display the implementation of the `resolveDispute` method.

# Find the implementation of the `resolveDispute` method in various patterns.
ast-grep --lang typescript --pattern '(function resolveDispute($_) { $$$ })'
ast-grep --lang typescript --pattern '(resolveDispute($_) { $$$ })'
ast-grep --lang typescript --pattern 'resolveDispute = ($_): $_ => { $$$ }'

Length of output: 226



Script:

#!/bin/bash
# Description: Locate the definition or usage of the `resolveDispute` method.

# Search for the term `resolveDispute` in the codebase.
rg 'resolveDispute'

Length of output: 2911



Script:

#!/bin/bash
# Description: Display the implementation of the `resolveDispute` method in `packages/core-sdk/src/resources/dispute.ts`.

# Extract the implementation of the `resolveDispute` method.
ast-grep --lang typescript --pattern 'public async resolveDispute($_): Promise<$_> { $$$ }' packages/core-sdk/src/resources/dispute.ts

Length of output: 136



Script:

#!/bin/bash
# Description: Display the lines around the implementation of the `resolveDispute` method in `packages/core-sdk/src/resources/dispute.ts`.

# Extract lines around the implementation of the `resolveDispute` method.
rg -A 20 'public async resolveDispute' packages/core-sdk/src/resources/dispute.ts

Length of output: 599



Script:

#!/bin/bash
# Description: Locate and display the implementation of the `handleError` function.

# Search for the definition of the `handleError` function.
rg 'function handleError' 

Length of output: 131



Script:

#!/bin/bash
# Description: Display the implementation of the `handleError` function in `packages/core-sdk/src/utils/errors.ts`.

# Extract the implementation of the `handleError` function.
rg -A 10 'export function handleError' packages/core-sdk/src/utils/errors.ts

Length of output: 280

packages/core-sdk/test/unit/utils/utils.test.ts (5)

Line range hint 1-3: Consider organizing imports alphabetically.

Organizing imports alphabetically can improve readability and maintainability.


Line range hint 35-49: LGTM!

The test cases for chainStringToViemChain are well-written and cover different scenarios.


Line range hint 51-66: LGTM!

The test case for waitTx is well-written and covers the expected behavior.


Line range hint 68-81: LGTM!

The test cases for getAddress are well-written and cover different scenarios.


7-12: Ensure the stubbed method returns correct value.

The stubbed method waitForTransactionReceipt should return the correct value.

Verification successful

Verified: The stubbed method waitForTransactionReceipt returns the correct value as expected in the test cases.

  • The test cases in packages/core-sdk/test/unit/utils/utils.test.ts correctly validate the behavior of the stubbed method waitForTransactionReceipt.
  • The stubbed method is set to return specific values or throw errors, and the tests check for these outcomes appropriately.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the return value of the stubbed method `waitForTransactionReceipt`.

# Test: Check the return value of the stubbed method. Expect: The return value matches the expected value.
rg --type ts 'waitForTransactionReceipt'

Length of output: 4662



Script:

#!/bin/bash
# Extract the relevant test cases from `packages/core-sdk/test/unit/utils/utils.test.ts` to verify the return value of the stubbed method `waitForTransactionReceipt`.

# Get the lines containing and surrounding the usage of `waitForTransactionReceipt` in the test file.
rg --type ts --context 10 'waitForTransactionReceipt' packages/core-sdk/test/unit/utils/utils.test.ts

Length of output: 3171

packages/react-sdk/test/integration/useRoyalty.test.ts (9)

1-1: Add a newline after imports for better readability.

Adding a newline after the import statements improves readability and adheres to common coding conventions.

import { act, renderHook, waitFor } from "@testing-library/react";
import { useIpAccount, useIpAsset, useLicense, useRoyalty } from "../../src";
import Wrapper from "./utils/Wrapper";
import { Address, encodeFunctionData } from "viem";
import { getTokenId, mockERC20Address, mockERC721Address } from "./utils/util";

+ 
describe("useRoyalty Functions", () => {

7-9: Consider restructuring the renderHook calls for better readability.

You can group the renderHook calls together and add comments to describe each hook.

describe("useRoyalty Functions", () => {
  // Initialize hooks
  const {
    result: { current: royaltyHook },
  } = renderHook(() => useRoyalty(), { wrapper: Wrapper });

  const {
    result: { current: ipAssetHook },
  } = renderHook(() => useIpAsset(), { wrapper: Wrapper });

  const {
    result: { current: licenseHook },
  } = renderHook(() => useLicense(), { wrapper: Wrapper });

  const {
    result: { current: ipAccountHook },
  } = renderHook(() => useIpAccount(), { wrapper: Wrapper });

62-77: Consider adding comments to the beforeAll block for better clarity.

Adding comments to describe the steps in the beforeAll block improves readability and understanding.

beforeAll(async () => {
  // Register IPs
  ipId1 = await getIpId();
  ipId2 = await getIpId();

  // Register commercial policy
  const licenseTermsId = await getCommercialPolicyId();
  await attachLicenseTerms(ipId1, licenseTermsId);

  // Register derivative
  await act(async () => {
    await ipAssetHook.registerDerivative({
      childIpId: ipId2,
      parentIpIds: [ipId1],
      licenseTermsIds: [licenseTermsId],
      txOptions: {
        waitForTransaction: true,
      },
    });
  });
});

79-96: Consider adding assertion messages for better debugging.

Adding assertion messages can help identify which part of the test failed.

it("should success when collect royalty tokens", async () => {
  await act(async () => {
    await expect(
      royaltyHook.collectRoyaltyTokens({
        parentIpId: ipId1,
        royaltyVaultIpId: ipId2,
        txOptions: {
          waitForTransaction: true,
        },
      })
    ).resolves.toEqual(
      expect.objectContaining({
        txHash: expect.any(String),
        royaltyTokensCollected: expect.any(BigInt),
      }),
      "Failed to collect royalty tokens"
    );
  });
});

98-116: Consider adding assertion messages for better debugging.

Adding assertion messages can help identify which part of the test failed.

it("should success when pay royalty on behalf", async () => {
  await act(async () => {
    await expect(
      royaltyHook.payRoyaltyOnBehalf({
        receiverIpId: ipId1,
        payerIpId: ipId2,
        token: mockERC20Address,
        amount: "10",
        txOptions: {
          waitForTransaction: true,
        },
      })
    ).resolves.toEqual(
      expect.objectContaining({
        txHash: expect.any(String),
      }),
      "Failed to pay royalty on behalf"
    );
  });
});

118-134: Consider adding assertion messages for better debugging.

Adding assertion messages can help identify which part of the test failed.

it("should success when snapshot", async () => {
  await act(async () => {
    await expect(
      royaltyHook.snapshot({
        royaltyVaultIpId: ipId1,
        txOptions: {
          waitForTransaction: true,
        },
      })
    ).resolves.toEqual(
      expect.objectContaining({
        txHash: expect.any(String),
        snapshotId: expect.any(BigInt),
      }),
      "Failed to create snapshot"
    );
  });
});

135-146: Consider adding assertion messages for better debugging.

Adding assertion messages can help identify which part of the test failed.

it("should success when claimable revenue", async () => {
  await act(async () => {
    await expect(
      royaltyHook.claimableRevenue({
        royaltyVaultIpId: ipId1,
        account: ipId1,
        snapshotId: "1",
        token: mockERC20Address,
      })
    ).resolves.toEqual(expect.any(BigInt), "Failed to claim revenue");
  });
});

148-167: Consider adding assertion messages for better debugging.

Adding assertion messages can help identify which part of the test failed.

it("should success when claim revenue by ipAccount", async () => {
  await act(async () => {
    await expect(
      royaltyHook.claimRevenue({
        royaltyVaultIpId: ipId1,
        snapshotIds: ["1"],
        account: ipId1,
        token: mockERC20Address,
        txOptions: {
          waitForTransaction: true,
        },
      })
    ).resolves.toEqual(
      expect.objectContaining({
        txHash: expect.any(String),
        claimableToken: expect.any(BigInt),
      }),
      "Failed to claim revenue by ipAccount"
    );
  });
});

169-257: Consider adding comments to describe the steps in the test case for better clarity.

Adding comments to describe the steps in the test case improves readability and understanding.

it("should success when claim revenue by ipAccount by EOA", async () => {
  const proxyAddress = await royaltyHook.getRoyaltyVaultAddress(ipId1);

  // Step 1: Transfer token to EOA
  await act(async () => {
    await ipAccountHook.execute({
      to: proxyAddress,
      value: 0,
      ipId: ipId1,
      txOptions: {
        waitForTransaction: true,
      },
      data: encodeFunctionData({
        abi: [
          {
            inputs: [
              {
                internalType: "address",
                name: "to",
                type: "address",
              },
              {
                internalType: "uint256",
                name: "value",
                type: "uint256",
              },
            ],
            name: "transfer",
            outputs: [
              {
                internalType: "bool",
                name: "",
                type: "bool",
              },
            ],
            stateMutability: "nonpayable",
            type: "function",
          },
        ],
        functionName: "transfer",
        args: [
          process.env.SEPOLIA_TEST_WALLET_ADDRESS as Address,
          BigInt(10 * 10 ** 6),
        ],
      }),
    });
  });

  // Step 2: Transfer token to royaltyVault, revenue token
  await act(async () => {
    await royaltyHook.payRoyaltyOnBehalf({
      receiverIpId: ipId1,
      payerIpId: ipId2,
      token: mockERC20Address,
      amount: "10",
      txOptions: {
        waitForTransaction: true,
      },
    });
  });

  // Step 3: Create snapshot
  let snapshotId: bigint;
  await act(async () => {
    snapshotId = (
      await royaltyHook.snapshot({
        royaltyVaultIpId: ipId1,
        txOptions: {
          waitForTransaction: true,
        },
      })
    ).snapshotId!;
  });

  // Step 4: Claim revenue
  await act(async () => {
    await expect(
      royaltyHook.claimRevenue({
        royaltyVaultIpId: ipId1,
        snapshotIds: [snapshotId],
        token: mockERC20Address,
        txOptions: {
          waitForTransaction: true,
        },
      })
    ).resolves.toEqual(
      expect.objectContaining({
        txHash: expect.any(String),
        claimableToken: expect.any(BigInt),
      }),
      "Failed to claim revenue by EOA"
    );
  });
});
packages/react-sdk/src/resources/useRoyalty.ts (4)

1-1: Add a newline after imports for better readability.

Adding a newline after the import statements improves readability and adheres to common coding conventions.

import {
  CollectRoyaltyTokensRequest,
  CollectRoyaltyTokensResponse,
  PayRoyaltyOnBehalfRequest,
  PayRoyaltyOnBehalfResponse,
  ClaimableRevenueRequest,
  ClaimableRevenueResponse,
  ClaimRevenueRequest,
  ClaimRevenueResponse,
  SnapshotRequest,
  SnapshotResponse,
} from "@story-protocol/core-sdk";
import { Hex, Address } from "viem";
import { useState } from "react";

+ 
import { useStoryContext } from "../StoryProtocolContext";
import { handleError } from "../util";

38-46: Fix the JSDoc comment for collectRoyaltyTokens.

The JSDoc comment should be consistent with the function parameters.

/**
 * Allows ancestors to claim the royalty tokens and any accrued revenue tokens.
 * @param request - The request object that contains all data needed to collect royalty tokens.
 *   @param request.parentIpId The IP ID of the ancestor to whom the royalty tokens belong.
 *   @param request.royaltyVaultIpId The ID of the royalty vault.
 *   @param request.txOptions [Optional] The transaction options.
 * @returns A Promise that resolves to an object containing the transaction hash and optionally the amount of royalty tokens collected if waitForTxn is set to true.
 * @emits RoyaltyTokensCollected (ancestorIpId, royaltyTokensCollected)
 */

64-76: Fix the JSDoc comment for payRoyaltyOnBehalf.

The JSDoc comment should be consistent with the function parameters.

/**
 * Allows the function caller to pay royalties to the receiver IP asset on behalf of the payer IP asset.
 * @param request - The request object that contains all data needed to pay royalty on behalf.
 *   @param request.receiverIpId The IP ID that receives the royalties.
 *   @param request.payerIpId The ID of the IP asset that pays the royalties.
 *   @param request.token The token to use to pay the royalties.
 *   @param request.amount The amount to pay.
 *   @param request.txOptions [Optional] The transaction options.
 * @returns A Promise that resolves to an object containing the transaction hash.
 */

91-99: Fix the JSDoc comment for claimableRevenue.

The JSDoc comment should be consistent with the function parameters.

/**
 * Calculates the amount of revenue token claimable by a token holder at a certain snapshot.
 * @param request - The request object that contains all data needed to claim revenue.
 *   @param request.royaltyVaultIpId The ID of the royalty vault.
 *   @param request.account The address of the token holder.
 *   @param request.snapshotId The snapshot ID.
 *   @param request.token The revenue token to claim.
 *   @param request.txOptions [Optional] The transaction options.
 * @returns A Promise that contains the amount of revenue token claimable.
 */
packages/react-sdk/src/resources/useLicense.ts (7)

44-73: LGTM!

The function registerNonComSocialRemixingPIL is correctly implemented with proper state management and error handling.


84-102: LGTM!

The function registerCommercialUsePIL is correctly implemented with proper state management and error handling.


114-132: LGTM!

The function registerCommercialRemixPIL is correctly implemented with proper state management and error handling.


143-158: LGTM!

The function attachLicenseTerms is correctly implemented with proper state management and error handling.


182-197: LGTM!

The function mintLicenseTokens is correctly implemented with proper state management and error handling.


204-221: LGTM!

The function getLicenseTerms is correctly implemented with proper state management and error handling.


223-233: LGTM!

The function useLicense is correctly implemented, returning all the necessary states and functions.

packages/react-sdk/src/resources/useIpAsset.ts (7)

53-68: LGTM!

The function register is correctly implemented with proper state management and error handling.


83-98: LGTM!

The function registerDerivative is correctly implemented with proper state management and error handling.


111-143: LGTM!

The function registerDerivativeWithLicenseTokens is correctly implemented with proper state management and error handling.


163-195: LGTM!

The function mintAndRegisterIpAssetWithPilTerms is correctly implemented with proper state management and error handling.


215-235: LGTM!

The function registerIpAndAttachPilTerms is correctly implemented with proper state management and error handling.


255-270: LGTM!

The function registerDerivativeIp is correctly implemented with proper state management and error handling.


272-282: LGTM!

The function useIpAsset is correctly implemented, returning all the necessary states and functions.

packages/core-sdk/src/resources/license.ts (2)

Line range hint 245-257: LGTM!

The function getLicenseTerms is correctly implemented with proper state management and error handling.


Line range hint 259-261: LGTM!

The function getLicenseTermsId is correctly implemented.

packages/core-sdk/test/unit/resources/license.test.ts (2)

Line range hint 52-56: LGTM!

The test case for registerNonComSocialRemixingPIL when licenseTermsId is registered is correctly implemented.


Line range hint 58-62: LGTM!

The test case for registerNonComSocialRemixingPIL when licenseTermsId is not registered is correctly implemented.

Comment on lines +1 to +7
export const handleError = (error: unknown): string => {
if (error instanceof Error) {
return error.message;
} else {
return "Unhandled error type";
}
};
Copy link

Choose a reason for hiding this comment

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

Refactor: Remove the unnecessary else clause.

The else clause can be omitted because the previous branch returns early.

export const handleError = (error: unknown): string => {
  if (error instanceof Error) {
    return error.message;
  }
-  else {
-    return "Unhandled error type";
-  }
+  return "Unhandled error type";
};
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
export const handleError = (error: unknown): string => {
if (error instanceof Error) {
return error.message;
} else {
return "Unhandled error type";
}
};
export const handleError = (error: unknown): string => {
if (error instanceof Error) {
return error.message;
}
return "Unhandled error type";
};
Tools
Biome

[error] 4-6: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

Comment on lines +7 to +9
const {
result: { current: nftClientHook },
} = renderHook(() => useNftClient(), { wrapper: Wrapper });
Copy link

Choose a reason for hiding this comment

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

Improve hook initialization for better readability.

Destructure the result directly from the renderHook call for better readability.

-  const {
-    result: { current: nftClientHook },
-  } = renderHook(() => useNftClient(), { wrapper: Wrapper });

+  const { result } = renderHook(() => useNftClient(), { wrapper: Wrapper });
+  const nftClientHook = result.current;
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 {
result: { current: nftClientHook },
} = renderHook(() => useNftClient(), { wrapper: Wrapper });
const { result } = renderHook(() => useNftClient(), { wrapper: Wrapper });
const nftClientHook = result.current;

Comment on lines +44 to +48
export const getStoryClientInSepolia = (): StoryClient => {
const config: StoryConfig = {
chainId: "sepolia",
transport: http(RPC),
account: privateKeyToAccount(privateKey || (process.env.SEPOLIA_WALLET_PRIVATE_KEY as Address)),
account: privateKeyToAccount(process.env.SEPOLIA_WALLET_PRIVATE_KEY as Address),
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure environment variable is set.

The environment variable SEPOLIA_WALLET_PRIVATE_KEY is not set, which can cause runtime errors. Please set this environment variable to ensure the function getStoryClientInSepolia works correctly.

  • Location: packages/core-sdk/test/integration/utils/util.ts, lines 44-48
Analysis chain

Ensure environment variable is set.

Verify that SEPOLIA_WALLET_PRIVATE_KEY is set in the environment to avoid runtime errors.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the environment variable `SEPOLIA_WALLET_PRIVATE_KEY` is set.

# Test: Check for the environment variable. Expect: Non-empty value.
if [ -z "${SEPOLIA_WALLET_PRIVATE_KEY}" ]; then
  echo "SEPOLIA_WALLET_PRIVATE_KEY is not set."
  exit 1
else
  echo "SEPOLIA_WALLET_PRIVATE_KEY is set."
fi

Length of output: 111

Comment on lines +43 to +45
} else {
return Reflect.set(target.environment, prop, value);
}
Copy link

Choose a reason for hiding this comment

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

Remove unnecessary else clause.

The else clause can be omitted because the previous branch returns early.

-        } else {
-          return Reflect.set(target.environment, prop, value);
-        }
+        }
+        return Reflect.set(target.environment, prop, value);
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
} else {
return Reflect.set(target.environment, prop, value);
}
}
return Reflect.set(target.environment, prop, value);
Tools
Biome

[error] 43-45: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

Comment on lines +36 to +38
} else {
return Reflect.get(target.environment, prop, receiver);
}
Copy link

Choose a reason for hiding this comment

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

Remove unnecessary else clause.

The else clause can be omitted because the previous branch returns early.

-        } else {
-          return Reflect.get(target.environment, prop, receiver);
-        }
+        }
+        return Reflect.get(target.environment, prop, receiver);
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
} else {
return Reflect.get(target.environment, prop, receiver);
}
}
return Reflect.get(target.environment, prop, receiver);
Tools
Biome

[error] 36-38: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

Comment on lines +77 to +89
try {
setLoadings((prev) => ({ ...prev, payRoyaltyOnBehalf: true }));
setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: null }));
const response = await client.royalty.payRoyaltyOnBehalf(request);
setLoadings((prev) => ({ ...prev, payRoyaltyOnBehalf: false }));
return response;
} catch (e) {
const errorMessage = handleError(e);
setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: errorMessage }));
setLoadings((prev) => ({ ...prev, payRoyaltyOnBehalf: false }));
throw new Error(errorMessage);
}
};
Copy link

Choose a reason for hiding this comment

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

Consider using a loading state wrapper to reduce repetition.

The loading state management can be abstracted into a wrapper function to reduce repetition.

const payRoyaltyOnBehalf = async (
  request: PayRoyaltyOnBehalfRequest
): Promise<PayRoyaltyOnBehalfResponse> => {
  try {
    setLoadingState("payRoyaltyOnBehalf", true);
    setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: null }));
    const response = await client.royalty.payRoyaltyOnBehalf(request);
    setLoadingState("payRoyaltyOnBehalf", false);
    return response;
  } catch (e) {
    const errorMessage = handleError(e);
    setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: errorMessage }));
    setLoadingState("payRoyaltyOnBehalf", false);
    throw new Error(errorMessage);
  }
};
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
try {
setLoadings((prev) => ({ ...prev, payRoyaltyOnBehalf: true }));
setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: null }));
const response = await client.royalty.payRoyaltyOnBehalf(request);
setLoadings((prev) => ({ ...prev, payRoyaltyOnBehalf: false }));
return response;
} catch (e) {
const errorMessage = handleError(e);
setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: errorMessage }));
setLoadings((prev) => ({ ...prev, payRoyaltyOnBehalf: false }));
throw new Error(errorMessage);
}
};
const payRoyaltyOnBehalf = async (
request: PayRoyaltyOnBehalfRequest
): Promise<PayRoyaltyOnBehalfResponse> => {
try {
setLoadingState("payRoyaltyOnBehalf", true);
setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: null }));
const response = await client.royalty.payRoyaltyOnBehalf(request);
setLoadingState("payRoyaltyOnBehalf", false);
return response;
} catch (e) {
const errorMessage = handleError(e);
setErrors((prev) => ({ ...prev, payRoyaltyOnBehalf: errorMessage }));
setLoadingState("payRoyaltyOnBehalf", false);
throw new Error(errorMessage);
}
};

Comment on lines +47 to +62
const collectRoyaltyTokens = async (
request: CollectRoyaltyTokensRequest
): Promise<CollectRoyaltyTokensResponse> => {
try {
setLoadings((prev) => ({ ...prev, collectRoyaltyTokens: true }));
setErrors((prev) => ({ ...prev, collectRoyaltyTokens: null }));
const response = await client.royalty.collectRoyaltyTokens(request);
setLoadings((prev) => ({ ...prev, collectRoyaltyTokens: false }));
return response;
} catch (e) {
const errorMessage = handleError(e);
setErrors((prev) => ({ ...prev, collectRoyaltyTokens: errorMessage }));
setLoadings((prev) => ({ ...prev, collectRoyaltyTokens: false }));
throw new Error(errorMessage);
}
};
Copy link

Choose a reason for hiding this comment

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

Consider using a loading state wrapper to reduce repetition.

The loading state management can be abstracted into a wrapper function to reduce repetition.

const setLoadingState = (key: string, state: boolean) => {
  setLoadings((prev) => ({ ...prev, [key]: state }));
};

const collectRoyaltyTokens = async (
  request: CollectRoyaltyTokensRequest
): Promise<CollectRoyaltyTokensResponse> => {
  try {
    setLoadingState("collectRoyaltyTokens", true);
    setErrors((prev) => ({ ...prev, collectRoyaltyTokens: null }));
    const response = await client.royalty.collectRoyaltyTokens(request);
    setLoadingState("collectRoyaltyTokens", false);
    return response;
  } catch (e) {
    const errorMessage = handleError(e);
    setErrors((prev) => ({ ...prev, collectRoyaltyTokens: errorMessage }));
    setLoadingState("collectRoyaltyTokens", false);
    throw new Error(errorMessage);
  }
};
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 collectRoyaltyTokens = async (
request: CollectRoyaltyTokensRequest
): Promise<CollectRoyaltyTokensResponse> => {
try {
setLoadings((prev) => ({ ...prev, collectRoyaltyTokens: true }));
setErrors((prev) => ({ ...prev, collectRoyaltyTokens: null }));
const response = await client.royalty.collectRoyaltyTokens(request);
setLoadings((prev) => ({ ...prev, collectRoyaltyTokens: false }));
return response;
} catch (e) {
const errorMessage = handleError(e);
setErrors((prev) => ({ ...prev, collectRoyaltyTokens: errorMessage }));
setLoadings((prev) => ({ ...prev, collectRoyaltyTokens: false }));
throw new Error(errorMessage);
}
};
const setLoadingState = (key: string, state: boolean) => {
setLoadings((prev) => ({ ...prev, [key]: state }));
};
const collectRoyaltyTokens = async (
request: CollectRoyaltyTokensRequest
): Promise<CollectRoyaltyTokensResponse> => {
try {
setLoadingState("collectRoyaltyTokens", true);
setErrors((prev) => ({ ...prev, collectRoyaltyTokens: null }));
const response = await client.royalty.collectRoyaltyTokens(request);
setLoadingState("collectRoyaltyTokens", false);
return response;
} catch (e) {
const errorMessage = handleError(e);
setErrors((prev) => ({ ...prev, collectRoyaltyTokens: errorMessage }));
setLoadingState("collectRoyaltyTokens", false);
throw new Error(errorMessage);
}
};

Comment on lines +27 to +42
/**
* Raises a dispute on a given ipId
* @param request - The request object containing necessary data to raise a dispute.
* @param request.targetIpId - The IP ID that is the target of the dispute.
* @param request.arbitrationPolicy - The address of the arbitration policy.
* @param request.linkToDisputeEvidence - The link to the dispute evidence.
* @param request.targetTag - The target tag of the dispute.
* @param request.calldata - Optional calldata to initialize the policy.
* @param request.txOptions - Optional transaction options.
* @returns A Promise that resolves to a RaiseDisputeResponse containing the transaction hash.
* @throws `NotRegisteredIpId` if targetIpId is not registered in the IPA Registry.
* @throws `NotWhitelistedDisputeTag` if targetTag is not whitelisted.
* @throws `ZeroLinkToDisputeEvidence` if linkToDisputeEvidence is empty
* @calls raiseDispute(address _targetIpId, string memory _linkToDisputeEvidence, bytes32 _targetTag, bytes calldata _data) external nonReentrant returns (uint256) {
* @emits DisputeRaised (disputeId_, targetIpId, msg.sender, arbitrationPolicy, linkToDisputeEvidence, targetTag, calldata);
*/
Copy link

Choose a reason for hiding this comment

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

Consider adding more detailed error handling.

The current error handling is generic. Consider adding more specific error handling for different error types.

-  throw new Error(errorMessage);
+  if (e instanceof SomeSpecificError) {
+    // Handle specific error
+  } else {
+    throw new Error(errorMessage);
+  }

Committable suggestion was skipped due to low confidence.

Comment on lines +60 to +71
/**
* Cancels an ongoing dispute
* @param request - The request object containing details to cancel the dispute.
* @param request.disputeId The ID of the dispute to be cancelled.
* @param request.calldata Optional additional data used in the cancellation process.
* @returns A Promise that resolves to a CancelDisputeResponse containing the transaction hash.
* @throws NotInDisputeState, if the currentTag of the Dispute is not being disputed
* @throws NotDisputeInitiator, if the transaction executor is not the one that initiated the dispute
* @throws error if the Dispute&#39;s ArbitrationPolicy contract is not valid
* @calls cancelDispute(uint256 _disputeId, bytes calldata _data) external nonReentrant {
* @emits DisputeCancelled (_disputeId, _data);
*/
Copy link

Choose a reason for hiding this comment

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

Consider adding more detailed error handling.

The current error handling is generic. Consider adding more specific error handling for different error types.

-  throw new Error(errorMessage);
+  if (e instanceof SomeSpecificError) {
+    // Handle specific error
+  } else {
+    throw new Error(errorMessage);
+  }

Committable suggestion was skipped due to low confidence.

Comment on lines +89 to +98
/**
* Resolves a dispute after it has been judged
* @param request - The request object containing details to resolve the dispute.
* @param request.disputeId The ID of the dispute to be resolved.
* @param request.data The data to resolve the dispute.
* @returns A Promise that resolves to a ResolveDisputeResponse.
* @throws NotAbleToResolve, if currentTag is still in dispute (i.e still needs a judgement to be set)
* @throws NotDisputeInitiator, if the transaction executor is not the one that initiated the dispute
* @emits DisputeResolved (_disputeId)
*/
Copy link

Choose a reason for hiding this comment

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

Consider adding more detailed error handling.

The current error handling is generic. Consider adding more specific error handling for different error types.

-  throw new Error(errorMessage);
+  if (e instanceof SomeSpecificError) {
+    // Handle specific error
+  } else {
+    throw new Error(errorMessage);
+  }

Committable suggestion was skipped due to low confidence.

@edisonz0718 edisonz0718 merged commit 0393af4 into main Jul 2, 2024
11 checks passed
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.

2 participants