Provider Hooks
Provider hooks require your component tree to be wrapped in OneProvider (or OneThirdwebProvider for Thirdweb-specific hooks). They are web-only -- React DOM apps that render inside a browser.
Calling any provider hook outside of OneProvider throws:
Error: useOne must be used within a OneProvider
If you need hooks in React Native, use the standalone hooks, AI Trading hooks, or Forex hooks instead.
Provider Setup
Before using any provider hook, wrap your app root:
import { OneProvider } from '@one_deploy/sdk';
function App() {
return (
<OneProvider
config={{
apiKey: process.env.NEXT_PUBLIC_ONE_API_KEY!,
projectId: process.env.NEXT_PUBLIC_ONE_PROJECT_ID!,
engineUrl: 'https://engine.one23.io', // optional, defaults to production
}}
>
<YourApp />
</OneProvider>
);
}
If you also use Thirdweb wallet features, wrap with OneThirdwebProvider:
import { OneThirdwebProvider } from '@one_deploy/sdk';
function App() {
return (
<OneThirdwebProvider
config={{
apiKey: process.env.NEXT_PUBLIC_ONE_API_KEY!,
projectId: process.env.NEXT_PUBLIC_ONE_PROJECT_ID!,
}}
thirdwebClientId={process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID!}
>
<YourApp />
</OneThirdwebProvider>
);
}
useOne
The main context hook. Returns the full SDK context including configuration, engine client, and current auth state.
Signature
function useOne(): OneContextValue;
interface OneContextValue {
/** The OneEngineClient instance managed by the provider. */
engineClient: OneEngineClient;
/** Current SDK configuration. */
config: OneConfig;
/** Whether the SDK has finished initializing. */
isReady: boolean;
/** Current authenticated user, or null. */
user: OneUser | null;
/** Whether a user is currently authenticated. */
isAuthenticated: boolean;
}
Usage
import { useOne } from '@one_deploy/sdk';
function Dashboard() {
const { engineClient, isReady, isAuthenticated, user } = useOne();
if (!isReady) return <p>Initializing SDK...</p>;
if (!isAuthenticated) return <p>Please sign in.</p>;
return (
<div>
<h1>Welcome, {user?.email}</h1>
<button
onClick={async () => {
const wallets = await engineClient.getUserWallets();
console.log(wallets);
}}
>
Load Wallets
</button>
</div>
);
}
useOneAuth
Manages authentication state: login, logout, and session info.
Signature
function useOneAuth(): OneAuthContextValue;
interface OneAuthContextValue {
/** The authenticated user object, or null. */
user: OneUser | null;
/** Whether a user session is active. */
isAuthenticated: boolean;
/** Whether an auth operation is in progress. */
isLoading: boolean;
/** Start an email OTP login flow. */
loginWithEmail: (email: string) => Promise<void>;
/** Verify the OTP code sent to the user's email. */
verifyEmailOtp: (email: string, otp: string) => Promise<OneUser>;
/** Start a wallet-signature login flow. */
loginWithWallet: (address: string, signature: string) => Promise<OneUser>;
/** Log the current user out and clear session tokens. */
logout: () => Promise<void>;
/** The current access token, or null. */
accessToken: string | null;
}
interface OneUser {
id: string;
email: string | null;
walletAddress: string | null;
createdAt: string;
}
Usage
import { useOneAuth } from '@one_deploy/sdk';
import { useState } from 'react';
function LoginForm() {
const { loginWithEmail, verifyEmailOtp, isLoading, isAuthenticated, user } = useOneAuth();
const [email, setEmail] = useState('');
const [otp, setOtp] = useState('');
const [otpSent, setOtpSent] = useState(false);
if (isAuthenticated) {
return <p>Signed in as {user?.email}</p>;
}
const handleSendOtp = async () => {
await loginWithEmail(email);
setOtpSent(true);
};
const handleVerify = async () => {
const user = await verifyEmailOtp(email, otp);
console.log('Authenticated:', user.id);
};
return (
<div>
{!otpSent ? (
<>
<input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
<button onClick={handleSendOtp} disabled={isLoading}>Send OTP</button>
</>
) : (
<>
<input value={otp} onChange={(e) => setOtp(e.target.value)} placeholder="Enter OTP" />
<button onClick={handleVerify} disabled={isLoading}>Verify</button>
</>
)}
</div>
);
}
useOneWallet
Provides wallet operations: listing wallets, active wallet selection, and balance data.
Signature
function useOneWallet(): OneWalletContextValue;
interface OneWalletContextValue {
/** All wallets belonging to the current user. */
wallets: Wallet[];
/** The currently selected (active) wallet. */
activeWallet: Wallet | null;
/** Set a wallet as the active wallet by address. */
setActiveWallet: (address: string) => void;
/** Aggregated USD balance of the active wallet. */
balance: string | null;
/** Whether wallets are being loaded. */
isLoading: boolean;
/** Error from the last wallet operation, or null. */
error: OneSDKError | null;
/** Refresh the wallet list and balances. */
refetch: () => Promise<void>;
}
interface Wallet {
address: string;
type: 'smart' | 'eoa';
chainId: number;
createdAt: string;
status: 'active' | 'pending_deployment';
}
Usage
import { useOneWallet } from '@one_deploy/sdk';
function WalletSelector() {
const { wallets, activeWallet, setActiveWallet, balance, isLoading } = useOneWallet();
if (isLoading) return <p>Loading wallets...</p>;
return (
<div>
<h2>Active: {activeWallet?.address ?? 'None selected'}</h2>
<p>Balance: ${balance ?? '0.00'}</p>
<ul>
{wallets.map((w) => (
<li key={w.address}>
<button onClick={() => setActiveWallet(w.address)}>
{w.address} ({w.type}, chain {w.chainId})
</button>
</li>
))}
</ul>
</div>
);
}
useOneOnramp
Manages fiat on-ramp operations: fetching quotes and creating buy sessions.
Signature
function useOneOnramp(): OneOnrampContextValue;
interface OneOnrampContextValue {
/** Fetch a quote for buying crypto with fiat. */
getQuote: (params: OnrampQuoteParams) => Promise<OnrampQuote>;
/** Create a payment session from a quote. */
createSession: (params: OnrampSessionRequest) => Promise<OnrampSession>;
/** The most recently fetched quote, or null. */
currentQuote: OnrampQuote | null;
/** Whether a quote or session request is in progress. */
isLoading: boolean;
/** Error from the last onramp operation, or null. */
error: OneSDKError | null;
}
interface OnrampQuoteParams {
fiatCurrency: string;
fiatAmount: number;
cryptoCurrency: string;
paymentMethod?: string;
}
Usage
import { useOneOnramp } from '@one_deploy/sdk';
function BuyCrypto() {
const { getQuote, createSession, currentQuote, isLoading, error } = useOneOnramp();
const handleBuy = async () => {
const quote = await getQuote({
fiatCurrency: 'USD',
fiatAmount: 100,
cryptoCurrency: 'USDT',
paymentMethod: 'card',
});
const session = await createSession({
quoteId: quote.quoteId,
walletAddress: '0xAbc...',
chainId: 137,
});
// Redirect user to session.paymentUrl
window.location.href = session.paymentUrl!;
};
return (
<div>
<button onClick={handleBuy} disabled={isLoading}>Buy 100 USD of USDT</button>
{currentQuote && (
<p>Rate: 1 USD = {currentQuote.exchangeRate} USDT (fee: ${currentQuote.fee.amount})</p>
)}
{error && <p>Error: {error.message}</p>}
</div>
);
}
useOneSwap
Manages token swap operations: fetching quotes, previewing routes, and executing swaps.
Signature
function useOneSwap(): OneSwapContextValue;
interface OneSwapContextValue {
/** Fetch a swap quote. */
getQuote: (params: SwapQuoteParams) => Promise<SwapQuote>;
/** Execute a swap from a quote. */
executeSwap: (quoteId: string) => Promise<SwapTransaction>;
/** The most recently fetched swap quote, or null. */
currentQuote: SwapQuote | null;
/** Whether a swap operation is in progress. */
isLoading: boolean;
/** Error from the last swap operation, or null. */
error: OneSDKError | null;
}
interface SwapQuoteParams {
fromToken: string;
toToken: string;
amount: string;
chainId: number;
slippageBps?: number;
}
interface SwapQuote {
quoteId: string;
fromToken: string;
toToken: string;
fromAmount: string;
toAmount: string;
exchangeRate: number;
priceImpact: number;
route: string[];
estimatedGas: string;
expiresAt: string;
}
interface SwapTransaction {
transactionHash: string;
status: 'pending' | 'confirmed' | 'failed';
fromAmount: string;
toAmount: string;
}
Usage
import { useOneSwap, CHAIN_IDS } from '@one_deploy/sdk';
function SwapPage() {
const { getQuote, executeSwap, currentQuote, isLoading, error } = useOneSwap();
const handleSwap = async () => {
const quote = await getQuote({
fromToken: 'ETH',
toToken: 'USDC',
amount: '0.5',
chainId: CHAIN_IDS.BASE,
slippageBps: 50, // 0.5%
});
console.log(`Swap 0.5 ETH -> ${quote.toAmount} USDC`);
const tx = await executeSwap(quote.quoteId);
console.log('Swap tx:', tx.transactionHash);
};
return (
<div>
<button onClick={handleSwap} disabled={isLoading}>Swap ETH to USDC</button>
{currentQuote && (
<p>
You receive: {currentQuote.toAmount} USDC
(impact: {currentQuote.priceImpact}%)
</p>
)}
{error && <p>Error: {error.message}</p>}
</div>
);
}
useOneTrading
Provides AI trading operations through the provider context. This is the provider-based counterpart to the standalone useAITrading hook.
Signature
function useOneTrading(): OneTradingContextValue;
interface OneTradingContextValue {
/** Create a new AI trading order. */
createOrder: (params: CreateAIOrderParams) => Promise<AIOrder>;
/** Cancel an active order. */
cancelOrder: (orderId: string) => Promise<void>;
/** List orders for the current user. */
getOrders: (params?: AIOrderFilterParams) => Promise<AIOrder[]>;
/** Fetch portfolio summary. */
getPortfolio: () => Promise<AIPortfolioSummary>;
/** Whether a trading operation is in progress. */
isLoading: boolean;
/** Error from the last trading operation, or null. */
error: OneSDKError | null;
}
Usage
import { useOneTrading } from '@one_deploy/sdk';
function TradingDashboard() {
const { getOrders, getPortfolio, isLoading } = useOneTrading();
const loadData = async () => {
const [orders, portfolio] = await Promise.all([
getOrders({ status: 'active' }),
getPortfolio(),
]);
console.log(`Active orders: ${orders.length}`);
console.log(`Total invested: $${portfolio.totalInvested}`);
};
return <button onClick={loadData} disabled={isLoading}>Load Trading Data</button>;
}
useOneEngine
Returns the OneEngineClient instance from the provider. Use this when you need to call raw API methods not covered by the higher-level hooks.
Signature
function useOneEngine(): OneEngineContextValue;
interface OneEngineContextValue {
/** The OneEngineClient instance, fully configured with auth. */
engineClient: OneEngineClient;
/** Whether the engine client has finished initialization. */
isReady: boolean;
}
Usage
import { useOneEngine } from '@one_deploy/sdk';
function AdvancedOperations() {
const { engineClient, isReady } = useOneEngine();
if (!isReady) return <p>Initializing...</p>;
const handleDeploy = async () => {
// Access any of the 91+ OneEngineClient methods directly
const result = await engineClient.deployContract({
chainId: 8453,
bytecode: '0x...',
abi: [...],
constructorArgs: ['My Token', 'MTK'],
});
console.log('Deployed at:', result.contractAddress);
};
const handleBridge = async () => {
const quote = await engineClient.getBridgeQuote({
fromChainId: 1,
toChainId: 8453,
token: 'USDC',
amount: '1000',
});
console.log('Bridge fee:', quote.fee);
};
return (
<div>
<button onClick={handleDeploy}>Deploy Contract</button>
<button onClick={handleBridge}>Get Bridge Quote</button>
</div>
);
}
useThirdwebClient
Returns the Thirdweb client instance from OneThirdwebProvider. Use this to interact with the Thirdweb SDK directly for advanced wallet and contract operations.
Signature
function useThirdwebClient(): ThirdwebClientContextValue;
interface ThirdwebClientContextValue {
/** The Thirdweb client instance. */
client: ThirdwebClient;
/** Whether the Thirdweb client is ready. */
isReady: boolean;
}
Usage
import { useThirdwebClient } from '@one_deploy/sdk';
function ThirdwebExample() {
const { client, isReady } = useThirdwebClient();
if (!isReady) return <p>Loading Thirdweb...</p>;
return (
<div>
<p>Thirdweb client loaded. Client ID: {client.clientId}</p>
{/* Pass the client to other Thirdweb components or SDK calls */}
</div>
);
}
useThirdwebClient requires your app to be wrapped in OneThirdwebProvider, not the plain OneProvider. If you use OneProvider without Thirdweb, this hook will throw.
Error Handling
All provider hooks surface errors through the error field in their return values. Errors are typed as OneSDKError:
interface OneSDKError {
code: string;
message: string;
details?: Record<string, unknown>;
}
Common error codes:
| Code | Meaning |
|---|---|
UNAUTHORIZED | No active session or token expired |
RATE_LIMITED | Too many requests -- retry after cooldown |
INVALID_PARAMS | Bad input to an API call |
NETWORK_ERROR | Failed to reach the ONE Engine API |
NOT_FOUND | Requested resource does not exist |
import { useOneSwap } from '@one_deploy/sdk';
function SwapWithErrorHandling() {
const { getQuote, error } = useOneSwap();
const handleQuote = async () => {
try {
await getQuote({ fromToken: 'ETH', toToken: 'USDC', amount: '1', chainId: 8453 });
} catch (err) {
// error is also available reactively via the hook return
console.error('Quote failed:', err);
}
};
return (
<div>
<button onClick={handleQuote}>Get Quote</button>
{error?.code === 'RATE_LIMITED' && <p>Too many requests. Please wait.</p>}
{error?.code === 'UNAUTHORIZED' && <p>Please sign in first.</p>}
</div>
);
}
See Also
- Hooks Overview -- all hook categories at a glance.
- Provider Setup -- configuring
OneProvider. - useWalletBalance -- standalone balance hook.
- AI Trading Hooks -- standalone AI trading hooks.
- Forex Hooks -- standalone forex hooks.