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
> 0x-solana-example@1.0.0 index
> tsx src/index.ts
💰 Quote received: 0.16 USDC
✅ Simulation succeeded
✍️ Transaction sent with signature: 3ofwWgzDzZRpPGNQTvAKSY4o3FMPT2y7fjCw6UtTAMTnvHj26TPaYVJWM88v28jNeey5CdX9sWGcVfPYfQNQsSBa
✅ Transaction confirmed: https://solscan.io/tx/3ofwWgzDzZRpPGNQTvAKSY4o3FMPT2y7fjCw6UtTAMTnvHj26TPaYVJWM88v28jNeey5CdX9sWGcVfPYfQNQsSBaThis 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-instructionsendpoint.
If you have provided a private key:
- Builds and signs a transaction from the instructions.
- Simulates the transaction to catch errors before sending.
- If
DRY_RUN=false, sends the transaction to the Solana blockchain to execute the swap.
npm installCopy 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 |
DRY_RUN |
When true, fetches a quote and simulates but does not send the transaction. |
❌ | true |
npm run index- The amount and token mint addresses are hardcoded for simplicity, but can be parameterized.
amount_inis denominated in base units (e.g. 1 USDC = 1_000_000 units).