Lending can be seen as leverage. For example, I predict ETH price is going up in the near future. I supply 10 ETH as collateral to Compound and borrow 300 DAI. I would buy more ETH using this 300 DAI I just borrowed, so that when ETH price indeed goes up my asset total value goes up even more. I will buy 300 DAI with my ETH balance and repay the loan, and I still have more ETH at hand because ETH price went up. These extra ETH is my profit. This is called "long ETH".
"Short ETH" is just the other way around. If we expect ETH price to drop, we can deposit DAI as collateral and borrow ETH. Then we sell these borrowed ETH and buy DAI. When the price of ETH does go down, we sell DAI and buy ETH, then pay back the loan. We will be left some DAI and that is our profit.
We will be writing functions to long ETH. It takes the following steps:
supply ETH
borrow stable coin (DAI, USDC)
buy ETH on Uniswap
When the price of ETH goes up:
sell ETH on Uniswap
repay borrowed stable coin
Code:
Setup
Nothing special here:
CEth public cEth;CErc20 public cTokenBorrow;IERC20 public tokenBorrow;uintpublic decimals;Comptroller public comptroller =Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);PriceFeed public priceFeed =PriceFeed(0x922018674c12a7F0D394ebEEf9B58F186CdE13c1);IUniswapV2Router privateconstant UNI =IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);IERC20 privateconstant WETH =IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);constructor(address_cEth,address_cTokenBorrow,address_tokenBorrow,uint_decimals) { cEth =CEth(_cEth); cTokenBorrow =CErc20(_cTokenBorrow); tokenBorrow =IERC20(_tokenBorrow); decimals = _decimals;// enter market to enable borrow// we are going to supply ETH (cEth)address[] memory cTokens =newaddress[](1); cTokens[0] =address(cEth);uint[] memory errors = comptroller.enterMarkets(cTokens);require(errors[0] ==0,"Comptroller.enterMarkets failed.");}receive() externalpayable {}
Step 1: supply ETH
We deposit ETH into Compound as collateral, which is equivalent to minting cEth:
Step 2 and 3: borrow stable coin (DAI, USDC) and buy ETH on Uniswap
Compute how much DAI we can borrow:
functiongetMaxBorrow() externalviewreturns (uint) {// This is the amount we can borrow in USD (uinterror,uint liquidity,uint shortfall) = comptroller.getAccountLiquidity(address(this) );require(error==0,"error");require(shortfall ==0,"shortfall > 0");require(liquidity >0,"liquidity = 0");// Price is also in USDuint price = priceFeed.getUnderlyingPrice(address(cTokenBorrow));uint maxBorrow = (liquidity * (10**decimals)) / price;return maxBorrow;}