Skip to content

Commit

Permalink
[SWA-46] Fix quote price for buy and sell token
Browse files Browse the repository at this point in the history
  • Loading branch information
Wixzi committed Jun 22, 2023
1 parent ce24f22 commit 8767a3a
Show file tree
Hide file tree
Showing 9 changed files with 257 additions and 112 deletions.
53 changes: 42 additions & 11 deletions src/pages/Swap/LimitOrder/LimitOrderForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Currency, Token, TokenAmount } from '@swapr/sdk'

import { formatUnits, parseUnits } from 'ethers/lib/utils'
import { parseUnits } from 'ethers/lib/utils'
import { useContext, useEffect, useState } from 'react'
import { Flex } from 'rebass'

Expand All @@ -16,7 +16,7 @@ import SwapTokens from './Components/SwapTokens'

export default function LimitOrderForm() {
const protocol = useContext(LimitOrderContext)

console.log('protocol', protocol)
const [fetchMarketPrice, setFetchMarketPrice] = useState<boolean>(true)

// eslint-disable-next-line @typescript-eslint/no-unused-vars
Expand All @@ -27,6 +27,7 @@ export default function LimitOrderForm() {

const [sellToken, setSellToken] = useState<Token>(protocol.sellToken)
const [buyToken, setBuyToken] = useState<Token>(protocol.buyToken)
const [loading, setLoading] = useState<boolean>(protocol.loading)

const [kind, setKind] = useState<Kind>(protocol?.kind || Kind.Sell)

Expand All @@ -35,9 +36,14 @@ export default function LimitOrderForm() {
setBuyToken(protocol.buyToken)
setSellAmount(protocol.sellAmount)
setBuyAmount(protocol.buyAmount)
protocol.getMarketPrice()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [protocol.activeChainId])

useEffect(() => {
setLoading(protocol.loading)
}, [protocol.loading])

useEffect(() => {
protocol?.onKindChange(kind)
}, [protocol, kind])
Expand All @@ -55,42 +61,66 @@ export default function LimitOrderForm() {
}, [protocol, buyToken])

useEffect(() => {
async function getMarketPrices() {
if (!protocol || !sellAmount) return
if (kind === Kind.Sell) {
setLoading(true)
await protocol.getMarketPrice()
setBuyAmount(protocol.buyAmount)
}
}

if (sellAmount) {
protocol?.onSellAmountChange(sellAmount)
getMarketPrices()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [protocol, sellAmount])

useEffect(() => {
async function getMarketPrices() {
if (!protocol || !buyAmount) return
if (kind === Kind.Buy) {
setLoading(true)
await protocol.getMarketPrice()
setSellAmount(protocol.sellAmount)
}
}

if (buyAmount) {
protocol?.onBuyAmountChange(buyAmount)
getMarketPrices()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [protocol, buyAmount])

const [marketPrices, setMarketPrices] = useState<MarketPrices>({ buy: 0, sell: 0 })

// TODO: REMOVE THIS USEEFFECT
useEffect(() => {
async function getMarketPrices() {
async function _getMarketPrices() {
if (!protocol) return
const { kind } = protocol
setLoading(true)
const amount = await protocol.getMarketPrice()

if (kind === Kind.Sell) {
// TODO: MOVE THIS LOGIC
setMarketPrices(marketPrice => ({ ...marketPrice, buy: amount }))
} else {
setMarketPrices(marketPrice => ({ ...marketPrice, sell: amount }))
}
}
getMarketPrices()
// getMarketPrices()
}, [protocol, protocol?.kind])

return (
<AutoColumn gap="12px">
<AutoColumn gap="3px">
<CurrencyInputPanel
id="limit-order-sell-currency"
value={formatUnits(sellAmount.raw.toString(), sellToken.decimals) || '0'}
onUserInput={function (_value: string): void {
// throw new Error('Function not implemented.')
value={protocol.getFormattedAmount(sellAmount)}
onUserInput={function (_value: string) {
setKind(Kind.Sell)
const amountWei = parseUnits(_value, sellToken.decimals).toString()
setSellAmount(new TokenAmount(sellToken, amountWei))
Expand All @@ -100,24 +130,25 @@ export default function LimitOrderForm() {
onCurrencySelect={(currency: Currency, _isMaxAmount?: boolean) => {
setSellToken(protocol.getTokenFromCurrency(currency))
}}
currencyOmitList={[buyToken.address]}
/>
<SwapTokens
swapTokens={() => {
setSellToken(buyToken)
setBuyToken(sellToken)
}}
loading={false}
loading={loading}
/>
<CurrencyInputPanel
id="limit-order-buy-currency"
value={formatUnits(buyAmount.raw.toString(), sellToken.decimals) || '0'}
value={protocol.getFormattedAmount(buyAmount)}
currency={buyToken}
onUserInput={function (_value: string): void {
onUserInput={function (_value: string) {
setKind(Kind.Buy)
const amountWei = parseUnits(_value, buyToken.decimals).toString()
setBuyAmount(new TokenAmount(buyToken, amountWei))
// throw new Error('Function not implemented.')
}}
currencyOmitList={[sellToken.address]}
showNativeCurrency={false}
onCurrencySelect={(currency: Currency, _isMaxAmount?: boolean) => {
setBuyToken(protocol.getTokenFromCurrency(currency))
Expand Down
17 changes: 7 additions & 10 deletions src/pages/Swap/LimitOrder/api/cow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import contractNetworks from '@cowprotocol/contracts/networks.json'
import { OrderKind as CoWOrderKind } from '@cowprotocol/cow-sdk'
import type { UnsignedOrder } from '@cowprotocol/cow-sdk/dist/utils/sign'

import { LimitOrderKind, SerializableLimitOrder, SerializableSignedLimitOrder } from '../../LimitOrderBox/interfaces'
import { Kind, LimitOrder } from '../../../../services/LimitOrders'
import { SignedLimitOrder } from '../../../../services/LimitOrders/CoW/CoW.types'
import cowAppData from '../generated/cow-app-data/app-data.json'
// import { LimitOrderKind, SerializableLimitOrder, SerializableSignedLimitOrder } from '../interfaces'

Expand All @@ -22,7 +23,7 @@ export function getAppDataIPFSHash(chainId: number): string {
}

export interface SignLimitOrderParams {
order: SerializableLimitOrder
order: LimitOrder
signer: Signer
chainId: number
}
Expand All @@ -44,7 +45,7 @@ export async function getQuote({ order, signer, chainId }: GetLimitOrderQuotePar

let cowQuote: Awaited<ReturnType<typeof cowSdk.cowApi.getQuote>>

if (kind === LimitOrderKind.BUY) {
if (kind === Kind.Buy) {
cowQuote = await cowSdk.cowApi.getQuote({
appData: getAppDataIPFSHash(chainId),
buyAmountAfterFee: buyAmount,
Expand Down Expand Up @@ -76,11 +77,7 @@ export async function getQuote({ order, signer, chainId }: GetLimitOrderQuotePar
/**
* Signs a limit order to produce a EIP712-compliant signature
*/
export async function signLimitOrder({
order,
signer,
chainId,
}: SignLimitOrderParams): Promise<SerializableSignedLimitOrder> {
export async function signLimitOrder({ order, signer, chainId }: SignLimitOrderParams): Promise<SignedLimitOrder> {
const cowSdk = CoWTrade.getCowSdk(chainId, {
signer,
appDataHash: getAppDataIPFSHash(chainId),
Expand All @@ -97,7 +94,7 @@ export async function signLimitOrder({
feeAmount, // from CoW APIs
receiver: receiverAddress, // the account that will receive the order
validTo: expiresAt,
kind: kind === LimitOrderKind.BUY ? CoWOrderKind.BUY : CoWOrderKind.SELL,
kind: kind === Kind.Buy ? CoWOrderKind.BUY : CoWOrderKind.SELL,
partiallyFillable: false,
})

Expand Down Expand Up @@ -127,7 +124,7 @@ export async function createCoWLimitOrder({ order, signer, chainId }: GetLimitOr
feeAmount: '0', // from CoW APIs
receiver: order.receiverAddress, // the account that will receive the order
validTo: order.expiresAt,
kind: order.kind === LimitOrderKind.BUY ? CoWOrderKind.BUY : CoWOrderKind.SELL,
kind: order.kind === Kind.Buy ? CoWOrderKind.BUY : CoWOrderKind.SELL,
partiallyFillable: false,
}

Expand Down
17 changes: 0 additions & 17 deletions src/services/LimitOrders/1Inch/OneInch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,42 +20,25 @@ export class OneInch extends LimitOrderBase {

onSellTokenChange(sellToken: Currency) {
this.sellToken = this.getTokenFromCurrency(sellToken)
this.limitOrder = {
...this.limitOrder,
sellToken: this.sellToken,
}
}

onBuyTokenChange(buyToken: Currency) {
this.buyToken = this.getTokenFromCurrency(buyToken)
this.limitOrder = {
...this.limitOrder,
buyToken: this.buyToken,
}
}

onSellAmountChange(sellAmount: TokenAmount) {
this.sellAmount = sellAmount
this.limitOrder = {
...this.limitOrder,
sellAmount: this.sellAmount,
}
}

onBuyAmountChange(buyAmount: TokenAmount) {
this.buyAmount = buyAmount
this.limitOrder = {
...this.limitOrder,
buyAmount: this.buyAmount,
}
}

onLimitOrderChange(limitOrder: any): void {
this.limitOrder = limitOrder
}

onExpireChange(expiresAt: number): void {
// TODO: Convert expiresAt based on expiresAtUnit
this.expiresAt = expiresAt
}

Expand Down
12 changes: 12 additions & 0 deletions src/services/LimitOrders/CoW/CoW.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ChainId, DAI, USDT, WETH, WXDAI } from '@swapr/sdk'

export const DefaultTokens = {
[ChainId.MAINNET]: {
sellToken: WETH[ChainId.MAINNET],
buyToken: DAI[ChainId.MAINNET],
},
[ChainId.GNOSIS]: {
sellToken: WXDAI[ChainId.GNOSIS],
buy: USDT[ChainId.GNOSIS],
},
}
Loading

0 comments on commit 8767a3a

Please sign in to comment.