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. Please note that this template is for development and testing purposes only. Be sure to customize and secure it before using in production.
Unity SDK Plug N' Play
Setup unity with Okto SDK within 10 minutes with our plug n' play.
Prerequisites
Before you begin, ensure you've completed these steps in the Okto Developer Dashboard:
- 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
Need assistance? Use our troubleshooting form and we'll help you get started.
Before getting started, ensure you have the following:
- Google SignIn Package: Download Package
- Okto API Keys: You need your
clientPrivateKey
andclientSwa
. 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
webClientId
.
- Go to Google Cloud Console.
- Create a new project or select an existing one
- Create OAuth 2.0 credentials for your project.
- Save your Client ID.
- Add authorized redirect URIs if necessary
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. 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
Play Services Resolver helps manage dependencies and automatically resolve Google Play services libraries for Unity.
Repository: https://github.com/googlesamples/unity-jar-resolver
Newtonsoft.Json is a popular high-performance JSON framework for .NET, used for parsing and serializing JSON data.
Package: com.unity.nuget.newtonsoft-json
: 3.0.2
3. Configure Environment Variables
Set up your authentication credentials for Google and Okto services:
// Your Okto client credentials from the developer dashboard
clientPrivateKey="YOUR_CLIENT_PRIVATE_KEY"
clientSwa="YOUR_CLIENT_SWA"
// 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.
- 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:
_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:
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.
(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:
// 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:-
- Open the OktoDemo scene in the project
- Click the Play button in the Unity Editor
- Test the authentication flow with your Google credentials
- 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:
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
Command | Description | Documentation |
---|---|---|
var account = await GetAccount(oktoClient); | Get user's wallet details | Method Overview |
var chains = await GetChains(oktoClient); | List supported blockchain networks | Method Overview |
var tokens = await getTokens(oktoClient); | List supported tokens | Method Overview |
var portfolio = await GetPortfolio(oktoClient); | Get user's token holdings | Method Overview |
var nfts = await GetPortfolioNFT(oktoClient); | Get user's NFT holdings | Method Overview |
var activity = await GetPortfolioActivity(oktoClient); | Get transaction history | Method Overview |
var orders = await GetOrdersHistory(oktoClient); | Get transaction order history | Method Overview |
var collections = await GetNftCollections(oktoClient); | Get NFT collections | 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
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. 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]
.