> For the complete documentation index, see [llms.txt](https://wiki.obsidian.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wiki.obsidian.finance/dex/api-docs-v2/quick-start.md). Agents can also search and read this documentation through its [MCP server](https://wiki.obsidian.finance/~gitbook/mcp).

# Swap API Quick Start

Build a swap on Cronos with Obsidian’s public API and an optional partner fee.

Build a direct swap on Cronos with Obsidian's public API. This example sells **1 native CRO** for a token selected from the public catalogue. It works with no additional fee or with an optional fee paid to your wallet.

No API key or custom contract deployment is needed for this flow. Use a Cronos mainnet wallet with enough CRO for the swap and gas. See [Build with Obsidian](https://wiki.obsidian.finance/dex/api-docs-v2) for other integration options.

### 1. Connect a wallet and select an output token

This browser example uses viem with an injected wallet. If your app already connects a wallet, reuse its wallet/public clients. The public client must use Cronos; the user must connect their signing wallet to chain ID `25`.

Replace `YOUR_OUTPUT_TOKEN_ADDRESS` with the selected token. Leave `partnerFee` undefined for a normal swap, or use the commented configuration with your own fee wallet to collect **0.6%**.

```js
import { createPublicClient, createWalletClient, custom, http } from "viem";
import { cronos } from "viem/chains";

const walletClient = createWalletClient({ chain: cronos, transport: custom(window.ethereum) });
const publicClient = createPublicClient({ chain: cronos, transport: http() });
const API = "https://api.obsidian.finance";
const NATIVE_CRO = "0x0000000000000000000000000000000000000000";
const WCRO = "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23";
const ROUTER = "0x1189331089b6ca8beA989C1F2fFd0EfAdCd33a69";
const outputTokenAddress = "YOUR_OUTPUT_TOKEN_ADDRESS";

const partnerFee = undefined;
// To collect 0.6%, replace the line above with your own wallet:
// const partnerFee = { recipient: "YOUR_FEE_WALLET_ADDRESS", basisPoints: 60 };
const usePartnerFee = partnerFee?.basisPoints > 0;

async function post(path, body) {
  const response = await fetch(API + path, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  });
  const data = await response.json();
  if (!response.ok) throw new Error(data.message || data.error || `Request failed: ${response.status}`);
  return data;
}

// Run this connection request from your Connect Wallet button.
const [walletAddress] = await walletClient.requestAddresses();
if (!walletAddress || await walletClient.getChainId() !== 25) {
  throw new Error("Connect your wallet to Cronos.");
}

const tokenResponse = await fetch(API + "/25/v1/whitelisted-tokens");
if (!tokenResponse.ok) throw new Error(`Token list failed: ${tokenResponse.status}`);
const { tokens } = await tokenResponse.json();
const outputToken = tokens.find(token =>
  token.chainId === 25 && token.address.toLowerCase() === outputTokenAddress.toLowerCase()
);
if (!outputToken || [NATIVE_CRO, WCRO].some(address =>
  address.toLowerCase() === outputToken.address.toLowerCase())) {
  throw new Error("Select a different output token from the Cronos token list.");
}
```

Use each token's actual `address`, `decimals`, `symbol` and `name` from `tokens[]`. Cache this list separately from quote refreshes.

### 2. Request a quote

```js
const quoteRequest = {
  chainId: 25,
  tradeType: 0,
  amount: {
    currency: { chainId: 25, address: NATIVE_CRO, decimals: 18, symbol: "CRO", name: "Cronos" },
    value: "1000000000000000000"
  },
  currency: {
    chainId: 25,
    address: outputToken.address,
    decimals: outputToken.decimals,
    symbol: outputToken.symbol,
    name: outputToken.name
  },
  poolTypes: [0, 1],
  venueScope: "all",
  maxHops: 4,
  maxSplits: 3,
  ...(usePartnerFee ? { partnerFee } : {})
};
let quote = await post("/25/v1/getquote", quoteRequest);
```

`tradeType: 0` is exact input. The amount is a raw integer string: `10^18` units is 1 CRO. `poolTypes: [0, 1]` permits V2 and V3, including mixed paths; `venueScope: "all"` includes all supported venues. `maxSplits: 3` permits up to three routes; the best result can still be one route.

Keep the **complete quote**. `quote.outputAmount.value` already includes the 0.4% Obsidian fee and, when requested, your extra fee. A 0.6% partner fee makes 1% total; the maximum partner fee is 1%, making 1.4% total. Both use gross output. Do not subtract either fee again.

Native CRO needs no ERC20 approval. Keep enough CRO for the input and gas. For an ERC20 version, approve the router for an ordinary swap or the settlement contract at `quote.execution.approvalSpender` for a positive partner fee. Confirm the approval and refresh the quote before preparation.

### 3. Prepare the swap

Request a fresh quote immediately before preparation; refresh after approvals, input/fee changes or expiry. Partner-fee quotes must remain within 30 seconds of their snapshot through preparation. Repeat the same `partnerFee` when used.

```js
const prepared = await post("/v1/getswap", {
  chainId: 25,
  userAddress: walletAddress,
  quote,
  ...(usePartnerFee ? { partnerFee } : {}),
  options: {
    recipient: walletAddress,
    slippageTolerance: { numerator: "5", denominator: "1000" },
    deadlineOrPreviousBlockhash: String(Math.floor(Date.now() / 1000) + 600)
  }
});
```

This allows 0.5% slippage and a ten-minute transaction deadline. Pass `quote` unchanged and use the actual signing wallet as `userAddress`. Resolve any balance, allowance or preparation errors before signing.

### 4. Review, sign and confirm

Display the expected output, fees and gas information before the user confirms. For a positive partner fee, the wallet calls the settlement contract listed in the [quick reference](https://wiki.obsidian.finance/dex/api-docs-v2#quick-reference). Sign **`prepared.transaction`** using its returned target, data and value; it handles the swap and fee payments in one transaction.

This example selects the correct target for either direct API mode. It preserves prepared gas-price fields when present; otherwise the wallet obtains gas pricing.

```js
const tx = usePartnerFee ? prepared.transaction : {
  chainId: prepared.chainId,
  from: walletAddress,
  to: prepared.routerAddress,
  data: prepared.calldata,
  value: prepared.value,
  gasLimit: prepared.estimatedGas
};
const expectedTarget = usePartnerFee ? quote.execution?.settlementAddress : ROUTER;
const [currentWallet] = await walletClient.getAddresses();
if (!tx || !expectedTarget || prepared.chainId !== 25 || Number(tx.chainId) !== 25
  || await walletClient.getChainId() !== 25
  || currentWallet?.toLowerCase() !== walletAddress.toLowerCase()
  || tx.from.toLowerCase() !== walletAddress.toLowerCase()
  || tx.to.toLowerCase() !== expectedTarget.toLowerCase()
  || prepared.recipient.toLowerCase() !== walletAddress.toLowerCase()
  || BigInt(tx.value) !== BigInt(quoteRequest.amount.value)) {
  throw new Error("Prepared transaction does not match this native CRO swap.");
}
if (usePartnerFee && (
  prepared.partnerFee?.recipient?.toLowerCase() !== partnerFee.recipient.toLowerCase()
  || prepared.partnerFee?.basisPoints !== partnerFee.basisPoints
)) throw new Error("Partner fee settings changed. Request a new quote.");
if (!Number.isSafeInteger(quote.quoteContext?.timestamp)
  || Date.now() / 1000 - quote.quoteContext.timestamp > 30) {
  throw new Error("Quote expired. Refresh the quote and preparation.");
}

const feeFields = tx.maxFeePerGas !== undefined
  ? { maxFeePerGas: BigInt(tx.maxFeePerGas), maxPriorityFeePerGas: BigInt(tx.maxPriorityFeePerGas) }
  : tx.gasPrice !== undefined ? { gasPrice: BigInt(tx.gasPrice) } : {};

// Run only from your Confirm button after the user reviews the swap.
const txHash = await walletClient.sendTransaction({
  account: walletAddress,
  chain: cronos,
  to: tx.to,
  data: tx.data,
  value: BigInt(tx.value),
  gas: BigInt(tx.gasLimit),
  ...feeFields
});
console.log("Submitted transaction:", txHash); // Show and save this hash immediately.
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash, confirmations: 2 });
if (receipt.status !== "success") throw new Error(`Swap reverted: ${txHash}`);
```

If submission or confirmation times out, check the saved hash before sending again. For an ERC20 adaptation, native `value` is zero rather than the input amount. Fees are paid in the output asset. See [Direct API partner fees](https://wiki.obsidian.finance/dex/api-docs-v2#direct-api-partner-fees) for fee details and supported token types.

### 5. Report from your backend, if enabled

Trade reporting requires a backend partner key. After the receipt succeeds, send `txHash` to your backend and use the [complete reporting example](https://wiki.obsidian.finance/dex/api-docs-v2#id-8.-report-confirmed-trades-from-your-backend). Inspect each result; an HTTP `200` can contain failed hashes. Reporting does not guarantee rewards or award the same trade twice.

Keep partner keys on your backend and honor `Retry-After` on `429`. See [API keys and rate limits](https://wiki.obsidian.finance/dex/api-docs-v2#id-2.-api-keys-and-rate-limits) for defaults. Open an Obsidian Discord support ticket if you need higher limits.

For your own fee-on-input or fee-on-output contract, use the [custom-contract guide](https://wiki.obsidian.finance/dex/api-docs-v2#id-9.-custom-contract-integrations).
