<!-- canonical: https://0xsimao.com/findings/ostium-storage-index-overwrite-found -->

# In OstiumTradingStorage, firstEmptyTradeIndex() and firstEmptyOpenLimitIndex() overwrite index 0 if not found

Crit/High · Three Sigma · RWA perpetuals DEX · 19th February, 2024

Finding 3S-OS-C01 of the Ostium security review.

- Protocol: https://www.ostium.com/
- Report: /reports/ostium
- Source: https://cdn.sanity.io/files/qoqld077/production/a95b9c69e0f65d1d6b0e649f0d62a362358ca8ce.pdf

---

### Description

[OstiumTradingStorage::firstEmptyTradeIndex()](https://github.com/0xOstium/smart-contracts-threeSigma/blob/audit-feedback/src/OstiumTradingStorage.sol#L383) and
[OstiumTradingStorage::firstEmptyOpenLimitIndex()](https://github.com/0xOstium/smart-contracts-threeSigma/blob/audit-feedback/src/OstiumTradingStorage.sol#L392) return index 0 if they can not find an
available index. This may lead to overwriting a trade in storeTrade() if, for example, a trader
has 2 trades, opens a third one via market order, but the Gov frontruns the chainlink bot
OstiumPriceUpKeep() and sets _maxTradesPerPair to 2. It will overwrite the trade in the
[callback](https://github.com/0xOstium/smart-contracts-threeSigma/blob/audit-feedback/src/OstiumTradingCallbacks.sol#L132), more specifically in [OstiumTradingCallbacks::registerTrade()](https://github.com/0xOstium/smart-contracts-threeSigma/blob/audit-feedback/src/OstiumTradingCallbacks.sol#L427) and lastly in
[OstiumTradingStorage::storeTrade()](https://github.com/0xOstium/smart-contracts-threeSigma/blob/audit-feedback/src/OstiumTradingStorage.sol#L146).

### Recommendation

Revert if it can not find an available open trade / limit order slot instead of returning index 0.

### Status

Addressed in [#21e90e7](https://github.com/0xOstium/smart-contracts-threeSigma/pull/58/commits/21e90e747638e3dffe2e3446504507d3e7a11c40).

---

Related findings:

- [open-term-loan-private: check dateFunded!=0 first to save gas.](https://0xsimao.com/findings/maple-finance-iii-term-date-funded-gas): Maple Finance
