This TypeScript project demonstrates how to interact with the 0x Swap API for Solana to get a quote, build swap instructions, and send a swap transaction.
➜ 0x-solana-example git:(main) ✗ npm run index
> [email protected] index
> tsx src/index.ts
💰 Quote received
✅ Simulation succeeded
✍️ Transaction sent with signature: 3ofwWgzDzZRpPGNQTvAKSY4o3FMPT2y7fjCw6UtTAMTnvHj26TPaYVJWM88v28jNeey5CdX9sWGcVfPYfQNQsSBa
✅ Transaction confirmed: https://solscan.io/tx/3ofwWgzDzZRpPGNQTvAKSY4o3FMPT2y7fjCw6UtTAMTnvHj26TPaYVJWM88v28jNeey5CdX9sWGcVfPYfQNQsSBa
This script performs the following steps:
- Loads environment variables from
.env
(0x API key, private key, RPC URL). - Fetches a swap quote from the 0x
/swap-instructions
endpoint.
If you have provided a private key:
- Builds and signs a transaction from the instructions.
- Simulates the transaction to catch errors before sending.
- Sends a transaction to the Solana blockchain to execute the swap.
git clone https://github.com/0xProject/0x-solana-example.git
cd 0x-solana-example
npm install
Copy the example from .env.example into a new .env
file:
Variable Name | Description | Required | Default Value |
---|---|---|---|
ZEROEX_API_KEY |
API Key for use with 0x Solana API. | ✅ | None |
PRIVATE_KEY |
Must be base58-encoded. | ❌ | Random generated |
RPC_URL |
Valid Solana RPC HTTP endpoint. For example, get a free RPC key and endpoint from Helius. | ❌ | https://api.mainnet-beta.solana.com |
npm run index
- The amount and token mint addresses are hardcoded for simplicity (SOL → USDC), but can be parameterized.