Collateral Accounting

This section provides a deep understanding of how the accounting of collateral is done in the BookKeeper contract.

Where is a position's collateral recorded?

Each position's collateral amount and debt are recorded in the BookKeeper contract. In the BookKeeper contract, positions are the double mapping that keeps track of each position's lockedCollateral and debtShare.

mapping(bytes32 => mapping(address => Position)) public positions;

positions mapping has the value as Position struct, and the struct's first member, lockedCollateral keeps track of the collateral.

struct Position {
    uint256 lockedCollateral; // Locked collateral inside this position
    uint256 debtShare;
}

How is a position's collateral recorded?

position.lockedCollateral represents the amount of collateral locked in a specific position. It serves as the primary reference to determine the amount of collateral a particular position holds. The value of position.lockedCollateral increases when a position is opened and decreases when it is closed. During the position opening flow, the value of CollateralToken variable increase temporarily, and later gets transferred to position.lockedCollateral.

mapping(bytes32 => mapping(address => uint256)) public collateralToken;

Similarly, the position value.lockedCollateral is temporarily transferred to the CollateralToken variable during the position closing flow. Then, when the collateral gets withdrawn from CollateralTokenAdapter, the temporarily increased number on CollateralToken decreases as much as withdrawn.

Three functions are directly involved in lockedCollateral accounting.

fn adjustPosition in BookKeeper.

fn moveCollateral in BookKeeper.

fn withdraw in CollateralTokenAdapter.

fn deposit in CollateralTokenAdapter.

Last updated

Copyright© Fathom App 2024.