> ## Documentation Index
> Fetch the complete documentation index at: https://docs.brc20.build/llms.txt
> Use this file to discover all available pages before exploring further.

# BiS AMM

> Technical reference for the Best in Slot AMM sequencer architecture, covering smart wallets, batch settlement, BLS signatures, BTC-frBTC wrapping, and the security model.

The Best in Slot (BiS) AMM is a non-custodial automated market maker built on BRC2.0. It uses BLS12-381 cryptography and Bitcoin batch settlement to deliver trustless DeFi on Bitcoin.

***

## Smart wallets

### Non-custodial design

Users hold their own BLS12-381 private keys. The sequencer never has access to user funds or signing capabilities. All operations are signed client-side before submission.

### BIP-322 signature verification

All operations — deposits, swaps, liquidity operations, and withdrawals — require a BIP-322 signature from the user's Bitcoin wallet as an additional security layer. This is enforced by the sequencer to protect users from unauthorized operations.

The first operation for every wallet is a deposit, which establishes the binding between the Bitcoin wallet and the BLS public key. The deposit authorization message format is:

```text theme={null}
Deposit Order:

Bitcoin Address:
BLS Public Key:
Token Address:

By signing this message, you authorize the creation of a deposit order with the above parameters.
```

### Pubkey index system

To optimize on-chain storage, public keys are assigned a sequential index. This allows operations to reference a compact identifier instead of the full 256-byte BLS public key, significantly reducing transaction sizes and inscription costs.

### Replay protection via nonces

Each wallet maintains a nonce that is atomically incremented with every operation. The nonce is included in the signed message, preventing replay attacks:

```javascript theme={null}
message = keccak256(pubkey) || nonce || op_type || params_hash
```

<Warning>
  If a user loses access to their Bitcoin wallet, the associated smart wallet cannot be recovered. This is by design — the system is non-custodial and there is no recovery mechanism. Users must secure their private keys.
</Warning>

***

## Bitcoin batch settlement

### Operation queue

User operations (swaps, liquidity adds/removes, withdrawals) are queued by the sequencer, which monitors pending operations and aggregates them into batches.

### Batching triggers

A new batch is created when either condition is met:

| Trigger             | Condition                                                          |
| ------------------- | ------------------------------------------------------------------ |
| Operation threshold | 500 or more pending operations in the queue                        |
| Withdrawal priority | Any pending withdrawal operations AND no currently pending batches |

This ensures withdrawals are processed promptly while maintaining efficient batching for regular operations.

### Compression

Batch data is compressed before inscription to minimize fees:

1. **Zstd compression** (level 22, maximum) is attempted first.
2. **NADA encoding** is used as fallback if it produces smaller output.
3. A 1-byte prefix indicates the encoding: `0x01` = NADA, `0x02` = Zstd.

The envelope format inscribed on-chain:

```json theme={null}
{ "p": "brc20-prog", "op": "t", "b": "<compressed_batch_data>" }
```

### Sequential execution

Once the batch is inscribed and mined, the BRC-20 EVM executes operations sequentially at the mined block height.

The system uses the **transact** command (signed EVM transactions) rather than simple calls for two reasons:

* **Key rotation resilience**: If the batch sender wallet key is compromised, operations can continue from a different wallet without interruption.
* **Nonce-based ordering**: The EVM transaction nonce enforces sequential execution on the BRC-20 side, preventing out-of-order processing.

***

## BLS signatures

### Cryptographic foundation

The system uses **BLS12-381**, a pairing-friendly elliptic curve providing 128-bit security. This curve is widely used in blockchain systems (Ethereum 2.0, Zcash) and enables efficient signature aggregation.

Signatures are computed on the G1 curve (shorter representation), while public keys reside on G2. This optimizes for aggregation efficiency since signatures are aggregated more frequently than public keys.

```javascript theme={null}
const P = bls12_381.G1.hashToCurve(msg_buf, {
  DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_'
});
```

### Message format

Each operation's signed message is constructed as:

```javascript theme={null}
keccak256(pubkey) || nonce (4 bytes) || op_type (1 byte) || params_hash
```

For unwrap operations specifically:

```javascript theme={null}
keccak256(pubkey) || nonce || 0x06 || keccak256(pkscript) || amount || fee
```

### Signature aggregation

Individual signatures from multiple operations are aggregated into a single signature per batch:

```javascript theme={null}
const aggregated_sigs = bls12_381.shortSignatures.aggregateSignatures(signatures);
const neg_aggregated_sigs = aggregated_sigs.negate();
```

The negated aggregated signature is submitted to the sequencer contract's `processBatch()` function for on-chain verification.

**N signatures compress to 1 aggregated signature**, providing constant verification cost regardless of batch size. This dramatically reduces on-chain verification costs and inscription sizes.

***

## BTC-frBTC wrapping

### Wrap: BTC to frBTC

<Steps>
  <Step title="Construct the call inscription">
    User constructs a `wrapAndExecute2()` call inscription.
  </Step>

  <Step title="Send BTC to the handler wallet">
    BTC is sent to the handler wallet in the send-to-OP\_RETURN transaction.
  </Step>

  <Step title="Sequencer validates">
    The sequencer checks transaction structure and signatures, fee rate within acceptable range, and mempool acceptance via `testmempoolaccept`.
  </Step>

  <Step title="frBTC minted">
    Upon inscription confirmation, frBTC is minted to the user's balance.
  </Step>
</Steps>

The wrap data includes:

* Token address
* Ticker index
* User pubkey and pubkey index
* BLS signature for emergency withdrawal
* EC signature for index verification

### Unwrap: frBTC to BTC

<Steps>
  <Step title="Submit BLS-signed unwrap request">
    User submits a request containing: public key and nonce, output pkscript (destination), and amount and BTC fee.
  </Step>

  <Step title="Signature verification">
    The sequencer verifies the signature against the message:

    ```javascript theme={null}
    keccak256(pubkey) || nonce || 0x06 || keccak256(pkscript) || amount || fee
    ```
  </Step>

  <Step title="Queue and process">
    The operation is queued and processed in the next batch.
  </Step>

  <Step title="BTC output created">
    A BTC output is created to the specified pkscript.
  </Step>
</Steps>

<Note>
  Minimum unwrap amount: **1000 satoshis**.
</Note>

### Custody model

The BTC handler wallet is secured by a multisig arrangement operated by Subfrost.

| Aspect       | Current state         | Planned                       |
| ------------ | --------------------- | ----------------------------- |
| Custody type | Multisig              | Committee-based               |
| Signers      | Subfrost team members | Independent committee members |

**Roadmap**: The custody model will transition from internal Subfrost signers to an independent committee approach, distributing trust across multiple parties external to the core team.

***

## Security

### Trust model

| Component      | Trust assumption                                                               |
| -------------- | ------------------------------------------------------------------------------ |
| **User**       | Holds private keys, signs all operations                                       |
| **Sequencer**  | Trusted for liveness only, not custody. Cannot forge signatures or steal funds |
| **Bitcoin**    | Provides finality and data availability                                        |
| **BRC-20 EVM** | Executes state transitions deterministically                                   |

<Info>
  **Roadmap — Force exit mechanism**: A force exit mechanism is planned to eliminate sequencer liveness trust. This will allow users to withdraw funds directly on-chain if the sequencer becomes unresponsive, ensuring users are never locked out of their assets.
</Info>

### Bitcoin finality and reorg handling

The system monitors block hashes on both Bitcoin and BRC-20 chains. On reorg detection:

<Steps>
  <Step title="Detection">
    Block hash mismatch triggers the reorg handler.
  </Step>

  <Step title="Wait for sync">
    System waits for BRC-20 to process the reorg.
  </Step>

  <Step title="Find divergence">
    Locate the last confirmed (correct) block height.
  </Step>

  <Step title="Rollback state">
    Clear executed batches and operations after the divergence point.
  </Step>

  <Step title="Preserve snapshots">
    Verified historical balances and pairs up to the last correct block are retained.
  </Step>

  <Step title="Reprocess">
    Re-execute all blocks to rebuild current state.
  </Step>
</Steps>

### Emergency stop

The sequencer includes a circuit breaker that activates automatically when unexpected failures or state mismatches are detected. When active, all new operations are rejected until the issue is resolved. This protects user funds from being processed during an inconsistent state.

### Transaction ordering

Operations are processed in **strict FIFO (First In, First Out) order**. The sequencer cannot reorder transactions within a batch, eliminating the possibility of sequencer-initiated front-running or MEV extraction.

***

## Audits

The smart contracts have been audited by Hashlock, an independent security firm.

| Auditor  | Scope                                             | Date          | Rating |
| -------- | ------------------------------------------------- | ------------- | ------ |
| Hashlock | BiS\_Swap, bls12lib.sol & Uniswap Smart Contracts | November 2025 | Secure |

For the full audit report and additional information, visit [hashlock.com/audits/best-in-slot](https://hashlock.com/audits/best-in-slot).
