React Setup
Learn how to create a React app and initialize it with the Okto SDK, including setting up authentication and executing your first token transfer.
Quick Start Template Available!
Skip the manual setup and get started in minutes with our template repository. Please note that this template is for development and testing purposes only. Be sure to customize and secure it before using in production.
Prerequisites
Before you begin, set up your developer dashboard by making sure you have :
- Created your Okto Developer Dashboard account
- Get your Okto credits from the dashboard
- Obtained your API keys from the dashboard
- Enabled the specific Chains and Tokens you plan to use in your application
- Optional: Enabled Sponsorship for the desired chains
If you need help, reach out to us on our troubleshooting form and we will contact you.
Before getting started, ensure you have the following:
- Node.js (v18+) and npm/pnpm/yarn: Download Node.js
- Okto API Keys: You need your
VITE_OKTO_CLIENT_PRIVATE_KEY
andVITE_OKTO_CLIENT_SWA
. Obtain these from the Okto Developer Dashboard. - Okto Account Setup: Ensure you have sufficient Okto Credits, enable the required Chains and Tokens , and optionally Activate Sponsorship.
- Google OAuth Credentials (if using Google authentication): Create OAuth 2.0 credentials in the Google Cloud Console to get your
VITE_GOOGLE_CLIENT_ID
.
- Go to Google Cloud Console.
- Create OAuth 2.0 credentials for your project.
- Set the redirect URI to:
[YOUR_APP_URL]/api/auth/callback/google
(for example,http://localhost:3000/api/auth/callback/google
during local development). - Save your Client ID.
Need detailed instructions? Check our Google Console Setup Guide.
Sponsorship Setup (Optional)
To enable sponsorship for transactions via Okto, follow the steps below:
-
Enable Supported Chains: Ensure the chains you wish to sponsor transactions on are enabled in your Okto Dashboard under Chains & Tokens.
-
Create and Configure a Treasury Wallet: Create at least one Treasury Wallet in your Okto Dashboard.
- For each supported chain:
- The Treasury Wallet used as the
feePayerAddress
must have its corresponding destination chain address funded with a small amount of native tokens for one-time verification. - Refer to the Treasury Wallet Docs for setup and verification details.
- The Treasury Wallet used as the
-
Activate Sponsorship: Navigate to the Sponsorship section in the Okto Dashboard and enable sponsorship for each chain individually.
-
Fund the Sponsor Wallet: Deposit a sufficient amount of native tokens into your Sponsor Wallet for each chain where sponsorship is active. These tokens will be used to cover user transaction fees.
- Only native tokens of the respective chains can be loaded into sponsorship accounts.
- Each chain has a unique sponsorship address. You can find this address in your Okto dashboard.
- For testnets, you can use faucets to acquire tokens.
1. Initialize a Vite React App
If you already have a React app, you can skip this step and proceed directly to Step 2 to start integrating Okto.
To create a new React app, run the following commands in your terminal:
npm create vite@latest my-okto-app --template react-ts
cd my-okto-app
Resolving Vite Buffer Error
To resolve a buffer not defined error with Vite, update your vite.config.ts
file with the following configuration:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { nodePolyfills } from "vite-plugin-node-polyfills";
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), nodePolyfills()],
server: {
port: 3000, // will always start the service on port 3000
},
});
Don't forget to install the required package:
npm i -D vite-plugin-node-polyfills
2. Install Dependencies
Install the required packages:
npm i @okto_web3/react-sdk@latest @react-oauth/google
pnpm add @okto_web3/react-sdk@latest @react-oauth/google
yarn add @okto_web3/react-sdk@latest @react-oauth/google
3. Configure Environment Variables
Create a .env
file in your project root:
# The Okto environment "sandbox" or "production"
VITE_OKTO_ENVIRONMENT="sandbox"
# Get the below values from Okto Developer Dashboard. Learn how here- https://docs.okto.tech/docs/developer-admin-dashboard
VITE_OKTO_CLIENT_PRIVATE_KEY="YOUR_CLIENT_PRIVATE_KEY"
VITE_OKTO_CLIENT_SWA="YOUR_CLIENT_SWA"
# Google OAuth credentials (Required only if you want to enable Google Sign-In)
VITE_GOOGLE_CLIENT_ID="YOUR_GOOGLE_CLIENT_ID"
Replace the placeholders with your actual credentials.
- Replace all placeholder values (
YOUR_...
) with your actual keys. - Never commit your
.env
file to version control. Add it to your.gitignore
.
- Go to Google Cloud Console.
- Create OAuth 2.0 credentials for your project.
- Set the redirect URI to:
[YOUR_APP_URL]/auth/google
(for example,http://localhost:3000/auth/google
during local development). - Save your Client ID and Client Secret.
Need detailed instructions? Check our Google Console Setup Guide.
4. Set Up Okto Provider
Update your main.tsx
to initialize the Okto SDK:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { OktoProvider } from "@okto_web3/react-sdk";
const config = {
environment: import.meta.env.VITE_OKTO_ENVIRONMENT,
clientPrivateKey: import.meta.env.VITE_OKTO_CLIENT_PRIVATE_KEY,
clientSWA: import.meta.env.VITE_OKTO_CLIENT_SWA,
};
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<OktoProvider config={config}>
<App />
</OktoProvider>
</React.StrictMode>
);
5. Set Up Google OAuth Provider
Wrap your app with the Google OAuth provider:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { GoogleOAuthProvider } from "@react-oauth/google";
import { OktoProvider } from "@okto_web3/react-sdk";
const config = {
environment: import.meta.env.VITE_OKTO_ENVIRONMENT,
clientPrivateKey: import.meta.env.VITE_OKTO_CLIENT_PRIVATE_KEY,
clientSWA: import.meta.env.VITE_OKTO_CLIENT_SWA,
};
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<GoogleOAuthProvider clientId={import.meta.env.VITE_GOOGLE_CLIENT_ID}>
<OktoProvider config={config}>
<App />
</OktoProvider>
</GoogleOAuthProvider>
</React.StrictMode>
);
6. Implement Authentication
Currently, you can onboard users and support on-chain interaction via the Okto Embedded wallet. To do this you must first authenticate your user via social login. We currently support Google OAuth.
import { useState } from "react";
import { useOkto } from "@okto_web3/react-sdk";
import { GoogleLogin } from "@react-oauth/google";
import { UserDashboard } from "./components/UserDashboard";
function App() {
const oktoClient = useOkto();
const [isLoading, setIsLoading] = useState(false);
async function handleGoogleLogin(credentialResponse: any) {
try {
setIsLoading(true);
await oktoClient.loginUsingOAuth({
idToken: credentialResponse.credential,
provider: "google",
});
} catch (error) {
console.error("Authentication error:", error);
} finally {
setIsLoading(false);
}
}
return (
<div>
{isLoading ? (
<div>Loading...</div>
) : oktoClient.userSWA ? (
<UserDashboard />
) : (
<GoogleLogin onSuccess={handleGoogleLogin} />
)}
</div>
);
}
export default App;
The user's embedded wallet is automatically created or retrieved once the session is created and can be accessed via TypeScript and React.
7. Get User Details and Portfolio
Create a UserDashboard component to display user information:
import { useOkto, getAccount, getPortfolio } from "@okto_web3/react-sdk";
import { useEffect, useState } from "react";
export function UserDashboard() {
const oktoClient = useOkto();
const [accounts, setAccounts] = useState([]);
const [portfolio, setPortfolio] = useState(null);
useEffect(() => {
async function fetchUserData() {
// Get user's accounts/wallets
const userAccounts = await getAccount(oktoClient);
setAccounts(userAccounts);
// Get user's portfolio
const userPortfolio = await getPortfolio(oktoClient);
setPortfolio(userPortfolio);
}
fetchUserData();
}, []);
return (
<div>
<h2>Welcome {oktoClient.userSWA}</h2>
<h3>Your Accounts:</h3>
{accounts.map(account => (
<div key={account.caipId}>
<p>Network: {account.networkName}</p>
<p>Address: {account.address}</p>
</div>
))}
<h3>Portfolio:</h3>
<pre>{JSON.stringify(portfolio, null, 2)}</pre>
</div>
);
}
9. Congratulations!
🎉 Your basic Okto integration is now complete! You're ready to bring your dApp to life. Let's try out a simple user operation!
Trying Out a User Operation
Now that we have our basic setup complete, let's implement a token transfer on Polygon Amoy Testnet to understand how user operations work in Okto.
1. Get Your Wallet Address
First, get your Polygon wallet address:
import { getAccount } from "@okto_web3/react-sdk";
const accounts = await getAccount(oktoClient);
const polygonAccount = accounts.data.find(account => account.network_name === "POLYGON_TESTNET_AMOY");
console.log("Your Polygon Amoy address:", polygonAccount.address);
2. Fund Your Wallet
To perform a token transfer, you'll need some funds in your wallet. Add funds to this address using the Polygon Amoy Faucet.
3. Check Network Information
Before creating the user operation, check the Network Information Guide for getting the correct CAIP-2 IDs of chains.
4. Implement Token Transfer
Create a new component for handling the transfer:
import { useOkto } from "@okto_web3/react-sdk";
import { tokenTransfer } from "@okto_web3/react-sdk";
import { useState } from "react";
export function TokenTransfer() {
const oktoClient = useOkto();
const [status, setStatus] = useState("");
async function handleTransfer() {
try {
const transferParams = {
amount: BigInt("1000000000000000000"), // 1 POL (18 decimals)
recipient: "RECIPIENT_ADDRESS",
token: "", // Empty string for native token
caip2Id: "eip155:80002" // Polygon Amoy Testnet chain ID
};
// Execute the transfer
const jobId = await tokenTransfer(oktoClient, transferParams);
setStatus(`Transfer jobId! Result: ${jobId}`);
} catch (error) {
console.error("Transfer failed:", error);
setStatus(`Transfer failed: ${error.message}`);
}
}
return (
<div>
<h2>Token Transfer</h2>
<button onClick={handleTransfer}>
Send 1 POL
</button>
<p>{status}</p>
</div>
);
}
5. Verify The Transfer
After the transfer is complete, you can verify it through:
- The
getPortfolio
method to check your updated balance - The Polygon Explorer using the transaction hash which can be fetched using the
getOrdersHistory
method using thejobId
.
Now that you've completed your first user operation, you're ready to explore more advanced features! Check out our Usage Guide to learn about other operations like NFT transfers, contract interactions, and more.
For more examples and advanced usage, check out the Template Repo.
SDK Reference
Get Commands
Command | Description | Documentation |
---|---|---|
const account = await getAccount(oktoClient); | Get user's wallet details | Method Overview |
const chains = await getChains(oktoClient); | List supported blockchain networks | Method Overview |
const tokens = await getTokens(oktoClient); | List supported tokens | Method Overview |
const portfolio = await getPortfolio(oktoClient); | Get user's token holdings | Method Overview |
const nfts = await getPortfolioNFT(oktoClient); | Get user's NFT holdings | Method Overview |
const activity = await getPortfolioActivity(oktoClient); | Get transaction history | Method Overview |
const orders = await getOrdersHistory(oktoClient); | Get transaction order history | Method Overview |
const collections = await getNftCollections(oktoClient); | Get NFT collections | Method Overview |
Message Signing
Enables the creation of signatures for messages or object data. The signing process is initiated through the OktoClient instance.
Command | Description | Documentation |
---|---|---|
const signature = await oktoClient.signMessage(message); | Signs messages following the EIP191 standard | Method Overview |
const signature = await oktoClient.signTypedData(data); | Signs typed data following the EIP712 standard | Method Overview |
User Operations (Intents)
Intents are pre-built action templates within the Okto SDK that simplify common Web3 tasks. They provide one-liner functions for complex blockchain interactions.
1. Token Transfer
Send tokens to another address. Learn more
const transferParams = {
amount: BigInt("1000000000000000000"), // Amount in smallest unit
recipient: "0xRecipientAddress...", // Recipient wallet address
token: "", // Token address ("" for native token)
caip2Id: "eip155:137", // Target chain CAIP-2 ID
};
const result = await tokenTransfer(oktoClient, transferParams);
2. NFT Transfer
Transfer NFTs between addresses. Learn more
const nftParams = {
caip2Id: "eip155:1", // Target chain CAIP-2 ID
collectionAddress: "0xCollectionAddress...", // NFT Collection address
nftId: "NFTTokenID", // NFT identifier
recipientWalletAddress: "0xRecipientAddress...",// Recipient address
amount: 1, // Amount of tokens to transfer
nftType: "ERC721", // or "ERC1155"
};
const result = await nftTransfer(oktoClient, nftParams);
3. Raw Transaction (EVM)
Execute custom EVM contract calls. Learn more
import { encodeFunctionData } from "viem";
// 1. Define Contract Interaction
const functionName = "setValue";
const functionArgs = [123];
// 2. Encode Function Data
const functionData = encodeFunctionData({
abi: [
{
"name": functionName,
"type": "function",
"stateMutability": "nonpayable",
"inputs": [{ "type": "uint256", "name": "_value" }]
}
],
functionName,
args: functionArgs,
});
// 3. Execute Transaction
const rawTxParams = {
caip2Id: "eip155:1",
transaction: {
from: "0xuserWalletAddress",
to: "0xcontractAddress",
data: functionData,
value: BigInt(0),
},
};
const result = await evmRawTransaction(oktoClient, rawTxParams);
Quick Start Template Available!
Skip the manual setup and get started in minutes with our template repository. Please note that this template is for development and testing purposes only. Be sure to customize and secure it before using in production.
Additional Resources
Need help? Join our Discord community or email us at [email protected]
.