1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-06-30 22:01:44 +02:00
market/src/components/organisms/AssetActions/Trade/FormTrade.tsx
Norbi 4123dae431
fix ocean symbol on Polygon (#487)
* updated Price component

* fixed on Pool Shares

* fixed on Pool

* fixed on Trade

* removed hardcoded data

* temp fixes

* fixes for subgraph2

* fixed token symbol in price for pools

* remove console.log

* remove comment default symbol

* remove temp values

* add tokens to query

* add token symbol

* remove console.log

Co-authored-by: Norbi <katunanorbert@gmai.com>
Co-authored-by: mihaisc <mihai@oceanprotocol.com>
2021-09-01 07:05:59 -07:00

172 lines
5.0 KiB
TypeScript

import React, { ReactElement, useState } from 'react'
import { DDO, Logger } from '@oceanprotocol/lib'
import * as Yup from 'yup'
import { Formik } from 'formik'
import Actions from '../Pool/Actions'
import { graphql, useStaticQuery } from 'gatsby'
import { useUserPreferences } from '../../../../providers/UserPreferences'
import { toast } from 'react-toastify'
import Swap from './Swap'
import { PoolBalance } from '../../../../@types/TokenBalance'
import Alert from '../../../atoms/Alert'
import styles from './FormTrade.module.css'
import { FormTradeData, initialValues } from '../../../../models/FormTrade'
import Decimal from 'decimal.js'
import { useOcean } from '../../../../providers/Ocean'
import { useWeb3 } from '../../../../providers/Web3'
import { useAsset } from '../../../../providers/Asset'
import { BestPrice } from '../../../../models/BestPrice'
const contentQuery = graphql`
query TradeQuery {
content: allFile(filter: { relativePath: { eq: "price.json" } }) {
edges {
node {
childContentJson {
trade {
action
warning
}
}
}
}
}
}
`
export default function FormTrade({
ddo,
balance,
maxDt,
maxOcean,
price
}: {
ddo: DDO
balance: PoolBalance
maxDt: string
maxOcean: string
price: BestPrice
}): ReactElement {
const data = useStaticQuery(contentQuery)
const content = data.content.edges[0].node.childContentJson.trade
const { accountId } = useWeb3()
const { ocean } = useOcean()
const { isAssetNetwork } = useAsset()
const { debug } = useUserPreferences()
const [txId, setTxId] = useState<string>()
const [maximumOcean, setMaximumOcean] = useState(maxOcean)
const [maximumDt, setMaximumDt] = useState(maxDt)
const [isWarningAccepted, setIsWarningAccepted] = useState(false)
const validationSchema: Yup.SchemaOf<FormTradeData> = Yup.object()
.shape({
ocean: Yup.number()
.max(
Number(maximumOcean),
(param) => `Must be less or equal to ${param.max}`
)
.min(0.001, (param) => `Must be more or equal to ${param.min}`)
.required('Required')
.nullable(),
datatoken: Yup.number()
.max(
Number(maximumDt),
(param) => `Must be less or equal to ${param.max}`
)
.min(0.00001, (param) => `Must be more or equal to ${param.min}`)
.required('Required')
.nullable(),
type: Yup.string(),
slippage: Yup.string()
})
.defined()
async function handleTrade(values: FormTradeData) {
try {
const impact = new Decimal(
new Decimal(100).sub(new Decimal(values.slippage))
).div(100)
const precision = 15
const tx =
values.type === 'buy'
? await ocean.pool.buyDTWithExactOcean(
accountId,
price.address,
new Decimal(values.datatoken)
.mul(impact)
.toFixed(precision)
.toString(),
new Decimal(values.ocean).toFixed(precision).toString()
)
: await ocean.pool.sellDT(
accountId,
price.address,
new Decimal(values.datatoken).toFixed(precision).toString(),
new Decimal(values.ocean)
.mul(impact)
.toFixed(precision)
.toString()
)
setTxId(tx?.transactionHash)
} catch (error) {
Logger.error(error.message)
toast.error(error.message)
}
}
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={async (values, { setSubmitting, resetForm }) => {
await handleTrade(values)
resetForm()
setSubmitting(false)
}}
>
{({ isSubmitting, submitForm, values }) => (
<>
{isWarningAccepted ? (
<Swap
ddo={ddo}
balance={balance}
maxDt={maxDt}
maxOcean={maxOcean}
price={price}
setMaximumOcean={setMaximumOcean}
setMaximumDt={setMaximumDt}
/>
) : (
<div className={styles.alertWrap}>
<Alert
text={content.warning}
state="info"
action={{
name: 'I understand',
style: 'text',
handleAction: () => setIsWarningAccepted(true)
}}
/>
</div>
)}
<Actions
isDisabled={!isWarningAccepted || !isAssetNetwork}
isLoading={isSubmitting}
loaderMessage="Swapping tokens..."
successMessage="Successfully swapped tokens."
actionName={content.action}
action={submitForm}
txId={txId}
/>
{debug && (
<pre>
<code>{JSON.stringify(values, null, 2)}</code>
</pre>
)}
</>
)}
</Formik>
)
}