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 all commits
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
55 changes: 52 additions & 3 deletions src/OnchainKitProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,38 @@ import '@testing-library/jest-dom';
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 { type Mock, beforeEach, describe, expect, it, vi } from 'vitest';
import { http, WagmiProvider, 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';
import { useProviderDependencies } from './useProviderDependencies';

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

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

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

const queryClient = new QueryClient();
const mockConfig = createConfig({
Expand Down Expand Up @@ -51,8 +75,17 @@ describe('OnchainKitProvider', () => {
const apiKey = 'test-api-key';
const paymasterUrl =
'https://api.developer.coinbase.com/rpc/v1/base/test-api-key';
const appLogo = undefined;
const appName = undefined;
const appLogo = '';
const appName = 'Dapp';

beforeEach(() => {
vi.clearAllMocks();
(useConfig as Mock).mockReturnValue(mockConfig);
(useProviderDependencies as Mock).mockReturnValue({
providedWagmiConfig: mockConfig,
providedQueryClient: queryClient,
});
});

it('provides the context value correctly', async () => {
render(
Expand All @@ -71,6 +104,22 @@ describe('OnchainKitProvider', () => {
});
});

it('provides the context value correctly without WagmiProvider', async () => {
(useProviderDependencies as Mock).mockReturnValue({
providedWagmiConfig: null,
providedQueryClient: null,
});
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
50 changes: 48 additions & 2 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 All @@ -24,6 +28,7 @@ export function OnchainKitProvider({
throw Error('EAS schemaId must be 64 characters prefixed with "0x"');
}

// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ignore
const value = useMemo(() => {
const defaultPaymasterUrl = apiKey
? `https://api.developer.coinbase.com/rpc/v1/${chain.name
Expand All @@ -36,8 +41,8 @@ export function OnchainKitProvider({
chain: chain,
config: {
appearance: {
name: config?.appearance?.name,
logo: config?.appearance?.logo,
name: config?.appearance?.name ?? 'Dapp',
logo: config?.appearance?.logo ?? '',
mode: config?.appearance?.mode ?? 'auto',
theme: config?.appearance?.theme ?? 'default',
},
Expand All @@ -51,6 +56,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: 'all',
});
});

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: 'all',
});
});

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: 'all',
}),
],
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

},
});
};
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ export type AppConfig = {
paymaster?: string | null; // Paymaster URL for gas sponsorship
};

export type CreateWagmiConfigParams = {
apiKey?: string;
appName?: string;
appLogoUrl?: string;
};

/**
* Note: exported as public Type
*/
Expand Down
Loading