React Native Quickstart
Learn how to create a React Native app with Expo 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
CLIENT_PRIVATE_KEY
andCLIENT_SWA
. Obtain these from the Okto 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
You'll need to set up OAuth 2.0 credentials in the Google Cloud Console:
- For Web & Expo Go: Web Client Setup
- For iOS: iOS Setup
- For Android: Android Setup
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.
Initialize an Expo App
Create a new Expo project:
npx create-expo-app@latest my-okto-app
cd my-okto-app
Resolving 'Buffer' doesn't exist error
To resolve the Buffer error in React Native, follow these steps:
- Install the buffer package:
npm i buffer
pnpm add buffer
yarn add buffer
- Add this line to your
app/_layout.tsx
file (or any other entry point of your app):
global.Buffer = global.Buffer || Buffer;
This makes the Buffer object available globally in your React Native application.
Install Dependencies
Install the required packages. Note that expo-auth-session
and expo-web-browser
handle the OAuth flow for Google authentication:
npm i @okto_web3/react-native-sdk@latest expo-auth-session expo-web-browser react-native-mmkv
pnpm add @okto_web3/react-native-sdk@latest expo-auth-session expo-web-browser react-native-mmkv
yarn add @okto_web3/react-native-sdk@latest expo-auth-session expo-web-browser react-native-mmkv
Set Up Okto Provider
Initialize the Okto SDK by wrapping your app with OktoProvider. This provides the SDK context throughout your app:
import { Hash, Hex, OktoProvider } from '@okto_web3/react-native-sdk';
import { ThemeProvider } from '@react-navigation/native';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
const config = {
environment: "sandbox",
clientPrivateKey: "YOUR_CLIENT_PRIVATE_KEY" as Hash, // Replace with your actual private key
clientSWA: "YOUR_CLIENT_SWA" as Hex, // Replace with your actual SWA
};
export default function RootLayout() {
return (
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
<OktoProvider config={config}>
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="+not-found" />
</Stack>
</OktoProvider>
<StatusBar style="auto" />
</ThemeProvider>
);
}
Implement Authentication
Create the authentication screen in app/(tabs)/index.tsx
:
import { View, Text, TouchableOpacity } from 'react-native';
import { useOkto } from '@okto_web3/react-native-sdk';
import * as Google from 'expo-auth-session/providers/google';
import * as WebBrowser from 'expo-web-browser';
import { useEffect } from 'react';
WebBrowser.maybeCompleteAuthSession();
export default function Index() {
const oktoClient = useOkto();
const [request, response, promptAsync] = Google.useAuthRequest({
webClientId: 'YOUR_WEB_CLIENT_ID', //for web & Expo Go
iosClientId: 'YOUR_IOS_CLIENT_ID', //for ios
androidClientId: 'YOUR_ANDROID_CLIENT_ID', //for android
scopes: ['openid', 'profile', 'email']
});
const handleAuthenticate = async (idToken: string) => {
try {
const response = await oktoClient.loginUsingOAuth({
idToken: idToken,
provider: 'google',
});
console.log("Authenticated with Okto", response);
} catch (error) {
console.error("Authentication failed:", error);
}
};
useEffect(() => {
if (response?.type === 'success') {
const { id_token } = response.params;
if (id_token) {
handleAuthenticate(id_token);
} else {
console.warn("ID token not returned!");
}
}
}, [response]);
return (
<View>
<Text>Welcome to Okto</Text>
<TouchableOpacity onPress={() => promptAsync()}>
<Text>Sign in with Google</Text>
</TouchableOpacity>
</View>
);
}
You'll need to set up OAuth 2.0 credentials in the Google Cloud Console:
- For Web & Expo Go: Web Client Setup
- For iOS: iOS Setup
- For Android: Android Setup
Get User Details and Portfolio
Create a new file app/(tabs)/HomeScreen.tsx
to fetch and display user's accounts and portfolio. This demonstrates basic SDK data retrieval:
import React, { useEffect, useState } from 'react';
import { View, Text, ScrollView } from 'react-native';
import { useOkto, getAccount, getPortfolio } from '@okto_web3/react-native-sdk';
export function HomeScreen() {
const oktoClient = useOkto();
const [accounts, setAccounts] = useState<any>([]);
const [portfolio, setPortfolio] = useState<any>();
useEffect(() => {
async function fetchUserData() {
try {
// Get user's accounts
const userAccounts = await getAccount(oktoClient);
setAccounts(userAccounts.data);
// Get user's portfolio
const userPortfolio = await getPortfolio(oktoClient);
setPortfolio(userPortfolio);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchUserData();
}, []);
return (
<ScrollView>
<Text>Your Accounts</Text>
{accounts.map((account: any) => (
<View key={account.caip_id}>
<Text>Network: {account.network_name}</Text>
<Text>Address: {account.address}</Text>
</View>
))}
<Text>Portfolio</Text>
<Text>{JSON.stringify(portfolio, null, 2)}</Text>
</ScrollView>
);
}
Run Your App
Start your Expo app:
npx expo start
This will open the Expo development server. You can run your app on:
- iOS Simulator
- Android Emulator
- Physical device using Expo Go app
- Web browser
Congratulations!
🎉 Your basic Okto integration is now complete! You're ready to explore more features and implement additional functionality.
Prerequisites
Before getting started, ensure you have the following:
- Node.js (v18+) and npm/yarn: Download Node.js
- Okto API Keys: You need your
CLIENT_PRIVATE_KEY
andCLIENT_SWA
. Obtain these from the Okto Dashboard. - Google OAuth Credentials: Create OAuth 2.0 credentials in the Google Cloud Console
You'll need to set up OAuth 2.0 credentials in the Google Cloud Console:
- For Web: Web Client Setup
- For iOS: iOS Setup
- For Android: Android Setup
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.
Initialize a React Native App
If you already have a React Native app, you can skip this step and proceed directly to Step 2.
Create a new React Native project using the CLI:
npx @react-native-community/cli@latest init OktoApp
cd OktoApp
Install Dependencies
Install the required packages:
npm i @okto_web3/react-native-sdk@latest @react-native-community/google-signin @react-native-async-storage/async-storage
# For iOS only: Install CocoaPods dependencies
npx pod-install
pnpm add @okto_web3/react-native-sdk@latest @react-native-community/google-signin @react-native-async-storage/async-storage
# For iOS only: Install CocoaPods dependencies
npx pod-install
yarn add @okto_web3/react-native-sdk@latest @react-native-community/google-signin @react-native-async-storage/async-storage
# For iOS only: Install CocoaPods dependencies
npx pod-install
Set Up Okto Provider
Update your index.js
to initialize the Okto SDK:
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import { OktoProvider } from '@okto_web3/react-native-sdk';
const config = {
environment: "sandbox",
clientPrivateKey: "YOUR_CLIENT_PRIVATE_KEY", // Replace with your actual private key
clientSWA: "YOUR_CLIENT_SWA", // Replace with your actual SWA
};
function Root() {
return (
<OktoProvider config={config}>
<App />
</OktoProvider>
);
}
AppRegistry.registerComponent(appName, () => Root);
Platform-Specific Setup
iOS Setup
In Xcode, open Info
tab as below:
Under the URL Types section, click
+
button. In the URL Schemes
field, enter your reversed iOS client ID
Android Setup
Update your android/build.gradle
:
buildscript {
ext {
// ... existing config
googlePlayServicesAuthVersion = "19.0.0"
}
// ... rest of the file
dependencies {
// ... existing dependencies
classpath('com.google.gms:google-services:4.3.4')
}
}
Implement Authentication
Create a new file called GoogleSignInButton.tsx
:
import React, { useState } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import { GoogleSignin, User } from '@react-native-community/google-signin';
import { useOkto } from '@okto_web3/react-native-sdk';
GoogleSignin.configure({
webClientId: 'OAUTH_WEB_CLIENT_ID', // Replace with your actual Web Client ID
androidClientId: 'OAUTH_ANDROID_CLIENT_ID', // Replace with your actual Android Client ID
iosClientId: 'OAUTH_IOS_CLIENT_ID', // Replace with your actual iOS Client ID
offlineAccess: false,
});
export function GoogleSignInButton() {
const oktoClient = useOkto();
const [userInfo, setUserInfo] = useState<User | null>(null);
const signIn = async () => {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
setUserInfo(userInfo);
await oktoClient.loginUsingOAuth({
idToken: userInfo.idToken,
provider: "google",
});
} catch (error) {
console.error('Sign-in error:', error);
}
};
return (
<View style={styles.container}>
{userInfo ? (
<Text>Welcome {userInfo.user.name}</Text>
) : (
<Button title="Sign in with Google" onPress={signIn} />
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
padding: 20,
}
});
Get User Details and Portfolio
Create a new file called Dashboard.tsx
:
import React, { useEffect, useState } from 'react';
import { View, Text, ScrollView, StyleSheet } from 'react-native';
import { useOkto, getAccount, getPortfolio } from '@okto_web3/react-native-sdk';
export function Dashboard() {
const oktoClient = useOkto();
const [accounts, setAccounts] = useState<any>([]);
const [portfolio, setPortfolio] = useState<any>();
useEffect(() => {
async function fetchUserData() {
try {
// Get user's accounts
const userAccounts = await getAccount(oktoClient);
setAccounts(userAccounts.data);
// Get user's portfolio
const userPortfolio = await getPortfolio(oktoClient);
setPortfolio(userPortfolio);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchUserData();
}, []);
return (
<ScrollView style={styles.container}>
<Text style={styles.title}>Your Accounts</Text>
{accounts.map((account: any) => (
<View key={account.caip_id} style={styles.accountCard}>
<Text>Network: {account.network_name}</Text>
<Text>Address: {account.address}</Text>
</View>
))}
<Text style={styles.title}>Portfolio</Text>
<Text>{JSON.stringify(portfolio, null, 2)}</Text>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 20,
fontWeight: 'bold',
marginVertical: 10,
},
accountCard: {
padding: 10,
marginVertical: 5,
backgroundColor: '#f5f5f5',
borderRadius: 5,
},
});
Congratulations! 🎉
You've successfully set up your React Native app with Okto SDK! You can now:
- Authenticate users with Google Sign-In
- View user accounts and portfolio
- Start implementing more advanced features
Check out our Usage Guide to learn about other operations like token transfers, NFT transfers, and more.
Trying Out a User Operation
Let's implement a token transfer on Polygon Testnet Amoy to understand how user operations work in Okto.
1. Get Your Wallet Address
import { getAccount } from '@okto_web3/react-native-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
Add funds to your wallet using the Polygon Amoy Faucet.
3. Implement Token Transfer
Create a transfer component:
import React, { useState } from 'react';
import { View, Button, Text } from 'react-native';
import { useOkto, tokenTransfer } from '@okto_web3/react-native-sdk';
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
};
//create the user operation
const userOp = await tokenTransfer(oktoClient, transferParams);
//sign the user operation
const signedOp = await oktoClient.signUserOp(userOp);
//send the user operation
const jobId = await oktoClient.executeUserOp(signedOp);
setStatus(`Transfer complete! JobId: ${jobId}`);
} catch (error) {
console.error("Transfer failed:", error);
setStatus(`Transfer failed: ${error.message}`);
}
}
return (
<View>
<Button
title="Send 1 POL"
onPress={handleTransfer}
/>
<Text>{status}</Text>
</View>
);
}
4. Verify The Transfer
After the transfer is complete, you can verify it through:
- The
getPortfolio
method to check your updated balance - The Polygon Amoy 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: "0xTokenAddress...", // Token address ("" for native token)
caip2Id: "eip155:1", // 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: 1n,
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 contractAddress = '0xContractAddress...';
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" }]
}
] as const,
functionName,
args: functionArgs,
});
// 3. Execute Transaction
const rawTxParams = {
caip2Id: "eip155:1",
transaction: {
to: contractAddress,
data: functionData,
// value: BigInt(0), // Optional: for payable functions
},
};
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]
.