Local Transaction API
The Local Transaction API provides maximum security and control. We build the transaction for you, but you sign and broadcast it using your own wallet and RPC endpoint.
Overview
Base URL: https://api.turnpike.dev
Flow:
Request a transaction from Turnpike
Receive base64-encoded unsigned transaction
Sign the transaction with your wallet
Broadcast to Solana using your RPC endpoint
Why Use Local Transactions?
Full Control: You sign and send transactions yourself
Custom RPC: Use your own Solana RPC infrastructure
Maximum Security: Private keys never leave your system
Transaction Transparency: Inspect transactions before signing
Institutional Grade: Meets compliance requirements
Endpoints
Build Buy Transaction
Build an unsigned transaction for buying tokens.
Endpoint: POST /transaction/buy
Request Body:
publicKey
string
Yes
Your Solana wallet public key
mint
string
Yes
Token mint address to purchase
amount
number
Yes
Amount of SOL to spend
slippage
number
No
Maximum slippage percentage (default: 10)
priorityFee
number
No
Priority fee in SOL (default: auto)
Example Request:
curl -X POST https://api.turnpike.dev/transaction/buy \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"publicKey": "7BgBvyjrZX8YTqjkKrfbSx9X8QP4NDaP1hj4VKMjqA5s",
"mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"amount": 0.01,
"slippage": 10,
"priorityFee": 0.0001
}'Success Response (200):
{
"transaction": "BASE64_ENCODED_TRANSACTION_DATA",
"lastValidBlockHeight": 123456789,
"estimatedTokensReceived": 1000000,
"estimatedPrice": 0.00001,
"expiresAt": 1697234627890
}Build Sell Transaction
Build an unsigned transaction for selling tokens.
Endpoint: POST /transaction/sell
Request Body:
publicKey
string
Yes
Your Solana wallet public key
mint
string
Yes
Token mint address to sell
amount
number
Yes
Amount of tokens to sell
slippage
number
No
Maximum slippage percentage
priorityFee
number
No
Priority fee in SOL
Example Request:
curl -X POST https://api.turnpike.dev/transaction/sell \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"publicKey": "7BgBvyjrZX8YTqjkKrfbSx9X8QP4NDaP1hj4VKMjqA5s",
"mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"amount": 1000000,
"slippage": 10
}'Success Response (200):
{
"transaction": "BASE64_ENCODED_TRANSACTION_DATA",
"lastValidBlockHeight": 123456789,
"estimatedSolReceived": 0.01,
"estimatedPrice": 0.00001,
"expiresAt": 1697234627890
}Signing and Sending
After receiving the unsigned transaction, you need to sign and broadcast it.
JavaScript/TypeScript Example
import { Connection, Transaction, Keypair } from '@solana/web3.js';
async function signAndSendTransaction(
base64Transaction: string,
wallet: Keypair,
rpcEndpoint: string
) {
// Create connection to your RPC
const connection = new Connection(rpcEndpoint);
// Deserialize the transaction
const transaction = Transaction.from(
Buffer.from(base64Transaction, 'base64')
);
// Sign the transaction with your wallet
transaction.sign(wallet);
// Send the transaction
const signature = await connection.sendRawTransaction(
transaction.serialize()
);
console.log('Transaction sent:', signature);
// Wait for confirmation
const confirmation = await connection.confirmTransaction(signature);
return {
signature,
confirmation
};
}
// Usage
async function executeBuyTrade() {
// 1. Get unsigned transaction from Turnpike
const response = await fetch('https://api.turnpike.dev/transaction/buy', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.TURNPIKE_API_KEY}`
},
body: JSON.stringify({
publicKey: wallet.publicKey.toBase58(),
mint: 'TOKEN_MINT_ADDRESS',
amount: 0.01,
slippage: 10
})
});
const data = await response.json();
// 2. Sign and send
const result = await signAndSendTransaction(
data.transaction,
wallet,
'https://api.mainnet-beta.solana.com'
);
console.log('Trade completed:', result);
}Using with Wallet Adapter (Browser)
import { useWallet, useConnection } from '@solana/wallet-adapter-react';
import { Transaction } from '@solana/web3.js';
function TradingComponent() {
const { publicKey, signTransaction, sendTransaction } = useWallet();
const { connection } = useConnection();
const executeTrade = async () => {
if (!publicKey || !signTransaction) {
throw new Error('Wallet not connected');
}
// 1. Get unsigned transaction
const response = await fetch('https://api.turnpike.dev/transaction/buy', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.TURNPIKE_API_KEY}`
},
body: JSON.stringify({
publicKey: publicKey.toBase58(),
mint: 'TOKEN_MINT_ADDRESS',
amount: 0.01,
slippage: 10
})
});
const data = await response.json();
// 2. Deserialize transaction
const transaction = Transaction.from(
Buffer.from(data.transaction, 'base64')
);
// 3. Sign with wallet adapter
const signedTransaction = await signTransaction(transaction);
// 4. Send transaction
const signature = await connection.sendRawTransaction(
signedTransaction.serialize()
);
// 5. Confirm
await connection.confirmTransaction(signature);
console.log('Transaction confirmed:', signature);
return signature;
};
return (
<button onClick={executeTrade}>
Execute Trade
</button>
);
}Python Example
from solana.rpc.api import Client
from solana.transaction import Transaction
from solders.keypair import Keypair
import base64
import requests
def sign_and_send_transaction(
base64_transaction: str,
wallet: Keypair,
rpc_url: str
) -> str:
# Create RPC client
client = Client(rpc_url)
# Deserialize transaction
transaction_bytes = base64.b64decode(base64_transaction)
transaction = Transaction.deserialize(transaction_bytes)
# Sign transaction
transaction.sign(wallet)
# Send transaction
result = client.send_raw_transaction(transaction.serialize())
signature = result['result']
print(f'Transaction sent: {signature}')
# Wait for confirmation
client.confirm_transaction(signature)
return signature
# Usage
def execute_buy_trade(wallet: Keypair):
# 1. Get unsigned transaction
response = requests.post(
'https://api.turnpike.dev/transaction/buy',
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {os.getenv("TURNPIKE_API_KEY")}'
},
json={
'publicKey': str(wallet.pubkey()),
'mint': 'TOKEN_MINT_ADDRESS',
'amount': 0.01,
'slippage': 10
}
)
data = response.json()
# 2. Sign and send
signature = sign_and_send_transaction(
data['transaction'],
wallet,
'https://api.mainnet-beta.solana.com'
)
print(f'Trade completed: {signature}')
return signatureRust Example
use solana_client::rpc_client::RpcClient;
use solana_sdk::{
signature::{Keypair, Signer},
transaction::Transaction,
};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
async fn sign_and_send_transaction(
base64_transaction: &str,
wallet: &Keypair,
rpc_url: &str,
) -> Result<String, Box<dyn std::error::Error>> {
// Create RPC client
let client = RpcClient::new(rpc_url.to_string());
// Deserialize transaction
let transaction_bytes = BASE64.decode(base64_transaction)?;
let mut transaction: Transaction = bincode::deserialize(&transaction_bytes)?;
// Sign transaction
transaction.sign(&[wallet], client.get_latest_blockhash()?);
// Send transaction
let signature = client.send_and_confirm_transaction(&transaction)?;
println!("Transaction sent: {}", signature);
Ok(signature.to_string())
}Transaction Expiration
Transactions have a limited validity period:
lastValidBlockHeight: Block height after which transaction is invalid
expiresAt: Unix timestamp when transaction expires (typically 60 seconds)
Always send transactions promptly after building them.
Best Practices
Verify Transaction Contents: Inspect the transaction before signing
Use Trusted RPC: Use your own RPC or a trusted provider
Handle Expiration: Build and send transactions quickly
Confirm Transactions: Always wait for confirmation
Store Private Keys Securely: Never expose private keys
Test Thoroughly: Test with small amounts first
Security Considerations
Inspect Before Signing
import { Transaction } from '@solana/web3.js';
function inspectTransaction(base64Tx: string) {
const tx = Transaction.from(Buffer.from(base64Tx, 'base64'));
console.log('Transaction details:');
console.log('- Instructions:', tx.instructions.length);
console.log('- Fee payer:', tx.feePayer?.toBase58());
console.log('- Recent blockhash:', tx.recentBlockhash);
// Inspect each instruction
tx.instructions.forEach((ix, i) => {
console.log(`Instruction ${i}:`, {
programId: ix.programId.toBase58(),
keys: ix.keys.length,
data: ix.data.length
});
});
}Simulate Before Sending
async function simulateTransaction(transaction: Transaction, connection: Connection) {
const simulation = await connection.simulateTransaction(transaction);
if (simulation.value.err) {
console.error('Simulation failed:', simulation.value.err);
throw new Error('Transaction would fail');
}
console.log('Simulation succeeded');
console.log('Logs:', simulation.value.logs);
return simulation;
}Error Handling
Same error codes as Lightning API apply. See Error Handling.
Next Steps
View WebSocket API for real-time data
Check Examples for complete integration code
Learn about Error Handling
Last updated