> For the complete documentation index, see [llms.txt](https://sonic-ai-works.gitbook.io/sonic-networks-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sonic-ai-works.gitbook.io/sonic-networks-docs/documentation/developers/solana-and-swap/swap-execution-slippage-and-fee-settlement.md).

# Swap execution, slippage & fee settlement

Canonical SONIC Swap execution, UI contract and production-verification specification for trusted assets, quotes, fees, routing, transaction intent, Solana verification, settlement and reconciliation.

## SONIC Swap — Execution, UX, Settlement & Verification

> **Development / pre-production** — This specification defines the intended production contract. It does not prove that SONIC Swap, a production SONIC mint, a liquidity venue, a provider route, or a mainnet transaction path is currently Active.

SONIC Swap is a **server-authoritative financial application**. The client requests and explains a swap; routing infrastructure discovers an executable route; the wallet explicitly authorizes the transaction; Solana executes it; and the SONIC finance kernel independently verifies, settles and reconciles the economic result.

### Product invariant

```
UI requests + explains
Wallet authorizes
Solana executes
Providers route/read
SONIC verifies + settles + reconciles
```

No browser state, provider response, signature, explorer result or confirmation alone is authoritative settlement evidence.

### Canonical execution flow

```
trusted token selection
→ signed session / auth context
→ route access + entitlement
→ wallet + network validation
→ balance validation
→ human amount → atomic bigint
→ 2% SONIC service fee
→ executable input
→ slippage policy
→ route discovery
→ normalized immutable quote
→ price-impact policy
→ TransactionIntent
→ Review Swap
→ explicit wallet signature
→ submission
→ Solana confirmation
→ on-chain effect verification
→ idempotent settlement
→ reconciliation
→ verified receipt + activity
```

For executable swaps, **quote → intent** is mandatory.

### Production token identity

```
network + mint + token program + verified decimals + registry version
= trusted token identity
```

SONIC resolves from the active deployment registry. Symbol, name, logo, wallet metadata, explorer search, token list or permissionless pool never establishes identity. Production SONIC mint, token program and decimals remain deployment-controlled until verified.

### Atomic accounting and balances

```ts
type AtomicAmount = bigint;
```

Ledger-critical calculations use atomic integers with authoritative decimals. Floating-point/display-rounded values are prohibited for quote, fee, balance, minimum output, settlement and reconciliation arithmetic.

Balance states are explicit: `ZERO`, `INSUFFICIENT`, `SUFFICIENT`, `UNAVAILABLE`, `STALE`. Unavailable data is never displayed as zero.

For SPL input:

```
inputTokenBalance >= grossInputAtomic
SOL balance >= required execution reserve
```

For native SOL input:

```
SOL balance >= gross input + network fee + priority fee + account costs + reserve
```

`MAX` preserves the native-SOL execution reserve.

### Fee contract

Current SONIC Swap service fee:

```
200 bps = 2%
serviceFeeAtomic = floor(grossInputAtomic × 200 / 10_000)
executableInputAtomic = grossInputAtomic - serviceFeeAtomic
```

The server calculates the fee with integer arithmetic. The quote and intent persist the fee-policy version. The recipient resolves from verified configuration. Execution verification checks the actual fee movement.

Keep separate:

* SONIC Service Fee;
* Solana Network Fee;
* Priority Fee;
* DEX / Venue Fee;
* Routing / Provider Fee;
* Token-Level Transfer Fee only if verified production token configuration enables one.

### Quote and route contract

```
Swap UI
→ /api/v1/swap/*
→ SwapService
→ MarketRouter
→ provider adapter
```

Jupiter is routing/aggregation infrastructure, not a SONIC pool. Raydium, Meteora and Orca are direct venues only when verified and enabled. Provider output is normalized before entering SONIC domain logic.

```
provider response ≠ settlement authority
```

No route may be fabricated.

An executable quote binds:

```
quoteId
provider
network
inputMint
outputMint
grossInputAtomic
serviceFeeAtomic
executableInputAtomic
expectedOutputAtomic
minimumOutputAtomic
slippageBps
priceImpactBps
route
feeBreakdown
feePolicyVersion
registryVersion
expiresAt
quoteHash
```

Quotes are persisted, immutable and expiring. Material changes require requote.

### TransactionIntent contract

Before signature, persist:

```
operationId
intentId
quoteId
authorityContextRef
wallet
network
inputMint
outputMint
grossInputAtomic
serviceFeeAtomic
executableInputAtomic
expectedOutputAtomic
minimumOutputAtomic
slippageBps
priceImpactBps
feeRecipient
feePolicyVersion
registryVersion
route
quoteHash
intentHash
expiresAt
```

The intent binds the exact operation the wallet may authorize. Expired or incompatible intents cannot execute.

### UX contract

#### Desktop

```
LEFT NAV | SWAP WORKSPACE | ROUTE / FEE / ACTIVITY RAIL
```

The transaction workspace has priority over promotional or market content. Recommended large-desktop shell:

```
248px | minmax(640px, 1fr) | 400px
```

#### Tablet

Remove the permanent navigation rail. Use the Swap workspace first and supporting route/fee/activity cards below or beside it depending on width.

#### Mobile

Mobile is transaction-first. Use a compact header, stacked From/To cards, centered circular swap-direction control, expandable quote details and a sticky **Review Swap** CTA. Token/settings/review surfaces use bottom sheets where appropriate.

#### Responsive breakpoints

```
<390        Mobile XS
390–639     Mobile
640–767     Large Mobile
768–1023    Tablet
1024–1199   Tablet Landscape
1200–1439   Desktop
1440–1799   Large Desktop
≥1800       XL Desktop
```

Ultra-wide layouts cap the application width rather than stretching the transaction form indefinitely.

### Brand and component rules

Default light theme uses white/light-gray surfaces, near-black text and restrained dark SONIC red. Primary financial actions use dark red, not blue/purple.

Canonical application lockup:

```
SONIC   ← semibold
SWAP    ← smaller / regular
```

Use the SONIC vector UI icon for compact application surfaces. The canonical 3D SONIC coin remains presentation artwork and is not redrawn as a UI token selector.

Use the Solana icon with:

```
Solana
Mainnet-beta
```

Token, route and avatar icons are circular. The swap-direction control is circular and centered between **From** and **To**.

### Swap form

The default transaction form exposes:

```
FROM
asset + balance
amount + fiat estimate
25% / 50% / 75% / MAX

SWAP DIRECTION

TO (Estimate)
asset + balance
estimated output + fiat estimate

rate + route
quote expiry
economic breakdown
Review Swap
```

Do not label estimated output as final before settlement.

### Economic disclosure

Before signature distinguish:

```
Gross Input
SONIC Service Fee
Executable Swap Input
Expected Output
Minimum Received
DEX / Venue Fees
Routing Fees
Estimated Solana Network Fee
Estimated Priority Fee
Slippage
Price Impact
Route
Quote Expiry
Wallet
Network
```

The service fee is never hidden in the rate. Estimated chain costs are not presented as exact final costs.

### Review and signing

`Review Swap` opens a dedicated review surface before the wallet. It binds the user-visible economics to the persisted intent. The wallet must remain visible before signing.

A wallet signature means **authorization**, not success.

If the user rejects the signature, no authoritative economic settlement mutation occurs.

### Submission recovery

```
SIGNED → SUBMITTED → CONFIRMING → CONFIRMED
```

Persist the transaction signature. After submission, state remains server-owned despite refresh, browser close, logout or wallet disconnect.

For uncertain writes:

```
unknown → inspect chain state → classify → retry only when safe
```

Never offer blind resubmission for ambiguous value-moving state.

### On-chain effect verification

Before settlement verify network, signer, success, input/output mints, executable input, service fee/recipient, allowed programs, minimum output, transaction uniqueness and intent compatibility.

```
signature exists ≠ settlement
provider success ≠ settlement
confirmation ≠ settlement
```

### Settlement and reconciliation

```
VERIFIED → SETTLING → SETTLED → RECONCILING → RECONCILED
```

One logical operation may create at most one authoritative settlement. Settlement uses verified actual output and separate fee accounting. Reconciliation compares quote, intent, settlement, Solana transaction, actual token movement and actual fee movement.

Outcomes:

```
MATCH
DRIFT_DETECTED
REQUIRES_REVIEW
FAILED
```

### User-visible lifecycle

Canonical user states:

```
Connect Wallet
Enter Amount
Fetching Quote
Quote Ready
Quote Expired
Review Swap
Awaiting Signature
Submitting
Confirming
Verifying
Settling
Reconciliation Pending
Reconciled
Failed
Requires Review
```

The UI must not use one indefinite `Processing` state for the complete financial lifecycle.

A confirmed transaction is not displayed as fully settled until effect verification and settlement complete. Receipts use verified actual values.

### Failure UX

Prefer precise states such as:

```
Wallet required
Wallet changed
Session expired
Wrong network
Balance unavailable
Insufficient balance
Insufficient SOL reserve
Quote expired
No route available
Price impact too high
Simulation failed
Signature rejected
Submission status pending verification
Transaction failed
Verification failed
Settlement failed
Requires review
```

`Something went wrong` is reserved for genuinely unclassified failures.

### Canonical state machine

```
CREATED
→ VALIDATED
→ QUOTED
→ INTENT_CREATED
→ AWAITING_SIGNATURE
→ SIGNED
→ SUBMITTED
→ CONFIRMING
→ CONFIRMED
→ VERIFYING
→ VERIFIED
→ SETTLING
→ SETTLED
→ RECONCILING
→ RECONCILED
```

Exceptional: `EXPIRED`, `REJECTED`, `CANCELLED`, `INVALID`, `FAILED`, `REQUIRES_REVIEW`.

### API surface

```http
GET  /api/v1/swap/tokens
GET  /api/v1/swap/settings
POST /api/v1/swap/quotes
POST /api/v1/swap/intents
POST /api/v1/swap/:intentId/submit
GET  /api/v1/swap/:intentId/status
POST /api/v1/swap/:intentId/verify
```

Duplicate-sensitive mutations use operation-scoped idempotency. API documentation should expose status, authentication, authorization, entitlement, validation, response, transition, idempotency, normalized errors, side effects and observability.

***

## Swap Launch Readiness & Verification

This is the **single source of truth for Swap acceptance testing, production readiness and launch validation**. Other pages reference these categories instead of copying test matrices.

### Required categories

1. Configuration
2. Trusted Token Registry
3. Wallet & Session
4. Amounts, Decimals & Balances
5. Fees & Disclosure
6. Slippage & Price Impact
7. Routing
8. Quote Integrity
9. Transaction Intent
10. Simulation & Signature
11. Submission & Confirmation
12. On-Chain Effect Verification
13. Settlement
14. Reconciliation
15. Provider Resilience
16. Circuit Breakers
17. Security
18. Observability
19. Admin Controls
20. User Experience & Accessibility

Every Required control must pass.

### Configuration

Verify production network, deployment registry/version, launch-blocking TBA resolution, SONIC mint/program/decimals, fee recipient, fee policy, provider configuration and environment isolation. Mainnet rejects devnet mints, programs, pools, recipients and registry entries.

### Trusted Token Registry

Verify valid mints, authoritative decimals/programs, deployment-registry SONIC identity, fail-closed unknown tokens and registry-version mismatch handling. Duplicate symbols/logos never bypass mint validation.

### Wallet & Session

Test missing wallet, wallet change after quote/intent, expired session, wrong network, disconnect before signature and client loss after submission. Durable submitted state remains server-owned.

### Amounts, Decimals & Balances

Test 6/8/9-decimal assets, minimum atomic amount, large amount, human↔atomic round trip, zero/insufficient/unavailable/stale/exact balances, SPL MAX and SOL MAX. No floating-point settlement arithmetic.

### Fees & Disclosure

Test `10,000 atomic → 200 atomic`, small-amount rounding, multiple decimal configurations, large amount, wrong/missing fee and wrong recipient. Review UI separates service, network, priority, venue and routing fees.

### Slippage & Price Impact

Test configured minimum/default/presets/maximum, invalid custom values and requote behavior. Test low/moderate/warning/blocked/missing price impact independently of slippage.

### Routing

Jupiter adapter must normalize validated executable quotes and enforce expiry/health. Test success, timeout, malformed response, no route, stale/expired quote, excessive impact and outage. Direct venues require verified markets/pools and passing policy/simulation. No fabricated fallback route.

### Quote Integrity

Test persistence, immutability, expiry, hash validation and requote after amount/token/wallet/network/slippage/routing/fee-policy/registry changes.

### Transaction Intent

Verify persistence before signature, intent hash, authority/wallet/network/fee recipient/minimum output/quote binding and expiry.

### Simulation & Signature

Test simulation pass/fail, approval/rejection, wallet change during signing and malformed prepared transaction. Rejection creates no settlement mutation.

### Submission & Confirmation

Test normal submission, timeout before response, timeout after likely submission, initially-not-found signature, delayed confirmation and failed transaction. Uncertain writes are inspected, not blindly retried.

### On-Chain Effect Verification

Test wrong signer/mint/amount/fee/recipient, minimum-output violation, unexpected program, failed transaction and duplicate transaction use. Signature/provider response/confirmation alone cannot settle.

### Settlement

Verify one settlement per logical operation, actual verified output, separate fee accounting, idempotency and convergence under repeated verification.

### Reconciliation

Compare quote, intent, settlement, chain transaction, token movement and fee movement. Test correct settlement, wrong persisted output/fee, missing transaction, duplicate settlement and deliberately corrupted ledger state.

### Provider Resilience

| Dependency               | Required degradation                        |
| ------------------------ | ------------------------------------------- |
| Jupiter                  | verified direct routes may remain available |
| Raydium / Meteora / Orca | remove affected route                       |
| RPC read                 | approved safe fallback may be used          |
| RPC write                | inspect uncertain submission before retry   |
| RPC disagreement         | pause sensitive writes                      |
| Explorer                 | disable explorer-link UX only               |

Unavailable data is never fabricated.

### Circuit Breakers

```
swapEnabled
jupiterEnabled
raydiumEnabled
meteoraEnabled
orcaEnabled
customSlippageEnabled
unverifiedTokensEnabled
```

Automatic pause triggers may include registry mismatch, invalid fee recipient, RPC disagreement, provider error threshold, verification instability, settlement drift and reconciliation drift.

### Security

Verify no client private keys/provider/treasury secrets; mint-spoof prevention; session/transaction replay mitigation; provider/webhook messages cannot settle; mutation idempotency; environment isolation; explicit authorization boundaries.

### Observability

Trace:

```
operationId
quoteId
intentId
transactionSignature
settlementId
reconciliationId
```

Monitor quote success/latency, route/provider failures, signature rejection, uncertain submissions, confirmation latency, verification failures, settlement success, reconciliation drift, slippage/impact rejections and service-fee totals. Never log secrets.

### Admin Controls

Expose feature state, fee policy/recipient, registry status, provider health, quote failures, settlement/reconciliation state, circuit breakers and audit history. Sensitive configuration changes are auditable.

### User Experience & Accessibility

Verify explicit quote expiry, minimum received, service fee, estimated network costs, wallet/network, actual receipt values, precise loading/error states, keyboard navigation, focus visibility, screen-reader labels, reduced-motion support, non-color-only status communication and minimum 44×44px touch targets.

### Pre-launch gate

`swapEnabled = true` is allowed only after every Required category passes and production configuration is verified.

### Release states

```
NOT_READY
→ READY_FOR_STAGING
→ STAGING_VERIFIED
→ MAINNET_READY
→ ACTIVE

ACTIVE → PAUSED
```

`MAINNET_READY` requires the consolidated suite to pass. `ACTIVE` additionally requires explicit production enablement.

### Post-launch verification

Continuously monitor settlement/reconciliation drift, unexpected fee movement, quote/route failures, provider degradation, RPC disagreement, reconciliation lag, registry changes, abnormal price impact and transaction failure rate. Critical invariant failure may automatically pause execution while safe read-only market/activity surfaces remain available.

### Production-valid Swap invariant

```
trusted configuration
+ verified token identity
+ validated wallet/session
+ sufficient balances
+ atomic accounting
+ transparent fees
+ valid slippage + acceptable price impact
+ verified route
+ immutable quote
+ TransactionIntent
+ explicit wallet authorization
+ confirmed Solana transaction
+ verified economic effects
+ one authoritative settlement
+ successful reconciliation
= production-valid swap
```

This section supersedes every separate Swap launch-gate, acceptance-test, provider-check, reconciliation-test, wallet/session-test, slippage-test, decimal-test and failure-test checklist.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://sonic-ai-works.gitbook.io/sonic-networks-docs/documentation/developers/solana-and-swap/swap-execution-slippage-and-fee-settlement.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
