Squeeth ‘s Smart Contract & Architecture Breakdown

Rati Montreewat
SCB 10X OFFICIAL PAGE
10 min readOct 11, 2022

Introduction

You probably know what the financial derivatives are or even use them.

A derivative is a security whose value is derived from (depends upon) that of another underlying more basic security

Squeeth (AKA squared ETH) is categorized as one of financial derivatives. However, it introduces unprecedented paradigm in the history of financial world. Mathematically, the derived value of it, rather than linear function, is a polynomial function of underlying security. For example, centralized derivative exchange now only, in simple words, offer futures which are traditional financial derivative contracts with constant leveraged positions ( 2x, 10x,50x and etc.). While, Squeeth offers payoffs with pure convexity payoff (e.g. ETH²).

In this article, we are going to dig deep into this first-of-its-kind, innovative product by breaking its smart contract down. Be alarmed, although this is surely very technical one, we are going to understand the business domain from the high level rather than instantly going through the code. In other words, both business domain and technical part will be examined .The reason is because I believe that programming languages are just medium to translating business logic from machine-like language to human-readable language. There is no point for a linguist to translate a foreign book without understanding its content.

Here is the outline:

  • Squeeth Protocol ‘s Objective and Challenges
  • How the code architecture is organized?
  • Specification: Funding
  • Code: Funding
  • Specification: Schelling Point

Squeeth Protocol ‘s Objective and Challenges

To understand Squeeth, we need to understand what the problem protocol trying to solve is and what the relevant design challenges are.

The main objective of the protocol is to keep pegging the derivative’s price at ETH², although the underlying collateralize asset is very volatile in price. This is quite difficult, especially when the protocol allows anyone to mint the derivative as synthetic asset with trust-less permission-less manner.

But why trust-less and permission-less? The answer is that exposing anyone to participant without any control could possibly improve both user experience and scalability. For instance, decentralized exchange without KYC can target more users who are restricted in some regions and those who are dis-engaged by KYC’s UX.

However, the possible trade-off is security as there are more attack surfaces on economic and business layers. The protocol does not have direct control over the synthetic asset’s price. Instead, the protocol decentralizes its power to control the ecosystem’s behavior to users . This essentially means that protocol ’s neutrality and security are maintained by defining governance rule to users , and this can be achieved by encouraging participants’ specific behaviors.

For Squeeth, users can, on one hand, mint synthetic asset token’ and sell them on UniswapV3 at profitable price, given that the synthetic asset’s price is higher than it should be. This should pull the price down to equilibrium price . On the other hand, those minters , when the synthetic asset’s price is under-priced, are incentivized to buy those tokens back. Then, the price should be pushed back on the peg.

The main challenges are how incentive system is designed, how incentive amount is calculated and how the incentive is aligned to participants. Those have to be solved in trust-less manner.

In general, I personally classify the solutions to those challenges into three genres: 1) Non off-chain operators 2) Partially off-chain operator . It is noted that off-chain operator means human or human operate service

Non off-chain operators

The objective is archived via indirect control, using invariant & hyper structure. it is fully automated.

An invariant is a computer science term for a logical assertion about the state of something (a contract on our case) that is always true.

Example: Invariant- ERC20

The total of number of ERC20 tokens is always greater or equal to the sum of individual ERC20 balances of all token holders.

A hyperstructure is crypto protocol that can run forever, without maintenance, interruption or intermediaries

Example: Hyperstructure- UNISWAP

UNISWAP implements the AMM invariant model called “x*y = k market maker”. In simple words, there is the contract which holds token X and Y, of x and y tokens respectively, and the contract always maintain the invariant that x*y = k for some constant k. Then, users can swap token X for Y by essentially shifting the market maker’s position on the curve x*y = k. As you can see, invariant are pre-defined on smart contract. Once deployed, the defined rules are immutable, unstoppable, infinite and independent of any central authorities.

Partially off-chain operator

The objective is archived via indirect control, using robust incentive network. It still needs external parties to do some operation in order to keep system function-able. Generally, reward is given to incentivize such parties in order to participate in the network.

How the code architecture is organized?

The repository layout is tier-based.

Tier-based folder structure encourages specialists (e.g. front-end developer) to focus on their job. Single folder represents accountability.

In the folder packages/ , we could see folders for specialists in several domains, includingfrontend/ , hardhat/ , andsubgraph/ . In this article, we will focus in hardhat/ where smart contract codebase lies on.

Most of business logics come from /core/controllers.sol in /hardhat/contracts . In fact, this controller contract has three main dependency contracts, which are /core/ShortPowerPerp.sol , /core/WPowerPerp.sol , and /core/Oracle.sol .With Controller Contract, users can open/close short position. Then, ShortPowerPerp NFT (ERC721) and WPowerPerp tokens(ERC20)are minted/burned respectively. To calculate funding, Oracle contract plays role in keeping track of the UNISWAP price of DAI per ETH and oSQTH per ETH.

Specification: Funding (Non off-chain operators)

In-kind funding is a mechanism that short position holders automatically earn interest from Squeeth token holders (long position holders). It is noted that it is NOT direct payment. Instead, The swap price of Squeeth token (Symbol: oSQTH) on UNISWAP gradually decays, meaning that the token holders’ portfolio values will gradually decrease as time passes. Vice versa, the debt for short position holders are obligated to repay will reduce. Those figures are referenced by one single global variable called “normalization factor”.

The oSQTH price decreases over time as a result of funding rate

On the one hand, the Squeeth token follows ERC20 token standard, and the Squeeth trading price rely on Schelling Point (will be more explained below). The general idea is there is one metric for different stakeholders to decide different actions, so that the (synthetic) Squeeth token keep tracking with ETH².

The short position ,on the other hand, are non-fungible by collateral deposited and Squeeth token debt amount minted by short position holders. Each positions are unique, and conforms ERC721 standard. Those debt amounts are automatically adjusted by normalization factor. Their values should usually decay. After some time passes, such position holders could buy back Squeeth token, and then close position by repaying Squeeth token with fewer amounts. Mathematically³, the specification could be expressed as :

How the short position holder gains

Code: Funding

Most of funding-related computation rely on only single global variable, called ‘normalizationFactor’. It is declared in /core/controllers.sol .

uint128 public normalizationFactor;

To determine whether the short positions could be opened, closed, or even liquidated as well as whether user-selected collateral amount could be added or withdrawn from the positions, they use one helper function: getVaultStatus found in /libs/VaultLib.sol . It is noted that ‘normalizationFactor is applied as formula specified above.

Specification: Schelling Point²

By way of illustration, noon could be called as Schelling Point in time. It is classically considered the very middle of the day. But what makes it a Schelling point? The most important factor is that it is special. noon is the only time that is “exactly in the middle of the day”. Exceptionally, midnight could also be considered as Schelling Point. However, it is when people would be expected to be too sleepy to meet up properly .

How about Squeeth protocol? What is the Schelling point? Let understand how ETH² is archived first.

General Scenario:

  1. need to exchange value of ETH² for 1 oSQTH (it is noticed that the currency is USD per oSQTH)
  2. let derive this: USD per oSQTH = (USD per ETH) * (ETH per oSQTH)
  3. Two UNISWAP pools are required as following:
  • USD <-> ETH
  • ETH <-> oSQTH

Example: ETH is now $3000

  1. need to exchange value of 3000² DAI for 1 oSQTH
  2. let derive this: 3000² DAI per oSQTH = 3000² (DAI per ETH) * (ETH per oSQTH)
  3. Two UNISWAP pools are required:
  • USD <-> ETH : at 3000 DAI per ETH
  • ETH <-> oSQTH : at 3000 ETH per oSQTH

In order to make the price keep tracking with ETH², the protocol needs to make sure that the swap prices in above both pools keep in line with ETH price (in USD) on the biggest trading market (could be Binance or UNISWAP). It is clear that the trading pair of DAI and ETH should already keep pegging with ETH price.

So, the only objective left is to make sure that the trading pair of ETH and oSQTH keep tracking with ETH price. This is designed to be done by arbitrageurs. The SQUEETH protocol create new synthetic market by deploying a vault smart contract, called “controller”. With added liquidity in the secondary market, arbitrageurs will ,therefore, be able to trade minted oSQTHs at the secondary market (UNISWAP) to make profit from the difference in oSQTH price between two markets until the trading price are pushed to the appropriate quote. In particular, any one can mint oSQTHs by depositing ETHs as collaterals into the vault. Vice versa, those minters can buy oSQTHs back at lower price from UNISWAP, then burn them and redeem their ETHs back.

However, ETH is volatile asset .The key point is to ensure that oSQTH tokens which have been minted are always collateralized with adequate ETH amount. For example, ETH price has increased from 1,000 to 1,500 DAI per ETH. The minimum ETH required for collateral should be also changed to be at least 1,500 ETH per oSQTH. This means that more ETH should be added in vault as collateral by who has minted oSQTHs. If these minters do not add ETH to maintain their positions, they are at risk of being penalized by liquidation and losing their collaterals deposited. It is noted that those short positions should be over-collateralized, to such an extent that positions are not easily liquidated.

To sum up, the participants are, with both over-collateralized nature and liquidation mechanism, either incentivized or penalized to keep the ETH amount in the vault changing as the ETH price changes. Le

But the real question is: What is the Schelling Point which those participants use as decision metrics to take actions, including minting, burning, selling, and buying back oSQTH tokens?

The ETH price (in USD)? The reason could be that ETH collateralized in vault (ETH per oSQTH) should be keep in line with ETH price (USD per ETH). But!!! only the ETH price does not account for Funding rate mentioned before. Instead of directly using such ETH price, new metrics are designed. Basically, the new price for reference should include the normalization factor.

Practically, the Schelling Point is the distance between ETH² and the squeeth price. The full formula is:

The full formula. It is note that the % change is expressed in log ratio.

I note that 10,000 is just a scaling unit, making it natural to read.

This figure represents how much the trading price on UNISWAP after adjusting past paid funding is far from the index of ETH² in USD. Users can easily find out whether the trading price on UNISWAP is far above or under-priced.

If the distance is greater than zero by some extent, it incentivizes ANYONE to mint oSQTH token and sell it on UNISWAP. This will push the trading price down.

If the figure is too close to zero (or be negative but rarely), it incentivizes MINTERs to buy oSQTH token at lower price, then burn it. This will push the trading price up.

I note that as the payoff of oSQTH is ETH², funding rate is usually positive.

Apart from the reference point, this figure is abstracted and implemented as how the normalization factor is updated through demand and supply for oSQTH on UNISWAP as time passes. In other words, the decaying effect of funding on trading price of oSQTH should be included to the single global variable. Otherwise, all accounting logics related to the normalization factor will be wrongly updated. These include squeeth price as well as each debt amount in each short position.

Code: Funding (Continued)

But how the normalization factor is updated. It is indirectly updated when the contracts’ functions are called in /core/controllers.sol . They are deposit , depositUniPositionToken , withdraw ,withdrawUniPositionToken , liquidate , openDepositMint , and _burnAndWithdraw .

All these functions call a mutual helper function called _applyFunding .

Then, _applyFunding also call another helper function _getNewNormalizationFactor . This function fetch the datas from UNISWAP oracle contract. Then they are calculated as the difference between mark and index price, then the resulting figure is used to update the normalization factor.

Closing thoughts

We have seen the SQUEETH ‘s core mechanism and its implementation. The codebase is not that complex. It is not even use proxy design pattern. More importantly, It has only one main contract which is /core/controllers.sol .

The hardest part is to understand how the incentive system works under the hood, as the peg is maintained by arbitrageurs interacting with UniswapV3 contract. These actions are not explicitly shown in SQUEETH ‘s codebase, since it happens when those arbitrageurs swap on UniswapV3. What it is only shown is how SQUEETH’s contract fetch the relevant data from Uniswap Oracle.

Reference

[1]: Hull J.C.-Options.(2015). Futures and Other Derivatives_9th edition

[2]: Scott Alexander. (June 29 2012). Nash Equilibria and Schelling Points

[3]: Wade Prospere. (Jan 10 2022). Squeeth Primer: a guide to understanding Opyn’s implementation of Squeeth

[4]: Joseph Clark. (Dec 21 2021). Squeeth insides volume 1: funding and volatility

--

--