A look at how deposits and withdrawals of the STX token in the LST protocol work
Deposits
A user can join the protocol and deposit their STX anytime. This does not mean their STX tokens are earning yield immediately. A STX deposit only becomes active once the subsequent PoX stacking cycle starts. This can take up to two weeks (2100 Bitcoin blocks).
Furthermore, the protocol should calculate, behind the scenes, how much total inflow there is in a given cycle against the total outflow. Based on this, more STX tokens will be stacked (net inflow), no extra tokens will be stacked (inflow equals outflow) or if STX tokens need to be taken out of PoX and withdrawn by users (net outflow).
To handle smooth deposits, there will be a deposit โcut-offโ for when the last STX tokens would be accepted for the next PoX cycle (the end period). As an example, this could be the last 60 Bitcoin blocks before the new stacking cycle, where this is enforceable on-chain. Either way, when depositing STX, the user receives stSTX at a shown UI ratio (which is calculated & enforced in Clarity).
Some sample code to do the above can be seen below:
In the above logic, the deposit function starts with requesting the next cycle ID from PoX (which is a positive number such as 65, 70 or whatever the current cycle ID is). Next, it requests the amount of deposits that have already happened so far in the cycle that is currently accepting deposits. The bulk of the logic in the function takes in STX from the tx-sender and keeps track of the deposits per cycle and the total amount of deposits. After this, an amount of stSTX will be minted based on the STX/stSTX ratio (discussed in another section).
Withdrawals
A user who wants to withdraw STX from the protocol (and burn their stSTX position) has two options:
Instant Withdrawal
End-of-Cycle Withdrawal
Instant Withdrawal
burn your stSTX to withdraw STX at a penalty (needs liquidity, but is profitable for market makers, they get the liquidity after PoX cycle ends and profitable)
End-of-Cycle Withdrawal
This way of withdrawing is the preferred method for any users when they do not want to incur a penalty. In this case, a user burns their stSTX position and receives an NFT that represents the position, which can be used to withdraw the STX at any time after the current PoX cycle ended.
Some sample code for the above logic could be as follows:
In the above implementation, no NFT is minted but the withdrawal request is kept in the contract using the withdrawals-by-adress method. Either method works, but the NFT method is preferred in production as it serves a double function. It helps the protocol to identify the position of the user, the position is still transferrable and it can be used as a reminder to the user that the protocol still owes STX to the user. The same init-withdraw method also burns the amount of stSTX sent into the method.
In the next section, we will look at how the STX per stSTX ratio is calculated.