> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sunrise.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Swap with the API

> Use the Sunrise API to quote, sign, and execute a swap on Solana.

<Info>
  This recipe swaps 0.01 SOL for USDC.
</Info>

The TypeScript examples assume you already have a connected Wallet Standard Solana wallet (`wallet`) and its account (`account`). Your wallet needs SOL for the swap and network fees. Install `@solana/kit` for the transaction encoding helpers used below.

## Step 1: Request an API key

Contact [contact@sunrise.xyz](mailto:contact@sunrise.xyz?subject=Sunrise%20API%20key%20request) to request a Sunrise API key for your app. Save it in your project's `.env` file:

```dotenv theme={null}
SUNRISE_API_KEY=your-api-key
```

Load the key using your project's environment configuration. Keep it private; for browser calls, use your app's existing authenticated request layer.

## Step 2: Choose your tokens

Call `GET /v1/tokens` to find token mint addresses and decimals. Requests use a Bearer token for authentication.

```typescript theme={null}
const headers = {
  Authorization: `Bearer ${process.env.SUNRISE_API_KEY}`,
  "Content-Type": "application/json",
};

const tokensResponse = await fetch("https://api.sunrise.xyz/v1/tokens", {
  headers,
});

const tokensResult = await tokensResponse.json();

if (!tokensResponse.ok || !tokensResult.success) {
  throw new Error(tokensResult.error?.message ?? "Could not load tokens");
}

console.log(tokensResult.data.tokens);
```

Use a token's `address` as its mint address. Native SOL uses `"native"`. For this recipe, use SOL as the input and the Solana USDC mint as the output.

## Step 3: Get a quote

Call `POST /v1/quotes` with your token pair, amount, and wallet addresses. Include both addresses to receive an unsigned transaction you can sign.

Amounts are strings in base units. SOL has 9 decimals, so `"10000000"` means 0.01 SOL.

```typescript theme={null}
const quoteResponse = await fetch("https://api.sunrise.xyz/v1/quotes", {
  method: "POST",
  headers,
  body: JSON.stringify({
    fromToken: "native",
    toToken: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    fromAmount: "10000000",
    fromAddress: account.address,
    toAddress: account.address,
  }),
});

const quoteResult = await quoteResponse.json();

if (!quoteResponse.ok || !quoteResult.success) {
  throw new Error(quoteResult.error?.message ?? "Could not get a quote");
}

const quote = quoteResult.data.quotes[0];

if (!quote?.unsignedTransaction) {
  throw new Error("No executable quote. Try another pair or amount");
}

// USDC has 6 decimals. Show this estimate before asking your user to sign.
console.log("Estimated USDC:", Number(quote.toAmount) / 10 ** 6);
console.log("Route:", quote.routeName);
```

This example selects the first quote. Let your user review the available quotes and choose one before continuing. If the quote expires before signing, request a new one.

## Step 4: Sign and execute the swap

Ask your wallet to sign the quote's transaction. Then call `POST /v1/execute` with the signed transaction and the same quote identifiers.

```typescript theme={null}
import { getBase64Encoder, getBase64Decoder } from "@solana/kit";

const [signed] = await wallet.features["solana:signTransaction"].signTransaction({
  account,
  chain: "solana:mainnet",
  transaction: new Uint8Array(getBase64Encoder().encode(quote.unsignedTransaction)),
});

if (!signed) throw new Error("Your wallet did not return a signed transaction");

const execution = {
  quoteId: quote.quoteId,
  routeName: quote.routeName,
  providerRequestId: quote.providerRequestId,
  signedTransaction: getBase64Decoder().decode(signed.signedTransaction),
};

let result;

do {
  const response = await fetch("https://api.sunrise.xyz/v1/execute", {
    method: "POST",
    headers,
    body: JSON.stringify(execution),
  });

  const payload = await response.json();

  if (!response.ok || !payload.success) {
    throw new Error(payload.error?.message ?? "Could not execute the swap");
  }

  result = payload.data;
  console.log(result.status, result.txHash);

  if (result.status !== "CONFIRMED") {
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
} while (result.status !== "CONFIRMED");
```

A `SUBMITTED` status means the transaction is still pending. Repeat the same execution request until it returns `CONFIRMED`. Once confirmed, your wallet holds the USDC received from the swap.

This submits a real transaction on Solana mainnet. If a request fails after submission, check `txHash` in a Solana explorer before starting another swap.

For the full request and response schemas, see the [API specification](https://api.sunrise.xyz/openapi).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.