HomeBlogTech UpdatesHow to Send Native Crypto Tokens Across Multiple Blockchains Using FastAPI API
Tech UpdatesDecember 8, 20254 min

How to Send Native Crypto Tokens Across Multiple Blockchains Using FastAPI API

How to Send Native Cryptocurrencies Across Multiple Blockchains Using a FastAPI API Sending native cryptocurrencies like SOL, ETH, BNB, or BASE programmatically can present certain challenges, especially when it...

How to Send Native Crypto Tokens Across Multiple Blockchains Using FastAPI API

How to Send Native Cryptocurrencies Across Multiple Blockchains Using a FastAPI API

Sending native cryptocurrencies like SOL, ETH, BNB, or BASE programmatically can present certain challenges, especially when it comes to transaction signing, interacting with RPC networks, and handling errors. In this context, the Crypto API service offers a straightforward solution through its FastAPI endpoints. In this article, we'll delve into the process of sending native tokens using the /send/native endpoint, discuss necessary prerequisites, and provide a Python code example.

Prerequisites

Before getting started with sending tokens, ensure you have the following:

  1. Python version 3.11 or higher.
  2. Dependencies installed. Run the command:
    pip install httpx asyncio
    
  3. A RapidAPI key. Sign up for the Crypto API service to obtain a key.
  4. A private key for the sender's wallet. In this example, a test wallet is used; never expose mai

et keys. 5. The recipient's wallet address.

Understanding the /send/native Endpoint

The /send/native endpoint allows you to send native blockchain tokens. To use it successfully, you need to provide several required parameters:

  • token: The token symbol (e.g., SOL, ETH, BNB, BASE).
  • destination_wallet: The recipient's address.
  • amount: The amount to send.
  • rpc_url: (Optional) RPC URL for a custom co

ection.

  • private_key: (Optional) Private key for transaction signing.

The expected response upon successful sending will be in the following format:

{
  "status": "success",
  "tx_hash": "5NfL1yS5kJjKx9rR4v8Q7P1M2Zq3vT6Y",
  "message": "SOL sent successfully"
}

Python Script Example

Now, let's create a Python script to send a native token. Create a file named send_native.py and add the following code:

# send_native.py
import asyncio
import httpx
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

API_URL = "https://api.aigoretech.cloud/api/v1/crypto/send/native"
API_KEY = "YOUR_RAPIDAPI_KEY"  # Replace with your RapidAPI key

async def send_native_token(token: str, destination_wallet: str, amount: float, rpc_url: str = None, private_key: str = None):
    """Function to send a native token via the Crypto API"""
    async with httpx.AsyncClient() as client:
        try:
            if amount <= 0:
                raise ValueError("Amount must be greater than 0")
            logger.info(f"🚀 Sending {amount} {token.upper()} to {destination_wallet}")
            
            resp = await client.post(
                API_URL,
                params={
                    "token": token,
                    "destination_wallet": destination_wallet,
                    "amount": amount,
                    "rpc_url": rpc_url,
                    "private_key": private_key
                },
                headers={"X-RapidAPI-Key": API_KEY}
            )
            
            resp.raise_for_status()
            data = resp.json()
            
            if data.get("status") != "success":
                raise Exception(data.get("message", "Sending failed"))
            
            logger.info(f"✅ Transaction successful! Hash: {data['tx_hash']}")
            print(data["message"])
        
        except Exception as e:
            logger.error(f"Error: {str(e)}")

# Run the function asynchronously
if __name__ == "__main__":
    asyncio.run(send_native_token("SOL", "YourRecipientAddress", 1.0))  # Replace the recipient address and amount

Code Breakdown

  1. Import libraries: First, we import the necessary libraries: httpx for making HTTP requests and logging for event logging.

  2. Configure logging: We set up logging to display information about the token sending process.

  3. Declare the token sending function: The core logic resides within the send_native_token function, which takes the token, recipient address, amount, and optional parameters as input.

  4. Send HTTP requests: Using httpx.AsyncClient, we send a POST request to the specified API, passing the required parameters.

  5. Handle responses: We check the status of the response and output messages based on the result.

  6. Asynchronous execution: At the end of the file, we run our function in an asynchronous context, which allows for efficient handling of requests even under high load.

Best Practices

  1. Key security: Never expose your private keys in plain sight. Use environment variables or dedicated secret managers to store keys.

  2. Logging: Always add logging to your code to simplify debugging and monitoring.

  3. Error handling: Make sure you properly handle potential errors to avoid leaving the user without information about what's happening.

  4. Testing: Before sending tokens to the mai

et, conduct testing on testnets. This will help avoid losses and misunderstandings.

  1. API documentation: Always refer to the API documentation for the most up-to-date information on parameters and possible responses. This will help avoid errors in your code.

Now that you are familiar with the basics of using the Crypto API to send native tokens, you can easily integrate this functionality into your projects and improve your work with cryptocurrencies.