import React, { createContext, useContext, useEffect, useState } from "react";
import { CulturaSDK, getChainName } from "@cultura/sdk";
// Assume you have a hook or library to manage wallet connection (e.g., RainbowKit, Wagmi, Web3Modal)
import { useWallet } from "your-wallet-provider"; // Replace with your actual wallet hook
const SDKContext = createContext<CulturaSDK | null>(null);
export function useSDK() {
const context = useContext(SDKContext);
// Return null if used outside the provider, allows for conditional logic
return context;
}
export function SDKProvider({ children }: { children: React.ReactNode }) {
// Adapt these based on your wallet provider's state
const { isConnected, provider, chainId, account } = useWallet();
const [sdk, setSdk] = useState<CulturaSDK | null>(null);
useEffect(() => {
// Only initialize SDK if wallet is connected and provider exists
if (!isConnected || !provider || !chainId || !account) {
// Optionally create a read-only SDK as a fallback
setSdk(CulturaSDK.create({ chain: 'testnet' })); // Fallback to testnet read-only
console.log("Cultura SDK initialized in read-only mode (wallet not connected).");
return;
}
try {
// Create SDK with wallet connection
// Note: 'provider' might need adjustment based on your library (e.g., Ethers provider, Viem transport)
// The SDK expects an EIP-1193 compliant provider (like window.ethereum or WalletConnect provider)
const newSdk = CulturaSDK.createWithWallet(provider, {
chain: getChainName(chainId), // Ensure getChainName handles your supported chain IDs
account: account as `0x${string}`,
});
setSdk(newSdk);
console.log("Cultura SDK initialized with wallet connection.");
} catch (error) {
console.error("Failed to initialize Cultura SDK with wallet:", error);
// Handle cases where the chainId might not be supported by the SDK
// Fallback to a read-only instance
setSdk(CulturaSDK.create({ chain: 'testnet' }));
console.log("Cultura SDK initialized in read-only mode (wallet connection failed or unsupported chain).");
}
}, [isConnected, provider, chainId, account]); // Re-run effect if connection state changes
return <SDKContext.Provider value={sdk}>{children}</SDKContext.Provider>;
}