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, positionsarrow-up-right are the double mapping that keeps track of each position's lockedCollateral and debtShare.

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

positionsarrow-up-right 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 CollateralTokenarrow-up-right variable increase temporarilyarrow-up-right, 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 CollateralTokenarrow-up-right decreases as much as withdrawnarrow-up-right.

Three functions are directly involved in lockedCollateral accounting.

fn adjustPositionarrow-up-right in BookKeeper.

fn moveCollateralarrow-up-right in BookKeeper.

fn withdrawarrow-up-right in CollateralTokenAdapter.

fn depositarrow-up-right in CollateralTokenAdapter.

Last updated