# Liquidity Pools (https://dev.cosmospay.lat/docs/api/liquidity-pools/)

> Deposit into and withdraw from Stellar AMM pools, and track your positions.

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

## Build a pool deposit → unsigned XDR + SEP-7 tx URI + QR for the wallet to sign

`POST /v1/liquidity-pools/deposit`

Builds a `liquidityPoolDeposit` on the key's network for `source` to sign (preceded by the pool-share trustline when the account has none), stores it as `PENDING` and emits `LIQUIDITY_CREATED`. Leave `maxAmountB` out to match the pool’s current ratio (an empty pool needs both amounts, which set its price); the price bounds bracket the pool price by `slippageBps` (default 50, cap 500 unless configured). Deposits pay no plan commission; a `merchantFee` is paid from each asset, and `source` must trust both assets and afford the amounts plus its reserve (`trustline_missing`, `insufficient_balance`). An `Idempotency-Key` (header or body) makes a retry return the same operation.

Requires the `liquidity:write` or `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 operation (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): `DepositLiquidityDto`

- `source` (string, required): Account funding (and signing) the deposit: the tx source.
- `assetACode` (string, optional): First asset of the pair. Native if omitted.
- `assetAIssuer` (string, optional): Issuer account for a non-native first asset.
- `assetBCode` (string, optional): Second asset of the pair. Native if omitted.
- `assetBIssuer` (string, optional): Issuer account for a non-native second asset.
- `maxAmountA` (string, required): Maximum amount of the first asset to deposit (decimal, ≤ 7 places).
- `maxAmountB` (string, optional): Maximum amount of the second asset. When the pool already has reserves this is derived from the pool price if omitted; it is required when the pool is new or empty (the deposit sets the price).
- `slippageBps` (number, optional): Slippage tolerance in basis points (50 = 0.5%) used to derive the on-chain min/max price bounds. Defaults to the service setting; capped by it.
- `memo` (string, optional): 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 operation instead of building another transaction; the same key with a different request is 409 `idempotency_conflict`.
- `merchantFee` (MerchantFeeDto, optional): Your own fee on this deposit: `bps` of EACH asset it moves, paid to `wallet` (a Stellar account that can receive both assets) by one payment per asset in the same transaction, beside the plan commission. `fixed` is refused here: the operation moves two assets. `paidBy: recipient` takes it from the amounts (less enters the pool); `payer` adds it on top (the full amounts enter the pool).

**Responses**

- `201` (`LiquidityOperationEntity`): Created
  - `id` (string, required): The operation's id, used by the read and submit routes.
  - `kind` (string, required): `DEPOSIT` adds both assets to the pool; `WITHDRAW` burns pool shares for both reserves. One of: `DEPOSIT`, `WITHDRAW`.
  - `status` (string, required): PENDING (built, unsigned), SUBMITTED (a signed transaction was sent to the network), SUCCEEDED (confirmed on the ledger), FAILED (rejected on the network) or EXPIRED (time bounds elapsed before submission). One of: `PENDING`, `SUBMITTED`, `SUCCEEDED`, `FAILED`, `EXPIRED`.
  - `network` (string, required): The Stellar network the operation targets, which follows the API key: `public` (mainnet) or `testnet`.
  - `source` (string, required): The Stellar account that funds and signs the operation: the transaction source.
  - `poolId` (string, required): Stellar liquidity pool id (64-character lowercase hex).
  - `assetA` (string, required): Asset A's code (`native` for XLM). The pair is stored in the protocol's canonical order (A < B).
  - `assetAIssuer` (object, required): Asset A's issuer account; null for native XLM.
  - `assetB` (string, required): Asset B's code (`native` for XLM).
  - `assetBIssuer` (object, required): Asset B's issuer account; null for native XLM.
  - `amountA` (string, required): DEPOSIT: maxAmountA cap. WITHDRAW: slippage-protected minimum of asset A.
  - `amountB` (string, required): DEPOSIT: maxAmountB cap. WITHDRAW: slippage-protected minimum of asset B.
  - `shares` (object, required): Pool shares burned (WITHDRAW only).
  - `minPrice` (object, required): A DEPOSIT's lower price bound (its `liquidityPoolDeposit` minPrice), in asset A per unit of asset B, as a decimal string of up to 7 places: the pool price when the operation was built (reserve A / reserve B, or `amountA` / `amountB` for a pool with no reserves yet) less `slippageBps`, rounded down. The deposit fails on-chain at a price below it. Null on a WITHDRAW.
  - `maxPrice` (object, required): A DEPOSIT's upper price bound (its `liquidityPoolDeposit` maxPrice), in the same units as `minPrice`: the same pool price plus `slippageBps`, rounded up. The deposit fails on-chain at a price above it. Null on a WITHDRAW.
  - `slippageBps` (number, required): The slippage tolerance the operation was built with, in basis points (50 = 0.5%).
  - `memo` (string, optional): The caller's MEMO_ID (uint64 as a string), null when none was supplied. A commission MEMO_TEXT is reported in `commissionMemo`, never here. Operations created before this field existed report null even when their envelope carries a MEMO_ID; the `xdr` is authoritative for those.
  - `idempotencyKey` (object, optional): Client idempotency key when supplied via Idempotency-Key / body (null otherwise).
  - `feeBps` (number, required): Plan commission in basis points (50 = 0.5%), applied to both assets.
  - `feeAmountA` (string, required): Commission taken from asset A (deducted from the deposit / the withdrawn minimum). "0" when no commission applies.
  - `feeAmountB` (string, required): Commission taken from asset B. "0" when none.
  - `feeWallet` (object, required): Commission collector account (null when the fee is disabled).
  - `merchantFee` (LiquidityMerchantFeeEntity, required): The merchant fee the request named: `bps` of each asset, `amount` in asset A and `amountB` in asset B, paid to `wallet` in this transaction; null without one.
  - `commissionMemo` (object, required): On-chain MEMO_TEXT label stamped when a commission is collected and no caller memo was supplied (null when no commission applies).
  - `xdr` (string, required): Unsigned transaction envelope (base64 XDR) to sign.
  - `uri` (string, required): A SEP-7 `tx` URI carrying `xdr`, for a wallet to sign.
  - `txHash` (string, required): Deterministic transaction hash (verified on submit).
  - `qr` (string, required): A QR code of `uri`, as a PNG data URL.
  - `expiresAt` (object, required): When the transaction's validity window closes (ISO 8601 date-time); after it the transaction can no longer settle.
  - `createdAt` (string (date-time), required): When the operation was built (ISO 8601 date-time).
  - `updatedAt` (string (date-time), required): When the operation was last updated (ISO 8601 date-time).
- `400` (`ApiErrorBodyEntity`): `validation_failed`: The body, query or headers failed validation `invalid_amount`: Not a Stellar amount, or not greater than zero `trustline_missing`: An account does not trust the asset, and this request cannot add the trustline for it `insufficient_balance`: The source account cannot cover the amount, or the XLM reserve the transaction needs
  - `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)
- `409` (`ApiErrorBodyEntity`): `idempotency_conflict`: this Idempotency-Key was already used for a different request, or an identical deposit was already built without a key (retry with an Idempotency-Key, or wait for the prior operation to settle or expire).
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)

## Build a pool withdrawal (burn shares) → unsigned XDR + SEP-7 tx URI + QR

`POST /v1/liquidity-pools/withdraw`

Builds a `liquidityPoolWithdraw` of `shares` from `poolId` on the key's network for `source` to sign, with minimum amounts of each reserve set from the current reserves less `slippageBps`, stores it as `PENDING` and emits `LIQUIDITY_CREATED`. The plan commission is charged only on the gain over the cost basis of shares deposited through this service, out of the withdrawn reserves; a `merchantFee` is a share of the minimum amounts. A withdrawal from the same pool that may already be on-chain blocks another one for that account (`operation_in_flight`); an `Idempotency-Key` (header or body) makes a retry return the same operation.

Requires the `liquidity:write` or `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 operation (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): `WithdrawLiquidityDto`

- `source` (string, required): Account holding the pool shares (and signing): the tx source.
- `poolId` (string, required): Stellar liquidity pool id (64-char hex).
- `shares` (string, required): Amount of pool shares to burn (decimal, ≤ 7 places).
- `slippageBps` (number, optional): Slippage tolerance in basis points (50 = 0.5%) used to derive the on-chain minimum received per reserve. Defaults to the service setting.
- `memo` (string, optional): 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 operation instead of building another transaction; the same key with a different request is 409 `idempotency_conflict`.
- `merchantFee` (MerchantFeeDto, optional): Your own fee on this withdrawal: `bps` of EACH asset it moves, paid to `wallet` (a Stellar account that can receive both assets) by one payment per asset in the same transaction, beside the plan commission. `fixed` is refused here: the operation moves two assets. The fee comes out of what the withdrawal pays, on its guaranteed minimums, whichever `paidBy` names: the account is payer and receiver.

**Responses**

- `201` (`LiquidityOperationEntity`): Created
- `400` (`ApiErrorBodyEntity`): `validation_failed`: The body, query or headers failed validation `invalid_amount`: Not a Stellar amount, or not greater than zero `insufficient_balance`: The source account cannot cover the amount, or the XLM reserve the transaction needs `trustline_missing`: An account does not trust the asset, and this request cannot add the trustline for it
- `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 withdrawal was already built without a key. `operation_in_flight`: a withdrawal from this pool is already in flight for this account; wait for it to settle or expire.
- `429`: RateLimited (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)

## An account's pool share positions with redeemable amounts

`GET /v1/liquidity-pools/positions`

Reads `account`'s pool-share trustlines from Horizon on the key's network and, per pool, its shares, its share of the pool in basis points, the reserves and what those shares redeem now. Ledger data, not this consumer's rows: any account can be read, and nothing is stored.

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

**Query parameters**

- `account` (string, required): Account whose pool share trustlines to inspect.

**Responses**

- `200` (`LiquidityPositionListEntity`): OK
  - `account` (string, required): The Stellar account whose positions are listed.
  - `network` (string, required): The Stellar network read, which follows the API key: `public` (mainnet) or `testnet`.
  - `data` (LiquidityPositionEntity[], required): One position per pool the account holds shares in.
- `400`: ValidationFailed (see Shared responses)
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)

## List the consumer's liquidity pool operations

`GET /v1/liquidity-pools/operations`

The deposits and withdrawals built through this service, newest first, optionally filtered by `kind` and `status`. Paginated with `take` (default 20, max 100) and `skip`; the answer is `{ data, total, take, skip }`. Only operations on the key's network are listed (a `prod` key sees mainnet, a `dev` key testnet).

Requires the `liquidity:read` or `swaps:read` scope.

**Query parameters**

- `kind` (string, optional): Only operations of this kind (`DEPOSIT` or `WITHDRAW`). One of: `DEPOSIT`, `WITHDRAW`.
- `status` (string, optional): Only operations in this status. One of: `PENDING`, `SUBMITTED`, `SUCCEEDED`, `FAILED`, `EXPIRED`.
- `take` (number, optional): How many operations to return per page (1 to 100).
- `skip` (number, optional): How many matching operations to skip before the page starts (newest first).

**Responses**

- `200` (`LiquidityOperationListEntity`): OK
  - `data` (LiquidityOperationListItemEntity[], required): The operations on this page, newest first.
  - `total` (number, required): How many operations match the filters, across all pages.
  - `take` (number, required): The page size applied.
  - `skip` (number, required): How many matching operations were skipped before this page.
- `400`: ValidationFailed (see Shared responses)
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `500`: InternalError (see Shared responses)

## Get a liquidity pool operation by id

`GET /v1/liquidity-pools/operations/{id}`

One deposit or withdrawal this consumer built: its unsigned XDR, SEP-7 `uri` and QR, its status, and the commission and merchant fee it carries. Answered from this service's own table, which submit and the settlement observer keep current.

Requires the `liquidity:read` or `swaps:read` scope.

**Path parameters**

- `id` (string, required)

**Responses**

- `200` (`LiquidityOperationEntity`): 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 transaction to the network (hash-checked); finalizes status

`POST /v1/liquidity-pools/operations/{id}/submit`

`signedXdr` must hash to the operation's stored transaction and carry a signature, checked before anything about the operation is answered. It is broadcast through Horizon and the answer is `SUCCEEDED` or `submitted: false` with the result codes (a `FAILED` operation can be resubmitted up to 3 times while its envelope is valid); an unreachable Horizon is a 503 that leaves it resubmittable. Emits `LIQUIDITY_SUBMITTED`, then `LIQUIDITY_SUCCEEDED` or `LIQUIDITY_FAILED`, and a settled deposit records the cost basis the withdrawal commission is charged against.

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

**Path parameters**

- `id` (string, required)

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

- `signedXdr` (string, required): The signed transaction envelope (base64 XDR).

**Responses**

- `200` (`LiquiditySubmitResultEntity`): OK
  - `submitted` (boolean, required): True when the transaction was confirmed on the ledger (status SUCCEEDED); false when this broadcast was rejected (see `reason`).
  - `status` (string, required): The operation's status after this submission. One of: `PENDING`, `SUBMITTED`, `SUCCEEDED`, `FAILED`, `EXPIRED`.
  - `txHash` (string, optional): The on-chain transaction hash once submitted.
  - `reason` (string, optional): Why submission failed, when `submitted` is false. With `status` FAILED the ledger confirms the failure; with `status` SUBMITTED the network refused this broadcast but the transaction may still be on the ledger, and its outcome arrives as a terminal webhook.
  - `resultCodes` (string[], optional): Horizon transaction/operation result codes on a rejection.
  - `operation` (LiquidityOperationEntity, required): The operation after this submission.
- `400` (`ApiErrorBodyEntity`): `validation_failed`: `signedXdr` is not a transaction envelope, is not the envelope built for this operation, or carries no signatures. `invalid_state_transition`: the operation can no longer be submitted, because it is EXPIRED, its transaction's time bounds have passed, or it was already resubmitted the maximum number of times after a rejection. Build a new deposit or withdrawal.
- `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, in a bucket separate from the swaps submit route. 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)
- `503`: UpstreamUnavailable (see Shared responses)

## Browse on-chain liquidity pools (Horizon proxy)

`GET /v1/liquidity-pools`

Horizon's pool list on the key's network, in descending order, optionally narrowed to pools holding one or two assets (`assetACode`/`assetAIssuer`, `assetBCode`/`assetBIssuer`) or to those an `account` holds shares in. Paged by Horizon cursor, not `take`/`skip`: `limit` per page (default 20, max 100), and the answer's `cursor` fetches the next page (null when the page is not full). Nothing is stored.

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

**Query parameters**

- `assetACode` (string, optional): Filter to pools containing this asset. Pass "XLM"/"native" for lumens.
- `assetAIssuer` (string, optional): Issuer for a non-native first asset.
- `assetBCode` (string, optional): Second asset of the pair (narrows to the exact pool).
- `assetBIssuer` (string, optional): Issuer for a non-native second asset.
- `account` (string, optional): Only pools this account participates in.
- `cursor` (string, optional): Horizon paging cursor.
- `limit` (number, optional): How many pools to return per page (1 to 100). Page on with the `cursor` the answer returns.

**Responses**

- `200` (`LiquidityPoolListEntity`): OK
  - `data` (LiquidityPoolEntity[], required): The pools on this page, in Horizon's descending order.
  - `cursor` (object, required): Horizon paging cursor for the next page (null when done).
- `400`: ValidationFailed (see Shared responses)
- `401`: Unauthorized (see Shared responses)
- `403`: Forbidden (see Shared responses)
- `500`: InternalError (see Shared responses)
- `503`: UpstreamUnavailable (see Shared responses)

## Get a liquidity pool by id (Horizon proxy)

`GET /v1/liquidity-pools/{poolId}`

One pool read from Horizon on the key's network: its fee, trustline count, total shares and reserves. `poolId` is the 64-character lowercase hex pool id; any other shape is `validation_failed`, and a pool that does not exist on that network is a 404.

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

**Path parameters**

- `poolId` (string, required)

**Responses**

- `200` (`LiquidityPoolEntity`): OK
  - `id` (string, required): Stellar liquidity pool id (64-character lowercase hex).
  - `network` (string, required): The Stellar network the pool was read from, which follows the API key: `public` (mainnet) or `testnet`.
  - `feeBp` (number, required): Pool fee in basis points (0.3%).
  - `totalTrustlines` (string, required): Accounts holding pool shares.
  - `totalShares` (string, required): Total pool shares outstanding, as a decimal string (up to 7 decimal places).
  - `reserves` (LiquidityPoolReserve[], required): Both reserves, canonical order.
- `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)
- `503`: UpstreamUnavailable (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.
- **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.
- **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.
