# Settle Trade Payment

### <mark style="color:orange;">EVM-Compatible Networks</mark>

#### Authorized Settlement with Fee Deduction

```solidity
function settlement(
    bytes32 tradeId,
    uint256 totalFee,
    address toAddress,
    TradeDetail calldata detail,
    bytes calldata presign,
    bytes calldata mpcSignature
) external nonReentrant;
```

🔐 Permissioned Execution

* Can only be executed by authorized actors capable of producing valid `mpcSignature` and `presign`.
* Ensures that settlement is authorized through off-chain coordination and validation.

🔎 Trade Validation

* Callable only if `block.timestamp <= detail.timeout`.
* Prevents settlement after the trade has expired.
* Validates that the provided `TradeDetail` matches the recorded hash for the `tradeId`.
* Guards against tampering and unauthorized settlements.

🔑 Signature Verification

* Verifies a pre-signature from the ephemeral asset signer.
* Confirms the settlement recipient (`toAddress`) and authorized `amount`.
* Requires a valid signature from the `MPC` to authorize settlement.
* Ensures consensus among off-chain nodes has been reached before finalizing the trade.

💰 Protocol Fee Handling

* If `totalFee` is non-zero, the specified amount is transferred to `protocol.pFeeAddr()` before proceeding with settlement.
* Guarantees protocol fee collection before fund distribution.

💸 Transfer Execution

* Transfers the remaining amount (`amount - totalFee`) to the PMM’s designated receiving address (`toAddress`).

📢 Event Emission

* Emits a `Settled` event containing all relevant data: tradeId, fee recipient, final recipient, total fee, and transferred amount.

### <mark style="color:orange;">Bitcoin Network</mark>

Unlike EVM and Solana networks which use smart contracts, Bitcoin utilizes the **Native Bitcoin Vault**—a non-custodial escrow built with Bitcoin's native scripting.

Users deposit BTC into a P2TR (Pay-to-Taproot) address controlled by a 2-of-2 multisig between the user and the Settlement Committee. Trades are settled when both parties sign, or users can reclaim funds after timelock expiry using only their own key.

For technical details on vault construction, spending paths, and security model, see [Native Bitcoin Vault.](/optimex-revolutionizing-bitcoin-finance/primary-building-blocks/native-bitcoin-vault.md)

### <mark style="color:orange;">Solana Networks</mark>

#### Authorized Settlement with Fee Deduction

```rust
pub struct SettlementArgs {
    /// The tradeId, unique identifier for the trade
    pub trade_id: [u8; 32], // uint256
}
pub fn handler_settlement<'c: 'info, 'info>(
    ctx: Context<'_, '_, 'c, 'info, SettlementAccounts<'info>>,
    settlement_args: SettlementArgs,
) -> Result<()>                                                                                        
```

🔐 Permissioned Execution

* Can only be executed by authorized actors capable of producing valid `mpcSignature` and `ephemeralSignature`.
* Ensures that settlement is authorized through off-chain coordination and validation.

🔎 Trade Validation

* Callable only if `Clock::get().unix_timestamp <= trade_detail.timeout`.
* Can only be executed for the `TradeDatail` in the `Deposited` state.
* Prevents settlement after the trade has expired.
* Validates that the provided `TradeDetail` matches the recorded hash for the `tradeId`.
* Guards against tampering and unauthorized settlements.

🔑 Signature Verification

* Verifies a signature from the ephemeral asset signer.
* Confirms the settlement recipient (`toAddress`) and authorized `amount`.
* Requires a valid signature from the `MPC` to authorize settlement.
* Ensures consensus among off-chain nodes has been reached before finalizing the trade.

💰 Protocol Fee Handling

* If `totalFee` is non-zero, the specified amount is transferred to `protocol` account before proceeding with settlement.
* Guarantees protocol fee collection before fund distribution.

💸 Transfer Execution

* Transfers the remaining amount (`amount - totalFee`) to the PMM’s designated receiving address (`toAddress`).
* Update the status of corresponding TradeDetail account from `Deposited`  to `Settled`

> **📌 Note: This function represents the final stage of a successful trade. It finalizes the transfer of funds according to MPC authorization and ensures both the PMM and protocol receive their respective payments securely.**


---

# Agent Instructions: 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:

```
GET https://docs.optimex.com/optimex-revolutionizing-bitcoin-finance/optimex-swap/optimex-swap-how-it-work/trade-life-cycle/asset-chain/settle-trade-payment.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
