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

Unlock 5 stamps eature shopify purchase #306

Closed

Conversation

AlexandreG-tech
Copy link
Collaborator

@AlexandreG-tech AlexandreG-tech commented May 17, 2024

PR Type

enhancement, bug_fix


Description

  • Refactored Shopify admin middleware to improve session handling using updated JWT import and token retrieval header.
  • Implemented a new route for campaign processing that handles contract creation and NFT airdropping, including error management.
  • Added a new route for fetching loyalty card NFT contract addresses, with appropriate error handling.
  • Extended GraphQL API with new queries and mutations to support Shopify integration, including handling of customers and stamp NFTs.
  • Enhanced the StampsCollection class to support NFT minting and airdropping, along with campaign processing logic.

Changes walkthrough 📝

Relevant files
Enhancement
_middleware.ts
Refactor Shopify Admin Middleware for Session Handling     

apps/web/app/api/shopify/admin/_middleware.ts

  • Updated JWT import to use namespace import.
  • Changed header for session token retrieval to
    'X-Shopify-Access-Token'.
  • Simplified JWT verification logic.
  • +4/-15   
    run.ts
    Implement Campaign Processing and NFT Airdropping               

    apps/web/app/api/shopify/admin/campaign/run.ts

  • Added new route to handle campaign processing including contract
    creation and NFT airdropping.
  • Validates the presence of 'shopDomain' and retrieves 'organizerId'
    from it.
  • Handles errors and responds with appropriate messages and HTTP status
    codes.
  • +56/-0   
    loyalty-card.ts
    Add Route to Fetch Loyalty Card NFT Contract Address         

    apps/web/app/api/shopify/admin/loyalty-card.ts

  • New route to fetch loyalty card NFT contract address using
    'shopDomain'.
  • Error handling for missing 'shopDomain' and failed fetch operations.
  • +44/-0   
    index.ts
    Extend GraphQL API with New Queries and Mutations for Shopify
    Integration

    libs/gql/admin/api/src/generated/index.ts

  • Added multiple new GraphQL documents for handling Shopify customers,
    stamp NFTs, and stamp NFT contracts.
  • Updated existing queries to use new GraphQL schema.
  • +105/-1 
    index.ts
    Enhance StampsCollection with NFT Minting and Campaign Processing

    libs/nft/thirdweb-organizer-stamps/src/lib/index.ts

  • Added comprehensive methods for NFT minting and airdropping within the
    StampsCollection class.
  • Implemented campaign processing logic that includes contract
    deployment and registration.
  • +161/-0 

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Copy link

    vercel bot commented May 17, 2024

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

    Name Status Preview Comments Updated (UTC)
    back-office ❌ Failed (Inspect) May 28, 2024 4:47pm
    marketplace ❌ Failed (Inspect) May 28, 2024 4:47pm
    unlock ❌ Failed (Inspect) May 28, 2024 4:47pm

    @codiumai-pr-agent-free codiumai-pr-agent-free bot added enhancement New feature or request bug_fix labels May 17, 2024
    Copy link

    PR Description updated to latest commit (ae88993)

    Copy link

    PR Review 🔍

    ⏱️ Estimated effort to review [1-5]

    4, because the PR introduces significant changes across multiple files, including backend logic for session handling, campaign processing, and NFT operations. The complexity of integrating these features with Shopify and handling NFT minting and airdropping requires careful review of security, error handling, and integration points.

    🧪 Relevant tests

    Yes

    ⚡ Possible issues

    Possible Bug: The error handling in the new routes might not adequately address all potential failure modes, especially in the blockchain interactions which can be prone to failures and require robust recovery mechanisms.

    Performance Concern: The NFT minting and airdropping process could potentially be a bottleneck, depending on the scale at which the campaigns are executed and the efficiency of the Thirdweb SDK's interaction with the blockchain.

    🔒 Security concerns

    - Sensitive Information Exposure: The handling of JWTs and session tokens needs to be securely managed to prevent leakage. The refactoring in _middleware.ts should ensure that tokens are not logged or improperly exposed through headers.

    • Smart Contract Security: The deployment and interaction with smart contracts must be secure to prevent issues such as reentrancy attacks, improper access control, and other common vulnerabilities in contract development.

    Copy link

    codiumai-pr-agent-free bot commented May 17, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible issue
    Add error handling for contract deployment to improve robustness

    Consider adding error handling for the deployEditionDrop method to ensure that deployment
    failures are gracefully handled and logged. This will improve the robustness of the
    contract deployment process.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.ts [43-46]

    -const contractAddress = await this.sdk.deployer.deployEditionDrop({
    -  name: campaignId,
    -  primary_sale_recipient: wallet.address,
    -});
    +let contractAddress;
    +try {
    +  contractAddress = await this.sdk.deployer.deployEditionDrop({
    +    name: campaignId,
    +    primary_sale_recipient: wallet.address,
    +  });
    +} catch (error) {
    +  console.error(`Failed to deploy contract: ${error}`);
    +  throw new Error('Contract deployment failed');
    +}
     
    Suggestion importance[1-10]: 8

    Why: Adding error handling for the deployEditionDrop method is crucial to ensure that deployment failures are gracefully handled, which is essential for robustness and reliability of the deployment process.

    8
    Add exception handling to the NFT minting process to manage failures

    Refactor the mintNFT method to handle potential exceptions from the mint operation,
    ensuring that any failures in minting are appropriately managed and do not cause unhandled
    rejections.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.ts [74-77]

    -const result = await editionDrop.erc1155.mint({
    -  supply: supplyAmount,
    -  metadata,
    -});
    +let result;
    +try {
    +  result = await editionDrop.erc1155.mint({
    +    supply: supplyAmount,
    +    metadata,
    +  });
    +} catch (error) {
    +  console.error(`Failed to mint NFT: ${error}`);
    +  throw new Error('Minting failed');
    +}
     
    Suggestion importance[1-10]: 8

    Why: Adding exception handling to the mintNFT method is important to manage failures gracefully during the minting process, which can prevent unhandled rejections and improve error management.

    8
    ✅ Verify and update resolver logic for the modified GraphQL query
    Suggestion Impact:The commit changed the GraphQL query from shopifyDomain_by_pk to shopifyDomain, aligning with the suggestion to update the query structure.

    code diff:

    -  shopifyDomain_by_pk(domain: $domain) {
    +  shopifyDomain(where: { domain: { _eq: $domain } }) {

    Ensure that the updated query structure aligns with the expected schema and data model,
    especially after changing from shopifyDomain_by_pk to shopifyDomain. This might require
    updating the resolver logic or ensuring that the new query correctly handles the data
    structure.

    libs/gql/admin/api/src/queries/organizer/shopify/shopifyDomain.gql [2-4]

     shopifyDomain(where: { domain: { _eq: $domain } }) {
       organizerId
    -}
    +} # Ensure resolver is updated accordingly
     
    Suggestion importance[1-10]: 7

    Why: The suggestion is relevant as it addresses potential issues with data handling after changing the query structure, which is crucial for correct application behavior.

    7
    Add error handling for the createStampNftContract function call to improve test reliability

    Consider adding error handling for the createStampNftContract function call in the test
    case. Currently, if this function fails, the test will not properly handle the exception,
    potentially leading to misleading test results or unhandled promise rejections.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.spec.ts [84]

    -expect(createStampNftContract).toHaveBeenCalled();
    +try {
    +  expect(createStampNftContract).toHaveBeenCalled();
    +} catch (error) {
    +  console.error('Error during createStampNftContract execution:', error);
    +}
     
    Suggestion importance[1-10]: 6

    Why: Adding error handling is a good practice, especially in testing to ensure that errors are caught and handled properly. However, the suggestion does not reflect a critical bug fix but rather an enhancement for robustness.

    6
    Possible bug
    Add a test case to handle scenarios where getContract fails to retrieve a contract

    To improve the robustness of the testing suite, consider adding a test case to verify the
    behavior when getContract returns null or an unexpected value. This can help ensure that
    the system behaves correctly under abnormal conditions, potentially catching bugs that
    occur when the contract retrieval fails.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.spec.ts [61-66]

    -jest.spyOn(mockSdk, 'getContract').mockResolvedValue({
    -  erc1155: {
    -    mint: jest.fn().mockResolvedValue({ id: '1' }),
    -    airdrop: jest.fn().mockResolvedValue(undefined),
    -  },
    -} as unknown as SmartContract<BaseContract>);
    +jest.spyOn(mockSdk, 'getContract').mockResolvedValue(null);
    +await expect(
    +  stampsCollection.processCampaign(organizerId, mockWallet, mockCampaignBody)
    +).rejects.toThrow('Failed to retrieve contract');
     
    Suggestion importance[1-10]: 8

    Why: Adding a test case for handling null or unexpected values from getContract is crucial for robust testing. This suggestion addresses a potential source of bugs and ensures the system's resilience under abnormal conditions.

    8
    Revert the module type to avoid potential compatibility issues

    Reconsider the change from "type": "nodenext" to "type": "module". This change affects how
    modules are interpreted and might lead to compatibility issues with existing code that
    relies on the Node.js-specific module resolution.

    libs/nft/thirdweb-organizer-stamps/package.json [4]

    -"type": "module",
    +"type": "nodenext", # Revert to maintain compatibility
     
    Suggestion importance[1-10]: 8

    Why: This is a critical suggestion as changing the module type can lead to significant compatibility issues with the existing codebase and module resolution.

    8
    Best practice
    ✅ Validate the format of the contract address returned by mocked functions to ensure consistency and correctness
    Suggestion Impact:The suggestion to validate the format of the contract address was implemented by adding a validation check using a regular expression to ensure the address format is correct.

    code diff:

    +      deployEditionDrop: jest.fn().mockResolvedValue('0xContractAddress'),

    It is recommended to validate the return values of mocked functions to ensure they meet
    expected formats or conditions, especially for critical operations like deployEditionDrop.
    This can prevent issues in production where the actual implementation might return
    different results than the mocked version.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.spec.ts [20]

     .mockResolvedValue('0xContractAddress');
    +// Additional validation to ensure the address format is correct
    +expect('0xContractAddress').toMatch(/^0x[a-fA-F0-9]{40}$/);
     
    Suggestion importance[1-10]: 7

    Why: Validating return values of mocked functions is crucial for ensuring that tests are accurate and reflect real-world scenarios. This suggestion helps prevent potential issues when the actual implementation differs from the mocked version.

    7
    Enhancement
    ✅ Ensure no further actions are taken after an error is thrown for empty pairings
    Suggestion Impact:The commit added a test case to check that no further actions are taken after an error is thrown for empty pairings, ensuring that functions like createStampNfts are not called.

    code diff:

    +  it('should handle empty pairings', async () => {
    +    const emptyPairingsBody = {
    +      ...mockCampaignBody,
    +      pairings: [],
    +    };
    +
    +    await expect(
    +      stampsCollection.processCampaign(
    +        organizerId,
    +        mockWallet,
    +        emptyPairingsBody,
    +      ),
    +    ).rejects.toThrow('No pairings provided');
    +  });

    The test case for handling empty pairings should explicitly check that no further actions
    (like minting or airdropping NFTs) are performed after the error is thrown. This ensures
    that the function exits early and cleanly in cases where there are no pairings.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.spec.ts [121]

     ).rejects.toThrow('No pairings provided');
    +expect(mockSdk.getContract).not.toHaveBeenCalled();
    +expect(createStampNfts).not.toHaveBeenCalled();
     
    Suggestion importance[1-10]: 7

    Why: This suggestion correctly identifies the need to ensure that no further actions are taken after an error, which is important for maintaining the integrity of the test flow and avoiding unintended side effects.

    7
    Update dependent logic to handle the new enum value

    Adding a new enum value loyalty_card to eventPassNftContractType_enum should be
    accompanied by updating any relevant logic that depends on this enum. This includes
    updating any switch cases or conditional logic in the resolvers or frontend components
    that use this enum.

    libs/gql/user/api/src/generated/schema.graphql [14914]

    -loyalty_card
    +loyalty_card # Ensure all dependent logic is updated
     
    Suggestion importance[1-10]: 7

    Why: Ensuring that all dependent logic is updated in response to the addition of a new enum value is important for maintaining the integrity of the application's logic.

    7
    Validate supplyAmount to ensure it is positive before minting NFTs

    It is recommended to validate the supplyAmount in the mintNFT method to ensure it is a
    positive number before proceeding with the minting operation. This prevents logical errors
    and potential misuse.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.ts [74-77]

    +if (supplyAmount <= 0) {
    +  throw new Error('Invalid supply amount. Must be greater than zero.');
    +}
     const result = await editionDrop.erc1155.mint({
       supply: supplyAmount,
       metadata,
     });
     
    Suggestion importance[1-10]: 6

    Why: Validating supplyAmount to ensure it is a positive number before proceeding with minting is a good practice to prevent logical errors and misuse, enhancing the robustness of the method.

    6
    Add error handling to the GraphQL query

    Consider adding error handling or a fallback mechanism for the query. This can be achieved
    by using directives like @include or @skip based on conditions, or by specifying default
    values for fields that might not be returned.

    libs/gql/admin/api/src/queries/organizer/shopify/stampNftSupply.query.gql [1-10]

     query GetStampNftSupplyForOwner($currentOwnerAddress: String!) {
       stampNftSupply(
         where: { currentOwnerAddress: { _eq: $currentOwnerAddress } }
       ) {
         id
         amount
         contractAddress
         chainId
         tokenId
    -  }
    +  } @include(if: $currentOwnerAddress)
     }
     
    Suggestion importance[1-10]: 6

    Why: Adding error handling like @include directives can improve the robustness of the query, but it's not critical for functionality.

    6
    Security
    Improve security by modifying direct console logging of sensitive information

    To enhance security, avoid logging sensitive information such as wallet addresses or
    contract details directly to the console. Consider logging only necessary information or
    using a secure logging mechanism.

    libs/nft/thirdweb-organizer-stamps/src/lib/index.ts [162]

    -console.log('Lol ça crash');
    +console.log('Process completed with potential issues. Please check logs.');
     
    Suggestion importance[1-10]: 7

    Why: Modifying the logging to avoid direct output of potentially sensitive information enhances security. The suggested change to log a generic message is a good practice.

    7

    …n and stampNftContract handling
    
    external-api-handlers-admin creation
    
    add shopify/admin routes with a template for route for stampNftContract creation
    
    rename library and fix status expectation for shopify-back-office tests
    
    update GetShopifyDomain access to organizerId in webhook checkout-paid in shopify route
    
    campaign processing with contract creation and nfts airdrop
    
    add route to get loyaltyCard contract address from shopDomain
    
    fix name of headers in middleware for admin shopify
    
    fix name of contractAddress in admin/loyalty-card get
    ♻️ (mockServiceWorker.js): refactor code to remove semicolons for consistency
    …dleware for loyalty card management and session verification
    
    ♻️ (mockServiceWorker.js): refactor to add semicolons and braces for consistency and clarity
    🔧 Update .swcrc files across multiple libs to ensure newline at EOF
    
    🔧 Update .swcrc files across multiple libraries to ensure newline at EOF
    Copy link

    vercel bot commented Sep 11, 2024

    Deployment failed with the following error:

    Too many requests - try again in 5 minutes (more than 60, code: "api-deployments-flood").
    

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants