> For the complete documentation index, see [llms.txt](https://stoxfi.gitbook.io/stoxfi-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://stoxfi.gitbook.io/stoxfi-docs/smart-contract-architecture.md).

# Smart Contract Architecture

StoxFi is built around three principal smart contracts.

1. `StoxVault`
2. `ConfidentialStock`
3. `StoxRegistry`

StoxVault operates on Robinhood Chain.

ConfidentialStock and StoxRegistry operate on Ethereum.

The contracts are not proxies and do not contain an upgrade mechanism.

### Contract Architecture

**StoxFi Smart Contract Architecture**

<figure><img src="https://2963579709-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FdIccUwMy0hIW7yzdERSR%2Fuploads%2FQ69j89ep3nNyvRlK2MlF%2Fstoxfi-smart-contract-architecture.png?alt=media&amp;token=34572e03-2ab0-444f-ba29-78d107617e96" alt=""><figcaption></figcaption></figure>

StoxVault controls custody of the underlying asset. ConfidentialStock controls its encrypted representation. StoxRegistry provides asset discovery.

Cross chain instructions connect StoxVault and ConfidentialStock without transferring the underlying token between chains.

### Compiler Configuration

The production contracts share the following compiler configuration.

| Setting        | Configuration |
| -------------- | ------------- |
| Solidity       | `0.8.27`      |
| Optimizer      | Enabled       |
| Optimizer runs | `200`         |
| EVM version    | `cancun`      |
| viaIR          | `true`        |
| Upgradeability | None          |
| Contract model | Non proxy     |

The contracts are immutable after deployment.

Changes that require modifying contract logic therefore require a new deployment.

### StoxVault

`StoxVault` is deployed on Robinhood Chain.

It is responsible for custody of the underlying ERC 20 assets and for coordinating the public side of the shield and redemption lifecycle.

StoxVault inherits:

`CCIPReceiver`

`Ownable2Step`

`ReentrancyGuard`

`Pausable`

#### Core Responsibilities

StoxVault performs the following functions:

1. Receives underlying assets during shielding
2. Verifies the exact quantity received
3. Converts between underlying and confidential decimals
4. Tracks collateral for each stock
5. Dispatches confidential mint instructions
6. Receives collateral release instructions
7. Releases underlying assets following valid redemption
8. Maintains the relationship between supported stocks and their confidential peers

#### Key Functions

| Function          | Role                                                 |
| ----------------- | ---------------------------------------------------- |
| `deposit`         | Receives an underlying asset and initiates shielding |
| `registerStock`   | Registers a supported stock                          |
| `setPeer`         | Configures the confidential peer                     |
| `previewDeposit`  | Previews deposit conversion                          |
| `quoteDepositFee` | Quotes the cross chain message fee                   |
| `_ccipReceive`    | Processes inbound release instructions               |
| `pause`           | Pauses supported operations                          |
| `unpause`         | Restores operation                                   |
| `rescueToken`     | Rescues eligible tokens                              |
| `withdrawNative`  | Withdraws native token held by the contract          |

#### Key State

StoxVault maintains:

`lockedOf[stock]`

`stockOfPeer[peer]`

`processedMessages[msgId]`

`confidentialChainSelector`

`confidentialChainSelector` is immutable.

`lockedOf[stock]` tracks the underlying collateral associated with the live confidential representation.

`stockOfPeer[peer]` maps a confidential peer to its corresponding underlying stock.

`processedMessages[msgId]` provides cross chain replay protection.

#### Key Events

StoxVault emits:

`Deposited`

`Released`

`StockRegistered`

`PeerConfigured`

These events expose the public lifecycle occurring on the custody side of StoxFi.

#### Access Control

Stock registration, pausing, and rescue operations are restricted to the owner.

Inbound cross chain messages must first arrive through the configured CCIP Router.

StoxVault then validates the source chain and registered peer before processing the message.

#### Exact Receipt Protection

StoxVault verifies the token balance change when accepting a deposit.

This prevents a token that deducts value during transfer from producing confidential supply larger than the quantity actually received by the vault.

#### Collateral Constraint

StoxVault maintains the relationship:

`lockedOf[stock] = live confidential supply × rate`

Collateral release is capped by `lockedOf[stock]`.

The vault therefore cannot release more of a stock than the quantity recorded as locked for that asset.

### ConfidentialStock

`ConfidentialStock` operates on Ethereum.

One ConfidentialStock instance represents one supported stock.

The contract uses a fixed 6 decimal confidential representation.

ConfidentialStock inherits:

`ZamaEthereumConfig`

`CCIPReceiver`

`Ownable2Step`

`ReentrancyGuard`

`Pausable`

#### Core Responsibilities

ConfidentialStock performs the following functions:

1. Maintains encrypted balances
2. Creates encrypted balances following validated shield instructions
3. Executes confidential transfers
4. Prevents encrypted arithmetic from wrapping
5. Creates redemption requests
6. Burns confidential value before redemption
7. Makes redemption values publicly decryptable
8. Verifies redemption proofs
9. Dispatches collateral release instructions

#### Key Functions

| Function                | Role                                                          |
| ----------------------- | ------------------------------------------------------------- |
| `confidentialTransfer`  | Transfers an encrypted amount between accounts                |
| `requestRedeem`         | Burns confidential value and creates a redemption request     |
| `finalizeRedeem`        | Verifies the decrypted value and initiates collateral release |
| `cancelEmptyRedeem`     | Cancels an empty redemption request                           |
| `confidentialBalanceOf` | Returns the confidential balance handle                       |
| `redeemHandle`          | Returns the encrypted handle associated with redemption       |
| `setVault`              | Configures the bound StoxVault                                |
| `_ccipReceive`          | Processes inbound mint instructions                           |

`confidentialTransfer` has two overloads.

`requestRedeem` also has two overloads.

#### Encrypted State

ConfidentialStock maintains:

`_balances[account] → euint64`

`_totalSupply → euint64`

`_redeemRequests[id]`

`vault`

`processedMessages`

User balances and total supply therefore remain encrypted rather than being stored as ordinary public token values.

#### Key Events

ConfidentialStock emits:

`ConfidentialMint`

`ConfidentialTransfer`

`RedeemRequested`

`RedeemFinalized`

`RedeemCancelled`

`VaultConfigured`

The `ConfidentialTransfer` event contains participant addresses without exposing the transfer amount.

#### Mint Authority

ConfidentialStock does not contain an administrative mint function.

Minting can occur only after the contract receives a valid cross chain instruction from its bound StoxVault.

The message must pass the router, source chain, sender, and replay checks before the encrypted balance can be created.

#### Transfer Authorization

The handle based transfer functions use sender permission checks before encrypted values can be used.

This prevents an account from naming an encrypted handle that it was never granted permission to use.

#### Clamped Arithmetic

ConfidentialStock uses clamped encrypted arithmetic.

Credits are prevented from wrapping beyond the supported confidential range.

Debits are limited before subtraction.

Encrypted selection determines whether the requested value or zero should be applied.

These controls operate without revealing the encrypted balance.

### StoxRegistry

`StoxRegistry` operates on Ethereum.

Its role is asset discovery.

The registry inherits:

`Ownable2Step`

It does not hold underlying collateral.

It does not maintain confidential balances.

It does not authorize minting or redemption.

A registry entry can therefore affect what a frontend displays without granting control over funds.

Listings can be activated or deactivated using `setActive`.

### Contract Relationships

StoxVault and ConfidentialStock form the value carrying relationship in StoxFi.

StoxVault holds the underlying collateral.

ConfidentialStock maintains the corresponding encrypted representation.

StoxRegistry sits outside that value path and provides discovery only.

The relationship between StoxVault and ConfidentialStock is configured through:

`setPeer`

and

`setVault`

Both bindings are one time configurations.

Once configured, they cannot be changed.

This prevents an existing contract from being repointed to a different trust anchor.

A configuration mistake therefore requires redeployment.

### Ownership Model

The production contracts use `Ownable2Step`.

This provides a two step ownership transfer process.

Within StoxVault, ownership controls functions including stock registration, pausing, and eligible rescue operations.

Within ConfidentialStock, ownership does not provide an administrative mint path.

The owner also cannot use the contract to replace an already configured vault relationship.

### Pausing

StoxVault and ConfidentialStock inherit `Pausable`.

This provides an administrative mechanism for pausing supported operations.

The current deployed contracts were not paused at the recorded implementation state.

### Reentrancy Protection

StoxVault and ConfidentialStock inherit `ReentrancyGuard`.

This protection is applied alongside the contract specific custody, encrypted balance, and cross chain validation controls.

### Immutable Deployment Model

StoxFi does not currently use upgradeable proxy contracts.

The deployed contract logic cannot be replaced through a proxy upgrade.

This removes a contract upgrade path from the architecture.

It also means that a contract level change requires redeployment.

The same applies to an incorrect one time vault or peer configuration.

### Test Contracts

The implementation also contains three contracts used for testing and demonstration.

| Contract                 | Purpose                                                   |
| ------------------------ | --------------------------------------------------------- |
| `MockStockToken.sol`     | Stand in tokenized stock used on testnet                  |
| `MockCCIPRouter.sol`     | Local CCIP simulation used in tests                       |
| `FeeOnTransferToken.sol` | Adversarial token used to verify exact receipt protection |

`MockStockToken` has an unrestricted public mint function.

It is test scaffolding and is the contract used for the current NVDA, TSLA, and NFLX demonstration tokens.

`MockCCIPRouter` is used for local testing rather than the live cross chain deployment.

`FeeOnTransferToken` is used to demonstrate that StoxVault rejects deposits where the expected quantity is not actually received.

### Contract Architecture Summary

The StoxFi contract architecture separates three responsibilities.

**StoxVault manages collateral.**

**ConfidentialStock manages confidential value.**

**StoxRegistry manages discovery.**

The value carrying relationship between StoxVault and ConfidentialStock is fixed through one time peer configuration.

Cross chain minting is restricted to the bound vault.

Collateral release is restricted to validated messages from the bound confidential peer.

The registry remains outside the value path.

Together, these contracts form the onchain foundation of StoxFi.


---

# 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://stoxfi.gitbook.io/stoxfi-docs/smart-contract-architecture.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.
