Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: OnchainKitProvider default dependencies #1589

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions src/OnchainKitProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,36 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, screen, waitFor } from '@testing-library/react';
import { base } from 'viem/chains';
import { describe, expect, it, vi } from 'vitest';
import { http, WagmiProvider, createConfig } from 'wagmi';
import { type Mock, beforeEach, describe, expect, it, vi } from 'vitest';
import {
http,
WagmiProvider,
WagmiProviderNotFoundError,
createConfig,
} from 'wagmi';
import { useConfig } from 'wagmi';
import { mock } from 'wagmi/connectors';
import { setOnchainKitConfig } from './OnchainKitConfig';
import { OnchainKitProvider } from './OnchainKitProvider';
import { COINBASE_VERIFIED_ACCOUNT_SCHEMA_ID } from './identity/constants';
import type { EASSchemaUid } from './identity/types';
import { useOnchainKit } from './useOnchainKit';

vi.mock('wagmi', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
useConfig: vi.fn(),
};
});

vi.mock('./useProviderDependencies', () => ({
useProviderDependencies: vi.fn(() => ({
providedWagmiConfig: null,
providedQueryClient: null,
})),
}));

const queryClient = new QueryClient();
const mockConfig = createConfig({
chains: [base],
Expand Down Expand Up @@ -54,6 +75,12 @@
const appLogo = undefined;
const appName = undefined;

beforeEach(() => {
vi.clearAllMocks();
(useConfig as Mock).mockReturnValue(mockConfig);
use;

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > provides the context value correctly

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > provides the context value correctly without WagmiProvider

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > throws an error if schemaId does not meet the required length

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > does not throw an error if schemaId is not provided

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > does not throw an error if api key is not provided

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > should call setOnchainKitConfig with the correct values

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > should use default values for config when not provided

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > should use default values for appearance when config is provided

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5

Check failure on line 81 in src/OnchainKitProvider.test.tsx

View workflow job for this annotation

GitHub Actions / build (18.x)

src/OnchainKitProvider.test.tsx > OnchainKitProvider > should use custom values when override in config is provided

ReferenceError: use is not defined ❯ src/OnchainKitProvider.test.tsx:81:5
});

it('provides the context value correctly', async () => {
render(
<WagmiProvider config={mockConfig}>
Expand All @@ -71,6 +98,21 @@
});
});

it('provides the context value correctly without WagmiProvider', async () => {
(useConfig as Mock).mockImplementation(() => {
throw new WagmiProviderNotFoundError();
});
render(
<OnchainKitProvider chain={base} schemaId={schemaId} apiKey={apiKey}>
<TestComponent />
</OnchainKitProvider>,
);
await waitFor(() => {
expect(screen.getByText(schemaId)).toBeInTheDocument();
expect(screen.getByText(apiKey)).toBeInTheDocument();
});
});

it('throws an error if schemaId does not meet the required length', () => {
expect(() => {
render(
Expand Down
45 changes: 45 additions & 0 deletions src/OnchainKitProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createContext, useMemo } from 'react';
import { WagmiProvider } from 'wagmi';
import { ONCHAIN_KIT_CONFIG, setOnchainKitConfig } from './OnchainKitConfig';
import { createWagmiConfig } from './createWagmiConfig';
import { COINBASE_VERIFIED_ACCOUNT_SCHEMA_ID } from './identity/constants';
import { checkHashLength } from './internal/utils/checkHashLength';
import type { OnchainKitContextType, OnchainKitProviderReact } from './types';
import { useProviderDependencies } from './useProviderDependencies';

export const OnchainKitContext =
createContext<OnchainKitContextType>(ONCHAIN_KIT_CONFIG);
Expand Down Expand Up @@ -51,6 +55,47 @@ export function OnchainKitProvider({
return onchainKitConfig;
}, [address, apiKey, chain, config, projectId, rpcUrl, schemaId]);

// Check the React context for WagmiProvider and QueryClientProvider
const { providedWagmiConfig, providedQueryClient } =
useProviderDependencies();

const defaultConfig = useMemo(() => {
// IMPORTANT: Don't create a new Wagmi configuration if one already exists
// This prevents the user-provided WagmiConfig from being overriden
return (
providedWagmiConfig ||
createWagmiConfig({
apiKey,
appName: value.config.appearance.name,
appLogoUrl: value.config.appearance.logo,
})
);
}, [
apiKey,
providedWagmiConfig,
value.config.appearance.name,
value.config.appearance.logo,
]);
const defaultQueryClient = useMemo(() => {
// IMPORTANT: Don't create a new QueryClient if one already exists
// This prevents the user-provided QueryClient from being overriden
return providedQueryClient || new QueryClient();
}, [providedQueryClient]);

// If both dependencies are missing, return a context with default parent providers
// If only one dependency is provided, expect the user to also provide the missing one
if (!providedWagmiConfig && !providedQueryClient) {
return (
<WagmiProvider config={defaultConfig}>
<QueryClientProvider client={defaultQueryClient}>
<OnchainKitContext.Provider value={value}>
{children}
</OnchainKitContext.Provider>
</QueryClientProvider>
</WagmiProvider>
);
Copy link
Contributor

Choose a reason for hiding this comment

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

since Wagmi requires QueryClient, the only time 1 dep is missing should be when there is a QueryClient, but no Wagmi? Seems like an edge case, but would be possible to support this usecase, no? or, should we adjust the console.errors at least to only state using default if both don't exist and otherwise prompt the user to fix?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

if 1 dep is missing, we shouldn't modify the default behavior and allow the app to display the typical error message instead

image

Copy link
Contributor Author

@0xAlec 0xAlec Nov 6, 2024

Choose a reason for hiding this comment

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

in my mind, if you provide 1 of the 2 deps then it should default to the same logic/behavior as before this PR which is Unhandled Runtime Error

}

return (
<OnchainKitContext.Provider value={value}>
{children}
Expand Down
96 changes: 96 additions & 0 deletions src/createWagmiConfig.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { describe, expect, it, vi } from 'vitest';
import { createConfig } from 'wagmi';
import { http } from 'wagmi';
import { base, baseSepolia } from 'wagmi/chains';
import { coinbaseWallet } from 'wagmi/connectors';
import { createWagmiConfig } from './createWagmiConfig';

// Mock the imported modules
vi.mock('wagmi', async () => {
const actual = await vi.importActual('wagmi');
return {
...actual,
createConfig: vi.fn(),
createStorage: vi.fn(),
};
});

vi.mock('wagmi/chains', async () => {
const actual = await vi.importActual('wagmi/chains');
return {
...actual,
base: { id: 8453 },
baseSepolia: { id: 84532 },
};
});

vi.mock('wagmi/connectors', async () => {
const actual = await vi.importActual('wagmi/connectors');
return {
...actual,
coinbaseWallet: vi.fn(),
};
});

describe('createWagmiConfig', () => {
it('should create config with default values when no parameters are provided', () => {
createWagmiConfig({});
expect(createConfig).toHaveBeenCalledWith(
expect.objectContaining({
chains: [base, baseSepolia],
ssr: true,
transports: {
[base.id]: expect.any(Function),
[baseSepolia.id]: expect.any(Function),
},
}),
);
expect(coinbaseWallet).toHaveBeenCalledWith({
appName: undefined,
appLogoUrl: undefined,
preference: 'smartWalletOnly',
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this going to force the components to use smart wallet ? thinking this might be related to the issue i'm having where i'm unable to connect to EOA

});
});

it('should create config with custom values when parameters are provided', () => {
const customConfig = {
appearance: {
name: 'Custom App',
logo: 'https://example.com/logo.png',
},
};
createWagmiConfig({
apiKey: 'test-api-key',
appName: customConfig.appearance.name,
appLogoUrl: customConfig.appearance.logo,
});
expect(createConfig).toHaveBeenCalledWith(
expect.objectContaining({
chains: [base, baseSepolia],
ssr: true,
transports: {
[base.id]: expect.any(Function),
[baseSepolia.id]: expect.any(Function),
},
}),
);
expect(coinbaseWallet).toHaveBeenCalledWith({
appName: 'Custom App',
appLogoUrl: 'https://example.com/logo.png',
preference: 'smartWalletOnly',
});
});

it('should use API key in transports when provided', () => {
const testApiKey = 'test-api-key';
const result = createWagmiConfig({ apiKey: testApiKey });
expect(result).toContain(
http(`https://api.developer.coinbase.com/rpc/v1/base/${testApiKey}`),
);
expect(result).toContain(
http(
`https://api.developer.coinbase.com/rpc/v1/base-sepolia/${testApiKey}`,
),
);
});
});
37 changes: 37 additions & 0 deletions src/createWagmiConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { http, cookieStorage, createConfig, createStorage } from 'wagmi';
import { base, baseSepolia } from 'wagmi/chains';
import { coinbaseWallet } from 'wagmi/connectors';
import type { CreateWagmiConfigParams } from './types';

// createWagmiConfig returns a WagmiConfig (https://wagmi.sh/react/api/createConfig) using OnchainKit provided settings.
// This function should only be used if the user does not provide WagmiProvider as a parent in the React context.
export const createWagmiConfig = ({
apiKey,
appName,
appLogoUrl,
}: CreateWagmiConfigParams) => {
return createConfig({
chains: [base, baseSepolia],
connectors: [
coinbaseWallet({
appName,
appLogoUrl,
preference: 'smartWalletOnly',
Copy link
Contributor Author

Choose a reason for hiding this comment

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

should we set this to all?

Copy link
Contributor

Choose a reason for hiding this comment

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

seems like it'd be a more flexible implementation, unless we just really want to push to smart wallet.

Copy link
Contributor

Choose a reason for hiding this comment

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

we need to add a second connector for EOA
coinbaseWallet({ appName: 'OnchainKit', preference: 'eoaOnly', }),

}),
],
storage: createStorage({
storage: cookieStorage,
}),
ssr: true,
transports: {
[base.id]: apiKey
? http(`https://api.developer.coinbase.com/rpc/v1/base/${apiKey}`)
: http(),
[baseSepolia.id]: apiKey
? http(
`https://api.developer.coinbase.com/rpc/v1/base-sepolia/${apiKey}`,
)
: http(),
Comment on lines +27 to +34
Copy link
Contributor Author

Choose a reason for hiding this comment

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

uses Base networks by default and sets the RPC as the CDP Node

},
});
};
110 changes: 110 additions & 0 deletions src/useProviderDependencies.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { type QueryClient, useQueryClient } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type Config, WagmiProviderNotFoundError, useConfig } from 'wagmi';
import { useProviderDependencies } from './useProviderDependencies';

// Mock the wagmi and react-query hooks
vi.mock('wagmi', async () => {
const actual = await vi.importActual('wagmi');
return {
...actual,
useConfig: vi.fn(),
};
});

vi.mock('@tanstack/react-query', async () => {
const actual = await vi.importActual('@tanstack/react-query');
return {
...actual,
useQueryClient: vi.fn(),
};
});

describe('useProviderDependencies', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('should return both configs when they exist', () => {
const mockWagmiConfig = { testWagmi: true } as unknown as Config;
const mockQueryClient = { testQuery: true } as unknown as QueryClient;
vi.mocked(useConfig).mockReturnValue(mockWagmiConfig);
vi.mocked(useQueryClient).mockReturnValue(mockQueryClient);
const { result } = renderHook(() => useProviderDependencies());
expect(result.current).toEqual({
providedWagmiConfig: mockWagmiConfig,
providedQueryClient: mockQueryClient,
});
});

it('should handle missing WagmiProvider gracefully', () => {
vi.mocked(useConfig).mockImplementation(() => {
throw new WagmiProviderNotFoundError();
});
const mockQueryClient = { testQuery: true } as unknown as QueryClient;
vi.mocked(useQueryClient).mockReturnValue(mockQueryClient);
const { result } = renderHook(() => useProviderDependencies());
expect(result.current).toEqual({
providedWagmiConfig: null,
providedQueryClient: mockQueryClient,
});
});

it('should handle missing QueryClient gracefully', () => {
const mockWagmiConfig = { testWagmi: true } as unknown as Config;
vi.mocked(useConfig).mockReturnValue(mockWagmiConfig);
vi.mocked(useQueryClient).mockImplementation(() => {
throw new Error('No QueryClient set, use QueryClientProvider to set one');
});
const { result } = renderHook(() => useProviderDependencies());
expect(result.current).toEqual({
providedWagmiConfig: mockWagmiConfig,
providedQueryClient: null,
});
});

it('should log non-WagmiProvider errors and return null config', () => {
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const error = new Error('Different error');
vi.mocked(useConfig).mockImplementation(() => {
throw error;
});
const mockQueryClient = { testQuery: true } as unknown as QueryClient;
vi.mocked(useQueryClient).mockReturnValue(mockQueryClient);
const { result } = renderHook(() => useProviderDependencies());
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Error fetching WagmiProvider, using default:',
error,
);
expect(result.current).toEqual({
providedWagmiConfig: null,
providedQueryClient: mockQueryClient,
});
consoleErrorSpy.mockRestore();
});

it('should log non-QueryClient provider errors and return null client', () => {
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const mockWagmiConfig = { testWagmi: true } as unknown as Config;
vi.mocked(useConfig).mockReturnValue(mockWagmiConfig);
const error = new Error('Different query error');
vi.mocked(useQueryClient).mockImplementation(() => {
throw error;
});
const { result } = renderHook(() => useProviderDependencies());
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Error fetching QueryClient, using default:',
error,
);
expect(result.current).toEqual({
providedWagmiConfig: mockWagmiConfig,
providedQueryClient: null,
});
consoleErrorSpy.mockRestore();
});
});
Loading
Loading