Skip to content

Commit

Permalink
Merge pull request #795 from divaprotocol/fix-break-even
Browse files Browse the repository at this point in the history
Fix break-even calc
  • Loading branch information
Walodja1987 authored Jul 20, 2023
2 parents 20d802e + 117b1f1 commit 32cfacd
Show file tree
Hide file tree
Showing 14 changed files with 86 additions and 94 deletions.
4 changes: 2 additions & 2 deletions packages/diva-app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Markets from './component/Markets/Markets'
import { useAppSelector } from './Redux/hooks'
import { LoadingBox } from './component/LoadingBox'

import { config, DIVA_GOVERNANCE_ADDRESS } from './constants'
import { config, DEFAULT_MARKETS_CREATED_BY } from './constants'
import { WrongChain } from './component/Wallet/WrongChain'
import Dashboard from './component/Dashboard/Dashboard'
import { Offer } from './component/CreatePool/Offer'
Expand Down Expand Up @@ -46,7 +46,7 @@ export const App = () => {
<CreatePool />
</Route>
<Route path="/">
<Redirect from="/" to={`/markets/${DIVA_GOVERNANCE_ADDRESS}`} />
<Redirect from="/" to={`/markets/${DEFAULT_MARKETS_CREATED_BY}`} />
</Route>
</Switch>
) : (
Expand Down
2 changes: 1 addition & 1 deletion packages/diva-app/src/DataService/OpenOrders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import axios from 'axios'
import {
config,
NULL_ADDRESS,
DIVA_GOVERNANCE_ADDRESS,
TRADING_FEE_RECIPIENT,
TRADING_FEE,
} from '../constants'
import { BigNumber, ethers } from 'ethers'
Expand Down
4 changes: 2 additions & 2 deletions packages/diva-app/src/Orders/BuyLimit.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { parseUnits, splitSignature } from 'ethers/lib/utils'
import { NULL_ADDRESS } from './Config'
import { config } from '../constants'
import { DIVA_GOVERNANCE_ADDRESS, TRADING_FEE } from '../constants'
import { TRADING_FEE_RECIPIENT, TRADING_FEE } from '../constants'
import { getFutureExpiryInSeconds } from '../Util/utils'
import { zeroXTypes, zeroXDomain } from '../lib/zeroX'
// eslint-disable-next-line @typescript-eslint/no-var-requires
Expand Down Expand Up @@ -38,7 +38,7 @@ export const buylimitOrder = async (orderData) => {
takerAmount: nbrOptionsToBuy.toString(),
maker: orderData.maker,
sender: NULL_ADDRESS,
feeRecipient: DIVA_GOVERNANCE_ADDRESS,
feeRecipient: TRADING_FEE_RECIPIENT,
takerTokenFeeAmount: positionTokenFeeAmount.toString(),
expiry: getFutureExpiryInSeconds(orderData.orderExpiry),
salt: Date.now().toString(),
Expand Down
4 changes: 2 additions & 2 deletions packages/diva-app/src/Orders/SellLimit.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { parseUnits, splitSignature } from 'ethers/lib/utils'
import { NULL_ADDRESS } from './Config'
import { utils } from './Config'
import { config } from '../constants'
import { DIVA_GOVERNANCE_ADDRESS, TRADING_FEE } from '../constants'
import { TRADING_FEE_RECIPIENT, TRADING_FEE } from '../constants'
import { getFutureExpiryInSeconds } from '../Util/utils'
import { zeroXTypes, zeroXDomain } from '../lib/zeroX'
// eslint-disable-next-line @typescript-eslint/no-var-requires
Expand Down Expand Up @@ -40,7 +40,7 @@ export const sellLimitOrder = async (orderData) => {
takerAmount: collateralTokenAmount.toString(),
maker: orderData.maker,
sender: NULL_ADDRESS,
feeRecipient: DIVA_GOVERNANCE_ADDRESS,
feeRecipient: TRADING_FEE_RECIPIENT,
takerTokenFeeAmount: collateralTokenFeeAmount.toString(),
expiry: getFutureExpiryInSeconds(orderData.orderExpiry),
salt: Date.now().toString(),
Expand Down
9 changes: 5 additions & 4 deletions packages/diva-app/src/Redux/appSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ import {
} from '../Models/orderbook'
import {
config,
DIVA_GOVERNANCE_ADDRESS,
DEFAULT_MARKETS_CREATED_BY,
TRADING_FEE_RECIPIENT,
NULL_ADDRESS,
DEFAULT_TAKER_TOKEN_FEE,
DEFAULT_THRESHOLD,
Expand Down Expand Up @@ -234,7 +235,7 @@ export const fetchPools = createAsyncThunk(
})

const taker = NULL_ADDRESS
const feeRecipient = DIVA_GOVERNANCE_ADDRESS
const feeRecipient = TRADING_FEE_RECIPIENT
const takerTokenFee = DEFAULT_TAKER_TOKEN_FEE
const threshold = DEFAULT_THRESHOLD
const count = 1
Expand Down Expand Up @@ -582,12 +583,12 @@ export const selectToken = (state: RootState, poolId: string) => {

export const selectMainPools = (state: RootState) =>
selectAppStateByChain(state).pools.filter(
(p) => p?.createdBy === DIVA_GOVERNANCE_ADDRESS.toLowerCase()
(p) => p?.createdBy === DEFAULT_MARKETS_CREATED_BY.toLowerCase()
)

export const selectOtherPools = (state: RootState) =>
selectAppStateByChain(state).pools.filter(
(p) => p?.createdBy !== DIVA_GOVERNANCE_ADDRESS.toLowerCase()
(p) => p?.createdBy !== DEFAULT_MARKETS_CREATED_BY.toLowerCase()
)

export const selectChainId = (state: RootState) => state.appSlice.chainId
Expand Down
23 changes: 12 additions & 11 deletions packages/diva-app/src/Util/calcPayoffPerToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,40 +90,41 @@ export function calcBreakEven(
cap = BigNumber.from(cap)
gradient = BigNumber.from(gradient)

// Scale gradient to 18 decimals for calculation purposes as floor, inflection, etc.
// have 18 decimals
// Scale gradient and price to 18 decimals for calculation purposes
// as floor, inflection, etc. have 18 decimals
const gradientScaled = gradient.mul(SCALING)
const priceScaled = price.mul(SCALING)

let breakEven

if (price.gt(UNIT) || price.lt(BigNumber.from(0))) {
if (priceScaled.gt(UNIT) || priceScaled.lt(BigNumber.from(0))) {
breakEven = 'n/a'
} else {
if (isLong) {
if (price.eq(gradientScaled)) {
if (priceScaled.eq(gradientScaled)) {
breakEven = inflection
} else if (price.lt(gradientScaled)) {
breakEven = price
} else if (priceScaled.lt(gradientScaled)) {
breakEven = priceScaled
.mul(inflection.sub(floor))
.div(gradientScaled)
.add(floor)
} else {
breakEven = price
breakEven = priceScaled
.sub(gradientScaled)
.mul(cap.sub(inflection))
.div(UNIT.sub(gradientScaled))
.add(inflection)
}
} else {
if (price.eq(UNIT.sub(gradientScaled))) {
if (priceScaled.eq(UNIT.sub(gradientScaled))) {
breakEven = inflection
} else if (price.gt(UNIT.sub(gradientScaled))) {
breakEven = UNIT.sub(price)
} else if (priceScaled.gt(UNIT.sub(gradientScaled))) {
breakEven = UNIT.sub(priceScaled)
.mul(inflection.sub(floor))
.div(gradientScaled)
.add(floor)
} else {
breakEven = UNIT.sub(price)
breakEven = UNIT.sub(priceScaled)
.sub(gradientScaled)
.mul(cap.sub(inflection))
.div(UNIT.sub(gradientScaled))
Expand Down
18 changes: 10 additions & 8 deletions packages/diva-app/src/component/Graphs/TradeChart.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export default function DIVATradeChart(props) {
}))

const optionTypeText = isLong ? 'LONG' : 'SHORT'
const reffeenceAsset = refAsset.slice(0, 8)
const referenceAsset =
refAsset.length > 8 ? refAsset.slice(0, 8) + '...' : refAsset
const [chartWidth, setChartWidth] = useState(w)
const [chartHeight, setChartHeight] = useState(h)
const [isLegendResponsive, setLegendResponsive] = useState(true)
Expand Down Expand Up @@ -173,11 +174,12 @@ export default function DIVATradeChart(props) {
.ticks(3)
)
.call((g) => g.select('.domain').remove())
.call((g) =>
g
.selectAll('.tick:not(:first-of-type) line')
.attr('stroke-opacity', 0.5)
.style('stroke', '#3393E0')
.call(
(g) =>
g
.selectAll('.tick:not(:first-of-type) line')
.attr('stroke-opacity', 0.5)
// .style('stroke', '#3393E0')
)
.call((g) => g.selectAll('.tick text').attr('x', 4).attr('dy', -4))

Expand All @@ -197,7 +199,7 @@ export default function DIVATradeChart(props) {
.attr('d', valueline)
.style('fill', 'none')
.style('stroke', function () {
return mouseHover ? 'grey' : blueColorCode
return blueColorCode
})
.style('stroke-width', '4px')
.attr('class', function () {
Expand Down Expand Up @@ -447,7 +449,7 @@ export default function DIVATradeChart(props) {
.attr('x', 18)
.attr('y', 40)
.attr('font-size', '14')
.text(reffeenceAsset + '...' + ' at Expiry:')
.text(referenceAsset + ' at Expiry:')

tooltipPerLine
.append('text')
Expand Down
12 changes: 8 additions & 4 deletions packages/diva-app/src/component/Markets/Markets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { ShowChartOutlined } from '@mui/icons-material'
import { useHistory, useParams } from 'react-router-dom'
import FilterListIcon from '@mui/icons-material/FilterList'

import { DIVA_GOVERNANCE_ADDRESS } from '../../constants'
import { DEFAULT_MARKETS_CREATED_BY } from '../../constants'
import PoolsTable, { PayoffCell } from '../PoolsTable'
import { config } from '../../constants'
import { getDateTime } from '../../Util/Dates'
Expand Down Expand Up @@ -68,6 +68,7 @@ const columns: GridColDef[] = [
<GrayText>{getShortenedAddress(cell.value)}</GrayText>
</Tooltip>
),
hide: true,
},
{
field: 'Icon',
Expand Down Expand Up @@ -114,6 +115,7 @@ const columns: GridColDef[] = [
{cell.value}
</Typography>
),
hide: true,
},
{
field: 'Buy',
Expand All @@ -125,6 +127,7 @@ const columns: GridColDef[] = [
{cell.value}
</Typography>
),
hide: true,
},
{
field: 'MaxYield',
Expand All @@ -136,6 +139,7 @@ const columns: GridColDef[] = [
{cell.value.buy}
</Typography>
),
hide: true,
},
{
field: 'Status',
Expand Down Expand Up @@ -704,9 +708,9 @@ export default function Markets() {
onInputChange={handleCreatorInput}
MenuItemLabel="Diva Governance"
onMenuItemClick={() => {
setCreatedBy(DIVA_GOVERNANCE_ADDRESS)
setCreatedBy(DEFAULT_MARKETS_CREATED_BY)
setCreatorButtonLabel(
getShortenedAddress(DIVA_GOVERNANCE_ADDRESS)
getShortenedAddress(DEFAULT_MARKETS_CREATED_BY)
)
}}
/>
Expand Down Expand Up @@ -831,7 +835,7 @@ export default function Markets() {
}}
onClearFilter={() => {
setSearch('')
setCreatedBy(DIVA_GOVERNANCE_ADDRESS)
setCreatedBy(DEFAULT_MARKETS_CREATED_BY)
setExpiredPoolClicked(false)
setSearchInput('')
setCheckedState(new Array(4).fill(false))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { useMemo } from 'react'
import ArrowDropUpIcon from '@mui/icons-material/ArrowDropUp'

import { getTopNObjectByProperty } from '../../Util/dashboard'
import { DIVA_GOVERNANCE_ADDRESS } from '../../constants'
import { DEFAULT_MARKETS_CREATED_BY } from '../../constants'

const FilterAccordion = ({ title, children }) => {
const theme = useTheme()
Expand Down Expand Up @@ -185,13 +185,13 @@ export const MobileFilterOptions = ({
>
<Box>Diva Governance</Box>
<Checkbox
checked={createdBy === DIVA_GOVERNANCE_ADDRESS}
checked={createdBy === DEFAULT_MARKETS_CREATED_BY}
id={`checkbox-diva-governance`}
onChange={() => {
if (createdBy === DIVA_GOVERNANCE_ADDRESS) {
if (createdBy === DEFAULT_MARKETS_CREATED_BY) {
setCreatedBy('')
} else {
setCreatedBy(DIVA_GOVERNANCE_ADDRESS)
setCreatedBy(DEFAULT_MARKETS_CREATED_BY)
}
}}
/>
Expand Down
50 changes: 20 additions & 30 deletions packages/diva-app/src/component/Trade/OrderBook.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ export default function OrderBook(props: {
}) {
const option = props.option
const optionTokenAddress = props.tokenAddress
let responseBuy = useAppSelector((state) => state.tradeOption.responseBuy)
let responseSell = useAppSelector((state) => state.tradeOption.responseSell)
const [orderBook, setOrderBook] = useState([] as any)
const chainId = useAppSelector(selectChainId)
const { provider } = useConnectionContext()
Expand All @@ -41,30 +39,22 @@ export default function OrderBook(props: {
)
const componentDidMount = async () => {
const orders = []
if (responseSell.length === 0) {
const rSell = await get0xOpenOrders(
optionTokenAddress,
option.collateralToken.id,
chainId,
provider,
props.exchangeProxy
)
if (rSell.length > 0) {
responseSell = rSell
}
}
if (responseBuy.length === 0) {
const rBuy = await get0xOpenOrders(
option.collateralToken.id,
optionTokenAddress,
chainId,
provider,
props.exchangeProxy
)
if (rBuy.length > 0) {
responseBuy = rBuy
}
}

const rSell = await get0xOpenOrders(
optionTokenAddress,
option.collateralToken.id,
chainId,
provider,
props.exchangeProxy
)

const rBuy = await get0xOpenOrders(
option.collateralToken.id,
optionTokenAddress,
chainId,
provider,
props.exchangeProxy
)

// Keep this for debugging
// const buyOrdersByMakerAddress = responseBuy.filter((v) =>
Expand All @@ -79,20 +69,20 @@ export default function OrderBook(props: {
// console.log('sellOrdersByMakerAddress', sellOrdersByMakerAddress)

const orderBookBuy = mapOrderData(
responseBuy,
rBuy,
option.collateralToken.decimals,
ORDER_TYPE.BUY
)
orders.push(orderBookBuy)

const orderBookSell = mapOrderData(
responseSell,
rSell,
option.collateralToken.decimals,
ORDER_TYPE.SELL
)
orders.push(orderBookSell)

//put both buy & sell orders in one array to format table rows
// Put both buy & sell orders in one array to format table rows
const completeOrderBook = createTable(
orders[ORDER_TYPE.BUY],
orders[ORDER_TYPE.SELL]
Expand All @@ -103,7 +93,7 @@ export default function OrderBook(props: {
useEffect(() => {
componentDidMount()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [responseBuy, responseSell, provider])
}, [provider, optionTokenAddress])

useEffect(() => {
if (websocketClient !== undefined) {
Expand Down
4 changes: 3 additions & 1 deletion packages/diva-app/src/component/Trade/Orders/BuyOrder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const BuyOrder = (props: {
const web3 = new Web3(Web3Provider as any)
const { getWeb3JsProvider, provider } = useConnectionContext()
const [collateralBalance, setCollateralBalance] = useState(ZERO)
const [checked, setChecked] = useState(true)
const [checked, setChecked] = useState(false)
const [numberOfOptions, setNumberOfOptions] = useState('') // User input field
const [pricePerOption, setPricePerOption] = useState(ZERO) // User input field
const [feeAmount, setFeeAmount] = React.useState(ZERO) // User input field
Expand Down Expand Up @@ -163,6 +163,8 @@ const BuyOrder = (props: {
setChecked(event.target.checked)
if (event.target.checked) {
setFeeAmount(ZERO)
} else {
setPricePerOption(ZERO)
}
}
const handleNumberOfOptions = (value: string) => {
Expand Down
Loading

0 comments on commit 32cfacd

Please sign in to comment.