Giter Site home page Giter Site logo

marginswap-interface's Issues

Fix risk gauge

The risk gauge on the Margin Account page is not working correctly. Probably because the algorithm is not correct.

Look at this for how it should work:
https://www.binance.com/en-IN/support/faq/360030493931

DrO says:
When margin level≤1.15, our system will trigger the liquidation engine and we will send you a notification by mail, text message and internal message to inform you that all assets will be liquidated to pay back the interest and loan.
1.15 is when we trigger
but when we get on faster chains, we will probably reduce to 1.1
Ethereum is too slow and clogged for us to do 1.1

Replace the swap ui with the swap ui in margin account

Go to https://master--nifty-poitras-d43873.netlify.app/ to quickly see the current state of UI mockup.

This is the most important change we need to do today: The margin account is only supposed to display account information, without the current swap side bar:

image

This swap part currently displayed in the margin account view is supposed to replace the main trading UI:
image

So, please find those two components and replace them. For now this replacement can be relatively quick & dirty!

Get correct borrow interest rate from Lending contract

If I'm not mistaken the borrow interest rate displayed currently is just the lending interest rate times 2, which is correct in the general case, but not always. We should create an SDK endpoint that gets the borrowing interest rate from the Lending smart contract directly instead.

Several tiny ui/ux issue

We need a couple of explainer for the table on margin account and bond lending page

  1. Margin account page
  • APR: change to 'Interest' add % to the rate, for example, 5% instead of just 5. Can we also have an interactive explainer on Interest that say 'Interest will start accruing per block as soon as a token is borrowed for a margin trade'
  • Liquidity: 'This is the total amount of an asset available to be borrowed for a trade'
  • Borrowable: 'This is the total amount you can borrow with your equity'

Bond lending
APY: Cap at 2 decimal and add % sign
Total supplied: Also cap the UI element at 2 decimal (just the ui)

This is a how to video link. Can we have it on the ui? https://www.youtube.com/watch?v=rGGPAOCpDRs

Find out how we can generalize the search for best route

In this file the code that we forked tries to find the best route for a specific trade on uniswap.
What we want is to generalize from just uniswap to using sushiswap as well, for looking for trading routes.

Please look for the best place in the code where we could generalize over getting data from uniswap to getting data from both uniswap and sushiswap and choosing the best route on the best system.

Liquidity, borrowable columns

rename what's currently called liquidity in the margin account table to "borrowable"
and create a new column that lists the entire liquidity in that token, not just how much an individual trader can currently borrow.

State and updates

Blockchain I/O

Input

We can query the ethereum blockchain via infura directly, as well as through wallets such as metamask. Both infura and metamask act as providers to frameworks such as ethers or web3.

Next to async requests, the infura provider also offers websocket connections with listeners which we can use in conjunction with events in our contracts to update account state without polling.

Output

The wallet is used to send signed transactions to the blockchain.

State

Accounts

  • Wallets can have multiple accounts/addresses/keypairs.
  • We ultimately want to make the whole UI switchable between addresses (maybe we put the index of the account in the URL fragment), but for the first version we can just assume that we use the first address

Balances

  • CrossMargin trading accounts
  • Lending
  • Rewards staking

In both lending and borrowing the set of possible tokens is fixed, hence there is a very common case where we will just iterate over the list of tokens and get information like interest rate, price or the bond lending balance for each token in the list.
The cross margin trading account has a view function that returns just the tokens that an account holds and borrows (and their balances).

Trading

  • Price information
  • Current UI state of trading interface
  • Bonus: Pending transactions (and listen for their resolution, which seems to be supported by ethers)

Some of the logic for getting and updating prices, tracking transactions etc. already exists in uniswap and hopefully we can reuse it.

Rollout strategy

  • Users need to grant the page access to their wallet before it can be queried or written to. That said, if it is easier structurally, we can do certain queries through the wallet (e.g. fields in tables), even if they don't need access to the user's key, at least for now.
  • We can first build out the entire functionality based on one-off queries to the blockchain which do not update.
  • Before we launch our final contracts we will need a list of all possible update events that the UI might listen for and we should make sure to add them to all our contracts
  • Then we can add state updates based on websocket event listeners

Hide unfinished parts

Make a branch where unfinshed stuff is hidden

  • the MFI pill
  • borrow / repay buttons
  • staking

Trading account overview component

NEW SPEC:

Modify Balances component to match this wireframe, i.e. it will include borrowing / dept, so we don't need a separate component:

image

  • Add a total account balance row at the top
  • [We still will need deposit and borrow token choice forms, but we need to decide where to put them, maybe it's a dialogue]

Withdraw `MAX` sometimes withdraws too much

the max button on withdraw doesn't leave enough dust and then transactions can fail.
MAX should pick an amount with some additional buffer.

Also when a user has debt that hasn't be paid, it makes sense that the user can't withdraw max.

Get best trading routes from both sushiswap and uniswap

Our code executes trades using ERC20 tokens on on-chain markets such as uniswap or sushiswap. We forked the uniswap code, but we want to expand it to not only do trades on uniswap, but also on sushiswap (which is compatible), if the price on sushiswap is better.

In this file the code that we forked tries to find the best route for a specific trade on uniswap: useTradeExactIn and useTradeExactOut both call to the Pair class in the SDK. Currently this Pair class imports a constant called FACTORY_ADDRESS.

  • Instead of this constant, make factoryAddress an attribute of the class Pair.
  • useAllCommonPairs should retrieve pairs for both uniswap and sushiswap.
  • You may need to modify the rest of the code to handle the fact that there now can be more than one pair with the same two tokens.

You may run into problems testing this. Let me know

Disable editing the token list in margin

Right now users can edit the token list and add tokens to the margin account interface -- which just got one user confuse.

image

They probably clicked on the manage button and imported their favorite token and were disappointed they couldn't trade it.

For now we should make sure that in margin we only show our approved token list

Cap borrowable amount on margin swaps based on liquidity

On swap page, the borrowable amount should not exceed the available liquidity in any given token.

This goes for both the displayed borrowable amount and the input validation. They should both be capped so they don't exceed the liquidity available for the selected token.

Add total available for borrowing

The margin account table should have a column for total amount available for borrowing in that token, using this endpoint. Furthermore, the borrowableInPeg2token function in src/state/wallet/hooks/ should cap any borrowable amount in that token by that total amount.

Token choice and transaction form template

We need a form to

  • Choose a token from a dropdown with token name and icon
  • enter an amount in a form field
  • a button to confirm the transaction (we'll have different labels for different transaction types)

A lot of the necessary building blocks should be in the code (i.e. the dropdown with tokens should be in the trading window code).

Swap component

  • we likely want to unify pagerswap and swap components, please evaluate
  • all the behavior & state that was attached to the old swap component should now work 1:1 in the "spot"' tab of the swap component
  • some of the state & parts such as price and routes should also be applicable to the margin tab

If while going through this you gain a good understanding you can look at the contract contracts/MarginRouter.sol in the core repo, find the parallels to the uniswap router in the functions like crossSwapExactTokensForTokens and work towards wiring them up similarly to the classic uniswap router contract.

Bond Lending component

BOND LENDING

Some of these will require SDK functions and maybe view functions in the contracts.

columns in table

  1. Coin
  2. Total Supplied
  3. APY -- Let's actually calculate this off-chain. APY = (100 + APR/n)**n - 100, where APR is a percentage and n = 24 * 365,i.e. hours per year.
  4. Maturity (make it hourly, maybe a count down? users can withdraw within 10 minutes at the beginning of every hour) -- for this you need to get the modulohour property from the HourlyBondSubscriptionLending contract. Either by reading the struct directly from this public variable, which would be called as HourlyBondSubscriptionLendingContract.hourlyBondAccounts(token, lenderAddress), which I believe returns a tuple which I'm not sure how `ethersjs parses that out. Alternatively we could write a new view function or add it to an existing view function.
  5. Actions (withdraw and deposit) -- Speak to the relevant functions in Lending, similarly to how crossDeposit works in the margin-account part of the SDK.

The 3 cells on top of the table

  1. Total Bond (in $) -- the sum of all hourly bonds held by the user, converted to the reference currency. You can get the price by calling this function. The PriceAware contract class is deployed at the same address as the CrossMarginTrading contract -- you may need to use the address of CrossMarginTrading, but the .abi of PriceAware when initializing the Contract object in the typescript code.
  2. Average Yield ( 10 %) -- weighted sum of all APY, weighted by the dollar amount of the hourly bond in that token.
  3. Earnings per day (in $) weighted sum of APR / 365

Please delete the BOND RATE table.

Restore token list logic

As discussed, I deleted token list logic and probably broke something in loading the token list for the margin account and bond supply page. perhaps dig through the git history and restore the appropriate functions

Approve error toast on successful transactions

On localhost, I first went to deposit 10 DAI in bond. clicked approve, and approved in metamask, then I see an "approve error" red toaster, followed by a notification from metamask that my transaction was completed successfully.
I then go and deposit 10 DAI into my margin account and click "borrow" to borrow 10 dai. again I get an "aprrove error" toast, on the borrow button, even though borrow should have nothing to do with approve

Feature flags

Add feature flags for "Stake" tab and ETH buttons in Margin Account table.

Stake tab should not be visible by default. Use ?stake=1 to view it.
on the Margin Account page, the "Deposit ETH" and "Withdraw ETH" buttons should not be visible by default. use ?eth=1 to view them

Display maturity countdown

the maturity column should display how many minutes until an hourly bond can be withdrawn.
does the current logic work, because I see nothing. maybe it's nothing coming back from the smart contract? please debug

Account balances component

We want a box component that contains a listing of:

  • Token icon & name
  • Current balance

There should be code for getting token icons and names from the token address somewhere in the repo.
If that's easy to find, make the component take that data structure as input, otherwise just make something up and we'll figure it out later.

Get available tokens for cross margin trading

For the swap page we need to calculate how much of a token a user can trade, which is a combination of how much they hold and how much they can borrow.

For this we need to get:

  • The amount of that token that he user holds from getHoldingAmounts in the SDK
  • getAccountHoldingTotal and getAccountBorrowTotal
  • borrowTargetInPeg = 3 * (holdingTotal - borrowTotal)
  • Some way to convert borrowTargetInPeg back into the original token. (there should be code repo already for querying the price along the best route?) -- let me know if you wanna talk about this.

The available amount is borrowTargetInToken + holdingAmounts

borrowed value varies over time

when I borrow tokens, the number displayed in margin accounts can go up and down more than it should. it even dips below the original amount. may well be on the contract side, but worth checking whether it's a UI thing

Account balance header numbers are inconsistent decimals

they should be in the decimals of the peg currency.
On kovan right now, DAI is the peg currency. It has 18 decimals. On local it's currently USDT which has 6. For now just make the number of peg decimals configurable somewhere in a constant.
We may switch everything over to DAI, need to discuss.

Can't enter fractions

On the bond supply page and probably also on the margin account page the input fields don't allow for fractions (i.e. numbers with a decimal point), they should and the fractions should be then interpreted according to the decimals of the token that is being entered.

Get borrowable from SDK

If the swap page is in margin mode, we should show the (previously hidden) borrowable field and show the value that gets computed in the borrowable function, (aplied to the input token) in the SDK newly added

Header boxes in margin account

issue example

👉Total account balance = conversion and addition of the holding in the total balance section of the table
👉Debt = conversion and addition of the holding in the debt section of the table
👉Equity = Total account balance minus the debt

Margin trade if you don't have balance

Currently some check in the swap logic sensibly keeps you from trading if you don't have enough balance in a token.

Ideally we would calculate holdings + borrowable for this. For now we can just torn off the check?

Run a full test of borrow interest rate on local

Basically:

  • change variables here: RATE_UPDATE_WINDOW = 0 seconds; withdrawalWindow = 60 minutes
  • npx hardhat node
  • deposit 10 DAI in margin trading
  • deposit 10 DAI in bond lending
  • borrow 10 DAI in margin trading
  • deposit 2 DAI in lending, then 10, then 100
  • record the borrow / lending interest at every utilization level
  • finally withdraw bond back down to 10 dai and record interest rates

Make whole UI mock

Please replace the menu bar with the following items:

  • Trading
  • Lending
  • Margin account
  • Staking

And link to the views that you have developed

Margin Account

Fields

Top

  • Total Account balance: The total value of the account holdings in USD, without considering debt
  • Debt: total value of debt in USD
  • Equity = Total Account Balance - Debt
  • Margin Risk Level = Equity / Debt: High risk is at 1.1 or below, low risk is at 1.34 or above.

Account balance per token

all the following amounts are denominated in the token itself (not USD)

  • Coin: name and logo taken from token list
  • Total balance: holding amount
  • Available balance = Total Balance - pending transactions: do not implement yet, hide for now
  • Borrowed: borrow amount
  • Interest rate: borrowing APR queried from lending contract

Actions

  • Borrow: max is the maximum amount the account is allowed to borrow to stay within the leverage limit, minus 5%
  • Repay: max is total balance in that token
  • Withdraw: max is queried from contract
  • Deposit: max is balanceOf that token in wallet. Before depositing we need an approve step (in case we haven't approved that token yet), which could just be the same button like in the swap interface

Swap

Spot

The spot interface should have the exact same behavior that the existing uniswap swapping interface has

Margin

The price / routing parts of the interface should have the same behavior, only that balances come from the margin account contract. Swap transactions should be sent to the margin router.
Also the margin interface only allows using the marginswap token list (you have access to the repo).

the swap button is replaced by a "connect wallet" button if it's not connected.

Margin Account Fixes

  • We probably should use TokenAmount as the value for setHoldingAmounts and setBorrowingAmounts in src/pages/MarginAccount/index.tsx L87-88 and then change the calls in L246-251 to create TokenAmounts from the address of the token and the value. -- and then we probably want to use the formattedCurrencyAmount function to format those strings

wallet connection logos broken

when I click to connect my wallet i see broken image stuff instead of wallet logos. do we need api keys to laod the logos or is it something else?

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.