TypeScript Setup

Learn how to create a TypeScript application 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.

TypeScript App

This approach shows how to create a TypeScript application and manually configure the Okto SDK. Follow these steps to set up your project and execute your first token transfer.

Prerequisites

Before getting started, ensure you have the following:

Tip:Setting up Google OAuth
Show
  1. Go to Google Cloud Console.
  2. Create OAuth 2.0 credentials for your project.
  3. Set the redirect URI to: [YOUR_APP_URL]/api/auth/callback/google (for example, http://localhost:3000/api/auth/callback/google during local development).
  4. Save your Client ID.

Need detailed instructions? Check our Google Console Setup Guide.

Initialize a TypeScript Project

If you already have a TypeScript project, you can skip this step and proceed directly to Step 2 to start integrating Okto.

bash
mkdir my-okto-app
cd my-okto-app
npm init -y
npm install typescript @types/node --save-dev
npx tsc --init

Install Dependencies

Install the required packages:

npm install @okto_web3/core-js-sdk@latest

Configure Environment Variables

Create a .env file in your project root:

.env
CLIENT_PRIVATE_KEY=YOUR_CLIENT_PRIVATE_KEY
CLIENT_SWA=YOUR_CLIENT_SWA
ENVIRONMENT=sandbox

Create a configuration file to load these variables:

config.ts
import * as dotenv from 'dotenv';
dotenv.config();
 
export const config = {
    environment: process.env.ENVIRONMENT || 'sandbox',
    clientPrivateKey: process.env.CLIENT_PRIVATE_KEY! ,
    clientSWA: process.env.CLIENT_SWA!,
};

Initialize Okto Client

Create your main file:

index.ts
import { Hash, Hex, OktoClient } from '@okto_web3/core-js-sdk';
import { config } from './config';
 
const oktoClient = new OktoClient({
    environment: config.environment,
    clientPrivateKey: config.clientPrivateKey as Hash,
    clientSWA: config.clientSWA as Hex,
});
 
async function main() {
    // Your code will go here
    console.log("Okto client initialized!");
}
 
main().catch(console.error);

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.

Update your main file to include authentication:

index.ts
async function authenticate(idToken: string) {
    try {
        const user = await oktoClient.loginUsingOAuth({
            idToken,
            provider: "google",
        });
        console.log("Authentication successful:", user);
        return user;
    } catch (error) {
        console.error("Authentication failed:", error);
        throw error;
    }
}

Start Development

Run your application:

npx ts-node index.ts

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

Add this function to your main file:

index.ts
import { tokenTransfer } from "@okto_web3/core-js-sdk";
 
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);
        console.log(`Transfer jobId! Result: ${jobId}`);
 
    } catch (error) {
        console.error("Transfer failed:", error);
        throw error;
    }
}

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.


SDK Reference

Get Commands

MethodDescriptionDocumentation
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].