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. It includes pre-configured Okto SDK integration, authentication setup, and example components and operations.

Warning:Essential Setup Required
Show

Before you begin, set up your developer dashboard by making sure you have :

If you need help, reach out to us on our troubleshooting form and we will contact you.

Prerequisites

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 and CLIENT_SWA. Obtain these from the Okto Dashboard.
  • Google OAuth Credentials: Create OAuth 2.0 credentials in the Google Cloud Console
Tip:Setting up Google OAuth
Show

You'll need to set up OAuth 2.0 credentials in the Google Cloud Console:

  1. For Web & Expo Go: Web Client Setup
  2. For iOS: iOS Setup
  3. For Android: Android Setup

Initialize an Expo App

Create a new Expo project:

bash
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:

  1. Install the buffer package:
npm i buffer
  1. 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

Set Up Okto Provider

Initialize the Okto SDK by wrapping your app with OktoProvider. This provides the SDK context throughout your app:

app/_layout.tsx
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:

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>
    );
}
Tip:Setting up Google OAuth
Show

You'll need to set up OAuth 2.0 credentials in the Google Cloud Console:

  1. For Web & Expo Go: Web Client Setup
  2. For iOS: iOS Setup
  3. 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:

app/(tabs)/HomeScreen.tsx
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:

bash
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.


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:

app/(tabs)/TokenTransfer.tsx
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 the jobId.

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

CommandDescriptionDocumentation
const account = await getAccount(oktoClient);Get user's wallet detailsMethod Overview
const chains = await getChains(oktoClient);List supported blockchain networksMethod Overview
const tokens = await getTokens(oktoClient);List supported tokensMethod Overview
const portfolio = await getPortfolio(oktoClient);Get user's token holdingsMethod Overview
const nfts = await getPortfolioNFT(oktoClient);Get user's NFT holdingsMethod Overview
const activity = await getPortfolioActivity(oktoClient);Get transaction historyMethod Overview
const orders = await getOrdersHistory(oktoClient);Get transaction order historyMethod Overview
const collections = await getNftCollections(oktoClient);Get NFT collectionsMethod 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. It includes pre-configured Okto SDK integration, authentication setup, and example components and operations.

Additional Resources

Need help? Join our Discord community or email us at [email protected].