Unity Setup

Learn how to create a Unity 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 Dashboard Setup Required
Show

Before you begin, ensure you've completed these steps in the Okto Developer Dashboard:

Need assistance? Use our troubleshooting form and we'll help you get started.

Prerequisites

Before getting started, ensure you have the following:

Tip:Setting up Google OAuth
Show
  1. Go to Google Cloud Console.
  2. Create a new project or select an existing one
  3. Create OAuth 2.0 credentials for your project.
  4. Save your Client ID.
  5. Add authorized redirect URIs if necessary

Need detailed instructions? Check our Google Console Setup Guide.

1. Create a new Unity project.

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

To create a new Unity project, just go to Unity Hub and choose version 2022.3.11f1 or higher.

Unity projects are generally not backward compatible. For the best experience, use the latest LTS (Long Term Support) version when starting your project.

2. Install Dependencies

Import the required packages:

Google Sign-In is a plugin that allows users to authenticate with their Google accounts in Unity applications.
Repository: https://github.com/googlesamples/google-signin-unity/releases

3. Configure Environment Variables

Set up your authentication credentials for Google and Okto services:

OktoClient.cs
// Your Okto client credentials from the developer dashboard
clientPrivateKey="YOUR_CLIENT_PRIVATE_KEY"
clientSwa="YOUR_CLIENT_SWA"
GoogleLogin.cs
// Google OAuth credentials (Required only if you want to enable Google Sign-In)
webClientId="YOUR_GOOGLE_CLIENT_ID"

Replace the placeholders with your actual credentials.

Warning:Important
Show
  • Never commit your webClientId parameter to version control. Add it to your .gitignore.

4. Initialize the Okto Client

Update your OktoClient.cs to initialize the Okto SDK:

OktoClient.cs
_clientConfig = new ClientConfig
{
    ClientPrivKey = config.ClientPrivateKey,
    ClientPubKey = GetPublicKey(config.ClientPrivateKey),
    ClientSWA = config.ClientSWA
};
_envConfig = config.Environment; 

This initializes the core Okto functionality in your Unity application, establishing a connection to the Okto backend services.

5. Set Up Google Authentication

Implement Google Sign-In functionality:

main.cs
    void InitializePlayGamesLogin()
    {
    #if GOOGLE_LOGIN
        configuration = new GoogleSignInConfiguration
        {
            WebClientId = webClientId,
            RequestEmail = true,
            RequestIdToken = true,
        };
    #else
        Debug.Log("Google Sign-In is not enabled. Please add GOOGLE_LOGIN to scripting define symbols.");
    }
    #endif

This configures the Google Sign-In provider with your credentials.

6. Implement User 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.

GoogleLogin.cs
(authenticationData, error) = await LoginGoogle();
if (error != null)
{
    Debug.LogError($"Login failed with error: {error.Message}");
}
else
{
    Debug.Log("Login successful!");
    Debug.Log("loginDone " + authenticationData);
}

The user's embedded wallet is automatically created or retrieved once the session is created and can be accessed via unity.

7. Get User Details and Portfolio

Use a BffClientRepository monobehavior to fetch user information:

BffClientRepository.cs
 
// Get user's wallet addresses across chains
public async Task<List<Wallet>> GetWallets()
{
    var response = await bffClient.Get<ApiResponse<List<Wallet>>>(Routes.GetWallets);
    if (response.status == "error")
    {
        throw new Exception("Failed to retrieve supported wallets");
    }
    if (response.data == null) 
    {
        throw new Exception("Response data is missing");
    }
    return response.data;
}
 
// Get user's portfolio
public async Task<UserPortfolioData> GetPortfolio()
{
    var response = await bffClient.Get<ApiResponse<UserPortfolioData>>(Routes.GetPortfolio);
    if (response.status == "error")
    {
        throw new Exception("Failed to retrieve portfolio");
    }
    if (response.data == null)
    {
        throw new Exception("Response data is missing");
    }
}

8. Start Unity App

Run your app:-

  1. Open the OktoDemo scene in the project
  2. Click the Play button in the Unity Editor
  3. Test the authentication flow with your Google credentials
  4. Explore available functions like wallet info and token balances

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:

public async Task<List<Wallet>> GetWallets()
{
    var response = await bffClient.Get<ApiResponse<List<Wallet>>>(Routes.GetWallets);
    if (response.status == "error")
    {
        throw new Exception("Failed to retrieve supported wallets");
    }
    if (response.data == null) 
    {
        throw new Exception("Response data is missing");
    }
    return response.data;
}

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. You can verify your balance using the GetPortfolio() method.

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:

TokenTransferView.cs
public async Task<string> ExecuteTokenTransfer(string receiptAddress, BigInteger amount, string network, string tokenAddress)
{
    // Create transfer parameters
    var transaction = new TokenTransferIntentParams
    {
        recipientWalletAddress = receiptAddress,
        tokenAddress = tokenAddress,
        amount = amount,
        caip2Id = network
    };
 
    Debug.Log($"Generated transaction: {JsonConvert.SerializeObject(transaction, Formatting.Indented)}");
 
    userOp = await CreateUserOp(transaction);
    string userOpStr = JsonConvert.SerializeObject(userOp, Formatting.Indented);
    Debug.Log($"UserOp created: {JsonConvert.SerializeObject(userOp, Formatting.Indented)}");
 
    userOp = SignUserOp(userOp, network);
    userOpStr = JsonConvert.SerializeObject(userOp, Formatting.Indented);
    Debug.Log($"UserOp Signed: {JsonConvert.SerializeObject(userOp, Formatting.Indented)}");
 
    JsonRpcResponse<ExecuteResult> txHash = await ExecuteUserOp(userOp);
    string txHashStr = JsonConvert.SerializeObject(txHash, Formatting.Indented);
    Debug.Log($"Transaction executed. Hash: {txHashStr}");
    return txHashStr;
}

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

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
var account = await GetAccount(oktoClient);Get user's wallet detailsMethod Overview
var chains = await GetChains(oktoClient);List supported blockchain networksMethod Overview
var tokens = await getTokens(oktoClient);List supported tokensMethod Overview
var portfolio = await GetPortfolio(oktoClient);Get user's token holdingsMethod Overview
var nfts = await GetPortfolioNFT(oktoClient);Get user's NFT holdingsMethod Overview
var activity = await GetPortfolioActivity(oktoClient);Get transaction historyMethod Overview
var orders = await GetOrdersHistory(oktoClient);Get transaction order historyMethod Overview
var 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

var transferParams = new TokenTransferIntentParams
{
    caip2Id = "eip155:137", // Target chain CAIP-2 ID
    recipientWalletAddress = "0xEE54970770DFC6cA138D12e0D9Ccc7D20b899089",
    tokenAddress = "",   // Token address ("" for native token)
    amount = 1000000000000000000  // Target chain CAIP-2 ID
};
string txHashStr = await ExecuteTokenTransfer(transferParams.recipientWalletAddress, transferParams.amount, caip2Id, transferParams.tokenAddress);

2. NFT Transfer

Transfer NFTs between addresses. Learn more

var transferParams = new NFTTransferIntentParams
{
   caip2Id = network,
   recipientWalletAddress = "0xEE54970770DFC6cA138D12e0D9Ccc7D20b899089",
   collectionAddress = "0x9501f6020b0cf374918ff3ea0f2817f8fbdd0762",
   nftId = "7",
   nftType = "ERC1155",
   amount = 1
};
 
string txHashStr = await ExecuteNFTTransaction(
transferParams.recipientWalletAddress,
transferParams.collectionAddress,
transferParams.nftId,
transferParams.amount,
transferParams.nftType,
network);

3. Raw Transaction (EVM)

Execute custom EVM contract calls. Learn more

var transferParams = new Transaction
{
  from = "0xc3AC3F050CCa482CF6F53070541A7B61A71C4abd",
  to = "0xEE54970770DFC6cA138D12e0D9Ccc7D20b899089",
  data = "",
  value = "1000000000000000000"
};
 
string txHashStr = await ExecuteEvmRawTransaction(
"eip155:137",
transferParams.to,
transferParams.value,
transferParams.data);

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