Skip to content

Instantly share code, notes, and snippets.

@beeman
Last active March 7, 2025 23:43
Show Gist options
  • Save beeman/e038dae0685aec7ee8b7b6a5a44ae4eb to your computer and use it in GitHub Desktop.
Save beeman/e038dae0685aec7ee8b7b6a5a44ae4eb to your computer and use it in GitHub Desktop.
Simple setup for @solana/web3.js v2 in a React/React Native app. Be sure to install`@solana/web3.js@2` in your project!
import { ReactNode } from 'react'
import { SolanaClientProvider } from './solana-client-provider'
function AppLayout({ children }: { children: ReactNode }) {
return <SolanaClientProvider rpc='https://api.devnet.solana.com'>
{children}
</SolanaClientProvider>
}
import React, { ReactNode } from 'react'
import { createSolanaClient, SolanaClient, SolanaClientConfig } from './solana-client'
const SolanaClientContext = React.createContext<SolanaClient>({} as SolanaClient)
export function SolanaClientProvider({ children, ...props }: SolanaClientConfig & { children: ReactNode }) {
const client = createSolanaClient(props)
return <SolanaClientContext.Provider value={client}>{children}</SolanaClientContext.Provider>
}
export function useSolanaClient() {
return React.useContext(SolanaClientContext)
}
import { createSolanaRpc, Rpc, SolanaRpcApiDevnet } from '@solana/rpc'
import { createSolanaRpcSubscriptions, RpcSubscriptions, SolanaRpcSubscriptionsApi } from '@solana/web3.js'
export type SolanaClient = {
rpc: Rpc<SolanaRpcApiDevnet>
rpcSubscriptions: RpcSubscriptions<SolanaRpcSubscriptionsApi>
}
export interface SolanaClientConfig {
rpc: string
rpcSubscriptions?: string
}
export function createSolanaClient(config: SolanaClientConfig): SolanaClient {
const rpc = createSolanaRpc(config.rpc)
const rpcSubscriptions = createSolanaRpcSubscriptions(
// Figure out the subscriptions URL if it's not provided.
config.rpcSubscriptions ?? config.rpc.replace('https', 'wss').replace('8899', '8900'),
)
return {
rpc,
rpcSubscriptions,
}
}
@beeman
Copy link
Author

beeman commented Mar 7, 2025

any updates here @beeman @arjendevos ?

Work on the new wallet adapter is still going on. I hope there will be a new template by next week this time. Sorry for the delays here.

Be sure to check my X if you want to see when I publish the new template.

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