LogoLogo
  • Introduction to Unizen
    • Unizen Overview
      • Unizen Liquidity Distribution Mechanism (ULDM)
        • ULDM Performance
      • Unizen Interoperability Protocol (UIP)
        • LayerZero
        • DeBridge
        • Stargate
        • Celer
        • Axelar
        • Thorchain
    • Unizen Dashboard
      • General
      • Portfolio
      • History
    • Unizen Trade
      • Fees
    • Unizen Explore
      • Unizen Omni-Chain Data Pool
    • Unizen Earn
  • ZCX
    • Token Utility
    • Tokenomics
  • API - Introduction
    • Introduction
    • Before you get started
      • Understanding Price Impact and Price Slippage in Token Swaps
      • Token Allowance Management for Non-updatable Allowance Tokens
      • Tokens with taxes
      • Wrapping and Unwrapping Native Tokens
      • Quote expiration deadline
    • Security Best Practices for Integrating Unizen
      • Why disable CORS
      • How to integrate with a reverse proxy
    • Version 2 of our smart contracts
      • Migration to smart contract v2
  • API - GET STARTED
    • QuickStart guide
    • Swagger
    • Information endpoints
      • GET /trade/v1/info/chains
      • GET /trade/v1/info/sources
      • GET/v1/info/cross-providers
      • GET /trade/v1/info/token/search
      • GET /v1/info/token/popular
      • GET /trade/v1/info/token/{chainId}/{tokenAddress}
      • GET /trade/v1/info/tokenLogo/{chainId}/{tokenAddress}
      • GET /info/thorchain-inbound-address
      • GET /trade/v1/info/tx/{txHash}
      • GET /trade/v1/info/trade/{chainId}/{txHash}
      • GET /trade/v1/info/trades
    • Approval
      • GET /trade/v1/{chainId}/approval/spender
      • GET /trade/v1/{chainId}/approval/transaction
      • GET /trade/v1/{chainId}/approval/allowance
    • Single-Chain Swap
      • GET /trade/v1/{chainId}/quote/single
      • GET /trade/v1/{chainId}/swap/single
      • Send transaction in evm chains
      • Send transaction in Solana
    • Cross-Chain Swap
      • GET /trade/v1/{chainId}/quote/cross
      • GET /trade/v1/{chainId}/swap/cross
      • Send transaction
    • Gasless orders
      • POST /trade/v1/gasless/typed-data
      • POST /v1/gasless/estimate
      • POST /v1/gasless/create
      • POST /v1/gasless/cancel
      • GET /trade/v1/gasless/status/{orderId}
      • GET /v1/gasless/orderByAddress/{address}
    • UTXO Assets and Cosmos Swap
      • GET /trade/v1/{chainId}/quote/cross 1
      • GET /trade/v1/{chainId}/swap/cross
      • Sending transactions
    • Efficient Quote Retrieval with Batch Processing
      • GET /trade/v1/{chainId}/batch_quote/single
    • Error Messages
  • GASLESS TRADES
    • Obtaining gasless quotes
    • Gas estimation
    • Executing the trade
    • Following the orders
  • On-Chain Contracts - Get Started
    • Integration with Unizen Contracts for Token Swapping
    • Registering Errors on Smart Contract Calls
  • PERMIT2
    • What is Permit2?
    • Usage in our api
  • WIDGET - Get Started
    • Embed the Unizen Widget
    • Playground
  • Other
    • Smart Contracts
    • Security Audits
    • Roadmap
  • links
    • Unizen
    • Marketing Website
    • Medium
    • Twitter
    • Discord
    • Telegram
Powered by GitBook
On this page

Was this helpful?

  1. API - GET STARTED
  2. Single-Chain Swap

Send transaction in Solana

Here's how you can send a Solana transaction to execute the trade.

Steps to Send a Transaction on Solana

  1. Set up a Solana connection.

  2. Create transaction instructions.

  3. Fetch the latest blockhash.

  4. Create a TransactionMessage.

  5. Use Address Lookup Tables (ALTs) if available.

  6. Compile and create a VersionedTransaction.

  7. Sign and send the transaction.

  8. Return the transaction signature.


Code Example (Without Hooks)

import { 
  Connection, PublicKey, TransactionInstruction, TransactionMessage, 
  VersionedTransaction, AddressLookupTableAccount 
} from '@solana/web3.js';

// 1️⃣ Initialize Solana connection
const connection = new Connection('https://api.mainnet-beta.solana.com');

// 2️⃣ Function to create and send a transaction
async function sendSolanaTransaction(wallet, instructionsData, addressLookupTableAccounts) {
  if (!wallet?.publicKey) {
    throw new Error("Wallet is not connected");
  }

  // 3️⃣ Convert instruction data into TransactionInstructions
  const instructions = instructionsData.map((instruction) => new TransactionInstruction({
    keys: instruction.keys.map(key => ({
      pubkey: new PublicKey(key.pubkey),
      isSigner: key.isSigner,
      isWritable: key.isWritable
    })),
    programId: new PublicKey(instruction.programId),
    data: Buffer.from(instruction.data)
  }));

  // 4️⃣ Fetch the latest blockhash
  const { blockhash } = await connection.getLatestBlockhash('confirmed');

  // 5️⃣ Handle Address Lookup Tables (if available)
  const lookupTables = addressLookupTableAccounts?.map(alta => new AddressLookupTableAccount({
    key: new PublicKey(alta.key),
    state: {
      addresses: alta.state.addresses.map(addr => new PublicKey(addr)),
      authority: new PublicKey(alta.state.authority),
      deactivationSlot: BigInt(alta.state.deactivationSlot),
      lastExtendedSlot: alta.state.lastExtendedSlot,
      lastExtendedSlotStartIndex: alta.state.lastExtendedSlotStartIndex
    }
  }));

  // 6️⃣ Create a TransactionMessage
  const messageV0 = new TransactionMessage({
    payerKey: wallet.publicKey,
    recentBlockhash: blockhash,
    instructions: instructions
  });

  // 7️⃣ Compile to VersionedTransaction
  const messageV0Compiled = messageV0.compileToV0Message(lookupTables);
  const transaction = new VersionedTransaction(messageV0Compiled);

  // 8️⃣ Sign and send the transaction
  const signature = await wallet.signAndSendTransaction(transaction);
  
  console.log("Transaction Signature:", signature);
  return signature;
}

How to Use This Function

// Example wallet object (Replace with actual wallet provider)
const wallet = {
  publicKey: new PublicKey("YourWalletPublicKeyHere"),
  signAndSendTransaction: async (tx) => {
    console.log("Signing and sending transaction...");
    return "mock_signature"; // Replace with actual wallet signing logic
  }
};

// Example transaction instructions (Replace with real data)
const transactionInstructions = [
  {
    keys: [{ pubkey: "TargetAddressHere", isSigner: false, isWritable: true }],
    programId: "ProgramIdHere",
    data: "Base64EncodedDataHere"
  }
];

// Example Address Lookup Tables (Replace with real ALTs)
const addressLookupTableAccounts = [];

// Send transaction
sendSolanaTransaction(wallet, transactionInstructions, addressLookupTableAccounts)
  .then(sig => console.log("Transaction sent with signature:", sig))
  .catch(err => console.error("Transaction failed:", err));

Explanation

  • Creates a transaction from provided instructions.

  • Fetches the latest blockhash to ensure validity.

  • Uses Address Lookup Tables (ALTs) for optimized transactions.

  • Compiles the transaction into a VersionedTransaction.

  • Signs and sends the transaction using the connected wallet.

PreviousSend transaction in evm chainsNextCross-Chain Swap

Last updated 1 month ago

Was this helpful?