Nuklai / hyperchain-js-sdk

(deprecated)
MIT License
1 stars 1 forks source link

SDK doesn't work with Next #2

Closed hyperantoine closed 2 months ago

hyperantoine commented 3 months ago

It is currently impossible to build a Next project and implement the SDK; the build function won't work.

Error

TypeError: Cannot read properties of undefined (reading 'bigint')
    at Span.stop (/Users/user/Desktop/demo/next-hyperchain/node_modules/next/dist/trace/trace.js:98:48)
    at Span.traceAsyncFn (/Users/user/Desktop/demo/next-hyperchain/node_modules/next/dist/trace/trace.js:156:18)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Error: Child can only be used on a forked process
    at reportError (/Users/user/Desktop/demo/next-hyperchain/node_modules/next/dist/compiled/jest-worker/processChild.js:1:1811)
    at reportClientError (/Users/user/Desktop/demo/next-hyperchain/node_modules/next/dist/compiled/jest-worker/processChild.js:1:1611)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Version

0.2.1

Steps to reproduce

  1. npx create-next-app@latest
  2. cd my-app
  3. npm run build -> works
  4. npm install @nuklai/hyperchain-sdk
  5. Add the sample code from the README (const sdk = new HyperchainSDK…) into src/app/page.tsx
  6. npm run build -> fails
kpachhai commented 3 months ago

Initial Issue: bigint and Related Errors

When integrating the @nuklai/hyperchain-sdk into a Next.js project, you encountered errors related to bigint and other issues. These problems arose primarily because:

  1. Server-Side Rendering (SSR) vs. Client-Side Rendering (CSR):

    • Next.js supports both SSR and CSR. When code that relies on browser-specific features (like bigint or certain polyfills) is executed on the server, it can cause errors since these features are not available in the Node.js environment used for SSR.
  2. Polyfills:

    • The @nuklai/hyperchain-sdk relies on certain polyfills (buffer, crypto, stream, etc.) that are available in the browser but not natively in Node.js.

Solution Overview

To resolve these issues, the main approach was to ensure that the @nuklai/hyperchain-sdk is used only on the client side and to properly handle browser-specific features. This was achieved by:

  1. Marking the Component as a Client Component:

    • Adding "use client"; at the top of the component file to ensure that the component and its hooks are treated as client-side components.
  2. Dynamic Imports:

    • Dynamically importing the @nuklai/hyperchain-sdk within a useEffect hook to ensure it runs only in the client-side environment.

Detailed Solution Steps

Here’s the detailed step-by-step explanation:

1. Marking the Component as a Client Component

Adding "use client"; at the top of your page.tsx file ensures that the component is treated as a client component by Next.js, preventing it from being rendered on the server.

Code:

'use client';

This directive tells Next.js to execute the component entirely on the client side, avoiding SSR issues with browser-specific code.

2. Dynamic Imports and Initializing the SDK

Using dynamic imports ensures that the SDK is only loaded in the browser environment. This prevents SSR-related errors since the SDK is not executed on the server.

Code:

'use client';

import { useEffect, useState } from 'react';
import { HyperchainSDK, common } from '@nuklai/hyperchain-sdk';
import Image from 'next/image';

export default function Home() {
  const [sdk, setSdk] = useState<HyperchainSDK | null>(null);
  const [networkInfo, setNetworkInfo] =
    useState<common.GetNetworkInfoResponse | null>(null);

  useEffect(() => {
    const initSDK = async () => {
      const { HyperchainSDK } = await import('@nuklai/hyperchain-sdk');
      const initializedSdk = new HyperchainSDK({
        baseApiUrl: 'https://api-devnet.nuklaivm-dev.net:9650', // Node API URL
        blockchainId: 'JopL8T69GBW1orW4ZkJ1TBRzF97KXaY8e64atDA1v2M12SNqm' // Blockchain ID
      });
      setSdk(initializedSdk);
      const networkInfo = await initializedSdk.rpcService.getNetworkInfo();
      setNetworkInfo(networkInfo);
    };

    if (typeof window !== 'undefined') {
      initSDK();
    }
  }, []);

  return (
    <main className='flex min-h-screen flex-col items-center justify-between p-24'>
      {networkInfo && (
        <div className='mb-4 p-4 border border-gray-300 rounded-md bg-gray-100'>
          <h2 className='text-xl font-semibold'>Network Information</h2>
          <p>
            <strong>Network ID:</strong> {networkInfo.networkId}
          </p>
          <p>
            <strong>Subnet ID:</strong> {networkInfo.subnetId}
          </p>
          <p>
            <strong>Chain ID:</strong> {networkInfo.chainId}
          </p>
        </div>
      )}
}

Explanation of the Solution

  1. 'use client';:

    • This directive ensures that the entire component is treated as a client-side component by Next.js, preventing any server-side rendering for this component and avoiding SSR-related issues with browser-specific code.
  2. Dynamic Import of SDK:

    • The SDK is dynamically imported within the useEffect hook, ensuring that it is loaded only in the browser environment.
    • This prevents SSR issues because the SDK and its dependencies (like bigint) are not loaded on the server.
  3. Fetching and Displaying Network Info:

    • After initializing the SDK, it fetches the network information using the rpcService.getNetworkInfo() method.
    • The fetched network information is stored in the state and displayed at the top of the page.

By making these changes, the integration of @nuklai/hyperchain-sdk should work correctly in your Next.js project without encountering SSR-related issues.