# Swaps (https://dev.cosmospay.lat/docs/api/swaps/)

> Quote, create, sign and submit same-chain swaps: Stellar path payments by default, Solana's and Monad's own markets with `chain`.

Base URL: `https://api.cosmospay.lat/cosmos-api`

## Quote a swap on one chain; persists nothing

`POST /v1/swaps/quote`

Prices `amount` of the source asset on the chain's own venue: the Stellar DEX (a Horizon strict-send path search on the key's network) when `chain` is omitted or `stellar`, the Solana swap route for `solana` and the Monad swap route for `monad`, both mainnet only. The answer carries the plan commission (`fee`: taken from the source amount on Stellar, from the output on Solana and Monad), any `merchantFee`, the estimated output and the minimum after slippage. `slippageBps` defaults to 50 and a value above the cap (500) is `slippage_exceeded`, unless the deployment configures other values.

Requires the `swaps:read` scope. The shared public key may call it.

**Request body** (`application/json`, required): `QuoteSwapDto`

- `chain` (string, optional): The chain to swap on. Omitted means Stellar. solana → the Solana swap route, monad → the Monad swap route; both mainnet only. Swaps between chains are /v1/cross-chain-swaps. One of: `stellar`, `solana`, `monad`.
- `sourceAssetCode` (string, optional): The asset being sold. Stellar: an asset code (native if omitted). Solana / Monad: SOL / MON, "native", or the mint / ERC-20 address.
- `sourceAssetIssuer` (string, optional): Stellar only: issuer account for a non-native source asset.
- `amount` (string, required): Gross amount of the source asset to swap, in its own units (decimal; at most 7 places on Stellar, the token decimals elsewhere). Stellar deducts the platform fee from it; Solana and Monad take it from the output.
- `destAssetCode` (string, required): The asset being bought, spelled as for sourceAssetCode.
- `destAssetIssuer` (string, optional): Stellar only: issuer account for the destination asset (required unless it is native).
- `slippageBps` (number, optional): Slippage tolerance in basis points (50 = 0.5%) used to derive the on-chain minimum received. Defaults to the service setting; capped by it.
- `merchantFee` (MerchantFeeDto, optional): Your own fee on this swap, paid in the source asset to `wallet` out of the source wallet, in the same transaction, beside the plan commission. Stellar: its own payment (the wallet must trust the asset). Solana: a transfer appended to the Solana swap route's transaction (a SOL fee goes to an existing account). `paidBy: recipient` takes it from `amount` (the swap routes less); `payer` adds it on top (the source sends `amount` plus the fee). Monad: through the deployment’s merchant fee router, which the wallet sends or approves the input plus the fee; without one configured, `merchant_fee_unsupported`.

**Responses**

- `200` (`SwapQuoteEntity`): OK
  - `network` (string, required): The network the quote was priced on: `public` or `testnet` on Stellar, following the API key; always `public` on Solana and Monad.
  - `chain` (string, optional): Solana and Monad quotes only. Absent on Stellar, which answers as it always has. One of: `solana`, `monad`.
  - `provider` (string, optional): The aggregator that priced a Solana or Monad swap. One of: `jupiter`, `kuru`.
  - `source` (SwapAssetAmount, required): Gross source input.
  - `fee` (SwapFeeBreakdown, required): The plan commission: in the source asset on Stellar, in the bought asset on Solana and Monad.
  - `swap` (SwapAssetAmount, required): The amount routed, in the source asset. Stellar: `source.amount` less the plan commission (`fee.amount`) and less a merchant fee with `paidBy: recipient`. Solana and Monad: `source.amount` less a merchant fee with `paidBy: recipient`; the commission comes out of the output.
  - `merchantFee` (MerchantFeeEntity, optional): The merchant fee the request named, in the source asset; null without one. With `paidBy: payer` the source sends `source.amount` plus it.
  - `destination` (SwapDestinationQuote, required): The bought asset, with the estimated output and the on-chain minimum.
  - `path` (SwapPathHop[], required): Intermediate hops (may be empty).
- `400` (`ApiErrorBodyEntity`): `network_unsupported`: `chain: solana | monad` with a dev (testnet) key: the Solana swap route and the Monad swap route run on mainnet only. `asset_unsupported`: not an SPL mint / ERC-20 on that chain. `provider_error`: the aggregator found no route or refused the amount. `merchant_fee_unsupported`: a `merchantFee` on a Monad swap where no merchant fee router is configured on this deployment.
  - `statusCode` (number, required): Always the HTTP status of the response itself.
  - `code` (string, required): Stable machine-readable code. Branch on this, never on the message: messages are human-facing and may be reworded; codes are never renamed once published. Each response documents the subset it can return. One of: `insufficient_scope`, `no_authenticated_consumer`, `gateway_required`, `admin_console_only`, `not_found`, `validation_failed`, `payload_too_large`, `idempotency_conflict`, `operation_in_flight`, `invalid_state_transition`, `slippage_exceeded`, `insufficient_balance`, `no_path_found`, `trustline_missing`, `invalid_amount`, `invalid_memo`, `transaction_rejected`, `transaction_already_settled`, `recipient_not_registered`, `payment_transfer_mismatch`, `fee_transfer_mismatch`, `merchant_fee_transfer_mismatch`, `payer_mismatch`, `transaction_not_found`, `expired`, `network_unsupported`, `asset_unsupported`, `merchant_fee_unsupported`, `provider_error`, `provider_unavailable`, `quote_not_found`, `quote_expired`, `kyc_state_invalid`, `kyc_review_required`, `account_disabled`, `payload_expired`, `rate_limited`, `customer_wallet_taken`, `alias_taken`, `alias_name_invalid`, `alias_challenge_invalid`, `alias_signature_invalid`, `alias_recovery_invalid`, `alias_address_conflict`, `wallet_handshake_invalid`, `wallet_verifier_invalid`, `wallet_login_code_invalid`, `wallet_login_code_cooldown`, `wallet_session_invalid`, `wallet_signature_invalid`, `wallet_backup_invalid`, `wallet_backup_limit`, `wallet_account_mismatch`, `wallet_provider_unavailable`, `wallet_return_url_not_allowed`, `wallet_recovery_setup_refused`, `easy_recovery_not_found`, `easy_recovery_already_offered`, `easy_recovery_not_offered`, `easy_recovery_code_invalid`, `easy_recovery_burned`, `plugin_not_installed`, `plugin_consent_mismatch`, `plugin_rejected`, `plugin_quota_exceeded`, `plugin_failed`, `protected_payment_buyer_mismatch`, `protected_payment_signature_invalid`, `misconfigured`, `internal_error`.
  - `error` (string, required): The HTTP reason phrase for `statusCode`.
  - `message` (string | string[], required): Human-readable detail. An array when class-validator rejected the body.
  - `details` (object, optional): Machine-readable facts about this failure, present only on the codes whose example shows it: `easy_recovery_code_invalid` carries `{ "attemptsLeft": 4 }`. Absent everywhere else.
  - `path` (string, required): The path of the request that failed.
  - `timestamp` (string, required): When the envelope was produced, ISO 8601.
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `502`: UpstreamError (see Shared responses)
- `503` (`ApiErrorBodyEntity`): `misconfigured`: the plan charges a commission and the chain has no fee wallet configured (STELLAR_SWAP_FEE_WALLET, SOLANA_SWAP_FEE_WALLET, MONAD_SWAP_FEE_WALLET), or the deployment’s merchant fee router is not the expected contract.
- `504`: UpstreamTimeout (see Shared responses)

## List the consumer's swaps on one chain

`GET /v1/swaps`

Stellar swaps when `chain` is omitted, otherwise those of the chain named, newest first and optionally filtered by `status`. Paginated with `take` (default 20, max 100) and `skip`; the answer is `{ data, total, take, skip }`. Only swaps on the key's network are listed (a `prod` key sees mainnet, a `dev` key testnet), and Solana and Monad swaps are mainnet only, so a `dev` key lists none of them.

Requires the `swaps:read` scope.

**Query parameters**

- `chain` (string, optional): Which chain to list. Omitted means Stellar. One of: `stellar`, `solana`, `monad`.
- `status` (string, optional): Only swaps in this status. One of: `PENDING`, `SUBMITTED`, `SUCCEEDED`, `FAILED`, `EXPIRED`.
- `take` (number, optional): How many swaps to return per page (1 to 100).
- `skip` (number, optional): How many swaps to skip before this page, for pagination.

**Responses**

- `200` (`SwapListEntity | ChainSwapListEntity`): Stellar swaps (no `chain`), or those of the chain named.
- `400`: ValidationFailed (see Shared responses)
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `500`: InternalError (see Shared responses)

## Create a swap: the unsigned transaction to sign

`POST /v1/swaps`

Prices the swap as the quote does, builds the transaction `source` signs, stores it as `PENDING` and emits `SWAP_CREATED`. Stellar: the XDR with a SEP-7 `uri` and QR, valid for the network timeout (300 s by default); when the swap pays `source` itself (no `destination`, or the same account) and it does not trust the bought asset yet, the transaction adds that trustline first. Solana and Monad (mainnet only): the aggregator’s transaction, valid for one minute on Solana and two on Monad, where an ERC-20 sale may also carry an `approval` to send first. Send the signed transaction to `POST /v1/swaps/{id}/submit`; an `Idempotency-Key` (header or body) makes a retry return the same swap.

Requires the `swaps:write` scope. The shared public key may call it.

**Headers**

- `Idempotency-Key` (string, optional): Optional idempotency key. A retry with the same key and the same request returns the existing swap (same id and txHash); the same key with a different request is 409 idempotency_conflict. Takes precedence over body.idempotencyKey.

**Request body** (`application/json`, required): `CreateSwapDto`

- `chain` (string, optional): The chain to swap on. Omitted means Stellar. solana → the Solana swap route, monad → the Monad swap route; both mainnet only. Swaps between chains are /v1/cross-chain-swaps. One of: `stellar`, `solana`, `monad`.
- `sourceAssetCode` (string, optional): The asset being sold. Stellar: an asset code (native if omitted). Solana / Monad: SOL / MON, "native", or the mint / ERC-20 address.
- `sourceAssetIssuer` (string, optional): Stellar only: issuer account for a non-native source asset.
- `amount` (string, required): Gross amount of the source asset to swap, in its own units (decimal; at most 7 places on Stellar, the token decimals elsewhere). Stellar deducts the platform fee from it; Solana and Monad take it from the output.
- `destAssetCode` (string, required): The asset being bought, spelled as for sourceAssetCode.
- `destAssetIssuer` (string, optional): Stellar only: issuer account for the destination asset (required unless it is native).
- `slippageBps` (number, optional): Slippage tolerance in basis points (50 = 0.5%) used to derive the on-chain minimum received. Defaults to the service setting; capped by it.
- `merchantFee` (MerchantFeeDto, optional): Your own fee on this swap, paid in the source asset to `wallet` out of the source wallet, in the same transaction, beside the plan commission. Stellar: its own payment (the wallet must trust the asset). Solana: a transfer appended to the Solana swap route's transaction (a SOL fee goes to an existing account). `paidBy: recipient` takes it from `amount` (the swap routes less); `payer` adds it on top (the source sends `amount` plus the fee). Monad: through the deployment’s merchant fee router, which the wallet sends or approves the input plus the fee; without one configured, `merchant_fee_unsupported`.
- `source` (string, required): Account paying for (and signing) the swap (the tx source) on `chain`.
- `destination` (string, optional): Account credited the destination asset. Defaults to `source` (a self-swap). On Stellar, when it is `source` and does not trust a non-native destination asset yet, the transaction adds that trustline first (see `trustline` on the response); any other account must already trust the asset, because only it can add the trustline. Stellar only: on Solana and Monad the output always goes to `source`.
- `memo` (string, optional): Stellar only: optional MEMO_ID (numeric uint64) echoed on-chain for reconciliation.
- `idempotencyKey` (string, optional): Optional idempotency key. Prefer the `Idempotency-Key` request header; when both are set, the header wins. A retry with the same key and the same request returns the existing swap instead of building another transaction; the same key with a different request is 409 `idempotency_conflict`.

**Responses**

- `201` (`SwapCreatedEntity | ChainSwapCreatedEntity`): A Stellar swap (no `chain`, or `stellar`), or a Solana / Monad swap. With the shared public key it carries `publicToken`: send it as `X-Record-Token` to read the swap or submit it.
- `400` (`ApiErrorBodyEntity`): Stellar: `trustline_missing` (the destination is another account that does not trust the bought asset, and only it can add the trustline; a source that receives the swap gets the trustline in the same transaction instead), `insufficient_balance` (the source cannot keep the 0.5 XLM reserve that trustline locks, after what the transaction sends and its fee), `no_path_found`. Solana / Monad: `network_unsupported` (a dev key), `asset_unsupported`, `provider_error` (no route, or the aggregator simulated a failure, usually a wallet that cannot cover the amount plus fees). Monad: `merchant_fee_unsupported` (a `merchantFee` and no merchant fee router configured on this deployment).
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `409` (`ApiErrorBodyEntity`): `idempotency_conflict`: this Idempotency-Key was already used for a different request, or an identical swap was already built without a key (retry with an Idempotency-Key, or wait for the prior swap to settle or expire). `operation_in_flight`: STELLAR_SWAP_SINGLE_INFLIGHT is on and this source account already has a PENDING swap.
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `502`: UpstreamError (see Shared responses)
- `503` (`ApiErrorBodyEntity`): `misconfigured`: the plan charges a commission and the chain has no fee wallet (or, on Solana, the fee wallet has no token account for the output mint yet), or, for a Monad swap with a merchant fee, the deployment’s merchant fee router is not the expected contract, or the Monad swap route moved to another router than the one it was built for.
- `504`: UpstreamTimeout (see Shared responses)

## Get a swap by id, on any chain

`GET /v1/swaps/{id}`

The shared public key may call it, so a swap made without an account can follow its own status, but only with the swap’s `publicToken` in `X-Record-Token`: without it, or with another swap’s, the answer is 404. Every other key reads its own swaps as before. Listing swaps stays closed to the public key.

Requires the `swaps:read` scope. The shared public key may call it.

**Path parameters**

- `id` (string, required)

**Headers**

- `X-Record-Token` (string, optional): Required with the shared public key: the `publicToken` the create response returned for this record. Without it, or with the token of another record, the answer is 404, as for a record that does not exist. Ignored for every other API key.

**Responses**

- `200` (`SwapEntity | ChainSwapEntity`): OK
- `400`: ValidationFailed (see Shared responses)
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `404`: NotFound (see Shared responses)
- `500`: InternalError (see Shared responses)

## Relay the signed swap transaction to its network (checked against the one built); finalizes status

`POST /v1/swaps/{id}/submit`

`signedXdr` (Stellar) or `signedTransaction` (Solana, Monad) must be the transaction built for this swap and carry its source's signature, checked before anything about the swap is answered. Stellar: broadcast through Horizon, the answer is `SUCCEEDED` or `submitted: false` with the result codes (a `FAILED` swap can be resubmitted up to 3 times while its envelope is valid). Solana and Monad: broadcast through this service's RPC, the swap is `SUBMITTED` until the observer sees it settle. A Monad wallet that sends the transaction itself (eth_sendTransaction) submits its `txHash` instead: the transaction is read from the network and checked the same way, then recorded as `SUBMITTED`; not on the network yet is `transaction_not_found`, retry in a few seconds, and the same hash again answers the swap as it is. Emits `SWAP_SUBMITTED`, then `SWAP_SUCCEEDED` or `SWAP_FAILED`; with the shared public key, send the swap's `publicToken` in `X-Record-Token`.

Requires the `swaps:write` scope. The shared public key may call it.

**Path parameters**

- `id` (string, required)

**Headers**

- `X-Record-Token` (string, optional): With the shared public key, send the `publicToken` the create response returned for this record. A wrong token is 404, as for a record that does not exist. A missing one is still accepted for now (and logged as deprecated) so wallets that do not send it yet keep working; it becomes required here when the deployment sets `PUBLIC_RECORD_TOKEN_REQUIRED_ON_LEGACY=true`. Ignored for every other API key.

**Request body** (`application/json`, required): `SubmitSwapDto`

- `signedXdr` (string, optional): Stellar swaps: the signed transaction envelope (base64 XDR). Required unless signedTransaction or txHash is sent.
- `signedTransaction` (string, optional): Solana and Monad swaps: the signed transaction, which this service broadcasts. Solana: base64 wire bytes of the VersionedTransaction; Monad: the 0x-hex raw EIP-1559 transaction (the eth_sendRawTransaction input). On Monad, send this or txHash, not both.
- `txHash` (string, optional): Monad swaps only: the hash of the swap transaction the wallet already broadcast, for wallets that send a transaction but never hand over its signed bytes (EVM browser wallets answer eth_sendTransaction with the hash alone). The service reads it from its Monad node and checks it is the call built for this swap (`to`, `input`, `value`), sent from the swap's source on chain 143, before anything about the swap is answered; it then records it and the swap is SUBMITTED until the observer sees it settle. Not on the node yet: 400 `transaction_not_found`, nothing recorded, retry in a few seconds. The same hash again answers the swap as it is. The approval transaction is sent by the wallet first and never submitted here. A Solana swap takes signedTransaction.

**Responses**

- `200` (`SwapSubmitResultEntity | ChainSwapSubmitResultEntity`): OK
- `400` (`ApiErrorBodyEntity`): `validation_failed`: `signedXdr` (Stellar) / `signedTransaction` (Solana, Monad) is not a transaction, is not the one built for this swap, or carries no signature of its source; or `txHash` (Monad) names another transaction (the message names the field: `to`, `input`, `value`, `from` or `chainId`), the approval, or one recorded on another swap; or the body sends a field the swap does not take. `transaction_not_found`: the network does not have that `txHash` yet; nothing was recorded, retry in a few seconds. `transaction_rejected`: the Solana or Monad node refused the broadcast; the swap stays PENDING. `invalid_state_transition`: the swap can no longer be submitted, because it is EXPIRED, its transaction's validity window has passed, it was already submitted with another `txHash`, or it was already resubmitted the maximum number of times after a rejection. Build a new swap.
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `404`: NotFound (see Shared responses)
- `429` (`ApiErrorBodyEntity`): Rate limited (`rate_limited`), per consumer and client address. Honour `Retry-After`: the window is shorter than the envelope lifetime, so a retry after it still lands in time.
- `500`: InternalError (see Shared responses)
- `502`: UpstreamError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)
- `504`: UpstreamTimeout (see Shared responses)

## Shared responses

- **Unauthorized** (`ApiErrorBodyEntity`): `no_authenticated_consumer`: The gateway forwarded no API key identity
- **Forbidden** (`ApiErrorBodyEntity`): `insufficient_scope`: the API key does not hold the scope this route requires. The shared public API key also gets this on every route that is not marked `x-cosmos-public-key`, with a message saying so; more scopes will not help, the key is the wrong one. `gateway_required`: the request did not arrive through APISIX.
- **RateLimited** (`ApiErrorBodyEntity`): The budget in `x-cosmos-rate-limit` is spent for this caller. Honour `Retry-After`. The `ratelimit-*` triple rides along on successful responses too, so a client can pace itself instead of being refused. If the counter store itself is unreachable the guard fails closed and answers `503 provider_unavailable`.
- **InternalError** (`ApiErrorBodyEntity`): Unexpected server error. The detail is logged server-side and never returned: there is nothing in the body to branch on beyond the code.
- **UpstreamError** (`ApiErrorBodyEntity`): The provider named in `x-cosmos-upstream` refused the request (`provider_error`) or could not be reached at all (`provider_unavailable`). Nothing was charged; retry is safe with the same `Idempotency-Key`.
- **UpstreamTimeout** (`ApiErrorBodyEntity`): The provider in `x-cosmos-upstream` did not answer in time. Whether it acted on the request is unknown. Retry with the same `Idempotency-Key`, never with a fresh one.
- **ValidationFailed** (`ApiErrorBodyEntity`): The body, query or path failed validation. `message` is an array of the individual failures. Routes that reject a *valid* request for a reason of their own (an amount, a memo, a state) document the code for it on their own 400.
- **NotFound** (`ApiErrorBodyEntity`): No such resource, or it exists and belongs to another consumer. The two are deliberately the same answer: "exists but not yours" is an ownership oracle.
- **UpstreamUnavailable** (`ApiErrorBodyEntity`): `provider_unavailable`: the provider in `x-cosmos-upstream` is down or unreachable; the message names it. Retry. `misconfigured`: this deployment is missing configuration the route needs (a provider instance, a fee wallet, the plan header the gateway must forward). Retrying will not help; it is an operator problem.
