Skip to content

About

Blubbo's smart contracts running on TON.

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

blubbo-contracts

blubbo test status blubbo test status blubbo test status blubbo test status blubbo test status

BlubboFi

This is a repository containing the following deployable contracts:

  • blubbo_master.fc
  • blubbo_user.fc
  • single_owner_ton_wallet.fc
  • owner_upgradable.fc

These contracts are the foundation of money market infrastructure.

Introduction

When we say "money market" or "lending protocol", essentially, it means a set of smart contracts with five main features:

  1. Deposit
  2. Withdraw
  3. Borrow
  4. Repay
  5. Liquidate

All other major lending protocols on any other chains will always have these five basic functionalities. If you are new to a lending protocol, you can try using a few of the well-known lending protocols, such as Aave or Compound. Reviewing their documentations would help a lot as well: Aave Docs, Compound. If you need more inspirations, see DefiLlama's lending protocols list.

In essence, a money market is where people deposit or borrow money based on their economic incentives. Here're a few examples:

  1. Earning interest: You have 100 USDT, and instead of just holding it in your wallet, you want to generate yield from it. You deposit 100 USDT into the lending pool, and others borrow USDT from that pool. Because the borrowers are benefiting from borrowing money to achieve their own goals, they pay interests. Then, the interests will be paid towards to the depositors as well as the protocol (us). Then you would be able to withdraw more than 100 USDT after some time, because you earned interests.
  2. Access to liquidity without selling:
    • Long: You hold 100 USD worth of TON, but you don't want to exit your position holding TON. You think that wBTC is going to go up in value, so you deposit 100 USD worth of TON first into the protocol, and borrow 80 USDT based on that collateral. You now instantly go to ston.fi, and swap your 80 USDT into 80 USD worth of wBTC. Now you hold wBTC until it increases in price. After a few days, your wBTC is now worth 120 USD. You go to ston.fi again, and swap all of your wBTC into 120 USDT, and pay back 80 USDT + little bit of interests accrued to the protocol. Now you have made about 40 USDT of profits just by holding 100 USD worth of TON.
    • Short: You hold 100 USDT, and you think TON is going to go down in price. You deposit 100 USDT, and borrow 80 USDT worth of TON (let's say, 10 TON). You instantly go to ston.fi and swap 80 USDT worth of TON into 80 USDT. Now you just wait until TON's price drops. After a few days, 10 TON is now only worth 50 USDT. You go to ston.fi and swap your 50 USDT into approximately 10 TON. Now you repay about 10 TON back to the protocol for your debt as well as your interests. Then you have a profit of about 30 USDT.
  3. Leveraging:
    • You are so sure that TON is going to go up in price, so you deposit 100 USD worth of TON (let's say the TON/USDT price is 8 USDT, so 12.5 TON), and borrow 80 USDT.
    • You purchase 80 USD worth of TON (= 10 TON), and you deposit that again into the protocol.
    • Now, based on the newest deposit, you borrow 64 USDT. You purchase 8 TON again with that.
    • Now, the price of TON/USDT increases to 10 USDT. Then, you go to ston.fi, and sell off 8 TON first, and get 80 USDT. You repay for the last borrowing, which was 64 USDT. You make 16 USDT of profit.
    • You withdraw the second last deposit of TON, which was 10 TON. 10 TON is now worth 100 USDT. You swap it into USDT, repay for 80 USDT of debt, and make 20 USD of profit.
    • Lastly, You withdraw the original deposit of 12.5 TON, which is now worth 125 USDT. You swap it into 125 USDT.
    • If you only held 12.5 TON and didn't do anything with it, the profit would have been 25 USD after the price of TON increased to 10 USDT.
    • However, if you looped your assets to leverage your position, you would have profited by additional 36 USD on top of the existing 25 USD.
  4. Further yield generation: you deposit 100 USDT into the protocol, and borrow some TON. You deposit that TON into DEX pools like ston.fi, and get more yield from the pool as a reward for liquidity provision.

If you are new to lending, I would recommend that you read my article on DeFi lending.

Dealing with Toncoin transfers

Sending and receiving Toncoin is a lot different from doing it with jettons. This will require us to handle deposit, withdrawal, borrowing, repayment and liquidation differently for toncoin and other jettons. If we want to make this easier, we need to find a way to unify the mechanics.

One great example is pton-contracts by ston.fi. Essentially, it's a wrapped toncoin that acts like a jetton. However, we don't even need that; this is because only BlubboMaster will need to hold the wrapped toncoin, and users can hold normal, 'unwrapped' toncoin, which is a little bit different from the jetton contract design where there is one minter and many jetton wallets. In our design, which we call Single Owner Ton Wallet (SOTW), we only have one contract where everything happens. This helps us reduce the gas fee and simplify the design further.

Transfer to BlubboMaster

Example: Alice transfers 10 TON to BlubboMaster

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Alice Wallet
    participant BlubboMaster's SOTW
    participant BlubboMaster
    alt Transfer succeeds
        Note over Alice Wallet,BlubboMaster's SOTW: send 10 toncoin + gas <br/> tokenize toncoin in SOTW's storage
        Alice Wallet->>BlubboMaster's SOTW: op::transfer
    else Transfer fails
        Note over Alice Wallet,BlubboMaster's SOTW: toncoin is automatically returned
        BlubboMaster's SOTW->>Alice Wallet: bounce
    end
    Note over BlubboMaster's SOTW,BlubboMaster: carry the remaining gas <br/> except the tokenized amount
    BlubboMaster's SOTW->>BlubboMaster: op::transfer_notification
Loading

Transfer out of BlubboMaster

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Alice Wallet
    participant BlubboMaster's SOTW
    participant BlubboMaster
    Note over BlubboMaster,BlubboMaster's SOTW: send instruction to send toncoin <br /> (no actual toncoin sent except gas)
    BlubboMaster->>BlubboMaster's SOTW: op::transfer
    alt Transfer notification succeeds
        Note over Alice Wallet,BlubboMaster's SOTW: send actual toncoin <br/>along with transfer notification
        BlubboMaster's SOTW->>Alice Wallet: op::transfer_notification
    else Transfer notification fails
        Note over Alice Wallet,BlubboMaster's SOTW: toncoin is returned back <br/> restore storage toncoin balance
        Alice Wallet->>BlubboMaster's SOTW: bounce
    end
Loading

No other ops such as Alice instructing BlubboMaster's SOTW to transfer out to her own wallet would be possible, because the protocol wouldn't have that use case anyway.

Note that in the following sequence diagrams below, we only show operations with a jetton (that is, not a toncoin). The only difference is that there is an additional step in transferring the jetton, like below:

An example of transferring a jetton into BlubboMaster

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Alice Wallet
    participant Alice USDT Wallet
    participant BlubboMaster USDT Wallet
    participant BlubboMaster
    Note over Alice Wallet,Alice USDT Wallet: send an instruction to send 10 USDT
    Alice Wallet->>Alice USDT Wallet: op::transfer
    Note over Alice USDT Wallet,BlubboMaster USDT Wallet: subtract and add USDT balance
    Alice USDT Wallet->>BlubboMaster USDT Wallet: op::internal_transfer
    Note over BlubboMaster USDT Wallet,BlubboMaster: notify BlubboMaster
    BlubboMaster USDT Wallet->>BlubboMaster: op::transfer_notification
Loading

As you can see, in a jetton transfer, there are two distinct wallets belonging to each account. But in the case of toncoin transfer, there is only one contract doing the bookkeeping. The reason for this is that the SOTW is only meant to transfer out to users, and receive transfer ins from the users. This business requirement allows us to have a single contract instead of having two.

Deposit

The ideal workflow without any errors has a bg color in dark green.

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Alice Wallet
    participant Alice USDT Wallet
    participant BlubboMaster USDT Wallet
    participant BlubboMaster
    participant Alice BlubboUser

    rect rgb(25, 126, 70)
        Alice Wallet->>Alice USDT Wallet: op::transfer

        Alice USDT Wallet->>BlubboMaster USDT Wallet: op::internal_transfer
    end

    rect rgb(25, 126, 70)
        par
            Note over BlubboMaster USDT Wallet,Alice Wallet: return excess gas to Alice's wallet <br/> (only applicable to non-toncoin jettons)
            BlubboMaster USDT Wallet->>Alice Wallet: D1: op::return_excess
        and
            Note over BlubboMaster USDT Wallet,BlubboMaster: update accumulators <br/> update rates <br/> do not adjust total available/debt yet
            BlubboMaster USDT Wallet->>BlubboMaster: D1: op::transfer_notification
        end
    end

    alt No error caught at BlubboMaster
        rect rgb(25, 126, 70)
            Note over BlubboMaster,Alice BlubboUser: non-bounceable (must succeed)
            BlubboMaster->>Alice BlubboUser: D2: op::deposit_from_blubbo_master_to_blubbo_user

            Note over Alice BlubboUser,Alice Wallet: return the remaining toncoin being used for gas
            Alice BlubboUser->>Alice Wallet: D3: op::return_excess
        end
    else Error caught at BlubboMaster
        BlubboMaster->>BlubboMaster USDT Wallet: D2: op::transfer
        BlubboMaster USDT Wallet->>Alice USDT Wallet: op::internal_transfer
    end
Loading

To understand how deposit works, it is crucial to first know how Jettons work on TON. If you are unsure, please revisit the documentation about Jettons on TON.

When Alice, a user of BlubboFi, wants to deposit USDT to BlubboFi, her wallet will send a message with op::transfer opcode to her USDT Jetton wallet.

Then, her USDT Jetton wallet will send another message with op::internal_transfer opcode to Blubbo Master contract's USDT Jetton wallet.

Alice would need to include forward_ton_amount and forward_payload in op::transfer message, because it is imperative that op::transfer_notification needs to reach Blubbo Master contract.

A naive user without knowing this documentation or a proper SDK might omit forward_ton_amount and forward_payload when sending a deposit. Then, this will only credit the sent Jetton to Blubbo Master's Jetton wallet contract, without triggering any of the further steps that need to be taken to properly update storage variables in the Blubbo Master and the Blubbo User contracts. Essentially, the user will have no way of withdrawing the Jetton back.

Upon receving op::transfer_notification message, the Blubbo Master contract will update its storage variables. The TL-B scheme of the storage is defined at blubbo_master/storage_reader.fc. Most importantly, it contains a dictionary, with all supported Jettons (and native toncoin) as keys and their respective 'reserve' variables as values.

A reserve is a term that is used to denote 'asset' or 'jetton' supported on the protocol. The reserve variables would contain various pieces of information about that reserve, such as enabled, decimals, borrow_factor_pct, ... and so on.

Here's the expected behavior of the Blubbo Master contract in summary upon receiving op::transfer_notification message:

  1. lending, debt accumulators, and pending amount to treasury are updated.
  2. total raw deposit balance is increased by the amount of deposit. 'Raw' hereinafter means 'market value', which means the opposite of 'face value'. 'Face value' is the value including the earned interest.
  3. lending and borrowing interest rates are updated.
  4. op::deposit_from_blubbo_master_to_blubbo_user message is sent to the Blubbo User contract of the depositor. The message would contain the raw deposited amount, so the Blubbo User contract can store that data. If the depositor doesn't own the Blubbo User contract, the Blubbo Master contract will deploy the Blubbo User contract by sending the op::deposit_from_blubbo_master_to_blubbo_user message.

Withdrawal

We are not sending a message to where the deposit balance data is stored. We need to send a message from BlubboMaster to BlubboUser, which is one more message in total compared to the previous withdrawal route. So this method has one more route, but has a big advantage: it allows us to take necessary data stored in BlubboMaster (for example, collateral factors for each supported jetton) and send it to BlubboUser together.

At first glance, it might be difficult to understand why the user will first send a message to BlubboMaster contract rather than the BlubboUser contract, because this doesn't seem quite intuitive according to TON's development principles.

If we wanted to make the user send a message first to the BlubboUser contract, it would look like this:

Approach 1: Send a message to the BlubboUser contract first

Withdrawal route 1

  1. User computes his BlubboUser contract address and the raw amount to be withdrawn off-chain.
  2. The derivation of BlubboUser contract address is just like that of a jetton wallet address. See token-contract/ft/jetton-utils.fc for reference. For convenience, BlubboMaster contract has a get method called fetch_blubbo_user_address that would receive the user's wallet address as an input and return the computed BlubboUser address.
  3. The user retrieves the signed price data from the oracle. See BlubboFi/blubbofi-contracts/tests/MiscTest.spec.ts for reference.
  4. The user sends the raw amount, price data, and signed configuration data. The configuration data is signed by a designated cold wallet owned by us. Using the config data, we make sure that the price data is signed by the addresses that we trust (Redstone Oracle signers), and the order of prices is in the designated order (in the ascending order of reserve ids), and compute collaterals with the collateral factor. However this approach values efficiency over decentralization. This will not be helpful in later stages when we want to form a DAO for example. However, this approach removes the need to make a round trip from the BlubboMaster contract.
  5. The BlubboUser contract checks that the user has more raw amount than requested. In case the user has borrowings, it checks that it has enough collaterals. Then it will send a message to BlubboMaster and it will send a jetton transfer message from there.

So we are not going to use this approach, primarily because of the centralization risk. If we use this method, users will have to trust that we are not using some unfavorable collateral factor when we are allowing them to withdraw their assets.

Approach 2: Send a message to the BlubboMaster contract (we use this)

  1. User sends a message to the BlubboMaster contract. The message has face amount requested, reserve_id of jetton to withdraw, and signed oracle price data, and signed config. The signed config will be used to verify that the signed oracle data is valid. The reason for using the signed config is as follows:
    • It is much easier to update the config together with the signed oracle data, for example, in case of an addition of an oracle data feed.
    • Data feed ids and signers need to be stored as tuples on chain. Storing tuple, although possible, is gas-consuming and requires serializing it into a cell first. Later, when needed, it needs to be deserialized into a tuple again. This is not the most efficient way.
    • Of course, users will still need to trust that the config signer will not use the signed config to his favor, for example, signing the oracle data feed with a different order, so that withdrawal or liquidation can be done without mathematically correct checks.
  2. The BlubboMaster contract takes the following variables from the storage: (latest updated) lending accumulator, collateral factor per jetton, borrowing factor per jetton, and sends it to the BlubboUser contract together with the data included in the message in the first step.
  3. The BlubboUser contract subtracts by the raw amount, and checks overcollateralization, and sends message to the BlubboMaster contract again to trigger transfer message.
  4. The BlubboMaster contract contract multiplies the raw amount by the latest lending accumulator again (because time has elapsed) to get the face amount. This face amount will be a little bit larger than the original requested amount due to the time difference between the initial and the last message. Finally, the total raw deposit amount is subtracted. At this point, the requested face amount will be a little bit more than requested, but this is by design and this is the limitation of async blockchain workflow.

It is very important that we handle each bounced message correctly, because failures can easily lead to the loss of funds. The simplest contract design is to revert the addition or the subtraction of the raw amount again at the BlubboUser contract whenever the amount has been debited already but the subsequent transaction fails.

The ideal workflow without any errors has a bg color in dark green.

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Alice USDT Wallet
    participant BlubboMaster USDT Wallet
    participant Alice Wallet
    participant BlubboMaster
    participant Alice BlubboUser

    rect rgb(25, 126, 70)
        Note over Alice Wallet,BlubboMaster: update accumulators and rates <br /> do not ⬇ total available yet <br/> non-bounceable
        Alice Wallet->>BlubboMaster: W0: op::withdraw_from_wallet_to_blubbo_master
    end

    alt Error caught at BlubboMaster
        Note over BlubboMaster,Alice Wallet: return the remaining toncoin being used for gas
        BlubboMaster->>Alice Wallet: W1: op::return_excess
    else No error at BlubboMaster
        rect rgb(25, 126, 70)
            Note over BlubboMaster,Alice BlubboUser: derease raw deposit <br/> activate withdrawal lock <br /> non-bounceable
            BlubboMaster->>Alice BlubboUser: W1: op::withdraw_from_blubbo_master_to_blubbo_user
        end
    end

    alt Error caught at BlubboUser
        Note over Alice BlubboUser,Alice Wallet: return the remaining toncoin being used for gas
        Alice BlubboUser->>Alice Wallet: W2: op::return_excess
    else No error at BlubboUser
        rect rgb(25, 126, 70)
            Note over Alice BlubboUser,BlubboMaster: update accumulators <br /> ⬇ total available <br /> update rates
            Alice BlubboUser->>BlubboMaster: W2: op::withdraw_from_blubbo_user_to_blubbo_master <br />
        end
    end

    alt Tx bounced at BlubboMaster
        Note over BlubboMaster,Alice BlubboUser: ⬆ raw deposit <br/> deactivate withdrawal lock
        BlubboMaster-->>Alice BlubboUser: W3: bounced message
        Note over Alice BlubboUser,Alice Wallet: return excess toncoin left after op::unlock_from_blubbo_master_to_blubbo_user
        Alice BlubboUser->>Alice Wallet: W4: op::return_excess
    else No error at BlubboMaster
        rect rgb(25, 126, 70)
            par
                Note over BlubboMaster,Alice BlubboUser: deactivate withdrawal lock <br/> non-bounceable
                BlubboMaster->>Alice BlubboUser: W3: op::unlock_from_blubbo_master_to_blubbo_user
            and
                Note over BlubboMaster,BlubboMaster USDT Wallet: trigger the transfer of requested amount of jetton <br/> non-bounceable
                BlubboMaster->>BlubboMaster USDT Wallet: W3: op::transfer
            end
        end
    end

    rect rgb(25, 126, 70)
        par
            Note over Alice BlubboUser,Alice Wallet: return excess toncoin left after op::unlock_from_blubbo_master_to_blubbo_user
            Alice BlubboUser->>Alice Wallet: W4: op::return_excess
        and
            Note over BlubboMaster USDT Wallet,Alice USDT Wallet: transfer requested amount of jetton
            BlubboMaster USDT Wallet->>Alice USDT Wallet: W4: op::internal_transfer
            Note over BlubboMaster USDT Wallet,Alice USDT Wallet: return excess toncoin being used for gas <br /> (standard jetton contract <br />  handles this automatically)
            Alice USDT Wallet->>Alice Wallet: W5: op::return_excess
        end

    end
Loading

Borrowing

The workflow is similar to the withdrawal. The only difference is that the accounting is done on the borrowing balance.

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Alice USDT Wallet
    participant BlubboMaster USDT Wallet
    participant Alice Wallet
    participant BlubboMaster
    participant Alice BlubboUser

    rect rgb(25, 126, 70)
        Note over Alice Wallet,BlubboMaster: update accumulators and rates <br /> do not ⬇ total available yet <br/> do not ⬆ total debt yet <br/> non-bounceable
        Alice Wallet->>BlubboMaster: B0: op::borrow_from_wallet_to_blubbo_master
    end

    alt Error caught at BlubboMaster
        Note over BlubboMaster,Alice Wallet: return the remaining toncoin being used for gas
        BlubboMaster->>Alice Wallet: B1: op::return_excess
    else No error at BlubboMaster
        rect rgb(25, 126, 70)
            Note over BlubboMaster,Alice BlubboUser: increase raw debt <br/> activate borrowing lock <br /> non-bounceable
            BlubboMaster->>Alice BlubboUser: B1: op::borrow_from_blubbo_master_to_blubbo_user
        end
    end

    alt Error caught at BlubboUser
        Note over Alice BlubboUser,Alice Wallet: return the remaining toncoin being used for gas
        Alice BlubboUser->>Alice Wallet: B2: op::return_excess
    else No error at BlubboUser
        rect rgb(25, 126, 70)
            Note over Alice BlubboUser,BlubboMaster: update accumulators <br /> update rates <br/> ⬇ total available <br /> ⬆ total debt
            Alice BlubboUser->>BlubboMaster: B2: op::borrow_from_blubbo_user_to_blubbo_master <br />
        end
    end

    alt Tx bounced at BlubboMaster
        Note over BlubboMaster,Alice BlubboUser: ⬇ raw debt <br/> deactivate borrowing lock
        BlubboMaster-->>Alice BlubboUser: B3: bounced message
        Note over Alice BlubboUser,Alice Wallet: return excess toncoin left after op::unlock_from_blubbo_master_to_blubbo_user
        Alice BlubboUser->>Alice Wallet: B4: op::return_excess
    else No error at BlubboMaster
        rect rgb(25, 126, 70)
            par
                Note over BlubboMaster,Alice BlubboUser: deactivate borrowing lock <br/> non-bounceable
                BlubboMaster->>Alice BlubboUser: B3: op::unlock_from_blubbo_master_to_blubbo_user
            and
                Note over BlubboMaster,BlubboMaster USDT Wallet: trigger the transfer of requested amount of jetton <br/> non-bounceable
                BlubboMaster->>BlubboMaster USDT Wallet: B3: op::transfer
            end
        end
    end

    rect rgb(25, 126, 70)
        par
            Note over Alice BlubboUser,Alice Wallet: return excess toncoin left after op::unlock_from_blubbo_master_to_blubbo_user
            Alice BlubboUser->>Alice Wallet: B4: op::return_excess
        and
            Note over BlubboMaster USDT Wallet,Alice USDT Wallet: transfer requested amount of jetton
            BlubboMaster USDT Wallet->>Alice USDT Wallet: B4: op::internal_transfer
            Note over BlubboMaster USDT Wallet,Alice USDT Wallet: return excess toncoin being used for gas <br /> (standard jetton contract <br />  handles this automatically)
            Alice USDT Wallet->>Alice Wallet: B5: op::return_excess
        end

    end
Loading

Repayment

The repayment and liquidation uses the same transfer notification. Because transfer notification (except for Toncoin transfers) is the last message that is sent in the chain of messages, we always assume that the user is repaying for some asset that he has a debt on.

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Alice Wallet
    participant Alice USDT Wallet
    participant BlubboMaster USDT Wallet
    participant BlubboMaster
    participant Alice BlubboUser

    rect rgb(25, 126, 70)
        Alice Wallet->>Alice USDT Wallet: op::transfer

        Alice USDT Wallet->>BlubboMaster USDT Wallet: op::internal_transfer
    end

    rect rgb(25, 126, 70)
        par
            Note over BlubboMaster USDT Wallet,Alice Wallet: return excess gas to Alice's wallet <br/> (only applicable to non-toncoin jettons)
            BlubboMaster USDT Wallet->>Alice Wallet: R0: op::return_excess
        and
            Note over BlubboMaster USDT Wallet,BlubboMaster: update accumulators <br/> update rates <br/> do not adjust total available/debt yet
            BlubboMaster USDT Wallet->>BlubboMaster: R0: op::transfer_notification
        end
    end

    alt No error caught at BlubboMaster
        rect rgb(25, 126, 70)
            Note over BlubboMaster,Alice BlubboUser: raw debt ⬇ <br/> activate repayment lock
            BlubboMaster->>Alice BlubboUser: R1: op::repay_from_blubbo_master_to_blubbo_user
        end
    else Error caught at BlubboMaster
        BlubboMaster->>BlubboMaster USDT Wallet: R2: op::transfer
        BlubboMaster USDT Wallet->>Alice USDT Wallet: R3: op::internal_transfer
    end

    alt No error at BlubboUser
        rect rgb(25, 126, 70)
            Note over Alice BlubboUser,BlubboMaster: update accumulators <br /> update rates <br/> ⬆ total available <br /> ⬇ total debt
            Alice BlubboUser->>BlubboMaster: R2: op::repay_from_blubbo_user_to_blubbo_master <br />
        end
    else Error caught at BlubboUser
        Note over Alice BlubboUser,BlubboMaster: send an op to BlubboMaster to trigger refund of repayment amount
        Alice BlubboUser->>BlubboMaster: R2: op::reject_jetton_from_blubbo_user_to_blubbo_master <br />

        BlubboMaster->>BlubboMaster USDT Wallet: R3: op::transfer

        BlubboMaster USDT Wallet->>Alice USDT Wallet: R4: op::internal_transfer
    end

    alt No error caught at BlubboMaster
        rect rgb(25, 126, 70)
            Note over BlubboMaster,Alice BlubboUser: deactivate repayment lock
            BlubboMaster->>Alice BlubboUser: R3: op::unlock_from_blubbo_master_to_blubbo_user
        end
    else Error caught at BlubboMaster
        par
            BlubboMaster->>BlubboMaster USDT Wallet: R3: op::transfer
            BlubboMaster USDT Wallet->>Alice USDT Wallet: R4: op::internal_transfer
        and
            Note over BlubboMaster,Alice BlubboUser: deactivate repayment lock <br/> raw debt ⬆
            BlubboMaster->>Alice BlubboUser: R3: op::increase_raw_debt_from_blubbo_master_to_blubbo_user
        end
    end

    rect rgb(25, 126, 70)
        Note over Alice BlubboUser,Alice Wallet: return excess toncoin left after op::unlock_from_blubbo_master_to_blubbo_user
        Alice BlubboUser->>Alice Wallet: R5: op::return_excess
    end
Loading

Liquidation

Example: Bob repays for Alice's stTON debt and takes USDT from Alice as a liquidation bonus.

%%{init: {'sequence': {'noteAlign': 'left'}}}%%
sequenceDiagram
    participant Bob Wallet
    participant Bob stTON Wallet
    participant BlubboMaster stTON Wallet
    participant BlubboMaster
    participant Alice BlubboUser
    participant Bob BlubboUser

    rect rgb(25, 126, 70)
        Bob Wallet->>Bob stTON Wallet: op::transfer

        Bob stTON Wallet->>BlubboMaster stTON Wallet: op::internal_transfer
    end

    rect rgb(25, 126, 70)
        par
            Note over BlubboMaster stTON Wallet,Bob Wallet: return excess gas to Alice's wallet <br/> (only applicable to non-toncoin jettons)
            BlubboMaster stTON Wallet->>Bob Wallet: L0: op::return_excess
        and
            Note over BlubboMaster stTON Wallet,BlubboMaster: update accumulators <br/> update rates <br/> do not adjust total available/debt yet
            BlubboMaster stTON Wallet->>BlubboMaster: L0: op::transfer_notification
        end
    end

    alt No error caught at BlubboMaster
        rect rgb(25, 126, 70)
            Note over BlubboMaster,Alice BlubboUser: raw debt ⬇ <br/> raw collateral ⬇ <br/> activate liquidation lock
            BlubboMaster->>Alice BlubboUser: L1: op::liquidate_from_blubbo_master_to_blubbo_user
        end
    else Error caught at BlubboMaster
        BlubboMaster->>BlubboMaster stTON Wallet: L2: op::transfer
        BlubboMaster stTON Wallet->>Bob stTON Wallet: L3: op::internal_transfer
    end

    alt No error at BlubboUser
        rect rgb(25, 126, 70)
            Note over Alice BlubboUser,BlubboMaster: update accumulators <br /> update rates <br/> ⬇ total debt <br/> ⬆ total available
            Alice BlubboUser->>BlubboMaster: L2: op::liquidate_from_blubbo_user_to_blubbo_master <br />
        end
    else Error caught at BlubboUser
        Note over Alice BlubboUser,BlubboMaster: send an op to BlubboMaster to trigger refund of liquidation amount
        Alice BlubboUser->>BlubboMaster: L2: op::reject_jetton_from_blubbo_user_to_blubbo_master <br />

        BlubboMaster->>BlubboMaster stTON Wallet: L3: op::transfer

        BlubboMaster stTON Wallet->>Bob stTON Wallet: L4: op::internal_transfer
    end

    alt No error caught at BlubboMaster
        rect rgb(25, 126, 70)
            par
                Note over BlubboMaster,Alice BlubboUser: deactivate liquidation lock
                BlubboMaster->>Alice BlubboUser: L3: op::unlock_from_blubbo_master_to_blubbo_user

                Note over Alice BlubboUser,Bob Wallet: return excess toncoin left after op::unlock_from_blubbo_master_to_blubbo_user
                Alice BlubboUser->>Bob Wallet: L4: op::return_excess
            and
                Note over BlubboMaster,Bob BlubboUser: send liquidated collateral + liquidation bonus collateral to Bob <br/> raw deposit ⬆
                BlubboMaster->>Bob BlubboUser: L3: op::move_collateral

                Note over Bob BlubboUser,Bob Wallet: return excess toncoin left after op::move_collateral
                Bob BlubboUser->>Bob Wallet: L4: op::return_excess
            end
        end
    else Error caught at BlubboMaster
        par
            BlubboMaster->>BlubboMaster stTON Wallet: L3: op::transfer
            BlubboMaster stTON Wallet->>Bob stTON Wallet: L4: op::internal_transfer
        and
            Note over BlubboMaster,Alice BlubboUser: deactivate liquidation lock <br/> raw debt ⬆ <br/> raw collateral ⬆
            BlubboMaster->>Alice BlubboUser: L3: op::cancel_liquidation_from_blubbo_master_to_blubbo_user

            Note over Alice BlubboUser,Bob Wallet: return excess toncoin left
            Alice BlubboUser->>Bob Wallet: L4: op::return_excess
        end
    end
Loading

Borrow factor

Review these docs:

A borrow factor is a risk-adjusted borrowing capacity ratio assigned to each asset. We follow Euler Finance's convention: it is the percentage of the asset that can be borrowed against a certain amount of collateral.

For example, given this table below:

TON USDT
Collateral factor 90% 90%
Borrow factor 70% 100%
Price 5 USD 1 USD

Deposit USDT, borrow TON:

  1. You deposit 100 USDT = 100 USD
  2. When you want to borrow TON, you can only borrow (original value of collateral) x (collateral factor of the collateral) x (borrow factor of the borrowing asset) = 100 x 0.9 x 0.7 = 63 USD.

Deposit TON, borrow USDT:

  1. You deposit 20 TON = 100 USD
  2. When you want to borrow USDT, you can only borrow (original value of collateral) x (collateral factor of the collateral) x (borrow factor of the borrowing asset) = 100 x 0.9 x 1 = 90 USD.

Generally speaking, the borrow factor helps manage risk within the protocol by accounting for volatility. Lower borrow factors are assigned to more volatile assets, allowing less borrowing against them, while more stable assets may have higher borrow factors.

Borrow factor, collateral factor, and liquidation

Borrow factor saves a room for price fluctuations in case of liquidation. Essentially, it has the same goal as the liquidation threshold in some of the other protocols, which is to protect borrowers from sharp price fluctuations and potential liquidations. When a user is withdrawing or borrowing, the protocol uses the collateral factor as well as borrow factor to check if the user is still overcollateralized after withdrawal or borrowing. Namely, it's called 'collateralization ratio':

$$\text{Collateralization ratio} = \frac{\sum (\text{Collateral Factor}_i \times \text{Collateral Value in USD}_i)}{\sum (\frac{\text{Borrowing Value in USD}_i}{\text{Borrow Factor}_i })}$$

where $0 \leq \text{Collateral factor} \leq 1$ and $0 \leq \text{Borrow factor} \leq 1$.

For example, given the following table:

TON USDT
Collateral factor 90% 90%
Borrow factor 70% 100%
Price 5 USD 1 USD
Deposited amount 5 USD 1 USD
Borrowed amount 2 USD 0.3 USD

The collateralization ratio would be:

$$\text{Collateralization ratio} = \frac{(0.9 \times 5) + (0.9 \times 1)}{\frac{2}{0.7} + \frac{0.3}{1.0}} = \frac{(4.5) + (0.9)}{\frac{2}{0.7} + 0.3} = \frac{5.4}{2.857 + 0.3} = \frac{5.4}{3.157} = 1.71... > 0$$

In this case, the collateralization ratio is bigger than 0, so this can be the state of the user after user has successfully withdrawn or borrowed some amount from a fully functional protocol. The user needs to keep the collateralization ratio above 1.

For liquidation, the health factor is calculated instead.

$$\text{Health factor} = \frac{\sum (\text{Collateral Factor}_i \times \text{Collateral Value in USD}_i)}{\sum \text{Borrowing Value in USD}_i}$$

The health factor is always bigger than or equal to the collateralization ratio because we take the borrow factor out, which always deflates the result of the equation. When they are equal, they will always be at the positive infinity.

Using the information from the table above, the health factor would be:

$$\text{Health factor} = \frac{(0.9 \times 5) + (0.9 \times 1)}{2 + 0.3} = \frac{(4.5) + (0.9)}{2.3} = \frac{5.4}{2.3} = 2.347$$

As it can be seen, the health factor is greater than the collateralization ratio. The difference between the health factor and the collateralization ratio is a buffer for the borrowers. When the health factor goes below 1, anyone can liquidate that user and make it back to 1 or closer to 1.

How much to pay for liquidation

The liquidation must happen before the health factor drops 'too much'. What would be 'too much'?: When the value of the collateral is so little that the health factor cannot be recovered back to 1 even after being liquidated. How do we derive the equation? We can use the same health factor equation we have above.

Let's give an example using the variables below, and let's say we are repaying USDT debt and taking away TON collateral during liquidation:

TON USDT
Collateral factor (liquidation threshold) 80% 85%
Deposited amount in USD 5.4 USD 0.1 USD
Borrowed amount in USD 0.1 USD 5 USD
Liquidation bonus 6% 7%

Let's expand:

$$\text{Health factor} = \frac{\sum (\text{Collateral Factor}_i \times \text{Collateral Value in USD}_i)}{\sum \text{Borrowing Value in USD}_i}$$

into

$$\text{HF}_{\text{after liquidation}} = \frac{CF_{TON} \times (CV_{TON} - RV_{USDT}(1 + LF_{TON})) + CF_{USDT} \times CV_{USDT}}{DV_{TON} + DV_{USDT} - RV_{USDT}}$$

where

  • $\text{HF}_{\text{after liquidation}}$ is the health factor after liquidation takes place.
  • $\text{CF}_{asset}$ is the collateral factor of an $asset$.
  • $\text{CV}_{asset}$ is the value of an $asset$ deposited as a collateral in USD.
  • $\text{RV}_{asset}$ is the value of repayment on the debt of an $asset$ in USD.
  • $\text{DV}_{asset}$ is the value of the debt of an $asset$ in USD.
  • $\text{LF}_{asset}$ is the liquidation bonus factor of an $asset$.

Notice that the equation is just an equation for the health factor in the post-liquidation state. $CF_{TON} \times (CV_{TON} - RV_{USDT}(1 + LF_{TON}))$ represents the discounted collateral left after a part of TON collateral including the liquidation bonus is captured in exchange for the USDT debt repayment by the liquidator. $CF_{USDT} \times CV_{USDT}$ represents the discounted USDT collateral. $DV_{TON} + DV_{USDT} - RV_{USDT}$ represents total debt after the USDT debt repayment.

Let's rearrange the equation so we can solve for $\text{RV}_{USDT}$:

$$\text{HF}_{\text{after liquidation}} = \frac{CF_{TON} \times (CV_{TON} - RV_{USDT}(1 + LF_{TON})) + CF_{USDT} \times CV_{USDT}}{DV_{TON} + DV_{USDT} - RV_{USDT}}$$ $$\implies \text{HF}_{\text{after liquidation}}(DV_{TON}) + \text{HF}_{\text{after liquidation}}(DV_{USDT}) - \text{HF}_{\text{after liquidation}}(RV_{USDT})$$ $$= (CF_{TON})(CV_{TON}) - (RV_{USDT})(CF_{TON})(1 + LF_{TON})) + (CF_{USDT})(CV_{USDT})$$ $$\implies (RV_{USDT})(CF_{TON})(1 + LF_{TON})) - \text{HF}_{\text{after liquidation}}(RV_{USDT}$$ $$= -\text{HF}_{\text{after liquidation}}(DV_{TON}) -\text{HF}_{\text{after liquidation}}(DV_{USDT}) + (CF_{TON})(CV_{TON}) + (CF_{USDT})(CV_{USDT})$$ $$\implies (RV_{USDT})((CF_{TON})(1 + LF_{TON})) - \text{HF}_{\text{after liquidation}})$$ $$= -\text{HF}_{\text{after liquidation}}(DV_{TON} + DV_{USDT}) + \sum\limits_{i}{(CF_i \times CV_i)}$$ $$\implies (RV_{USDT})((CF_{TON})(1 + LF_{TON})) - \text{HF}_{\text{after liquidation}})$$ $$= -\text{HF}_{\text{after liquidation}}(\sum\limits_{i}{DV_i}) + \sum\limits_{i}{(CF_i \times CV_i)}$$ $$\implies RV_{USDT} = \frac{-\text{HF}_{\text{after liquidation}}(\sum\limits_{i}{DV_i}) + \sum\limits_{i}{(CF_i \times CV_i)}}{((CF_{TON})(1 + LF_{TON})) - \text{HF}_{\text{after liquidation}}}$$

Now that we have the equation ready, substitute the variables. We know that:

$$\text{HF}_{\text{after liquidation}} \le 1$$

, so let's substitute:

$$\text{HF}_{\text{after liquidation}} = 1$$

in this equation below:

$$RV_{USDT} = \frac{-(1)(5 + 0.1) + (0.8 \times 5.4 + 0.85 \times 0.1)}{((0.8)(1 + 0.06)) - 1}$$

We can run this Python script to confirm the result:

RV_USDT_NUMERATOR = (-1 * (0.1 + 5) + (0.8 * 5.4 + 0.85 * 0.1))
RV_USDT_DENOMINATOR = ((0.8) * (1 + 0.06) - 1)
RV_USDT = RV_USDT_NUMERATOR / RV_USDT_DENOMINATOR

print(RV_USDT_NUMERATOR)
print(RV_USDT_DENOMINATOR)
print(RV_USDT)

HF_CHECK_NUMERATOR = 0.8 * (5.4 - RV_USDT * (1 + 0.06)) + 0.85 * 0.1
HF_CHECK_DENOMINATOR = 5.1 - RV_USDT
HF = HF_CHECK_NUMERATOR/HF_CHECK_DENOMINATOR

print(HF_CHECK_NUMERATOR)
print(HF_CHECK_DENOMINATOR)
print(HF)

The console will print:

-0.6949999999999994 # RV_USDT_NUMERATOR
-0.1519999999999999 # RV_USDT_DENOMINATOR
4.57236842105263 # RV_USDT
0.5276315789473698 # HF_CHECK_NUMERATOR
0.5276315789473696 # HF_CHECK_DENOMINATOR
1.0000000000000004 # HF

Disregarding the floating point number errors, we can confirm that we deduced the correct $RV_{USDT}$.

We can now generalize the equation further, from:

$$RV_{USDT} = \frac{-\text{HF}_{\text{after liquidation}}(\sum\limits_{i}{DV_i}) + \sum\limits_{i}{(CF_i \times CV_i)}}{((CF_{TON})(1 + LF_{TON})) - \text{HF}_{\text{after liquidation}}}$$

to:

$$RV_{\text{repaid asset}} = \frac{-\text{HF}_{\text{after liquidation}}(\sum\limits_{i}{DV_i}) + \sum\limits_{i}{(CF_i \times CV_i)}}{(CF_{\text{liquidated asset}})(1 + LF\_{\text{liquidated asset}}) - \text{HF}_{\text{after liquidation}}}$$

However, in some cases where more than two assets are borrowed or deposited as collaterals, $RV_{\text{repaid asset}}$ can exceed $DV_{\text{repaid asset}}$ or $CV_{\text{liquidated asset}}$. In either case, repayment is not valid because repayment amount must be smaller than the debt and must be smaller than the captured collateral amount plus liquidation bonus in order for the liquidation to work.

In such cases, $\text{Final Repaid Amount}_{\text{repaid asset}}$ needs to be reduced down to $min(RV_{\text{repaid asset}}, min(DV_{\text{repaid asset}}, \frac{CV_{\text{liquidated asset}}}{1 + LF_{\text{liquidated asset}}}))$.

Below, we review all of the different possibilities for liquidation. We use $\text{USDT} = \text{repaid asset}$, and $\text{TON} = \text{liquidated asset}$.

  1. $\text{HF} \ge 1$
TON USDT
Collateral factor (liquidation threshold) 80% 85%
Deposited amount in USD 5.4 USD 0.1 USD
Borrowed amount in USD 0.1 USD 0 USD
Liquidation bonus 6% 7%

In this case, there can't be a liquidation on this account, because the user's position is healthy:

$$\text{HF} = \frac{0.8 \times 5.4 + 0.85 \times 0.1}{0.1} \ge 1$$
  1. $\text{HF} \le 1$ and $RV_{\text{repaid asset}} = min(RV_{\text{repaid asset}}, min(DV_{\text{repaid asset}}, \frac{CV_{\text{liquidated asset}}}{1 + LF_{\text{liquidated asset}}}))$
TON USDT
Collateral factor (liquidation threshold) 80% 85%
Deposited amount in USD 5.4 USD 0.1 USD
Borrowed amount in USD 0.1 USD 5 USD
Liquidation bonus 6% 7%

This is the example we used previously. HF is smaller than 1:

$$\text{HF} = \frac{0.8 \times 5.4 + 0.85 \times 0.1}{0.1 + 5} = \frac{4.405}{5.1} \le 1$$

and $RV_{\text{repaid asset}} = min(RV_{\text{repaid asset}}, min(DV_{\text{repaid asset}}, \frac{CV_{\text{liquidated asset}}}{1 + LF_{\text{liquidated asset}}})$:

$$RV_{\text{repaid asset}} = \frac{-\text{HF}_{\text{after liquidation}}(\sum\limits_{i}{DV_i}) + \sum\limits_{i}{(CF_i \times CV_i)}}{((CF_{\text{liquidated asset}})(1 + LF_{\text{liquidated asset}})) - \text{HF}_{\text{after liquidation}}}$$ $$\implies RV_{\text{USDT}} = \frac{-(1)(5 + 0.1) + (0.8 \times 5.4 + 0.85 \times 0.1)}{((0.8)(1 + 0.06)) - 1}$$ $$\implies RV_{\text{USDT}} = 4.57236842105263...$$
  1. $\text{HF} \le 1$ and $\text{Final Repaid Amount}_{\text{repaid asset}} = \frac{CV_{\text{liquidated asset}}}{1 + LF_{\text{liquidated asset}}} = min(RV_{\text{repaid asset}}, min(DV_{\text{repaid asset}}, \frac{CV_{\text{liquidated asset}}}{1 + LF_{\text{liquidated asset}}})$

Put simply, this is when the amount of collateral to be liquidated isn't enough to bring HF back to 1, because the user has multiple collaterals.

TON USDT
Collateral factor (liquidation threshold) 80% 85%
Deposited amount in USD 3 USD 2.5 USD
Borrowed amount in USD 0.1 USD 5 USD
Liquidation bonus 6% 7%

Calculate HF first:

$$\text{HF} = \frac{0.8 \times 3 + 0.85 \times 2.5}{0.1 + 5} = \frac{4.525}{5.1} \le 1$$ $$RV_{\text{USDT}} = \frac{-(1)(5 + 0.1) + (0.8 \times 3 + 0.85 \times 2.5)}{((0.8)(1 + 0.06)) - 1} = 3.7828947368421026...$$ $$3.7828947368421026... \ge CV_{TON} \because CV_{TON} = 3$$ $$3.7828947368421026... \le DV_{USDT} \because DV_{USDT} = 5$$ $$\implies \text{Final Repaid Amount}_{USDT} = \frac{CV_{\text{TON}}}{1 + LF_{\text{TON}}} = min(RV_{\text{repaid asset}}, min(DV_{\text{repaid asset}}, \frac{CV_{\text{TON}}}{1 + LF_{\text{TON}}})$$

Therefore, we can only repay $\frac{3}{1 + LF_{\text{TON}}} = \frac{3}{1.06} = 2.830188679....$ in this scenario. HF will not be fully restored back to 1. The denominator exists to account for the liquidation bonus, so that we can get 3 USD as the value of captured collateral plus liquidation bonus, which is the maximum we can get from the deposited USDT collateral. But liquidation should still run regardless.

Here's $\text{HF}_{\text{after liquidation}}$:

$$\text{HF}_{\text{after liquidation}} = \frac{CF_{TON} \times (CV_{TON} - (\text{Final Repaid Amount}_{USDT})(1 + LF_{\text{TON}})) + CF_{USDT} \times CV_{USDT}}{DV_{TON} + DV_{USDT} - \text{Final Repaid Amount}_{USDT}}$$ $$= \frac{0 + CF_{USDT} \times CV_{USDT}}{DV_{TON} + DV_{USDT} - \text{Final Repaid Amount}_{USDT}}$$ $$= \frac{0 + 2.5 \times 0.85}{5.1 - 2.5} = \frac{2.125}{2.6} = 0.81730769....$$

Notice that we will need to liquidate the other collateral to fully recover the health factor back to 1.

  1. $DV_{\text{repaid asset}} = min(RV_{\text{repaid asset}}, min(DV_{\text{repaid asset}}, \frac{CV_{\text{liquidated asset}}}{1 + LF_{\text{liquidated asset}}})$

This is when the amount of debt to be repaid isn't enough to bring HF back to 1 because the user has multiple assets in debt, and this amount is smaller than the collateral that can be captured.

TON USDT
Collateral factor (liquidation threshold) 80% 85%
Deposited amount in USD 5.4 USD 0.1 USD
Borrowed amount in USD 2.5 USD 2.6 USD
Liquidation bonus 6% 7%

Again, we are repaying USDT and liquidating TON:

$$RV_{\text{USDT}} = \frac{-(1)(2.5 + 2.6) + (0.8 \times 5.4 + 0.85 \times 0.1)}{((0.8)(1 + 0.06)) - 1}$$ $$= 4.57236842105263...$$

This means we want to liquidate 4.57236842105263 USD equivalent of USDT, but we cannot because the user only has 2.6 USD worth of USDT in debt, thus:

$$\text{Final repaid amount}_{USDT} = min(4.57236842105263, min(2.6, \frac{5.4}{1.06}))$$ $$= 2.6$$

This won't recover HF back to 1. It will require another liquidation to be run to repay TON and liquidate TON.

LTV (Loan-to-value)

Sometimes, when you visit other lending apps, you may see the term "LTV". Check out this doc for a good intro: https://docs.notional.finance/notional-v2/borrower-resources/loan-to-value-ltv

Simply put, $LTV = \frac{\text{Total debt in USD}}{\text{Total collateral in USD}}$.

However, we encourage saying the term "$\text{Collateralization Ratio}$" over LTV just because it makes more sense.

One collateral at a time

In case Alice is collateralized by multiple reserves and liquidating and taking away one collateralized reserve doesn't recover Alice's health factor back to 1, a liquidator should run liquidation multiple times. This is because the contract implementation only allows one collateral asset to be taken away for each liquidation.

Smart choice to make a profit

The liquidator must make a smart choice to liquidate positions by carefully comparing the gas fee and the expected liquidation bonus (profit) from the liquidation.

Contract upgrades

It is important that a specific TON wallet at a time has only ONE BlubboUser contract only. Over time, it might be required that BlubboUser contract is upgraded to a new code, although it will have to happen very seldom.

But it is not as straightforward as upgrading the BlubboMaster contract, because there will be as many BlubboUser contracts as the number of users (unique TON wallets) using BlubboFi, whereas upgrading the BlubboMaster contract is just a matter of upgrading a single contract.

Upgrading BlubboUser: owner_upgradable.fc

In all approaches, a user wallet can only have one BlubboUser contract at a time to avoid confusion at all. In either way, upgrading BlubboUser contract must thoroughly be tested, because it cannot easily be upgraded.

Approach 1

When we decide to release an upgrade for the BlubboUser contract, we sponsor a transaction for the user as long as it will not cost much.

The user will sign a payload, and we send that payload ourselves by verifying the user's signature on-chain. If we confirm that the signature is from the user, we send an upgrade payload to the corresponding BlubboUser contract. The data must be migrated carefully in case the TL-B definition of persistent data cell changes, which is very likely in upgrades.

The new BlubboUser contract code will need to be stored by BlubboMaster contract. Our relayer will send a message to BlubboMaster contract which in turn will send a message to the user's BlubboUser contract to trigger an upgrade.

The possibility of upgrades raises a concern for the computation of BlubboUser contract address, because BlubboUser contract code and its permanent storage layout are the parameters that determine the address. In that regard, it will be necessary to only store the latest BlubboUser contract code in BlubboMaster's permanent storage's TL-B scheme somewhere, so it could be used to see which version of the BlubboUser contract the user currently has.

Approach 2

  1. We store different versions of BlubboUser contract's code (or at least a hash) in BlubboMaster's storage as we upgrade. This is needed because we want to calculate the correct address of BlubboUser contract.
  2. Once we release an upgrade, we silently require a bit of TON for the upgrade whenever user wants to interact with the protocol. Whenever there is an upgrade payload along with the actual payload for the transaction (deposit, withdrawal, ... etc) during the interaction, BlubboUser contract will receive and upgrade the code itself.

Approach 3 (we use this)

So far we have explored rather premitive ways to upgrade BlubboUser. But there's a bit more sophisticated way to do it: to write a contract that is only upgradable by Blubbo Master and keep upgrading it as BlubboUser code needs to update.

Initially, the contract will only have the bare minimum to allow a contract upgrade from Blubbo Master. This way, we make sure that the contract is still only controlled by Blubbo Master, but at the same time allow the contract address to stay constant even if the BlubboUser source code changes because the contract address will not update after the initial deployment. This is how we mitigate the problem of ever-changing calculated BlubboUser address if we do not have an upgradable contract.

When BlubboUser code needs to be updated, we send along an upgrade payload to the contract, upgrade the contract, and run the intended op with the upgraded contract.

It is necessary to NOT upgrade BlubboUser when any of the locks are activated. In other words, BlubboUser code must not be upgraded when it receives a reply from BlubboMaster. This is because this might cause inconsistencies in BlubboUser's behavior. For example:

  1. A user does not have any locks activated in his BlubboUser contract.
  2. A user sends a withdrawal request from his wallet.
  3. Let's skip the part about transferring toncoin/jetton because its irrelevant here.
  4. op::withdraw_from_blubbo_master_to_blubbo_user is sent from BlubboMaster to BlubboUser. At this point, if BlubboUser's code needs to be upgraded, it can be sent along with the payload for the upgrade, because there's no existing chain of messages waiting to be finished. Now the withdrawal lock is activated.
  5. In response to the previous message, BlubboUser will send op::withdraw_from_blubbo_user_to_blubbo_master.
  6. BlubboMaster will finally send back op::unlock_from_blubbo_master_to_blubbo_user to BlubboUser. When BlubboUser receives the message back from BlubboMaster, it will deactivate the lock. Now, it is very dangerous to upgrade BlubboUser at this point, because we have no guarantee that BlubboUser behaved in a particular way when it processed op::withdraw_from_blubbo_master_to_blubbo_user. In other words, BlubboUser version A was used until op::withdraw_from_blubbo_user_to_blubbo_master, and BlubboUser version B was used at op::unlock_from_blubbo_master_to_blubbo_user. This is very risky because 1) it is a big hassle to keep version A compatible with version B 2) even if they are compatible, it is just still risky because we are dealing with two different source codes which will require a lot of testing efforts too. So we won't just allow this. We will ONLY allow upgrading the BlubboUser contract when it first receives the message from BlubboMaster, not the second time.

The contract is found at ./contracts/owner_upgradable/owner_upgradable.fc. No changes to the contract can be made once the first BlubboUser contract is deployed, because the address derivation cannot change anymore once any BlubboUser contracts are deployed.

Here's an exact sequence in which the BlubboUser contract will be upgraded:

  1. Initially, BlubboMaster contains an existing version of BlubboUser code ('version A') in its persistent storage.
  2. Changes to version A are made to produce version B.
  3. Admin sends op::set_blubbo_user_code along with version B to BlubboMaster.
  4. BlubboMaster starts sending version B in the messages that are sent from BlubboMaster to BlubboUser.
  5. On receiving the message, BlubboUser executes the upgrade, and runs the originally intended op.

Handling inconsistencies immediately after upgrade

First thing we need to note is that unless the code upgrade affects only one of BlubboMaster or BlubboUser contracts, the code upgrade of these two contracts must be atomic. In other words, when we need to change something in BlubboUser that requires a change in BlubboMaster too, which would typically be the case, we need to upgrade the code of BlubboMaster the same time as BlubboUser is upgraded. This can be done by sending op::upgrade_code to BlubboMaster, with the new version of BlubboMaster included as a new_code and new version of BlubboUser included as a nested ref in upgrade_parameters that should be manually updated in the permanent storage by after_code_upgrade. Any explanations below assume that this is done correctly. If this is not done, it becomes dramatically difficult to support the compatibility of two different versions of BlubboMaster and BlubboUser respectively at a time.

We must remember that TON is an asynchronous blockchain, and simply upgrading the code will NOT be the end of the story.

Take this case for example:

  1. Initially, BlubboMaster contains an existing version of BlubboUser code ('version A') in its persistent storage.
  2. Changes to version A are made to produce version B.
  3. Admin sends op::upgrade_code along with version B to BlubboMaster. BlubboMaster code is upgraded, and BlubboUser code is updated at BlubboMaster's persistent storage.
  4. At the same time, a user has an ongoing withdrawal tx, which already has gone past BlubboMaster to BlubboUser contract. The message will need to come back to BlubboMaster with op::withdraw_from_blubbo_user_to_blubbo_master. However, we are uncertain if this message is going to be compatible with the latest version of BlubboMaster, because now it's supposed to work with the latest version of BlubboUser that is stored in its persistent storage.

Or take this case:

  1. BlubboMaster is at version A.
  2. User initiates a tx from his wallet to BlubboMaster.
  3. Before 2 finishes, BlubboMaster upgrades to version B, rendering the tx from step 2 incompatible with the latest version of BlubboMaster. For instance, the way BlubboMaster parses a message sent from user's wallet changed, and it's not able to deal with that anymore.

It is possible to always care about backward compatibility, but it's a lot easier for us to not care and simply gracefully reject all transactions that are not compatible anymore. So we choose to implement graceful rejection.

There can only be two cases where a message needs to be rejected because it originates from an outdated Blubbouser or BlubboMaster contract. And here are respective solutions for those:

  1. A message is coming back from BlubboUser to BlubboMaster, but it's outdated: carry a int blubbo_system_version in the message, and throw if it is not the same as the one stored in BlubboMaster at any time, or handle the logic differently if it is the previous version instead of throwing (this is recommended, but by default the code will throw because it does not know what to do). The system version is stored as a constant in version.fc as version::SYSTEM_VERSION.
  2. A message is coming from a user's wallet directly to BlubboMaster, but it's outdated: get the latest int blubbo_system_version by querying directly from BlubboMaster before sending a message from a wallet. Store that in the message and send it to BlubboMaster, and throw if it is not the same as the one stored in BlubboMaster.

Optimizing BlubboUser upgrade

BlubboUser will upgrade itself automatically if it finds that it has a version number lower than the one sent in the message received. Otherwise, it will not be upgraded. Therefore, it is essential that you increment blubbo_user_version whenever you update BlubboUser code stored in BlubboMaster's persistent storage.

Oracle and config

The only available oracle on TON at the time of writing is RedStone oracle. However, there isn't so much public information about how to use it end-to-end on TON. Also, the SDK is not perfect yet; parts of the essential code had to be copied directly from https://github.com/evaafi/merkle-oracles/blob/main/src/oracles/redstone and https://github.com/redstone-finance/redstone-oracles-monorepo/tree/main/packages/ton-connector/src and be modified.

tsTON and stTON prices are not supported by RedStone. Evaa protocol mitigates this by implementing their own oracle by querying the price from the pool directly: https://github.com/evaafi/merkle-oracles/tree/main/src/oracles/ton. This is not a concern as of now, but we will have to consider this problem once we need to support these assets.

Note that Redstone oracle uses a novel approach to providing price information on-chain. Its core model includes signed price data in the transaction, which then can be decoded and verified on-chain. No rocket science, but might be unfamiliar at first glance.

contracts/redstone directory had been copied directly from https://github.com/redstone-finance/redstone-oracles-monorepo/blob/281e41517a54ae0d9a9c0c30c39d0ccf15950d68/packages/ton-connector/contracts/redstone/ because there is no way to 'inherit' the contracts like in Solidity. Therefore, future updates will need to be manually made if any.

The oracle data has to be verified against a set of signers (ex. 0x123, 0x456, etc), data feeds (ex. TON, USDT, etc) and the unique number of signers to check if the data from the external world is indeed from Redstone oracle and is according to the off-chain configuration.

However, the off-chain configuration can change at any time, for example, if we were to add more data feeds. Because of this dynamic nature, the configuration data will be signed and included in the message. The BlubboMaster contract will keep the public key of the signer of the configuration and verify the signature of the config with it on-chain.

Price decimals

It does not matter how many decimal places are required for the price feed received from the oracle, but the number of decimal places used for all prices of all reserves MUST be the same.

Currently, RedStone oracle offers the price of TON and USDT in 8 decimal places in the form of an integer (for example, 526832150 for 5.26832150).

Handling bounced messages

Currently, bounced messages in TON have only 224 usable data bits in the message body and don't have any references ^1. This means that we need to carefully position and size each message body, so that most important pieces of information can be restored (such as account balance).

Because we want to include as much data as possible, we artificially reduce the maximum bit length of coins to 108 bits. We can use rest of the bits (224 - 108 bits) to store other data.

Reserve ID

A reserve id is an identifier for a specific reserve, starting from 0. Currently, the reserve id is 6 bits long. This means 2**6 = 64 unique reserves can be represented in the protocol. There are mainly two reasons why it exists:

  1. A jetton minter's address (the parent contract of all jetton wallets, which communicates with as many jetton wallet contracts as there are) is 256 bits long, excluding the workchain id. This becomes very troublesome when you want to include as much data as possible in the body of a bounced message because it only allows 256 bits of the message body to be bounced. The rest will be gone. But the opcode will take up the first 32 bits, so we won't even have full 256 bits to know which jetton it was that the relevant transaction has failed. In contrast, a reserve id is only 6 bits long, so we have many more bits to store other info.
  2. For a permissionless deployment of lending pools, it is possible that we might have multiple pools of the same jetton. In such a case, jetton minter address cannot be used as a unique ID for identifying a pool anymore. FYI, this feature is not a part of MVP, but it would be nice to factor the reserve id into the design earlier so we have less things to adjust when we want to roll out permissionless deployment of lending pools.

Accumulator

An accumulator, also referred to as cumulative liquidity/borrow index, or simply interest index, tracks how much interest is accrued over time. According to Aave, it is defined as "the Interest cumulated by the reserve during the time interval since the last updated timestamp". Over time, it grows in value, and it will usually be multiplied by the value of principal to get the amount with interests included.

Such a term does not exist in the web2 world, so don't try too hard to understand it fully at first glance. You will naturally get to know what it means as you keep using it.

Raw and face amount

  • Raw amount is the amount that only includes the principal.
  • Face amount is the up-to-date amount that includes the principal as well as interests earned.

Fees

Good references are:

One special characteristic of fees on TON compared to other major blockchains is that there is the storage fee. If the smart contract stores a lot of data but does not have enough toncoin over time to pay for the rent, it will be 'frozen', meaning that both the code cell and the data cell of the frozen contract will be deleted to free resources. The system does remember the hashes of these two cells to allow the contract to be recovered in the future. A frozen contract still retains its address and its TON coin balance.

It is possible to recover the contract code and data using some handy tool like https://github.com/ton-blockchain/unfreezer/. But ideally, we just never want it to happen.

It is required that the smart contract maintains a table of the minimum amount of gas needed for each operation. The minimum amount of gas will account for the gas used in the worst-case scenario with the most gas consumption including the cases where messages might be bounced, probably producing the longest chain and consuming the most amount of gas. The excess amount will have to be returned to the user anyway, so levying a bit of more TON shouldn't be a problem as long as the user is aware of the protocol's design.

If the incoming message does not have enough gas for a certain op, it must be rejected at the earliest time possible, because a lack of gas might result in a partial execution of transactions at any point of chained transactions. Otherwise, it might be a vulnerability right off the bat, because carefully adjusted amount of gas might cause the bounced transaction handlers to not execute.

For every op, max fee must be known before. This is covered in tests/*.paths.*.spec.ts tests.

Treasury balance management

Reserve factor

Each reserve has a reserve factor. It is the percentage of interest paid by borrowers that is allocated to the reserves of the protocol.

For example:

  • You borrow $1000 USDC from the protocol.
  • The USDC Borrow APY (Annual Percentage Yield) is 10%.
  • Over the course of one year, you would pay approximately $100 in interest.
  • If the reserve factor is 20%, $20 of the $100 is directed to the treasury. The rest is paid to the depositors as a deposit interest.

Accrual

In traditional lending protocols on EVM, the deposit certificate token (aToken for Aave, or cToken for Compound) is minted directly at every block at which the interest rate is updated. However, this would mean having to send one more message to the treasury BlubboUser account when it comes to building on TON. This increases the gas fee.

Therefore, the total raw amount to treasury is constantly updated and stored in the permanent storage of BlubboMaster contract. From time to time, a message can be sent to BlubboMaster contract to withdraw the treasury balance to the treasury address.

Ensuring atomicity

Important

A prerequisite to this part is understanding Messages and Transactions.

Let's take a hypothetical example:

blubbomaster_fails_repayment_succeeds_withdrawal.png

Before any transactions, this is Alice's position on BlubboFi:

TON USDT
Price in USD 5 1
Deposit in USD 100 0
Debt in USD 0 100
Collateral factor 100% 100%
Borrow factor 100% 100%
Lending & Debt Accumulators 1 1

For the purpose of illustration, the collateral and borrow factors are all 100%. Alice has 100 USD worth of debt and 100 USD worth of deposit. Currently, she cannot withdraw any TON because 100% of her collaterals are backing her deposit.

  1. logical time (hereinafter "lt") = 1: BlubboMaster USDT Wallet receives USDT from Alice's USDT Wallet.
  2. lt = 3: BlubboMaster receives a transfer notification from its USDT wallet, about Alice's repayment.
  3. some time before lt = 3, Alice sends another message to BlubboMaster to request withdrawal of 20 TON, which are held as collaterals. This message reaches BlubboMaster at lt = 4.
  4. lt = 5: repayment message reaches Alice's BlubboUser contract. The raw debt USDT balance is decreased to 0. Now according to this contract's state, Alice's collaterals aren't backing any debts anymore, and therefore are free to be withdrawn.
  5. lt = 6: withdrawal message arrives, and collateralization ratio check passes, as Alice's total raw debt is zero.
  6. lt = 7: some logic fails at BlubboMaster while finalizing repayment. For example, there is an underflow bug due to incorrect subtraction. The message is bounced, and the bounced message reaches BlubboUser at lt = 9, increasing the raw debt again back to 100 USDT.
  7. lt = 8: withdrawal is finalized at BlubboMaster. BlubboMaster sends 20 TON to Alice.
  8. At lt > 9, Alice's BlubboUser contract now has total raw debt = 100 USD, and total raw deposit = 0. Effectively, Alice bypassed the collateralization checks by cleverly detecting a bug and slipping in a transaction ahead of time. Now the protocol is insolvable.

Due to this, we propose a simple way to guarantee atomic transactions at BlubboUser: a lock.

A lock is a storage variable kept at BlubboUser contract. When it is on, no other transactions can enter BlubboUser contract. When it is off, only one transaction can enter BlubboUser contract at a time. Other 'competing' transactions would be rejected by BlubboUser contract.

blubbomaster_fails_repayment_rejects_withdrawal.png

If you want to see what a chain of transactions would look like in reality, take a look at swap transactions at ston.fi.

Here's a relationship between all types of messages and whether they need a lock in each case (X = No lock needed, O = Lock is needed). The columns denote the earlier transaction that fails. The rows denote the latter.

Here's the template sentence for the question: [column] increases/decreases BlubboUser's deposit/debt first. Can [row] exploit that state before [column] gets bounced and reverts the state?

For example:

  • [borrowing] increases BlubboUser's debt first. Can [deposit] exploit that state before [borrowing] gets bounced and reverts the change in debt by decreasing it?
  • Answer: no. Simply increasing the deposit before the debt decreases doesn't do harm.
Deposit Withdrawal Borrowing Repayment Liquidation
Deposit X X X X X
Withdrawal X X X O O
Borrowing X X X O O
Repayment X X X X X
Liquidation X O O X X

This table below explains the reasons for positive cases:

  • column = repayment, row = withdrawal: [repayment] decreases BlubboUser's debt first. Can [withdrawal] exploit that state before bounced [repayment] reverts the change in debt by increasing it back? Yes. Because user can slip in repayment and then withdrawal message within a very close interval, and then if repayment first decreases the debt, the collateralization ratio would be larger, allowing the user to withdraw more collateral than when he had a debt. But when the repayment txn is bounced, the debt will recover with not enough collateral. The user then can run away with that debt.
  • column = repayment, row = borrowing: [repayment] decreases BlubboUser's debt first. Can [borrowing] exploit that state before bounced [repayment] reverts the change in debt by increasing it back? Yes. Same collateralization ratio issue as column = repayment, row = withdrawal. Essentially, user will be able to borrow more than he actually can.
  • column = liquidation, row = withdrawal: [liquidation] decreases BlubboUser's debt first. Can [withdrawal] exploit that state before bounced [liquidation] reverts the change in debt by increasing it back? Yes. Same collateralization ratio issue as column = repayment, row = withdrawal.
  • column = liquidation, row = borrowing: [liquidation] decreases BlubboUser's debt first. Can [borrowing] exploit that state before bounced [liquidation] reverts the change in debt by increasing it back? Yes. Same sollateralization problem.
  • column = withdrawal, row = liquidation: [withdrawal] decreases BlubboUser's deposit first. Can [liquidation] exploit that state before bounced [withdrawal] reverts the change in deposit by increasing it back? Yes. The collateralization ratio will be lower, and a sudden price drop in a second might allow another liquidator to exploit that low collateralization ratio, although it's very very unlikely.
  • column = borrowing, row = liquidation: [borrowing] increases BlubboUser's debt first. Can [liquidation] exploit that state before bounced [borrowing] reverts the change in debt by decreasing it back? Yes. Same collateralization problem.

To mitigate this problem, we implement a simple lock mechanism in BlubboUser. When a message first enters the contract, we check if the lock is on. If it is, reject the message. If not, lock the contract and continue. When the whole transaction is completed at BlubboMaster, it sends an 'ack' (or simply 'unlock') message back to BlubboUser, which will unlock the contract again. Then the contract is free to receive other messages.

The downside of this method is increased gas fee because we're sending another message. But there would be no other way to precisely handle this problem.

Repeated operations

The concern on the atomicity raises another question: what if the user repeatedly sends the same transaction to unlock the lock earlier than expected, because there is only a single lock for each type of transaction (withdrawal, borrowing, repayment, and liquidation)?

The initial BoC for the locks was:

tx_locks$_;
withdrawal: uint2;
borrowing: uint2;
repayment: uint2;
liquidation: uint2 = TxLocks;

where unlocked = 1, locked = 2.

And how an 'early unlock' could work with this:

Alice sends withdrawal tx one after the other, almost instantly. Then at the first withdrawal tx, the lock would go active. For the second withdrawal, it will keep the lock locked and continue the tx because we don't regard repeated withdrawals as dangerous transactions according to the table above.

However, when the first withdrawal's last message reaches the BlubboUser contract again, it has no way of knowing that there is a withdrawal transaction that is coming later than itself, so it will just unlock the withdrawal lock despite the second withdrawal that is still not yet finished.

Although it could be very rare, it is technically possible that the user (or the liquidator) takes this to his own advantage and slips through a type of txn that is forbidden to be preceded by another according to the table above. In this specific example of two withdrawals, a liquidator might come in the middle, effectively taking advantage of the lower collateralization ratio of the user, while it is not guaranteed that the entire chain of messages for the second withdrawal will succeed, which would recover the collateralization ratio.

One may also ask it would be possible to simply block any following operations while the same type of operation is ongoing. However, I simply doubt if this is an option, because this might bring a bad UX to the user: what if user wants to repeatedly withdraw twice or thrice, and the blockchain is acting weird and it would take like 30 secs for each operation to complete separately?

Therefore, we propose an incremental lock for each operation, where the lock would simply increment in value:

tx_locks$_;
withdrawal_lock_id: uint10;
withdrawal_lock: uint2;

borrowing_lock_id: uint10;
borrowing_lock: uint2;

repayment_lock_id: uint10;
repayment_lock: uint2;

liquidation_lock_id: uint10;
liquidation_lock: uint2 = TxLocks;

Going back to the original example, the first withdrawal would have the withdrawal lock set to 1, and the second withdrawal would increment it to 2. At the end of the chain of messages, the last message for the first withdrawal will see that the withdrawal lock at the BlubboUser contract is set as 1, while the lock id it brought with it is 1. Then, it will not unlock the the contract yet, because now it knows that there is another withdrawal that happened after itself. The second withdrawal message will come back and unlock the lock.

One important assumption of this design is that we assume that the number of operations that can be 'in progress' is only 2**10 = 1024 operations. In other words, we assume that the blockchain is fast enough to have the 1st operation of a particular user 'finished' (either bounced, aborted or successful) before his 1024th operation finishes. This way, we can guarantee that there will only be one message carrying a unique lock ID at a time. Increasing this number will make the protocol more secure. However, it comes at the cost of using up the number of bits usable for bounced messages, which is 224 bits except the 32-bits long op bit. We therefore conclude that 10 bits is a safe enough compromise.

Tests

Tests are located under /tests folder. It is encouraged to always mimic the behavior of the asynchronous blockchain by updating the block timestamp after each transaction instead of using a constant block timestamp (by default, the test will have the same block timestamp).

SDK

The official SDK lives in blubbofi/blubbo-sdk. The SDK in this repository is only for testing/reference purposes.

Contributing

  1. If your contribution requires some change in the TL-B scheme, update contracts/types.tlb accordingly. And very likely, you will need to write a code to migrate the data structure as well. See handle_upgrade_code.fc.
  2. Make sure you cover what you wrote with tests.
  3. CI should be all passing on your PR.
  4. func doesn't have public/private function semantics. But it's good to have artificial semantics for easier development. Prefix a public function name with topic_name::, like topic_name::function_name. An example would be: handlers::handle_add_reserve. However, if it is meant to be a private function, just write a function name without a prefix. Private functions must be at the bottom of the file. Public functions must be above all private functions. Use function header declarations at the top of the file to make private functions visible to the public functions.

Resources

About

Blubbo's smart contracts running on TON.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages