Cyfrin / foundry-defi-stablecoin-cu

241 stars 107 forks source link

Balance of the liquidated user not updated in token's contract #51

Closed rdf5 closed 9 months ago

rdf5 commented 9 months ago

Maybe this question is stupid, but could someone explain me how the balance of a user being liquidated would be updated in the ERC-20 token's contract?

I can see that in DSCEngine.sol the amount of tokens minted by the user is removed:

s_DSCMinted[onBehalfOf] -= amountDscToBurn;

But in DecentralizedStableCoin.sol, the mapping with the balances inherited from the ERC20 contract is not updated. Wouldn't then the user be still owning there the token?

PatrickAlphaC commented 9 months ago

That's right!

So the original minter keeps the token, but their debt is removed.

It looks like this:

  1. User A deposits $10 of collateral and mints $5 of stablecoin.
  2. When minting a stablecoin, you can sort of think of it as debt to the protocol:

User A's balance: $5 of Stablecoin User A's DSCEngine.sol Debt: -$5 of stablecoins User A's DSCEngine.sol Collateral: $10 of ETH User A Total: $10

  1. The value of their collateral drops to $4 (ETH price tanks or something), so now, their $5 stablecoin is only collateralized by $4, oh no! We have to fix this!
  2. They get liquidated by User B. User B mints $5 of stablecoins, and then immediately burns them on behalf of User A, essentially returning User A's stablecoins for them.

New Balances:

User A's balance: $5 of Stablecoin User A's DSCEngine.sol Debt: $0 of stablecoins (PAID OFF BY USER B) User A's DSCEngine.sol Collateral: 0 (TOOK BY USER A) User A Total: $5

User B's balance: $10 of ETH (THEY TOOK USER A'S COLLATERAL) User B's DSCEngine.sol Debt: -$5 of stablecoins User B's DSCEngine.sol Collateral: $5 of ETH User B's Total: $10

Does that make sense?

rdf5 commented 9 months ago

Thanks Patrick for your reply!

However, I was wondering if that mechanism would imply that the DSC token may not retain its stability or value when traded on external platforms, as its intrinsic stability was initially tied to the collateral held within the decentralized stablecoin ecosystem.

For example, what would happen if now User A decides to swap DSC for another token in Uniswap?

PatrickAlphaC commented 9 months ago

Good question!

For example, what would happen if now User A decides to swap DSC for another token in Uniswap?

Since we are using a price oracle (chainlink) in this system where users can always redeem their stablecoin for an equal amount of collateral, the idea is the price will stay the same even when traded.

Someone knows that no matter what, if they have 5 DSC, they can always redeem it for $5 of collateral on the DSCEngine, and that's how the price stays stable.

However, we've seen that in practice, supply and demand still have an effect. This demo contract is based on DAI and you can see from it's price chart, that sometimes it fluctuates from the $1 mark!

Screenshot 2023-12-03 at 9 24 32 PM