How to Build a Secure AI Agent on Solana

ForesightNews
SOL-1.02%

The encryption infrastructure is uniquely suited for programmable, autonomous transactions.

Author: Helius

The surge of AI agents on Solana has sparked intense speculation about autonomous agents engaging in financial transactions.

The current wave of AI tokens has a trading volume of over $1 billion in 24 hours, with a total market capitalization exceeding $9.5 billion. But beyond these speculative markets, the cryptocurrency field has quietly undergone a deeper transformation based on the increasing level of automation over the years.

Robots have already driven most encryption transactions, reaching 90% in certain encryption areas. These AI agents, which are not yet fully autonomous, are clearly pioneers and will become more universal and independent over time.

Their widespread existence highlights a crucial fact: encryption infrastructure uniquely suits programmable, autonomous transactions.

Security Challenge: How can AI agents securely access Solana wallets?

With the rise of AI agents in Solana and other fields, a major security challenge has emerged: how to allow autonomous systems to access wallets without compromising security?

To perform on-chain operations, the AI agent needs wallet access permission. However, the private key stored in the code will cause significant security vulnerabilities:

  • They are the main target of attackers
  • They are susceptible to code errors that can lead to the loss of funds
  • Developers rarely structure them in a way that can separate funds.
  • They may open the door to rogue AI behavior

In September 2024, a real risk case occurred at Banana Gun, a Telegram-based trading bot, where attackers exploited a vulnerability in its message oracle to steal 3 million dollars from user wallets.

A robot or agent with direct wallet access may make unexpected, irreversible transactions due to vulnerabilities, errors, or unchecked decision loops.

Balancing Security and Autonomy

Traditional solutions force developers to choose between security and true proxy autonomy. Traditional methods either expose private keys or require centralized hosting, both of which are unacceptable for production systems.

One solution is Turnkey, which is a highly flexible encryption key management infrastructure built specifically for security, scale, and automation. Turnkey allows AI agents to interact with wallets through restricted, policy-controlled APIs, rather than exposing private keys.

Here is how it works:

Scope API Key

AI agent receives limited API credentials associated with specific wallets and operations.

Fine-grained strategy

Developers can precisely define the operations that AI agents are allowed to perform - whether it’s signing transactions based on certain conditions, interacting with specific smart contracts, or enforcing rate limits.

User Control

End users or developers can retain full control of the wallet while entrusting specific operations to AI agents.

Why it works:

This method ensures that AI agents can interact with on-chain assets independently, without holding the original private keys, thus addressing security concerns while maintaining the trustless and permissionless nature of encryption technology.

In addition, Turnkey’s verifiable computing environment allows teams to deploy AI agents in an environment where anyone can verify the code being run. We’ll discuss this later.

Let’s walk through a practical example by configuring a simple bot with a wallet permission API key. From here, developers can take the next step: evolving the bot into a fully autonomous AI agent.

How to create a Solana AI agent

Let’s use Turnkey to build a secure trading bot. We will cover:

  • Set up a Solana wallet with strategy control
  • Create an API-only user for your bot
  • Define policies that limit the bot’s behavior
  • Use Jupiter Exchange to implement a simple trading function

Prerequisites

Before delving into the code, you must install Node.js and npm.

You also need a Turnkey account.

Create a Solana wallet in Turnkey

Login to your Turnkey dashboard, then:

  • Navigate to Wallets
  • Click Create New Wallet
  • Choose Solana and ED25519 as your wallet settings
  • Provide some SOL for this wallet to trade

Create an API user for your robot

Next:

  • Go to Users tab
  • Click Add User
  • Select API key under the access type
  • Give it a name (e.g. “Trading Bot Alpha”)

Write down the user ID and then click approve. You will need this key for your strategy configuration.

Limit your bot through strategies

First, navigate to the Policies tab and click on Add new policy. Then, configure the policy to restrict the actions the robot can take. Let’s define a policy to ensure the robot:

  • Only token transfer is allowed (other transaction types are not allowed)
  • Can only trade SOL and USDC
  • Unable to execute transactions exceeding 1 SOL
{  「policyName」: 「AI Trading Bot Policy」,  「effect」: 「EFFECT_ALLOW」,  「consensus」: 「approvers.any(user, user.id == 『<bot_user_id>』)」,  「condition」: 「solana.tx.instructions.count() == solana.tx.spl_transfers.count() && solana.tx.spl_transfers.all(transfer, transfer.token_mint == 『<usdc_mint>』 || transfer.token_mint == 『<sol_mint>』) && solana.tx.spl_transfers.all(transfer, transfer.amount < 1000000000)」}

Set up your project

Next, create your project and install the dependencies.

    mkdir ai-trading-bot    cd ai-trading-bot    npm init -y    npm install @solana/web3.js @turnkey/sdk-server @turnkey/solana @jup-ag/api

Create an .env file to store your credentials.

    TURNKEY_API_PRIVATE_KEY=「YOUR_API_PRIVATE_KEY_HERE」    TURNKEY_API_PUBLIC_KEY=「YOUR_API_PUBLIC_KEY_HERE」    TURNKEY_ORGANIZATION_ID=「YOUR_TURNKEY_ORGANIZATION_ID_HERE」

Create a simple robot

Now, let’s write code. Create an index.js file:

    import process from 'node:process';    import { Turnkey } from '@turnkey/sdk-server';    import { TurnkeySigner } from '@turnkey/solana';    import {      Connection,      clusterApiUrl,      PublicKey,      VersionedTransaction    } from '@solana/web3.js';    import { createJupiterApiClient } from '@jup-ag/api';        // Load environment variables    process.loadEnvFile('.env');        // Define token addresses    const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';    const SOL = 'So11111111111111111111111111111111111111112';    const BOT_ADDRESS = 'YOUR_TURNKEY_WALLET_ADDRESS_HERE';    const BOT_PUBLIC_KEY = new PublicKey(BOT_ADDRESS);        async function main() {      // Initialize Turnkey and Jupiter clients      const turnkey = new Turnkey({        apiBaseUrl: ",        apiPrivateKey: process.env.TURNKEY_API_PRIVATE_KEY,        apiPublicKey: process.env.TURNKEY_API_PUBLIC_KEY,        defaultOrganizationId: process.env.TURNKEY_ORGANIZATION_ID,      });          const signer = new TurnkeySigner({        organizationId: process.env.TURNKEY_ORGANIZATION_ID,        client: turnkey.apiClient(),      });          const connection = new Connection(clusterApiUrl('mainnet-beta'), 'confirmed');      const jupiterClient = createJupiterApiClient();

Create Policy-Controlled Credentials

Now, the interesting part is coming. We will create a policy-controlled credential instead of giving your AI agent full wallet access:

const agentUSDCPolicy = {  」policyName「: 」require consensus on Solana transactions containing more than 1000 USDC in SPL tokens「,  」effect「: 」EFFECT_ALLOW「,  」consensus「: 」approvers.count() >= 2「,  」condition「: 」solana.tx.spl_transfers.all(transfer, transfer.token_mint == 『EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v』) && solana.tx.spl_transfers.all(transfer, transfer.amount > 1000000000)「,  」notes「: 」「,}const agentSOLPolicy = {  」policyName「: 」require consensus on Solana transactions containing more than 1 SOL「,  」effect「: 」EFFECT_ALLOW「,  」consensus「: 」approvers.count() >= 2「,  」condition「: 」solana.tx.transfers.count == 1 && solana.tx.transfers[0].amount > 1000000000「,  」notes「: 」「,}const createUSDCPolicyResponse = await turnkey.apiClient().createPolicy(agentUSDCPolicy);const createSOLPolicyResponse = await turnkey.apiClient().createPolicy(agentSOLPolicy);

Realize the trading function of the robot

After setting the constraints, you can enable trading functionality:

async function executeTrade fromToken: string, toToken: string, amount: string {  // Get quote from Jupiter  const quoteResponse = await jupiterClient.quoteGet{    inputMint: fromToken,    outputMint: toToken,    amount: amount  };  // Create swap transaction  const swapResponse = await jupiterClient.swapPost{    swapRequest: {      userPublicKey: BOT_PUBLIC_KEY,      quoteResponse: quoteResponse,    },  };  // Sign and submit transaction  const transaction = VersionedTransaction.deserialize    Buffer.from(swapResponse.swapTransaction, 'base64');    const signedTx = await signer.signTransaction    (transaction,    BOT_PUBLIC_KEY  );  const txid = await connection.sendRawTransaction    (signedTx.serialize(),    { skipPreflight: true, maxRetries: 5 }  );  await connection.confirmTransaction(txid);  return txid;}main();

This is the content you need!

This is not yet a complete AI agent - but this simple policy control robot lays the foundation for you.

From here, you can enhance its autonomy, add decision logic, and develop it into a more complex agent.

You can also enhance security by requiring multi-signature confirmation for high-risk transactions or granting agent access to wallets controlled by end users.

Beyond Secure Wallet: How Verifiable Environment Unlocks Secure AI Agents

Ensuring that AI agents transact securely isn’t just about securing wallet access – it’s about verifying that the code the agent is running is exactly what it claims to be.

Imagine a world where AI agents trade securely and operate in a fully verifiable environment. In this environment, anyone can independently verify what code the agents are executing.

The verifiable computing infrastructure of Turnkey enables anyone to verify software running securely in isolation, solving one of the biggest challenges faced by trusted software today.

Turnkey uses a trusted execution environment (TEEs) at its core, particularly AWS Nitro isolation, to provide a tamper-resistant environment for sensitive operations. These isolations run as isolated virtual machines with no persistent storage, no external network access, and are unmodifiable after boot. This ensures that once the isolation is configured, its code and data will remain secure and immune to external interference—including interference from the infrastructure provider itself.

However, it’s not enough to perform it securely – it’s verifiability that matters. Turnkey achieves this through three key innovations:

(# 1. Remote Attestation

Each turnkey isolation generates an encryption proof that proves the exact code it is running. The attestation consists of a hash of the isolated operating system and application binaries, signed by AWS’s Nitro Security Module (NSM). Soon, anyone will be able to independently verify the attestation to confirm that the quarantine is running the intended software.

)# 2. QuorumOS (QOS)

A minimal open source operating system designed specifically for verifiability. QOS ensures that each isolation runs only approved auditable code and provides a QOS manifest - a machine-readable proof that links isolated execution to publicly verifiable software fingerprints.

(# 3. StageX and Reproducible Builds

To eliminate the risk of supply chain attacks, Turnkey enforces reproducible builds. Any binary running in isolation can be independently recompiled from human-readable source code to verify that it has not been altered. This ensures a one-to-one mapping between the code reviewed by developers and the software running in a secure environment.

By combining TEE, remote attestation, and reproducible builds, Turnkey makes it possible to run applications with absolute verifiability - whether it’s for wallet security, encryption signing, or AI agent execution. This architecture goes beyond the traditional cloud security model, where trust is assumed, and enters a new paradigm of security that is provable, transparent, and decentralized.

)# What this means for AI agents

Verifiable execution environment enhances security, broadens the design space for autonomous systems, financial applications, and any service that requires verifiable trust.

When users can independently verify software running in isolation, new possibilities arise - such as untrusted AI execution, developers and users can confidently avoid the ‘Oz Wizard’ proxy (i.e. human actors pretending to be real AI agents).

Beyond verifiable AI, teams can deploy everything from off-chain coprocessors to trusted oracles and AI inference engines. Everything has encryption proof, ensuring that it really performs as promised, and that it cannot be updated unilaterally. The following table lists some of the sensitive workloads that may benefit from migrating to a demonstrable environment:

Want to participate and run your critical applications in a verifiable manner?

The Turnkey team is working with the selected team to deploy AI agents and other applications in a fully verifiable execution environment - anyone can verify the exact code running in the background.

Additional Resources

  1. CoinGecko - AI Proxy Market Capitalization
  2. QZ - Robot executes 90% of stablecoin trades
  3. Turnkey’s new white paper
  4. Turnkey Official Website</sol_mint></usdc_mint></bot_user_id>
Disclaimer: The information on this page may come from third parties and does not represent the views or opinions of Gate. The content displayed on this page is for reference only and does not constitute any financial, investment, or legal advice. Gate does not guarantee the accuracy or completeness of the information and shall not be liable for any losses arising from the use of this information. Virtual asset investments carry high risks and are subject to significant price volatility. You may lose all of your invested principal. Please fully understand the relevant risks and make prudent decisions based on your own financial situation and risk tolerance. For details, please refer to Disclaimer.
Comment
0/400
No comments