Coder Social home page Coder Social logo

ethereumdefi's Introduction

Hi there 👋

I am iri, a Computer Science student and enthusiast at IIT Roorkee. Born into the blockchain (mainly Ethereum as yet) ecosystem in 2022, here's a snapshot of my journey so far:

Hackathons

🔭 Learning

  • ZK, Cryptography, Ethereum Core, CS Fundamentals and more.

🔗 Connect

ethereumdefi's People

Watchers

 avatar

ethereumdefi's Issues

Defi Protocols #[1]

Compound: Money Market Protocol

  • Major flaws of blockchain assets:
    - Limited borrowing mechanisms, leading to mispriced assets(e.g. scamcoins).
    - Negative yield of assets due to storage costs and risks, leading to volatility.
  • Compound Protocol: Decentralized system for rictionless borrowing of Ethereum tokens without existing flaws, and creating a safe positive-yield approach to storing assets.
  • Money markets: Pools of assets with algorithmically derived interest rates, based on the supply and demand for the asset, unique to an Ethereum asset.
  • The protocol aggregates supply of each user, when user supplies asset it becomes a fungible resource, offering more liquidity unless each asset is borrowed, users can withdraw assets anytime without waiting for any a loan to mature.
  • When a supplier supplies asset to market, in return he is provided cTokens. As the money market recieves interest(function of borrowing demand), cTokens convert into increasing amount of underlying asset.
  • A user needs to specify a desired asset for borrowing, using cTokens as collateral.
  • each money market has a floating interest rate, set by market forces, which determines the
    borrowing cost for each asset.
  • Each market has a collateral factor, ranging from 0 to 1, that represents the portion of the underlying asset value that can be borrowed.
  • User’s borrowing capacity:The sum of the value of an accounts underlying token balances, multiplied by the collateral factors.
  • Close Factor: The portion of borrowed assets that can be repaid, ranges from 0 to 1. The liquidation process may continue to be called until the user’s borrowing is less than their borrowing capacity.
  • Utilization Ratio(U) for market 'a;: U_a = Borrows_a / (Cash_a + Borrows_a)
  • Borrowing Interest Rate of market a: Borrowing Interest Rate_a = 2.5% + U_a * 20%
  • Interest Rate Earned by supplier: Borrowing Interest Rate_a * U_a
  • In periods of extreme demand for an asset, the liquidity of the protocol (the tokens available to withdraw or borrow) will decline; when this occur, interest rates rise, incentivizing supply, and disincentivizing borrowing.

Implementation

  • Each money market - ERC20 token specification smart contract.
  • Users mint cTokens by supplying assets to market or redeem cTokens for underlying asset.
  • exchangeRate = (underlyingBalance + totalBorrowBalance_a − reserves_a) / cTokenSupply_a
  • Interest Rate Index: Captures the history of each interest rate, for each money market, which is calculated each time an interest rate changes, resulting from a user minting, redeeming, borrowing, repaying or liquidating the asset.
  • Index_a,n = Inde_a,n-1 * (1 + r*t)
  • totalBorrowBalance_a,n = totalBorrowBalance_a,(n-1) * (1 + r*t)
  • Reserves: Portion of received interest that is retained, reserveFactor ranges 0 to 1.
    reserves_a = reserves_a, n-1 + totalBorrowBalance_a,n-1 * (r*t*reserveFactor)
  • Borrower's Balance: ratio of the current index divided by the index when the user’s balance was last checkpointed.
  • The balance for each borrower address in the cToken is stored as an account checkpoint. An account checkpoint is a Solidity tuple <uint256 balance, uint256 interestIndex> . This tuple describes the balance at the time interest was last applied to that account.
  • borrow(uint amount) : t. This function call checks the user’s account value, and given sufficient collateral, will update the user’s borrow balance, transfer the tokens to the user’s Ethereum address, and update the money market’s floating interest rate.
  • Liquidation: If a user’s borrowing balance exceeds their total collateral value (borrowing capacity) due to the value of collateral falling, or borrowed assets increasing in value, the public function liquidate(address target, address collateralAsset, address borrowAsset, uint closeAmount) can be called, which exchanges the invoking user’s asset for the borrower’s collateral, at a slightly better than market price.
  • Comptroller: Policy layer, validates each function call. Validates collateral and liquidity before allowing user action to proceed.

Questions

  1. How the protocol avoids the risk whenever borrowing amount exceeds borrowing capacity? Had difficulty understanding this,
    If the value of an account’s borrowing outstanding exceeds their borrowing capacity, a portion of the outstanding borrowing may be repaid in exchange for the user’s cToken collateral, at the current market price minus a liquidation discount ; this incentives an ecosystem of arbitrageurs to quickly step in to reduce the borrower’s exposure, and eliminate the protocol’s risk.
  2. How does the protocol decides the Interest Rate?
  3. The protocol incentivizes lenders to to lend to the market by giving them cTokens whose value may increase due to the interest rates or market demand but how is it incentivizing the borrowers to borrow from the market?
  4. What does the function repayBorrow(uint amount) do?
  5. When the borrowers assets are liquified due to collateral falling or borrowed assets' value increase, the liquidate function is called. Who calls this function? Does the contract keeps check of this from time to time?

Automated Market Makers

  • Replace order book model with autonomous protocol.
  • AMM -algorithm that helps in pricing of assets.
  • Trading pairs represented as individual liquidity pools.
  • Liquidity providers work by adding funds to liquidity pools. Liquidity providers can earn a certain share of fees from the trades occurring in their pool for providing liquidity in the automated market maker algorithm.
  • Higher levels of liquidity in the pool ensures limited possibilities of slippage for large orders.
  • Impermanent Loss: happens when the price ratio of the tokens you have deposited in a liquidity pool changes after you have deposited the tokens in the pool.
  • Arbitrage is the simultaneous buying and selling of, in our case, a token to make a profit

Yield Farming:

  • First an investor stakes their coins by depositing them into a lending protocol.
  • In return for providing liquidity to the pool, LPs get a reward which comes from fees generated by the underlying DeFi platform, or some other source.
  • On top of fees, another incentive to add funds to a liquidity pool could be the distribution of a new token.
  • APR doesn’t take into account the effect of compounding, while APY does. Compounding, means directly reinvesting profits to generate more returns.

Uniswap

  • It is a collection of smart contracts that define a standard way to create liquidity pools, provide liquidity, and swap assets.
  • Each pool has 2 assets. Pools keep track of aggregate liquidity reserves. x*y = k
  • The reserves are automatically balanced after each trade.
  • v3: liquidity allocated within custom price range(concentrated liquidity).
  • As asset's price increases or decreases, it may exit the price bounds that LPs have set in a position. When price exits the position interval, the position's liquidity becomes inactive.
  • Ticks: Continuous price space divided with ticks to achieve concentrated liquidity. Ticks are spaced such that an increase or decrease of 1 tick represents a 0.0001% increase or decrease in price at any point in price space.
  • Ticks- boundaries for liquidity positions. When a position is created, the provider must choose the lower and upper tick that represents their position's borders.
  • Crossing an active tick increases the cost of the transaction in which it is crossed, as the tick crossing will activate the liquidity within any new positions using the given tick as a border.
  • Narrow tick spacing improves prices for stable coin swaps.

Curve Finance

  • Allows users and other decentralised protocols exchange stablecoins (DAI to USDC for example) through it with low fees and low slippage.
  • Curve implements StableSwap invariant of stablecoin trades, which have significantly lower slippage.
  • Stable coins - problem of price stability and liquidity.
  • StableSwap - automated liquidity provider for stablecoins
  • Demand side - offers Uniswap like automated exchange with low slippage.
  • Supply Side - offers a multi-stablecoin saving account

Uniswap

  • "constant product" market making formula
  • Selling ETH for ERC20 tokens --> increases the size of the ETH reserve and decreases the size of the ERC20 reserve --> shifts the reserve ratio, increasing the ERC20 token's price relative to ETH for subsequent transactions.
  • Limit Order: traders can specify the minimum amount bought on sell orders or the max amount sold on buy orders --> limti order --> automatically cancels if not fulfilled.
  • Transaction deadlines: cancel orders if they are not executed fast enough.
  • Only one exchange per token can be registered
  • Factory contract: can be used to create exchange contracts for any ERC20 token that does not already have one.
  • separate exchange contract for each ERC20 token --> hold reserves of both ETH and their associated ERC20.

Token Standards

ERC721

  • Nonfungible assets: unique and non-divisible, a title of ownership of unique, non-replicable item, one-of-a-kind. Store data rather than value( which is stored in fungible tokens).
  • Each NFT has globally unique tokenID and contract address.
  • Events: Transfer, Approval, ApproveForAll
  • Functions: balanceOf(owner) - returns count of NFTs associated with owner.
    ownerOf(tokenId) - returns owner of an NFT
    safeTransferFrom(from,to,tokenId,data) - throws if 'to' address is address[0]
    transferFrom(from,to,tokenId) - 'from' needs to verify 'to' address is capable of
    receiving, else NFT lost
    approve(approved,tokenId) - change or reaffirm approved address, zero address
    means no one approved.
    setApprovalForAll(operator, approved) - approve operator to manage assets
    getApproved(tokenId) - get approved address of tokenId
    isApprovedForAll(owner,operator) - true if operator is approved for owner.
  • Metadata - name(), symblo(), tokenURI()
  • Enumeration extension: If application is able to grow then avoid using for/while loops in the code These indicate the contract may be unable to scale and gas costs will rise over time without bound.

Questions

  1. Fungible tokens store value as Bitcoin and ERC20 whereas NonFungible Tokens store data. What does data and value refer to here?
  2. What does quantity or totalSupply of token denotes? The tokens are unique so how can we have more than one of the same token?
  3. Use of data parameter while calling safeTransferFrom? What it actually contains?
  4. 'The ERC721 smart contract calls onERC721Received on the recipient after a transfer. This function may throw to revert and reject the transfer. Return of other than the magic value MUST result in the transaction being reverted'. What is the magic value here?

Defi Protocols #[2]

AAVE

  • Lenders provide liquidity by depositing crytocurrencies in a pool contract, the pooled funds can be borrowed by placing collateral.
  • Interest rates: for borrowers - depends on cost of money - amount of funds available in pool at specific time. More borrowing -> less funds -> higher interest rate.
  • Interest rates: for lenders - corresponds to earn rates
  • Every pool holds reserve in multiple currencies, total amount in Ethereum defined as total liquidity.
  • Reserve accepts deposits from lenders. Users borrow these funds, by locking greater value as collateral(low risk tokens considered) which backs the borrow position.
  • Every reserve has specific Loan-to-Value(LTV) calculated as weighted average of different LTVs of currencies composing the collateral.
  • Weight of each LTV = equivalent amount of collateral in ETH
  • Every borrow position can be opened with stable or variable rates.
  • In case of price fluctuations, borrow position might be liquidated. Liquidation happens when price of collateral drops below the threshold, Lq (Liquidation Threshold). Reaching this ratio channels a liquidation bonus, which incentivizes liquidators to buy collateral at discounted price.
  • At any point the borrow position is checked using the Health factor Hf, a function of total collateral and total borrows which determines if the loan is undercollaterized.
  • Hf = (TotalCollateralETH * Lq(avg))/(TotalBorrowsETH + TotalFeesETH)
  • Hf <1 -> undercollaterized loan, can be liquidated.
  • LendingPoolCore Contract: holds state of every reserve and the assets deposited, handles basic logic(calculations etc.)
  • LendingPoolDataProvider Contract: performs calculations on higher level of abstraction than LendingPoolCore, calculates ETH equivalent a user's balance( borrow balance, collateral balance, liquidity balance) to check how much user is allowed to borrow and the health factor, collects data from lending pool to provide higher level of information to LendingPool, calculates Avg Loan-To-Value and Avg Liquidation Ratio.
  • LendingPool: uses LendingPoolCore,LendingPoolContract to interact with reserves. Implements Tokenization of lending position, when user deposits currencies, receives aTokens.
    User -> check state -> check conditions -> satisfied, update liquidity/borrow inices -> change state to execute action -> update interest states -> external transfers.
  • LendingPoolConfigurator: provides main configuration functions for LendingPool and LendingPoolCore(reserve initialization, reserve configuration, enable/disable borrowing, enable/disable usage reserve as collateral)
  • Redeem action- allows user to exchange aTokens with underlying asset.
  • The Repay action allows user to repay borrowed amount plus the origination fees and accrues interest. Origination fees - 0/5% to 1% of loan amount for processing loan application.
  • Swap Rate Action allows user with borrow in progress to swap between variable and stable borrow rate.
  • Stable rates act as a fixed rate in the short-term, but can be re-balanced in the long-term in response to changes in market conditions. The variable rate is the rate based on the offer and demand in Aave.
  • Flash Loan: allows users to borrow reserves within a single transaction, as long as the user returns more liquidity that has been taken. Flash loans temporarily transfer funds to a smart contract respecting IFlashLoanEnabledContract.sol interface. excuteOperation() called when funds transferred. Check is performed to verify that funds +fee is returned to LendingPool contract.
  • Stable rate theory - time, rate constraints.

Questions

  1. Why health factor is checked when a user performs redeem action? He is not borrowing assets by providing collateral rather is exchanging aTokens.
  2. Why is the liquidation call reverted if the amount of collateral in principal currency with discount is above 50% of principal borrow balance?
  3. Is there a specific currency or reserve in which the borrower needs to pay the interest rates? How aTokens implement interest rate redirection?

Notional Finance

nTokens

  • nTokens are ERC-20 tokens that enable users to provide liquidity across all active maturities without interacting with specific liquidity pools tied to a particular maturity. This means that the LP can make a single deposit into one liquidity pool using cTokens which distributes liquidity across underlying pools and the LP with nTokens.
  • holders of nTokens earn interests in 3ways:
    • blended rate of interest earned from cTokens and fCash held by nToken account. This rate will sit somewhere between the fCash interest rate and cToken supply rate. borrowing drives up interest rates, the nToken accounts receive fCash while cToken are deposited. The opposite holds true for falling interest rates and greater demand to lend.
    • nToken owners can earn a return through traditional liquidity fees which may be offset by impermanent loss. Potential for nTokens to achieve impermanent loss is low given stable exchange rates of fCash.
    • Third, is the accrual of NOTE tokens, Notional’s governance token, which are awarded proportional to the total share of nTokens in a specific currency.
  • Lending and borrowing on Notional is facilitated by liquidity providers who hold nTokens.
  • When redeeming nTokens, fCash will be sold on the market to convert it back to cash. There are slippage costs associated with this that may make it impossible to redeem nTokens as cash.
  • method called nTokenRedeem that allows accounts to manually redeem nTokens without selling fCash. nTokens will always be redeemable via this second method.
  • nTokens are automatically listed as collateral inside Notional.
  • an account can borrow ETH against nETH and then use that ETH to mint additional nETH. This is called providing liquidity on leverage, and the maximum amount of leverage allowed is determined by the nToken PV Haircut percentage.
  • NOTE incentives for a particular currency are automatically claimed and transferred whenever an nToken balance is changed (minted or redeemed), manually - nTokenClaimIncentives.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.