From 93b310220b6df4692b3d4e36c8a41fdd30ebcedd Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sun, 25 Sep 2022 16:09:33 -0300 Subject: [PATCH 01/83] feat: robotlist --- src/components/Button/index.tsx | 2 +- src/components/PanelLimitPrice/index.tsx | 58 ++ src/features/onsen/FarmMenu.tsx | 26 +- src/features/robots/RobotList.tsx | 74 ++ src/features/robots/RobotListItemDetails.tsx | 145 ++++ src/features/robots/RobotListItems.tsx | 99 +++ src/pages/robots/create-robot/index.tsx | 358 ++++++++ src/pages/robots/robots-list/index.tsx | 859 +++++++++++++++++++ 8 files changed, 1619 insertions(+), 2 deletions(-) create mode 100644 src/components/PanelLimitPrice/index.tsx create mode 100644 src/features/robots/RobotList.tsx create mode 100644 src/features/robots/RobotListItemDetails.tsx create mode 100644 src/features/robots/RobotListItems.tsx create mode 100644 src/pages/robots/create-robot/index.tsx create mode 100644 src/pages/robots/robots-list/index.tsx diff --git a/src/components/Button/index.tsx b/src/components/Button/index.tsx index 639c7d1ba3..17ed42b1f1 100644 --- a/src/components/Button/index.tsx +++ b/src/components/Button/index.tsx @@ -48,7 +48,7 @@ const VARIANT = { link: LINK, } -export type ButtonColor = 'blue' | 'pink' | 'gradient' | 'gray' | 'default' | 'red' | 'green' +export type ButtonColor = 'blue' | 'pink' | 'gradient' | 'gray' | 'default' | 'red' | 'green' | 'border' export type ButtonSize = 'xs' | 'sm' | 'lg' | 'default' | 'none' diff --git a/src/components/PanelLimitPrice/index.tsx b/src/components/PanelLimitPrice/index.tsx new file mode 100644 index 0000000000..cda47e1002 --- /dev/null +++ b/src/components/PanelLimitPrice/index.tsx @@ -0,0 +1,58 @@ +import React, { useState } from 'react' +import { classNames, escapeRegExp } from '../../functions' +import Input from '../Input' + + +const PanelLimitPrice = ({label, currencyA, currencyB}) => { + const [value, setValue] = useState('') + + const handleValue = (e) => { + setValue(e.target.value) + } + + const inputRegex = RegExp(`^\\d*(?:\\\\[.])?\\d*$`) // match escaped "." characters via in a non-capturing group + + const defaultClassName = 'w-0 p-0 text-2xl bg-transparent' + + const enforcer = (nextUserInput: string) => { + if (nextUserInput === '' || inputRegex.test(escapeRegExp(nextUserInput))) { + setValue(nextUserInput) + } + } + + return ( +
+
+ {label} +
+ { + // replace commas with periods, because uniswap exclusively uses period as the decimal separator + enforcer(event.target.value.replace(/,/g, '.')) + }} + // universal input options + inputMode="decimal" + title="Token Amount" + autoComplete="off" + autoCorrect="off" + // text-specific options + type="text" + pattern="^[0-9]*[.,]?[0-9]*$" + placeholder={'0.0'} + min={0.0} + minLength={1} + maxLength={14} + spellCheck="false" + className={'relative flex text-center justify-center font-bold outline-none border-none overflow-hidden overflow-ellipsis placeholder-low-emphesis focus:placeholder-primary text-xl bg-transparent'} + // readOnly={true} + /> +
+ {/* {label} */} + {currencyA} per {currencyB} +
+
+ ) +} + +export default PanelLimitPrice \ No newline at end of file diff --git a/src/features/onsen/FarmMenu.tsx b/src/features/onsen/FarmMenu.tsx index e78406caad..9eabfe2d81 100644 --- a/src/features/onsen/FarmMenu.tsx +++ b/src/features/onsen/FarmMenu.tsx @@ -6,7 +6,31 @@ import { useLingui } from '@lingui/react' import { useActiveWeb3React } from '../../hooks' import { useWalletModalToggle } from '../../state/application/hooks' -const Menu = ({ positionsLength }) => { +const defaultOptions = [ + { + href: `/farm?filter=portfolio`, + label: 'Your Farms', + exact: true + }, + { + divider: true + }, + { + href: "/farm?filter=all", + label: 'All Farms' + }, + { + href: `/farm?filter=2x`, + label: '2x Reward Farms', + exact: true + }, + { + href: "/farm?filter=past", + label: 'Past Farms' + } +] + +const Menu = ({ positionsLength, options = defaultOptions}) => { const { account, chainId } = useActiveWeb3React() const { i18n } = useLingui() const toggleWalletModal = useWalletModalToggle() diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx new file mode 100644 index 0000000000..3df0949a9d --- /dev/null +++ b/src/features/robots/RobotList.tsx @@ -0,0 +1,74 @@ +import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/outline' +import InfiniteScroll from 'react-infinite-scroll-component' +import Dots from '../../components/Dots' +import React from 'react' +import { t } from '@lingui/macro' +import { useLingui } from '@lingui/react' +import useSortableData from '../../hooks/useSortableData' +import { useInfiniteScroll } from '../onsen/hooks' +import RobotListItems from './RobotListItems' + +const RobotList = ({ robots, term }) => { + const { items, requestSort, sortConfig } = useSortableData(robots) + const { i18n } = useLingui() + const [numDisplayed, setNumDisplayed] = useInfiniteScroll(items) + + return items ? ( + <> +
+
requestSort('symbol')} + > +
{i18n._(t`Pair`)}
+ {sortConfig && + sortConfig.key === 'symbol' && + ((sortConfig.direction === 'ascending' && ) || + (sortConfig.direction === 'descending' && ))} +
+
requestSort('tvl')} + > + {i18n._(t`Min Price to Buy`)} + {sortConfig && + sortConfig.key === 'tvl' && + ((sortConfig.direction === 'ascending' && ) || + (sortConfig.direction === 'descending' && ))} +
+
requestSort('roiPerYear')} + > + {i18n._(t`Max Price to Sell`)} + {sortConfig && + sortConfig.key === 'roiPerYear' && + ((sortConfig.direction === 'ascending' && ) || + (sortConfig.direction === 'descending' && ))} +
+
+ {i18n._(t`Balance`)} +
+
+ setNumDisplayed(numDisplayed + 5)} + hasMore={true} + loader={null} + > +
+ {items.slice(0, numDisplayed).map((robot, index) => ( + + ))} +
+
+ + ) : ( +
{term ? No Results. : Loading}
+ ) +} + +export default RobotList diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx new file mode 100644 index 0000000000..005fbb3fb2 --- /dev/null +++ b/src/features/robots/RobotListItemDetails.tsx @@ -0,0 +1,145 @@ +import { ApprovalState, useApproveCallback } from '../../hooks/useApproveCallback' +import { ChainId, CurrencyAmount, JSBI, MASTERCHEF_ADDRESS, MASTERCHEF_V2_ADDRESS, Token, ZERO } from '@tangoswapcash/sdk' +import { Disclosure, Transition } from '@headlessui/react' +import React, { useState } from 'react' + +import Button, { ButtonError } from '../../components/Button' +import Dots from '../../components/Dots' +import Input from '../../components/Input' +import { formatCurrencyAmount, formatNumber, formatPercent } from '../../functions' +import { getAddress } from '@ethersproject/address' +import { t } from '@lingui/macro' +import { tryParseAmount } from '../../functions/parse' +import useActiveWeb3React from '../../hooks/useActiveWeb3React' +import { useLingui } from '@lingui/react' +import { useTokenBalance } from '../../state/wallet/hooks' +import { useTransactionAdder } from '../../state/transactions/hooks' +import { BigNumber } from '@ethersproject/bignumber' +import { isMobile } from 'react-device-detect' +import { useRouter } from 'next/router' +import { Chef, PairType } from '../onsen/enum' +import { usePendingSushi, useUserInfo } from '../onsen/hooks' +import useMasterChef from '../onsen/useMasterChef' +import usePendingReward from '../onsen/usePendingReward' + +const RobotListItemDetails = ({ robot }) => { + const { i18n } = useLingui() + + const router = useRouter() + + const { account, chainId } = useActiveWeb3React() + const [pendingTx, setPendingTx] = useState(false) + const [maxValue, setMaxValue] = useState(robot.maxValue ? robot.maxValue : 0) + const [minValue, setMinValue] = useState(robot.minValue ? robot.minValue : 0) + + const addTransaction = useTransactionAdder() + + const liquidityToken = new Token( + chainId, + getAddress(robot.pair.id), + robot.pair.type === PairType.KASHI ? Number(robot.pair.asset.decimals) : 18, + robot.pair.symbol, + robot.pair.name + ) + + // User liquidity token balance + const balance = useTokenBalance(account, liquidityToken) + + // TODO: Replace these + const amount = useUserInfo(robot, liquidityToken) + + const handleSellRobot = () => { + console.log('Vendido') + } + + const handleBuyRobot = () => { + console.log('Borrado') + } + + const handleDeleteRobot = () => { + console.log('Borrado') + } + + const { deposit, withdraw, harvest } = useMasterChef(robot.chef) + + const poolFraction = (Number.parseFloat(amount?.toFixed()) / robot.chefBalance) || 0 + const token0Reserve = robot.pool.reserves ? (robot.pool.reserves.reserve0 as BigNumber).toString() : 0 + const token0Amount = CurrencyAmount.fromRawAmount(robot.pair.token0, JSBI.BigInt(token0Reserve)).multiply(Math.round(poolFraction * 1e8)).divide(1e8) + const token1Reserve = robot.pool.reserves ? (robot.pool.reserves.reserve1 as BigNumber).toString() : 0 + const token1Amount = CurrencyAmount.fromRawAmount(robot.pair.token1, JSBI.BigInt(token1Reserve)).multiply(Math.round(poolFraction * 1e8)).divide(1e8) + const token0Name = robot.pool.token0 === robot.pair.token0.id ? robot.pair.token0.symbol : robot.pair.token1.symbol + const token1Name = robot.pool.token1 === robot.pair.token1.id ? robot.pair.token1.symbol : robot.pair.token0.symbol + + return ( + + +
+
+
+ + +
+
+
+
+ + { + setMaxValue(value) + }} + disabled + /> +
+
+
+ { robot.pending !== 0 ? ( +
+
+ +
+
+ +
+
+ ) : ( +
+ +
+ ) + } +
+
+ ) +} + +export default RobotListItemDetails diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx new file mode 100644 index 0000000000..b5545dfdee --- /dev/null +++ b/src/features/robots/RobotListItems.tsx @@ -0,0 +1,99 @@ +import { classNames, formatNumber, formatPercent } from '../../functions' +import { DotsHorizontalIcon } from '@heroicons/react/outline' +import { ZERO } from '@tangoswapcash/sdk' +import { Disclosure } from '@headlessui/react' +import DoubleLogo from '../../components/DoubleLogo' +import Image from '../../components/Image' +import React from 'react' +import { useLingui } from '@lingui/react' +import { t } from '@lingui/macro' +import { useCurrency } from '../../hooks/Tokens' +import { isMobile } from 'react-device-detect' +import { usePendingSushi } from '../onsen/hooks' +import usePendingReward from '../onsen/usePendingReward' +import RobotListItemDetails from './RobotListItemDetails' +import { PairType } from '../onsen/enum' + +const RobotListItems = ({ robot, ...rest }) => { + const token0 = useCurrency(robot.pair.token0.id) + const token1 = useCurrency(robot.pair.token1.id) + + const pendingSushi = usePendingSushi(robot) + const rewardAmount = usePendingReward(robot) + + const { i18n } = useLingui() + + return ( + + {({ open }) => ( + <> + +
+
+ +
+
+

{robot?.pair?.token0?.symbol}

+

+ {robot?.pair?.token1?.symbol} +

+
+
+
+
+ $ {robot.allocPoint / 4} +
+
+
+ $ {robot.allocPoint} +
+
+ {pendingSushi && pendingSushi.greaterThan(ZERO) ? ( +
+
+ + {robot?.rewards?.map((reward, i) => ( +
+ {reward.token} +
+ ))} +
+ +
+ {robot?.rewards?.map((reward, i) => ( +
+ {i == 0 ? formatNumber(pendingSushi.toFixed(18)) : formatNumber(rewardAmount)} {reward.token} +
+ ))} +
+
+ ) : ( +
+ {i18n._(t`Stake LP to robot`)} + {/* */} +
+ )} +
+
+ {/* {open && } */} + + )} +
+ ) +} + +export default RobotListItems + +// robot.rewards.length > 1 ? `& ${formatNumber(reward)} ${robot.rewards[1].token}` : '' diff --git a/src/pages/robots/create-robot/index.tsx b/src/pages/robots/create-robot/index.tsx new file mode 100644 index 0000000000..18323613ee --- /dev/null +++ b/src/pages/robots/create-robot/index.tsx @@ -0,0 +1,358 @@ +import { ApprovalState, useApproveCallback } from '../../../hooks/useApproveCallback' +import { AutoRow, RowBetween } from '../../../components/Row' +import Button, { ButtonError } from '../../../components/Button' +import { Currency, CurrencyAmount, Percent, WNATIVE, currencyEquals } from '@tangoswapcash/sdk' +import { ONE_BIPS, ZERO_PERCENT } from '../../../constants' +import React, { useCallback, useState } from 'react' +import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' +import { calculateGasMargin, calculateSlippageAmount, getGasPrice } from '../../../functions/trade' +import { currencyId, maxAmountSpend } from '../../../functions/currency' +import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' +import { useExpertModeManager, useUserSlippageToleranceWithDefault } from '../../../state/user/hooks' + +import Alert from '../../../components/Alert' +import { AutoColumn } from '../../../components/Column' +import { BigNumber } from '@ethersproject/bignumber' +import { ConfirmAddModalBottom } from '../../../features/exchange-v1/liquidity/ConfirmAddModalBottom' +import Container from '../../../components/Container' +import CurrencyInputPanel from '../../../components/CurrencyInputPanel' +import CurrencyLogo from '../../../components/CurrencyLogo' +import Dots from '../../../components/Dots' +import DoubleCurrencyLogo from '../../../components/DoubleLogo' +import DoubleGlowShadow from '../../../components/DoubleGlowShadow' +import ExchangeHeader from '../../../features/trade/Header' +import { Field } from '../../../state/mint/actions' +import Head from 'next/head' +import LiquidityHeader from '../../../features/exchange-v1/liquidity/LiquidityHeader' +import LiquidityPrice from '../../../features/exchange-v1/liquidity/LiquidityPrice' +import { MinimalPositionCard } from '../../../components/PositionCard' +import NavLink from '../../../components/NavLink' +import { PairState } from '../../../hooks/useV2Pairs' +import { Plus } from 'react-feather' +import { TransactionResponse } from '@ethersproject/providers' +import Typography from '../../../components/Typography' +import UnsupportedCurrencyFooter from '../../../features/exchange-v1/swap/UnsupportedCurrencyFooter' +import Web3Connect from '../../../components/Web3Connect' +import { t } from '@lingui/macro' +import { useActiveWeb3React } from '../../../hooks/useActiveWeb3React' +import { useCurrency } from '../../../hooks/Tokens' +import { useIsSwapUnsupported } from '../../../hooks/useIsSwapUnsupported' +import { useLingui } from '@lingui/react' +import { useRouter } from 'next/router' +import { useRouterContract } from '../../../hooks' +import { useTransactionAdder } from '../../../state/transactions/hooks' +import useTransactionDeadline from '../../../hooks/useTransactionDeadline' +import { useWalletModalToggle } from '../../../state/application/hooks' +import PanelLimitPrice from '../../../components/PanelLimitPrice' + +const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) + +export default function CreateRobotPage() { + const { i18n } = useLingui() + const { account, chainId, library } = useActiveWeb3React() + const router = useRouter() + const tokens = router.query.tokens + const [currencyIdA, currencyIdB] = (tokens as string[]) || [undefined, undefined] + + const currencyA = useCurrency(currencyIdA) + const currencyB = useCurrency(currencyIdB) + + const [currenciesSelected, setCurrenciesSelected] = useState(null) + + const oneCurrencyIsWETH = Boolean( + chainId && + ((currencyA && currencyEquals(currencyA, WNATIVE[chainId])) || + (currencyB && currencyEquals(currencyB, WNATIVE[chainId]))) + ) + + const toggleWalletModal = useWalletModalToggle() // toggle wallet when disconnected + + const [isExpertMode] = useExpertModeManager() + + // mint state + const { independentField, typedValue, otherTypedValue } = useMintState() + const { + dependentField, + currencies, + pair, + pairState, + currencyBalances, + parsedAmounts, + price, + noLiquidity, + liquidityMinted, + poolTokenPercentage, + error, + } = useDerivedMintInfo(currencyA ?? undefined, currencyB ?? undefined) + + const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) + + const isValid = !error + + // modal and loading + const [showConfirm, setShowConfirm] = useState(false) + const [attemptingTxn, setAttemptingTxn] = useState(false) // clicked confirm + + // txn values + const deadline = useTransactionDeadline() // custom from users settings + + // const [allowedSlippage] = useUserSlippageTolerance(); // custom from users + + const allowedSlippage = useUserSlippageToleranceWithDefault(DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE) // custom from users + + const [txHash, setTxHash] = useState('') + + // get formatted amounts + const formattedAmounts = { + [independentField]: typedValue, + [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', + } + + // get the max amounts user can add + const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmountSpend(currencyBalances[field]), + } + }, + {} + ) + + const atMaxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0'), + } + }, + {} + ) + + const routerContract = useRouterContract() + + // check whether the user has approved the router on the tokens + const [approvalA, approveACallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_A], routerContract?.address) + const [approvalB, approveBCallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_B], routerContract?.address) + + const addTransaction = useTransactionAdder() + + async function onAdd() { + if (!chainId || !library || !account || !routerContract) return + + const { [Field.CURRENCY_A]: parsedAmountA, [Field.CURRENCY_B]: parsedAmountB } = parsedAmounts + + console.log({ parsedAmountA, parsedAmountB, currencyA, currencyB, deadline }) + + if (!parsedAmountA || !parsedAmountB || !currencyA || !currencyB || !deadline) { + return + } + + const amountsMin = { + [Field.CURRENCY_A]: calculateSlippageAmount(parsedAmountA, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], + [Field.CURRENCY_B]: calculateSlippageAmount(parsedAmountB, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], + } + + let estimate, + method: (...args: any) => Promise, + args: Array, + value: BigNumber | null + if (currencyA.isNative || currencyB.isNative) { + const tokenBIsETH = currencyB.isNative + estimate = routerContract.estimateGas.addLiquidityETH + method = routerContract.addLiquidityETH + args = [ + (tokenBIsETH ? currencyA : currencyB)?.wrapped?.address ?? '', // token + (tokenBIsETH ? parsedAmountA : parsedAmountB).quotient.toString(), // token desired + amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min + amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min + account, + deadline.toHexString(), + ] + value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).quotient.toString()) + } else { + estimate = routerContract.estimateGas.addLiquidity + method = routerContract.addLiquidity + args = [ + currencyA?.wrapped?.address ?? '', + currencyB?.wrapped?.address ?? '', + parsedAmountA.quotient.toString(), + parsedAmountB.quotient.toString(), + amountsMin[Field.CURRENCY_A].toString(), + amountsMin[Field.CURRENCY_B].toString(), + account, + deadline.toHexString(), + ] + value = null + } + + setAttemptingTxn(true) + try { + const estimatedGasLimit = await estimate(...args, { + ...(value ? { value } : {}), + gasPrice: getGasPrice(), + }) + + const response = await method(...args, { + ...(value ? { value } : {}), + gasLimit: calculateGasMargin(estimatedGasLimit), + gasPrice: getGasPrice(), + }) + + setAttemptingTxn(false) + + addTransaction(response, { + summary: i18n._( + t`Add ${parsedAmounts[Field.CURRENCY_A]?.toSignificant(3)} ${ + currencies[Field.CURRENCY_A]?.symbol + } and ${parsedAmounts[Field.CURRENCY_B]?.toSignificant(3)} ${currencies[Field.CURRENCY_B]?.symbol}` + ), + }) + + setTxHash(response.hash) + } catch (error) { + setAttemptingTxn(false) + // we only care if the error is something _other_ than the user rejected the tx + if (error?.code !== 4001) { + console.error(error) + } + } + } + + const handleCurrencyASelect = (currencyA: Currency) => { + setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) + } + const handleCurrencyBSelect = (currencyB: Currency) => { + console.log(currenciesSelected) + setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) + } + + const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B) + + // console.log( + // { addIsUnsupported, isValid, approvaonFieldBInputlA, approvalB }, + // approvalA === ApprovalState.APPROVED && approvalB === ApprovalState.APPROVED + // ) + return ( + <> + + Create Robots | Orders.Cash + + + + + + + +
+
+ {pair && pairState !== PairState.INVALID && ( + + )} +
+ { + onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') + }} + onCurrencySelect={handleCurrencyASelect} + showMaxButton={!atMaxAmounts[Field.CURRENCY_A]} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + id="add-liquidity-input-tokena" + showCommonBases + /> + + + + + + + + { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + showMaxButton={!atMaxAmounts[Field.CURRENCY_B]} + currency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + id="add-liquidity-input-tokenb" + showCommonBases + /> +
+ + {currencies[Field.CURRENCY_A] && currencies[Field.CURRENCY_B] && pairState !== PairState.INVALID && ( +
+ +
+ )} + + { + currenciesSelected && currenciesSelected?.currencyA && currenciesSelected?.currencyB && ( +
+ + +
+ ) + } + + {addIsUnsupported ? ( + + ) : !account ? ( + + ) : ( + + )} +
+ + {!addIsUnsupported ? ( + pair && !noLiquidity && pairState !== PairState.INVALID ? ( + + ) : null + ) : ( + + )} +
+
+
+ + ) +} diff --git a/src/pages/robots/robots-list/index.tsx b/src/pages/robots/robots-list/index.tsx new file mode 100644 index 0000000000..f8c1ff87d7 --- /dev/null +++ b/src/pages/robots/robots-list/index.tsx @@ -0,0 +1,859 @@ +import { Chef, PairType } from '../../../features/onsen/enum' +import { PlusIcon } from '@heroicons/react/outline' +import { useActiveWeb3React, useFuse } from '../../../hooks' +import { + useAverageBlockTime, + useEthPrice, + useFarmPairAddresses, + useFarms, + useMasterChefV1SushiPerBlock, + useMasterChefV1TotalAllocPoint, + useSushiPairs, + useSushiPrice, +} from '../../../services/graph' + +import { BigNumber } from '@ethersproject/bignumber' +import { + ChainId, + WNATIVE, + Token, + CurrencyAmount, + JSBI, + WBCH, + MASTERCHEF_ADDRESS, + MASTERCHEF_V2_ADDRESS, +} from '@tangoswapcash/sdk' +import { TANGO, FLEXUSD } from '../../../config/tokens' +import Container from '../../../components/Container' +import FarmList from '../../../features/onsen/FarmList' +import Head from 'next/head' +import Menu from '../../../features/onsen/FarmMenu' +import React, { useEffect } from 'react' +import Search from '../../../components/Search' +import { classNames } from '../../../functions' +import dynamic from 'next/dynamic' +import { getAddress } from '@ethersproject/address' +import useFarmRewards from '../../../hooks/useFarmRewards' +import usePool from '../../../hooks/usePool' +import { useTokenBalancesWithLoadingIndicator } from '../../../state/wallet/hooks' +import { usePositions, usePendingSushi } from '../../../features/onsen/hooks' +import { useRouter } from 'next/router' +import { updateUserFarmFilter } from '../../../state/user/actions' +import { getFarmFilter, useUpdateFarmFilter } from '../../../state/user/hooks' +import { t } from '@lingui/macro' +import { useLingui } from '@lingui/react' +import RobotList from '../../../features/robots/RobotList' +import Button from '../../../components/Button' +import NavLink from '../../../components/NavLink' + +function getTokensSorted(pool, pair) { + if (pool.token0 == pair.token0.address && pool.token1 == pair.token1.address) { + return [pair.token0, pair.token1, pool.reserves[0], pool.reserves[1]] + } + + if (pool.token0 == pair.token1.address && pool.token1 == pair.token0.address) { + return [pair.token0, pair.token1, pool.reserves[1], pool.reserves[0]] + } + + return [undefined, undefined, undefined, undefined] +} + +function getTokenPriceInBch(pool, pair, chainId, tangoPriceBCH, bchPriceUSD) { + let [token0, token1, reserve0, reserve1] = getTokensSorted(pool, pair) + + if (!token0) return 0 + + let factor = 0 + let tokenAmount0 = Number.parseFloat(CurrencyAmount.fromRawAmount(token0, JSBI.BigInt(reserve0.toString())).toFixed()) + let tokenAmount1 = Number.parseFloat(CurrencyAmount.fromRawAmount(token1, JSBI.BigInt(reserve1.toString())).toFixed()) + + if (token0.address === TANGO[chainId].address) { + factor = tangoPriceBCH + } else if (token1.address === TANGO[chainId].address) { + ;[tokenAmount1, tokenAmount0] = [tokenAmount0, tokenAmount1] + factor = tangoPriceBCH + } else if (token0.address === FLEXUSD.address) { + factor = bchPriceUSD + } else if (token1.address === FLEXUSD.address) { + ;[tokenAmount1, tokenAmount0] = [tokenAmount0, tokenAmount1] + factor = bchPriceUSD + } else if (token0.address === WBCH[chainId].address) { + factor = 1 + } else if (token1.address === WBCH[chainId].address) { + ;[tokenAmount1, tokenAmount0] = [tokenAmount0, tokenAmount1] + factor = 1 + } + const derivedETH = (tokenAmount0 / tokenAmount1) * factor + return derivedETH +} + +export default function Robot(): JSX.Element { + const { i18n } = useLingui() + const { chainId } = useActiveWeb3React() + const router = useRouter() + + const type = router.query.filter as string + + const savedFilter = getFarmFilter() + + const updateFarmFilter = useUpdateFarmFilter() + updateFarmFilter(type) + + const hardcodedPairs = { + [ChainId.SMARTBCH]: { + '0x7963269e8a854D3F9D98a6cDEa81efFb31B4D1f2': { + farmId: 0, + allocPoint: 9999999, + token0: TANGO[ChainId.SMARTBCH], + token1: new Token(ChainId.SMARTBCH, '0x98Ff640323C059d8C4CB846976973FEEB0E068aA', 18, 'XTANGO', 'TANGObar'), + }, + '0xf8534BB9603c501Bbe16deF7D08D941F0241855b': { + farmId: 1, + allocPoint: 205699999, + token0: TANGO[ChainId.SMARTBCH], + token1: FLEXUSD, + }, + '0x4b773a2ea30C6A77564E4FaE60204e7Bc0a81A90': { + farmId: 2, + allocPoint: 509999999, + token0: TANGO[ChainId.SMARTBCH], + token1: WBCH[ChainId.SMARTBCH], + }, + '0xA15F8102AB4723A4D1554363c0c8AFF471F16E21': { + farmId: 3, + allocPoint: 170250512, + token0: FLEXUSD, + token1: WBCH[ChainId.SMARTBCH], + }, + '0x1A2bdFF5bA942bF20f0db7218cdE28D19aC8dD20': { + farmId: 4, + allocPoint: 14999999, + token0: new Token(ChainId.SMARTBCH, '0x98Dd7eC28FB43b3C4c770AE532417015fa939Dd3', 18, 'FLEX', 'FLEX Coin'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x5b860757a77c62Dca833542e8E4650AEE777a08F': { + farmId: 5, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x5fA664f69c2A4A3ec94FaC3cBf7049BD9CA73129', 18, 'MIST', 'MistToken'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xd12C1De8740406438eb84Dde44cd0839F48211aa': { + farmId: 6, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x77CB87b57F54667978Eb1B199b28a0db8C8E1c0B', 18, 'EBEN', 'Green Ben'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xa790208A8C49e586a3F2145aD2c9096d6072E1F3': { + farmId: 7, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0xc8E09AEdB3c949a875e1FD571dC4b3E48FB221f0', 18, 'MILK', 'Milk'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xF463db65674426A58E9C3fE557FaaE338026ef39': { + farmId: 8, + allocPoint: 0, + token0: new Token( + ChainId.SMARTBCH, + '0x675E1d6FcE8C7cC091aED06A68D079489450338a', + 18, + 'ARG', + 'Bitcoin Cash Argentina' + ), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xCFa5B1C5FaBF867842Ac3C25E729Fc3671d27c50': { + farmId: 9, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xf9185C281fE4C8af452244A65cE7317345352942': { + farmId: 10, + allocPoint: 1250000, + token0: new Token(ChainId.SMARTBCH, '0xe11829a7d5d8806bb36e118461a1012588fafd89', 18, 'SPICE', 'SPICE'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xBe0e246a87a3e9a2D2Db2efD384E0174F13E62b1': { + farmId: 11, + allocPoint: 4999999, + token0: new Token(ChainId.SMARTBCH, '0x0b00366fBF7037E9d75E4A569ab27dAB84759302', 18, 'LAW', 'LAWTOKEN'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x1946978E39E6105fEb2107D9c01197a962746bf5': { + farmId: 12, + allocPoint: 499999, + token0: new Token(ChainId.SMARTBCH, '0xff3ed63bf8bc9303ea0a7e1215ba2f82d569799e', 18, 'ORB', 'ORB'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x23e1E177aE511342fFc27F59da57685b3a0413bc': { + farmId: 13, + allocPoint: 4999999, + token0: new Token(ChainId.SMARTBCH, '0x265bD28d79400D55a1665707Fa14A72978FA6043', 2, 'CATS', 'CashCats'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x5340619781a8963377aFD76A6999edB6437e3B72': { + farmId: 14, + allocPoint: 2499999, + token0: new Token(ChainId.SMARTBCH, '0x6732E55Ac3ECa734F54C26Bd8DF4eED52Fb79a6E', 2, 'JOY', 'Joystick.club'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x91dde68D0C08e8620d77B8e7F1836aD4ec3CB33c': { + farmId: 15, + allocPoint: 2499999, + token0: new Token(ChainId.SMARTBCH, '0x7642Df81b5BEAeEb331cc5A104bd13Ba68c34B91', 2, 'CLY', 'Celery'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xa24e2a9a41020bD1EaD472aF07bCc74cd7fB85A4': { + farmId: 16, + allocPoint: 499999, + token0: new Token(ChainId.SMARTBCH, '0xca0235058985fcc1839e9e37c10900a73c126708', 7, 'DAO', 'DAO'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x0152F077D2808506FbF6B991b48D1e8DDCBF7107': { + farmId: 17, + allocPoint: 499999, + token0: new Token(ChainId.SMARTBCH, '0x3d13DaFcCA3a188DB340c81414239Bc2be312Ec9', 18, 'AXIEBCH', 'AxieBCH'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x9E59AAc21DaB7C89d0BDA99335386868539Af9B8': { + farmId: 18, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x0D8b355f9CEDeB612f2df4B39CdD87059A244567', 2, 'CANDYMAN', 'CandyMAN'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xD4625760E0B5D9a0f46cB95dDa9b660fd6Db610A': { + farmId: 19, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x225FCa2A940cd5B18DFb168cD9B7f921C63d7B6E', 18, 'FIRE', 'Incinerate'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xC28f5F07B733862f021f2266B99F5214c68E95d0': { + farmId: 20, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x7ebeadb95724a006afaf2f1f051b13f4ebebf711', 2, 'KITTEN', 'CashKitten'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x1CC824B67e694fd5e0cC7D55120355B1AE4B9c50': { + farmId: 21, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x9192940099fDB2338B928DE2cad9Cd1525fEa881', 18, 'BPAD', 'BCHPad'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xfe323f2898810E6C3c2c5A9E7dF78A116fFAD4fa': { + farmId: 22, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0xffa2394b61d3de16538a2bbf3491297cc5a7c79a', 18, 'UATX', 'UatX Token'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x365Ec450d670455b336b833Ca363d21b4de3B9E3': { + farmId: 23, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x4F1480ba79F7477230ec3b2eCc868E8221925072', 18, 'KONRA', 'Konra'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x7FbcD4B5b7838F3C22151d492cB7E30B28dED77a': { + farmId: 24, + allocPoint: 999999, + token0: new Token(ChainId.SMARTBCH, '0x98Ff640323C059d8C4CB846976973FEEB0E068aA', 18, 'XTANGO', 'TANGObar'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x0152E5F007D85aae58Eb7191Bd484f12F9c13052': { + farmId: 25, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x49F9ECF126B6dDF51C731614755508A4674bA7eD', 18, 'RMZ', 'Xolos'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xC073d247f8FdB539Bc6653b6bfFEF8c61092738F': { + farmId: 26, + allocPoint: 999999, + token0: new Token(ChainId.SMARTBCH, '0x98Dd7eC28FB43b3C4c770AE532417015fa939Dd3', 18, 'FLEX', 'FLEX Coin'), + token1: TANGO[ChainId.SMARTBCH], + }, + '0xcdb6081DCb9fd2b3d48927790DF7757E8d137fF4': { + farmId: 27, + allocPoint: 4499999, + token0: new Token(ChainId.SMARTBCH, '0x98Ff640323C059d8C4CB846976973FEEB0E068aA', 18, 'XTANGO', 'TANGObar'), + token1: FLEXUSD, + }, + '0xfa2A542B0BF8F5e92Af0D1045ebF0abBB0A6C093': { + farmId: 28, + allocPoint: 26999999, + token0: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x018005da1a5C886Fb48eB18Eda0849a26B99DA80': { + farmId: 29, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x77d4b6e44a53bbda9a1d156b32bb53a2d099e53d', 18, '1BCH', '1BCH'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0x864c0090D955D947D809CF315E17665Bf9e3b6aB': { + farmId: 30, + allocPoint: 0, + token0: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), + token1: TANGO[ChainId.SMARTBCH], + }, + '0x4509Ff66a56cB1b80a6184DB268AD9dFBB79DD53': { + farmId: 32, + allocPoint: 2499999, + token0: new Token(ChainId.SMARTBCH, '0xF05bD3d7709980f60CD5206BddFFA8553176dd29', 18, 'SIDX', 'SmartIndex'), + token1: WBCH[ChainId.SMARTBCH], + }, + '0xE7845D6df693BFD1b0b50AB2d17ac06964559c6b': { + farmId: 33, + allocPoint: 4999750, + token0: new Token(ChainId.SMARTBCH, '0xe1e655be6f50344e6dd708c27bd8d66492d6ecaf', 18, 'LAWUSD', 'lawUSD'), + token1: TANGO[ChainId.SMARTBCH], + }, + }, + [ChainId.SMARTBCH_AMBER]: { + '0x07DE6fc05597E0E4c92C83637A8a0CA411f3a769': { + farmId: 0, + allocPoint: 1000, + token0: WBCH[ChainId.SMARTBCH_AMBER], + token1: new Token(ChainId.SMARTBCH_AMBER, '0xC6F80cF669Ab9e4BE07B78032b4821ed5612A9ce', 18, 'sc', 'testcoin2'), + }, + }, + } + + const hardcodedPairs2x = { + [ChainId.SMARTBCH]: { + '0xCFa5B1C5FaBF867842Ac3C25E729Fc3671d27c50': { + farmId: 0, + allocPoint: 1249938, + token0: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0xbA85D6bB454315A0fb65b205Fa48DBAff82A4019', + rewardToken: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), + rewardPerSecond: '1000000000000000000', + }, + '0xF463db65674426A58E9C3fE557FaaE338026ef39': { + farmId: 1, + allocPoint: 1249937, + token0: new Token( + ChainId.SMARTBCH, + '0x675E1d6FcE8C7cC091aED06A68D079489450338a', + 18, + 'ARG', + 'Bitcoin Cash Argentina' + ), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0x3f28b9BE239038568D67f076a0ff9AEdEa5668d8', + rewardToken: new Token( + ChainId.SMARTBCH, + '0x675E1d6FcE8C7cC091aED06A68D079489450338a', + 18, + 'ARG', + 'Bitcoin Cash Argentina' + ), + rewardPerSecond: '2342000000000000000000', + }, + '0x0152E5F007D85aae58Eb7191Bd484f12F9c13052': { + farmId: 2, + allocPoint: 499999, + token0: new Token(ChainId.SMARTBCH, '0x49F9ECF126B6dDF51C731614755508A4674bA7eD', 18, 'RMZ', 'Xolos'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0xefEf4dC16316Ae8c7AF00489b0e5FA52be68D1B6', + rewardToken: new Token(ChainId.SMARTBCH, '0x49F9ECF126B6dDF51C731614755508A4674bA7eD', 18, 'RMZ', 'Xolos'), + rewardPerSecond: '58330000000000', + }, + '0xD513165b3bbC1Ca812Db7CBB60340DDf74903A1c': { + farmId: 3, + allocPoint: 15624, + token0: new Token(ChainId.SMARTBCH, '0xF2d4D9c65C2d1080ac9e1895F6a32045741831Cd', 2, 'HONK', 'Honk'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0x3f43FF8eF6715Eb6E76452a9d719f54eFa5372b1', + rewardToken: new Token(ChainId.SMARTBCH, '0xF2d4D9c65C2d1080ac9e1895F6a32045741831Cd', 2, 'HONK', 'Honk'), + rewardPerSecond: '2325', + }, + '0x864c0090D955D947D809CF315E17665Bf9e3b6aB': { + farmId: 4, + allocPoint: 14999748, + token0: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), + token1: TANGO[ChainId.SMARTBCH], + rewarderId: '0x3e9AFf4008F3D6E05697025acCb607021e36e1e6', + rewardToken: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), + rewardPerSecond: '005787037000000000', + }, + '0x9E59AAc21DaB7C89d0BDA99335386868539Af9B8': { + farmId: 5, + allocPoint: 1, + token0: new Token(ChainId.SMARTBCH, '0x0D8b355f9CEDeB612f2df4B39CdD87059A244567', 2, 'CANDYMAN', 'CandyMAN'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0xDc7D5F633F5721fa3Ff2B73B9396F0eAcE58ec0F', + rewardToken: new Token( + ChainId.SMARTBCH, + '0x0D8b355f9CEDeB612f2df4B39CdD87059A244567', + 2, + 'CANDYMAN', + 'CandyMAN' + ), + rewardPerSecond: '01', + }, + '0x365Ec450d670455b336b833Ca363d21b4de3B9E3': { + farmId: 6, + allocPoint: 62499, + token0: new Token(ChainId.SMARTBCH, '0x4F1480ba79F7477230ec3b2eCc868E8221925072', 18, 'KONRA', 'Konra'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0x2F3056526014992b757a9F81D7B084e60a0Eb187', + rewardToken: new Token(ChainId.SMARTBCH, '0x4F1480ba79F7477230ec3b2eCc868E8221925072', 18, 'KONRA', 'Konra'), + rewardPerSecond: '000011580000000000', + }, + '0x5109aABC359c5267B6d470f43414319dd8a3C123': { + farmId: 7, + allocPoint: 15624, + token0: new Token(ChainId.SMARTBCH, '0x0cb20466c0dd6454acf50ec26f3042ccc6362fa0', 18, 'NARATH', 'Narath'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0x1d42B726E32f41102BC265d8a1cD5a1751e8deD9', + rewardToken: new Token(ChainId.SMARTBCH, '0x0cb20466c0dd6454acf50ec26f3042ccc6362fa0', 18, 'NARATH', 'Narath'), + rewardPerSecond: '925000000000000000000', + }, + '0x7B545548dabA183Fc779e656da09dF6bD2b94F88': { + farmId: 8, + allocPoint: 499998, + token0: new Token( + ChainId.SMARTBCH, + '0x4EA4A00E15B9E8FeE27eB6156a865525083e9F71', + 18, + 'Martin₿', + 'Africa Unite' + ), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0x6C54582E1F7E0602F526267BEB4b073E35eB46a4', + rewardToken: new Token( + ChainId.SMARTBCH, + '0x4EA4A00E15B9E8FeE27eB6156a865525083e9F71', + 18, + 'Martin₿', + 'Africa Unite' + ), + rewardPerSecond: '66979000000000000000000', + }, + '0x2a7c9D8E0E2286A596192C3C16Cc68979D331F29': { + farmId: 9, + allocPoint: 62499, + token0: new Token(ChainId.SMARTBCH, '0x387122d80A642581E5AD620696a37b98BB9272e7', 18, 'JOOST', 'Joost.energy'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0xA76F4318eDe44a205EAcFB5eF6EaF28b0A83AAb8', + rewardToken: new Token( + ChainId.SMARTBCH, + '0x387122d80A642581E5AD620696a37b98BB9272e7', + 18, + 'JOOST', + 'Joost.energy' + ), + rewardPerSecond: '800000000000000000', + }, + }, + [ChainId.SMARTBCH_AMBER]: { + '0xCFa5B1C5FaBF867842Ac3C25E729Fc3671d27c50': { + farmId: 0, + allocPoint: 1249937, + token0: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), + token1: WBCH[ChainId.SMARTBCH], + rewarderId: '0xbA85D6bB454315A0fb65b205Fa48DBAff82A4019', + rewardToken: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), + rewardPerSecond: '1000000000000000000', + }, + }, + } + + const kashiPairs = [] // unused + const swapPairs = [] + const farms2 = useFarms() + let farms = [] + + for (const [pairAddress, pair] of Object.entries(hardcodedPairs[chainId])) { + swapPairs.push({ + id: pairAddress, + reserveUSD: '100000', + totalSupply: '1000', + timestamp: '1599830986', + token0: { + id: pair.token0.address, + name: pair.token0.name, + symbol: pair.token0.symbol, + decimals: pair.token0.decimals, + }, + token1: { + id: pair.token1.address, + name: pair.token1.name, + symbol: pair.token1.symbol, + decimals: pair.token1.decimals, + }, + }) + + const f = { + pair: pairAddress, + symbol: `${hardcodedPairs[chainId][pairAddress].token0.symbol}-${hardcodedPairs[chainId][pairAddress].token1.symbol}`, + // eslint-disable-next-line react-hooks/rules-of-hooks + pool: usePool(pairAddress), + allocPoint: pair.allocPoint, + balance: '1000000000000000000', + chef: 0, + id: pair.farmId, + pendingSushi: undefined, + pending: 0, + owner: { + id: MASTERCHEF_ADDRESS[chainId], + sushiPerBlock: '10000000000000000000', + totalAllocPoint: '999949984', + }, + userCount: 1, + } + // eslint-disable-next-line react-hooks/rules-of-hooks + f.pendingSushi = usePendingSushi(f) + f.pending = Number.parseFloat(f.pendingSushi?.toFixed()) + + farms.push(f) + } + + // console.log(farms); + const flexUSDTangoPool = farms[1].pool + const bchFlexUSDPool = farms[3].pool + const bchTangoPool = farms[2].pool + let bchPriceUSD = 0 + let tangoPriceUSD = 0 + let tangoPriceBCH = 0 + if (bchFlexUSDPool.reserves) { + bchPriceUSD = + Number.parseFloat(bchFlexUSDPool.reserves[1].toFixed()) / Number.parseFloat(bchFlexUSDPool.reserves[0].toFixed()) + } + if (flexUSDTangoPool.reserves) { + tangoPriceUSD = + 1 / + (Number.parseFloat(flexUSDTangoPool.reserves[0].toFixed()) / + Number.parseFloat(flexUSDTangoPool.reserves[1].toFixed())) + } + if (bchTangoPool.reserves) { + tangoPriceBCH = + Number.parseFloat(bchTangoPool.reserves[0].toFixed()) / Number.parseFloat(bchTangoPool.reserves[1].toFixed()) + } + + for (const [pairAddress, pair] of Object.entries(hardcodedPairs2x[chainId])) { + swapPairs.push({ + id: pairAddress, + reserveUSD: '100000', + totalSupply: '1000', + timestamp: '1599830986', + token0: { + id: pair.token0.address, + name: pair.token0.name, + symbol: pair.token0.symbol, + decimals: pair.token0.decimals, + }, + token1: { + id: pair.token1.address, + name: pair.token1.name, + symbol: pair.token1.symbol, + decimals: pair.token1.decimals, + }, + }) + + const f = { + pair: pairAddress, + symbol: `${hardcodedPairs2x[chainId][pairAddress].token0.symbol}-${hardcodedPairs2x[chainId][pairAddress].token1.symbol}`, + + // eslint-disable-next-line react-hooks/rules-of-hooks + pool: usePool(pairAddress), + + allocPoint: pair.allocPoint, + balance: '1000000000000000000', + chef: 1, + id: pair.farmId, + pendingSushi: undefined, + pending: 0, + owner: { + id: MASTERCHEF_V2_ADDRESS[chainId], + sushiPerBlock: '10000000000000000000', + totalAllocPoint: '999949984', // "999949984" + }, + + rewarder: { + id: pair.rewarderId, + rewardToken: pair.rewardToken.address, + rewardPerSecond: pair.rewardPerSecond, + }, + + rewardToken: { + ...pair.rewardToken, + // eslint-disable-next-line react-hooks/rules-of-hooks + derivedETH: getTokenPriceInBch(usePool(pairAddress), pair, chainId, tangoPriceBCH, bchPriceUSD), + }, + maxPrice: (100 * Math.random()).toFixed(4), + minPrice: (10 * Math.random()).toFixed(4), + userCount: 1, + } + // eslint-disable-next-line react-hooks/rules-of-hooks + f.pendingSushi = usePendingSushi(f) + f.pending = f.id % 2 === 0 ? 1 : 0 + farms.push(f) + } + + const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator( + MASTERCHEF_ADDRESS[chainId], + farms.map((farm) => new Token(chainId, farm.pair, 18, 'LP', 'LP Token')) + ) + + const [v2PairsBalances2x, fetchingV2PairBalances2x] = useTokenBalancesWithLoadingIndicator( + MASTERCHEF_V2_ADDRESS[chainId], + farms.map((farm) => new Token(chainId, farm.pair, 18, 'LP', 'LP Token')) + ) + + if (!fetchingV2PairBalances) { + for (let i = 0; i < farms.length; ++i) { + if (v2PairsBalances.hasOwnProperty(farms[i].pair) && farms[i].pool.totalSupply) { + const totalSupply = Number.parseFloat(farms[i].pool.totalSupply.toFixed()) + let chefBalance = Number.parseFloat(v2PairsBalances[farms[i].pair].toFixed()) + + if (v2PairsBalances2x.hasOwnProperty(farms[i].pair)) { + chefBalance += Number.parseFloat(v2PairsBalances2x[farms[i].pair].toFixed()) + } + + let tvl = 0 + if (farms[i].pool.token0 === TANGO[chainId].address) { + const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) + tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 + } else if (farms[i].pool.token1 === TANGO[chainId].address) { + const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) + tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 + } else if (farms[i].pool.token0 === FLEXUSD.address) { + const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) + tvl = (reserve / totalSupply) * chefBalance * 2 + } else if (farms[i].pool.token1 === FLEXUSD.address) { + const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) + tvl = (reserve / totalSupply) * chefBalance * 2 + } else if (farms[i].pool.token0 === WBCH[chainId].address) { + const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) + tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 + } else if (farms[i].pool.token1 === WBCH[chainId].address) { + const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) + tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 + } + farms[i].tvl = tvl + farms[i].chefBalance = chefBalance + } else { + farms[i].tvl = '0' + farms[i].chefBalance = 0 + } + } + } + + const positions = usePositions(chainId) + + // const averageBlockTime = useAverageBlockTime() + const averageBlockTime = 6 + const masterChefV1TotalAllocPoint = useMasterChefV1TotalAllocPoint() + const masterChefV1SushiPerBlock = useMasterChefV1SushiPerBlock() + + const blocksPerDay = 86400 / Number(averageBlockTime) + + const map = (pool) => { + // TODO: Account for fees generated in case of swap pairs, and use standard compounding + // algorithm with the same intervals acrosss chains to account for consistency. + // For lending pairs, what should the equivilent for fees generated? Interest gained? + // How can we include this? + + // TODO: Deal with inconsistencies between properties on subgraph + pool.owner = pool?.owner || pool?.masterChef + pool.balance = pool?.balance || pool?.slpBalance + + const swapPair = swapPairs?.find((pair) => pair.id === pool.pair) + const kashiPair = kashiPairs?.find((pair) => pair.id === pool.pair) + + const type = swapPair ? PairType.SWAP : PairType.KASHI + + const pair = swapPair || kashiPair + + const blocksPerDay = 15684 // calculated empirically + + function getRewards() { + // TODO: Some subgraphs give sushiPerBlock & sushiPerSecond, and mcv2 gives nothing + const sushiPerBlock = + pool?.owner?.sushiPerBlock / 1e18 || + (pool?.owner?.sushiPerSecond / 1e18) * averageBlockTime || + masterChefV1SushiPerBlock + + const rewardPerBlock = (pool.allocPoint / pool.owner.totalAllocPoint) * sushiPerBlock + + const defaultReward = { + token: 'TANGO', + icon: 'https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/0x73BE9c8Edf5e951c9a0762EA2b1DE8c8F38B5e91/logo.png', + rewardPerBlock, + rewardPerDay: rewardPerBlock * blocksPerDay, + rewardPrice: +tangoPriceUSD, + } + + let rewards = [defaultReward] + + if (pool.chef === Chef.MASTERCHEF_V2) { + // override for mcv2... + pool.owner.totalAllocPoint = masterChefV1TotalAllocPoint + + const icon = `https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/${getAddress( + pool.rewarder.rewardToken + )}/logo.png` + + const decimals = 10 ** pool.rewardToken.decimals + // console.log("pool.rewardToken.decimals: ", pool.rewardToken.decimals); + // console.log("pool.rewardToken.derivedETH: ", pool.rewardToken.derivedETH); + // console.log("pool.rewarder.rewardPerSecond: ", pool.rewarder.rewardPerSecond); + // console.log("decimals: ", decimals); + + if (pool.rewarder.rewardToken !== '0x0000000000000000000000000000000000000000') { + // console.log("pool.rewarder.rewardPerSecond / decimals: ", pool.rewarder.rewardPerSecond / decimals); + + const rewardPerBlock = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime + + // console.log("rewardPerBlock: ", rewardPerBlock); + + const rewardPerDay = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime * blocksPerDay + const rewardPrice = pool.rewardToken.derivedETH * bchPriceUSD + + // console.log("rewardPrice: ", rewardPrice); + + const reward = { + token: pool.rewardToken.symbol, + icon: icon, + rewardPerBlock, + rewardPerDay, + rewardPrice, + } + + rewards[1] = reward + } + } + + return rewards + } + + const rewards = getRewards() + + const balance = Number(pool.balance / 1e18) + + const roiPerBlock = + rewards.reduce((previousValue, currentValue) => { + return previousValue + currentValue.rewardPerBlock * currentValue.rewardPrice + }, 0) / pool.tvl + + const roiPerDay = roiPerBlock * blocksPerDay + const roiPerYear = roiPerDay * 365 + + // console.log("rewards: ", rewards); + // console.log("roiPerBlock: ", roiPerBlock); + // console.log("roiPerDay: ", roiPerDay); + // console.log("roiPerYear: ", roiPerYear); + + const position = positions.find((position) => position.id === pool.id && position.chef === pool.chef) + + return { + ...pool, + ...position, + pair: { + ...pair, + decimals: pair.type === PairType.KASHI ? Number(pair.asset.tokenInfo.decimals) : 18, + type, + }, + balance, + roiPerYear, + rewards, + } + } + + const FILTER = { + all: (farm) => farm.allocPoint !== 0, + portfolio: (farm) => farm.pending !== 0, + past: (farm) => farm.allocPoint === 0, + // sushi: (farm) => farm.pair.type === PairType.SWAP && farm.allocPoint !== '0', + // kashi: (farm) => farm.pair.type === PairType.KASHI && farm.allocPoint !== '0', + // '2x': (farm) => (farm.chef === Chef.MASTERCHEF_V2) && farm.allocPoint !== '0', + + '2x': (farm) => farm.chef === Chef.MASTERCHEF_V2 && farm.rewards.length > 1 && farm.allocPoint !== '0', + } + + const data = farms + .filter((farm) => { + return ( + (swapPairs && swapPairs.find((pair) => pair.id === farm.pair)) || + (kashiPairs && kashiPairs.find((pair) => pair.id === farm.pair)) + ) + }) + .map(map) + .filter((farm) => { + return type in FILTER ? FILTER[type](farm) : true + }) + + const options = { + keys: ['pair.id', 'pair.token0.symbol', 'pair.token1.symbol'], + threshold: 0.4, + } + + const { result, term, search } = useFuse({ + data, + options, + }) + + const basePath = 'robots/robots-list' + + const optionsMenu = [ + { + href: `/${basePath}?filter=portfolio`, + label: 'Your Robots', + exact: true + }, + { + divider: true + }, + { + href: `/${basePath}?filter=all`, + label: 'All Robots' + }, + ] + + return ( + + + Robots | Orders.Cash + + +
+ +
+
+
+ + + + +
+ +
+ Robots{' '} +
+
+ + +
+
+ ) +} From 178ef3ce6b5d55446848f7347ce5c6e2a6a5a5c6 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sun, 25 Sep 2022 17:00:18 -0300 Subject: [PATCH 02/83] feat: gridex added to navlink --- next.config.js | 4 + src/components/Header/index.tsx | 12 +- src/functions/feature.ts | 2 + src/pages/robots/buy-robot/index.tsx | 142 ++++++++++++++++++++++++ src/pages/robots/create-robot/index.tsx | 11 +- src/pages/robots/robots-list/index.tsx | 18 ++- 6 files changed, 178 insertions(+), 11 deletions(-) create mode 100644 src/pages/robots/buy-robot/index.tsx diff --git a/next.config.js b/next.config.js index a93b377437..7f626dd993 100644 --- a/next.config.js +++ b/next.config.js @@ -127,6 +127,10 @@ const nextConfig = { source: '/find', destination: '/exchange/find', }, + { + source: '/gridex', + destination: '/robots/robots-list' + } ] }, i18n: { diff --git a/src/components/Header/index.tsx b/src/components/Header/index.tsx index da87c5a9eb..ddb901da73 100644 --- a/src/components/Header/index.tsx +++ b/src/components/Header/index.tsx @@ -66,7 +66,7 @@ function AppBar(): JSX.Element { id={`smart-swap-nav-link`} className="p-2 text-baseline text-primary hover:text-high-emphesis focus:text-high-emphesis md:p-3 whitespace-nowrap" > - {i18n._(t`Limit`)} NEW + {i18n._(t`Limit`)} @@ -127,6 +127,16 @@ function AppBar(): JSX.Element { )} + {chainId && featureEnabled(Feature.GRIDEX, chainId) && ( + + + {i18n._(t`Gridex`)} NEW + + + )} {/* {chainId && featureEnabled(Feature.ANALYTICS, chainId) && ( { + setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) + } + const handleCurrencyBSelect = (currencyB: Currency) => { + console.log(currenciesSelected) + setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) + } + + const router = useRouter() + const tokens = router.query.tokens + const [currencyIdA, currencyIdB] = (tokens as string[]) || [undefined, undefined] + + const currencyA = useCurrency(currencyIdA) + const currencyB = useCurrency(currencyIdB) + + const { independentField, typedValue, otherTypedValue } = useMintState() + const { + dependentField, + currencies, + pair, + pairState, + currencyBalances, + parsedAmounts, + price, + noLiquidity, + liquidityMinted, + poolTokenPercentage, + error, + } = useDerivedMintInfo(currencyA ?? undefined, currencyB ?? undefined) + + + const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) + + + + // get the max amounts user can add + const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmountSpend(currencyBalances[field]), + } + }, + {} + ) + const atMaxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0'), + } + }, + {} + ) + + + + return (<> + + Buy Gridex | Orders.Cash + + + + + + + + { + onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') + }} + onCurrencySelect={handleCurrencyASelect} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + showCommonBases + + /> + + + + + + + + + ) +} +{/* + + + + */} + + + + +{/* +
+ + + + + + + +
+ + +*/} \ No newline at end of file diff --git a/src/pages/robots/create-robot/index.tsx b/src/pages/robots/create-robot/index.tsx index 18323613ee..bbb6d0da3a 100644 --- a/src/pages/robots/create-robot/index.tsx +++ b/src/pages/robots/create-robot/index.tsx @@ -236,7 +236,7 @@ export default function CreateRobotPage() { return ( <> - Create Robots | Orders.Cash + Create Gridex | Orders.Cash - {i18n._(t`View Orders Robots`)} + {i18n._(t`View Your Gridex`)} { onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') @@ -294,6 +295,7 @@ export default function CreateRobotPage() { { @@ -319,12 +321,11 @@ export default function CreateRobotPage() { )} { - currenciesSelected && currenciesSelected?.currencyA && currenciesSelected?.currencyB && (
- ) + } {addIsUnsupported ? ( @@ -335,7 +336,7 @@ export default function CreateRobotPage() { ) : ( )} diff --git a/src/pages/robots/robots-list/index.tsx b/src/pages/robots/robots-list/index.tsx index f8c1ff87d7..b0ccf239f2 100644 --- a/src/pages/robots/robots-list/index.tsx +++ b/src/pages/robots/robots-list/index.tsx @@ -764,6 +764,7 @@ export default function Robot(): JSX.Element { all: (farm) => farm.allocPoint !== 0, portfolio: (farm) => farm.pending !== 0, past: (farm) => farm.allocPoint === 0, + // sushi: (farm) => farm.pair.type === PairType.SWAP && farm.allocPoint !== '0', // kashi: (farm) => farm.pair.type === PairType.KASHI && farm.allocPoint !== '0', // '2x': (farm) => (farm.chef === Chef.MASTERCHEF_V2) && farm.allocPoint !== '0', @@ -798,7 +799,7 @@ export default function Robot(): JSX.Element { const optionsMenu = [ { href: `/${basePath}?filter=portfolio`, - label: 'Your Robots', + label: 'Your Gridex', exact: true }, { @@ -806,8 +807,15 @@ export default function Robot(): JSX.Element { }, { href: `/${basePath}?filter=all`, - label: 'All Robots' + label: 'Gridex on Sale' + },{ + divider: true }, + { + href: `/robots/buy-robot`, + label: 'Buy Gridex', + exact: true + } ] return ( @@ -817,7 +825,7 @@ export default function Robot(): JSX.Element { maxWidth="7xl" > - Robots | Orders.Cash + Gridex | Orders.Cash
@@ -842,13 +850,13 @@ export default function Robot(): JSX.Element { className='w-[190px] text-[#E3E3E3] flex items-center gap-2' > - {i18n._(t`Create Robot`)} + {i18n._(t`Create Gridex`)}
- Robots{' '} + Gridex{' '}
From 7a0a65806cc08d572207db3941ec3d173ab1d318 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 26 Sep 2022 18:40:45 -0300 Subject: [PATCH 03/83] feat: gridexmenu and routes --- next.config.js | 2 +- src/features/onsen/GridexMenu.tsx | 116 ++++++++++++++++++ src/features/robots/RobotList.tsx | 2 +- .../buy-robot => gridex/buy-gridex}/index.tsx | 6 +- .../create-gridex}/index.tsx | 2 +- .../gridex-list}/index.tsx | 7 +- 6 files changed, 124 insertions(+), 11 deletions(-) create mode 100644 src/features/onsen/GridexMenu.tsx rename src/pages/{robots/buy-robot => gridex/buy-gridex}/index.tsx (99%) rename src/pages/{robots/create-robot => gridex/create-gridex}/index.tsx (99%) rename src/pages/{robots/robots-list => gridex/gridex-list}/index.tsx (99%) diff --git a/next.config.js b/next.config.js index 7f626dd993..2a09ae1035 100644 --- a/next.config.js +++ b/next.config.js @@ -129,7 +129,7 @@ const nextConfig = { }, { source: '/gridex', - destination: '/robots/robots-list' + destination: '/gridex/gridex-list' } ] }, diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx new file mode 100644 index 0000000000..bb6fc71558 --- /dev/null +++ b/src/features/onsen/GridexMenu.tsx @@ -0,0 +1,116 @@ +import { ChainId } from '@tangoswapcash/sdk' +import NavLink from '../../components/NavLink' +import React from 'react' +import { t } from '@lingui/macro' +import { useLingui } from '@lingui/react' +import { useActiveWeb3React } from '../../hooks' +import { useWalletModalToggle } from '../../state/application/hooks' + +const defaultOptions = [ + { + href: `/farm?filter=portfolio`, + label: 'Your Farms', + exact: true + }, + { + divider: true + }, + { + href: "/farm?filter=all", + label: 'All Farms' + }, + { + href: `/farm?filter=2x`, + label: '2x Reward Farms', + exact: true + }, + { + href: "/farm?filter=past", + label: 'Past Farms' + } +] + +const GridexMenu = ({ positionsLength, options = defaultOptions}) => { + const { account, chainId } = useActiveWeb3React() + const { i18n } = useLingui() + const toggleWalletModal = useWalletModalToggle() + + return ( +
+ {account ? ( + + + Your Gridex + + + ) : ( + + Your Gridex + + )} + + + Gridex on Sale + + + +
+ + + + {i18n._(t`Buy Gridex`)} + + + {/* + + {i18n._(t`Past Farms`)} + + */} + + + {/*chainId === ChainId.MAINNET && ( + <> + + + Kashi Farms + + + + + TANGOswap Farms + + + + )*/} + +
+
+ ) +} + +export default GridexMenu diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index 3df0949a9d..44d136f9eb 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -20,7 +20,7 @@ const RobotList = ({ robots, term }) => { className="flex items-center col-span-2 px-4 cursor-pointer md:col-span-1" onClick={() => requestSort('symbol')} > -
{i18n._(t`Pair`)}
+
{i18n._(t`Stock/Money`)}
{sortConfig && sortConfig.key === 'symbol' && ((sortConfig.direction === 'ascending' && ) || diff --git a/src/pages/robots/buy-robot/index.tsx b/src/pages/gridex/buy-gridex/index.tsx similarity index 99% rename from src/pages/robots/buy-robot/index.tsx rename to src/pages/gridex/buy-gridex/index.tsx index 906e7a0bcd..26302c5302 100644 --- a/src/pages/robots/buy-robot/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -11,11 +11,7 @@ import { useRouter } from 'next/router' import { Field } from '../../../state/mint/actions' import { currencyId, maxAmountSpend } from '../../../functions/currency' - - - - -export default function Modal() { +export default function BuyGridex() { const [currenciesSelected, setCurrenciesSelected] = useState(null); const handleCurrencyASelect = (currencyA: Currency) => { setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) diff --git a/src/pages/robots/create-robot/index.tsx b/src/pages/gridex/create-gridex/index.tsx similarity index 99% rename from src/pages/robots/create-robot/index.tsx rename to src/pages/gridex/create-gridex/index.tsx index bbb6d0da3a..4bdf805ab0 100644 --- a/src/pages/robots/create-robot/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -47,7 +47,7 @@ import PanelLimitPrice from '../../../components/PanelLimitPrice' const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) -export default function CreateRobotPage() { +export default function CreateGridexPage() { const { i18n } = useLingui() const { account, chainId, library } = useActiveWeb3React() const router = useRouter() diff --git a/src/pages/robots/robots-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx similarity index 99% rename from src/pages/robots/robots-list/index.tsx rename to src/pages/gridex/gridex-list/index.tsx index b0ccf239f2..7130638ddc 100644 --- a/src/pages/robots/robots-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -45,6 +45,7 @@ import { useLingui } from '@lingui/react' import RobotList from '../../../features/robots/RobotList' import Button from '../../../components/Button' import NavLink from '../../../components/NavLink' +import GridexMenu from '../../../features/onsen/GridexMenu' function getTokensSorted(pool, pair) { if (pool.token0 == pair.token0.address && pool.token1 == pair.token1.address) { @@ -87,7 +88,7 @@ function getTokenPriceInBch(pool, pair, chainId, tangoPriceBCH, bchPriceUSD) { return derivedETH } -export default function Robot(): JSX.Element { +export default function Gridex(): JSX.Element { const { i18n } = useLingui() const { chainId } = useActiveWeb3React() const router = useRouter() @@ -829,7 +830,7 @@ export default function Robot(): JSX.Element {
- +
@@ -843,7 +844,7 @@ export default function Robot(): JSX.Element { 'relative w-full bg-transparent border border-transparent focus:border-gradient-r-blue-pink-dark-900 rounded placeholder-secondary focus:placeholder-primary font-bold text-base px-6 py-3.5', }} /> - + +
+
+ +
+ {/* {!hideInput && ( +
+ <> + {showMaxButton && selectedCurrencyBalance && ( + + )} + { + onUserInput(val) + }} + readOnly={readOnly} + /> + {!hideBalance && currency && selectedCurrencyBalance ? ( +
+
+ {renderBalance ? ( + renderBalance(selectedCurrencyBalance) + ) : ( + <> + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBalance, 4)} {currency.symbol} + + )} +
+ +
+ ) : null} + +
+ )} */} +
+ {!disableCurrencySelect && onCurrencySelect && ( + + )} +
+ ) +} diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index b5545dfdee..1c8f8e74e4 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -87,10 +87,12 @@ const RobotListItems = ({ robot, ...rest }) => { )}
- {/* {open && } */} + {open && } )} + + ) } diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index 26302c5302..04e42a3825 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -10,6 +10,7 @@ import { useCurrency } from '../../../hooks/Tokens' import { useRouter } from 'next/router' import { Field } from '../../../state/mint/actions' import { currencyId, maxAmountSpend } from '../../../functions/currency' +import BuyRobotsPanel from "../../../components/BuyRobotsPanel" export default function BuyGridex() { const [currenciesSelected, setCurrenciesSelected] = useState(null); @@ -84,7 +85,7 @@ export default function BuyGridex() { - Date: Mon, 26 Sep 2022 20:29:04 -0300 Subject: [PATCH 06/83] feat: on-sale added --- src/features/onsen/GridexMenu.tsx | 4 ++-- src/features/robots/RobotListItemDetails.tsx | 6 +++--- src/pages/gridex/on-sale/index.tsx | 6 ++++++ 3 files changed, 11 insertions(+), 5 deletions(-) create mode 100644 src/pages/gridex/on-sale/index.tsx diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx index 2dcea1dbd9..d8567800dc 100644 --- a/src/features/onsen/GridexMenu.tsx +++ b/src/features/onsen/GridexMenu.tsx @@ -18,7 +18,7 @@ const defaultOptions = [ divider: true }, { - href: `/${basePath}/on-Sale`, + href: `/${basePath}/on-sale`, label: 'Gridex on Sale' },{ divider: true @@ -56,7 +56,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { )} diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 005fbb3fb2..6d9f4adc7f 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -114,7 +114,7 @@ const RobotListItemDetails = ({ robot }) => { color='red' onClick={handleDeleteRobot} > - {i18n._(t`Delete Robot`)} + {i18n._(t`Delete Gridex`)}
@@ -122,7 +122,7 @@ const RobotListItemDetails = ({ robot }) => { color='default' onClick={handleSellRobot} > - {i18n._(t`Sell Robot`)} + {i18n._(t`Sell Gridex`)}
@@ -132,7 +132,7 @@ const RobotListItemDetails = ({ robot }) => { color="gradient" onClick={handleBuyRobot} > - {i18n._(t`BUY ROBOT`)} + {i18n._(t`Buy Gridex`)} ) diff --git a/src/pages/gridex/on-sale/index.tsx b/src/pages/gridex/on-sale/index.tsx new file mode 100644 index 0000000000..649fc2f5d8 --- /dev/null +++ b/src/pages/gridex/on-sale/index.tsx @@ -0,0 +1,6 @@ +import React from 'react' +export default function index() { + return
+ +
+}; From ae05d06f1fa27cd0df17cd84956a4bb9ee1a858f Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Thu, 29 Sep 2022 21:44:00 -0300 Subject: [PATCH 07/83] feat: buymenu better appearance --- src/components/BuyRobotsPanel/index.tsx | 56 ++-- src/pages/gridex/buy-gridex/index.tsx | 7 +- src/pages/gridex/buy-gridex/test.tsx | 359 ++++++++++++++++++++++++ 3 files changed, 395 insertions(+), 27 deletions(-) create mode 100644 src/pages/gridex/buy-gridex/test.tsx diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 1c1b3e2e26..58312c605b 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -39,7 +39,7 @@ interface CurrencyInputPanelProps { readOnly?: boolean } -export default function ({ +export default function BuyRobotsPanel({ value, onUserInput, onMax, @@ -65,14 +65,15 @@ export default function ({ const [modalOpen, setModalOpen] = useState(false) const { account } = useActiveWeb3React() const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) + const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, otherCurrency ?? undefined) const handleDismissSearch = useCallback(() => { setModalOpen(false) }, [setModalOpen]) return ( -
-
+
+
+ {/* Second input */}
- {/* {!hideInput && ( +
<> - {showMaxButton && selectedCurrencyBalance && ( + { (
{!disableCurrencySelect && onCurrencySelect && ( - - + + + diff --git a/src/pages/gridex/buy-gridex/test.tsx b/src/pages/gridex/buy-gridex/test.tsx new file mode 100644 index 0000000000..4bdf805ab0 --- /dev/null +++ b/src/pages/gridex/buy-gridex/test.tsx @@ -0,0 +1,359 @@ +import { ApprovalState, useApproveCallback } from '../../../hooks/useApproveCallback' +import { AutoRow, RowBetween } from '../../../components/Row' +import Button, { ButtonError } from '../../../components/Button' +import { Currency, CurrencyAmount, Percent, WNATIVE, currencyEquals } from '@tangoswapcash/sdk' +import { ONE_BIPS, ZERO_PERCENT } from '../../../constants' +import React, { useCallback, useState } from 'react' +import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' +import { calculateGasMargin, calculateSlippageAmount, getGasPrice } from '../../../functions/trade' +import { currencyId, maxAmountSpend } from '../../../functions/currency' +import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' +import { useExpertModeManager, useUserSlippageToleranceWithDefault } from '../../../state/user/hooks' + +import Alert from '../../../components/Alert' +import { AutoColumn } from '../../../components/Column' +import { BigNumber } from '@ethersproject/bignumber' +import { ConfirmAddModalBottom } from '../../../features/exchange-v1/liquidity/ConfirmAddModalBottom' +import Container from '../../../components/Container' +import CurrencyInputPanel from '../../../components/CurrencyInputPanel' +import CurrencyLogo from '../../../components/CurrencyLogo' +import Dots from '../../../components/Dots' +import DoubleCurrencyLogo from '../../../components/DoubleLogo' +import DoubleGlowShadow from '../../../components/DoubleGlowShadow' +import ExchangeHeader from '../../../features/trade/Header' +import { Field } from '../../../state/mint/actions' +import Head from 'next/head' +import LiquidityHeader from '../../../features/exchange-v1/liquidity/LiquidityHeader' +import LiquidityPrice from '../../../features/exchange-v1/liquidity/LiquidityPrice' +import { MinimalPositionCard } from '../../../components/PositionCard' +import NavLink from '../../../components/NavLink' +import { PairState } from '../../../hooks/useV2Pairs' +import { Plus } from 'react-feather' +import { TransactionResponse } from '@ethersproject/providers' +import Typography from '../../../components/Typography' +import UnsupportedCurrencyFooter from '../../../features/exchange-v1/swap/UnsupportedCurrencyFooter' +import Web3Connect from '../../../components/Web3Connect' +import { t } from '@lingui/macro' +import { useActiveWeb3React } from '../../../hooks/useActiveWeb3React' +import { useCurrency } from '../../../hooks/Tokens' +import { useIsSwapUnsupported } from '../../../hooks/useIsSwapUnsupported' +import { useLingui } from '@lingui/react' +import { useRouter } from 'next/router' +import { useRouterContract } from '../../../hooks' +import { useTransactionAdder } from '../../../state/transactions/hooks' +import useTransactionDeadline from '../../../hooks/useTransactionDeadline' +import { useWalletModalToggle } from '../../../state/application/hooks' +import PanelLimitPrice from '../../../components/PanelLimitPrice' + +const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) + +export default function CreateGridexPage() { + const { i18n } = useLingui() + const { account, chainId, library } = useActiveWeb3React() + const router = useRouter() + const tokens = router.query.tokens + const [currencyIdA, currencyIdB] = (tokens as string[]) || [undefined, undefined] + + const currencyA = useCurrency(currencyIdA) + const currencyB = useCurrency(currencyIdB) + + const [currenciesSelected, setCurrenciesSelected] = useState(null) + + const oneCurrencyIsWETH = Boolean( + chainId && + ((currencyA && currencyEquals(currencyA, WNATIVE[chainId])) || + (currencyB && currencyEquals(currencyB, WNATIVE[chainId]))) + ) + + const toggleWalletModal = useWalletModalToggle() // toggle wallet when disconnected + + const [isExpertMode] = useExpertModeManager() + + // mint state + const { independentField, typedValue, otherTypedValue } = useMintState() + const { + dependentField, + currencies, + pair, + pairState, + currencyBalances, + parsedAmounts, + price, + noLiquidity, + liquidityMinted, + poolTokenPercentage, + error, + } = useDerivedMintInfo(currencyA ?? undefined, currencyB ?? undefined) + + const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) + + const isValid = !error + + // modal and loading + const [showConfirm, setShowConfirm] = useState(false) + const [attemptingTxn, setAttemptingTxn] = useState(false) // clicked confirm + + // txn values + const deadline = useTransactionDeadline() // custom from users settings + + // const [allowedSlippage] = useUserSlippageTolerance(); // custom from users + + const allowedSlippage = useUserSlippageToleranceWithDefault(DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE) // custom from users + + const [txHash, setTxHash] = useState('') + + // get formatted amounts + const formattedAmounts = { + [independentField]: typedValue, + [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', + } + + // get the max amounts user can add + const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmountSpend(currencyBalances[field]), + } + }, + {} + ) + + const atMaxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0'), + } + }, + {} + ) + + const routerContract = useRouterContract() + + // check whether the user has approved the router on the tokens + const [approvalA, approveACallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_A], routerContract?.address) + const [approvalB, approveBCallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_B], routerContract?.address) + + const addTransaction = useTransactionAdder() + + async function onAdd() { + if (!chainId || !library || !account || !routerContract) return + + const { [Field.CURRENCY_A]: parsedAmountA, [Field.CURRENCY_B]: parsedAmountB } = parsedAmounts + + console.log({ parsedAmountA, parsedAmountB, currencyA, currencyB, deadline }) + + if (!parsedAmountA || !parsedAmountB || !currencyA || !currencyB || !deadline) { + return + } + + const amountsMin = { + [Field.CURRENCY_A]: calculateSlippageAmount(parsedAmountA, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], + [Field.CURRENCY_B]: calculateSlippageAmount(parsedAmountB, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], + } + + let estimate, + method: (...args: any) => Promise, + args: Array, + value: BigNumber | null + if (currencyA.isNative || currencyB.isNative) { + const tokenBIsETH = currencyB.isNative + estimate = routerContract.estimateGas.addLiquidityETH + method = routerContract.addLiquidityETH + args = [ + (tokenBIsETH ? currencyA : currencyB)?.wrapped?.address ?? '', // token + (tokenBIsETH ? parsedAmountA : parsedAmountB).quotient.toString(), // token desired + amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min + amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min + account, + deadline.toHexString(), + ] + value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).quotient.toString()) + } else { + estimate = routerContract.estimateGas.addLiquidity + method = routerContract.addLiquidity + args = [ + currencyA?.wrapped?.address ?? '', + currencyB?.wrapped?.address ?? '', + parsedAmountA.quotient.toString(), + parsedAmountB.quotient.toString(), + amountsMin[Field.CURRENCY_A].toString(), + amountsMin[Field.CURRENCY_B].toString(), + account, + deadline.toHexString(), + ] + value = null + } + + setAttemptingTxn(true) + try { + const estimatedGasLimit = await estimate(...args, { + ...(value ? { value } : {}), + gasPrice: getGasPrice(), + }) + + const response = await method(...args, { + ...(value ? { value } : {}), + gasLimit: calculateGasMargin(estimatedGasLimit), + gasPrice: getGasPrice(), + }) + + setAttemptingTxn(false) + + addTransaction(response, { + summary: i18n._( + t`Add ${parsedAmounts[Field.CURRENCY_A]?.toSignificant(3)} ${ + currencies[Field.CURRENCY_A]?.symbol + } and ${parsedAmounts[Field.CURRENCY_B]?.toSignificant(3)} ${currencies[Field.CURRENCY_B]?.symbol}` + ), + }) + + setTxHash(response.hash) + } catch (error) { + setAttemptingTxn(false) + // we only care if the error is something _other_ than the user rejected the tx + if (error?.code !== 4001) { + console.error(error) + } + } + } + + const handleCurrencyASelect = (currencyA: Currency) => { + setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) + } + const handleCurrencyBSelect = (currencyB: Currency) => { + console.log(currenciesSelected) + setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) + } + + const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B) + + // console.log( + // { addIsUnsupported, isValid, approvaonFieldBInputlA, approvalB }, + // approvalA === ApprovalState.APPROVED && approvalB === ApprovalState.APPROVED + // ) + return ( + <> + + Create Gridex | Orders.Cash + + + + +
+ + +
+
+ {pair && pairState !== PairState.INVALID && ( + + )} +
+ { + onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') + }} + onCurrencySelect={handleCurrencyASelect} + showMaxButton={!atMaxAmounts[Field.CURRENCY_A]} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + id="add-liquidity-input-tokena" + showCommonBases + /> + + + + + + + + { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + showMaxButton={!atMaxAmounts[Field.CURRENCY_B]} + currency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + id="add-liquidity-input-tokenb" + showCommonBases + /> +
+ + {currencies[Field.CURRENCY_A] && currencies[Field.CURRENCY_B] && pairState !== PairState.INVALID && ( +
+ +
+ )} + + { +
+ + +
+ + } + + {addIsUnsupported ? ( + + ) : !account ? ( + + ) : ( + + )} +
+ + {!addIsUnsupported ? ( + pair && !noLiquidity && pairState !== PairState.INVALID ? ( + + ) : null + ) : ( + + )} +
+
+ + + ) +} From 9125db6449852d2aaedacd244664fe8256932850 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 5 Oct 2022 00:05:45 -0300 Subject: [PATCH 08/83] feat: bug out of buyrobotspanel --- src/components/BuyRobotsPanel/index.tsx | 58 +++++++++++++------ .../SearchModal/CurrencySearchModal.tsx | 1 + src/pages/gridex/buy-gridex/index.tsx | 22 +++---- 3 files changed, 50 insertions(+), 31 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 58312c605b..65a2a6025b 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -23,12 +23,13 @@ interface CurrencyInputPanelProps { showMaxButton: boolean label?: string onCurrencySelect?: (currency: Currency) => void + onCurrencyBSelect?: (currency: Currency) => void currency?: Currency | null + currencyB?: Currency | null disableCurrencySelect?: boolean hideBalance?: boolean pair?: Pair | null hideInput?: boolean - otherCurrency?: Currency | null fiatValue?: CurrencyAmount | null priceImpact?: Percent id: string @@ -46,9 +47,10 @@ export default function BuyRobotsPanel({ showMaxButton, label = 'Input', onCurrencySelect, + onCurrencyBSelect, currency, + currencyB, disableCurrencySelect = false, - otherCurrency, id, showCommonBases, renderBalance, @@ -65,12 +67,16 @@ export default function BuyRobotsPanel({ const [modalOpen, setModalOpen] = useState(false) const { account } = useActiveWeb3React() const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) - const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, otherCurrency ?? undefined) + const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) + const [teta, setTeta] = useState(null) const handleDismissSearch = useCallback(() => { setModalOpen(false) }, [setModalOpen]) + console.log("currencyA", currency); + console.log("currencyB", currencyB); + return (
@@ -81,7 +87,9 @@ export default function BuyRobotsPanel({ !!currency ? 'text-primary' : 'text-high-emphesis', 'open-currency-select-button h-full outline-none select-none cursor-pointer border-none text-xl font-medium items-center' )} - onClick={() => { + onClick={() => { + setTeta(false) + console.log('teta:', teta); if (onCurrencySelect) { setModalOpen(true) } @@ -138,19 +146,20 @@ export default function BuyRobotsPanel({
- {!disableCurrencySelect && onCurrencySelect && ( + { + teta ? ( + + ) + : + ( - )} + ) + }
) } diff --git a/src/modals/SearchModal/CurrencySearchModal.tsx b/src/modals/SearchModal/CurrencySearchModal.tsx index f544005f0b..f59b67fa72 100644 --- a/src/modals/SearchModal/CurrencySearchModal.tsx +++ b/src/modals/SearchModal/CurrencySearchModal.tsx @@ -18,6 +18,7 @@ interface CurrencySearchModalProps { selectedCurrency?: Currency | null onCurrencySelect: (currency: Currency) => void otherSelectedCurrency?: Currency | null + onCurrencyBSelect?: Currency | null showCommonBases?: boolean currencyList?: string[] includeNativeCurrency?: boolean diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index ebd13ef565..bd1e068cb1 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -14,14 +14,16 @@ import BuyRobotsPanel from "../../../components/BuyRobotsPanel" export default function BuyGridex() { const [currenciesSelected, setCurrenciesSelected] = useState(null); + const handleCurrencyASelect = (currencyA: Currency) => { + console.log('currencyA:', currencyA) setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) } - const handleCurrencyBSelect = (currencyB: Currency) => { - console.log(currenciesSelected) + const handleCurrencyBSelect = (currencyB: Currency) => { + console.log('currencyB:', currencyB) setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) } - + const router = useRouter() const tokens = router.query.tokens const [currencyIdA, currencyIdB] = (tokens as string[]) || [undefined, undefined] @@ -47,8 +49,6 @@ export default function BuyGridex() { const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) - - // get the max amounts user can add const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( (accumulator, field) => { @@ -84,27 +84,23 @@ export default function BuyGridex() { - { - onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') }} onCurrencySelect={handleCurrencyASelect} + onCurrencyBSelect={handleCurrencyBSelect} currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} // onOtherCurrencySelect={handleCurrencyBSelect} - otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} showCommonBases - /> - - - - From 1b54abd70b082f25efea90b83748bdfc521e1867 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 5 Oct 2022 00:13:26 -0300 Subject: [PATCH 09/83] feat: fix panel --- src/components/BuyRobotsPanel/index.tsx | 63 ++++++++++++------- .../SearchModal/CurrencySearchModal.tsx | 1 + src/pages/gridex/buy-gridex/index.tsx | 22 +++---- 3 files changed, 49 insertions(+), 37 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 58312c605b..ebcf3eb070 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -23,12 +23,13 @@ interface CurrencyInputPanelProps { showMaxButton: boolean label?: string onCurrencySelect?: (currency: Currency) => void + onCurrencyBSelect?: (currency: Currency) => void currency?: Currency | null + currencyB?: Currency | null disableCurrencySelect?: boolean hideBalance?: boolean pair?: Pair | null hideInput?: boolean - otherCurrency?: Currency | null fiatValue?: CurrencyAmount | null priceImpact?: Percent id: string @@ -46,9 +47,10 @@ export default function BuyRobotsPanel({ showMaxButton, label = 'Input', onCurrencySelect, + onCurrencyBSelect, currency, + currencyB, disableCurrencySelect = false, - otherCurrency, id, showCommonBases, renderBalance, @@ -63,9 +65,10 @@ export default function BuyRobotsPanel({ }: CurrencyInputPanelProps) { const { i18n } = useLingui() const [modalOpen, setModalOpen] = useState(false) + const [currencySelector, setCurrencySelector] = useState('') const { account } = useActiveWeb3React() const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) - const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, otherCurrency ?? undefined) + const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) const handleDismissSearch = useCallback(() => { setModalOpen(false) @@ -81,7 +84,8 @@ export default function BuyRobotsPanel({ !!currency ? 'text-primary' : 'text-high-emphesis', 'open-currency-select-button h-full outline-none select-none cursor-pointer border-none text-xl font-medium items-center' )} - onClick={() => { + onClick={() => { + setCurrencySelector('A') if (onCurrencySelect) { setModalOpen(true) } @@ -138,19 +142,20 @@ export default function BuyRobotsPanel({
- {!disableCurrencySelect && onCurrencySelect && ( + { currencySelector == 'A' ? ( + + ) : ( - )} + isOpen={modalOpen} + onDismiss={handleDismissSearch} + onCurrencySelect={onCurrencyBSelect} + selectedCurrency={currencyB} + otherSelectedCurrency={currencyB} + showCommonBases={showCommonBases} + /> + ) + }
) } diff --git a/src/modals/SearchModal/CurrencySearchModal.tsx b/src/modals/SearchModal/CurrencySearchModal.tsx index f544005f0b..f59b67fa72 100644 --- a/src/modals/SearchModal/CurrencySearchModal.tsx +++ b/src/modals/SearchModal/CurrencySearchModal.tsx @@ -18,6 +18,7 @@ interface CurrencySearchModalProps { selectedCurrency?: Currency | null onCurrencySelect: (currency: Currency) => void otherSelectedCurrency?: Currency | null + onCurrencyBSelect?: Currency | null showCommonBases?: boolean currencyList?: string[] includeNativeCurrency?: boolean diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index ebd13ef565..bd1e068cb1 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -14,14 +14,16 @@ import BuyRobotsPanel from "../../../components/BuyRobotsPanel" export default function BuyGridex() { const [currenciesSelected, setCurrenciesSelected] = useState(null); + const handleCurrencyASelect = (currencyA: Currency) => { + console.log('currencyA:', currencyA) setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) } - const handleCurrencyBSelect = (currencyB: Currency) => { - console.log(currenciesSelected) + const handleCurrencyBSelect = (currencyB: Currency) => { + console.log('currencyB:', currencyB) setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) } - + const router = useRouter() const tokens = router.query.tokens const [currencyIdA, currencyIdB] = (tokens as string[]) || [undefined, undefined] @@ -47,8 +49,6 @@ export default function BuyGridex() { const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) - - // get the max amounts user can add const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( (accumulator, field) => { @@ -84,27 +84,23 @@ export default function BuyGridex() { - { - onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') }} onCurrencySelect={handleCurrencyASelect} + onCurrencyBSelect={handleCurrencyBSelect} currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} // onOtherCurrencySelect={handleCurrencyBSelect} - otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} showCommonBases - /> - - - - From 620d2cb0dd984c4f363021ec3b003aa39221131a Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 5 Oct 2022 19:39:24 -0300 Subject: [PATCH 10/83] feat: robots panel --- src/components/BuyRobotsPanel/index.tsx | 64 +++++++++++++------ src/components/Header/index.tsx | 2 +- .../SearchModal/CurrencySearchModal.tsx | 3 +- src/pages/gridex/buy-gridex/index.tsx | 27 ++++---- 4 files changed, 57 insertions(+), 39 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 58312c605b..00ec27d3b0 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -23,12 +23,13 @@ interface CurrencyInputPanelProps { showMaxButton: boolean label?: string onCurrencySelect?: (currency: Currency) => void + onCurrencyBSelect?: (currency: Currency) => void currency?: Currency | null + currencyB?: Currency | null disableCurrencySelect?: boolean hideBalance?: boolean pair?: Pair | null hideInput?: boolean - otherCurrency?: Currency | null fiatValue?: CurrencyAmount | null priceImpact?: Percent id: string @@ -46,9 +47,10 @@ export default function BuyRobotsPanel({ showMaxButton, label = 'Input', onCurrencySelect, + onCurrencyBSelect, currency, + currencyB, disableCurrencySelect = false, - otherCurrency, id, showCommonBases, renderBalance, @@ -64,13 +66,17 @@ export default function BuyRobotsPanel({ const { i18n } = useLingui() const [modalOpen, setModalOpen] = useState(false) const { account } = useActiveWeb3React() + const [currencySelector, setCurrencySelector] = useState('') const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) - const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, otherCurrency ?? undefined) + const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) const handleDismissSearch = useCallback(() => { setModalOpen(false) }, [setModalOpen]) + console.log("currencyA", currency); + console.log("currencyB", currencyB); + return (
@@ -81,7 +87,8 @@ export default function BuyRobotsPanel({ !!currency ? 'text-primary' : 'text-high-emphesis', 'open-currency-select-button h-full outline-none select-none cursor-pointer border-none text-xl font-medium items-center' )} - onClick={() => { + onClick={() => { + setCurrencySelector('A') if (onCurrencySelect) { setModalOpen(true) } @@ -138,19 +145,20 @@ export default function BuyRobotsPanel({
- {!disableCurrencySelect && onCurrencySelect && ( + { + currencySelector == 'A' ? ( - )} + + ) + : + ( + + ) + }
) -} +} \ No newline at end of file diff --git a/src/components/Header/index.tsx b/src/components/Header/index.tsx index ddb901da73..612f99d5c6 100644 --- a/src/components/Header/index.tsx +++ b/src/components/Header/index.tsx @@ -133,7 +133,7 @@ function AppBar(): JSX.Element { id={`gridex-nav-link`} className="p-2 text-baseline text-primary hover:text-high-emphesis focus:text-high-emphesis md:p-3 whitespace-nowrap" > - {i18n._(t`Gridex`)} NEW + {i18n._(t`Tango CMM`)} NEW )} diff --git a/src/modals/SearchModal/CurrencySearchModal.tsx b/src/modals/SearchModal/CurrencySearchModal.tsx index f544005f0b..5cc7e73643 100644 --- a/src/modals/SearchModal/CurrencySearchModal.tsx +++ b/src/modals/SearchModal/CurrencySearchModal.tsx @@ -18,6 +18,7 @@ interface CurrencySearchModalProps { selectedCurrency?: Currency | null onCurrencySelect: (currency: Currency) => void otherSelectedCurrency?: Currency | null + onCurrencyBSelect?: Currency | null showCommonBases?: boolean currencyList?: string[] includeNativeCurrency?: boolean @@ -111,4 +112,4 @@ function CurrencySearchModal({ CurrencySearchModal.whyDidYouRender = true -export default CurrencySearchModal +export default CurrencySearchModal \ No newline at end of file diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index ebd13ef565..35210ec9c7 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -14,14 +14,14 @@ import BuyRobotsPanel from "../../../components/BuyRobotsPanel" export default function BuyGridex() { const [currenciesSelected, setCurrenciesSelected] = useState(null); + const handleCurrencyASelect = (currencyA: Currency) => { setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) } - const handleCurrencyBSelect = (currencyB: Currency) => { - console.log(currenciesSelected) + const handleCurrencyBSelect = (currencyB: Currency) => { setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) } - + const router = useRouter() const tokens = router.query.tokens const [currencyIdA, currencyIdB] = (tokens as string[]) || [undefined, undefined] @@ -47,8 +47,6 @@ export default function BuyGridex() { const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) - - // get the max amounts user can add const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( (accumulator, field) => { @@ -69,7 +67,8 @@ export default function BuyGridex() { {} ) - + // console.log(maxAmounts); + return (<> @@ -84,27 +83,23 @@ export default function BuyGridex() { - { - onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') }} onCurrencySelect={handleCurrencyASelect} + onCurrencyBSelect={handleCurrencyBSelect} currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} // onOtherCurrencySelect={handleCurrencyBSelect} - otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} showCommonBases - /> - - - - From 275d5284326c0fa2f44f7ef5efca298477910f64 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 5 Oct 2022 20:00:01 -0300 Subject: [PATCH 11/83] feat: balance detector --- src/components/BuyRobotsPanel/index.tsx | 15 ++++++--------- src/pages/gridex/buy-gridex/index.tsx | 6 ++---- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 00ec27d3b0..e4c52ab06d 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -68,15 +68,12 @@ export default function BuyRobotsPanel({ const { account } = useActiveWeb3React() const [currencySelector, setCurrencySelector] = useState('') const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) - const selectedOtherCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) + const selectedCurrencyBBalance = useCurrencyBalance(account ?? undefined, currencyB ?? undefined) const handleDismissSearch = useCallback(() => { setModalOpen(false) }, [setModalOpen]) - console.log("currencyA", currency); - console.log("currencyB", currencyB); - return (
@@ -226,17 +223,17 @@ export default function BuyRobotsPanel({ }} readOnly={readOnly} /> - {!hideBalance && currency && selectedOtherCurrencyBalance ? ( + {!hideBalance && currency && selectedCurrencyBBalance ? (
- {/*
+
{renderBalance ? ( - renderBalance(selectedOtherCurrencyBalance) + renderBalance(selectedCurrencyBBalance) ) : ( <> - {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedOtherCurrencyBalance, 4)} {currency.symbol} + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} )} -
*/} +
) : null} diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index 35210ec9c7..bc8e499a6f 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -42,8 +42,7 @@ export default function BuyGridex() { liquidityMinted, poolTokenPercentage, error, - } = useDerivedMintInfo(currencyA ?? undefined, currencyB ?? undefined) - + } = useDerivedMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) @@ -67,8 +66,7 @@ export default function BuyGridex() { {} ) - // console.log(maxAmounts); - + // console.log(currenciesSelected.currencyB); return (<> From 61b7d6d5543766c1e3649a43b0cc22d3c434e43a Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 5 Oct 2022 20:59:50 -0300 Subject: [PATCH 12/83] feat: max button now working --- src/components/BuyRobotsPanel/index.tsx | 9 +++++---- src/pages/gridex/buy-gridex/index.tsx | 9 +++++++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index e4c52ab06d..5f190488f9 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -114,7 +114,7 @@ export default function BuyRobotsPanel({ ) : (
- {label &&
{label}
} + {"Stock" &&
Stock
}
{(currency && currency.symbol && currency.symbol.length > 20 @@ -206,7 +206,7 @@ export default function BuyRobotsPanel({ )} > <> - { ( + { showMaxButton && (
diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index bc8e499a6f..08dbe4000d 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -46,6 +46,11 @@ export default function BuyGridex() { const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) + const formattedAmounts = { + [independentField]: typedValue, + [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', + } + // get the max amounts user can add const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( (accumulator, field) => { @@ -66,7 +71,7 @@ export default function BuyGridex() { {} ) - // console.log(currenciesSelected.currencyB); + console.log(maxAmounts[Field.CURRENCY_B]?.toExact() ?? ''); return (<> @@ -82,13 +87,13 @@ export default function BuyGridex() { { onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') }} + value={formattedAmounts[Field.CURRENCY_B]} onCurrencySelect={handleCurrencyASelect} onCurrencyBSelect={handleCurrencyBSelect} currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} From e5902a24589648142e1b9d15641c16f0f5c69f2f Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Wed, 5 Oct 2022 23:23:14 -0300 Subject: [PATCH 13/83] feat: robots panel style fix --- src/components/BuyRobotsPanel/index.tsx | 14 +++++++------- src/pages/gridex/buy-gridex/index.tsx | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 1dee153e06..39e8959c91 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -79,7 +79,7 @@ export default function BuyRobotsPanel({ console.log("currencyB", currencyB); return ( -
+
@@ -227,11 +227,11 @@ export default function BuyRobotsPanel({ onUserInput(val) }} readOnly={readOnly} - className={`w-1/5 bg-transparent mr-6`} + className={`w-2/3 h-16 text-base bg-transparent `} /> - {/* {!hideBalance && currency && selectedCurrencyBBalance ? ( + {!hideBalance && currency && selectedCurrencyBBalance ? (
-
+
{renderBalance ? ( renderBalance(selectedCurrencyBBalance) ) : ( @@ -242,7 +242,7 @@ export default function BuyRobotsPanel({
- ) : null} */} + ) : null}
diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index 4bb602c7a9..918adc0e94 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -84,7 +84,7 @@ export default function BuyGridex() { /> - + Date: Wed, 5 Oct 2022 23:26:03 -0300 Subject: [PATCH 14/83] feat: gridex modal --- src/components/BuyRobotsPanel/index.tsx | 10 ++++++++++ src/modals/GridexModal/index.tsx | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/modals/GridexModal/index.tsx diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 1dee153e06..1c3c9c0260 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -16,6 +16,7 @@ import { useActiveWeb3React } from '../../hooks/useActiveWeb3React' import { useCurrencyBalance } from '../../state/wallet/hooks' import { useLingui } from '@lingui/react' import { Search as SearchIcon } from 'react-feather' +import GridexInfo from '../../modals/GridexModal' interface CurrencyInputPanelProps { value?: string @@ -65,8 +66,13 @@ export default function BuyRobotsPanel({ readOnly = false, }: CurrencyInputPanelProps) { const { i18n } = useLingui() + const [modalOpen, setModalOpen] = useState(false) + + const [gridexInfoOpen, setGridexInfoOpen] = useState(false) + const [currencySelector, setCurrencySelector] = useState('') + const { account } = useActiveWeb3React() const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currency ?? undefined) const selectedCurrencyBBalance = useCurrencyBalance(account ?? undefined, currencyB ?? undefined) @@ -255,6 +261,10 @@ export default function BuyRobotsPanel({ {/*{}*/}
+
+ + +
{ currencySelector == 'A' ? ( void; +} + +const GridexInfo: FC = ({ isOpen, setIsOpen }) => { + return ( + setIsOpen(false)} maxWidth={550}> + setIsOpen(false)} title="Concentrated Market Making" /> +
+

Tango CMM CMM (Concentrated Market Making), an alternative to UniswapV3. The market-making effect which can be achieved by UniswapV3, can also be approached by Tango CMM and merge the liquidity into SmartSwap.fi The general idea of Tango CMM is to use many small Bancor pools and let each pool take charge of a small price range. If the pools are dense enough, we can approximate any curve. Each small pool has its own fungible liquidity token, implemented in ERC1155. This is different from the NFT scheme used by UniswapV3. Fungible tokens are more flexible. For example, some rewards can be distributed to a small pool’s liquid providers as long as UniswapV2’s price falls into its price range.

+
+
+ ) +} + +export default GridexInfo From f479879ab2203b8653f6dd374250083760efc5b4 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Fri, 7 Oct 2022 19:11:58 -0300 Subject: [PATCH 15/83] feat: contracts abi --- src/components/BuyRobotsPanel/index.tsx | 3 --- src/modals/GridexModal/index.tsx | 2 +- src/pages/gridex/create-gridex/index.tsx | 26 +++++++++++++++++++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 981670ba33..9e09bc4434 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -81,9 +81,6 @@ export default function BuyRobotsPanel({ setModalOpen(false) }, [setModalOpen]) - console.log("currencyA", currency); - console.log("currencyB", currencyB); - return (
diff --git a/src/modals/GridexModal/index.tsx b/src/modals/GridexModal/index.tsx index 19e24f9928..8e836e129a 100644 --- a/src/modals/GridexModal/index.tsx +++ b/src/modals/GridexModal/index.tsx @@ -12,7 +12,7 @@ const GridexInfo: FC = ({ isOpen, setIsOpen }) => { setIsOpen(false)} maxWidth={550}> setIsOpen(false)} title="Concentrated Market Making" />
-

Tango CMM CMM (Concentrated Market Making), an alternative to UniswapV3. The market-making effect which can be achieved by UniswapV3, can also be approached by Tango CMM and merge the liquidity into SmartSwap.fi The general idea of Tango CMM is to use many small Bancor pools and let each pool take charge of a small price range. If the pools are dense enough, we can approximate any curve. Each small pool has its own fungible liquidity token, implemented in ERC1155. This is different from the NFT scheme used by UniswapV3. Fungible tokens are more flexible. For example, some rewards can be distributed to a small pool’s liquid providers as long as UniswapV2’s price falls into its price range.

+

Tango CMM (Concentrated Market Making), an alternative to UniswapV3. The market-making effect which can be achieved by UniswapV3, can also be approached by Tango CMM and merge the liquidity into SmartSwap.fi The general idea of Tango CMM is to use many small Bancor pools and let each pool take charge of a small price range. If the pools are dense enough, we can approximate any curve. Each small pool has its own fungible liquidity token, implemented in ERC1155. This is different from the NFT scheme used by UniswapV3. Fungible tokens are more flexible. For example, some rewards can be distributed to a small pool’s liquid providers as long as UniswapV2’s price falls into its price range.

) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 4bdf805ab0..b2137b0925 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -39,7 +39,7 @@ import { useCurrency } from '../../../hooks/Tokens' import { useIsSwapUnsupported } from '../../../hooks/useIsSwapUnsupported' import { useLingui } from '@lingui/react' import { useRouter } from 'next/router' -import { useRouterContract } from '../../../hooks' +import { useContract, useRouterContract } from '../../../hooks' import { useTransactionAdder } from '../../../state/transactions/hooks' import useTransactionDeadline from '../../../hooks/useTransactionDeadline' import { useWalletModalToggle } from '../../../state/application/hooks' @@ -102,6 +102,30 @@ export default function CreateGridexPage() { const [txHash, setTxHash] = useState('') + const SEP20ABI = [ + "function symbol() view returns (string)", + "function decimals() view returns (uint8)", + "function balanceOf(address account) external view returns (uint256)", + "function allowance(address owner, address spender) external view returns (uint256)", + "function approve(address spender, uint256 amount) external returns (bool)", + ] + + const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" + const FactoryAddr = "0xc6ec5d65cA33E7E3ac58A263177c9eEF8042fE17" + + const CCABI = [ + "function getAllRobots() view public returns (uint[] memory robotsIdAndInfo)", + "function createRobot(uint robotInfo) external payable", + "function deleteRobot(uint index, uint robotId) external", + "function sellToRobot(uint robotId, uint stockDelta) external payable", + "function buyFromRobot(uint robotId, uint moneyDelta) external payable", + ] + + const FactoryABI = [ + "function create(address stock, address money, address impl) external", + "function getAddress(address stock, address money, address impl) public view returns (address)", + ] + // get formatted amounts const formattedAmounts = { [independentField]: typedValue, From 49cbc25da01d70f2251ae4ff486b66274b774527 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Fri, 7 Oct 2022 20:32:53 -0300 Subject: [PATCH 16/83] feat: max price panel fix --- src/features/robots/RobotListItemDetails.tsx | 10 ++++++---- src/pages/gridex/create-gridex/index.tsx | 11 +++++++---- src/pages/gridex/gridex-list/index.tsx | 2 +- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 6d9f4adc7f..71754ed946 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -107,7 +107,8 @@ const RobotListItemDetails = ({ robot }) => {
- { robot.pending !== 0 ? ( + {/* robot.pending !== 0 ? */} + {(
- ) : ( + ) } + {/*: (
- ) - } + )*/} + ) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 4bdf805ab0..b0e3eb9ceb 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -233,6 +233,8 @@ export default function CreateGridexPage() { // { addIsUnsupported, isValid, approvaonFieldBInputlA, approvalB }, // approvalA === ApprovalState.APPROVED && approvalB === ApprovalState.APPROVED // ) + + return ( <> @@ -270,12 +272,12 @@ export default function CreateGridexPage() { )}
{ onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') }} + value={formattedAmounts[Field.CURRENCY_A]} onCurrencySelect={handleCurrencyASelect} showMaxButton={!atMaxAmounts[Field.CURRENCY_A]} currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} @@ -294,13 +296,14 @@ export default function CreateGridexPage() { { onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') }} + value={formattedAmounts[Field.CURRENCY_B]} showMaxButton={!atMaxAmounts[Field.CURRENCY_B]} currency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} id="add-liquidity-input-tokenb" @@ -322,8 +325,8 @@ export default function CreateGridexPage() { {
- - + +
} diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index d8a906c3e5..664344d2fc 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -861,7 +861,7 @@ export default function Gridex(): JSX.Element {
- + {/* */}
) From 786958a9cc561ff7e78c6aee52e6b9fc850333f8 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Sat, 8 Oct 2022 13:53:01 -0300 Subject: [PATCH 17/83] feat: mobile option added --- src/components/BuyRobotsPanel/index.tsx | 2 +- src/components/Header/index.tsx | 12 +++++++++++- src/pages/gridex/buy-gridex/index.tsx | 4 ++-- src/pages/gridex/create-gridex/index.tsx | 2 +- 4 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 9e09bc4434..2e4d05a199 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -82,7 +82,7 @@ export default function BuyRobotsPanel({ }, [setModalOpen]) return ( -
+
- ) : !account ? ( + ) + : !stock ? ( + + ) + : !money ? ( + + ) + : !parsedAmounts[Field.CURRENCY_A] && !parsedAmounts[Field.CURRENCY_B] ? ( + + ) + : !account ? ( - ) : ( - + ) : + ( + - )} + ) + }
- {!addIsUnsupported ? ( + {/* {!addIsUnsupported ? ( pair && !noLiquidity && pairState !== PairState.INVALID ? ( ) : null @@ -448,7 +471,7 @@ export default function CreateGridexPage() { show={addIsUnsupported} currencies={[currencies.CURRENCY_A, currencies.CURRENCY_B]} /> - )} + )} */}
From 1dd3f93f2160da094c7b6278b4b6369f236fd7c9 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sat, 8 Oct 2022 21:01:57 -0300 Subject: [PATCH 22/83] feat: changes in button state --- src/pages/gridex/create-gridex/index.tsx | 41 +++++++++++++++++++++--- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 48bcc75371..41e0ce9103 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -44,6 +44,7 @@ import { useTransactionAdder } from '../../../state/transactions/hooks' import useTransactionDeadline from '../../../hooks/useTransactionDeadline' import { useWalletModalToggle } from '../../../state/application/hooks' import PanelLimitPrice from '../../../components/PanelLimitPrice' +import { useCurrencyBalances } from '../../../state/wallet/hooks' const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) @@ -225,6 +226,26 @@ export default function CreateGridexPage() { [independentField]: typedValue } + const relevantTokenBalances = useCurrencyBalances(account ?? undefined, [ + stock ?? undefined, + money ?? undefined, + ]) + + const walletBalances = { + [Field.CURRENCY_A]: relevantTokenBalances[0], + [Field.CURRENCY_B]: relevantTokenBalances[1], + } + + const [balanceInStock, amountInStock] = [ + walletBalances[Field.CURRENCY_A], + parsedAmounts[Field.CURRENCY_A], + ] + + const [balanceInMoney, amountInMoney] = [ + walletBalances[Field.CURRENCY_B], + parsedAmounts[Field.CURRENCY_B], + ] + // get the max amounts user can add const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( (accumulator, field) => { @@ -423,7 +444,11 @@ export default function CreateGridexPage() { } - {!stock && !money ? ( + { + !account ? ( + + ) + : !stock && !money ? ( @@ -443,9 +468,17 @@ export default function CreateGridexPage() { {i18n._(t`Enter an Amount`)} ) - : !account ? ( - - ) : showStockApprove ? ( + : balanceInStock && amountInStock && balanceInStock.lessThan(amountInStock) ? ( + + ) + : balanceInMoney && amountInMoney && balanceInMoney.lessThan(amountInMoney) ? ( + + ) + : showStockApprove ? (
- {/* */} + {/* */}
) From 7f1972c3321754181ef20fe6ee22392d63676ddd Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Thu, 13 Oct 2022 14:21:52 -0300 Subject: [PATCH 24/83] feat: responsive desing --- src/components/BuyRobotsPanel/index.tsx | 6 +- src/features/onsen/GridexMenu.tsx | 14 +- src/features/robots/RobotList.tsx | 5 +- src/features/robots/RobotListItemDetails.tsx | 10 +- src/features/robots/RobotListItems.tsx | 10 +- src/pages/gridex/buy-gridex/index.tsx | 14 +- src/pages/gridex/buy-gridex/test.tsx | 359 ------------------- src/pages/gridex/create-gridex/index.tsx | 14 +- src/pages/gridex/gridex-list/index.tsx | 46 ++- 9 files changed, 78 insertions(+), 400 deletions(-) delete mode 100644 src/pages/gridex/buy-gridex/test.tsx diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index d2658283b9..a07abb4453 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -84,9 +84,9 @@ export default function BuyRobotsPanel({ return ( -
+
-
+
{/* Second input */} -
+
diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index 1c8f8e74e4..c9cbbd4836 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -24,7 +24,9 @@ const RobotListItems = ({ robot, ...rest }) => { const { i18n } = useLingui() return ( - + {({ open }) => ( <> { 'w-full px-4 py-6 text-left rounded cursor-pointer select-none bg-dark-900 text-primary text-sm md:text-lg' )} > -
-
+
+
@@ -81,7 +83,7 @@ const RobotListItems = ({ robot, ...rest }) => {
) : (
- {i18n._(t`Stake LP to robot`)} + {i18n._(t`Balance`)} {/* */}
)} diff --git a/src/pages/gridex/buy-gridex/index.tsx b/src/pages/gridex/buy-gridex/index.tsx index 4929516105..a6afbfea25 100644 --- a/src/pages/gridex/buy-gridex/index.tsx +++ b/src/pages/gridex/buy-gridex/index.tsx @@ -11,8 +11,12 @@ import { useRouter } from 'next/router' import { Field } from '../../../state/mint/actions' import { currencyId, maxAmountSpend } from '../../../functions/currency' import BuyRobotsPanel from "../../../components/BuyRobotsPanel" +import { i18n } from "@lingui/core" +import { t } from '@lingui/macro' +import { useLingui } from '@lingui/react' export default function BuyGridex() { + const { i18n } = useLingui() const [currenciesSelected, setCurrenciesSelected] = useState(null); const handleCurrencyASelect = (currencyA: Currency) => { @@ -76,17 +80,19 @@ export default function BuyGridex() { return (<> - Buy Gridex | Orders.Cash + Buy | Tango CMM - - + + + +

{i18n._(t`Search Your Tango CMM`)}

(false) - const [attemptingTxn, setAttemptingTxn] = useState(false) // clicked confirm - - // txn values - const deadline = useTransactionDeadline() // custom from users settings - - // const [allowedSlippage] = useUserSlippageTolerance(); // custom from users - - const allowedSlippage = useUserSlippageToleranceWithDefault(DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE) // custom from users - - const [txHash, setTxHash] = useState('') - - // get formatted amounts - const formattedAmounts = { - [independentField]: typedValue, - [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', - } - - // get the max amounts user can add - const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( - (accumulator, field) => { - return { - ...accumulator, - [field]: maxAmountSpend(currencyBalances[field]), - } - }, - {} - ) - - const atMaxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( - (accumulator, field) => { - return { - ...accumulator, - [field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0'), - } - }, - {} - ) - - const routerContract = useRouterContract() - - // check whether the user has approved the router on the tokens - const [approvalA, approveACallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_A], routerContract?.address) - const [approvalB, approveBCallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_B], routerContract?.address) - - const addTransaction = useTransactionAdder() - - async function onAdd() { - if (!chainId || !library || !account || !routerContract) return - - const { [Field.CURRENCY_A]: parsedAmountA, [Field.CURRENCY_B]: parsedAmountB } = parsedAmounts - - console.log({ parsedAmountA, parsedAmountB, currencyA, currencyB, deadline }) - - if (!parsedAmountA || !parsedAmountB || !currencyA || !currencyB || !deadline) { - return - } - - const amountsMin = { - [Field.CURRENCY_A]: calculateSlippageAmount(parsedAmountA, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], - [Field.CURRENCY_B]: calculateSlippageAmount(parsedAmountB, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], - } - - let estimate, - method: (...args: any) => Promise, - args: Array, - value: BigNumber | null - if (currencyA.isNative || currencyB.isNative) { - const tokenBIsETH = currencyB.isNative - estimate = routerContract.estimateGas.addLiquidityETH - method = routerContract.addLiquidityETH - args = [ - (tokenBIsETH ? currencyA : currencyB)?.wrapped?.address ?? '', // token - (tokenBIsETH ? parsedAmountA : parsedAmountB).quotient.toString(), // token desired - amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min - amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min - account, - deadline.toHexString(), - ] - value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).quotient.toString()) - } else { - estimate = routerContract.estimateGas.addLiquidity - method = routerContract.addLiquidity - args = [ - currencyA?.wrapped?.address ?? '', - currencyB?.wrapped?.address ?? '', - parsedAmountA.quotient.toString(), - parsedAmountB.quotient.toString(), - amountsMin[Field.CURRENCY_A].toString(), - amountsMin[Field.CURRENCY_B].toString(), - account, - deadline.toHexString(), - ] - value = null - } - - setAttemptingTxn(true) - try { - const estimatedGasLimit = await estimate(...args, { - ...(value ? { value } : {}), - gasPrice: getGasPrice(), - }) - - const response = await method(...args, { - ...(value ? { value } : {}), - gasLimit: calculateGasMargin(estimatedGasLimit), - gasPrice: getGasPrice(), - }) - - setAttemptingTxn(false) - - addTransaction(response, { - summary: i18n._( - t`Add ${parsedAmounts[Field.CURRENCY_A]?.toSignificant(3)} ${ - currencies[Field.CURRENCY_A]?.symbol - } and ${parsedAmounts[Field.CURRENCY_B]?.toSignificant(3)} ${currencies[Field.CURRENCY_B]?.symbol}` - ), - }) - - setTxHash(response.hash) - } catch (error) { - setAttemptingTxn(false) - // we only care if the error is something _other_ than the user rejected the tx - if (error?.code !== 4001) { - console.error(error) - } - } - } - - const handleCurrencyASelect = (currencyA: Currency) => { - setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) - } - const handleCurrencyBSelect = (currencyB: Currency) => { - console.log(currenciesSelected) - setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) - } - - const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B) - - // console.log( - // { addIsUnsupported, isValid, approvaonFieldBInputlA, approvalB }, - // approvalA === ApprovalState.APPROVED && approvalB === ApprovalState.APPROVED - // ) - return ( - <> - - Create Gridex | Orders.Cash - - - - - - - -
-
- {pair && pairState !== PairState.INVALID && ( - - )} -
- { - onFieldAInput(maxAmounts[Field.CURRENCY_A]?.toExact() ?? '') - }} - onCurrencySelect={handleCurrencyASelect} - showMaxButton={!atMaxAmounts[Field.CURRENCY_A]} - currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} - id="add-liquidity-input-tokena" - showCommonBases - /> - - - - - - - - { - onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') - }} - showMaxButton={!atMaxAmounts[Field.CURRENCY_B]} - currency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - id="add-liquidity-input-tokenb" - showCommonBases - /> -
- - {currencies[Field.CURRENCY_A] && currencies[Field.CURRENCY_B] && pairState !== PairState.INVALID && ( -
- -
- )} - - { -
- - -
- - } - - {addIsUnsupported ? ( - - ) : !account ? ( - - ) : ( - - )} -
- - {!addIsUnsupported ? ( - pair && !noLiquidity && pairState !== PairState.INVALID ? ( - - ) : null - ) : ( - - )} -
-
-
- - ) -} diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index dee967f24d..5c995473dc 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -169,8 +169,8 @@ export default function CreateGridexPage() { const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING - // console.log('parsedAmounts A', parsedAmounts[Field.CURRENCY_A]); - // console.log('stockApprovalState:', stockApprovalState); + console.log('parsedAmounts A', parsedAmounts[Field.CURRENCY_A]); + console.log('stockApprovalState:', stockApprovalState); // to create the robot factoryContract.create(stockAddr, moneyAddr, ImplAddr) @@ -371,15 +371,17 @@ export default function CreateGridexPage() { console.log('parsedAmounts A', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4)) console.log('parsedAmounts B', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4)) + + console.log(formattedAmounts) return ( <> - Create Gridex | Orders.Cash + Create | Tango CMM @@ -387,7 +389,7 @@ export default function CreateGridexPage() {
- {i18n._(t`View Your Gridex`)} + {i18n._(t`View Your Tango CMMs`)} - {i18n._(t`Create Gridex`)} + {i18n._(t`Create Tango CMM`)} ) } diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 5ec00a7b30..d1c3dab310 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -46,6 +46,7 @@ import RobotList from '../../../features/robots/RobotList' import Button from '../../../components/Button' import NavLink from '../../../components/NavLink' import GridexMenu from '../../../features/onsen/GridexMenu' +import { isMobile } from 'react-device-detect' function getTokensSorted(pool, pair) { if (pool.token0 == pair.token0.address && pool.token1 == pair.token1.address) { @@ -800,7 +801,7 @@ export default function Gridex(): JSX.Element { const optionsMenu = [ { href: `/${basePath}`, - label: 'Your Gridex', + label: 'Your Tango CMMs', exact: true }, { @@ -808,13 +809,13 @@ export default function Gridex(): JSX.Element { }, { href: `/${basePath}/on-Sale`, - label: 'Gridex on Sale' + label: 'Tango CMMs on Sale' },{ divider: true }, { href: `/gridex/buy-gridex`, - label: 'Buy Gridex', + label: 'Buy Tango CMMs', exact: true } ] @@ -826,19 +827,20 @@ export default function Gridex(): JSX.Element { maxWidth="7xl" > - Gridex | Orders.Cash + Tango CMM | Tango
+ {!isMobile ?
+ : + <> +
+ +
+ + + + + }
- Gridex{' '} + Tango CMM list{' '}
- {/* */} +
) From ca8a6ab1ab8433f8a813b8afa93c823341494aef Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Thu, 13 Oct 2022 14:51:31 -0300 Subject: [PATCH 25/83] feat: unnecesary filters removed --- src/pages/gridex/gridex-list/index.tsx | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 5ec00a7b30..70c5e8a5e4 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -762,15 +762,8 @@ export default function Gridex(): JSX.Element { } const FILTER = { - all: (farm) => farm.allocPoint !== 0, - portfolio: (farm) => farm.pending !== 0, - past: (farm) => farm.allocPoint === 0, - - // sushi: (farm) => farm.pair.type === PairType.SWAP && farm.allocPoint !== '0', - // kashi: (farm) => farm.pair.type === PairType.KASHI && farm.allocPoint !== '0', - // '2x': (farm) => (farm.chef === Chef.MASTERCHEF_V2) && farm.allocPoint !== '0', - - '2x': (farm) => farm.chef === Chef.MASTERCHEF_V2 && farm.rewards.length > 1 && farm.allocPoint !== '0', + buy: (farm) => farm.allocPoint !== 0, // buscar alguna estadistica que sea unica de los gridex activos y ponerlo aca + portfolio: (farm) => farm.pending !== 0, // buscar alguna estadistica que sea unica de los gridex propios y ponerlo aca } const data = farms From 1ef7251b19104959785961c894cd0673b0fbf163 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Thu, 13 Oct 2022 14:55:18 -0300 Subject: [PATCH 26/83] feat: tag names CMM --- src/features/onsen/GridexMenu.tsx | 10 +++++----- src/pages/gridex/create-gridex/index.tsx | 2 +- src/pages/gridex/gridex-list/index.tsx | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx index 64f4485b36..42e7dc2fa1 100644 --- a/src/features/onsen/GridexMenu.tsx +++ b/src/features/onsen/GridexMenu.tsx @@ -11,7 +11,7 @@ const basePath = 'gridex/gridex-list' const defaultOptions = [ { href: `/${basePath}`, - label: 'Your Tango CMMs', + label: 'Your Tango CMM', exact: true }, { @@ -43,7 +43,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { activeClassName="font-bold bg-transparent border rounded text-high-emphesis border-transparent border-gradient-r-blue-pink-dark-900" >
- Your Tango CMMs + Your Tango CMM
) : ( @@ -51,7 +51,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { className="striped-background text-secondary flex items-center justify-between px-2 py-3 md:px-4 md:py-6 text-base font-bold border border-transparent rounded cursor-pointer bg-dark-900 hover:bg-dark-800" onClick={toggleWalletModal} > - Your Tango CMMs + Your Tango CMM )} { activeClassName="bg-transparent border rounded text-high-emphesis border-transparent border-gradient-r-blue-pink-dark-900" > - Tango CMMs on Sale + Tango CMM on Sale @@ -71,7 +71,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { activeClassName="font-bold bg-transparent border rounded text-high-emphesis border-transparent border-gradient-r-blue-pink-dark-900" > - {i18n._(t`Buy Tango CMMs`)} + {i18n._(t`Buy Tango CMM`)} {/* - {i18n._(t`View Your Tango CMMs`)} + {i18n._(t`View Your Tango CMM`)} Date: Thu, 13 Oct 2022 19:07:32 -0300 Subject: [PATCH 27/83] feat: max button now working --- src/pages/gridex/create-gridex/index.tsx | 71 ++++------ src/state/mint/hooks.ts | 164 +++++++++++++++++++++++ 2 files changed, 187 insertions(+), 48 deletions(-) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 5c995473dc..ef8efe5692 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -1,13 +1,13 @@ import { ApprovalState, useApproveCallback } from '../../../hooks/useApproveCallback' import { AutoRow, RowBetween } from '../../../components/Row' import Button, { ButtonError } from '../../../components/Button' -import { Currency, CurrencyAmount, Percent, WNATIVE, currencyEquals } from '@tangoswapcash/sdk' +import { Currency, CurrencyAmount, Percent, WNATIVE, currencyEquals, SmartBCH, Token } from '@tangoswapcash/sdk' import { ONE_BIPS, ZERO_PERCENT } from '../../../constants' import React, { useCallback, useEffect, useState } from 'react' import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' import { calculateGasMargin, calculateSlippageAmount, getGasPrice } from '../../../functions/trade' import { currencyId, maxAmountSpend } from '../../../functions/currency' -import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' +import { useDerivedMintInfo, useGridexMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' import { useExpertModeManager, useUserSlippageToleranceWithDefault } from '../../../state/user/hooks' import Alert from '../../../components/Alert' @@ -46,6 +46,7 @@ import { useWalletModalToggle } from '../../../state/application/hooks' import PanelLimitPrice from '../../../components/PanelLimitPrice' import { useCurrencyBalances } from '../../../state/wallet/hooks' import { formatCurrencyAmount } from '../../../functions' +import { WrappedTokenInfo } from '../../../state/lists/wrappedTokenInfo' const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) @@ -84,7 +85,7 @@ export default function CreateGridexPage() { liquidityMinted, poolTokenPercentage, error, - } = useDerivedMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) + } = useGridexMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) @@ -169,9 +170,6 @@ export default function CreateGridexPage() { const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING - console.log('parsedAmounts A', parsedAmounts[Field.CURRENCY_A]); - console.log('stockApprovalState:', stockApprovalState); - // to create the robot factoryContract.create(stockAddr, moneyAddr, ImplAddr) // async function checkAllowanceAndBalance(contract, symbol, myAddr, amount, decimals) { @@ -358,13 +356,14 @@ export default function CreateGridexPage() { } } } - + const handleCurrencyASelect = (currencyA: Currency) => { setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) } const handleCurrencyBSelect = (currencyB: Currency) => { setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) } + const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B) @@ -372,7 +371,7 @@ export default function CreateGridexPage() { console.log('parsedAmounts A', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4)) console.log('parsedAmounts B', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4)) - + console.log(formattedAmounts) return ( <> @@ -453,42 +452,19 @@ export default function CreateGridexPage() {
} - + { !account ? ( ) - : !stock && !money ? ( - - ) - : !stock ? ( + : + error ? ( - ) - : !money ? ( - - ) - : !parsedAmounts[Field.CURRENCY_A] && !parsedAmounts[Field.CURRENCY_B] ? ( - ) - : balanceInStock && amountInStock && balanceInStock.lessThan(amountInStock) ? ( - - ) - : balanceInMoney && amountInMoney && balanceInMoney.lessThan(amountInMoney) ? ( - - ) - : showStockApprove ? ( + : + showStockApprove ? ( ) : + showMoneyApprove ? ( + + ) + : (
- - {/* {!addIsUnsupported ? ( - pair && !noLiquidity && pairState !== PairState.INVALID ? ( - - ) : null - ) : ( - - )} */}
diff --git a/src/state/mint/hooks.ts b/src/state/mint/hooks.ts index 59aa2cab65..b3fdea0169 100644 --- a/src/state/mint/hooks.ts +++ b/src/state/mint/hooks.ts @@ -226,3 +226,167 @@ export function useDerivedMintInfo( error, } } + +export function useGridexMintInfo( + currencyA: Currency | undefined, + currencyB: Currency | undefined +): { + dependentField: Field + currencies: { [field in Field]?: Currency } + pair?: Pair | null + pairState: PairState + currencyBalances: { [field in Field]?: CurrencyAmount } + parsedAmounts: { [field in Field]?: CurrencyAmount } + price?: Price + noLiquidity?: boolean + liquidityMinted?: CurrencyAmount + poolTokenPercentage?: Percent + error?: string +} { + const { i18n } = useLingui() + const { account } = useActiveWeb3React() + + const { independentField, typedValue, otherTypedValue } = useMintState() + + const dependentField = independentField === Field.CURRENCY_A ? Field.CURRENCY_B : Field.CURRENCY_A + + // tokens + const currencies: { [field in Field]?: Currency } = useMemo( + () => ({ + [Field.CURRENCY_A]: currencyA ?? undefined, + [Field.CURRENCY_B]: currencyB ?? undefined, + }), + [currencyA, currencyB] + ) + + // pair + const [pairState, pair] = useV2Pair(currencies[Field.CURRENCY_A], currencies[Field.CURRENCY_B]) + const totalSupply = useTotalSupply(pair?.liquidityToken) + + const noLiquidity: boolean = true + + // balances + const balances = useCurrencyBalances(account ?? undefined, [ + currencies[Field.CURRENCY_A], + currencies[Field.CURRENCY_B], + ]) + const currencyBalances: { [field in Field]?: CurrencyAmount } = { + [Field.CURRENCY_A]: balances[0], + [Field.CURRENCY_B]: balances[1], + } + + // amounts + const independentAmount: CurrencyAmount | undefined = tryParseAmount( + typedValue, + currencies[independentField] + ) + const dependentAmount: CurrencyAmount | undefined = useMemo(() => { + if (noLiquidity) { + if (otherTypedValue && currencies[dependentField]) { + return tryParseAmount(otherTypedValue, currencies[dependentField]) + } + return undefined + } else if (independentAmount) { + // we wrap the currencies just to get the price in terms of the other token + const wrappedIndependentAmount = independentAmount?.wrapped + const [tokenA, tokenB] = [currencyA?.wrapped, currencyB?.wrapped] + if (tokenA && tokenB && wrappedIndependentAmount && pair) { + const dependentCurrency = dependentField === Field.CURRENCY_B ? currencyB : currencyA + const dependentTokenAmount = + dependentField === Field.CURRENCY_B + ? pair.priceOf(tokenA).quote(wrappedIndependentAmount) + : pair.priceOf(tokenB).quote(wrappedIndependentAmount) + return dependentCurrency?.isNative + ? CurrencyAmount.fromRawAmount(dependentCurrency, dependentTokenAmount.quotient) + : dependentTokenAmount + } + return undefined + } else { + return undefined + } + }, [noLiquidity, otherTypedValue, currencies, dependentField, independentAmount, currencyA, currencyB, pair]) + + const parsedAmounts: { + [field in Field]: CurrencyAmount | undefined + } = useMemo(() => { + return { + [Field.CURRENCY_A]: independentField === Field.CURRENCY_A ? independentAmount : dependentAmount, + [Field.CURRENCY_B]: independentField === Field.CURRENCY_A ? dependentAmount : independentAmount, + } + }, [dependentAmount, independentAmount, independentField]) + + const price = useMemo(() => { + if (noLiquidity) { + const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts + if (currencyAAmount?.greaterThan(0) && currencyBAmount?.greaterThan(0)) { + const value = currencyBAmount.divide(currencyAAmount) + return new Price(currencyAAmount.currency, currencyBAmount.currency, value.denominator, value.numerator) + } + return undefined + } else { + const wrappedCurrencyA = currencyA?.wrapped + return pair && wrappedCurrencyA ? pair.priceOf(wrappedCurrencyA) : undefined + } + }, [currencyA, noLiquidity, pair, parsedAmounts]) + + // liquidity minted + const liquidityMinted = useMemo(() => { + const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts + const [tokenAmountA, tokenAmountB] = [currencyAAmount?.wrapped, currencyBAmount?.wrapped] + if (pair && totalSupply && tokenAmountA && tokenAmountB) { + try { + return pair.getLiquidityMinted(totalSupply, tokenAmountA, tokenAmountB) + } catch (error) { + console.error(error) + return undefined + } + } else { + return undefined + } + }, [parsedAmounts, pair, totalSupply]) + + const poolTokenPercentage = useMemo(() => { + if (liquidityMinted && totalSupply) { + return new Percent(liquidityMinted.quotient, totalSupply.add(liquidityMinted).quotient) + } else { + return undefined + } + }, [liquidityMinted, totalSupply]) + + let error: string | undefined + if (!account) { + error = i18n._(t`Connect Wallet`) + } + + if (pairState === PairState.INVALID) { + error = error ?? i18n._(t`Invalid pair`) + } + + if (!parsedAmounts[Field.CURRENCY_A] || !parsedAmounts[Field.CURRENCY_B]) { + error = error ?? i18n._(t`Enter an amount`) + } + + const { [Field.CURRENCY_A]: currencyAAmount, [Field.CURRENCY_B]: currencyBAmount } = parsedAmounts + + if (currencyAAmount && currencyBalances?.[Field.CURRENCY_A]?.lessThan(currencyAAmount)) { + error = i18n._(t`Insufficient ${currencies[Field.CURRENCY_A]?.symbol} balance`) + } + + if (currencyBAmount && currencyBalances?.[Field.CURRENCY_B]?.lessThan(currencyBAmount)) { + error = i18n._(t`Insufficient ${currencies[Field.CURRENCY_B]?.symbol} balance`) + } + + return { + dependentField, + currencies, + pair, + pairState, + currencyBalances, + parsedAmounts, + price, + noLiquidity, + liquidityMinted, + poolTokenPercentage, + error, + } +} From 17415e32a395ae69e47efafc4b78c58990d0eb00 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Thu, 13 Oct 2022 20:51:06 -0300 Subject: [PATCH 28/83] feat: maxValue --- src/components/PanelLimitPrice/index.tsx | 6 ++++-- src/pages/gridex/create-gridex/index.tsx | 24 ++++++++++++++++-------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/src/components/PanelLimitPrice/index.tsx b/src/components/PanelLimitPrice/index.tsx index cda47e1002..29ff111725 100644 --- a/src/components/PanelLimitPrice/index.tsx +++ b/src/components/PanelLimitPrice/index.tsx @@ -1,11 +1,13 @@ -import React, { useState } from 'react' +import React, { useState, useRef } from 'react' import { classNames, escapeRegExp } from '../../functions' import Input from '../Input' -const PanelLimitPrice = ({label, currencyA, currencyB}) => { +const PanelLimitPrice = ({label, currencyA, currencyB, caca}) => { const [value, setValue] = useState('') + caca(value) + const handleValue = (e) => { setValue(e.target.value) } diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index e016176b02..b4072d1d41 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -3,7 +3,7 @@ import { AutoRow, RowBetween } from '../../../components/Row' import Button, { ButtonError } from '../../../components/Button' import { Currency, CurrencyAmount, Percent, WNATIVE, currencyEquals, SmartBCH, Token } from '@tangoswapcash/sdk' import { ONE_BIPS, ZERO_PERCENT } from '../../../constants' -import React, { useCallback, useEffect, useState } from 'react' +import React, { useCallback, useEffect, useRef, useState, useMemo } from 'react' import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' import { calculateGasMargin, calculateSlippageAmount, getGasPrice } from '../../../functions/trade' import { currencyId, maxAmountSpend } from '../../../functions/currency' @@ -47,6 +47,7 @@ import PanelLimitPrice from '../../../components/PanelLimitPrice' import { useCurrencyBalances } from '../../../state/wallet/hooks' import { formatCurrencyAmount } from '../../../functions' import { WrappedTokenInfo } from '../../../state/lists/wrappedTokenInfo' +import { ethers } from 'ethers' const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) @@ -62,6 +63,14 @@ export default function CreateGridexPage() { const [currenciesSelected, setCurrenciesSelected] = useState(null) + const [minValue, setMinValue] = useState() + const teta = (value) => useMemo(() => { + setMinValue(value) + console.log('value:', value); + }, + [value] + ) + const oneCurrencyIsWETH = Boolean( chainId && ((currencyA && currencyEquals(currencyA, WNATIVE[chainId])) || @@ -370,8 +379,7 @@ export default function CreateGridexPage() { console.log('parsedAmounts A', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4)) console.log('parsedAmounts B', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4)) - - + console.log(formattedAmounts) return ( <> @@ -447,10 +455,9 @@ export default function CreateGridexPage() {
{
- - + +
- } { @@ -472,11 +479,12 @@ export default function CreateGridexPage() { i18n._(t`Approve ${stock.symbol}`) // ver como se usa useApproveSep206Callback )} - ) : + ) + : showMoneyApprove ? (
{ // replace commas with periods, because uniswap exclusively uses period as the decimal separator enforcer(event.target.value.replace(/,/g, '.')) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index b4072d1d41..faf4ca8ba6 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -9,7 +9,6 @@ import { calculateGasMargin, calculateSlippageAmount, getGasPrice } from '../../ import { currencyId, maxAmountSpend } from '../../../functions/currency' import { useDerivedMintInfo, useGridexMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' import { useExpertModeManager, useUserSlippageToleranceWithDefault } from '../../../state/user/hooks' - import Alert from '../../../components/Alert' import { AutoColumn } from '../../../components/Column' import { BigNumber } from '@ethersproject/bignumber' @@ -23,15 +22,9 @@ import DoubleGlowShadow from '../../../components/DoubleGlowShadow' import ExchangeHeader from '../../../features/trade/Header' import { Field } from '../../../state/mint/actions' import Head from 'next/head' -import LiquidityHeader from '../../../features/exchange-v1/liquidity/LiquidityHeader' -import LiquidityPrice from '../../../features/exchange-v1/liquidity/LiquidityPrice' -import { MinimalPositionCard } from '../../../components/PositionCard' import NavLink from '../../../components/NavLink' -import { PairState } from '../../../hooks/useV2Pairs' import { Plus } from 'react-feather' import { TransactionResponse } from '@ethersproject/providers' -import Typography from '../../../components/Typography' -import UnsupportedCurrencyFooter from '../../../features/exchange-v1/swap/UnsupportedCurrencyFooter' import Web3Connect from '../../../components/Web3Connect' import { t } from '@lingui/macro' import { useActiveWeb3React } from '../../../hooks/useActiveWeb3React' @@ -45,9 +38,9 @@ import useTransactionDeadline from '../../../hooks/useTransactionDeadline' import { useWalletModalToggle } from '../../../state/application/hooks' import PanelLimitPrice from '../../../components/PanelLimitPrice' import { useCurrencyBalances } from '../../../state/wallet/hooks' -import { formatCurrencyAmount } from '../../../functions' -import { WrappedTokenInfo } from '../../../state/lists/wrappedTokenInfo' import { ethers } from 'ethers' +import { parseUnits } from '@ethersproject/units' +import { formatUnits } from '@ethersproject/units' const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) @@ -64,13 +57,22 @@ export default function CreateGridexPage() { const [currenciesSelected, setCurrenciesSelected] = useState(null) const [minValue, setMinValue] = useState() - const teta = (value) => useMemo(() => { + const [maxValue, setMaxValue] = useState() + + const minPriceValue = (value) => useMemo(() => { setMinValue(value) - console.log('value:', value); + console.log('minValue:', value); }, [value] ) + const maxPriceValue = (value) => useMemo(() => { + setMaxValue(value) + console.log('maxValue:', value); + }, + [value] + ) + const oneCurrencyIsWETH = Boolean( chainId && ((currencyA && currencyEquals(currencyA, WNATIVE[chainId])) || @@ -113,6 +115,23 @@ export default function CreateGridexPage() { const [txHash, setTxHash] = useState('') + function packPrice(price) { + var effBits = 1 + while(!price.mask(effBits).eq(price)) { + effBits += 1 + } + var twoPow24 = BigNumber.from(2).pow(24) + if(effBits <= 25) { + return price + } + var shift = effBits-25 + var shiftBN = BigNumber.from(2).pow(shift) + var low24 = price.div(shiftBN).sub(twoPow24) + var high8 = BigNumber.from(shift).add(1).mul(twoPow24) + return high8.add(low24) + } + + const SEP20ABI = [ "function symbol() view returns (string)", "function decimals() view returns (uint8)", @@ -140,9 +159,9 @@ export default function CreateGridexPage() { const stock = currenciesSelected?.currencyA const money = currenciesSelected?.currencyB - const stockContract = useContract(stock?.address, SEP20ABI, false) - const moneyContract = useContract(money?.address, SEP20ABI, false) - const factoryContract = useContract(FactoryAddr, FactoryABI, false) + const stockContract = useContract(stock?.address, SEP20ABI) + const moneyContract = useContract(money?.address, SEP20ABI) + const factoryContract = useContract(FactoryAddr, FactoryABI) const [marketAddress, setMarketAddress] = useState() factoryContract.getAddress(stock?.address, money?.address, ImplAddr).then(a => setMarketAddress(a)) @@ -154,83 +173,34 @@ export default function CreateGridexPage() { let stockSymbol = stockContract?.symbol() let stockDecimals = stockContract?.decimals() let stockAmount = stockContract?.balanceOf(account) - - const [stockApprovalState, stockApprove] = useApproveSep206Callback( - parsedAmounts[Field.CURRENCY_A], - marketAddress - ) - - const [moneyApprovalState, moneyApprove] = useApproveSep206Callback( - parsedAmounts[Field.CURRENCY_B], - marketAddress - ) - const showStockApprove = - chainId && - currenciesSelected?.currencyA && - parsedAmounts[Field.CURRENCY_A] && - (stockApprovalState === ApprovalState.NOT_APPROVED || stockApprovalState === ApprovalState.PENDING) + // to create a robot market factoryContract.create(stockAddr, moneyAddr, ImplAddr) - const showMoneyApprove = - chainId && - currenciesSelected?.currencyB && - parsedAmounts[Field.CURRENCY_B] && - (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) + const marketContract = useContract(marketAddress, CCABI) - const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING - - // to create the robot factoryContract.create(stockAddr, moneyAddr, ImplAddr) - - // async function checkAllowanceAndBalance(contract, symbol, myAddr, amount, decimals) { - // const allowanceBN = await contract.allowance(myAddr, await MarketAddress) - // const allowance = ethers.utils.formatUnits(allowanceBN, decimals)*1.0 - // // console.log(symbol, ', allowance:', allowance); - - // if(allowance < amount) { - // new Attention.Confirm({title: `Approve ${symbol}`, - // content: `You did not approve enough ${symbol} to continue.cash, do you want to approve now? After sending the approving transaction, you can retry.`, - // onConfirm(component) { - // const MaxAmount = ethers.utils.parseUnits('999999999') - // contract.approve(MarketAddress, MaxAmount) - // }, - // onCancel(component) {}}); - // return - // } - // const balanceBN = await contract.balanceOf(myAddr) - // const balance = ethers.utils.formatUnits(balanceBN, decimals)*1.0 - // if(balance < amount) { - // window.AlertDlg = new Attention.Alert({title: "Not Enough ${symbol}", - // content: `${amount} ${symbol} is needed, but you only have ${balance}`}); - // } - // } - - // async function CreateRobot() { - - // checkAllowanceAndBalance(stockContract, await stockSymbol, account, await stockAmount, await stockDecimals) - // checkAllowanceAndBalance(moneyContract, await moneySymbol, account, await moneyAmount, await moneyDecimals) - - // var stockAmountBN = ethers.utils.parseUnits(stockAmount, await stockDecimals) - // var moneyAmountBN = ethers.utils.parseUnits(moneyAmount, await moneyDecimals) - // var highPrice = packPrice(ethers.utils.parseUnits(document.getElementById("highPrice").value)) - // var lowPrice = packPrice(ethers.utils.parseUnits(document.getElementById("lowPrice").value)) - // var robotInfo = stockAmountBN.mul(ethers.BigNumber.from(2).pow(96)).add(moneyAmountBN) - // robotInfo = robotInfo.mul(ethers.BigNumber.from(2).pow(32)).add(highPrice) - // robotInfo = robotInfo.mul(ethers.BigNumber.from(2).pow(32)).add(lowPrice) - // // const provider = new ethers.providers.Web3Provider(window.ethereum); - // // const signer = provider.getSigner(); - // const marketContract = new ethers.Contract(MarketAddress, CCABI, provider).connect(signer); - - // let val = null; - // if (window.stockAddr == '0x0000000000000000000000000000000000002711') { - // val = {value: stockAmountBN}; - // } else if (window.moneyAddr == '0x0000000000000000000000000000000000002711') { - // val = {value: moneyAmountBN}; - // } - // console.log('val:', val); + async function CreateRobot() { + var stockAmountBN = parseUnits(stockAmount, await stockDecimals) + var moneyAmountBN = parseUnits(moneyAmount, await moneyDecimals) + var highPrice = packPrice(parseUnits(maxValue)) + var lowPrice = packPrice(parseUnits(minValue)) + var robotInfo = stockAmountBN.mul(BigNumber.from(2).pow(96)).add(moneyAmountBN) + robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(highPrice) + robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(lowPrice) + + let val = null; + if (stock?.address == '0x0000000000000000000000000000000000002711') { + val = {value: stockAmountBN}; + } else if (money?.address == '0x0000000000000000000000000000000000002711') { + val = {value: moneyAmountBN}; + } + console.log('val:', val); - // await marketContract.createRobot(robotInfo, val) - // } + await marketContract.createRobot(robotInfo, val) + } + async function createMarket() { + factoryContract.create(stock?.address, money?.address, ImplAddr) + } const formattedAmounts = { [independentField]: typedValue, @@ -278,93 +248,93 @@ export default function CreateGridexPage() { {} ) - const routerContract = useRouterContract() + // const routerContract = useRouterContract() // check whether the user has approved the router on the tokens - const [approvalA, approveACallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_A], routerContract?.address) - const [approvalB, approveBCallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_B], routerContract?.address) + // const [approvalA, approveACallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_A], routerContract?.address) + // const [approvalB, approveBCallback] = useApproveCallback(parsedAmounts[Field.CURRENCY_B], routerContract?.address) - const addTransaction = useTransactionAdder() + // const addTransaction = useTransactionAdder() - async function onAdd() { - if (!chainId || !library || !account || !routerContract) return + // async function onAdd() { + // if (!chainId || !library || !account || !routerContract) return - const { [Field.CURRENCY_A]: parsedAmountA, [Field.CURRENCY_B]: parsedAmountB } = parsedAmounts + // const { [Field.CURRENCY_A]: parsedAmountA, [Field.CURRENCY_B]: parsedAmountB } = parsedAmounts - if (!parsedAmountA || !parsedAmountB || !currencyA || !currencyB || !deadline) { - return - } + // if (!parsedAmountA || !parsedAmountB || !currencyA || !currencyB || !deadline) { + // return + // } - const amountsMin = { - [Field.CURRENCY_A]: calculateSlippageAmount(parsedAmountA, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], - [Field.CURRENCY_B]: calculateSlippageAmount(parsedAmountB, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], - } + // const amountsMin = { + // [Field.CURRENCY_A]: calculateSlippageAmount(parsedAmountA, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], + // [Field.CURRENCY_B]: calculateSlippageAmount(parsedAmountB, noLiquidity ? ZERO_PERCENT : allowedSlippage)[0], + // } - let estimate, - method: (...args: any) => Promise, - args: Array, - value: BigNumber | null - if (currencyA.isNative || currencyB.isNative) { - const tokenBIsETH = currencyB.isNative - estimate = routerContract.estimateGas.addLiquidityETH - method = routerContract.addLiquidityETH - args = [ - (tokenBIsETH ? currencyA : currencyB)?.wrapped?.address ?? '', // token - (tokenBIsETH ? parsedAmountA : parsedAmountB).quotient.toString(), // token desired - amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min - amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min - account, - deadline.toHexString(), - ] - value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).quotient.toString()) - } else { - estimate = routerContract.estimateGas.addLiquidity - method = routerContract.addLiquidity - args = [ - currencyA?.wrapped?.address ?? '', - currencyB?.wrapped?.address ?? '', - parsedAmountA.quotient.toString(), - parsedAmountB.quotient.toString(), - amountsMin[Field.CURRENCY_A].toString(), - amountsMin[Field.CURRENCY_B].toString(), - account, - deadline.toHexString(), - ] - value = null - } + // let estimate, + // method: (...args: any) => Promise, + // args: Array, + // value: BigNumber | null + // if (currencyA.isNative || currencyB.isNative) { + // const tokenBIsETH = currencyB.isNative + // estimate = routerContract.estimateGas.addLiquidityETH + // method = routerContract.addLiquidityETH + // args = [ + // (tokenBIsETH ? currencyA : currencyB)?.wrapped?.address ?? '', // token + // (tokenBIsETH ? parsedAmountA : parsedAmountB).quotient.toString(), // token desired + // amountsMin[tokenBIsETH ? Field.CURRENCY_A : Field.CURRENCY_B].toString(), // token min + // amountsMin[tokenBIsETH ? Field.CURRENCY_B : Field.CURRENCY_A].toString(), // eth min + // account, + // deadline.toHexString(), + // ] + // value = BigNumber.from((tokenBIsETH ? parsedAmountB : parsedAmountA).quotient.toString()) + // } else { + // estimate = routerContract.estimateGas.addLiquidity + // method = routerContract.addLiquidity + // args = [ + // currencyA?.wrapped?.address ?? '', + // currencyB?.wrapped?.address ?? '', + // parsedAmountA.quotient.toString(), + // parsedAmountB.quotient.toString(), + // amountsMin[Field.CURRENCY_A].toString(), + // amountsMin[Field.CURRENCY_B].toString(), + // account, + // deadline.toHexString(), + // ] + // value = null + // } - setAttemptingTxn(true) - try { - const estimatedGasLimit = await estimate(...args, { - ...(value ? { value } : {}), - gasPrice: getGasPrice(), - }) - - const response = await method(...args, { - ...(value ? { value } : {}), - gasLimit: calculateGasMargin(estimatedGasLimit), - gasPrice: getGasPrice(), - }) - - setAttemptingTxn(false) - - addTransaction(response, { - summary: i18n._( - t`Add ${parsedAmounts[Field.CURRENCY_A]?.toSignificant(3)} ${ - currencies[Field.CURRENCY_A]?.symbol - } and ${parsedAmounts[Field.CURRENCY_B]?.toSignificant(3)} ${currencies[Field.CURRENCY_B]?.symbol}` - ), - }) - - setTxHash(response.hash) - } catch (error) { - setAttemptingTxn(false) - // we only care if the error is something _other_ than the user rejected the tx - if (error?.code !== 4001) { - console.error(error) - } - } - } + // setAttemptingTxn(true) + // try { + // const estimatedGasLimit = await estimate(...args, { + // ...(value ? { value } : {}), + // gasPrice: getGasPrice(), + // }) + + // const response = await method(...args, { + // ...(value ? { value } : {}), + // gasLimit: calculateGasMargin(estimatedGasLimit), + // gasPrice: getGasPrice(), + // }) + + // setAttemptingTxn(false) + + // addTransaction(response, { + // summary: i18n._( + // t`Add ${parsedAmounts[Field.CURRENCY_A]?.toSignificant(3)} ${ + // currencies[Field.CURRENCY_A]?.symbol + // } and ${parsedAmounts[Field.CURRENCY_B]?.toSignificant(3)} ${currencies[Field.CURRENCY_B]?.symbol}` + // ), + // }) + + // setTxHash(response.hash) + // } catch (error) { + // setAttemptingTxn(false) + // // we only care if the error is something _other_ than the user rejected the tx + // if (error?.code !== 4001) { + // console.error(error) + // } + // } + // } const handleCurrencyASelect = (currencyA: Currency) => { setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) @@ -373,14 +343,31 @@ export default function CreateGridexPage() { setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) } + const [stockApprovalState, stockApprove] = useApproveSep206Callback( + parsedAmounts[Field.CURRENCY_A], + marketAddress + ) - const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B) - + const [moneyApprovalState, moneyApprove] = useApproveSep206Callback( + parsedAmounts[Field.CURRENCY_B], + marketAddress + ) + + const showStockApprove = + chainId && + currenciesSelected?.currencyA && + parsedAmounts[Field.CURRENCY_A] && + (stockApprovalState === ApprovalState.NOT_APPROVED || stockApprovalState === ApprovalState.PENDING) - console.log('parsedAmounts A', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4)) - console.log('parsedAmounts B', formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4)) + const showMoneyApprove = + chainId && + currenciesSelected?.currencyB && + parsedAmounts[Field.CURRENCY_B] && + (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) + + const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING + // const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B) - console.log(formattedAmounts) return ( <> @@ -455,8 +442,8 @@ export default function CreateGridexPage() {
{
- - + +
} @@ -476,7 +463,7 @@ export default function CreateGridexPage() { {stockApprovalState === ApprovalState.PENDING ? ( {i18n._(t`Approving ${stock.symbol}`)} ) : ( - i18n._(t`Approve ${stock.symbol}`) // ver como se usa useApproveSep206Callback + i18n._(t`Approve ${stock.symbol}`) )} ) @@ -486,7 +473,7 @@ export default function CreateGridexPage() { {moneyApprovalState === ApprovalState.PENDING ? ( {i18n._(t`Approving ${money.symbol}`)} ) : ( - i18n._(t`Approve ${money.symbol}`) // ver como se usa useApproveSep206Callback + i18n._(t`Approve ${money.symbol}`) )} ) From 9631eca10678bafbb2ed399c42f278cb8e332cca Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 17 Oct 2022 19:38:41 -0300 Subject: [PATCH 30/83] feat: contracts --- src/pages/gridex/create-gridex/index.tsx | 29 ++++++++++++++++-------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index faf4ca8ba6..b8f827d36d 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -41,6 +41,7 @@ import { useCurrencyBalances } from '../../../state/wallet/hooks' import { ethers } from 'ethers' import { parseUnits } from '@ethersproject/units' import { formatUnits } from '@ethersproject/units' +import { formatCurrencyAmount } from '../../../functions' const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) @@ -179,6 +180,8 @@ export default function CreateGridexPage() { const marketContract = useContract(marketAddress, CCABI) async function CreateRobot() { + const stockAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4) + const moneyAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4) var stockAmountBN = parseUnits(stockAmount, await stockDecimals) var moneyAmountBN = parseUnits(moneyAmount, await moneyDecimals) var highPrice = packPrice(parseUnits(maxValue)) @@ -187,15 +190,14 @@ export default function CreateGridexPage() { robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(highPrice) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(lowPrice) - let val = null; - if (stock?.address == '0x0000000000000000000000000000000000002711') { - val = {value: stockAmountBN}; - } else if (money?.address == '0x0000000000000000000000000000000000002711') { - val = {value: moneyAmountBN}; - } - console.log('val:', val); + // let val = null; + // if (stock?.address == '0x0000000000000000000000000000000000002711') { + // val = {value: stockAmountBN}; + // } else if (money?.address == '0x0000000000000000000000000000000000002711') { + // val = {value: moneyAmountBN}; + - await marketContract.createRobot(robotInfo, val) + await marketContract.createRobot(robotInfo) } async function createMarket() { @@ -366,7 +368,8 @@ export default function CreateGridexPage() { (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING - // const addIsUnsupported = useIsSwapUnsupported(currencies?.CURRENCY_A, currencies?.CURRENCY_B) + const haveMarketAddress = !marketAddress && currenciesSelected + console.log(haveMarketAddress); return ( <> @@ -458,6 +461,12 @@ export default function CreateGridexPage() { ) : + haveMarketAddress ? ( + + ) + : showStockApprove ? ( ) From 6bf96b98553c5a383b6d5f1a274fd37ae2d18bca Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Tue, 18 Oct 2022 19:34:23 -0300 Subject: [PATCH 31/83] feat: market address now working --- src/pages/gridex/create-gridex/index.tsx | 35 ++++++++++++++++-------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index b8f827d36d..39cdd2b7e0 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -60,6 +60,8 @@ export default function CreateGridexPage() { const [minValue, setMinValue] = useState() const [maxValue, setMaxValue] = useState() + const [haveMarketAddress, setHaveMarketAddress] = useState(false) + const minPriceValue = (value) => useMemo(() => { setMinValue(value) console.log('minValue:', value); @@ -190,20 +192,23 @@ export default function CreateGridexPage() { robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(highPrice) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(lowPrice) - // let val = null; - // if (stock?.address == '0x0000000000000000000000000000000000002711') { - // val = {value: stockAmountBN}; - // } else if (money?.address == '0x0000000000000000000000000000000000002711') { - // val = {value: moneyAmountBN}; - - await marketContract.createRobot(robotInfo) } async function createMarket() { - factoryContract.create(stock?.address, money?.address, ImplAddr) + await factoryContract.create(stock?.address, money?.address, ImplAddr) } + useEffect(() => { + const marketAddressCheck = async () => { + let provider = new ethers.providers.Web3Provider(window.ethereum) + let code = await provider.getCode(marketAddress) + code == "0x" ? setHaveMarketAddress(false) : setHaveMarketAddress(true) + } + marketAddressCheck() + }, [marketAddress]) + + const formattedAmounts = { [independentField]: typedValue, [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', @@ -354,6 +359,7 @@ export default function CreateGridexPage() { parsedAmounts[Field.CURRENCY_B], marketAddress ) + const showStockApprove = chainId && @@ -368,8 +374,9 @@ export default function CreateGridexPage() { (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING - const haveMarketAddress = !marketAddress && currenciesSelected - console.log(haveMarketAddress); + + const minValueFilled = minValue !== '' + const maxValueFilled = maxValue !== '' return ( <> @@ -461,7 +468,7 @@ export default function CreateGridexPage() { ) : - haveMarketAddress ? ( + !haveMarketAddress ? ( @@ -487,6 +494,12 @@ export default function CreateGridexPage() { ) : + !minValueFilled || !maxValueFilled ? ( + + ) + : (  ` + htmlStr += `Stock: ${robots[i].stockAmount} ` + htmlStr += `Money: ${robots[i].moneyAmount} ` + htmlStr += `HighPrice: ${robots[i].highPrice} ` + htmlStr += `LowPrice: ${robots[i].lowPrice}

` + } + document.getElementById("deleteDiv").innerHTML = htmlStr +} + export default function Gridex(): JSX.Element { const { i18n } = useLingui() const { chainId } = useActiveWeb3React() @@ -127,186 +222,6 @@ export default function Gridex(): JSX.Element { token0: FLEXUSD, token1: WBCH[ChainId.SMARTBCH], }, - '0x1A2bdFF5bA942bF20f0db7218cdE28D19aC8dD20': { - farmId: 4, - allocPoint: 14999999, - token0: new Token(ChainId.SMARTBCH, '0x98Dd7eC28FB43b3C4c770AE532417015fa939Dd3', 18, 'FLEX', 'FLEX Coin'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x5b860757a77c62Dca833542e8E4650AEE777a08F': { - farmId: 5, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x5fA664f69c2A4A3ec94FaC3cBf7049BD9CA73129', 18, 'MIST', 'MistToken'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xd12C1De8740406438eb84Dde44cd0839F48211aa': { - farmId: 6, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x77CB87b57F54667978Eb1B199b28a0db8C8E1c0B', 18, 'EBEN', 'Green Ben'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xa790208A8C49e586a3F2145aD2c9096d6072E1F3': { - farmId: 7, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0xc8E09AEdB3c949a875e1FD571dC4b3E48FB221f0', 18, 'MILK', 'Milk'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xF463db65674426A58E9C3fE557FaaE338026ef39': { - farmId: 8, - allocPoint: 0, - token0: new Token( - ChainId.SMARTBCH, - '0x675E1d6FcE8C7cC091aED06A68D079489450338a', - 18, - 'ARG', - 'Bitcoin Cash Argentina' - ), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xCFa5B1C5FaBF867842Ac3C25E729Fc3671d27c50': { - farmId: 9, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xf9185C281fE4C8af452244A65cE7317345352942': { - farmId: 10, - allocPoint: 1250000, - token0: new Token(ChainId.SMARTBCH, '0xe11829a7d5d8806bb36e118461a1012588fafd89', 18, 'SPICE', 'SPICE'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xBe0e246a87a3e9a2D2Db2efD384E0174F13E62b1': { - farmId: 11, - allocPoint: 4999999, - token0: new Token(ChainId.SMARTBCH, '0x0b00366fBF7037E9d75E4A569ab27dAB84759302', 18, 'LAW', 'LAWTOKEN'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x1946978E39E6105fEb2107D9c01197a962746bf5': { - farmId: 12, - allocPoint: 499999, - token0: new Token(ChainId.SMARTBCH, '0xff3ed63bf8bc9303ea0a7e1215ba2f82d569799e', 18, 'ORB', 'ORB'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x23e1E177aE511342fFc27F59da57685b3a0413bc': { - farmId: 13, - allocPoint: 4999999, - token0: new Token(ChainId.SMARTBCH, '0x265bD28d79400D55a1665707Fa14A72978FA6043', 2, 'CATS', 'CashCats'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x5340619781a8963377aFD76A6999edB6437e3B72': { - farmId: 14, - allocPoint: 2499999, - token0: new Token(ChainId.SMARTBCH, '0x6732E55Ac3ECa734F54C26Bd8DF4eED52Fb79a6E', 2, 'JOY', 'Joystick.club'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x91dde68D0C08e8620d77B8e7F1836aD4ec3CB33c': { - farmId: 15, - allocPoint: 2499999, - token0: new Token(ChainId.SMARTBCH, '0x7642Df81b5BEAeEb331cc5A104bd13Ba68c34B91', 2, 'CLY', 'Celery'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xa24e2a9a41020bD1EaD472aF07bCc74cd7fB85A4': { - farmId: 16, - allocPoint: 499999, - token0: new Token(ChainId.SMARTBCH, '0xca0235058985fcc1839e9e37c10900a73c126708', 7, 'DAO', 'DAO'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x0152F077D2808506FbF6B991b48D1e8DDCBF7107': { - farmId: 17, - allocPoint: 499999, - token0: new Token(ChainId.SMARTBCH, '0x3d13DaFcCA3a188DB340c81414239Bc2be312Ec9', 18, 'AXIEBCH', 'AxieBCH'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x9E59AAc21DaB7C89d0BDA99335386868539Af9B8': { - farmId: 18, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x0D8b355f9CEDeB612f2df4B39CdD87059A244567', 2, 'CANDYMAN', 'CandyMAN'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xD4625760E0B5D9a0f46cB95dDa9b660fd6Db610A': { - farmId: 19, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x225FCa2A940cd5B18DFb168cD9B7f921C63d7B6E', 18, 'FIRE', 'Incinerate'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xC28f5F07B733862f021f2266B99F5214c68E95d0': { - farmId: 20, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x7ebeadb95724a006afaf2f1f051b13f4ebebf711', 2, 'KITTEN', 'CashKitten'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x1CC824B67e694fd5e0cC7D55120355B1AE4B9c50': { - farmId: 21, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x9192940099fDB2338B928DE2cad9Cd1525fEa881', 18, 'BPAD', 'BCHPad'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xfe323f2898810E6C3c2c5A9E7dF78A116fFAD4fa': { - farmId: 22, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0xffa2394b61d3de16538a2bbf3491297cc5a7c79a', 18, 'UATX', 'UatX Token'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x365Ec450d670455b336b833Ca363d21b4de3B9E3': { - farmId: 23, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x4F1480ba79F7477230ec3b2eCc868E8221925072', 18, 'KONRA', 'Konra'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x7FbcD4B5b7838F3C22151d492cB7E30B28dED77a': { - farmId: 24, - allocPoint: 999999, - token0: new Token(ChainId.SMARTBCH, '0x98Ff640323C059d8C4CB846976973FEEB0E068aA', 18, 'XTANGO', 'TANGObar'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x0152E5F007D85aae58Eb7191Bd484f12F9c13052': { - farmId: 25, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x49F9ECF126B6dDF51C731614755508A4674bA7eD', 18, 'RMZ', 'Xolos'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xC073d247f8FdB539Bc6653b6bfFEF8c61092738F': { - farmId: 26, - allocPoint: 999999, - token0: new Token(ChainId.SMARTBCH, '0x98Dd7eC28FB43b3C4c770AE532417015fa939Dd3', 18, 'FLEX', 'FLEX Coin'), - token1: TANGO[ChainId.SMARTBCH], - }, - '0xcdb6081DCb9fd2b3d48927790DF7757E8d137fF4': { - farmId: 27, - allocPoint: 4499999, - token0: new Token(ChainId.SMARTBCH, '0x98Ff640323C059d8C4CB846976973FEEB0E068aA', 18, 'XTANGO', 'TANGObar'), - token1: FLEXUSD, - }, - '0xfa2A542B0BF8F5e92Af0D1045ebF0abBB0A6C093': { - farmId: 28, - allocPoint: 26999999, - token0: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x018005da1a5C886Fb48eB18Eda0849a26B99DA80': { - farmId: 29, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x77d4b6e44a53bbda9a1d156b32bb53a2d099e53d', 18, '1BCH', '1BCH'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0x864c0090D955D947D809CF315E17665Bf9e3b6aB': { - farmId: 30, - allocPoint: 0, - token0: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), - token1: TANGO[ChainId.SMARTBCH], - }, - '0x4509Ff66a56cB1b80a6184DB268AD9dFBB79DD53': { - farmId: 32, - allocPoint: 2499999, - token0: new Token(ChainId.SMARTBCH, '0xF05bD3d7709980f60CD5206BddFFA8553176dd29', 18, 'SIDX', 'SmartIndex'), - token1: WBCH[ChainId.SMARTBCH], - }, - '0xE7845D6df693BFD1b0b50AB2d17ac06964559c6b': { - farmId: 33, - allocPoint: 4999750, - token0: new Token(ChainId.SMARTBCH, '0xe1e655be6f50344e6dd708c27bd8d66492d6ecaf', 18, 'LAWUSD', 'lawUSD'), - token1: TANGO[ChainId.SMARTBCH], - }, }, [ChainId.SMARTBCH_AMBER]: { '0x07DE6fc05597E0E4c92C83637A8a0CA411f3a769': { @@ -359,93 +274,6 @@ export default function Gridex(): JSX.Element { rewardToken: new Token(ChainId.SMARTBCH, '0x49F9ECF126B6dDF51C731614755508A4674bA7eD', 18, 'RMZ', 'Xolos'), rewardPerSecond: '58330000000000', }, - '0xD513165b3bbC1Ca812Db7CBB60340DDf74903A1c': { - farmId: 3, - allocPoint: 15624, - token0: new Token(ChainId.SMARTBCH, '0xF2d4D9c65C2d1080ac9e1895F6a32045741831Cd', 2, 'HONK', 'Honk'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0x3f43FF8eF6715Eb6E76452a9d719f54eFa5372b1', - rewardToken: new Token(ChainId.SMARTBCH, '0xF2d4D9c65C2d1080ac9e1895F6a32045741831Cd', 2, 'HONK', 'Honk'), - rewardPerSecond: '2325', - }, - '0x864c0090D955D947D809CF315E17665Bf9e3b6aB': { - farmId: 4, - allocPoint: 14999748, - token0: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), - token1: TANGO[ChainId.SMARTBCH], - rewarderId: '0x3e9AFf4008F3D6E05697025acCb607021e36e1e6', - rewardToken: new Token(ChainId.SMARTBCH, '0x4b85a666dec7c959e88b97814e46113601b07e57', 18, 'GOC', 'GoCrypto'), - rewardPerSecond: '005787037000000000', - }, - '0x9E59AAc21DaB7C89d0BDA99335386868539Af9B8': { - farmId: 5, - allocPoint: 1, - token0: new Token(ChainId.SMARTBCH, '0x0D8b355f9CEDeB612f2df4B39CdD87059A244567', 2, 'CANDYMAN', 'CandyMAN'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0xDc7D5F633F5721fa3Ff2B73B9396F0eAcE58ec0F', - rewardToken: new Token( - ChainId.SMARTBCH, - '0x0D8b355f9CEDeB612f2df4B39CdD87059A244567', - 2, - 'CANDYMAN', - 'CandyMAN' - ), - rewardPerSecond: '01', - }, - '0x365Ec450d670455b336b833Ca363d21b4de3B9E3': { - farmId: 6, - allocPoint: 62499, - token0: new Token(ChainId.SMARTBCH, '0x4F1480ba79F7477230ec3b2eCc868E8221925072', 18, 'KONRA', 'Konra'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0x2F3056526014992b757a9F81D7B084e60a0Eb187', - rewardToken: new Token(ChainId.SMARTBCH, '0x4F1480ba79F7477230ec3b2eCc868E8221925072', 18, 'KONRA', 'Konra'), - rewardPerSecond: '000011580000000000', - }, - '0x5109aABC359c5267B6d470f43414319dd8a3C123': { - farmId: 7, - allocPoint: 15624, - token0: new Token(ChainId.SMARTBCH, '0x0cb20466c0dd6454acf50ec26f3042ccc6362fa0', 18, 'NARATH', 'Narath'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0x1d42B726E32f41102BC265d8a1cD5a1751e8deD9', - rewardToken: new Token(ChainId.SMARTBCH, '0x0cb20466c0dd6454acf50ec26f3042ccc6362fa0', 18, 'NARATH', 'Narath'), - rewardPerSecond: '925000000000000000000', - }, - '0x7B545548dabA183Fc779e656da09dF6bD2b94F88': { - farmId: 8, - allocPoint: 499998, - token0: new Token( - ChainId.SMARTBCH, - '0x4EA4A00E15B9E8FeE27eB6156a865525083e9F71', - 18, - 'Martin₿', - 'Africa Unite' - ), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0x6C54582E1F7E0602F526267BEB4b073E35eB46a4', - rewardToken: new Token( - ChainId.SMARTBCH, - '0x4EA4A00E15B9E8FeE27eB6156a865525083e9F71', - 18, - 'Martin₿', - 'Africa Unite' - ), - rewardPerSecond: '66979000000000000000000', - }, - '0x2a7c9D8E0E2286A596192C3C16Cc68979D331F29': { - farmId: 9, - allocPoint: 62499, - token0: new Token(ChainId.SMARTBCH, '0x387122d80A642581E5AD620696a37b98BB9272e7', 18, 'JOOST', 'Joost.energy'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0xA76F4318eDe44a205EAcFB5eF6EaF28b0A83AAb8', - rewardToken: new Token( - ChainId.SMARTBCH, - '0x387122d80A642581E5AD620696a37b98BB9272e7', - 18, - 'JOOST', - 'Joost.energy' - ), - rewardPerSecond: '800000000000000000', - }, }, [ChainId.SMARTBCH_AMBER]: { '0xCFa5B1C5FaBF867842Ac3C25E729Fc3671d27c50': { @@ -459,7 +287,7 @@ export default function Gridex(): JSX.Element { }, }, } - + const kashiPairs = [] // unused const swapPairs = [] const farms2 = useFarms() From 8e8308275661f4dbfe3b959e57c39ef7d66bcae5 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sun, 23 Oct 2022 20:06:22 -0300 Subject: [PATCH 33/83] feat: fix and changes in creat-gridex page --- src/pages/gridex/create-gridex/index.tsx | 115 +++++++++++++---------- 1 file changed, 65 insertions(+), 50 deletions(-) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 39f0dca286..1596a4f698 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -43,36 +43,51 @@ import { parseUnits } from '@ethersproject/units' import { formatUnits } from '@ethersproject/units' import { formatCurrencyAmount } from '../../../functions' -const DEFAULT_ADD_V2_SLIPPAGE_TOLERANCE = new Percent(50, 10_000) - export default function CreateGridexPage() { const { i18n } = useLingui() - const { account, chainId, library } = useActiveWeb3React() - const router = useRouter() - const tokens = router.query.tokens - const [currencyIdA, currencyIdB] = (tokens as string[]) || [undefined, undefined] - - const currencyA = useCurrency(currencyIdA) - const currencyB = useCurrency(currencyIdB) + const { account, chainId } = useActiveWeb3React() const [currenciesSelected, setCurrenciesSelected] = useState(null) const [minValue, setMinValue] = useState() const [maxValue, setMaxValue] = useState() - const [haveMarketAddress, setHaveMarketAddress] = useState(false) + const [foundMarketAddress, setFoundMarketAddress] = useState(true) + + const addTransaction = useTransactionAdder() - const minPriceValue = (value) => useMemo(() => { + function minPriceValue(value) { + useMemo(() => { setMinValue(value) }, [value] ) + } - const maxPriceValue = (value) => useMemo(() => { - setMaxValue(value) - }, - [value] - ) + function maxPriceValue(value) { + useMemo(() => { + setMaxValue(value) + }, + [value] + ) + } + + + function packPrice(price) { + var effBits = 1 + while(!price.mask(effBits).eq(price)) { + effBits += 1 + } + var twoPow24 = BigNumber.from(2).pow(24) + if(effBits <= 25) { + return price + } + var shift = effBits-25 + var shiftBN = BigNumber.from(2).pow(shift) + var low24 = price.div(shiftBN).sub(twoPow24) + var high8 = BigNumber.from(shift).add(1).mul(twoPow24) + return high8.add(low24) + } const [isExpertMode] = useExpertModeManager() // mint state @@ -92,67 +107,65 @@ export default function CreateGridexPage() { } = useGridexMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) - - function packPrice(price) { - var effBits = 1 - while(!price.mask(effBits).eq(price)) { - effBits += 1 - } - var twoPow24 = BigNumber.from(2).pow(24) - if(effBits <= 25) { - return price - } - var shift = effBits-25 - var shiftBN = BigNumber.from(2).pow(shift) - var low24 = price.div(shiftBN).sub(twoPow24) - var high8 = BigNumber.from(shift).add(1).mul(twoPow24) - return high8.add(low24) - } const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" - const FactoryAddr = "0xc6ec5d65cA33E7E3ac58A263177c9eEF8042fE17" const stock = currenciesSelected?.currencyA const money = currenciesSelected?.currencyB + const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address + const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address const stockContract = useTokenContract(stock?.address) const moneyContract = useTokenContract(money?.address) const factoryContract = useFactoryGridexContract() const [marketAddress, setMarketAddress] = useState() - factoryContract.getAddress(stock?.address, money?.address, ImplAddr).then(a => setMarketAddress(a)) - - let moneyDecimals = moneyContract?.decimals() - let stockDecimals = stockContract?.decimals() + factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) const marketContract = useGridexMarketContract(marketAddress) async function CreateRobot() { + const moneyDecimals = await moneyContract?.decimals() + const stockDecimals = await stockContract?.decimals() const stockAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4) const moneyAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4) - var stockAmountBN = parseUnits(stockAmount, await stockDecimals) - var moneyAmountBN = parseUnits(moneyAmount, await moneyDecimals) + var stockAmountBN = parseUnits(stockAmount, stockDecimals) + var moneyAmountBN = parseUnits(moneyAmount, moneyDecimals) var highPrice = packPrice(parseUnits(maxValue)) var lowPrice = packPrice(parseUnits(minValue)) var robotInfo = stockAmountBN.mul(BigNumber.from(2).pow(96)).add(moneyAmountBN) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(highPrice) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(lowPrice) + + console.log(highPrice); + console.log(lowPrice); - await marketContract.createRobot(robotInfo) + await marketContract.createRobot(robotInfo).then((response) => { + addTransaction(response, { + summary: `Create Robot` + }) + }) } + async function createMarket() { - await factoryContract.create(stock?.address, money?.address, ImplAddr) + factoryContract.create(stockAddress, moneyAddress, ImplAddr) + .then((response: TransactionResponse) => { + addTransaction(response, { + summary: `Create Market for ${stock?.symbol}-${money?.symbol}` + }) + }) + } + + async function marketAddressCheck() { + let provider = new ethers.providers.Web3Provider(window.ethereum) + let code = await provider.getCode(marketAddress) + code == "0x" ? setFoundMarketAddress(false) : setFoundMarketAddress(true) } useEffect(() => { - const marketAddressCheck = async () => { - let provider = new ethers.providers.Web3Provider(window.ethereum) - let code = await provider.getCode(marketAddress) - code == "0x" ? setHaveMarketAddress(false) : setHaveMarketAddress(true) - } marketAddressCheck() - }, [marketAddress]) + }) const formattedAmounts = { @@ -203,12 +216,14 @@ export default function CreateGridexPage() { chainId && currenciesSelected?.currencyA && parsedAmounts[Field.CURRENCY_A] && + stock?.symbol !== 'BCH' && (stockApprovalState === ApprovalState.NOT_APPROVED || stockApprovalState === ApprovalState.PENDING) const showMoneyApprove = chainId && currenciesSelected?.currencyB && parsedAmounts[Field.CURRENCY_B] && + money?.symbol !== 'BCH' && (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING @@ -290,8 +305,8 @@ export default function CreateGridexPage() {
{
- - + +
} @@ -306,7 +321,7 @@ export default function CreateGridexPage() { ) : - !haveMarketAddress ? ( + !foundMarketAddress ? ( From 227620e638efdf3da8ac4deb372b59615207d90a Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 24 Oct 2022 23:43:40 -0300 Subject: [PATCH 34/83] feat: contracts created in gridex list --- src/pages/gridex/create-gridex/index.tsx | 6 - src/pages/gridex/gridex-list/index.tsx | 214 ++++++++++++++++------- 2 files changed, 146 insertions(+), 74 deletions(-) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 1596a4f698..5d77573432 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -94,15 +94,9 @@ export default function CreateGridexPage() { const { independentField, typedValue, otherTypedValue } = useMintState() const { dependentField, - currencies, - pair, - pairState, currencyBalances, parsedAmounts, - price, noLiquidity, - liquidityMinted, - poolTokenPercentage, error, } = useGridexMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 0e13ade319..deec237bcf 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -1,6 +1,6 @@ import { Chef, PairType } from '../../../features/onsen/enum' import { PlusIcon } from '@heroicons/react/outline' -import { useActiveWeb3React, useFuse } from '../../../hooks' +import { useActiveWeb3React, useFactoryGridexContract, useFuse, useGridexMarketContract, useTokenContract } from '../../../hooks' import { useAverageBlockTime, useEthPrice, @@ -22,15 +22,16 @@ import { WBCH, MASTERCHEF_ADDRESS, MASTERCHEF_V2_ADDRESS, + Currency, } from '@tangoswapcash/sdk' import { TANGO, FLEXUSD } from '../../../config/tokens' import Container from '../../../components/Container' import FarmList from '../../../features/onsen/FarmList' import Head from 'next/head' import Menu from '../../../features/onsen/FarmMenu' -import React, { useEffect } from 'react' +import React, { useEffect, useState } from 'react' import Search from '../../../components/Search' -import { classNames } from '../../../functions' +import { classNames, maxAmountSpend } from '../../../functions' import dynamic from 'next/dynamic' import { getAddress } from '@ethersproject/address' import useFarmRewards from '../../../hooks/useFarmRewards' @@ -51,7 +52,9 @@ import { ethers } from 'ethers' import { parseUnits } from '@ethersproject/units' import { formatUnits } from '@ethersproject/units' import { formatCurrencyAmount } from '../../../functions' -import { CCABI } from '../create-gridex' +import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' +import BuyRobotsPanel from "../../../components/BuyRobotsPanel" +import { Field } from '../../../state/burn/actions' function getTokensSorted(pool, pair) { if (pool.token0 == pair.token0.address && pool.token1 == pair.token1.address) { @@ -121,74 +124,131 @@ function unpackPrice(packed) { return low24.add(twoPow24).mul(shiftBN) } -async function getAllRobots(onlyForAddr) { - const provider = new ethers.providers.Web3Provider(window.ethereum) - const marketContract = new ethers.Contract(window.MarketAddress, CCABI, provider) - let allRobotsArr = await marketContract.getAllRobots() - // console.log('allRobotsArr:', allRobotsArr); - let allRobots = [] - let twoPow96 = BigNumber.from(2).pow(96) - let twoPow32 = BigNumber.from(2).pow(32) - const RobotsMap = {} - for(var i=0; iRobot#${robots[i].shortId+1} ` - htmlStr += ` ` - htmlStr += `Stock: ${robots[i].stockAmount} ` - htmlStr += `Money: ${robots[i].moneyAmount} ` - htmlStr += `HighPrice: ${robots[i].highPrice} ` - htmlStr += `LowPrice: ${robots[i].lowPrice}

` - } - document.getElementById("deleteDiv").innerHTML = htmlStr -} - export default function Gridex(): JSX.Element { const { i18n } = useLingui() - const { chainId } = useActiveWeb3React() + const { account, chainId } = useActiveWeb3React() const router = useRouter() + const [currenciesSelected, setCurrenciesSelected] = useState(null); + + const handleCurrencyASelect = (currencyA: Currency) => { + // console.log('currencyA:', currencyA) + setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) + } + const handleCurrencyBSelect = (currencyB: Currency) => { + setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) + } + + const { independentField, typedValue, otherTypedValue } = useMintState() + + const { + dependentField, + currencies, + currencyBalances, + parsedAmounts, + noLiquidity + } = useDerivedMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) + + + const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) + + const formattedAmounts = { + [independentField]: typedValue, + [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', + } + + const maxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmountSpend(currencyBalances[field]), + } + }, + {} + ) + const atMaxAmounts: { [field in Field]?: CurrencyAmount } = [Field.CURRENCY_A, Field.CURRENCY_B].reduce( + (accumulator, field) => { + return { + ...accumulator, + [field]: maxAmounts[field]?.equalTo(parsedAmounts[field] ?? '0'), + } + }, + {} + ) + const stock = currenciesSelected?.currencyA + const money = currenciesSelected?.currencyB + + const stockContract = useTokenContract(stock?.address) + const moneyContract = useTokenContract(money?.address) + + async function getAllRobots(onlyForAddr) { + const moneyDecimals = await moneyContract?.decimals() + const stockDecimals = await stockContract?.decimals() + const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" + const factoryContract = useFactoryGridexContract() + const marketAddress = await factoryContract.getAddress() + const provider = new ethers.providers.Web3Provider(window.ethereum) + const marketContract = useGridexMarketContract(marketAddress) + let allRobotsArr = await marketContract.getAllRobots() + let allRobots = [] + let twoPow96 = BigNumber.from(2).pow(96) + let twoPow32 = BigNumber.from(2).pow(32) + const RobotsMap = {} + for(var i=0; iRobot#${robots[i].shortId+1} ` + htmlStr += ` ` + htmlStr += `Stock: ${robots[i].stockAmount} ` + htmlStr += `Money: ${robots[i].moneyAmount} ` + htmlStr += `HighPrice: ${robots[i].highPrice} ` + htmlStr += `LowPrice: ${robots[i].lowPrice}

` + } + document.getElementById("deleteDiv").innerHTML = htmlStr + } + getAllRobots(account).then(result => console.log(result)) + const type = router.query.filter as string const savedFilter = getFarmFilter() @@ -654,6 +714,7 @@ export default function Gridex(): JSX.Element {
+
{!isMobile ?
@@ -710,6 +771,23 @@ export default function Gridex(): JSX.Element {
+ + { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + value={formattedAmounts[Field.CURRENCY_B]} + onCurrencySelect={handleCurrencyASelect} + onCurrencyBSelect={handleCurrencyBSelect} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + // onOtherCurrencySelect={handleCurrencyBSelect} + // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + showCommonBases + /> ) } From 183e8f677881d607bca1b469fd751ddb211f8686 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Wed, 26 Oct 2022 15:02:35 -0300 Subject: [PATCH 35/83] feat: change search style and fix view gridex navlink --- src/components/BuyRobotsPanel/index.tsx | 4 +- src/pages/gridex/create-gridex/index.tsx | 3 +- src/pages/gridex/gridex-list/index.tsx | 221 +++++++++++++---------- 3 files changed, 125 insertions(+), 103 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index a07abb4453..de8a573456 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -84,7 +84,7 @@ export default function BuyRobotsPanel({ return ( -
+
 ` htmlStr += `Stock: ${robots[i].stockAmount} ` htmlStr += `Money: ${robots[i].moneyAmount} ` @@ -347,7 +347,7 @@ export default function Gridex(): JSX.Element { }, }, } - + const kashiPairs = [] // unused const swapPairs = [] const farms2 = useFarms() @@ -691,7 +691,7 @@ export default function Gridex(): JSX.Element { { href: `/${basePath}/on-Sale`, label: 'Tango CMM on Sale' - },{ + }, { divider: true }, { @@ -712,66 +712,87 @@ export default function Gridex(): JSX.Element {
- +
- +
- {!isMobile ? -
- - - - -
- : - <> -
- -
- - - - - } + {!isMobile ? +
+ { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + value={formattedAmounts[Field.CURRENCY_B]} + onCurrencySelect={handleCurrencyASelect} + onCurrencyBSelect={handleCurrencyBSelect} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + // onOtherCurrencySelect={handleCurrencyBSelect} + // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + showCommonBases + /> + +
+ +
+
+ + + + +
+ +
+ : + <> +
+ { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + value={formattedAmounts[Field.CURRENCY_B]} + onCurrencySelect={handleCurrencyASelect} + onCurrencyBSelect={handleCurrencyBSelect} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + // onOtherCurrencySelect={handleCurrencyBSelect} + // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + showCommonBases + /> +
+ + + + + + }
Tango CMM list{' '}
- +
- + + /> ) } From d6ec920479bdf6969935f12f227ab1ba167e7bd8 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 26 Oct 2022 20:40:19 -0300 Subject: [PATCH 36/83] feat: commit --- src/features/robots/RobotList.tsx | 8 +- src/pages/gridex/create-gridex/index.tsx | 4 +- src/pages/gridex/gridex-list/index.tsx | 251 ++++++----------------- 3 files changed, 68 insertions(+), 195 deletions(-) diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index 13de402117..ddd0e870a5 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -29,21 +29,21 @@ const RobotList = ({ robots, term }) => {
requestSort('tvl')} + onClick={() => requestSort('lowPrice')} > {i18n._(t`Min Price to Buy`)} {sortConfig && - sortConfig.key === 'tvl' && + sortConfig.key === 'lowPrice' && ((sortConfig.direction === 'ascending' && ) || (sortConfig.direction === 'descending' && ))}
requestSort('roiPerYear')} + onClick={() => requestSort('highPrice')} > {i18n._(t`Max Price to Sell`)} {sortConfig && - sortConfig.key === 'roiPerYear' && + sortConfig.key === 'highPrice' && ((sortConfig.direction === 'ascending' && ) || (sortConfig.direction === 'descending' && ))}
diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index b816489a7b..636725aad2 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -300,8 +300,8 @@ export default function CreateGridexPage() {
{
- - + +
} diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 1b79e5bf46..d5955cf744 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -29,7 +29,7 @@ import Container from '../../../components/Container' import FarmList from '../../../features/onsen/FarmList' import Head from 'next/head' import Menu from '../../../features/onsen/FarmMenu' -import React, { useEffect, useState } from 'react' +import React, { useEffect, useMemo, useState } from 'react' import Search from '../../../components/Search' import { classNames, maxAmountSpend } from '../../../functions' import dynamic from 'next/dynamic' @@ -129,6 +129,9 @@ export default function Gridex(): JSX.Element { const { account, chainId } = useActiveWeb3React() const router = useRouter() + const [marketAddress, setMarketAddress] = useState('') + const [gridexList, setGridexList] = useState([]) + const [currenciesSelected, setCurrenciesSelected] = useState(null); const handleCurrencyASelect = (currencyA: Currency) => { @@ -175,8 +178,18 @@ export default function Gridex(): JSX.Element { }, {} ) + + const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" + const stock = currenciesSelected?.currencyA const money = currenciesSelected?.currencyB + const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address + const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address + + const factoryContract = useFactoryGridexContract() + factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) + + const marketContract = useGridexMarketContract(marketAddress) const stockContract = useTokenContract(stock?.address) const moneyContract = useTokenContract(money?.address) @@ -184,17 +197,13 @@ export default function Gridex(): JSX.Element { async function getAllRobots(onlyForAddr) { const moneyDecimals = await moneyContract?.decimals() const stockDecimals = await stockContract?.decimals() - const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" - const factoryContract = useFactoryGridexContract() - const marketAddress = await factoryContract.getAddress() const provider = new ethers.providers.Web3Provider(window.ethereum) - const marketContract = useGridexMarketContract(marketAddress) - let allRobotsArr = await marketContract.getAllRobots() + let allRobotsArr = await marketContract?.getAllRobots() let allRobots = [] let twoPow96 = BigNumber.from(2).pow(96) let twoPow32 = BigNumber.from(2).pow(32) const RobotsMap = {} - for (var i = 0; i < allRobotsArr.length; i += 2) { + for (var i = 0; i < allRobotsArr?.length; i += 2) { let fullId = allRobotsArr[i] let robot = { fullId: fullId.toHexString(), @@ -247,7 +256,13 @@ export default function Gridex(): JSX.Element { } document.getElementById("deleteDiv").innerHTML = htmlStr } - getAllRobots(account).then(result => console.log(result)) + + useEffect(() => { + getAllRobots(account).then(result => setGridexList(result)) + }, [stock || money]) + + console.log(gridexList); + // se necesita Stock amount, Money Amount, highprice, lowprice const type = router.query.filter as string @@ -293,61 +308,6 @@ export default function Gridex(): JSX.Element { }, } - const hardcodedPairs2x = { - [ChainId.SMARTBCH]: { - '0xCFa5B1C5FaBF867842Ac3C25E729Fc3671d27c50': { - farmId: 0, - allocPoint: 1249938, - token0: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0xbA85D6bB454315A0fb65b205Fa48DBAff82A4019', - rewardToken: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), - rewardPerSecond: '1000000000000000000', - }, - '0xF463db65674426A58E9C3fE557FaaE338026ef39': { - farmId: 1, - allocPoint: 1249937, - token0: new Token( - ChainId.SMARTBCH, - '0x675E1d6FcE8C7cC091aED06A68D079489450338a', - 18, - 'ARG', - 'Bitcoin Cash Argentina' - ), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0x3f28b9BE239038568D67f076a0ff9AEdEa5668d8', - rewardToken: new Token( - ChainId.SMARTBCH, - '0x675E1d6FcE8C7cC091aED06A68D079489450338a', - 18, - 'ARG', - 'Bitcoin Cash Argentina' - ), - rewardPerSecond: '2342000000000000000000', - }, - '0x0152E5F007D85aae58Eb7191Bd484f12F9c13052': { - farmId: 2, - allocPoint: 499999, - token0: new Token(ChainId.SMARTBCH, '0x49F9ECF126B6dDF51C731614755508A4674bA7eD', 18, 'RMZ', 'Xolos'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0xefEf4dC16316Ae8c7AF00489b0e5FA52be68D1B6', - rewardToken: new Token(ChainId.SMARTBCH, '0x49F9ECF126B6dDF51C731614755508A4674bA7eD', 18, 'RMZ', 'Xolos'), - rewardPerSecond: '58330000000000', - }, - }, - [ChainId.SMARTBCH_AMBER]: { - '0xCFa5B1C5FaBF867842Ac3C25E729Fc3671d27c50': { - farmId: 0, - allocPoint: 1249937, - token0: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), - token1: WBCH[ChainId.SMARTBCH], - rewarderId: '0xbA85D6bB454315A0fb65b205Fa48DBAff82A4019', - rewardToken: new Token(ChainId.SMARTBCH, '0xc70c7718C7f1CCd906534C2c4a76914173EC2c44', 18, 'KTH', 'Knuth'), - rewardPerSecond: '1000000000000000000', - }, - }, - } - const kashiPairs = [] // unused const swapPairs = [] const farms2 = useFarms() @@ -398,7 +358,6 @@ export default function Gridex(): JSX.Element { farms.push(f) } - // console.log(farms); const flexUSDTangoPool = farms[1].pool const bchFlexUSDPool = farms[3].pool const bchTangoPool = farms[2].pool @@ -420,114 +379,45 @@ export default function Gridex(): JSX.Element { Number.parseFloat(bchTangoPool.reserves[0].toFixed()) / Number.parseFloat(bchTangoPool.reserves[1].toFixed()) } - for (const [pairAddress, pair] of Object.entries(hardcodedPairs2x[chainId])) { - swapPairs.push({ - id: pairAddress, - reserveUSD: '100000', - totalSupply: '1000', - timestamp: '1599830986', - token0: { - id: pair.token0.address, - name: pair.token0.name, - symbol: pair.token0.symbol, - decimals: pair.token0.decimals, - }, - token1: { - id: pair.token1.address, - name: pair.token1.name, - symbol: pair.token1.symbol, - decimals: pair.token1.decimals, - }, - }) - - const f = { - pair: pairAddress, - symbol: `${hardcodedPairs2x[chainId][pairAddress].token0.symbol}-${hardcodedPairs2x[chainId][pairAddress].token1.symbol}`, - - // eslint-disable-next-line react-hooks/rules-of-hooks - pool: usePool(pairAddress), - - allocPoint: pair.allocPoint, - balance: '1000000000000000000', - chef: 1, - id: pair.farmId, - pendingSushi: undefined, - pending: 0, - owner: { - id: MASTERCHEF_V2_ADDRESS[chainId], - sushiPerBlock: '10000000000000000000', - totalAllocPoint: '999949984', // "999949984" - }, - - rewarder: { - id: pair.rewarderId, - rewardToken: pair.rewardToken.address, - rewardPerSecond: pair.rewardPerSecond, - }, - - rewardToken: { - ...pair.rewardToken, - // eslint-disable-next-line react-hooks/rules-of-hooks - derivedETH: getTokenPriceInBch(usePool(pairAddress), pair, chainId, tangoPriceBCH, bchPriceUSD), - }, - maxPrice: (100 * Math.random()).toFixed(4), - minPrice: (10 * Math.random()).toFixed(4), - userCount: 1, - } - // eslint-disable-next-line react-hooks/rules-of-hooks - f.pendingSushi = usePendingSushi(f) - f.pending = f.id % 2 === 0 ? 1 : 0 - farms.push(f) - } - - const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator( - MASTERCHEF_ADDRESS[chainId], - farms.map((farm) => new Token(chainId, farm.pair, 18, 'LP', 'LP Token')) - ) - - const [v2PairsBalances2x, fetchingV2PairBalances2x] = useTokenBalancesWithLoadingIndicator( - MASTERCHEF_V2_ADDRESS[chainId], - farms.map((farm) => new Token(chainId, farm.pair, 18, 'LP', 'LP Token')) - ) - - if (!fetchingV2PairBalances) { - for (let i = 0; i < farms.length; ++i) { - if (v2PairsBalances.hasOwnProperty(farms[i].pair) && farms[i].pool.totalSupply) { - const totalSupply = Number.parseFloat(farms[i].pool.totalSupply.toFixed()) - let chefBalance = Number.parseFloat(v2PairsBalances[farms[i].pair].toFixed()) - - if (v2PairsBalances2x.hasOwnProperty(farms[i].pair)) { - chefBalance += Number.parseFloat(v2PairsBalances2x[farms[i].pair].toFixed()) - } - - let tvl = 0 - if (farms[i].pool.token0 === TANGO[chainId].address) { - const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) - tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 - } else if (farms[i].pool.token1 === TANGO[chainId].address) { - const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) - tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 - } else if (farms[i].pool.token0 === FLEXUSD.address) { - const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) - tvl = (reserve / totalSupply) * chefBalance * 2 - } else if (farms[i].pool.token1 === FLEXUSD.address) { - const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) - tvl = (reserve / totalSupply) * chefBalance * 2 - } else if (farms[i].pool.token0 === WBCH[chainId].address) { - const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) - tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 - } else if (farms[i].pool.token1 === WBCH[chainId].address) { - const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) - tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 - } - farms[i].tvl = tvl - farms[i].chefBalance = chefBalance - } else { - farms[i].tvl = '0' - farms[i].chefBalance = 0 - } - } - } + // const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator( + // MASTERCHEF_ADDRESS[chainId], + // farms.map((farm) => new Token(chainId, farm.pair, 18, 'LP', 'LP Token')) + // ) + + // if (!fetchingV2PairBalances) { + // for (let i = 0; i < farms.length; ++i) { + // if (v2PairsBalances.hasOwnProperty(farms[i].pair) && farms[i].pool.totalSupply) { + // const totalSupply = Number.parseFloat(farms[i].pool.totalSupply.toFixed()) + // let chefBalance = Number.parseFloat(v2PairsBalances[farms[i].pair].toFixed()) + + // let tvl = 0 + // if (farms[i].pool.token0 === TANGO[chainId].address) { + // const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) + // tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 + // } else if (farms[i].pool.token1 === TANGO[chainId].address) { + // const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) + // tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 + // } else if (farms[i].pool.token0 === FLEXUSD.address) { + // const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) + // tvl = (reserve / totalSupply) * chefBalance * 2 + // } else if (farms[i].pool.token1 === FLEXUSD.address) { + // const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) + // tvl = (reserve / totalSupply) * chefBalance * 2 + // } else if (farms[i].pool.token0 === WBCH[chainId].address) { + // const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) + // tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 + // } else if (farms[i].pool.token1 === WBCH[chainId].address) { + // const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) + // tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 + // } + // farms[i].tvl = tvl + // farms[i].chefBalance = chefBalance + // } else { + // farms[i].tvl = '0' + // farms[i].chefBalance = 0 + // } + // } + // } const positions = usePositions(chainId) @@ -792,23 +682,6 @@ export default function Gridex(): JSX.Element {
- - { - onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') - }} - value={formattedAmounts[Field.CURRENCY_B]} - onCurrencySelect={handleCurrencyASelect} - onCurrencyBSelect={handleCurrencyBSelect} - currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} - currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - // onOtherCurrencySelect={handleCurrencyBSelect} - // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - showCommonBases - /> ) } From 6a4b95fc2cce3fc7fde61a3fe3f637efca594a0b Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Thu, 27 Oct 2022 12:42:49 -0300 Subject: [PATCH 37/83] feat: create search function prop --- src/components/BuyRobotsPanel/index.tsx | 176 ++++++++++++------------ src/pages/gridex/gridex-list/index.tsx | 34 +++++ 2 files changed, 123 insertions(+), 87 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index de8a573456..75a4b90b9f 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -40,6 +40,7 @@ interface CurrencyInputPanelProps { locked?: boolean customBalanceText?: string readOnly?: boolean + searchFunction?: any } export default function BuyRobotsPanel({ @@ -64,6 +65,7 @@ export default function BuyRobotsPanel({ locked = false, customBalanceText, readOnly = false, + searchFunction }: CurrencyInputPanelProps) { const { i18n } = useLingui() @@ -93,7 +95,7 @@ export default function BuyRobotsPanel({ !!currency ? 'text-primary' : 'text-high-emphesis', 'open-currency-select-button h-full outline-none select-none cursor-pointer border-none text-xl font-medium items-center' )} - onClick={() => { + onClick={() => { setCurrencySelector('A') if (onCurrencySelect) { setModalOpen(true) @@ -101,7 +103,7 @@ export default function BuyRobotsPanel({ }} >
- { currency ? ( + {currency ? (
@@ -128,13 +130,13 @@ export default function BuyRobotsPanel({
{(currency && currency.symbol && currency.symbol.length > 20 ? currency.symbol.slice(0, 4) + - '...' + - currency.symbol.slice(currency.symbol.length - 5, currency.symbol.length) + '...' + + currency.symbol.slice(currency.symbol.length - 5, currency.symbol.length) : currency?.symbol) || ( -
- {i18n._(t`Select a token`)} -
- )} +
+ {i18n._(t`Select a token`)} +
+ )}
{!disableCurrencySelect && currency && ( @@ -156,7 +158,7 @@ export default function BuyRobotsPanel({ )} onClick={() => { setCurrencySelector('B') - if (onCurrencyBSelect ) { + if (onCurrencyBSelect) { setModalOpen(true) } }} @@ -189,13 +191,13 @@ export default function BuyRobotsPanel({
{(currencyB && currencyB.symbol && currencyB.symbol.length > 20 ? currencyB.symbol.slice(0, 4) + - '...' + - currencyB.symbol.slice(currencyB.symbol.length - 5, currencyB.symbol.length) + '...' + + currencyB.symbol.slice(currencyB.symbol.length - 5, currencyB.symbol.length) : currencyB?.symbol) || ( -
- {i18n._(t`Select a token`)} -
- )} +
+ {i18n._(t`Select a token`)} +
+ )}
{!disableCurrencySelect && currencyB && ( @@ -207,87 +209,87 @@ export default function BuyRobotsPanel({
- -
+ <> + {showMaxButton && ( + )} - > - <> - { showMaxButton && ( - - )} - { - // console.log('val:', val); - onUserInput(val) - }} - readOnly={readOnly} - className={`w-2/3 h-16 text-base bg-transparent `} - /> - {!hideBalance && currency && selectedCurrencyBBalance ? ( -
-
- {renderBalance ? ( - renderBalance(selectedCurrencyBBalance) - ) : ( - <> - {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} - - )} -
- + { + // console.log('val:', val); + onUserInput(val) + }} + readOnly={readOnly} + className={`w-2/3 h-16 text-base bg-transparent `} + /> + {!hideBalance && currency && selectedCurrencyBBalance ? ( +
+
+ {renderBalance ? ( + renderBalance(selectedCurrencyBBalance) + ) : ( + <> + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} + + )}
- ) : null} - -
+ +
+ ) : null} + +
- +
- - -
- { + + +
+ { currencySelector == 'A' ? ( - - - ) - : - ( - ) - } + isOpen={modalOpen} + onDismiss={handleDismissSearch} + onCurrencySelect={onCurrencySelect} + selectedCurrency={currency} + otherSelectedCurrency={currency} + showCommonBases={showCommonBases} + /> + + ) + : + ( + + ) + }
) } \ No newline at end of file diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 1b79e5bf46..a1a181ff87 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -701,6 +701,38 @@ export default function Gridex(): JSX.Element { } ] + const [robot, setRobot] = useState([]) + function listRobotsForBuying() { + console.log("sis"); + + useEffect(() => { + const robotsCall = async () => { + alert("haciedo la call") + try{ + var robots = await getAllRobots(""); + console.log("Robots:", robots); + if (robots.length == 0) { + + return alert("No Robots availables") + } + robots.sort(function (a, b) { + return a.highPrice - b.highPrice; + }); + alert("call hecha"); + robotsCall();}catch(e){ + alert("Fallo en la call") + alert(e); + }} + + } + , []); + + + + } + + + return (
@@ -808,6 +841,7 @@ export default function Gridex(): JSX.Element { // onOtherCurrencySelect={handleCurrencyBSelect} // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} showCommonBases + searchFunction={listRobotsForBuying} /> ) From e94856ef3d91d10468f6129de292df2c70a721e4 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sat, 29 Oct 2022 18:42:37 -0300 Subject: [PATCH 38/83] feat: commit to pull --- src/pages/gridex/gridex-list/index.tsx | 292 ++++++++++++------------- 1 file changed, 135 insertions(+), 157 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index d5955cf744..da0e9a7751 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -234,29 +234,7 @@ export default function Gridex(): JSX.Element { } return allRobots } - - async function listMyRobots() { - const provider = new ethers.providers.Web3Provider(window.ethereum); - const signer = provider.getSigner(); - const myAddr = await signer.getAddress(); - - var robots = await getAllRobots(myAddr); - if (robots.length == 0) { - document.getElementById("deleteDiv").innerHTML = "

You have no robots on duty!

" - return - } - var htmlStr = "

" - for (var i = 0; i < robots.length; i++) { - htmlStr += `Robot#${robots[i].shortId + 1} ` - htmlStr += ` ` - htmlStr += `Stock: ${robots[i].stockAmount} ` - htmlStr += `Money: ${robots[i].moneyAmount} ` - htmlStr += `HighPrice: ${robots[i].highPrice} ` - htmlStr += `LowPrice: ${robots[i].lowPrice}

` - } - document.getElementById("deleteDiv").innerHTML = htmlStr - } - + useEffect(() => { getAllRobots(account).then(result => setGridexList(result)) }, [stock || money]) @@ -313,71 +291,71 @@ export default function Gridex(): JSX.Element { const farms2 = useFarms() let farms = [] - for (const [pairAddress, pair] of Object.entries(hardcodedPairs[chainId])) { - swapPairs.push({ - id: pairAddress, - reserveUSD: '100000', - totalSupply: '1000', - timestamp: '1599830986', - token0: { - id: pair.token0.address, - name: pair.token0.name, - symbol: pair.token0.symbol, - decimals: pair.token0.decimals, - }, - token1: { - id: pair.token1.address, - name: pair.token1.name, - symbol: pair.token1.symbol, - decimals: pair.token1.decimals, - }, - }) - - const f = { - pair: pairAddress, - symbol: `${hardcodedPairs[chainId][pairAddress].token0.symbol}-${hardcodedPairs[chainId][pairAddress].token1.symbol}`, - // eslint-disable-next-line react-hooks/rules-of-hooks - pool: usePool(pairAddress), - allocPoint: pair.allocPoint, - balance: '1000000000000000000', - chef: 0, - id: pair.farmId, - pendingSushi: undefined, - pending: 0, - owner: { - id: MASTERCHEF_ADDRESS[chainId], - sushiPerBlock: '10000000000000000000', - totalAllocPoint: '999949984', - }, - userCount: 1, - } - // eslint-disable-next-line react-hooks/rules-of-hooks - f.pendingSushi = usePendingSushi(f) - f.pending = Number.parseFloat(f.pendingSushi?.toFixed()) - - farms.push(f) - } + // for (const [pairAddress, pair] of Object.entries(hardcodedPairs[chainId])) { + // swapPairs.push({ + // id: pairAddress, + // reserveUSD: '100000', + // totalSupply: '1000', + // timestamp: '1599830986', + // token0: { + // id: pair.token0.address, + // name: pair.token0.name, + // symbol: pair.token0.symbol, + // decimals: pair.token0.decimals, + // }, + // token1: { + // id: pair.token1.address, + // name: pair.token1.name, + // symbol: pair.token1.symbol, + // decimals: pair.token1.decimals, + // }, + // }) + + // const f = { + // pair: pairAddress, + // symbol: `${hardcodedPairs[chainId][pairAddress].token0.symbol}-${hardcodedPairs[chainId][pairAddress].token1.symbol}`, + // // eslint-disable-next-line react-hooks/rules-of-hooks + // pool: usePool(pairAddress), + // allocPoint: pair.allocPoint, + // balance: '1000000000000000000', + // chef: 0, + // id: pair.farmId, + // pendingSushi: undefined, + // pending: 0, + // owner: { + // id: MASTERCHEF_ADDRESS[chainId], + // sushiPerBlock: '10000000000000000000', + // totalAllocPoint: '999949984', + // }, + // userCount: 1, + // } + // // eslint-disable-next-line react-hooks/rules-of-hooks + // f.pendingSushi = usePendingSushi(f) + // f.pending = Number.parseFloat(f.pendingSushi?.toFixed()) - const flexUSDTangoPool = farms[1].pool - const bchFlexUSDPool = farms[3].pool - const bchTangoPool = farms[2].pool - let bchPriceUSD = 0 - let tangoPriceUSD = 0 - let tangoPriceBCH = 0 - if (bchFlexUSDPool.reserves) { - bchPriceUSD = - Number.parseFloat(bchFlexUSDPool.reserves[1].toFixed()) / Number.parseFloat(bchFlexUSDPool.reserves[0].toFixed()) - } - if (flexUSDTangoPool.reserves) { - tangoPriceUSD = - 1 / - (Number.parseFloat(flexUSDTangoPool.reserves[0].toFixed()) / - Number.parseFloat(flexUSDTangoPool.reserves[1].toFixed())) - } - if (bchTangoPool.reserves) { - tangoPriceBCH = - Number.parseFloat(bchTangoPool.reserves[0].toFixed()) / Number.parseFloat(bchTangoPool.reserves[1].toFixed()) - } + // farms.push(f) + // } + + // const flexUSDTangoPool = farms[1].pool + // const bchFlexUSDPool = farms[3].pool + // const bchTangoPool = farms[2].pool + // let bchPriceUSD = 0 + // let tangoPriceUSD = 0 + // let tangoPriceBCH = 0 + // if (bchFlexUSDPool.reserves) { + // bchPriceUSD = + // Number.parseFloat(bchFlexUSDPool.reserves[1].toFixed()) / Number.parseFloat(bchFlexUSDPool.reserves[0].toFixed()) + // } + // if (flexUSDTangoPool.reserves) { + // tangoPriceUSD = + // 1 / + // (Number.parseFloat(flexUSDTangoPool.reserves[0].toFixed()) / + // Number.parseFloat(flexUSDTangoPool.reserves[1].toFixed())) + // } + // if (bchTangoPool.reserves) { + // tangoPriceBCH = + // Number.parseFloat(bchTangoPool.reserves[0].toFixed()) / Number.parseFloat(bchTangoPool.reserves[1].toFixed()) + // } // const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator( // MASTERCHEF_ADDRESS[chainId], @@ -421,12 +399,12 @@ export default function Gridex(): JSX.Element { const positions = usePositions(chainId) - // const averageBlockTime = useAverageBlockTime() - const averageBlockTime = 6 - const masterChefV1TotalAllocPoint = useMasterChefV1TotalAllocPoint() - const masterChefV1SushiPerBlock = useMasterChefV1SushiPerBlock() + // // const averageBlockTime = useAverageBlockTime() + // const averageBlockTime = 6 + // const masterChefV1TotalAllocPoint = useMasterChefV1TotalAllocPoint() + // const masterChefV1SushiPerBlock = useMasterChefV1SushiPerBlock() - const blocksPerDay = 86400 / Number(averageBlockTime) + // const blocksPerDay = 86400 / Number(averageBlockTime) const map = (pool) => { // TODO: Account for fees generated in case of swap pairs, and use standard compounding @@ -435,81 +413,81 @@ export default function Gridex(): JSX.Element { // How can we include this? // TODO: Deal with inconsistencies between properties on subgraph - pool.owner = pool?.owner || pool?.masterChef - pool.balance = pool?.balance || pool?.slpBalance + // pool.owner = pool?.owner || pool?.masterChef + // pool.balance = pool?.balance || pool?.slpBalance - const swapPair = swapPairs?.find((pair) => pair.id === pool.pair) - const kashiPair = kashiPairs?.find((pair) => pair.id === pool.pair) + // const swapPair = swapPairs?.find((pair) => pair.id === pool.pair) + // const kashiPair = kashiPairs?.find((pair) => pair.id === pool.pair) - const type = swapPair ? PairType.SWAP : PairType.KASHI + // const type = swapPair ? PairType.SWAP : PairType.KASHI - const pair = swapPair || kashiPair + // const pair = swapPair || kashiPair - const blocksPerDay = 15684 // calculated empirically + // const blocksPerDay = 15684 // calculated empirically - function getRewards() { - // TODO: Some subgraphs give sushiPerBlock & sushiPerSecond, and mcv2 gives nothing - const sushiPerBlock = - pool?.owner?.sushiPerBlock / 1e18 || - (pool?.owner?.sushiPerSecond / 1e18) * averageBlockTime || - masterChefV1SushiPerBlock + // function getRewards() { + // // TODO: Some subgraphs give sushiPerBlock & sushiPerSecond, and mcv2 gives nothing + // // const sushiPerBlock = + // // pool?.owner?.sushiPerBlock / 1e18 || + // // (pool?.owner?.sushiPerSecond / 1e18) * averageBlockTime || + // // masterChefV1SushiPerBlock - const rewardPerBlock = (pool.allocPoint / pool.owner.totalAllocPoint) * sushiPerBlock + // const rewardPerBlock = (pool.allocPoint / pool.owner.totalAllocPoint) * sushiPerBlock - const defaultReward = { - token: 'TANGO', - icon: 'https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/0x73BE9c8Edf5e951c9a0762EA2b1DE8c8F38B5e91/logo.png', - rewardPerBlock, - rewardPerDay: rewardPerBlock * blocksPerDay, - rewardPrice: +tangoPriceUSD, - } + // const defaultReward = { + // token: 'TANGO', + // icon: 'https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/0x73BE9c8Edf5e951c9a0762EA2b1DE8c8F38B5e91/logo.png', + // rewardPerBlock, + // rewardPerDay: rewardPerBlock * blocksPerDay, + // rewardPrice: +tangoPriceUSD, + // } - let rewards = [defaultReward] + // let rewards = [defaultReward] - if (pool.chef === Chef.MASTERCHEF_V2) { - // override for mcv2... - pool.owner.totalAllocPoint = masterChefV1TotalAllocPoint + // if (pool.chef === Chef.MASTERCHEF_V2) { + // // override for mcv2... + // pool.owner.totalAllocPoint = masterChefV1TotalAllocPoint - const icon = `https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/${getAddress( - pool.rewarder.rewardToken - )}/logo.png` + // const icon = `https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/${getAddress( + // pool.rewarder.rewardToken + // )}/logo.png` - const decimals = 10 ** pool.rewardToken.decimals - // console.log("pool.rewardToken.decimals: ", pool.rewardToken.decimals); - // console.log("pool.rewardToken.derivedETH: ", pool.rewardToken.derivedETH); - // console.log("pool.rewarder.rewardPerSecond: ", pool.rewarder.rewardPerSecond); - // console.log("decimals: ", decimals); + // const decimals = 10 ** pool.rewardToken.decimals + // // console.log("pool.rewardToken.decimals: ", pool.rewardToken.decimals); + // // console.log("pool.rewardToken.derivedETH: ", pool.rewardToken.derivedETH); + // // console.log("pool.rewarder.rewardPerSecond: ", pool.rewarder.rewardPerSecond); + // // console.log("decimals: ", decimals); - if (pool.rewarder.rewardToken !== '0x0000000000000000000000000000000000000000') { - // console.log("pool.rewarder.rewardPerSecond / decimals: ", pool.rewarder.rewardPerSecond / decimals); + // if (pool.rewarder.rewardToken !== '0x0000000000000000000000000000000000000000') { + // // console.log("pool.rewarder.rewardPerSecond / decimals: ", pool.rewarder.rewardPerSecond / decimals); - const rewardPerBlock = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime + // const rewardPerBlock = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime - // console.log("rewardPerBlock: ", rewardPerBlock); + // // console.log("rewardPerBlock: ", rewardPerBlock); - const rewardPerDay = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime * blocksPerDay - const rewardPrice = pool.rewardToken.derivedETH * bchPriceUSD + // const rewardPerDay = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime * blocksPerDay + // const rewardPrice = pool.rewardToken.derivedETH * bchPriceUSD - // console.log("rewardPrice: ", rewardPrice); + // // console.log("rewardPrice: ", rewardPrice); - const reward = { - token: pool.rewardToken.symbol, - icon: icon, - rewardPerBlock, - rewardPerDay, - rewardPrice, - } + // const reward = { + // token: pool.rewardToken.symbol, + // icon: icon, + // rewardPerBlock, + // rewardPerDay, + // rewardPrice, + // } - rewards[1] = reward - } - } + // rewards[1] = reward + // } + // } - return rewards - } + // return rewards + // } - const rewards = getRewards() + // const rewards = getRewards() - const balance = Number(pool.balance / 1e18) + // const balance = Number(pool.balance / 1e18) const roiPerBlock = rewards.reduce((previousValue, currentValue) => { @@ -541,22 +519,22 @@ export default function Gridex(): JSX.Element { } const FILTER = { - buy: (farm) => farm.allocPoint !== 0, // buscar alguna estadistica que sea unica de los gridex activos y ponerlo aca - portfolio: (farm) => farm.pending !== 0, // buscar alguna estadistica que sea unica de los gridex propios y ponerlo aca + buy: (gridexList) => gridexList.moneyAmount !== 0, // buscar alguna estadistica que sea unica de los gridex activos y ponerlo aca + portfolio: (gridexList) => gridexList.stockAmount !== 0, // buscar alguna estadistica que sea unica de los gridex propios y ponerlo aca } - const data = farms - .filter((farm) => { - return ( - (swapPairs && swapPairs.find((pair) => pair.id === farm.pair)) || - (kashiPairs && kashiPairs.find((pair) => pair.id === farm.pair)) - ) - }) - .map(map) + const data = gridexList + // .filter((farm) => { + // return ( + // (swapPairs && swapPairs.find((pair) => pair.id === farm.pair)) || + // (kashiPairs && kashiPairs.find((pair) => pair.id === farm.pair)) + // ) + // }) + // .map(map) .filter((farm) => { return type in FILTER ? FILTER[type](farm) : true }) - + const options = { keys: ['pair.id', 'pair.token0.symbol', 'pair.token1.symbol'], threshold: 0.4, From b69b4c2033f31bf1a23a35f2918f881f59b53285 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Tue, 1 Nov 2022 11:00:17 -0300 Subject: [PATCH 39/83] feat: push --- src/features/onsen/GridexMenu.tsx | 2 +- src/features/robots/RobotList.tsx | 4 +- src/features/robots/RobotListItemDetails.tsx | 49 +-- src/features/robots/RobotListItems.tsx | 20 +- src/pages/gridex/create-gridex/index.tsx | 20 +- src/pages/gridex/gridex-list/index.tsx | 426 ++----------------- 6 files changed, 80 insertions(+), 441 deletions(-) diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx index 42e7dc2fa1..0cb5b61694 100644 --- a/src/features/onsen/GridexMenu.tsx +++ b/src/features/onsen/GridexMenu.tsx @@ -39,7 +39,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { {account ? (
diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index ddd0e870a5..3d24b7c7e8 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -9,7 +9,7 @@ import { useInfiniteScroll } from '../onsen/hooks' import RobotListItems from './RobotListItems' import { isMobile } from 'react-device-detect' -const RobotList = ({ robots, term }) => { +const RobotList = ({ stockAddress, moneyAddress, robots, term }) => { const { items, requestSort, sortConfig } = useSortableData(robots) const { i18n } = useLingui() const [numDisplayed, setNumDisplayed] = useInfiniteScroll(items) @@ -62,7 +62,7 @@ const RobotList = ({ robots, term }) => { >
{items.slice(0, numDisplayed).map((robot, index) => ( - + ))}
diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index ae669a76d0..c04fe949cd 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -21,9 +21,18 @@ import { Chef, PairType } from '../onsen/enum' import { usePendingSushi, useUserInfo } from '../onsen/hooks' import useMasterChef from '../onsen/useMasterChef' import usePendingReward from '../onsen/usePendingReward' +import { useFactoryGridexContract, useGridexMarketContract } from '../../hooks' -const RobotListItemDetails = ({ robot }) => { +const RobotListItemDetails = ({stockAddress, moneyAddress, robot }) => { const { i18n } = useLingui() + const [marketAddress, setMarketAddress] = useState('') + + const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK + + const factoryContract = useFactoryGridexContract() + factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) + + const marketContract = useGridexMarketContract(marketAddress) const router = useRouter() @@ -34,20 +43,6 @@ const RobotListItemDetails = ({ robot }) => { const addTransaction = useTransactionAdder() - const liquidityToken = new Token( - chainId, - getAddress(robot.pair.id), - robot.pair.type === PairType.KASHI ? Number(robot.pair.asset.decimals) : 18, - robot.pair.symbol, - robot.pair.name - ) - - // User liquidity token balance - const balance = useTokenBalance(account, liquidityToken) - - // TODO: Replace these - const amount = useUserInfo(robot, liquidityToken) - const handleSellRobot = () => { console.log('Vendido') } @@ -55,21 +50,15 @@ const RobotListItemDetails = ({ robot }) => { const handleBuyRobot = () => { console.log('Borrado') } - - const handleDeleteRobot = () => { - console.log('Borrado') + + const DeleteRobot = async () => { + await marketContract.deleteRobot(robot.index, robot.fullId).then((response) => { + addTransaction(response, { + summary: `Delete Robot` + }) + }); } - - const { deposit, withdraw, harvest } = useMasterChef(robot.chef) - - const poolFraction = (Number.parseFloat(amount?.toFixed()) / robot.chefBalance) || 0 - const token0Reserve = robot.pool.reserves ? (robot.pool.reserves.reserve0 as BigNumber).toString() : 0 - const token0Amount = CurrencyAmount.fromRawAmount(robot.pair.token0, JSBI.BigInt(token0Reserve)).multiply(Math.round(poolFraction * 1e8)).divide(1e8) - const token1Reserve = robot.pool.reserves ? (robot.pool.reserves.reserve1 as BigNumber).toString() : 0 - const token1Amount = CurrencyAmount.fromRawAmount(robot.pair.token1, JSBI.BigInt(token1Reserve)).multiply(Math.round(poolFraction * 1e8)).divide(1e8) - const token0Name = robot.pool.token0 === robot.pair.token0.id ? robot.pair.token0.symbol : robot.pair.token1.symbol - const token1Name = robot.pool.token1 === robot.pair.token1.id ? robot.pair.token1.symbol : robot.pair.token0.symbol - + return ( {
diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index c9cbbd4836..7de0e6d360 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -7,17 +7,17 @@ import Image from '../../components/Image' import React from 'react' import { useLingui } from '@lingui/react' import { t } from '@lingui/macro' -import { useCurrency } from '../../hooks/Tokens' +import { useCurrency, useToken } from '../../hooks/Tokens' import { isMobile } from 'react-device-detect' import { usePendingSushi } from '../onsen/hooks' import usePendingReward from '../onsen/usePendingReward' import RobotListItemDetails from './RobotListItemDetails' import { PairType } from '../onsen/enum' -const RobotListItems = ({ robot, ...rest }) => { - const token0 = useCurrency(robot.pair.token0.id) - const token1 = useCurrency(robot.pair.token1.id) - +const RobotListItems = ({ stockAddress, moneyAddress, robot, ...rest }) => { + const token0 = robot?.stock + const token1 = robot?.money + const pendingSushi = usePendingSushi(robot) const rewardAmount = usePendingReward(robot) @@ -40,19 +40,19 @@ const RobotListItems = ({ robot, ...rest }) => {
-

{robot?.pair?.token0?.symbol}

+

{token0?.symbol}

- {robot?.pair?.token1?.symbol} + {token1?.symbol}

- $ {robot.allocPoint / 4} + $ {String(robot.lowPrice).slice(0,6)}
- $ {robot.allocPoint} + $ {String(robot.highPrice).slice(0,6)}
{pendingSushi && pendingSushi.greaterThan(ZERO) ? ( @@ -89,7 +89,7 @@ const RobotListItems = ({ robot, ...rest }) => { )}
- {open && } + {open && } )} diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 636725aad2..c7c5c43b7b 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -106,8 +106,9 @@ export default function CreateGridexPage() { const stock = currenciesSelected?.currencyA const money = currenciesSelected?.currencyB - const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address - const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address + const BCHADDRESS = '0x0000000000000000000000000000000000002711' + const stockAddress = stock?.symbol == 'BCH' ? BCHADDRESS : stock?.address + const moneyAddress = money?.symbol == 'BCH' ? BCHADDRESS : money?.address const stockContract = useTokenContract(stock?.address) const moneyContract = useTokenContract(money?.address) @@ -130,11 +131,11 @@ export default function CreateGridexPage() { var robotInfo = stockAmountBN.mul(BigNumber.from(2).pow(96)).add(moneyAmountBN) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(highPrice) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(lowPrice) - - console.log(highPrice); - console.log(lowPrice); - - await marketContract.createRobot(robotInfo).then((response) => { + + let val = null + val = stockAddress == BCHADDRESS ? {value: stockAmountBN} : moneyAddress == BCHADDRESS ? {value: moneyAmountBN} : null + + await marketContract.createRobot(robotInfo, val).then((response) => { addTransaction(response, { summary: `Create Robot` }) @@ -205,19 +206,20 @@ export default function CreateGridexPage() { marketAddress ) + const nativeSymbol = 'BCH' || 'WBCH' const showStockApprove = chainId && currenciesSelected?.currencyA && parsedAmounts[Field.CURRENCY_A] && - stock?.symbol !== 'BCH' && + stock?.symbol !== nativeSymbol && (stockApprovalState === ApprovalState.NOT_APPROVED || stockApprovalState === ApprovalState.PENDING) const showMoneyApprove = chainId && currenciesSelected?.currencyB && parsedAmounts[Field.CURRENCY_B] && - money?.symbol !== 'BCH' && + money?.symbol !== nativeSymbol && (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 620fc986f8..2721fef91e 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -56,47 +56,6 @@ import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../. import BuyRobotsPanel from "../../../components/BuyRobotsPanel" import { Field } from '../../../state/burn/actions' -function getTokensSorted(pool, pair) { - if (pool.token0 == pair.token0.address && pool.token1 == pair.token1.address) { - return [pair.token0, pair.token1, pool.reserves[0], pool.reserves[1]] - } - - if (pool.token0 == pair.token1.address && pool.token1 == pair.token0.address) { - return [pair.token0, pair.token1, pool.reserves[1], pool.reserves[0]] - } - - return [undefined, undefined, undefined, undefined] -} - -function getTokenPriceInBch(pool, pair, chainId, tangoPriceBCH, bchPriceUSD) { - let [token0, token1, reserve0, reserve1] = getTokensSorted(pool, pair) - - if (!token0) return 0 - - let factor = 0 - let tokenAmount0 = Number.parseFloat(CurrencyAmount.fromRawAmount(token0, JSBI.BigInt(reserve0.toString())).toFixed()) - let tokenAmount1 = Number.parseFloat(CurrencyAmount.fromRawAmount(token1, JSBI.BigInt(reserve1.toString())).toFixed()) - - if (token0.address === TANGO[chainId].address) { - factor = tangoPriceBCH - } else if (token1.address === TANGO[chainId].address) { - ;[tokenAmount1, tokenAmount0] = [tokenAmount0, tokenAmount1] - factor = tangoPriceBCH - } else if (token0.address === FLEXUSD.address) { - factor = bchPriceUSD - } else if (token1.address === FLEXUSD.address) { - ;[tokenAmount1, tokenAmount0] = [tokenAmount0, tokenAmount1] - factor = bchPriceUSD - } else if (token0.address === WBCH[chainId].address) { - factor = 1 - } else if (token1.address === WBCH[chainId].address) { - ;[tokenAmount1, tokenAmount0] = [tokenAmount0, tokenAmount1] - factor = 1 - } - const derivedETH = (tokenAmount0 / tokenAmount1) * factor - return derivedETH -} - function packPrice(price) { var effBits = 1 while (!price.mask(effBits).eq(price)) { @@ -179,7 +138,7 @@ export default function Gridex(): JSX.Element { {} ) - const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" + const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK const stock = currenciesSelected?.currencyA const money = currenciesSelected?.currencyB @@ -215,7 +174,9 @@ export default function Gridex(): JSX.Element { moneyAmountBN: '', stockAmountBN: '', moneyAmount: null, - stockAmount: null + stockAmount: null, + stock: stock, + money: money } robot.shortId = fullId.mod(twoPow96).toNumber() robot.ownerAddr = ethers.utils.getAddress(fullId.div(twoPow96).toHexString()) @@ -234,10 +195,10 @@ export default function Gridex(): JSX.Element { } return allRobots } - - useEffect(() => { + + function getRobots() { getAllRobots(account).then(result => setGridexList(result)) - }, [stock || money]) + } console.log(gridexList); // se necesita Stock amount, Money Amount, highprice, lowprice @@ -249,288 +210,14 @@ export default function Gridex(): JSX.Element { const updateFarmFilter = useUpdateFarmFilter() updateFarmFilter(type) - const hardcodedPairs = { - [ChainId.SMARTBCH]: { - '0x7963269e8a854D3F9D98a6cDEa81efFb31B4D1f2': { - farmId: 0, - allocPoint: 9999999, - token0: TANGO[ChainId.SMARTBCH], - token1: new Token(ChainId.SMARTBCH, '0x98Ff640323C059d8C4CB846976973FEEB0E068aA', 18, 'XTANGO', 'TANGObar'), - }, - '0xf8534BB9603c501Bbe16deF7D08D941F0241855b': { - farmId: 1, - allocPoint: 205699999, - token0: TANGO[ChainId.SMARTBCH], - token1: FLEXUSD, - }, - '0x4b773a2ea30C6A77564E4FaE60204e7Bc0a81A90': { - farmId: 2, - allocPoint: 509999999, - token0: TANGO[ChainId.SMARTBCH], - token1: WBCH[ChainId.SMARTBCH], - }, - '0xA15F8102AB4723A4D1554363c0c8AFF471F16E21': { - farmId: 3, - allocPoint: 170250512, - token0: FLEXUSD, - token1: WBCH[ChainId.SMARTBCH], - }, - }, - [ChainId.SMARTBCH_AMBER]: { - '0x07DE6fc05597E0E4c92C83637A8a0CA411f3a769': { - farmId: 0, - allocPoint: 1000, - token0: WBCH[ChainId.SMARTBCH_AMBER], - token1: new Token(ChainId.SMARTBCH_AMBER, '0xC6F80cF669Ab9e4BE07B78032b4821ed5612A9ce', 18, 'sc', 'testcoin2'), - }, - }, - } - - const kashiPairs = [] // unused - const swapPairs = [] - const farms2 = useFarms() - let farms = [] - - // for (const [pairAddress, pair] of Object.entries(hardcodedPairs[chainId])) { - // swapPairs.push({ - // id: pairAddress, - // reserveUSD: '100000', - // totalSupply: '1000', - // timestamp: '1599830986', - // token0: { - // id: pair.token0.address, - // name: pair.token0.name, - // symbol: pair.token0.symbol, - // decimals: pair.token0.decimals, - // }, - // token1: { - // id: pair.token1.address, - // name: pair.token1.name, - // symbol: pair.token1.symbol, - // decimals: pair.token1.decimals, - // }, - // }) - - // const f = { - // pair: pairAddress, - // symbol: `${hardcodedPairs[chainId][pairAddress].token0.symbol}-${hardcodedPairs[chainId][pairAddress].token1.symbol}`, - // // eslint-disable-next-line react-hooks/rules-of-hooks - // pool: usePool(pairAddress), - // allocPoint: pair.allocPoint, - // balance: '1000000000000000000', - // chef: 0, - // id: pair.farmId, - // pendingSushi: undefined, - // pending: 0, - // owner: { - // id: MASTERCHEF_ADDRESS[chainId], - // sushiPerBlock: '10000000000000000000', - // totalAllocPoint: '999949984', - // }, - // userCount: 1, - // } - // // eslint-disable-next-line react-hooks/rules-of-hooks - // f.pendingSushi = usePendingSushi(f) - // f.pending = Number.parseFloat(f.pendingSushi?.toFixed()) - - // farms.push(f) - // } - - // const flexUSDTangoPool = farms[1].pool - // const bchFlexUSDPool = farms[3].pool - // const bchTangoPool = farms[2].pool - // let bchPriceUSD = 0 - // let tangoPriceUSD = 0 - // let tangoPriceBCH = 0 - // if (bchFlexUSDPool.reserves) { - // bchPriceUSD = - // Number.parseFloat(bchFlexUSDPool.reserves[1].toFixed()) / Number.parseFloat(bchFlexUSDPool.reserves[0].toFixed()) - // } - // if (flexUSDTangoPool.reserves) { - // tangoPriceUSD = - // 1 / - // (Number.parseFloat(flexUSDTangoPool.reserves[0].toFixed()) / - // Number.parseFloat(flexUSDTangoPool.reserves[1].toFixed())) - // } - // if (bchTangoPool.reserves) { - // tangoPriceBCH = - // Number.parseFloat(bchTangoPool.reserves[0].toFixed()) / Number.parseFloat(bchTangoPool.reserves[1].toFixed()) - // } - - // const [v2PairsBalances, fetchingV2PairBalances] = useTokenBalancesWithLoadingIndicator( - // MASTERCHEF_ADDRESS[chainId], - // farms.map((farm) => new Token(chainId, farm.pair, 18, 'LP', 'LP Token')) - // ) - - // if (!fetchingV2PairBalances) { - // for (let i = 0; i < farms.length; ++i) { - // if (v2PairsBalances.hasOwnProperty(farms[i].pair) && farms[i].pool.totalSupply) { - // const totalSupply = Number.parseFloat(farms[i].pool.totalSupply.toFixed()) - // let chefBalance = Number.parseFloat(v2PairsBalances[farms[i].pair].toFixed()) - - // let tvl = 0 - // if (farms[i].pool.token0 === TANGO[chainId].address) { - // const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) - // tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 - // } else if (farms[i].pool.token1 === TANGO[chainId].address) { - // const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) - // tvl = (reserve / totalSupply) * chefBalance * tangoPriceUSD * 2 - // } else if (farms[i].pool.token0 === FLEXUSD.address) { - // const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) - // tvl = (reserve / totalSupply) * chefBalance * 2 - // } else if (farms[i].pool.token1 === FLEXUSD.address) { - // const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) - // tvl = (reserve / totalSupply) * chefBalance * 2 - // } else if (farms[i].pool.token0 === WBCH[chainId].address) { - // const reserve = Number.parseFloat(farms[i].pool.reserves[0].toFixed()) - // tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 - // } else if (farms[i].pool.token1 === WBCH[chainId].address) { - // const reserve = Number.parseFloat(farms[i].pool.reserves[1].toFixed()) - // tvl = (reserve / totalSupply) * chefBalance * bchPriceUSD * 2 - // } - // farms[i].tvl = tvl - // farms[i].chefBalance = chefBalance - // } else { - // farms[i].tvl = '0' - // farms[i].chefBalance = 0 - // } - // } - // } - const positions = usePositions(chainId) - // // const averageBlockTime = useAverageBlockTime() - // const averageBlockTime = 6 - // const masterChefV1TotalAllocPoint = useMasterChefV1TotalAllocPoint() - // const masterChefV1SushiPerBlock = useMasterChefV1SushiPerBlock() - - // const blocksPerDay = 86400 / Number(averageBlockTime) - - const map = (pool) => { - // TODO: Account for fees generated in case of swap pairs, and use standard compounding - // algorithm with the same intervals acrosss chains to account for consistency. - // For lending pairs, what should the equivilent for fees generated? Interest gained? - // How can we include this? - - // TODO: Deal with inconsistencies between properties on subgraph - // pool.owner = pool?.owner || pool?.masterChef - // pool.balance = pool?.balance || pool?.slpBalance - - // const swapPair = swapPairs?.find((pair) => pair.id === pool.pair) - // const kashiPair = kashiPairs?.find((pair) => pair.id === pool.pair) - - // const type = swapPair ? PairType.SWAP : PairType.KASHI - - // const pair = swapPair || kashiPair - - // const blocksPerDay = 15684 // calculated empirically - - // function getRewards() { - // // TODO: Some subgraphs give sushiPerBlock & sushiPerSecond, and mcv2 gives nothing - // // const sushiPerBlock = - // // pool?.owner?.sushiPerBlock / 1e18 || - // // (pool?.owner?.sushiPerSecond / 1e18) * averageBlockTime || - // // masterChefV1SushiPerBlock - - // const rewardPerBlock = (pool.allocPoint / pool.owner.totalAllocPoint) * sushiPerBlock - - // const defaultReward = { - // token: 'TANGO', - // icon: 'https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/0x73BE9c8Edf5e951c9a0762EA2b1DE8c8F38B5e91/logo.png', - // rewardPerBlock, - // rewardPerDay: rewardPerBlock * blocksPerDay, - // rewardPrice: +tangoPriceUSD, - // } - - // let rewards = [defaultReward] - - // if (pool.chef === Chef.MASTERCHEF_V2) { - // // override for mcv2... - // pool.owner.totalAllocPoint = masterChefV1TotalAllocPoint - - // const icon = `https://raw.githubusercontent.com/tangoswap-cash/assets/master/blockchains/smartbch/assets/${getAddress( - // pool.rewarder.rewardToken - // )}/logo.png` - - // const decimals = 10 ** pool.rewardToken.decimals - // // console.log("pool.rewardToken.decimals: ", pool.rewardToken.decimals); - // // console.log("pool.rewardToken.derivedETH: ", pool.rewardToken.derivedETH); - // // console.log("pool.rewarder.rewardPerSecond: ", pool.rewarder.rewardPerSecond); - // // console.log("decimals: ", decimals); - - // if (pool.rewarder.rewardToken !== '0x0000000000000000000000000000000000000000') { - // // console.log("pool.rewarder.rewardPerSecond / decimals: ", pool.rewarder.rewardPerSecond / decimals); - - // const rewardPerBlock = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime - - // // console.log("rewardPerBlock: ", rewardPerBlock); - - // const rewardPerDay = (pool.rewarder.rewardPerSecond / decimals) * averageBlockTime * blocksPerDay - // const rewardPrice = pool.rewardToken.derivedETH * bchPriceUSD - - // // console.log("rewardPrice: ", rewardPrice); - - // const reward = { - // token: pool.rewardToken.symbol, - // icon: icon, - // rewardPerBlock, - // rewardPerDay, - // rewardPrice, - // } - - // rewards[1] = reward - // } - // } - - // return rewards - // } - - // const rewards = getRewards() - - // const balance = Number(pool.balance / 1e18) - - const roiPerBlock = - rewards.reduce((previousValue, currentValue) => { - return previousValue + currentValue.rewardPerBlock * currentValue.rewardPrice - }, 0) / pool.tvl - - const roiPerDay = roiPerBlock * blocksPerDay - const roiPerYear = roiPerDay * 365 - - // console.log("rewards: ", rewards); - // console.log("roiPerBlock: ", roiPerBlock); - // console.log("roiPerDay: ", roiPerDay); - // console.log("roiPerYear: ", roiPerYear); - - const position = positions.find((position) => position.id === pool.id && position.chef === pool.chef) - - return { - ...pool, - ...position, - pair: { - ...pair, - decimals: pair.type === PairType.KASHI ? Number(pair.asset.tokenInfo.decimals) : 18, - type, - }, - balance, - roiPerYear, - rewards, - } - } - const FILTER = { - buy: (gridexList) => gridexList.moneyAmount !== 0, // buscar alguna estadistica que sea unica de los gridex activos y ponerlo aca - portfolio: (gridexList) => gridexList.stockAmount !== 0, // buscar alguna estadistica que sea unica de los gridex propios y ponerlo aca + buy: (gridexList) => gridexList.moneyAmount !== 0, // buscar alguna estadistica que sea unica de los gridex activos para comprar y ponerlo aca + portfolio: (gridexList) => gridexList.index !== -1, // buscar alguna estadistica que sea unica de los gridex propios y ponerlo aca } const data = gridexList - // .filter((farm) => { - // return ( - // (swapPairs && swapPairs.find((pair) => pair.id === farm.pair)) || - // (kashiPairs && kashiPairs.find((pair) => pair.id === farm.pair)) - // ) - // }) - // .map(map) .filter((farm) => { return type in FILTER ? FILTER[type](farm) : true }) @@ -545,6 +232,8 @@ export default function Gridex(): JSX.Element { options, }) + console.log('result:', result); + const basePath = 'gridex/gridex-list' const optionsMenu = [ @@ -569,37 +258,32 @@ export default function Gridex(): JSX.Element { } ] - const [robot, setRobot] = useState([]) - function listRobotsForBuying() { - console.log("sis"); + // const [robot, setRobot] = useState([]) + // function listRobotsForBuying() { + // console.log("sis"); - useEffect(() => { - const robotsCall = async () => { - alert("haciedo la call") - try{ - var robots = await getAllRobots(""); - console.log("Robots:", robots); - if (robots.length == 0) { + // useEffect(() => { + // const robotsCall = async () => { + // alert("haciedo la call") + // try{ + // var robots = await getAllRobots(""); + // console.log("Robots:", robots); + // if (robots.length == 0) { - return alert("No Robots availables") - } - robots.sort(function (a, b) { - return a.highPrice - b.highPrice; - }); - alert("call hecha"); - robotsCall();}catch(e){ - alert("Fallo en la call") - alert(e); - }} + // return alert("No Robots availables") + // } + // robots.sort(function (a, b) { + // return a.highPrice - b.highPrice; + // }); + // alert("call hecha"); + // robotsCall();}catch(e){ + // alert("Fallo en la call") + // alert(e); + // }} - } - , []); - - - - } - - + // } + // , []); + // } return (
@@ -655,25 +339,6 @@ export default function Gridex(): JSX.Element {
: <> -
- { - onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') - }} - value={formattedAmounts[Field.CURRENCY_B]} - onCurrencySelect={handleCurrencyASelect} - onCurrencyBSelect={handleCurrencyBSelect} - currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} - currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - // onOtherCurrencySelect={handleCurrencyBSelect} - // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - showCommonBases - /> -
-
- +
- - { - onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') - }} - value={formattedAmounts[Field.CURRENCY_B]} - onCurrencySelect={handleCurrencyASelect} - onCurrencyBSelect={handleCurrencyBSelect} - currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} - currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - // onOtherCurrencySelect={handleCurrencyBSelect} - // otherCurrency={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - showCommonBases - searchFunction={listRobotsForBuying} - /> ) } + From 7fcda5b12bd988cd9d4aeed69e927cf7af64f773 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Tue, 1 Nov 2022 21:18:22 -0300 Subject: [PATCH 40/83] feat: delete on sale and modify balance --- src/components/BuyRobotsPanel/index.tsx | 3 +- src/features/onsen/GridexMenu.tsx | 21 ++----- src/features/robots/RobotList.tsx | 2 +- src/features/robots/RobotListItemDetails.tsx | 58 +++----------------- src/features/robots/RobotListItems.tsx | 11 ++-- src/pages/gridex/gridex-list/index.tsx | 34 ------------ src/pages/gridex/on-sale/index.tsx | 6 -- 7 files changed, 24 insertions(+), 111 deletions(-) delete mode 100644 src/pages/gridex/on-sale/index.tsx diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 75a4b90b9f..9086b483d8 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -259,10 +259,9 @@ export default function BuyRobotsPanel({ className='h-12 w-10/12 ml-2 text-sm sm:pr-14 sm:text-sm sm:w-1/12 sm:text-center ' onClick={searchFunction} >{i18n._(t`Search`)} - {/*{}*/}
-
+
diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx index 0cb5b61694..cb7d4d11a7 100644 --- a/src/features/onsen/GridexMenu.tsx +++ b/src/features/onsen/GridexMenu.tsx @@ -24,7 +24,7 @@ const defaultOptions = [ divider: true }, { - href: `/gridex/buy-gridex`, + href: `/${basePath}/buy-gridex`, label: 'Buy Tango CMM', exact: true }] @@ -43,7 +43,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { activeClassName="font-bold bg-transparent border rounded text-high-emphesis border-transparent border-gradient-r-blue-pink-dark-900" >
- Your Tango CMM + {i18n._(t` Your Tango CMM`)} ) : ( @@ -51,26 +51,17 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { className="striped-background text-secondary flex items-center justify-between px-2 py-3 md:px-4 md:py-6 text-base font-bold border border-transparent rounded cursor-pointer bg-dark-900 hover:bg-dark-800" onClick={toggleWalletModal} > - Your Tango CMM + {i18n._(t` Your Tango CMM`)} )} - - - Tango CMM on Sale - - - +
- + {i18n._(t`Buy Tango CMM`)} diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index 3d24b7c7e8..cad27489fd 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -60,7 +60,7 @@ const RobotList = ({ stockAddress, moneyAddress, robots, term }) => { hasMore={true} loader={null} > -
+
{items.slice(0, numDisplayed).map((robot, index) => ( ))} diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index c04fe949cd..c4257385b3 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -69,64 +69,24 @@ const RobotListItemDetails = ({stockAddress, moneyAddress, robot }) => { leaveFrom="opacity-100" leaveTo="opacity-0" > - -
-
-
- - -
-
-
-
- - { - setMaxValue(value) - }} - - /> -
-
-
+ + {/* robot.pending !== 0 ? */} {( -
-
+ + -
-
- -
-
+ + + ) } - {/*: ( -
- -
- )*/} +
diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index 7de0e6d360..ab686a0c80 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -13,6 +13,7 @@ import { usePendingSushi } from '../onsen/hooks' import usePendingReward from '../onsen/usePendingReward' import RobotListItemDetails from './RobotListItemDetails' import { PairType } from '../onsen/enum' +import { useState } from 'react' const RobotListItems = ({ stockAddress, moneyAddress, robot, ...rest }) => { const token0 = robot?.stock @@ -22,7 +23,6 @@ const RobotListItems = ({ stockAddress, moneyAddress, robot, ...rest }) => { const rewardAmount = usePendingReward(robot) const { i18n } = useLingui() - return ( { ))}
- ) : ( + ) : (
+
+ {i18n._(t`Stock: ${robot.stockAmount}`)} +
- {i18n._(t`Balance`)} - {/* */} + {i18n._(t`Money: ${robot.stockAmount}`)} +
)}
diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 2721fef91e..0321a04370 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -245,12 +245,6 @@ export default function Gridex(): JSX.Element { { divider: true }, - { - href: `/${basePath}/on-Sale`, - label: 'Tango CMM on Sale' - }, { - divider: true - }, { href: `/gridex/buy-gridex`, label: 'Buy Tango CMM', @@ -258,32 +252,6 @@ export default function Gridex(): JSX.Element { } ] - // const [robot, setRobot] = useState([]) - // function listRobotsForBuying() { - // console.log("sis"); - - // useEffect(() => { - // const robotsCall = async () => { - // alert("haciedo la call") - // try{ - // var robots = await getAllRobots(""); - // console.log("Robots:", robots); - // if (robots.length == 0) { - - // return alert("No Robots availables") - // } - // robots.sort(function (a, b) { - // return a.highPrice - b.highPrice; - // }); - // alert("call hecha"); - // robotsCall();}catch(e){ - // alert("Fallo en la call") - // alert(e); - // }} - - // } - // , []); - // } return ( diff --git a/src/pages/gridex/on-sale/index.tsx b/src/pages/gridex/on-sale/index.tsx deleted file mode 100644 index 649fc2f5d8..0000000000 --- a/src/pages/gridex/on-sale/index.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import React from 'react' -export default function index() { - return
- -
-}; From 95d6cb0862b98f29ddfbcd3fbd0989cf16cf41a8 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Fri, 4 Nov 2022 19:39:38 -0300 Subject: [PATCH 41/83] feat: menu buy list gridex modified --- src/components/BuyRobotsPanel/index.tsx | 2 +- src/features/onsen/GridexMenu.tsx | 13 +- .../index.tsx => gridex-list/buy-gridex.tsx} | 127 ++++++++++++------ src/pages/gridex/gridex-list/index.tsx | 4 +- 4 files changed, 90 insertions(+), 56 deletions(-) rename src/pages/gridex/{buy-gridex/index.tsx => gridex-list/buy-gridex.tsx} (54%) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 9086b483d8..55b696cb65 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -86,7 +86,7 @@ export default function BuyRobotsPanel({ return ( -
+
- - */} - - - - - {/* -
- - - - - - - -
- - -*/} \ No newline at end of file diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index d5c35fb03b..9384d3bcda 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -197,7 +197,7 @@ export default function Gridex(): JSX.Element { } function getRobots() { - getAllRobots(account).then(result => setGridexList(result)) + getAllRobots("").then(result => setGridexList(result)) } console.log(gridexList); @@ -213,9 +213,10 @@ export default function Gridex(): JSX.Element { const positions = usePositions(chainId) const FILTER = { - buy: (gridexList) => gridexList.moneyAmount !== 0, // buscar alguna estadistica que sea unica de los gridex activos para comprar y ponerlo aca - portfolio: (gridexList) => gridexList.index !== -1, // buscar alguna estadistica que sea unica de los gridex propios y ponerlo aca - } + sell: (gridexList) => gridexList.moneyAmount !== 0, + buy: (gridexList) => gridexList.stockAmount !== 0, + portfolio: (gridexList) => gridexList.index !== -1, + } const data = gridexList .filter((farm) => { From d769063d40a9a35a667abccbd7fac0381e251b90 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sat, 5 Nov 2022 19:33:39 -0300 Subject: [PATCH 43/83] feat: ownerAddress --- src/pages/gridex/gridex-list/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 9384d3bcda..eb54e2d309 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -196,7 +196,7 @@ export default function Gridex(): JSX.Element { return allRobots } - function getRobots() { + function getRobots() { getAllRobots("").then(result => setGridexList(result)) } @@ -215,7 +215,7 @@ export default function Gridex(): JSX.Element { const FILTER = { sell: (gridexList) => gridexList.moneyAmount !== 0, buy: (gridexList) => gridexList.stockAmount !== 0, - portfolio: (gridexList) => gridexList.index !== -1, + portfolio: (gridexList) => gridexList.ownerAddr == account, } const data = gridexList From 9f4044509a24a8a9d26b9a706f8ece945049e68b Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Sat, 5 Nov 2022 19:39:33 -0300 Subject: [PATCH 44/83] feat: fix navlink create gridex --- src/pages/gridex/create-gridex/index.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index c7c5c43b7b..9a90f1da78 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -240,8 +240,7 @@ export default function CreateGridexPage() {
- {/* */} - + {i18n._(t`View Your Tango CMM`)} Date: Sat, 5 Nov 2022 19:43:05 -0300 Subject: [PATCH 45/83] feat: new navlink in head --- src/components/Header/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/Header/index.tsx b/src/components/Header/index.tsx index 241f4a32e1..61c5c765d3 100644 --- a/src/components/Header/index.tsx +++ b/src/components/Header/index.tsx @@ -128,7 +128,7 @@ function AppBar(): JSX.Element { )} {chainId && featureEnabled(Feature.GRIDEX, chainId) && ( - + )} {chainId && featureEnabled(Feature.GRIDEX, chainId) && ( - + Date: Tue, 8 Nov 2022 11:24:33 -0300 Subject: [PATCH 46/83] feat: cleaning a bit of code --- src/features/onsen/GridexMenu.tsx | 33 +----------------------- src/pages/gridex/create-gridex/index.tsx | 2 +- src/pages/gridex/gridex-list/index.tsx | 20 ++++---------- 3 files changed, 7 insertions(+), 48 deletions(-) diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx index f79c99ef95..36daf1331b 100644 --- a/src/features/onsen/GridexMenu.tsx +++ b/src/features/onsen/GridexMenu.tsx @@ -69,38 +69,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions}) => { {i18n._(t`Sell Tango CMM`)} - {/* - - {i18n._(t`Past Farms`)} - - */} - - - {/*chainId === ChainId.MAINNET && ( - <> - - - Kashi Farms - - - - - TANGOswap Farms - - - - )*/} +
diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 9a90f1da78..069e345e7b 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -234,7 +234,7 @@ export default function CreateGridexPage() { diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index eb54e2d309..e6727e2c8f 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -218,6 +218,7 @@ export default function Gridex(): JSX.Element { portfolio: (gridexList) => gridexList.ownerAddr == account, } + const data = gridexList .filter((farm) => { return type in FILTER ? FILTER[type](farm) : true @@ -254,6 +255,7 @@ export default function Gridex(): JSX.Element { ] + return ( Tango CMM | Tango - +
- {!isMobile ? +
- : - <> - - - - - } +
Tango CMM list{' '} From 4826bf93f0c792225891679f6b71d3533b02d14d Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Tue, 8 Nov 2022 11:24:59 -0300 Subject: [PATCH 47/83] feat: robotlistitemdetails --- src/features/robots/RobotListItemDetails.tsx | 54 +++++++++++++------- src/pages/gridex/gridex-list/index.tsx | 10 ++-- 2 files changed, 42 insertions(+), 22 deletions(-) diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index c4257385b3..9f3ab92ec7 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -70,27 +70,43 @@ const RobotListItemDetails = ({stockAddress, moneyAddress, robot }) => { leaveTo="opacity-0" > - - {/* robot.pending !== 0 ? */} - {( - - - - - - - ) } - - + { + robot.ownerAddr == account && + ( + + ) + || + robot.filter == 'buy' && + ( + + ) + || + robot.filter == 'sell' && + ( + + ) + } ) } -export default RobotListItemDetails +export default RobotListItemDetails \ No newline at end of file diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index eb54e2d309..f733359493 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -176,7 +176,8 @@ export default function Gridex(): JSX.Element { moneyAmount: null, stockAmount: null, stock: stock, - money: money + money: money, + filter: '' } robot.shortId = fullId.mod(twoPow96).toNumber() robot.ownerAddr = ethers.utils.getAddress(fullId.div(twoPow96).toHexString()) @@ -199,8 +200,6 @@ export default function Gridex(): JSX.Element { function getRobots() { getAllRobots("").then(result => setGridexList(result)) } - - console.log(gridexList); // se necesita Stock amount, Money Amount, highprice, lowprice const type = router.query.filter as string @@ -212,12 +211,17 @@ export default function Gridex(): JSX.Element { const positions = usePositions(chainId) + + const FILTER = { sell: (gridexList) => gridexList.moneyAmount !== 0, buy: (gridexList) => gridexList.stockAmount !== 0, portfolio: (gridexList) => gridexList.ownerAddr == account, } +// gridexList.filter = 'sell' +// gridexList.filter = 'buy' + const data = gridexList .filter((farm) => { return type in FILTER ? FILTER[type](farm) : true From a974ff8b3fb540e067c193bb2257ba55b8dcd879 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Sun, 13 Nov 2022 21:55:51 -0300 Subject: [PATCH 48/83] feat: button styled --- src/features/robots/RobotListItemDetails.tsx | 74 ++++++++++---------- src/pages/gridex/gridex-list/index.tsx | 4 +- 2 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 9f3ab92ec7..6f04a657c9 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -23,7 +23,7 @@ import useMasterChef from '../onsen/useMasterChef' import usePendingReward from '../onsen/usePendingReward' import { useFactoryGridexContract, useGridexMarketContract } from '../../hooks' -const RobotListItemDetails = ({stockAddress, moneyAddress, robot }) => { +const RobotListItemDetails = ({ stockAddress, moneyAddress, robot }) => { const { i18n } = useLingui() const [marketAddress, setMarketAddress] = useState('') @@ -50,15 +50,15 @@ const RobotListItemDetails = ({stockAddress, moneyAddress, robot }) => { const handleBuyRobot = () => { console.log('Borrado') } - + const DeleteRobot = async () => { await marketContract.deleteRobot(robot.index, robot.fullId).then((response) => { addTransaction(response, { summary: `Delete Robot` - }) + }) }); } - + return ( { leaveFrom="opacity-100" leaveTo="opacity-0" > - + { - robot.ownerAddr == account && - ( - - ) - || - robot.filter == 'buy' && - ( - - ) - || - robot.filter == 'sell' && - ( - - ) + + window.location.href.endsWith("filter=portfolio") ? + ( + + ) + : + window.location.href.endsWith("filter=buy") ? + ( + + ) : + window.location.href.endsWith("filter=sell") ? + ( + + ) : null } diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 5623f6805d..c94a384d7e 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -214,8 +214,8 @@ export default function Gridex(): JSX.Element { const FILTER = { - sell: (gridexList) => gridexList.moneyAmount !== 0, - buy: (gridexList) => gridexList.stockAmount !== 0, + sell: (gridexList) => gridexList.moneyAmount !== 0 && gridexList.ownerAddr !== account, + buy: (gridexList) => gridexList.stockAmount !== 0 && gridexList.ownerAddr !== account, portfolio: (gridexList) => gridexList.ownerAddr == account, } From 06f02c4a4036b75787284fb78a788593380e60b4 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sun, 20 Nov 2022 21:30:57 -0300 Subject: [PATCH 49/83] feat: buy function --- src/components/BuyRobotsPanel/index.tsx | 12 +++-- src/features/onsen/GridexMenu.tsx | 9 ++-- src/features/robots/RobotList.tsx | 4 +- src/features/robots/RobotListItemDetails.tsx | 50 ++++++++++++++++---- src/features/robots/RobotListItems.tsx | 8 ++-- src/pages/gridex/gridex-list/index.tsx | 20 ++++---- 6 files changed, 67 insertions(+), 36 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 55b696cb65..92aa84f4a4 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -83,7 +83,7 @@ export default function BuyRobotsPanel({ setModalOpen(false) }, [setModalOpen]) - + const activeLink = String(window.location) return (
@@ -210,10 +210,10 @@ export default function BuyRobotsPanel({
+ {activeLink.endsWith('portfolio') == false &&
<> @@ -241,10 +241,14 @@ export default function BuyRobotsPanel({
{renderBalance ? ( renderBalance(selectedCurrencyBBalance) - ) : ( + ) : activeLink.endsWith('buy') ? ( <> {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} + ) : activeLink.endsWith('sell') && ( + <> + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBalance, 4)} {currency.symbol} + )}
@@ -252,7 +256,7 @@ export default function BuyRobotsPanel({ ) : null}
- + } ) || - robot.filter == 'buy' && + activeLink.endsWith('buy') && ( ) || - robot.filter == 'sell' && + activeLink.endsWith('sell') && ( ) } diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index ab686a0c80..9193b084a6 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -15,7 +15,7 @@ import RobotListItemDetails from './RobotListItemDetails' import { PairType } from '../onsen/enum' import { useState } from 'react' -const RobotListItems = ({ stockAddress, moneyAddress, robot, ...rest }) => { +const RobotListItems = ({ stockAddress, moneyAddress, robot, inputValue, RobotsMap, ...rest }) => { const token0 = robot?.stock const token1 = robot?.money @@ -48,11 +48,11 @@ const RobotListItems = ({ stockAddress, moneyAddress, robot, ...rest }) => {
- $ {String(robot.lowPrice).slice(0,6)} + {String(robot.lowPrice).slice(0,6)}
- $ {String(robot.highPrice).slice(0,6)} + {String(robot.highPrice).slice(0,6)}
{pendingSushi && pendingSushi.greaterThan(ZERO) ? ( @@ -92,7 +92,7 @@ const RobotListItems = ({ stockAddress, moneyAddress, robot, ...rest }) => { )}
- {open && } + {open && } )} diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 5623f6805d..cd21398cc4 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -90,6 +90,7 @@ export default function Gridex(): JSX.Element { const [marketAddress, setMarketAddress] = useState('') const [gridexList, setGridexList] = useState([]) + const [RobotsMap, setRobotsMap] = useState({}) const [currenciesSelected, setCurrenciesSelected] = useState(null); @@ -152,6 +153,8 @@ export default function Gridex(): JSX.Element { const stockContract = useTokenContract(stock?.address) const moneyContract = useTokenContract(money?.address) + + const RobotsMapF = {} async function getAllRobots(onlyForAddr) { const moneyDecimals = await moneyContract?.decimals() @@ -161,7 +164,6 @@ export default function Gridex(): JSX.Element { let allRobots = [] let twoPow96 = BigNumber.from(2).pow(96) let twoPow32 = BigNumber.from(2).pow(32) - const RobotsMap = {} for (var i = 0; i < allRobotsArr?.length; i += 2) { let fullId = allRobotsArr[i] let robot = { @@ -177,7 +179,6 @@ export default function Gridex(): JSX.Element { stockAmount: null, stock: stock, money: money, - filter: '' } robot.shortId = fullId.mod(twoPow96).toNumber() robot.ownerAddr = ethers.utils.getAddress(fullId.div(twoPow96).toHexString()) @@ -192,15 +193,16 @@ export default function Gridex(): JSX.Element { robot.moneyAmount = formatUnits(robot.stockAmountBN, stockDecimals) robot.stockAmount = formatUnits(robot.stockAmountBN, moneyDecimals) allRobots.push(robot) - RobotsMap[robot.fullId] = robot + RobotsMapF[robot.fullId] = robot } + setRobotsMap(RobotsMapF) return allRobots } + function getRobots() { getAllRobots("").then(result => setGridexList(result)) } - // se necesita Stock amount, Money Amount, highprice, lowprice const type = router.query.filter as string @@ -211,7 +213,6 @@ export default function Gridex(): JSX.Element { const positions = usePositions(chainId) - const FILTER = { sell: (gridexList) => gridexList.moneyAmount !== 0, @@ -219,9 +220,6 @@ export default function Gridex(): JSX.Element { portfolio: (gridexList) => gridexList.ownerAddr == account, } -// gridexList.filter = 'sell' -// gridexList.filter = 'buy' - const data = gridexList .filter((farm) => { return type in FILTER ? FILTER[type](farm) : true @@ -257,8 +255,6 @@ export default function Gridex(): JSX.Element { } ] - - return (
- +
@@ -316,7 +312,7 @@ export default function Gridex(): JSX.Element {
- +
) From aedc3fc1bbf07402c4a9685739c5111bcdc8227f Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sun, 20 Nov 2022 22:35:07 -0300 Subject: [PATCH 50/83] feat: design made --- src/components/BuyRobotsPanel/index.tsx | 4 +- src/features/robots/RobotListItemDetails.tsx | 40 +++++++++++++------- src/features/robots/RobotListItems.tsx | 2 +- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 92aa84f4a4..8e0867508a 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -88,7 +88,7 @@ export default function BuyRobotsPanel({ return (
-
+
{/* Second input */} -
+
- {i18n._(t`Money: ${robot.stockAmount}`)} + {i18n._(t`Money: ${robot.moneyAmount}`)}
)} From 08d68379f2c85c5e1190d8f88330a1efd42e7eec Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 01:27:01 -0300 Subject: [PATCH 51/83] feat: responsive design completed --- src/components/BuyRobotsPanel/index.tsx | 2 +- src/features/robots/RobotList.tsx | 12 ++++++------ src/features/robots/RobotListItems.tsx | 26 +++++++++++++++++-------- src/pages/gridex/gridex-list/index.tsx | 2 +- 4 files changed, 26 insertions(+), 16 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 8e0867508a..2ab6116da0 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -86,7 +86,7 @@ export default function BuyRobotsPanel({ const activeLink = String(window.location) return ( -
+
{/* Second input */} -
+
- {activeLink.endsWith('portfolio') == false && +
@@ -234,7 +234,7 @@ export default function BuyRobotsPanel({ onUserInput(val) }} readOnly={readOnly} - className={`w-2/3 h-16 text-base bg-transparent `} + className= {`w-2/3 h-16 text-base bg-transparent `} /> {!hideBalance && currency && selectedCurrencyBBalance ? (
@@ -256,7 +256,7 @@ export default function BuyRobotsPanel({ ) : null}
- } +
- -
- <> - {showMaxButton && ( - - )} - { - // console.log('val:', val); - onUserInput(val) - }} - readOnly={readOnly} - className= {`w-2/3 h-16 text-base bg-transparent `} - /> - {!hideBalance && currency && selectedCurrencyBBalance ? ( -
-
- {renderBalance ? ( - renderBalance(selectedCurrencyBBalance) - ) : activeLink.endsWith('buy') ? ( - <> - {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} - - ) : activeLink.endsWith('sell') && ( - <> - {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBalance, 4)} {currency.symbol} - - )} -
- -
- ) : null} - -
- + )} + { + // console.log('val:', val); + onUserInput(val) + }} + className= {`w-2/3 h-16 text-base bg-transparent `} + /> + {currency && selectedCurrencyBBalance ? ( +
+
+ {activeLink.endsWith('buy') ? ( + <> + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} + + ) : activeLink.endsWith('sell') && ( + <> + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBalance, 4)} {currency.symbol} + + )} +
+ {/* */} +
+ ) : null} + +
+ { robot.ownerAddr == account && ( diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index 3977fd57e9..f3c41e945a 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -15,7 +15,21 @@ import RobotListItemDetails from './RobotListItemDetails' import { PairType } from '../onsen/enum' import { useState } from 'react' -const RobotListItems = ({ stockAddress, moneyAddress, robot, inputValue, RobotsMap, ...rest }) => { +const RobotListItems = ({ + stockAddress, + moneyAddress, + robot, + inputValue, + RobotsMap, + showMaxButton, + onUserInput, + onMax, + currency, + currencyB, + selectedCurrencyBBalance, + selectedCurrencyBalance, + ...rest + }) => { const token0 = robot?.stock const token1 = robot?.money @@ -102,7 +116,19 @@ const RobotListItems = ({ stockAddress, moneyAddress, robot, inputValue, RobotsM )}
- {open && } + {open && } )} diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index bf5c3ab97d..7e7d24b7bb 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -36,7 +36,7 @@ import dynamic from 'next/dynamic' import { getAddress } from '@ethersproject/address' import useFarmRewards from '../../../hooks/useFarmRewards' import usePool from '../../../hooks/usePool' -import { useTokenBalancesWithLoadingIndicator } from '../../../state/wallet/hooks' +import { useCurrencyBalance, useTokenBalancesWithLoadingIndicator } from '../../../state/wallet/hooks' import { usePositions, usePendingSushi } from '../../../features/onsen/hooks' import { useRouter } from 'next/router' import { updateUserFarmFilter } from '../../../state/user/actions' @@ -95,7 +95,6 @@ export default function Gridex(): JSX.Element { const [currenciesSelected, setCurrenciesSelected] = useState(null); const handleCurrencyASelect = (currencyA: Currency) => { - // console.log('currencyA:', currencyA) setCurrenciesSelected({ ...currenciesSelected, currencyA: currencyA }) getRobots() } @@ -257,6 +256,9 @@ export default function Gridex(): JSX.Element { } ] + const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyA ?? undefined) + const selectedCurrencyBBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyB ?? undefined) + // meter la funcion search en el currencySelect en robotspanel // poner abajo de todo el what is Tango CMM // poner el Input Numeric en robotListItemsDetails @@ -279,12 +281,6 @@ export default function Gridex(): JSX.Element {
{ - onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') - }} - value={formattedAmounts[Field.CURRENCY_B]} onCurrencySelect={handleCurrencyASelect} onCurrencyBSelect={handleCurrencyBSelect} currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} @@ -317,7 +313,23 @@ export default function Gridex(): JSX.Element {
- + { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + selectedCurrencyBBalance={selectedCurrencyBBalance} + selectedCurrencyBalance={selectedCurrencyBalance} + />
) From c0da0411fba6c145f3b5125211009a1df6fdd3ef Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 15:51:00 -0300 Subject: [PATCH 55/83] feat: new style was born --- src/pages/gridex/gridex-list/index.tsx | 120 ++++++++++++++++--------- 1 file changed, 79 insertions(+), 41 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index bf5c3ab97d..c3fa62cdd7 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -55,6 +55,9 @@ import { formatCurrencyAmount } from '../../../functions' import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' import BuyRobotsPanel from "../../../components/BuyRobotsPanel" import { Field } from '../../../state/burn/actions' +import Toggle from '../../../components/Toggle' +import Typography from '../../../components/Typography' + function packPrice(price) { var effBits = 1 @@ -147,7 +150,7 @@ export default function Gridex(): JSX.Element { const money = currenciesSelected?.currencyB const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address - + const factoryContract = useFactoryGridexContract() factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) @@ -155,7 +158,7 @@ export default function Gridex(): JSX.Element { const stockContract = useTokenContract(stock?.address) const moneyContract = useTokenContract(money?.address) - + const RobotsMapF = {} async function getAllRobots(onlyForAddr) { @@ -202,8 +205,8 @@ export default function Gridex(): JSX.Element { } - function getRobots() { - getAllRobots("").then(result => setGridexList(result)) + function getRobots() { + getAllRobots("").then(result => setGridexList(result)) } const type = router.query.filter as string @@ -218,15 +221,15 @@ export default function Gridex(): JSX.Element { const FILTER = { sell: (gridexList) => gridexList.moneyAmount !== 0 && gridexList.ownerAddr !== account, - buy: (gridexList) => gridexList.stockAmount !== 0 && gridexList.ownerAddr !== account, - portfolio: (gridexList) => gridexList.ownerAddr == account, - } + buy: (gridexList) => gridexList.stockAmount !== 0 && gridexList.ownerAddr !== account, + portfolio: (gridexList) => gridexList.ownerAddr == account, + } const data = gridexList .filter((farm) => { return type in FILTER ? FILTER[type](farm) : true }) - + const options = { keys: ['pair.id', 'pair.token0.symbol', 'pair.token1.symbol'], threshold: 0.4, @@ -238,7 +241,7 @@ export default function Gridex(): JSX.Element { }) console.log('result:', result); - + const basePath = 'gridex/gridex-list' const optionsMenu = [ @@ -256,6 +259,13 @@ export default function Gridex(): JSX.Element { exact: true } ] + const [marketSelector, toggleMarketSelector] = useState(Boolean) + + function functionSelector() { + window.location.href.endsWith( `?filter=sell`) ? toggleMarketSelector(true) : toggleMarketSelector(false); + window.location.href.endsWith( `?filter=sell`) ? history.pushState(null, '', `?filter=buy`) : history.pushState(null, '',`?filter=sell`) + + } // meter la funcion search en el currencySelect en robotspanel // poner abajo de todo el what is Tango CMM @@ -276,44 +286,72 @@ export default function Gridex(): JSX.Element {
-
- { - onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') - }} - value={formattedAmounts[Field.CURRENCY_B]} - onCurrencySelect={handleCurrencyASelect} - onCurrencyBSelect={handleCurrencyBSelect} - currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} - currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - showCommonBases - searchFunction={getRobots} - /> +
+ { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + value={formattedAmounts[Field.CURRENCY_B]} + onCurrencySelect={handleCurrencyASelect} + onCurrencyBSelect={handleCurrencyBSelect} + currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} + currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} + showCommonBases + searchFunction={getRobots} + /> + + +
+ + + + +
+ +
-
+
+ Tango CMM list{' '} +
+
+ + {i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock.symbol}`} +
-
- - - - + { + toggleMarketSelector(false); + functionSelector() + + } + : () => { + toggleMarketSelector(true) + functionSelector() + + } + } + /> +
+ + {i18n._(t`Sell `)}{stock?.symbol == undefined ? ` Stock` : ` ${money.symbol}`} +
- - -
- Tango CMM list{' '}
From 22d0bd931d621b97047f981c55b20ff848118287 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 16:02:59 -0300 Subject: [PATCH 56/83] feat: bug fixed --- src/pages/gridex/gridex-list/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index eb50567e6c..9c23e7e36b 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -321,7 +321,7 @@ export default function Gridex(): JSX.Element {
- {i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock.symbol}`} + {i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`}
- {i18n._(t`Sell `)}{stock?.symbol == undefined ? ` Stock` : ` ${money.symbol}`} + {i18n._(t`Sell `)}{stock?.symbol == undefined ? ` Stock` : ` ${money?.symbol}`}
From a49854107836ec0f877bf369a178404c625ce9b6 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 21 Nov 2022 16:07:39 -0300 Subject: [PATCH 57/83] feat: design --- src/features/robots/RobotListItemDetails.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 41d2d18b4f..cef3542455 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -130,11 +130,11 @@ const RobotListItemDetails = ({ leaveFrom="opacity-100" leaveTo="opacity-0" > - + <>
<> @@ -154,7 +154,7 @@ const RobotListItemDetails = ({ // console.log('val:', val); onUserInput(val) }} - className= {`w-2/3 h-16 text-base bg-transparent `} + className= {`w-2/3 h-16 text-base bg-transparent`} /> {currency && selectedCurrencyBBalance ? (
From 4515b965605be1ed1e0532f7387779a80d258799 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 16:58:06 -0300 Subject: [PATCH 58/83] feat: toggle working --- src/components/Toggle/gridexToggle.tsx | 49 ++++++++++++++++++++++++++ src/pages/gridex/gridex-list/index.tsx | 18 +++++----- 2 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 src/components/Toggle/gridexToggle.tsx diff --git a/src/components/Toggle/gridexToggle.tsx b/src/components/Toggle/gridexToggle.tsx new file mode 100644 index 0000000000..2ecbda89e5 --- /dev/null +++ b/src/components/Toggle/gridexToggle.tsx @@ -0,0 +1,49 @@ +import React from 'react' +import { Switch } from '@headlessui/react' +import { classNames } from '../../functions' + +export interface ToggleProps { + id?: string + isActive: boolean + toggle: () => void +} + +export default function GridexToggle({ id, isActive, toggle }: ToggleProps) { + return ( + + Use setting + + + + + + ) +} diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 9c23e7e36b..cfd73248fc 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -55,8 +55,8 @@ import { formatCurrencyAmount } from '../../../functions' import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' import BuyRobotsPanel from "../../../components/BuyRobotsPanel" import { Field } from '../../../state/burn/actions' -import Toggle from '../../../components/Toggle' import Typography from '../../../components/Typography' +import GridexToggle from '../../../components/Toggle/gridexToggle' function packPrice(price) { @@ -316,15 +316,17 @@ export default function Gridex(): JSX.Element {
-
+
+
Tango CMM list{' '} -
-
- +
+
+
+ {i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`}
-
- - {i18n._(t`Sell `)}{stock?.symbol == undefined ? ` Stock` : ` ${money?.symbol}`} + + {i18n._(t`Sell `)}{money?.symbol == undefined || stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`}
From e7f3a63ff25543c4f9826bb0f30389630f249cac Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 21 Nov 2022 17:00:27 -0300 Subject: [PATCH 59/83] feat: push --- src/components/BuyRobotsPanel/index.tsx | 8 -------- src/features/onsen/GridexMenu.tsx | 13 +------------ src/features/robots/RobotListItemDetails.tsx | 7 +++---- src/pages/gridex/gridex-list/index.tsx | 17 +++++++++-------- 4 files changed, 13 insertions(+), 32 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 1223a0ac58..9899beaf49 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -16,7 +16,6 @@ import { useActiveWeb3React } from '../../hooks/useActiveWeb3React' import { useCurrencyBalance } from '../../state/wallet/hooks' import { useLingui } from '@lingui/react' import { Search as SearchIcon } from 'react-feather' -import GridexInfo from '../../modals/GridexModal' interface CurrencyInputPanelProps { onCurrencySelect?: (currency: Currency) => void @@ -48,8 +47,6 @@ export default function BuyRobotsPanel({ const [modalOpen, setModalOpen] = useState(false) - const [gridexInfoOpen, setGridexInfoOpen] = useState(false) - const [currencySelector, setCurrencySelector] = useState('') const { account } = useActiveWeb3React() @@ -193,10 +190,6 @@ export default function BuyRobotsPanel({ >{i18n._(t`Search`)}
-
- - -
{ currencySelector == 'A' ? ( - ) : ( diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx index 1ade637159..2f6ae66157 100644 --- a/src/features/onsen/GridexMenu.tsx +++ b/src/features/onsen/GridexMenu.tsx @@ -56,20 +56,9 @@ const GridexMenu = ({ positionsLength, options = defaultOptions, robots }) => { activeClassName="font-bold bg-transparent border rounded text-high-emphesis border-transparent border-gradient-r-blue-pink-dark-900" > - {i18n._(t`Buy Stock`)} + {i18n._(t`CMM Market`)} - - - {i18n._(t`Sell Stock`)} - - - -
) diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index cef3542455..02b68d9cd6 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -61,7 +61,6 @@ const RobotListItemDetails = ({ const stockContract = useTokenContract(stockAddress) const moneyContract = useTokenContract(moneyAddress) - console.log(RobotsMap); async function Buy(robotId) { const moneyDecimals = await moneyContract?.decimals() @@ -130,7 +129,7 @@ const RobotListItemDetails = ({ leaveFrom="opacity-100" leaveTo="opacity-0" > - + <>
- {i18n._(t`Buy Stock from Tango CMM`)} + {i18n._(t`Buy Stock from CMM`)} ) || @@ -205,7 +204,7 @@ const RobotListItemDetails = ({ className={`w-full mx-auto`} style={{ backgroundColor: 'red', color: '#FFF' }} > - {i18n._(t`Sell Money to Tango CMM`)} + {i18n._(t`Sell Money to CMM`)} ) } diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 9c23e7e36b..d3850e3f25 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -57,7 +57,7 @@ import BuyRobotsPanel from "../../../components/BuyRobotsPanel" import { Field } from '../../../state/burn/actions' import Toggle from '../../../components/Toggle' import Typography from '../../../components/Typography' - +import GridexInfo from '../../../modals/GridexModal' function packPrice(price) { var effBits = 1 @@ -99,13 +99,15 @@ export default function Gridex(): JSX.Element { const handleCurrencyASelect = (currencyA: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyA: currencyA }) - getRobots() } + const handleCurrencyBSelect = (currencyB: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyB: currencyB }) getRobots() } + console.log(gridexList); + const { independentField, typedValue, otherTypedValue } = useMintState() const { @@ -118,6 +120,7 @@ export default function Gridex(): JSX.Element { const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) + const [gridexInfoOpen, setGridexInfoOpen] = useState(false) const formattedAmounts = { [independentField]: typedValue, @@ -163,7 +166,6 @@ export default function Gridex(): JSX.Element { async function getAllRobots(onlyForAddr) { const moneyDecimals = await moneyContract?.decimals() const stockDecimals = await stockContract?.decimals() - const provider = new ethers.providers.Web3Provider(window.ethereum) let allRobotsArr = await marketContract?.getAllRobots() let allRobots = [] let twoPow96 = BigNumber.from(2).pow(96) @@ -203,7 +205,6 @@ export default function Gridex(): JSX.Element { return allRobots } - function getRobots() { getAllRobots("").then(result => setGridexList(result)) } @@ -239,8 +240,6 @@ export default function Gridex(): JSX.Element { options, }) - console.log('result:', result); - const basePath = 'gridex/gridex-list' const optionsMenu = [ @@ -270,8 +269,6 @@ export default function Gridex(): JSX.Element { const selectedCurrencyBBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyB ?? undefined) // meter la funcion search en el currencySelect en robotspanel - // poner abajo de todo el what is Tango CMM - // poner el Input Numeric en robotListItemsDetails return ( +
+ + +
) From 92ce350e2d014f4fc71aea17b35126c9d5e85fc6 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 17:03:40 -0300 Subject: [PATCH 60/83] feat: toggle where you wanted --- src/pages/gridex/gridex-list/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index cfd73248fc..1b64bd90f3 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -320,7 +320,7 @@ export default function Gridex(): JSX.Element {
Tango CMM list{' '}
-
+
{i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} From 246104cc562026c1e2c93a397de82af2c6bda01a Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 17:05:42 -0300 Subject: [PATCH 61/83] feat: now responsive toggle where you wanted --- src/pages/gridex/gridex-list/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 4054047d9b..83e97ca15a 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -317,7 +317,7 @@ export default function Gridex(): JSX.Element {
Tango CMM list{' '}
-
+
{i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} From ab13b685547e5cfc85997f13ec1d07ae1f2a4e55 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 17:17:05 -0300 Subject: [PATCH 62/83] feat: toggle already --- src/pages/gridex/gridex-list/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 83e97ca15a..7aba5c9486 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -314,7 +314,7 @@ export default function Gridex(): JSX.Element {
-
+
Tango CMM list{' '}
From d510ee32007759e1aac5aadd225be872a054d738 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 21 Nov 2022 17:19:23 -0300 Subject: [PATCH 63/83] feat: ads --- src/pages/gridex/gridex-list/index.tsx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 83e97ca15a..e788d14c08 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -106,8 +106,6 @@ export default function Gridex(): JSX.Element { getRobots() } - console.log(gridexList); - const { independentField, typedValue, otherTypedValue } = useMintState() const { @@ -200,13 +198,18 @@ export default function Gridex(): JSX.Element { robot.stockAmount = formatUnits(robot.stockAmountBN, moneyDecimals) allRobots.push(robot) RobotsMapF[robot.fullId] = robot + console.log(robot.stock); + console.log(robot.money); } setRobotsMap(RobotsMapF) return allRobots } function getRobots() { - getAllRobots("").then(result => setGridexList(result)) + getAllRobots("").then(result => { + setGridexList(result) + console.log('result:', result) + }) } const type = router.query.filter as string @@ -317,7 +320,7 @@ export default function Gridex(): JSX.Element {
Tango CMM list{' '}
-
+
{i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} From 9e2976f5c9fca30a88770b5d5eea1d7f4ed89819 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Mon, 21 Nov 2022 17:22:10 -0300 Subject: [PATCH 64/83] feat: masd --- src/pages/gridex/gridex-list/index.tsx | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 42490ec3d7..7aba5c9486 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -106,6 +106,8 @@ export default function Gridex(): JSX.Element { getRobots() } + console.log(gridexList); + const { independentField, typedValue, otherTypedValue } = useMintState() const { @@ -198,18 +200,13 @@ export default function Gridex(): JSX.Element { robot.stockAmount = formatUnits(robot.stockAmountBN, moneyDecimals) allRobots.push(robot) RobotsMapF[robot.fullId] = robot - console.log(robot.stock); - console.log(robot.money); } setRobotsMap(RobotsMapF) return allRobots } function getRobots() { - getAllRobots("").then(result => { - setGridexList(result) - console.log('result:', result) - }) + getAllRobots("").then(result => setGridexList(result)) } const type = router.query.filter as string @@ -320,7 +317,7 @@ export default function Gridex(): JSX.Element {
Tango CMM list{' '}
-
+
{i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} From 091925723149d084f0e83ebbd9b491baa8ca1fa7 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Tue, 22 Nov 2022 12:04:58 -0300 Subject: [PATCH 65/83] feat: robot list style filtered --- src/features/robots/RobotList.tsx | 124 ++++++++++++------------- src/features/robots/RobotListItems.tsx | 6 +- 2 files changed, 65 insertions(+), 65 deletions(-) diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index 9ee8be47b5..09e124accb 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -9,20 +9,20 @@ import { useInfiniteScroll } from '../onsen/hooks' import RobotListItems from './RobotListItems' import { isMobile } from 'react-device-detect' -const RobotList = ({ - stockAddress, - moneyAddress, - robots, - term, - inputValue, - RobotsMap, +const RobotList = ({ + stockAddress, + moneyAddress, + robots, + term, + inputValue, + RobotsMap, showMaxButton, - onUserInput, - onMax, - currency, - currencyB, - selectedCurrencyBBalance, - selectedCurrencyBalance + onUserInput, + onMax, + currency, + currencyB, + selectedCurrencyBBalance, + selectedCurrencyBalance }) => { const { items, requestSort, sortConfig } = useSortableData(robots) const { i18n } = useLingui() @@ -30,43 +30,43 @@ const RobotList = ({ return items ? ( <> -
+
requestSort('symbol')} > -
{i18n._(t`Stock/Money`)}
- {sortConfig && - sortConfig.key === 'symbol' && - ((sortConfig.direction === 'ascending' && ) || - (sortConfig.direction === 'descending' && ))} -
-
requestSort('lowPrice')} - > - {i18n._(t`Price to Buy`)} - {sortConfig && - sortConfig.key === 'lowPrice' && - ((sortConfig.direction === 'ascending' && ) || - (sortConfig.direction === 'descending' && ))} -
-
requestSort('highPrice')} - > - {i18n._(t`Price to Sell`)} - {sortConfig && - sortConfig.key === 'highPrice' && - ((sortConfig.direction === 'ascending' && ) || - (sortConfig.direction === 'descending' && ))} -
-
- {i18n._(t`Balance`)} -
+
{i18n._(t`Stock/Money`)}
+ {sortConfig && + sortConfig.key === 'symbol' && + ((sortConfig.direction === 'ascending' && ) || + (sortConfig.direction === 'descending' && ))} +
+
requestSort('lowPrice')} + > + {i18n._(t`Price to Sell`)} + {sortConfig && + sortConfig.key === 'lowPrice' && + ((sortConfig.direction === 'ascending' && ) || + (sortConfig.direction === 'descending' && ))} +
+
requestSort('highPrice')} + > + {i18n._(t`Price to Buy`)} + {sortConfig && + sortConfig.key === 'highPrice' && + ((sortConfig.direction === 'ascending' && ) || + (sortConfig.direction === 'descending' && ))} +
+
+ {i18n._(t`Balance`)} +
{items.slice(0, numDisplayed).map((robot, index) => ( - + ))}
diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index f3c41e945a..e1aac1fe38 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -49,7 +49,7 @@ const RobotListItems = ({ 'w-full sm:px-4 px-2 py-6 text-left rounded cursor-pointer select-none bg-dark-900 text-primary text-sm md:text-lg' )} > -
+
@@ -63,10 +63,10 @@ const RobotListItems = ({
-
+
{String(robot.lowPrice).slice(0,6)}
-
+
{String(robot.highPrice).slice(0,6)}
From fac33e55fdf59e5784962ab1607e938cfbea4454 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Tue, 22 Nov 2022 21:52:05 -0300 Subject: [PATCH 66/83] feat: fix stock amount and money amount --- src/features/robots/RobotListItems.tsx | 12 ++++++------ src/pages/gridex/gridex-list/index.tsx | 15 ++++++++------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index f3c41e945a..93c24cbea9 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -99,15 +99,15 @@ const RobotListItems = ({
) : (
- {robot.stockAmount < 0.01 ? - i18n._(t`Stock: < 0.01`) + {robot.stockAmount < 0.001 ? + i18n._(t`Stock: < 0.001`) : - i18n._(t`Stock: ${(Math.round(robot.stockAmount* 100) / 100).toFixed(3)}`)} + i18n._(t`Stock: ${Number(robot.stockAmount).toFixed(5)}`)}
-
{robot.moneyAmount < 0.01 ? - i18n._(t`Money: < 0.01`) +
{robot.moneyAmount < 0.001 ? + i18n._(t`Money: < 0.001`) : - i18n._(t`Money: ${(Math.round(robot.moneyAmount * 100) / 100).toFixed(3)}`) + i18n._(t`Money: ${Number(robot.moneyAmount).toFixed(5)}`) }
diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 7aba5c9486..b0ff58b267 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -94,26 +94,29 @@ export default function Gridex(): JSX.Element { const [marketAddress, setMarketAddress] = useState('') const [gridexList, setGridexList] = useState([]) const [RobotsMap, setRobotsMap] = useState({}) + const [stock, setStock] = useState(null) + const [money, setMoney] = useState(null) const [currenciesSelected, setCurrenciesSelected] = useState(null); const handleCurrencyASelect = (currencyA: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyA: currencyA }) + console.log(currenciesSelected); + getRobots() } const handleCurrencyBSelect = (currencyB: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyB: currencyB }) + console.log(currenciesSelected); getRobots() } - console.log(gridexList); - const { independentField, typedValue, otherTypedValue } = useMintState() const { dependentField, currencies, - currencyBalances, + currencyBalances, parsedAmounts, noLiquidity } = useDerivedMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) @@ -148,8 +151,6 @@ export default function Gridex(): JSX.Element { const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK - const stock = currenciesSelected?.currencyA - const money = currenciesSelected?.currencyB const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address @@ -196,8 +197,8 @@ export default function Gridex(): JSX.Element { info = info.div(twoPow32) robot.moneyAmountBN = info.mod(twoPow96) robot.stockAmountBN = info.div(twoPow96) - robot.moneyAmount = formatUnits(robot.stockAmountBN, stockDecimals) - robot.stockAmount = formatUnits(robot.stockAmountBN, moneyDecimals) + robot.moneyAmount = formatUnits(robot.moneyAmountBN, moneyDecimals) + robot.stockAmount = formatUnits(robot.stockAmountBN, stockDecimals) allRobots.push(robot) RobotsMapF[robot.fullId] = robot } From e00a660176d24b8d8b6ebad13a86c2354fc12e07 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Sat, 26 Nov 2022 20:11:02 -0300 Subject: [PATCH 67/83] feat: back to old consts --- src/pages/gridex/gridex-list/index.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index b0ff58b267..8fd2bb2158 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -94,8 +94,6 @@ export default function Gridex(): JSX.Element { const [marketAddress, setMarketAddress] = useState('') const [gridexList, setGridexList] = useState([]) const [RobotsMap, setRobotsMap] = useState({}) - const [stock, setStock] = useState(null) - const [money, setMoney] = useState(null) const [currenciesSelected, setCurrenciesSelected] = useState(null); @@ -108,7 +106,7 @@ export default function Gridex(): JSX.Element { const handleCurrencyBSelect = (currencyB: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyB: currencyB }) console.log(currenciesSelected); - getRobots() + getRobots() } const { independentField, typedValue, otherTypedValue } = useMintState() @@ -151,6 +149,9 @@ export default function Gridex(): JSX.Element { const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK + const stock = currenciesSelected?.currencyA + const money = currenciesSelected?.currencyB + const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address From 001c62558a3f7e895e21452879e01de6321025fd Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Sat, 26 Nov 2022 22:57:24 -0300 Subject: [PATCH 68/83] feat: fix bug in options menu --- src/components/Toggle/gridexToggle.tsx | 2 +- src/features/onsen/GridexMenu.tsx | 35 +++++++++++++------------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/src/components/Toggle/gridexToggle.tsx b/src/components/Toggle/gridexToggle.tsx index 2ecbda89e5..d629f0c404 100644 --- a/src/components/Toggle/gridexToggle.tsx +++ b/src/components/Toggle/gridexToggle.tsx @@ -18,7 +18,7 @@ export default function GridexToggle({ id, isActive, toggle }: ToggleProps) { 'relative inline-flex flex-shrink-0 sm:h-8 h-6 w-11 sm:w-20 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none' )} > - Use setting + { @@ -30,36 +31,36 @@ const GridexMenu = ({ positionsLength, options = defaultOptions, robots }) => { return (
- {account ? ( + {account ? (<> - {i18n._(t`Your CMM`)} + {i18n._(t`Your CMM`)} + + +
+ + + + {i18n._(t`CMM Market`)} - ) : ( +
+ ) : ( - {i18n._(t`Your CMM`)} + {i18n._(t`Your CMM`)} )} - -
- - - {i18n._(t`CMM Market`)} - - -
+
) } From 4ab35789b144de85556b89d6f2abf6ccc1e56f4c Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Wed, 30 Nov 2022 12:13:29 -0300 Subject: [PATCH 69/83] feat: disclosure panel now shows the token symbol --- src/features/robots/RobotListItemDetails.tsx | 4 ++-- src/pages/gridex/gridex-list/index.tsx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 02b68d9cd6..2d7015cf23 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -193,7 +193,7 @@ const RobotListItemDetails = ({ className={`w-full mx-auto`} style={{ backgroundColor: '#060', color: '#FFF' }} > - {i18n._(t`Buy Stock from CMM`)} + {i18n._(t`Buy ${robot?.stock?.symbol} from CMM`)} ) || @@ -204,7 +204,7 @@ const RobotListItemDetails = ({ className={`w-full mx-auto`} style={{ backgroundColor: 'red', color: '#FFF' }} > - {i18n._(t`Sell Money to CMM`)} + {i18n._(t`Sell ${robot?.stock?.symbol} to CMM`)} ) } diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 8fd2bb2158..22e32579d3 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -320,7 +320,7 @@ export default function Gridex(): JSX.Element { Tango CMM list{' '}
-
+
{ toggleMarketSelector(false); functionSelector()}:null}> {i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} @@ -342,7 +342,7 @@ export default function Gridex(): JSX.Element { } } /> -
+
{ toggleMarketSelector(false); functionSelector()}:null}> {i18n._(t`Sell `)}{money?.symbol == undefined || stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} From b07b88aec56d5337b0d70a405983c795a82a0acd Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Tue, 13 Dec 2022 14:12:26 -0300 Subject: [PATCH 70/83] feat: epic changes --- src/components/BuyRobotsPanel/index.tsx | 6 +- src/components/Toggle/gridexToggle.tsx | 6 +- src/pages/gridex/gridex-list/index.tsx | 206 ++++++++++++------------ 3 files changed, 109 insertions(+), 109 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index 9899beaf49..f8712be765 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -1,5 +1,5 @@ import { Currency, CurrencyAmount, Pair, Percent, Token } from '@tangoswapcash/sdk' -import React, { ReactNode, useCallback, useState } from 'react' +import React, { ReactNode, useCallback, useEffect, useState } from 'react' import { classNames, formatCurrencyAmount } from '../../functions' import Button from '../Button' @@ -49,8 +49,6 @@ export default function BuyRobotsPanel({ const [currencySelector, setCurrencySelector] = useState('') - const { account } = useActiveWeb3React() - const handleDismissSearch = useCallback(() => { setModalOpen(false) }, [setModalOpen]) @@ -131,7 +129,7 @@ export default function BuyRobotsPanel({ onClick={() => { setCurrencySelector('B') if (onCurrencyBSelect) { - setModalOpen(true) + setModalOpen(true) } }} > diff --git a/src/components/Toggle/gridexToggle.tsx b/src/components/Toggle/gridexToggle.tsx index 2ecbda89e5..0bc4179a99 100644 --- a/src/components/Toggle/gridexToggle.tsx +++ b/src/components/Toggle/gridexToggle.tsx @@ -5,14 +5,14 @@ import { classNames } from '../../functions' export interface ToggleProps { id?: string isActive: boolean - toggle: () => void + onChange: () => void } -export default function GridexToggle({ id, isActive, toggle }: ToggleProps) { +export default function GridexToggle({ id, isActive, onChange }: ToggleProps) { return ( { setCurrenciesSelected({ ...currenciesSelected, currencyA: currencyA }) - console.log(currenciesSelected); - getRobots() + // console.log(currenciesSelected?.currencyA) } const handleCurrencyBSelect = (currencyB: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyB: currencyB }) - console.log(currenciesSelected); - getRobots() + // console.log(currenciesSelected?.currencyB) } + + // useEffect(() => { + // console.log(currenciesSelected) + // }, [currenciesSelected]) const { independentField, typedValue, otherTypedValue } = useMintState() @@ -149,12 +201,15 @@ export default function Gridex(): JSX.Element { const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK - const stock = currenciesSelected?.currencyA - const money = currenciesSelected?.currencyB - + const stock = currenciesSelected.currencyA + const money = currenciesSelected.currencyB + + // console.log("stock: ", stock); + // console.log("money: ", money); + const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address - + const factoryContract = useFactoryGridexContract() factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) @@ -162,54 +217,10 @@ export default function Gridex(): JSX.Element { const stockContract = useTokenContract(stock?.address) const moneyContract = useTokenContract(money?.address) - - const RobotsMapF = {} - - async function getAllRobots(onlyForAddr) { - const moneyDecimals = await moneyContract?.decimals() - const stockDecimals = await stockContract?.decimals() - let allRobotsArr = await marketContract?.getAllRobots() - let allRobots = [] - let twoPow96 = BigNumber.from(2).pow(96) - let twoPow32 = BigNumber.from(2).pow(32) - for (var i = 0; i < allRobotsArr?.length; i += 2) { - let fullId = allRobotsArr[i] - let robot = { - fullId: fullId.toHexString(), - index: i / 2, - shortId: '', - ownerAddr: '', - lowPrice: null, - highPrice: null, - moneyAmountBN: '', - stockAmountBN: '', - moneyAmount: null, - stockAmount: null, - stock: stock, - money: money, - } - robot.shortId = fullId.mod(twoPow96).toNumber() - robot.ownerAddr = ethers.utils.getAddress(fullId.div(twoPow96).toHexString()) - if (onlyForAddr && onlyForAddr != robot.ownerAddr) { continue } - let info = allRobotsArr[i + 1] - robot.lowPrice = formatUnits(unpackPrice(info.mod(twoPow32))) - info = info.div(twoPow32) - robot.highPrice = formatUnits(unpackPrice(info.mod(twoPow32))) - info = info.div(twoPow32) - robot.moneyAmountBN = info.mod(twoPow96) - robot.stockAmountBN = info.div(twoPow96) - robot.moneyAmount = formatUnits(robot.moneyAmountBN, moneyDecimals) - robot.stockAmount = formatUnits(robot.stockAmountBN, stockDecimals) - allRobots.push(robot) - RobotsMapF[robot.fullId] = robot - } - setRobotsMap(RobotsMapF) - return allRobots - } - - function getRobots() { - getAllRobots("").then(result => setGridexList(result)) - } + + useEffect(() => { + // getAllRobots("", currenciesSelected?.currencyA, currenciesSelected?.currencyB, ).then(result => setGridexList(result)) + }, [currenciesSelected]) const type = router.query.filter as string @@ -259,18 +270,25 @@ export default function Gridex(): JSX.Element { exact: true } ] - const [marketSelector, toggleMarketSelector] = useState(Boolean) + const [marketSelector, setMarketSelector] = useState(window.location.href.endsWith( `?filter=sell`)) - function functionSelector() { - window.location.href.endsWith( `?filter=sell`) ? toggleMarketSelector(true) : toggleMarketSelector(false); - window.location.href.endsWith( `?filter=sell`) ? history.pushState(null, '', `?filter=buy`) : history.pushState(null, '',`?filter=sell`) - - } + // function functionSelector() { + // window.location.href.endsWith( `?filter=sell`) ? setMarketSelector(true) : setMarketSelector(false); + // window.location.href.endsWith( `?filter=sell`) ? history.pushState(null, '', `?filter=buy`) : history.pushState(null, '',`?filter=sell`) + // } const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyA ?? undefined) const selectedCurrencyBBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyB ?? undefined) - - // meter la funcion search en el currencySelect en robotspanel + // marketSelector + // ? () => { + // toggleMarketSelector(false); + // functionSelector() + + // } + // : () => { + // toggleMarketSelector(true) + // functionSelector() + // } return (
-
getAllRobots("", currenciesSelected?.currencyA, currenciesSelected?.currencyB).then(result => setGridexList(result))} /> - -
@@ -311,7 +326,6 @@ export default function Gridex(): JSX.Element {
-
@@ -327,20 +341,8 @@ export default function Gridex(): JSX.Element {
{ - toggleMarketSelector(false); - functionSelector() - - } - : () => { - toggleMarketSelector(true) - functionSelector() - - } - } + isActive={marketSelector} + onChange={() => setMarketSelector(!marketSelector)} />
@@ -353,21 +355,21 @@ export default function Gridex(): JSX.Element {
{ - onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') - }} - currency={currenciesSelected && currenciesSelected.currencyA && currenciesSelected.currencyA} - currencyB={currenciesSelected && currenciesSelected.currencyB && currenciesSelected.currencyB} - selectedCurrencyBBalance={selectedCurrencyBBalance} - selectedCurrencyBalance={selectedCurrencyBalance} + stockAddress={stockAddress} + moneyAddress={moneyAddress} + robots={result} + term={term} + inputValue={formattedAmounts[Field.CURRENCY_B]} + RobotsMap={RobotsMap} + showMaxButton={!atMaxAmounts[Field.CURRENCY_B]} + onUserInput={onFieldBInput} + onMax={() => { + onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') + }} + currency={currenciesSelected.currencyA} + currencyB={currenciesSelected.currencyB} + selectedCurrencyBBalance={selectedCurrencyBBalance} + selectedCurrencyBalance={selectedCurrencyBalance} />
From defdb4d69359474c70c302fef1c3e4e1f7fbddab Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 14 Dec 2022 18:18:10 -0300 Subject: [PATCH 71/83] feat: changes in components --- src/features/onsen/GridexMenu.tsx | 3 +- src/features/robots/RobotList.tsx | 13 ++++-- src/features/robots/RobotListItemDetails.tsx | 17 ++++--- src/features/robots/RobotListItems.tsx | 14 ++++-- src/pages/gridex/gridex-list/index.tsx | 48 +++++++++++--------- 5 files changed, 59 insertions(+), 36 deletions(-) diff --git a/src/features/onsen/GridexMenu.tsx b/src/features/onsen/GridexMenu.tsx index ef61148383..db91741e19 100644 --- a/src/features/onsen/GridexMenu.tsx +++ b/src/features/onsen/GridexMenu.tsx @@ -28,6 +28,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions, robots }) => { const { account, chainId } = useActiveWeb3React() const { i18n } = useLingui() const toggleWalletModal = useWalletModalToggle() + const portfolio = window.location.href.endsWith("?filter=portfolio") return (
@@ -46,7 +47,7 @@ const GridexMenu = ({ positionsLength, options = defaultOptions, robots }) => { exact href={`/${basePath}/?filter=buy`} activeClassName="font-bold bg-transparent border rounded text-high-emphesis border-transparent border-gradient-r-blue-pink-dark-900" > - + {i18n._(t`CMM Market`)} diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index 09e124accb..8e4d8ed977 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -22,15 +22,19 @@ const RobotList = ({ currency, currencyB, selectedCurrencyBBalance, - selectedCurrencyBalance + selectedCurrencyBalance, + marketSelector }) => { const { items, requestSort, sortConfig } = useSortableData(robots) const { i18n } = useLingui() const [numDisplayed, setNumDisplayed] = useInfiniteScroll(items) + const sell = marketSelector + const buy = !marketSelector + const portfolio = window.location.href.endsWith("?filter=portfolio") return items ? ( <> -
+
requestSort('symbol')} @@ -42,7 +46,7 @@ const RobotList = ({ (sortConfig.direction === 'descending' && ))}
requestSort('lowPrice')} > {i18n._(t`Price to Sell`)} @@ -52,7 +56,7 @@ const RobotList = ({ (sortConfig.direction === 'descending' && ))}
requestSort('highPrice')} > {i18n._(t`Price to Buy`)} @@ -90,6 +94,7 @@ const RobotList = ({ currencyB={currencyB} selectedCurrencyBBalance={selectedCurrencyBBalance} selectedCurrencyBalance={selectedCurrencyBalance} + marketSelector={marketSelector} /> ))}
diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 2d7015cf23..d36affa7ef 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -37,12 +37,17 @@ const RobotListItemDetails = ({ currency, currencyB, selectedCurrencyBBalance, - selectedCurrencyBalance + selectedCurrencyBalance, + marketSelector }) => { const { i18n } = useLingui() const [marketAddress, setMarketAddress] = useState('') + const sell = marketSelector + const buy = !marketSelector + const portfolio = window.location.href.endsWith("?filter=portfolio") + const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK const factoryContract = useFactoryGridexContract() @@ -132,7 +137,7 @@ const RobotListItemDetails = ({ <>
@@ -158,11 +163,11 @@ const RobotListItemDetails = ({ {currency && selectedCurrencyBBalance ? (
- {activeLink.endsWith('buy') ? ( + {buy ? ( <> {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} - ) : activeLink.endsWith('sell') && ( + ) : sell && ( <> {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBalance, 4)} {currency.symbol} @@ -186,7 +191,7 @@ const RobotListItemDetails = ({ ) || - activeLink.endsWith('buy') && + buy && ( ) || - activeLink.endsWith('sell') && + sell && ( From 6791068bfb354293467eb890d965c5c9cf6edf2f Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Thu, 15 Dec 2022 12:09:43 -0300 Subject: [PATCH 72/83] feat: useeffect working --- src/pages/gridex/gridex-list/index.tsx | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 47297084d7..0ec8e9872d 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -65,7 +65,7 @@ async function getAllRobots(onlyForAddr, moneyContract, stockContract, marketCon const stockDecimals = await stockContract?.decimals() let allRobotsArr = await marketContract?.getAllRobots() - // const RobotsMapF = {} + const RobotsMapF = {} let allRobots = [] let twoPow96 = BigNumber.from(2).pow(96) @@ -99,11 +99,11 @@ async function getAllRobots(onlyForAddr, moneyContract, stockContract, marketCon robot.moneyAmount = formatUnits(robot.moneyAmountBN, moneyDecimals) robot.stockAmount = formatUnits(robot.stockAmountBN, stockDecimals) allRobots.push(robot) - // RobotsMapF[robot.fullId] = robot + RobotsMapF[robot.fullId] = robot } // setRobotsMap(RobotsMapF) - console.log("allRobots: ", allRobots) - return allRobots + // console.log("allRobots: ", allRobots) + return { RobotsMapF, allRobots } } function packPrice(price) { @@ -221,8 +221,11 @@ export default function Gridex() { const [marketSelector, setMarketSelector] = useState(false) useEffect(() => { - // getAllRobots("", currenciesSelected?.currencyA, currenciesSelected?.currencyB, ).then(result => setGridexList(result)) - }, [currenciesSelected]) + getAllRobots("", moneyContract, stockContract, marketContract, currenciesSelected?.currencyA, currenciesSelected?.currencyB).then(result => { + setGridexList(result.allRobots) + setRobotsMap(result.RobotsMapF) + }) + }, [currenciesSelected, moneyContract, stockContract, marketContract]) const type = router.query.filter as string const portfolio = type == 'portfolio' @@ -317,7 +320,10 @@ export default function Gridex() { currency={currenciesSelected.currencyA} currencyB={currenciesSelected.currencyB} showCommonBases - searchFunction={() => getAllRobots("", moneyContract, stockContract, marketContract, currenciesSelected?.currencyA, currenciesSelected?.currencyB).then(result => setGridexList(result))} + searchFunction={() => getAllRobots("", moneyContract, stockContract, marketContract, currenciesSelected?.currencyA, currenciesSelected?.currencyB).then(result => { + setGridexList(result.allRobots) + setRobotsMap(result.RobotsMapF) + })} />
From c2a90565fb8a3269c70612fdb03c9918385f5e0b Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Thu, 15 Dec 2022 12:21:15 -0300 Subject: [PATCH 73/83] feat: button removed --- src/components/BuyRobotsPanel/index.tsx | 8 ++++---- src/pages/gridex/gridex-list/index.tsx | 4 ---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/components/BuyRobotsPanel/index.tsx b/src/components/BuyRobotsPanel/index.tsx index f8712be765..56a8530ecf 100644 --- a/src/components/BuyRobotsPanel/index.tsx +++ b/src/components/BuyRobotsPanel/index.tsx @@ -41,7 +41,7 @@ export default function BuyRobotsPanel({ showCommonBases, pair = null, // used for double token logo hideInput = false, - searchFunction + // searchFunction }: CurrencyInputPanelProps) { const { i18n } = useLingui() @@ -56,7 +56,7 @@ export default function BuyRobotsPanel({ const activeLink = String(window.location) return ( -
+
- + */}
{ currencySelector == 'A' ? ( diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 0ec8e9872d..967c9354f8 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -320,10 +320,6 @@ export default function Gridex() { currency={currenciesSelected.currencyA} currencyB={currenciesSelected.currencyB} showCommonBases - searchFunction={() => getAllRobots("", moneyContract, stockContract, marketContract, currenciesSelected?.currencyA, currenciesSelected?.currencyB).then(result => { - setGridexList(result.allRobots) - setRobotsMap(result.RobotsMapF) - })} />
From 02f4da6e447fbfe3d5a9383ab119eb434aa9d16f Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Thu, 15 Dec 2022 12:51:18 -0300 Subject: [PATCH 74/83] feat: new color gridex toggle --- src/components/Toggle/gridexToggle.tsx | 2 +- src/features/robots/RobotListItemDetails.tsx | 7 +++---- src/pages/gridex/gridex-list/index.tsx | 6 +++--- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/components/Toggle/gridexToggle.tsx b/src/components/Toggle/gridexToggle.tsx index 809f443bcb..f695c0689f 100644 --- a/src/components/Toggle/gridexToggle.tsx +++ b/src/components/Toggle/gridexToggle.tsx @@ -14,7 +14,7 @@ export default function GridexToggle({ id, isActive, onChange }: ToggleProps) { checked={isActive} onChange={onChange} className={classNames( - isActive ? 'bg-blue' : 'bg-[#060]', + isActive ? 'bg-blue' : 'bg-pink', 'relative inline-flex flex-shrink-0 sm:h-8 h-6 w-11 sm:w-20 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none' )} > diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index d36affa7ef..a04f788918 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -195,8 +195,7 @@ const RobotListItemDetails = ({ ( @@ -206,8 +205,8 @@ const RobotListItemDetails = ({ ( diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index 0ec8e9872d..a718ca433b 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -341,10 +341,10 @@ export default function Gridex() {
-
+
Tango CMM list{' '}
-
+
setMarketSelector(false)}> {i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} @@ -356,7 +356,7 @@ export default function Gridex() { onChange={() => setMarketSelector(!marketSelector)} />
setMarketSelector(true)}> - + {i18n._(t`Sell `)}{money?.symbol == undefined || stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`}
From 9fc9edb564f9b4a6d71d1e2736756a755be437bc Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Fri, 16 Dec 2022 12:03:23 -0300 Subject: [PATCH 75/83] feat: falopa --- src/components/PanelLimitPrice/index.tsx | 19 ++++++--- src/features/robots/RobotListItems.tsx | 4 +- src/pages/gridex/create-gridex/index.tsx | 53 +++++++++++++++++------- 3 files changed, 52 insertions(+), 24 deletions(-) diff --git a/src/components/PanelLimitPrice/index.tsx b/src/components/PanelLimitPrice/index.tsx index dbdc4c0426..8f5cb764a1 100644 --- a/src/components/PanelLimitPrice/index.tsx +++ b/src/components/PanelLimitPrice/index.tsx @@ -1,12 +1,18 @@ import { escapeRegExp } from 'lodash' import React, { useState } from 'react' -const PanelLimitPrice = ({label, currencyA, currencyB, minPrice, maxPrice}) => { - const [minPriceValue, setMinPriceValue] = useState('') - const [maxPriceValue, setMaxPriceValue] = useState('') +// const PanelLimitPrice = ({label, currencyA, currencyB, minPrice, maxPrice}) => { +// const [minPriceValue, setMinPriceValue] = useState('') +// const [maxPriceValue, setMaxPriceValue] = useState('') - minPrice(minPriceValue) - maxPrice(maxPriceValue) +// minPrice(minPriceValue) +// maxPrice(maxPriceValue) +const PanelLimitPrice = ({label, currencyA, currencyB, minPriceValue, maxPriceValue, setMinPriceValue, setMaxPriceValue}) => { + // const [minPriceValue, setMinPriceValue] = useState('') + // const [maxPriceValue, setMaxPriceValue] = useState('') + + // minPrice(minPriceValue) + // maxPrice(maxPriceValue) const inputRegex = RegExp(`^\\d*(?:\\\\[.])?\\d*$`) // match escaped "." characters via in a non-capturing group const defaultClassName = 'w-0 p-0 text-2xl bg-transparent' @@ -50,4 +56,5 @@ const PanelLimitPrice = ({label, currencyA, currencyB, minPrice, maxPrice}) => { ) } -export default PanelLimitPrice \ No newline at end of file +export default PanelLimitPrice + diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index cff6dd66c1..9a2c50b713 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -69,11 +69,11 @@ const RobotListItems = ({
- {String(robot.lowPrice).slice(0,6)} + {String(robot.lowPrice).slice(0,8)}
- {String(robot.highPrice).slice(0,6)} + {String(robot.highPrice).slice(0,8)}
{pendingSushi && pendingSushi.greaterThan(ZERO) ? ( diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 649c33d2d6..8d06049d86 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -56,21 +56,39 @@ export default function CreateGridexPage() { const addTransaction = useTransactionAdder() - function minPriceValue(value) { - useMemo(() => { - setMinValue(value) - }, - [value] - ) - } + // const minPriceValue = (value) => { + // useMemo(() => { + // setMinValue(value) + // }, + // [value] + // ) + // } + // function minPriceValue(value) { + // useMemo(() => { + // setMinValue(value) + // }, + // [value] + // ) + // } - function maxPriceValue(value) { - useMemo(() => { - setMaxValue(value) - }, - [value] - ) - } +// const maxPriceValue = (value) => { +// useMemo(() => { +// setMaxValue(value) +// }, +// [value] +// ) +// } + + // function maxPriceValue(value) { + // useMemo(() => { + // setMaxValue(value) + // }, + // [value] + // ) + // } + + // console.log(minValue) + // console.log(maxValue) function packPrice(price) { @@ -140,6 +158,7 @@ export default function CreateGridexPage() { summary: `Create Robot` }) }) + .catch(error => console.log("error", error)) } @@ -301,8 +320,10 @@ export default function CreateGridexPage() {
{
- - + {/* */} + {/* */} + +
} From 95fc7576f44624dbbf41bec200ef2461c62fc9fc Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 19 Dec 2022 21:56:01 -0300 Subject: [PATCH 76/83] feat: build fix --- next.config.js | 5 +++-- src/pages/gridex/create-gridex/index.tsx | 20 ++++++++++++++------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/next.config.js b/next.config.js index 2a09ae1035..4bf45bedcd 100644 --- a/next.config.js +++ b/next.config.js @@ -14,7 +14,7 @@ const withBundleAnalyzer = require('@next/bundle-analyzer')({ // https://nextjs.org/docs/api-reference/next.config.js/introduction // https://docs.sentry.io/platforms/javascript/guides/nextjs/ -const { withSentryConfig } = require('@sentry/nextjs') +// const { withSentryConfig } = require('@sentry/nextjs') const nextConfig = { webpack: (config) => { @@ -154,7 +154,8 @@ const SentryWebpackPluginOptions = { // Make sure adding Sentry options is the last code to run before exporting, to // ensure that your source maps include changes from all other Webpack plugins -module.exports = withSentryConfig(withPWA(withBundleAnalyzer(nextConfig)), SentryWebpackPluginOptions) +// module.exports = withSentryConfig(withPWA(withBundleAnalyzer(nextConfig)), SentryWebpackPluginOptions) +module.exports = withPWA(withBundleAnalyzer(nextConfig)), SentryWebpackPluginOptions // Don't delete this console log, useful to see the config in Vercel deployments console.log('next.config.js', JSON.stringify(module.exports, null, 2)) diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 8d06049d86..3084619e59 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -51,7 +51,7 @@ export default function CreateGridexPage() { const [minValue, setMinValue] = useState() const [maxValue, setMaxValue] = useState() - + const [foundMarketAddress, setFoundMarketAddress] = useState(true) const addTransaction = useTransactionAdder() @@ -90,7 +90,6 @@ export default function CreateGridexPage() { // console.log(minValue) // console.log(maxValue) - function packPrice(price) { var effBits = 1 while(!price.mask(effBits).eq(price)) { @@ -158,7 +157,9 @@ export default function CreateGridexPage() { summary: `Create Robot` }) }) - .catch(error => console.log("error", error)) + .catch(error => { + console.log("error", error) + }) } @@ -370,10 +371,17 @@ export default function CreateGridexPage() { ) : + minValue > maxValue ? ( - + + ) + : + ( + ) }
From 554b0409021876b605a7fc352383be6d887104d5 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Mon, 2 Jan 2023 15:39:44 -0300 Subject: [PATCH 77/83] feat: modal create gridex --- src/features/robots/ConfirmCreateModal.tsx | 120 ++++++++ src/features/robots/CreateModalFooter.tsx | 106 +++++++ src/features/robots/CreateModalHeader.tsx | 163 ++++++++++ .../TransactionConfirmationModal/index.tsx | 2 +- src/pages/gridex/create-gridex/index.tsx | 290 +++++++++++------- src/pages/gridex/gridex-list/index.tsx | 184 ++++++----- 6 files changed, 672 insertions(+), 193 deletions(-) create mode 100644 src/features/robots/ConfirmCreateModal.tsx create mode 100644 src/features/robots/CreateModalFooter.tsx create mode 100644 src/features/robots/CreateModalHeader.tsx diff --git a/src/features/robots/ConfirmCreateModal.tsx b/src/features/robots/ConfirmCreateModal.tsx new file mode 100644 index 0000000000..4217e61fe2 --- /dev/null +++ b/src/features/robots/ConfirmCreateModal.tsx @@ -0,0 +1,120 @@ +import { ChainId, Currency, CurrencyAmount, SmartBCH, Percent, TradeType, Trade as V2Trade } from '@tangoswapcash/sdk' +import React, { useCallback, useMemo } from 'react' +import TransactionConfirmationModal, { + ConfirmationModalContent, + TransactionErrorContent, +} from '../../modals/TransactionConfirmationModal' + +import CreateModalFooter from './CreateModalFooter' +import CreateModalHeader from './CreateModalHeader' + +/** + * Returns true if the trade requires a confirmation of details before we can submit it + * @param args either a pair of V2 trades or a pair of V3 trades + */ +function tradeMeaningfullyDiffers( + ...args: [V2Trade, V2Trade] +): boolean { + const [tradeA, tradeB] = args + return ( + tradeA.tradeType !== tradeB.tradeType || + !tradeA.inputAmount.currency.equals(tradeB.inputAmount.currency) || + !tradeA.inputAmount.equalTo(tradeB.inputAmount) || + !tradeA.outputAmount.currency.equals(tradeB.outputAmount.currency) || + !tradeA.outputAmount.equalTo(tradeB.outputAmount) + ) +} + +export default function ConfirmCreateModal({ + currencyA, + currencyB, + maxValue, + minValue, + stockInputValue, + moneyInputValue, + onConfirm, + onDismiss, + swapErrorMessage, + isOpen, + attemptingTxn, + txHash, + // minerBribe, +}: { + isOpen: boolean + attemptingTxn: boolean + txHash: string | undefined + currencyA: Currency + currencyB: Currency + maxValue: string + minValue: string + stockInputValue: CurrencyAmount + moneyInputValue: CurrencyAmount + onConfirm: () => void + swapErrorMessage: string | undefined + onDismiss: () => void +}) { + const modalHeader = useCallback(() => { + return ( + + ) + }, [currencyA, currencyB, minValue, maxValue, stockInputValue, moneyInputValue]) + + const modalBottom = useCallback(() => { + return ( + + ) + }, [stockInputValue, moneyInputValue, currencyA, currencyB, minValue, maxValue]) + + // const confirmationContent = useCallback(() => { + // return ( + // console.log('dismissed')} + // topContent={modalHeader} + // bottomContent={modalBottom} + // /> + // ) + // }, [currenciesSelected, modalBottom, modalHeader]) + + const pendingText = `Creating a Gridex of ${currencyA?.symbol} + ${currencyB?.symbol}` + + const pendingText2 = `` + + const confirmationContent = useCallback( + () => + swapErrorMessage ? ( + + ) : ( + + ), + [onDismiss, modalBottom, modalHeader, swapErrorMessage] + ) + + return ( + + ) +} diff --git a/src/features/robots/CreateModalFooter.tsx b/src/features/robots/CreateModalFooter.tsx new file mode 100644 index 0000000000..81ad1965a2 --- /dev/null +++ b/src/features/robots/CreateModalFooter.tsx @@ -0,0 +1,106 @@ +import { Currency, TradeType, Trade as V2Trade } from '@tangoswapcash/sdk' +import React, { ReactNode } from 'react' + +import { ButtonError } from '../../components/Button' +import { SwapCallbackError } from '../exchange-v1/swap/styleds' +import { t } from '@lingui/macro' +import { useLingui } from '@lingui/react' + +export default function CreateModalFooter({ +// trade, + onConfirm, + swapErrorMessage, +// disabledConfirm, +}: { +// trade: V2Trade + onConfirm: () => void + swapErrorMessage: ReactNode | undefined +// disabledConfirm: boolean +}) { + const { i18n } = useLingui() + return ( +
+ {/*
+
+
{i18n._(t`Price`)}
+
+ {formatExecutionPrice(trade, showInverted, chainId)} + setShowInverted(!showInverted)} + > + + +
+
+
+
+ {trade.tradeType === TradeType.EXACT_INPUT + ? i18n._(t`Minimum received`) + : i18n._(t`Maximum sold`)} + +
+
+ {trade.tradeType === TradeType.EXACT_INPUT + ? slippageAdjustedAmounts[Field.OUTPUT]?.toSignificant(4) ?? "-" + : slippageAdjustedAmounts[Field.INPUT]?.toSignificant(4) ?? "-"} + + {trade.tradeType === TradeType.EXACT_INPUT + ? trade.outputAmount.currency.symbol + : trade.inputAmount.currency.symbol} + +
+
+
+
+
+ {i18n._(t`Price Impact`)} + +
+
+ +
+
+
+
{i18n._(t`Liquidity Provider Fee`)}
+
+
+ {realizedLPFee + ? realizedLPFee?.toSignificant(6) + + " " + + trade.inputAmount.currency.symbol + : "-"} +
+
+ {archerETHTip && ( +
+
+
{i18n._(t`Miner Tip`)}
+
+
+ {SmartBCH.fromRawAmount(archerETHTip).toFixed(4)} ETH +
+
+ )} +
*/} + + + {i18n._(t`Confirm Creation`)} + + + {swapErrorMessage ? : null} +
+ ) +} diff --git a/src/features/robots/CreateModalHeader.tsx b/src/features/robots/CreateModalHeader.tsx new file mode 100644 index 0000000000..2fdd8cfc48 --- /dev/null +++ b/src/features/robots/CreateModalHeader.tsx @@ -0,0 +1,163 @@ +import { AlertTriangle, ArrowDown, Plus } from 'react-feather' +import { Currency, Percent, TradeType, Trade as V2Trade, CurrencyAmount, JSBI } from '@tangoswapcash/sdk' +import React, { useState } from 'react' +import { isAddress, shortenAddress } from '../../functions' +import { AdvancedSwapDetails } from '../exchange-v1/swap/AdvancedSwapDetails' +import Card from '../../components/Card' +import CurrencyLogo from '../../components/CurrencyLogo' +import { Field } from '../../state/swap/actions' +import { RowBetween, RowFixed} from '../../components/Row' +import TradePrice from '../exchange-v1/swap/TradePrice' +import Typography from '../../components/Typography' +import { t } from '@lingui/macro' +import { useActiveWeb3React } from '../../hooks/useActiveWeb3React' +import { useLingui } from '@lingui/react' +import { useUSDCValue } from '../../hooks/useUSDCPrice' +import { warningSeverity } from '../../functions' +import QuestionHelper from '../../components/QuestionHelper' + +export default function CreateModalHeader({ +currencyA, +currencyB, +maxValue, +minValue, +stockInputValue, +moneyInputValue +}: +{ +currencyA: Currency +currencyB: Currency +maxValue: string +minValue: string +stockInputValue: CurrencyAmount +moneyInputValue: CurrencyAmount +}) { + const { i18n } = useLingui() + + // const [showInverted, setShowInverted] = useState(false) + + // const fiatValueInput = useUSDCValue(trade.inputAmount) + // const fiatValueOutput = useUSDCValue(trade.outputAmount) + + // const priceImpactSeverity = warningSeverity(trade.priceImpact) + + return ( +
+
+
+
+ +
+ {/* {trade.inputAmount.toSignificant(6)} */} + {stockInputValue.toSignificant(6)} +
+
+ {/*
{trade.inputAmount.currency.symbol}
*/} +
{currencyA?.symbol}
+
+
+
+
+ +
+ {moneyInputValue.toSignificant(6)} +
+
+
{currencyB?.symbol}
+
+
+ + {/* */} + + {/* */} +
+ + + {/*
+ {trade.tradeType === TradeType.EXACT_INPUT ? i18n._(t`Minimum received`) : i18n._(t`Maximum sent`)} +
*/} +
+ Price to Buy +
+ +
+ + {/*
+ {trade.tradeType === TradeType.EXACT_INPUT + ? `${trade.minimumAmountOut(allowedSlippage).toSignificant(6)} ${trade.outputAmount.currency.symbol}` + : `${trade.maximumAmountIn(allowedSlippage).toSignificant(6)} ${trade.inputAmount.currency.symbol}`} +
*/} +
+ {minValue} +
+
+
+ + +
{i18n._(t`Price to Sell`)}
+ +
+
+ {maxValue} +
+
+ + {/* {showAcceptChanges ? ( +
+
+
+ +
+ {i18n._(t`Price Updated`)} +
+ + {i18n._(t`Accept`)} + +
+ ) : null} */} + {/*
+ {trade.tradeType === TradeType.EXACT_INPUT ? ( + <> + {i18n._(t`Output is estimated. You will receive at least`)}{' '} + + {trade.minimumAmountOut(allowedSlippage).toSignificant(6)} {trade.outputAmount.currency.symbol} + trade.minimumAmountOut(allowedSlippage).toSignificant(6) trade.outputAmount.currency.symbol + {' '} + {i18n._(t`or the transaction will revert.`)} + + ) : ( + <> + {i18n._(t`Input is estimated. You will sell at most`)}{' '} + + {trade.maximumAmountIn(allowedSlippage).toSignificant(6)} {trade.inputAmount.currency.symbol} + {' '} + {i18n._(t`or the transaction will revert.`)} + + )} +
*/} + + {/* {recipient !== null ? ( +
+ <> + {i18n._(t`Output will be sent to`)}{' '} + {isAddress(recipient) ? shortenAddress(recipient) : recipient} + +
+ ) : null} */} +
+
+ ) +} diff --git a/src/modals/TransactionConfirmationModal/index.tsx b/src/modals/TransactionConfirmationModal/index.tsx index cd549ae93f..2742e2ac69 100644 --- a/src/modals/TransactionConfirmationModal/index.tsx +++ b/src/modals/TransactionConfirmationModal/index.tsx @@ -110,7 +110,7 @@ export const TransactionSubmittedContent: FC = interface ConfirmationModelContentProps { title: string - onDismiss: () => void + onDismiss: () => void topContent: () => React.ReactNode bottomContent: () => React.ReactNode } diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index 3084619e59..bcec6862f0 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -1,10 +1,19 @@ import { ApprovalState, useApproveCallback } from '../../../hooks/useApproveCallback' import { AutoRow, RowBetween } from '../../../components/Row' import Button, { ButtonError } from '../../../components/Button' -import { Currency, CurrencyAmount, Percent, WNATIVE, currencyEquals, SmartBCH, Token } from '@tangoswapcash/sdk' +import { + Currency, + CurrencyAmount, + Percent, + WNATIVE, + currencyEquals, + SmartBCH, + Token, + TradeType, + Trade as V2Trade, +} from '@tangoswapcash/sdk' import { ONE_BIPS, ZERO_PERCENT } from '../../../constants' import React, { useCallback, useEffect, useRef, useState, useMemo } from 'react' -import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' import { calculateGasMargin, calculateSlippageAmount, getGasPrice } from '../../../functions/trade' import { currencyId, maxAmountSpend } from '../../../functions/currency' import { useDerivedMintInfo, useGridexMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' @@ -32,7 +41,12 @@ import { useCurrency } from '../../../hooks/Tokens' import { useIsSwapUnsupported } from '../../../hooks/useIsSwapUnsupported' import { useLingui } from '@lingui/react' import { useRouter } from 'next/router' -import { useApproveSep206Callback, useFactoryGridexContract, useGridexMarketContract, useTokenContract } from '../../../hooks' +import { + useApproveSep206Callback, + useFactoryGridexContract, + useGridexMarketContract, + useTokenContract, +} from '../../../hooks' import { useTransactionAdder } from '../../../state/transactions/hooks' import useTransactionDeadline from '../../../hooks/useTransactionDeadline' import { useWalletModalToggle } from '../../../state/application/hooks' @@ -42,6 +56,16 @@ import { ethers } from 'ethers' import { parseUnits } from '@ethersproject/units' import { formatUnits } from '@ethersproject/units' import { formatCurrencyAmount } from '../../../functions' +import ConfirmCreateModal from '../../../features/robots/ConfirmCreateModal' +import { useDerivedSwapInfo, useSwapState } from '../../../state/swap/hooks' +import { useSwapCallback } from '../../../hooks/useSwapCallback' +import Modal from '../../../components/Modal' +import TransactionConfirmationModal, { + ConfirmationModalContent, + TransactionErrorContent, +} from '../../../modals/TransactionConfirmationModal' +import CreateModalHeader from '../../../features/robots/CreateModalHeader' +import CreateModalFooter from '../../../features/robots/CreateModalFooter' export default function CreateGridexPage() { const { i18n } = useLingui() @@ -49,10 +73,15 @@ export default function CreateGridexPage() { const [currenciesSelected, setCurrenciesSelected] = useState(null) - const [minValue, setMinValue] = useState() - const [maxValue, setMaxValue] = useState() - + const [minValue, setMinValue] = useState('') + const [maxValue, setMaxValue] = useState('') + const [foundMarketAddress, setFoundMarketAddress] = useState(true) + const [isOpen, setIsOpen] = useState(false) + const [attemptingTxn, setAttempingTxn] = useState(false) + const [hash, setHash] = useState("") + + // const [showConfirm, setShowConfirm] = useState(false) const addTransaction = useTransactionAdder() @@ -71,13 +100,13 @@ export default function CreateGridexPage() { // ) // } -// const maxPriceValue = (value) => { -// useMemo(() => { -// setMaxValue(value) -// }, -// [value] -// ) -// } + // const maxPriceValue = (value) => { + // useMemo(() => { + // setMaxValue(value) + // }, + // [value] + // ) + // } // function maxPriceValue(value) { // useMemo(() => { @@ -92,14 +121,14 @@ export default function CreateGridexPage() { function packPrice(price) { var effBits = 1 - while(!price.mask(effBits).eq(price)) { + while (!price.mask(effBits).eq(price)) { effBits += 1 } var twoPow24 = BigNumber.from(2).pow(24) - if(effBits <= 25) { + if (effBits <= 25) { return price } - var shift = effBits-25 + var shift = effBits - 25 var shiftBN = BigNumber.from(2).pow(shift) var low24 = price.div(shiftBN).sub(twoPow24) var high8 = BigNumber.from(shift).add(1).mul(twoPow24) @@ -109,17 +138,14 @@ export default function CreateGridexPage() { const [isExpertMode] = useExpertModeManager() // mint state const { independentField, typedValue, otherTypedValue } = useMintState() - const { - dependentField, - currencyBalances, - parsedAmounts, - noLiquidity, - error, - } = useGridexMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) + const { dependentField, currencyBalances, parsedAmounts, noLiquidity, error } = useGridexMintInfo( + currenciesSelected?.currencyA ?? undefined, + currenciesSelected?.currencyB ?? undefined + ) const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) - - const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" + + const ImplAddr = '0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe' const stock = currenciesSelected?.currencyA const money = currenciesSelected?.currencyB @@ -127,20 +153,22 @@ export default function CreateGridexPage() { const stockAddress = stock?.symbol == 'BCH' ? BCHADDRESS : stock?.address const moneyAddress = money?.symbol == 'BCH' ? BCHADDRESS : money?.address - const stockContract = useTokenContract(stock?.address) - const moneyContract = useTokenContract(money?.address) + const stockContract = useTokenContract(stock?.address) + const moneyContract = useTokenContract(money?.address) const factoryContract = useFactoryGridexContract() - + const [marketAddress, setMarketAddress] = useState() - factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) + factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then((a) => setMarketAddress(a)) const marketContract = useGridexMarketContract(marketAddress) - + async function CreateRobot() { const moneyDecimals = await moneyContract?.decimals() const stockDecimals = await stockContract?.decimals() const stockAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4) const moneyAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4) + console.log(stockAmount); + console.log(moneyAmount); var stockAmountBN = parseUnits(stockAmount, stockDecimals) var moneyAmountBN = parseUnits(moneyAmount, moneyDecimals) var highPrice = packPrice(parseUnits(maxValue)) @@ -148,41 +176,50 @@ export default function CreateGridexPage() { var robotInfo = stockAmountBN.mul(BigNumber.from(2).pow(96)).add(moneyAmountBN) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(highPrice) robotInfo = robotInfo.mul(BigNumber.from(2).pow(32)).add(lowPrice) - + let val = null - val = stockAddress == BCHADDRESS ? {value: stockAmountBN} : moneyAddress == BCHADDRESS ? {value: moneyAmountBN} : null - - await marketContract.createRobot(robotInfo, val).then((response) => { - addTransaction(response, { - summary: `Create Robot` + val = + stockAddress == BCHADDRESS + ? { value: stockAmountBN } + : moneyAddress == BCHADDRESS + ? { value: moneyAmountBN } + : null + + setAttempingTxn(true) + await marketContract + .createRobot(robotInfo, val) + .then((response) => { + setHash(response.hash) + setAttempingTxn(false) + addTransaction(response, { + summary: `Create Robot`, + }) + }) + .catch((error) => { + setHash("") + console.log('error', error) + setAttempingTxn(false) }) - }) - .catch(error => { - console.log("error", error) - }) } - async function createMarket() { - factoryContract.create(stockAddress, moneyAddress, ImplAddr) - .then((response: TransactionResponse) => { + factoryContract.create(stockAddress, moneyAddress, ImplAddr).then((response: TransactionResponse) => { addTransaction(response, { - summary: `Create Market for ${stock?.symbol}-${money?.symbol}` + summary: `Create Market for ${stock?.symbol}-${money?.symbol}`, }) }) } - + async function marketAddressCheck() { let provider = new ethers.providers.Web3Provider(window.ethereum) let code = await provider.getCode(marketAddress) - code == "0x" ? setFoundMarketAddress(false) : setFoundMarketAddress(true) + code == '0x' ? setFoundMarketAddress(false) : setFoundMarketAddress(true) } useEffect(() => { marketAddressCheck() }) - const formattedAmounts = { [independentField]: typedValue, [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', @@ -208,45 +245,40 @@ export default function CreateGridexPage() { }, {} ) - + const handleCurrencyASelect = (currencyA: Currency) => { - setCurrenciesSelected({...currenciesSelected, currencyA: currencyA}) + setCurrenciesSelected({ ...currenciesSelected, currencyA: currencyA }) } const handleCurrencyBSelect = (currencyB: Currency) => { - setCurrenciesSelected({...currenciesSelected, currencyB: currencyB}) + setCurrenciesSelected({ ...currenciesSelected, currencyB: currencyB }) } - - const [stockApprovalState, stockApprove] = useApproveSep206Callback( - parsedAmounts[Field.CURRENCY_A], - marketAddress - ) - const [moneyApprovalState, moneyApprove] = useApproveSep206Callback( - parsedAmounts[Field.CURRENCY_B], - marketAddress - ) - + const [stockApprovalState, stockApprove] = useApproveSep206Callback(parsedAmounts[Field.CURRENCY_A], marketAddress) + + const [moneyApprovalState, moneyApprove] = useApproveSep206Callback(parsedAmounts[Field.CURRENCY_B], marketAddress) + const nativeSymbol = 'BCH' || 'WBCH' const showStockApprove = - chainId && - currenciesSelected?.currencyA && - parsedAmounts[Field.CURRENCY_A] && - stock?.symbol !== nativeSymbol && - (stockApprovalState === ApprovalState.NOT_APPROVED || stockApprovalState === ApprovalState.PENDING) + chainId && + currenciesSelected?.currencyA && + parsedAmounts[Field.CURRENCY_A] && + stock?.symbol !== nativeSymbol && + (stockApprovalState === ApprovalState.NOT_APPROVED || stockApprovalState === ApprovalState.PENDING) const showMoneyApprove = - chainId && - currenciesSelected?.currencyB && - parsedAmounts[Field.CURRENCY_B] && - money?.symbol !== nativeSymbol && - (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) - + chainId && + currenciesSelected?.currencyB && + parsedAmounts[Field.CURRENCY_B] && + money?.symbol !== nativeSymbol && + (moneyApprovalState === ApprovalState.NOT_APPROVED || moneyApprovalState === ApprovalState.PENDING) + const disabled = stockApprovalState === ApprovalState.PENDING || moneyApprovalState === ApprovalState.PENDING - const minValueFilled = minValue !== '' - const maxValueFilled = maxValue !== '' - + const minValueFilled = minValue !== '' ? true : false + const maxValueFilled = maxValue !== '' ? true : false + + return ( <> @@ -293,6 +325,28 @@ export default function CreateGridexPage() { id="add-liquidity-input-tokena" showCommonBases /> +{/* + setIsOpen(false)} + attemptingTxn={attemptingTxn} + hash={hash} + /> */} + + CreateRobot()} + onDismiss={() => setIsOpen(false)} + attemptingTxn={attemptingTxn} + txHash={hash} + swapErrorMessage={undefined} + /> @@ -305,7 +359,6 @@ export default function CreateGridexPage() {
{ -
- {/* */} - {/* */} - - -
+
+ {/* */} + {/* */} + + +
} - - { - !account ? ( + + {!account ? ( - ) - : - error ? ( + ) : error ? ( - ) - : - !foundMarketAddress ? ( + ) : !foundMarketAddress ? ( - ) - : - showStockApprove ? ( + ) : showStockApprove ? ( - ) - : - showMoneyApprove ? ( + ) : showMoneyApprove ? ( - ) - : - !minValueFilled || !maxValueFilled ? ( + ) : !minValueFilled || !maxValueFilled ? ( - ) - : - minValue > maxValue ? - ( - - ) - : - ( - - ) - } + ) : minValue > maxValue ? ( + + ) : ( + + )}
diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index fb81cfbed2..f6d14d5597 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -1,6 +1,12 @@ import { Chef, PairType } from '../../../features/onsen/enum' import { PlusIcon } from '@heroicons/react/outline' -import { useActiveWeb3React, useFactoryGridexContract, useFuse, useGridexMarketContract, useTokenContract } from '../../../hooks' +import { + useActiveWeb3React, + useFactoryGridexContract, + useFuse, + useGridexMarketContract, + useTokenContract, +} from '../../../hooks' import { useAverageBlockTime, useEthPrice, @@ -53,17 +59,18 @@ import { parseUnits } from '@ethersproject/units' import { formatUnits } from '@ethersproject/units' import { formatCurrencyAmount } from '../../../functions' import { useDerivedMintInfo, useMintActionHandlers, useMintState } from '../../../state/mint/hooks' -import BuyRobotsPanel from "../../../components/BuyRobotsPanel" +import BuyRobotsPanel from '../../../components/BuyRobotsPanel' import { Field } from '../../../state/burn/actions' import Typography from '../../../components/Typography' import GridexInfo from '../../../modals/GridexModal' import GridexToggle from '../../../components/Toggle/gridexToggle' import { NextPage } from 'next' +import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' async function getAllRobots(onlyForAddr, moneyContract, stockContract, marketContract, token1, token2) { const moneyDecimals = await moneyContract?.decimals() const stockDecimals = await stockContract?.decimals() - + let allRobotsArr = await marketContract?.getAllRobots() const RobotsMapF = {} @@ -88,7 +95,9 @@ async function getAllRobots(onlyForAddr, moneyContract, stockContract, marketCon } robot.shortId = fullId.mod(twoPow96).toNumber() robot.ownerAddr = ethers.utils.getAddress(fullId.div(twoPow96).toHexString()) - if (onlyForAddr && onlyForAddr != robot.ownerAddr) { continue } + if (onlyForAddr && onlyForAddr != robot.ownerAddr) { + continue + } let info = allRobotsArr[i + 1] robot.lowPrice = formatUnits(unpackPrice(info.mod(twoPow32))) info = info.div(twoPow32) @@ -143,8 +152,8 @@ export default function Gridex() { const [RobotsMap, setRobotsMap] = useState({}) const [currenciesSelected, setCurrenciesSelected] = useState({ - currencyA: null, - currencyB: null + currencyA: null, + currencyB: null, }) const handleCurrencyASelect = (currencyA: Currency) => { @@ -156,25 +165,24 @@ export default function Gridex() { setCurrenciesSelected({ ...currenciesSelected, currencyB: currencyB }) // console.log(currenciesSelected?.currencyB) } - + // useEffect(() => { // console.log(currenciesSelected) // }, [currenciesSelected]) const { independentField, typedValue, otherTypedValue } = useMintState() - const { - dependentField, - currencies, - currencyBalances, - parsedAmounts, - noLiquidity - } = useDerivedMintInfo(currenciesSelected?.currencyA ?? undefined, currenciesSelected?.currencyB ?? undefined) - + const { dependentField, currencies, currencyBalances, parsedAmounts, noLiquidity } = useDerivedMintInfo( + currenciesSelected?.currencyA ?? undefined, + currenciesSelected?.currencyB ?? undefined + ) const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) const [gridexInfoOpen, setGridexInfoOpen] = useState(false) + const [isOpen, setIsOpen] = useState(false) + const [hash, setHash] = useState("") + const formattedAmounts = { [independentField]: typedValue, [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', @@ -199,19 +207,19 @@ export default function Gridex() { {} ) - const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK + const ImplAddr = '0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe' // add this to SDK - const stock = currenciesSelected.currencyA + const stock = currenciesSelected.currencyA const money = currenciesSelected.currencyB - + // console.log("stock: ", stock); // console.log("money: ", money); - + const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address - + const factoryContract = useFactoryGridexContract() - factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) + factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then((a) => setMarketAddress(a)) const marketContract = useGridexMarketContract(marketAddress) @@ -221,7 +229,14 @@ export default function Gridex() { const [marketSelector, setMarketSelector] = useState(false) useEffect(() => { - getAllRobots("", moneyContract, stockContract, marketContract, currenciesSelected?.currencyA, currenciesSelected?.currencyB).then(result => { + getAllRobots( + '', + moneyContract, + stockContract, + marketContract, + currenciesSelected?.currencyA, + currenciesSelected?.currencyB + ).then((result) => { setGridexList(result.allRobots) setRobotsMap(result.RobotsMapF) }) @@ -245,20 +260,19 @@ export default function Gridex() { portfolio: (x) => x.ownerAddr == account, } - const data = gridexList - .filter((x) => { - if (portfolio) { - return x.ownerAddr == account - } - if (buy) { - return x.stockAmount !== 0 && x.ownerAddr !== account - } - if (sell) { - return x.moneyAmount !== 0 && x.ownerAddr !== account - } - return false - // return type in FILTER ? FILTER[type](element) : true - }) + const data = gridexList.filter((x) => { + if (portfolio) { + return x.ownerAddr == account + } + if (buy) { + return x.stockAmount !== 0 && x.ownerAddr !== account + } + if (sell) { + return x.moneyAmount !== 0 && x.ownerAddr !== account + } + return false + // return type in FILTER ? FILTER[type](element) : true + }) const options = { keys: ['pair.id', 'pair.token0.symbol', 'pair.token1.symbol'], @@ -276,27 +290,31 @@ export default function Gridex() { { href: `/${basePath}`, label: 'Your Tango CMM', - exact: true + exact: true, }, { - divider: true + divider: true, }, { href: `/${basePath}/buy-gridex`, label: 'Buy Tango CMM', - exact: true - } + exact: true, + }, ] - // function functionSelector() { // window.location.href.endsWith( `?filter=sell`) ? setMarketSelector(true) : setMarketSelector(false); - // window.location.href.endsWith( `?filter=sell`) ? history.pushState(null, '', `?filter=buy`) : history.pushState(null, '',`?filter=sell`) + // window.location.href.endsWith( `?filter=sell`) ? history.pushState(null, '', `?filter=buy`) : history.pushState(null, '',`?filter=sell`) // } const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyA ?? undefined) const selectedCurrencyBBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyB ?? undefined) + const pendingText = `Creating a Gridex of ${currenciesSelected?.currencyA?.symbol} + ${currenciesSelected?.currencyB?.symbol}` + + const pendingText2 = `` + + return (
+{/* + setIsOpen(false)} + attemptingTxn={attemptingTxn} + hash={hash} + content={confirmationContent} + pendingText={pendingText} + pendingText2={pendingText2} + /> */}
-
- -
- +
+ +
-
-
- Tango CMM list{' '} -
-
-
setMarketSelector(false)}> +
Tango CMM list
+
+
setMarketSelector(false)}> - {i18n._(t`Buy `)}{stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} + {i18n._(t`Buy `)} + {stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`}
setMarketSelector(!marketSelector)} /> -
setMarketSelector(true)}> +
setMarketSelector(true)}> - {i18n._(t`Sell `)}{money?.symbol == undefined || stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`} + {i18n._(t`Sell `)} + {money?.symbol == undefined || stock?.symbol == undefined ? ` Stock` : ` ${stock?.symbol}`}
-
- { onFieldBInput(maxAmounts[Field.CURRENCY_B]?.toExact() ?? '') @@ -379,12 +410,13 @@ export default function Gridex() { selectedCurrencyBalance={selectedCurrencyBalance} marketSelector={marketSelector} /> -
- +
+
) } - From 38688198ecb65507a5997b6dcd69500ce4bf9807 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Wed, 4 Jan 2023 17:09:27 -0300 Subject: [PATCH 78/83] feat: modal gridex list --- src/features/robots/ActionModalFooter.tsx | 106 +++++++++ src/features/robots/ActionModalHeader.tsx | 163 +++++++++++++ src/features/robots/RobotList.tsx | 8 +- src/features/robots/RobotListItemDetails.tsx | 226 ++++++++++--------- src/features/robots/RobotListItems.tsx | 114 +++++----- src/pages/gridex/create-gridex/index.tsx | 66 ++---- src/pages/gridex/gridex-list/index.tsx | 84 +++++-- 7 files changed, 528 insertions(+), 239 deletions(-) create mode 100644 src/features/robots/ActionModalFooter.tsx create mode 100644 src/features/robots/ActionModalHeader.tsx diff --git a/src/features/robots/ActionModalFooter.tsx b/src/features/robots/ActionModalFooter.tsx new file mode 100644 index 0000000000..e111942727 --- /dev/null +++ b/src/features/robots/ActionModalFooter.tsx @@ -0,0 +1,106 @@ +import { Currency, TradeType, Trade as V2Trade } from '@tangoswapcash/sdk' +import React, { ReactNode } from 'react' + +import { ButtonError } from '../../components/Button' +import { SwapCallbackError } from '../exchange-v1/swap/styleds' +import { t } from '@lingui/macro' +import { useLingui } from '@lingui/react' + +export default function CreateModalFooter({ +// trade, + onConfirm, + swapErrorMessage, +// disabledConfirm, +}: { +// trade: V2Trade + onConfirm: () => void + swapErrorMessage: ReactNode | undefined +// disabledConfirm: boolean +}) { + const { i18n } = useLingui() + return ( +
+ {/*
+
+
{i18n._(t`Price`)}
+
+ {formatExecutionPrice(trade, showInverted, chainId)} + setShowInverted(!showInverted)} + > + + +
+
+
+
+ {trade.tradeType === TradeType.EXACT_INPUT + ? i18n._(t`Minimum received`) + : i18n._(t`Maximum sold`)} + +
+
+ {trade.tradeType === TradeType.EXACT_INPUT + ? slippageAdjustedAmounts[Field.OUTPUT]?.toSignificant(4) ?? "-" + : slippageAdjustedAmounts[Field.INPUT]?.toSignificant(4) ?? "-"} + + {trade.tradeType === TradeType.EXACT_INPUT + ? trade.outputAmount.currency.symbol + : trade.inputAmount.currency.symbol} + +
+
+
+
+
+ {i18n._(t`Price Impact`)} + +
+
+ +
+
+
+
{i18n._(t`Liquidity Provider Fee`)}
+
+
+ {realizedLPFee + ? realizedLPFee?.toSignificant(6) + + " " + + trade.inputAmount.currency.symbol + : "-"} +
+
+ {archerETHTip && ( +
+
+
{i18n._(t`Miner Tip`)}
+
+
+ {SmartBCH.fromRawAmount(archerETHTip).toFixed(4)} ETH +
+
+ )} +
*/} + + + {i18n._(t`Confirm Action`)} + + + {swapErrorMessage ? : null} +
+ ) +} diff --git a/src/features/robots/ActionModalHeader.tsx b/src/features/robots/ActionModalHeader.tsx new file mode 100644 index 0000000000..bd1f4b8ca0 --- /dev/null +++ b/src/features/robots/ActionModalHeader.tsx @@ -0,0 +1,163 @@ +import { AlertTriangle, ArrowDown, Plus } from 'react-feather' +import { Currency, Percent, TradeType, Trade as V2Trade, CurrencyAmount, JSBI } from '@tangoswapcash/sdk' +import React, { useState } from 'react' +import { isAddress, shortenAddress } from '../../functions' +import { AdvancedSwapDetails } from '../exchange-v1/swap/AdvancedSwapDetails' +import Card from '../../components/Card' +import CurrencyLogo from '../../components/CurrencyLogo' +import { Field } from '../../state/swap/actions' +import { RowBetween, RowFixed} from '../../components/Row' +import TradePrice from '../exchange-v1/swap/TradePrice' +import Typography from '../../components/Typography' +import { t } from '@lingui/macro' +import { useActiveWeb3React } from '../../hooks/useActiveWeb3React' +import { useLingui } from '@lingui/react' +import { useUSDCValue } from '../../hooks/useUSDCPrice' +import { warningSeverity } from '../../functions' +import QuestionHelper from '../../components/QuestionHelper' + +export default function CreateModalHeader({ +currencyA, +currencyB, +// maxValue, +// minValue, +// stockInputValue, +// moneyInputValue +}: +{ +currencyA: Currency +currencyB: Currency +// maxValue: string +// minValue: string +// stockInputValue: CurrencyAmount +// moneyInputValue: CurrencyAmount +}) { + const { i18n } = useLingui() + + // const [showInverted, setShowInverted] = useState(false) + + // const fiatValueInput = useUSDCValue(trade.inputAmount) + // const fiatValueOutput = useUSDCValue(trade.outputAmount) + + // const priceImpactSeverity = warningSeverity(trade.priceImpact) + + return ( +
+
+
+
+ +
+ {/* {trade.inputAmount.toSignificant(6)} */} + stockInputValue.toSignificant(6) +
+
+ {/*
{trade.inputAmount.currency.symbol}
*/} +
{currencyA?.symbol}
+
+
+
+
+ +
+ moneyInputValue.toSignificant(6) +
+
+
{currencyB?.symbol}
+
+
+ + {/* */} + + {/* */} +
+ + + {/*
+ {trade.tradeType === TradeType.EXACT_INPUT ? i18n._(t`Minimum received`) : i18n._(t`Maximum sent`)} +
*/} +
+ Price to Buy +
+ +
+ + {/*
+ {trade.tradeType === TradeType.EXACT_INPUT + ? `${trade.minimumAmountOut(allowedSlippage).toSignificant(6)} ${trade.outputAmount.currency.symbol}` + : `${trade.maximumAmountIn(allowedSlippage).toSignificant(6)} ${trade.inputAmount.currency.symbol}`} +
*/} +
+ minValue +
+
+
+ + +
{i18n._(t`Price to Sell`)}
+ +
+
+ maxValue +
+
+ + {/* {showAcceptChanges ? ( +
+
+
+ +
+ {i18n._(t`Price Updated`)} +
+ + {i18n._(t`Accept`)} + +
+ ) : null} */} + {/*
+ {trade.tradeType === TradeType.EXACT_INPUT ? ( + <> + {i18n._(t`Output is estimated. You will receive at least`)}{' '} + + {trade.minimumAmountOut(allowedSlippage).toSignificant(6)} {trade.outputAmount.currency.symbol} + trade.minimumAmountOut(allowedSlippage).toSignificant(6) trade.outputAmount.currency.symbol + {' '} + {i18n._(t`or the transaction will revert.`)} + + ) : ( + <> + {i18n._(t`Input is estimated. You will sell at most`)}{' '} + + {trade.maximumAmountIn(allowedSlippage).toSignificant(6)} {trade.inputAmount.currency.symbol} + {' '} + {i18n._(t`or the transaction will revert.`)} + + )} +
*/} + + {/* {recipient !== null ? ( +
+ <> + {i18n._(t`Output will be sent to`)}{' '} + {isAddress(recipient) ? shortenAddress(recipient) : recipient} + +
+ ) : null} */} +
+
+ ) +} diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index 8e4d8ed977..d16c4d0a84 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -23,7 +23,10 @@ const RobotList = ({ currencyB, selectedCurrencyBBalance, selectedCurrencyBalance, - marketSelector + marketSelector, + setModalOpen, + setActionToCall, + value }) => { const { items, requestSort, sortConfig } = useSortableData(robots) const { i18n } = useLingui() @@ -95,6 +98,9 @@ const RobotList = ({ selectedCurrencyBBalance={selectedCurrencyBBalance} selectedCurrencyBalance={selectedCurrencyBalance} marketSelector={marketSelector} + setModalOpen={setModalOpen} + setActionToCall={setActionToCall} + value={value} /> ))}
diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index a04f788918..54ff8ce2b1 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -1,5 +1,13 @@ import { ApprovalState, useApproveCallback } from '../../hooks/useApproveCallback' -import { ChainId, CurrencyAmount, JSBI, MASTERCHEF_ADDRESS, MASTERCHEF_V2_ADDRESS, Token, ZERO } from '@tangoswapcash/sdk' +import { + ChainId, + CurrencyAmount, + JSBI, + MASTERCHEF_ADDRESS, + MASTERCHEF_V2_ADDRESS, + Token, + ZERO, +} from '@tangoswapcash/sdk' import { Disclosure, Transition } from '@headlessui/react' import React, { useState } from 'react' @@ -25,33 +33,35 @@ import { useFactoryGridexContract, useGridexMarketContract, useTokenContract } f import { parseUnits } from '@ethersproject/units' import { FiatValue } from '../../components/BuyRobotsPanel/FiatValue' -const RobotListItemDetails = ({ - stockAddress, - moneyAddress, - robot, - inputValue, - RobotsMap, - showMaxButton, - onUserInput, - onMax, - currency, - currencyB, - selectedCurrencyBBalance, +const RobotListItemDetails = ({ + stockAddress, + moneyAddress, + robot, + inputValue, + RobotsMap, + showMaxButton, + onUserInput, + onMax, + currency, + currencyB, + selectedCurrencyBBalance, selectedCurrencyBalance, - marketSelector - }) => { - + marketSelector, + setModalOpen, + setActionToCall, + value +}) => { const { i18n } = useLingui() const [marketAddress, setMarketAddress] = useState('') const sell = marketSelector const buy = !marketSelector - const portfolio = window.location.href.endsWith("?filter=portfolio") + const portfolio = window.location.href.endsWith('?filter=portfolio') - const ImplAddr = "0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe" // add this to SDK + const ImplAddr = '0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe' // add this to SDK const factoryContract = useFactoryGridexContract() - factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then(a => setMarketAddress(a)) + factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then((a) => setMarketAddress(a)) const marketContract = useGridexMarketContract(marketAddress) @@ -75,20 +85,19 @@ const RobotListItemDetails = ({ var moneyBalance = moneyContract.balanceOf(account) var stockDelta = moneyDelta / robot.highPrice - - if(moneyDeltaBN > moneyBalance) { + + if (moneyDeltaBN > moneyBalance) { alert(`You don't have enough money.`) - } else if(stockDelta > robot.stockAmount) { + } else if (stockDelta > robot.stockAmount) { alert('Tango CMM has not enough stock') } - + let val = null - val = moneyAddress == '0x0000000000000000000000000000000000002711' ? {value: moneyDeltaBN} : null - - await marketContract.buyFromRobot(robotId, moneyDeltaBN, val) - .then((response) => { + val = moneyAddress == '0x0000000000000000000000000000000000002711' ? { value: moneyDeltaBN } : null + + await marketContract.buyFromRobot(robotId, moneyDeltaBN, val).then((response) => { addTransaction(response, { - summary: `Buy Stock from ${(robot.fullId).slice(0,8)}...` + summary: `Buy Stock from ${robot.fullId.slice(0, 8)}...`, }) }) } @@ -103,27 +112,24 @@ const RobotListItemDetails = ({ if (stockDeltaBN > stockBalance) { alert(`You don't have enough stock.`) - } else if(moneyDelta > robot.moneyAmount) { + } else if (moneyDelta > robot.moneyAmount) { alert(`Tango CMM has not enough money`) } - let val = null; - val = stockAddress == '0x0000000000000000000000000000000000002711' ? {value: stockDeltaBN} : null - + let val = null + val = stockAddress == '0x0000000000000000000000000000000000002711' ? { value: stockDeltaBN } : null + await marketContract.sellToRobot(robotId, stockDeltaBN, val) } - const DeleteRobot = async () => { await marketContract.deleteRobot(robot.index, robot.fullId).then((response) => { addTransaction(response, { - summary: `Delete Robot` + summary: `Delete Robot`, }) - }); + }) } - const activeLink = String(window.location) - return ( - - <> -
- <> - {showMaxButton && ( - - )} - { - // console.log('val:', val); - onUserInput(val) - }} - className= {`w-2/3 h-16 text-base bg-transparent`} - /> - {currency && selectedCurrencyBBalance ? ( -
-
- {buy ? ( - <> - {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} - - ) : sell && ( - <> - {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBalance, 4)} {currency.symbol} - - )} + + <> +
+ <> + {showMaxButton && ( + + )} + { + // console.log('val:', val); + onUserInput(val) + }} + className={`w-2/3 h-16 text-base bg-transparent`} + /> + {currency && selectedCurrencyBBalance ? ( +
+
+ {buy ? ( + <> + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBBalance, 4)} {currencyB.symbol} + + ) : ( + sell && ( + <> + {i18n._(t`Balance:`)} {formatCurrencyAmount(selectedCurrencyBalance, 4)} {currency.symbol} + + ) + )} +
+ {/* */}
- {/* */} -
- ) : null} - -
- - { - robot.ownerAddr == account && - ( - - ) - || - buy && - ( + ) : null} + +
+ + {(robot.ownerAddr == account && ( + + )) || + (buy && ( - ) - || - sell && - ( + )) || + (sell && ( - ) - } + ))} ) } -export default RobotListItemDetails \ No newline at end of file +export default RobotListItemDetails diff --git a/src/features/robots/RobotListItems.tsx b/src/features/robots/RobotListItems.tsx index 9a2c50b713..8a23912cd2 100644 --- a/src/features/robots/RobotListItems.tsx +++ b/src/features/robots/RobotListItems.tsx @@ -15,37 +15,38 @@ import RobotListItemDetails from './RobotListItemDetails' import { PairType } from '../onsen/enum' import { useState } from 'react' -const RobotListItems = ({ - stockAddress, +const RobotListItems = ({ + stockAddress, moneyAddress, - robot, + robot, inputValue, - RobotsMap, - showMaxButton, - onUserInput, - onMax, - currency, - currencyB, - selectedCurrencyBBalance, + RobotsMap, + showMaxButton, + onUserInput, + onMax, + currency, + currencyB, + selectedCurrencyBBalance, selectedCurrencyBalance, marketSelector, + setModalOpen, + setActionToCall, + value, ...rest - }) => { +}) => { const token0 = robot?.stock const token1 = robot?.money const sell = marketSelector const buy = !marketSelector - const portfolio = window.location.href.endsWith("?filter=portfolio") + const portfolio = window.location.href.endsWith('?filter=portfolio') const pendingSushi = usePendingSushi(robot) const rewardAmount = usePendingReward(robot) const { i18n } = useLingui() return ( - + {({ open }) => ( <> -
+
- +

{token0?.symbol}

-

- {token1?.symbol} -

+

{token1?.symbol}

-
-
- {String(robot.lowPrice).slice(0,8)} +
+ {String(robot.lowPrice).slice(0, 8)}
-
-
- {String(robot.highPrice).slice(0,8)} -
+
+
{String(robot.highPrice).slice(0, 8)}
{pendingSushi && pendingSushi.greaterThan(ZERO) ? (
- {robot?.rewards?.map((reward, i) => (
- ) : (
-
- {robot.stockAmount < 0.001 ? - i18n._(t`Stock: < 0.001`) - : - i18n._(t`Stock: ${Number(robot.stockAmount).toFixed(5)}`)} -
-
{robot.moneyAmount < 0.001 ? - i18n._(t`Money: < 0.001`) - : - i18n._(t`Money: ${Number(robot.moneyAmount).toFixed(5)}`) - } -
- + ) : ( +
+
+ {robot.stockAmount < 0.001 + ? i18n._(t`Stock: < 0.001`) + : i18n._(t`Stock: ${Number(robot.stockAmount).toFixed(5)}`)} +
+
+ {robot.moneyAmount < 0.001 + ? i18n._(t`Money: < 0.001`) + : i18n._(t`Money: ${Number(robot.moneyAmount).toFixed(5)}`)} +
- )}
- {open && } + {open && ( + + )} )} - - ) } diff --git a/src/pages/gridex/create-gridex/index.tsx b/src/pages/gridex/create-gridex/index.tsx index bcec6862f0..42e9ff9457 100644 --- a/src/pages/gridex/create-gridex/index.tsx +++ b/src/pages/gridex/create-gridex/index.tsx @@ -79,46 +79,10 @@ export default function CreateGridexPage() { const [foundMarketAddress, setFoundMarketAddress] = useState(true) const [isOpen, setIsOpen] = useState(false) const [attemptingTxn, setAttempingTxn] = useState(false) - const [hash, setHash] = useState("") - - // const [showConfirm, setShowConfirm] = useState(false) + const [hash, setHash] = useState('') const addTransaction = useTransactionAdder() - // const minPriceValue = (value) => { - // useMemo(() => { - // setMinValue(value) - // }, - // [value] - // ) - // } - // function minPriceValue(value) { - // useMemo(() => { - // setMinValue(value) - // }, - // [value] - // ) - // } - - // const maxPriceValue = (value) => { - // useMemo(() => { - // setMaxValue(value) - // }, - // [value] - // ) - // } - - // function maxPriceValue(value) { - // useMemo(() => { - // setMaxValue(value) - // }, - // [value] - // ) - // } - - // console.log(minValue) - // console.log(maxValue) - function packPrice(price) { var effBits = 1 while (!price.mask(effBits).eq(price)) { @@ -156,19 +120,21 @@ export default function CreateGridexPage() { const stockContract = useTokenContract(stock?.address) const moneyContract = useTokenContract(money?.address) const factoryContract = useFactoryGridexContract() - + const [marketAddress, setMarketAddress] = useState() factoryContract.getAddress(stockAddress, moneyAddress, ImplAddr).then((a) => setMarketAddress(a)) const marketContract = useGridexMarketContract(marketAddress) + const provider = new ethers.providers.Web3Provider(window?.ethereum) + async function CreateRobot() { const moneyDecimals = await moneyContract?.decimals() const stockDecimals = await stockContract?.decimals() const stockAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_A], 4) const moneyAmount = formatCurrencyAmount(parsedAmounts[Field.CURRENCY_B], 4) - console.log(stockAmount); - console.log(moneyAmount); + console.log(stockAmount) + console.log(moneyAmount) var stockAmountBN = parseUnits(stockAmount, stockDecimals) var moneyAmountBN = parseUnits(moneyAmount, moneyDecimals) var highPrice = packPrice(parseUnits(maxValue)) @@ -184,7 +150,7 @@ export default function CreateGridexPage() { : moneyAddress == BCHADDRESS ? { value: moneyAmountBN } : null - + setAttempingTxn(true) await marketContract .createRobot(robotInfo, val) @@ -194,9 +160,12 @@ export default function CreateGridexPage() { addTransaction(response, { summary: `Create Robot`, }) + // provider.waitForTransaction(response.hash).then(() => { + // setHash(undefined) + // }) }) .catch((error) => { - setHash("") + setHash('') console.log('error', error) setAttempingTxn(false) }) @@ -278,7 +247,6 @@ export default function CreateGridexPage() { const minValueFilled = minValue !== '' ? true : false const maxValueFilled = maxValue !== '' ? true : false - return ( <> @@ -325,13 +293,6 @@ export default function CreateGridexPage() { id="add-liquidity-input-tokena" showCommonBases /> -{/* - setIsOpen(false)} - attemptingTxn={attemptingTxn} - hash={hash} - /> */} CreateRobot()} - onDismiss={() => setIsOpen(false)} + onDismiss={() => { + setIsOpen(false) + setHash(undefined) + }} attemptingTxn={attemptingTxn} txHash={hash} swapErrorMessage={undefined} diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index f6d14d5597..859735dc6c 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -35,7 +35,7 @@ import Container from '../../../components/Container' import FarmList from '../../../features/onsen/FarmList' import Head from 'next/head' import Menu from '../../../features/onsen/FarmMenu' -import React, { useEffect, useMemo, useState } from 'react' +import React, { useEffect, useMemo, useState, useCallback } from 'react' import Search from '../../../components/Search' import { classNames, maxAmountSpend } from '../../../functions' import dynamic from 'next/dynamic' @@ -66,6 +66,8 @@ import GridexInfo from '../../../modals/GridexModal' import GridexToggle from '../../../components/Toggle/gridexToggle' import { NextPage } from 'next' import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' +import ActionModalHeader from "../../../features/robots/ActionModalHeader" +import ActionModalFooter from "../../../features/robots/ActionModalFooter" async function getAllRobots(onlyForAddr, moneyContract, stockContract, marketContract, token1, token2) { const moneyDecimals = await moneyContract?.decimals() @@ -158,18 +160,12 @@ export default function Gridex() { const handleCurrencyASelect = (currencyA: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyA: currencyA }) - // console.log(currenciesSelected?.currencyA) } const handleCurrencyBSelect = (currencyB: Currency) => { setCurrenciesSelected({ ...currenciesSelected, currencyB: currencyB }) - // console.log(currenciesSelected?.currencyB) } - // useEffect(() => { - // console.log(currenciesSelected) - // }, [currenciesSelected]) - const { independentField, typedValue, otherTypedValue } = useMintState() const { dependentField, currencies, currencyBalances, parsedAmounts, noLiquidity } = useDerivedMintInfo( @@ -180,9 +176,16 @@ export default function Gridex() { const { onFieldAInput, onFieldBInput } = useMintActionHandlers(noLiquidity) const [gridexInfoOpen, setGridexInfoOpen] = useState(false) + const [modalOpen, setModalOpen] = useState(false) + + const [attemptingTxn, setAttempingTxn] = useState(false) + const [isOpen, setIsOpen] = useState(false) const [hash, setHash] = useState("") + const [actionToCall, setActionToCall] = useState() + // "buy" "sell" "delte" + const formattedAmounts = { [independentField]: typedValue, [dependentField]: noLiquidity ? otherTypedValue : parsedAmounts[dependentField]?.toSignificant(6) ?? '', @@ -207,14 +210,11 @@ export default function Gridex() { {} ) - const ImplAddr = '0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe' // add this to SDK + const ImplAddr = '0x8dEa2aB783258207f6db13F8b43a4Bda7B03bFBe' const stock = currenciesSelected.currencyA const money = currenciesSelected.currencyB - // console.log("stock: ", stock); - // console.log("money: ", money); - const stockAddress = stock?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : stock?.address const moneyAddress = money?.symbol == 'BCH' ? '0x0000000000000000000000000000000000002711' : money?.address @@ -301,19 +301,54 @@ export default function Gridex() { exact: true, }, ] - - // function functionSelector() { - // window.location.href.endsWith( `?filter=sell`) ? setMarketSelector(true) : setMarketSelector(false); - // window.location.href.endsWith( `?filter=sell`) ? history.pushState(null, '', `?filter=buy`) : history.pushState(null, '',`?filter=sell`) - // } - + const selectedCurrencyBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyA ?? undefined) const selectedCurrencyBBalance = useCurrencyBalance(account ?? undefined, currenciesSelected?.currencyB ?? undefined) - const pendingText = `Creating a Gridex of ${currenciesSelected?.currencyA?.symbol} + ${currenciesSelected?.currencyB?.symbol}` - + const pendingText = `This is the action modal` const pendingText2 = `` + const value = (data) => { + } + + const modalHeader = useCallback(() => { + return ( + + ) + }, [currenciesSelected?.currencyA, currenciesSelected?.currencyB]) + + const modalBottom = useCallback(() => { + return ( + + ) + }, [currenciesSelected?.currencyA, currenciesSelected?.currencyB, actionToCall, setActionToCall]) + + const confirmationContent = useCallback( + () => + ( + { + setModalOpen(false) + setHash(undefined) + }} + topContent={modalHeader} + bottomContent={modalBottom} + /> + ), + [modalBottom, modalHeader] + ) + return (
-{/* + setIsOpen(false)} + isOpen={modalOpen} + onDismiss={() => setModalOpen(false)} attemptingTxn={attemptingTxn} hash={hash} content={confirmationContent} pendingText={pendingText} pendingText2={pendingText2} - /> */} + />
@@ -409,6 +444,9 @@ export default function Gridex() { selectedCurrencyBBalance={selectedCurrencyBBalance} selectedCurrencyBalance={selectedCurrencyBalance} marketSelector={marketSelector} + setModalOpen={setModalOpen} + setActionToCall={setActionToCall} + value={value} />
diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 54ff8ce2b1..3ff807a180 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -48,8 +48,13 @@ const RobotListItemDetails = ({ selectedCurrencyBalance, marketSelector, setModalOpen, + setIndex, + setRobotId, + setRobotHighPrice, + setRobotLowPrice, + setRobotStockAmount, + setRobotMoneyAmount, setActionToCall, - value }) => { const { i18n } = useLingui() const [marketAddress, setMarketAddress] = useState('') @@ -77,52 +82,7 @@ const RobotListItemDetails = ({ const stockContract = useTokenContract(stockAddress) const moneyContract = useTokenContract(moneyAddress) - async function Buy(robotId) { - const moneyDecimals = await moneyContract?.decimals() - var moneyDelta = inputValue //*1.0 - var moneyDeltaBN = parseUnits(inputValue, moneyDecimals) - var robot = RobotsMap[robotId] - var moneyBalance = moneyContract.balanceOf(account) - - var stockDelta = moneyDelta / robot.highPrice - - if (moneyDeltaBN > moneyBalance) { - alert(`You don't have enough money.`) - } else if (stockDelta > robot.stockAmount) { - alert('Tango CMM has not enough stock') - } - - let val = null - val = moneyAddress == '0x0000000000000000000000000000000000002711' ? { value: moneyDeltaBN } : null - - await marketContract.buyFromRobot(robotId, moneyDeltaBN, val).then((response) => { - addTransaction(response, { - summary: `Buy Stock from ${robot.fullId.slice(0, 8)}...`, - }) - }) - } - - async function Sell(robotId) { - const stockDecimals = await stockContract?.decimals() - var stockDelta = inputValue - var stockDeltaBN = parseUnits(inputValue, stockDecimals) - var robot = RobotsMap[robotId] - var moneyDelta = stockDelta * robot.lowPrice - var stockBalance = stockContract.balanceOf(account) - - if (stockDeltaBN > stockBalance) { - alert(`You don't have enough stock.`) - } else if (moneyDelta > robot.moneyAmount) { - alert(`Tango CMM has not enough money`) - } - - let val = null - val = stockAddress == '0x0000000000000000000000000000000000002711' ? { value: stockDeltaBN } : null - - await marketContract.sellToRobot(robotId, stockDeltaBN, val) - } - - const DeleteRobot = async () => { + async function DeleteRobot() { await marketContract.deleteRobot(robot.index, robot.fullId).then((response) => { addTransaction(response, { summary: `Delete Robot`, @@ -199,7 +159,9 @@ const RobotListItemDetails = ({ color="red" onClick={() => { setModalOpen(true) - value(DeleteRobot) + setActionToCall("delete") + setIndex(robot?.index) + setRobotId(robot?.fullId) }} className={`w-full mx-auto`} > @@ -210,7 +172,11 @@ const RobotListItemDetails = ({
) } diff --git a/src/features/robots/ActionModalHeader.tsx b/src/features/robots/ActionGridexModal/ActionModalHeader.tsx similarity index 88% rename from src/features/robots/ActionModalHeader.tsx rename to src/features/robots/ActionGridexModal/ActionModalHeader.tsx index bd1f4b8ca0..34a595dfa9 100644 --- a/src/features/robots/ActionModalHeader.tsx +++ b/src/features/robots/ActionGridexModal/ActionModalHeader.tsx @@ -1,20 +1,20 @@ import { AlertTriangle, ArrowDown, Plus } from 'react-feather' import { Currency, Percent, TradeType, Trade as V2Trade, CurrencyAmount, JSBI } from '@tangoswapcash/sdk' import React, { useState } from 'react' -import { isAddress, shortenAddress } from '../../functions' -import { AdvancedSwapDetails } from '../exchange-v1/swap/AdvancedSwapDetails' -import Card from '../../components/Card' -import CurrencyLogo from '../../components/CurrencyLogo' -import { Field } from '../../state/swap/actions' -import { RowBetween, RowFixed} from '../../components/Row' -import TradePrice from '../exchange-v1/swap/TradePrice' -import Typography from '../../components/Typography' +import { isAddress, shortenAddress } from '../../../functions' +import { AdvancedSwapDetails } from '../../exchange-v1/swap/AdvancedSwapDetails' +import Card from '../../../components/Card' +import CurrencyLogo from '../../../components/CurrencyLogo' +import { Field } from '../../../state/swap/actions' +import { RowBetween, RowFixed} from '../../../components/Row' +import TradePrice from '../../exchange-v1/swap/TradePrice' +import Typography from '../../../components/Typography' import { t } from '@lingui/macro' -import { useActiveWeb3React } from '../../hooks/useActiveWeb3React' +import { useActiveWeb3React } from '../../../hooks/useActiveWeb3React' import { useLingui } from '@lingui/react' -import { useUSDCValue } from '../../hooks/useUSDCPrice' -import { warningSeverity } from '../../functions' -import QuestionHelper from '../../components/QuestionHelper' +import { useUSDCValue } from '../../../hooks/useUSDCPrice' +import { warningSeverity } from '../../../functions' +import QuestionHelper from '../../../components/QuestionHelper' export default function CreateModalHeader({ currencyA, diff --git a/src/features/robots/ConfirmCreateModal.tsx b/src/features/robots/CreateGridexModal/ConfirmCreateModal.tsx similarity index 80% rename from src/features/robots/ConfirmCreateModal.tsx rename to src/features/robots/CreateGridexModal/ConfirmCreateModal.tsx index 4217e61fe2..e9438c395a 100644 --- a/src/features/robots/ConfirmCreateModal.tsx +++ b/src/features/robots/CreateGridexModal/ConfirmCreateModal.tsx @@ -3,28 +3,11 @@ import React, { useCallback, useMemo } from 'react' import TransactionConfirmationModal, { ConfirmationModalContent, TransactionErrorContent, -} from '../../modals/TransactionConfirmationModal' +} from '../../../modals/TransactionConfirmationModal' import CreateModalFooter from './CreateModalFooter' import CreateModalHeader from './CreateModalHeader' -/** - * Returns true if the trade requires a confirmation of details before we can submit it - * @param args either a pair of V2 trades or a pair of V3 trades - */ -function tradeMeaningfullyDiffers( - ...args: [V2Trade, V2Trade] -): boolean { - const [tradeA, tradeB] = args - return ( - tradeA.tradeType !== tradeB.tradeType || - !tradeA.inputAmount.currency.equals(tradeB.inputAmount.currency) || - !tradeA.inputAmount.equalTo(tradeB.inputAmount) || - !tradeA.outputAmount.currency.equals(tradeB.outputAmount.currency) || - !tradeA.outputAmount.equalTo(tradeB.outputAmount) - ) -} - export default function ConfirmCreateModal({ currencyA, currencyB, diff --git a/src/features/robots/CreateModalFooter.tsx b/src/features/robots/CreateGridexModal/CreateModalFooter.tsx similarity index 97% rename from src/features/robots/CreateModalFooter.tsx rename to src/features/robots/CreateGridexModal/CreateModalFooter.tsx index 81ad1965a2..9a02c90430 100644 --- a/src/features/robots/CreateModalFooter.tsx +++ b/src/features/robots/CreateGridexModal/CreateModalFooter.tsx @@ -1,8 +1,8 @@ import { Currency, TradeType, Trade as V2Trade } from '@tangoswapcash/sdk' import React, { ReactNode } from 'react' -import { ButtonError } from '../../components/Button' -import { SwapCallbackError } from '../exchange-v1/swap/styleds' +import { ButtonError } from '../../../components/Button' +import { SwapCallbackError } from '../../exchange-v1/swap/styleds' import { t } from '@lingui/macro' import { useLingui } from '@lingui/react' diff --git a/src/features/robots/CreateModalHeader.tsx b/src/features/robots/CreateGridexModal/CreateModalHeader.tsx similarity index 88% rename from src/features/robots/CreateModalHeader.tsx rename to src/features/robots/CreateGridexModal/CreateModalHeader.tsx index 2fdd8cfc48..25ca0b1d2e 100644 --- a/src/features/robots/CreateModalHeader.tsx +++ b/src/features/robots/CreateGridexModal/CreateModalHeader.tsx @@ -1,20 +1,20 @@ import { AlertTriangle, ArrowDown, Plus } from 'react-feather' import { Currency, Percent, TradeType, Trade as V2Trade, CurrencyAmount, JSBI } from '@tangoswapcash/sdk' import React, { useState } from 'react' -import { isAddress, shortenAddress } from '../../functions' -import { AdvancedSwapDetails } from '../exchange-v1/swap/AdvancedSwapDetails' -import Card from '../../components/Card' -import CurrencyLogo from '../../components/CurrencyLogo' -import { Field } from '../../state/swap/actions' -import { RowBetween, RowFixed} from '../../components/Row' -import TradePrice from '../exchange-v1/swap/TradePrice' -import Typography from '../../components/Typography' +import { isAddress, shortenAddress } from '../../../functions' +import { AdvancedSwapDetails } from '../../exchange-v1/swap/AdvancedSwapDetails' +import Card from '../../../components/Card' +import CurrencyLogo from '../../../components/CurrencyLogo' +import { Field } from '../../../state/swap/actions' +import { RowBetween, RowFixed} from '../../../components/Row' +import TradePrice from '../../exchange-v1/swap/TradePrice' +import Typography from '../../../components/Typography' import { t } from '@lingui/macro' -import { useActiveWeb3React } from '../../hooks/useActiveWeb3React' +import { useActiveWeb3React } from '../../../hooks/useActiveWeb3React' import { useLingui } from '@lingui/react' -import { useUSDCValue } from '../../hooks/useUSDCPrice' -import { warningSeverity } from '../../functions' -import QuestionHelper from '../../components/QuestionHelper' +import { useUSDCValue } from '../../../hooks/useUSDCPrice' +import { warningSeverity } from '../../../functions' +import QuestionHelper from '../../../components/QuestionHelper' export default function CreateModalHeader({ currencyA, diff --git a/src/features/robots/RobotList.tsx b/src/features/robots/RobotList.tsx index e089a54e33..d29cc48179 100644 --- a/src/features/robots/RobotList.tsx +++ b/src/features/robots/RobotList.tsx @@ -27,10 +27,6 @@ const RobotList = ({ setModalOpen, setIndex, setRobotId, - setRobotHighPrice, - setRobotLowPrice, - setRobotStockAmount, - setRobotMoneyAmount, setActionToCall }) => { const { items, requestSort, sortConfig } = useSortableData(robots) @@ -106,10 +102,6 @@ const RobotList = ({ setModalOpen={setModalOpen} setIndex={setIndex} setRobotId={setRobotId} - setRobotHighPrice={setRobotHighPrice} - setRobotLowPrice={setRobotLowPrice} - setRobotStockAmount={setRobotStockAmount} - setRobotMoneyAmount={setRobotMoneyAmount} setActionToCall={setActionToCall} /> ))} diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index 3ff807a180..d510f1e992 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -9,7 +9,7 @@ import { ZERO, } from '@tangoswapcash/sdk' import { Disclosure, Transition } from '@headlessui/react' -import React, { useState } from 'react' +import React, { useCallback, useEffect, useState } from 'react' import Button, { ButtonError } from '../../components/Button' import Dots from '../../components/Dots' @@ -30,7 +30,7 @@ import { usePendingSushi, useUserInfo } from '../onsen/hooks' import useMasterChef from '../onsen/useMasterChef' import usePendingReward from '../onsen/usePendingReward' import { useFactoryGridexContract, useGridexMarketContract, useTokenContract } from '../../hooks' -import { parseUnits } from '@ethersproject/units' +import { parseEther, parseUnits } from '@ethersproject/units' import { FiatValue } from '../../components/BuyRobotsPanel/FiatValue' const RobotListItemDetails = ({ @@ -50,10 +50,6 @@ const RobotListItemDetails = ({ setModalOpen, setIndex, setRobotId, - setRobotHighPrice, - setRobotLowPrice, - setRobotStockAmount, - setRobotMoneyAmount, setActionToCall, }) => { const { i18n } = useLingui() @@ -79,15 +75,53 @@ const RobotListItemDetails = ({ const [maxValue, setMaxValue] = useState(robot.maxValue ? robot.maxValue : 0) const [minValue, setMinValue] = useState(robot.minValue ? robot.minValue : 0) + const [errorCode, setErrorCode] = useState(null) + const stockContract = useTokenContract(stockAddress) const moneyContract = useTokenContract(moneyAddress) - async function DeleteRobot() { - await marketContract.deleteRobot(robot.index, robot.fullId).then((response) => { - addTransaction(response, { - summary: `Delete Robot`, - }) - }) + // variable to check if the user has enough balance || cmm has enough balance + async function balanceStatus() { + if (sell) { + const stockDecimals = await stockContract?.decimals() + const stockDelta = inputValue + const stockDeltaBN = parseUnits(inputValue, stockDecimals) + const moneyDelta = stockDelta * robot.lowPrice + const stockBalance = await stockContract?.balanceOf(account) + + if (stockDeltaBN.gt(stockBalance)) { + return 0 // "Error: You don't have enough stock." + } else if (moneyDelta > robot.moneyAmount) { + return 1 // "Error: CMM has not enough money" + } else { + return 'No error' + } + } + if (buy) { + const moneyDecimals = await moneyContract?.decimals() + const moneyDelta = inputValue + const moneyDeltaBN = parseUnits(inputValue, moneyDecimals) + const moneyBalance = await moneyContract.balanceOf(account) + const stockDelta = moneyDelta / robot.highPrice + + if (moneyDeltaBN.gt(moneyBalance)) { + return 0 // alert(`You don't have enough money.`) + } else if (stockDelta > robot.stockAmount) { + return 1 //alert('Tango CMM has not enough stock') + } + } + } + + useEffect(() => { + balanceStatus().then((r) => setErrorCode(r)) + }, [balanceStatus, currency, currencyB, marketSelector, inputValue]) + + + const openTx = (action: string) => { + setModalOpen(true) + setActionToCall(action) + setIndex(robot?.index) + setRobotId(robot?.fullId) } return ( @@ -157,42 +191,40 @@ const RobotListItemDetails = ({ {(robot.ownerAddr == account && ( )) || - (buy && ( - + ) : errorCode == 1 ? ( + + ) : ( + + ))) || + (sell && errorCode == 0 ? ( + + ) : errorCode == 1 ? ( + - )) || - (sell && ( + ) : (
- setModalOpen(false)} attemptingTxn={attemptingTxn} hash={hash} - content={confirmationContent} - pendingText={pendingText} - pendingText2={pendingText2} + currencyA={currenciesSelected?.currencyA} + currencyB={currenciesSelected?.currencyB} + onConfirm={onConfirm} + txErrorMsg={txErrorMsg} + onDismiss={onDismiss} + stockContract={stockContract} + moneyContract={moneyContract} + marketContract={marketContract} + factoryContract={factoryContract} + index={index} + robotId={index} />
@@ -546,10 +502,6 @@ export default function Gridex() { setModalOpen={setModalOpen} setIndex={setIndex} setRobotId={setRobotId} - setRobotHighPrice={setRobotHighPrice} - setRobotLowPrice={setRobotLowPrice} - setRobotStockAmount={setRobotStockAmount} - setRobotMoneyAmount={setRobotMoneyAmount} setActionToCall={setActionToCall} />
From 0ec476fb57ebb15275443c5de3996c5e1812d3c1 Mon Sep 17 00:00:00 2001 From: Santiago Benegas Date: Fri, 13 Jan 2023 14:25:41 -0300 Subject: [PATCH 81/83] feat: actionmodal confirmationModal fixed --- .../ActionGridexModal/ActionConfirmModal.tsx | 132 ++++++++++-------- .../ActionGridexModal/ActionModalHeader.tsx | 71 ++++++---- src/pages/gridex/gridex-list/index.tsx | 47 ++++--- 3 files changed, 147 insertions(+), 103 deletions(-) diff --git a/src/features/robots/ActionGridexModal/ActionConfirmModal.tsx b/src/features/robots/ActionGridexModal/ActionConfirmModal.tsx index a74a31c53b..9d999a1146 100644 --- a/src/features/robots/ActionGridexModal/ActionConfirmModal.tsx +++ b/src/features/robots/ActionGridexModal/ActionConfirmModal.tsx @@ -2,73 +2,89 @@ import ActionModalHeader from '../../../features/robots/ActionGridexModal/Action import ActionModalFooter from '../../../features/robots/ActionGridexModal/ActionModalFooter' import TransactionConfirmationModal, { ConfirmationModalContent } from '../../../modals/TransactionConfirmationModal' import React, { useCallback } from 'react' -import { Currency } from '@tangoswapcash/sdk' +import { Currency, Percent, TradeType, Trade as V2Trade, CurrencyAmount, JSBI } from '@tangoswapcash/sdk' import { Contract } from '@ethersproject/contracts' export default function ConfirmCreateModal({ -isOpen, -attemptingTxn, -hash, -currencyA, -currencyB, -onConfirm, -txErrorMsg, -onDismiss, -stockContract, -moneyContract, -marketContract, -factoryContract, -index, -robotId + isOpen, + attemptingTxn, + hash, + currencyA, + currencyB, + onConfirm, + txErrorMsg, + onDismiss, + stockContract, + moneyContract, + marketContract, + factoryContract, + index, + robotId, + currentMarket, + inputValue, + robots, + }: { - isOpen: boolean - attemptingTxn: boolean - hash: string | undefined - currencyA: Currency - currencyB: Currency - onConfirm: () => void - txErrorMsg: string | undefined - onDismiss: () => void - stockContract: Contract - moneyContract: Contract - marketContract: Contract - factoryContract: Contract - index: number | string - robotId: number | string -}) { -const pendingText = `This is the action modal` -const pendingText2 = `` + isOpen: boolean + attemptingTxn: boolean + hash: string | undefined + currencyA: Currency + currencyB: Currency + onConfirm: () => void + txErrorMsg: string | undefined + onDismiss: () => void + stockContract: Contract + moneyContract: Contract + marketContract: Contract + factoryContract: Contract + index: number | string + robotId: number | string + currentMarket: boolean + inputValue: CurrencyAmount + robots: object -const modalHeader = useCallback(() => { - return -}, [currencyA, currencyB]) -const modalBottom = useCallback(() => { - return -}, [modalHeader, currencyA, currencyB, stockContract, moneyContract, marketContract, factoryContract, index, robotId]) +}) { + const pendingText = `This is the action modal` + const pendingText2 = `` -const confirmationContent = useCallback( - () => ( - { + return - ), - [modalBottom, modalHeader] -) + }, [currencyA, currencyB, currentMarket, inputValue, robots, index]) -return ( + const modalBottom = useCallback(() => { + return + }, [modalHeader, currencyA, currencyB, stockContract, moneyContract, marketContract, factoryContract, index, robotId]) + + const confirmationContent = useCallback( + () => ( + + ), + [modalBottom, modalHeader] + ) + + return ( -) + isOpen={isOpen} + onDismiss={onDismiss} + attemptingTxn={attemptingTxn} + hash={hash} + content={confirmationContent} + pendingText={pendingText} + pendingText2={pendingText2} + /> + ) } diff --git a/src/features/robots/ActionGridexModal/ActionModalHeader.tsx b/src/features/robots/ActionGridexModal/ActionModalHeader.tsx index 34a595dfa9..36f8e3f220 100644 --- a/src/features/robots/ActionGridexModal/ActionModalHeader.tsx +++ b/src/features/robots/ActionGridexModal/ActionModalHeader.tsx @@ -1,4 +1,4 @@ -import { AlertTriangle, ArrowDown, Plus } from 'react-feather' +import { AlertTriangle, ArrowDown, ArrowUp, Plus } from 'react-feather' import { Currency, Percent, TradeType, Trade as V2Trade, CurrencyAmount, JSBI } from '@tangoswapcash/sdk' import React, { useState } from 'react' import { isAddress, shortenAddress } from '../../../functions' @@ -6,7 +6,7 @@ import { AdvancedSwapDetails } from '../../exchange-v1/swap/AdvancedSwapDetails' import Card from '../../../components/Card' import CurrencyLogo from '../../../components/CurrencyLogo' import { Field } from '../../../state/swap/actions' -import { RowBetween, RowFixed} from '../../../components/Row' +import { RowBetween, RowFixed } from '../../../components/Row' import TradePrice from '../../exchange-v1/swap/TradePrice' import Typography from '../../../components/Typography' import { t } from '@lingui/macro' @@ -15,23 +15,25 @@ import { useLingui } from '@lingui/react' import { useUSDCValue } from '../../../hooks/useUSDCPrice' import { warningSeverity } from '../../../functions' import QuestionHelper from '../../../components/QuestionHelper' +import { useRouter } from 'next/router' +import { parseUnits } from '@ethersproject/units' export default function CreateModalHeader({ -currencyA, -currencyB, -// maxValue, -// minValue, -// stockInputValue, -// moneyInputValue + currencyA, + currencyB, + currentMarket, + inputValue, + robots, + index }: -{ -currencyA: Currency -currencyB: Currency -// maxValue: string -// minValue: string -// stockInputValue: CurrencyAmount -// moneyInputValue: CurrencyAmount -}) { + { + currencyA: Currency + currencyB: Currency + currentMarket: boolean + inputValue: CurrencyAmount + robots: any + index: number | string + }) { const { i18n } = useLingui() // const [showInverted, setShowInverted] = useState(false) @@ -40,7 +42,24 @@ currencyB: Currency // const fiatValueOutput = useUSDCValue(trade.outputAmount) // const priceImpactSeverity = warningSeverity(trade.priceImpact) - +console.log("inputValue",robots); + + + const router = useRouter() + const type = router.query.filter as string + const portfolio = type == 'portfolio' + const sell = currentMarket == true; + const buy = currentMarket == false; + // console.log("buy",buy); + // console.log("sell",sell); + // console.log("portfolio",portfolio); + // console.log("currentMarket",currentMarket); + const moneyDelta = String((Number(inputValue) * robots[index].lowPrice).toFixed(6)); + const stockDelta = String((Number(inputValue) / robots[index].highPrice).toFixed(6)); + const maxValue = String(Number(robots[0].highPrice).toFixed(4)); + const minValue = String(Number(robots[0].lowPrice).toFixed(4)); + + return (
@@ -49,20 +68,20 @@ currencyB: Currency
{/* {trade.inputAmount.toSignificant(6)} */} - stockInputValue.toSignificant(6) + {sell ? inputValue : stockDelta}
{/*
{trade.inputAmount.currency.symbol}
*/}
{currencyA?.symbol}
-
+
{buy && !portfolio ? : sell && !portfolio ? : }
- moneyInputValue.toSignificant(6) + {buy ? inputValue : moneyDelta}
{currencyB?.symbol}
@@ -84,11 +103,11 @@ currencyB: Currency {trade.tradeType === TradeType.EXACT_INPUT ? i18n._(t`Minimum received`) : i18n._(t`Maximum sent`)}
*/}
- Price to Buy + {i18n._(t`Price to Buy ${currencyB.symbol}`)}
@@ -99,19 +118,19 @@ currencyB: Currency : `${trade.maximumAmountIn(allowedSlippage).toSignificant(6)} ${trade.inputAmount.currency.symbol}`}
*/}
- minValue + {minValue + ` ${currencyA.symbol}`}
-
{i18n._(t`Price to Sell`)}
+
{i18n._(t`Price to Buy ${currencyA.symbol}`)}
- maxValue + {maxValue + ` ${currencyB.symbol}`}
diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index d77db3fa8a..56219b275c 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -255,6 +255,12 @@ export default function Gridex() { const portfolio = type == 'portfolio' const sell = marketSelector const buy = !marketSelector + // console.log("buy",buy); + // console.log("sell",sell); + // console.log("portfolio",portfolio); + //console.log("marketSelector",marketSelector); + + const savedFilter = getFarmFilter() @@ -389,8 +395,8 @@ export default function Gridex() { actionToCall == 'buy' ? Buy(robotId) : actionToCall == 'sell' - ? Sell(robotId) - : actionToCall == 'delete' && DeleteRobot() + ? Sell(robotId) + : actionToCall == 'delete' && DeleteRobot() } const onDismiss = () => { @@ -412,22 +418,6 @@ export default function Gridex() {
-
@@ -456,7 +446,7 @@ export default function Gridex() {
Tango CMM list
+ Date: Fri, 13 Jan 2023 14:27:34 -0300 Subject: [PATCH 82/83] feat: commit --- src/features/robots/RobotListItemDetails.tsx | 31 +++++++++++++------- src/pages/gridex/gridex-list/index.tsx | 4 +-- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/features/robots/RobotListItemDetails.tsx b/src/features/robots/RobotListItemDetails.tsx index d510f1e992..90f85bf54c 100644 --- a/src/features/robots/RobotListItemDetails.tsx +++ b/src/features/robots/RobotListItemDetails.tsx @@ -89,13 +89,14 @@ const RobotListItemDetails = ({ const moneyDelta = stockDelta * robot.lowPrice const stockBalance = await stockContract?.balanceOf(account) + console.log(stockDelta); + if (stockDeltaBN.gt(stockBalance)) { return 0 // "Error: You don't have enough stock." } else if (moneyDelta > robot.moneyAmount) { return 1 // "Error: CMM has not enough money" - } else { - return 'No error' - } + } + } if (buy) { const moneyDecimals = await moneyContract?.decimals() @@ -105,9 +106,9 @@ const RobotListItemDetails = ({ const stockDelta = moneyDelta / robot.highPrice if (moneyDeltaBN.gt(moneyBalance)) { - return 0 // alert(`You don't have enough money.`) + return 0 // "Error: You don't have enough money" } else if (stockDelta > robot.stockAmount) { - return 1 //alert('Tango CMM has not enough stock') + return 1 // "Error: Tango CMM has not enough stock" } } } @@ -198,12 +199,16 @@ const RobotListItemDetails = ({ )) || (buy && - (errorCode == 0 ? ( - + ) : errorCode == 0 ? ( + ) : errorCode == 1 ? ( - ) : ( @@ -214,12 +219,16 @@ const RobotListItemDetails = ({ {i18n._(t`Buy ${robot?.stock?.symbol} from CMM`)} ))) || - (sell && errorCode == 0 ? ( - + ) : sell && errorCode == 0 ? ( + ) : errorCode == 1 ? ( - ) : ( diff --git a/src/pages/gridex/gridex-list/index.tsx b/src/pages/gridex/gridex-list/index.tsx index d77db3fa8a..19e0df1abc 100644 --- a/src/pages/gridex/gridex-list/index.tsx +++ b/src/pages/gridex/gridex-list/index.tsx @@ -316,7 +316,7 @@ export default function Gridex() { const addTransaction = useTransactionAdder() - const inputValue = formattedAmounts[Field.CURRENCY_B] + const inputValue = formattedAmounts[Field.CURRENCY_B] const Buy = async (robotId) => { const moneyDecimals = await moneyContract?.decimals() @@ -422,7 +422,7 @@ export default function Gridex() { txErrorMsg={txErrorMsg} onDismiss={onDismiss} stockContract={stockContract} - moneyContract={moneyContract} + moneyContract={moneyContract} marketContract={marketContract} factoryContract={factoryContract} index={index} From a903be58c95df8ab5a9e684213b01a0f8ea88df4 Mon Sep 17 00:00:00 2001 From: lifelessdev Date: Fri, 13 Jan 2023 14:35:57 -0300 Subject: [PATCH 83/83] feat: commit --- locale/de.json | 34 +++++++++++++++++++++++++++++++++- locale/en.json | 34 +++++++++++++++++++++++++++++++++- locale/es.json | 34 +++++++++++++++++++++++++++++++++- locale/fa.json | 34 +++++++++++++++++++++++++++++++++- locale/fr.json | 34 +++++++++++++++++++++++++++++++++- locale/hi.json | 34 +++++++++++++++++++++++++++++++++- locale/it.json | 34 +++++++++++++++++++++++++++++++++- locale/ja.json | 34 +++++++++++++++++++++++++++++++++- locale/ko.json | 34 +++++++++++++++++++++++++++++++++- locale/pt_BR.json | 34 +++++++++++++++++++++++++++++++++- locale/ro.json | 34 +++++++++++++++++++++++++++++++++- locale/ru.json | 34 +++++++++++++++++++++++++++++++++- locale/tr.json | 34 +++++++++++++++++++++++++++++++++- locale/vi.json | 34 +++++++++++++++++++++++++++++++++- locale/zh_CN.json | 34 +++++++++++++++++++++++++++++++++- locale/zh_TW.json | 34 +++++++++++++++++++++++++++++++++- 16 files changed, 528 insertions(+), 16 deletions(-) diff --git a/locale/de.json b/locale/de.json index b8038cb04e..0b9018f6ee 100644 --- a/locale/de.json +++ b/locale/de.json @@ -35,8 +35,12 @@ "Borrow": "Leihen", "Borrowed": "Geliehen", "Buy": "Kaufen", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Umgeht Bestätigungsmodalitäten und ermöglicht hohe Slippage-Trades. Die Verwendung erfolgt auf eigene Gefahr.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Stornieren", "Cancelled": "Storniert", "Change": "Ändern", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Gemeinschaftliche Genehmigung", "Confirm": "Bestätigen", + "Confirm Action": "", "Confirm Adding Liquidity": "Hinzufügen von Liquidität bestätigen", + "Confirm Creation": "", "Confirm Limit Order": "Order Limit bestätigen", "Confirm Staking": "Staking bestätigen", "Confirm Supply": "Lieferung bestätigen", @@ -60,10 +66,13 @@ "Copied": "Kopiert", "Copy Address": "Adresse kopieren", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Erstellen Sie Pool & Supply", + "Create Tango CMM": "", "Create pool": "Pool erstellen", "Current": "Aktuell", "DAY": "Tag", + "Delete Tango CMM": "", "Deposit": "Einzahlen", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Zahlen Sie Token für alle Erträge in Mirror ein", @@ -89,6 +98,7 @@ "Expired": "Abgelaufen", "Farm": "Farm", "Fee": "", + "Fill the parameters": "", "Find Pool": "Pool finden", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Pool importieren", "In Mirror:": "In Mirror:", "In Wallet:": "Im Wallet:", + "Input an amount": "", "Input is estimated. You will sell at most": "Die Eingabe wird geschätzt. Sie verkaufen höchstens zu", "Insufficient Balance": "Zu wenig Guthaben", "Insufficient liquidity for this trade": "Unzureichende Liquidität für diesen Trade", "Insufficient {0} balance": "Zu wenig {0} Guthaben", "Interface Settings": "Einstellungen", + "Invalid Price": "", "Invalid pair": "Ungültiges Paar", "Invalid recipient": "Ungültiger Empfänger", "Join the community on Telegram.": "Trete der Community bei Telegram bei", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Mirror Guthaben: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror bietet zusätzliche Renditen für Einlagen mit Flash-Krediten, Strategien und festen, Low-Gas-Transfers zwischen integrierten Dapps wie den Lend-Märkten.", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Meine Liquiditätspositionen", "My TANGO": "", "New to SmartBCH?": "Neu bei SmartBCH?", @@ -173,6 +187,9 @@ "Price Impact High": "Preisauswirkung hoch", "Price Impact Too High": "Preisauswirkung zu hoch", "Price Updated": "Preis aktualisiert", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Preis", "Rates": "Kurse", "Recent Transactions": "Letzte Transaktionen", @@ -196,6 +213,8 @@ "Select a token": "Wähle einen Token aus", "Select a token to find your liquidity": "Wähle einen Token aus, um deine Liquidität zu ermitteln", "Select an order expiration": "Wähle ein Ablaufdatum für die Bestellung", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Senden an:", "Share": "", "Share of Pool": "Poolanteil", @@ -213,6 +232,9 @@ "Stake TANGO": "Stake TANGO", "Stake TANGO for xTANGO": "Stake TANGO für xTANGO", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "Liefere APR", "Supplying {0} {1} and {2} {3}": "Lieferung von {0} {1} und {2} {3}", "Swap": "Swap", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Die Uniswap-Invariante x*y=k wurde durch den Tausch nicht erfüllt. Dies bedeutet in der Regel, dass eines der Token, die Sie tauschen, ein benutzerdefiniertes Verhalten bei der Übertragung aufweist.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "Die Differenz zwischen dem Marktpreis und dem geschätzten Preis aufgrund der Handelsgröße.", "The input token cannot be transferred. There may be an issue with the input token.": "Der Eingabe-Token kann nicht übertragen werden. Möglicherweise gibt es ein Problem mit dem Eingabe-Token.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "Der Ausgabe-Token kann nicht übertragen werden. Möglicherweise gibt es ein Problem mit dem Ausgabe-Token.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "Die Transaktion konnte nicht gesendet werden, da die Frist dafür überschritten wurde. Bitte überprüfen Sie, ob Ihre Transaktionsfrist nicht zu kurzfristig ist.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Verwenden Sie dieses Tool, um Paare zu finden, die nicht automatisch in der Schnittstelle erscheinen.", "Vesting is executed within the guidelines selected by the community in": "Die Festlegung der Freizügigkeit erfolgt im Rahmen der von der Gemeinschaft in", "View Liquidity Positions": "Liquiditätspositionen anzeigen", + "View Your Tango CMM": "", "View on explorer": "Ansicht auf Explorer", "Waiting for Confirmation": "Warten auf Bestätigung", "Wallet": "Wallet", @@ -270,10 +298,13 @@ "You Pay:": "Du zahlst:", "You are creating a pool": "Erstelle einen Pool", "You are on the wrong network": "Du befindest dich im falschen Netzwerk", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Du hast noch keine Liquidität in diesem Pool", "You pay:": "", "You receive:": "Du hast erhalten:", "You will receive": "Du wirst erhalten", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Dein Stake", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} Hinterlegt", "{0} {1} per {2}": "{0} {1} pro {2}", "{0} {sign} market rate": "{0} {sign} Marktpreis", - "{0}/{1} Burned": "{0}/{1} verbrannt" + "{0}/{1} Burned": "{0}/{1} verbrannt", + "{error}": "" } \ No newline at end of file diff --git a/locale/en.json b/locale/en.json index 7afc877ef0..8f8c6baa22 100644 --- a/locale/en.json +++ b/locale/en.json @@ -35,8 +35,12 @@ "Borrow": "", "Borrowed": "", "Buy": "", + "Buy {0} from CMM": "Buy {0} from CMM", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "", + "CMM Market": "CMM Market", + "CMM has not enough money": "CMM has not enough money", + "CMM has not enough stock": "CMM has not enough stock", "Cancel": "", "Cancelled": "", "Change": "", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "", "Confirm": "", + "Confirm Action": "Confirm Action", "Confirm Adding Liquidity": "", + "Confirm Creation": "Confirm Creation", "Confirm Limit Order": "", "Confirm Staking": "", "Confirm Supply": "", @@ -60,10 +66,13 @@ "Copied": "", "Copy Address": "", "Create Limit Order": "", + "Create Market": "Create Market", "Create Pool & Supply": "", + "Create Tango CMM": "Create Tango CMM", "Create pool": "", "Current": "", "DAY": "", + "Delete Tango CMM": "Delete Tango CMM", "Deposit": "", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "", @@ -89,6 +98,7 @@ "Expired": "", "Farm": "", "Fee": "", + "Fill the parameters": "Fill the parameters", "Find Pool": "", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "", "In Mirror:": "", "In Wallet:": "", + "Input an amount": "Input an amount", "Input is estimated. You will sell at most": "", "Insufficient Balance": "", "Insufficient liquidity for this trade": "", "Insufficient {0} balance": "", "Interface Settings": "", + "Invalid Price": "Invalid Price", "Invalid pair": "", "Invalid recipient": "", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "", "Mirror Balance: {0}": "", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "", + "Money: < 0.001": "Money: < 0.001", + "Money: {0}": "Money: {0}", "My Liquidity Positions": "", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "", "Price Impact Too High": "", "Price Updated": "", + "Price to Buy": "Price to Buy", + "Price to Buy {0}": "Price to Buy {0}", + "Price to Sell": "Price to Sell", "Rate": "", "Rates": "", "Recent Transactions": "", @@ -196,6 +213,8 @@ "Select a token": "", "Select a token to find your liquidity": "", "Select an order expiration": "", + "Sell": "Sell", + "Sell {0} to CMM": "Sell {0} to CMM", "Send to:": "", "Share": "", "Share of Pool": "", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "Stock/Money", + "Stock: < 0.001": "Stock: < 0.001", + "Stock: {0}": "Stock: {0}", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "", "Swap": "", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "", "Take Limit Order": "", + "Tango CMM": "Tango CMM", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "", + "The amount of {0} that the user will spend for {1}": "The amount of {0} that the user will spend for {1}", + "The amount of {0} that the user will spend for {1}": "The amount of {0} that the user will spend for {1}", "The difference between the market price and estimated price due to trade size.": "", "The input token cannot be transferred. There may be an issue with the input token.": "", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "", + "The price that the user will buy {0}": "The price that the user will buy {0}", + "The price that the user will sell {0}": "The price that the user will sell {0}", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "", "Vesting is executed within the guidelines selected by the community in": "", "View Liquidity Positions": "", + "View Your Tango CMM": "View Your Tango CMM", "View on explorer": "", "Waiting for Confirmation": "", "Wallet": "", @@ -270,10 +298,13 @@ "You Pay:": "", "You are creating a pool": "", "You are on the wrong network": "", + "You don't have enough Money": "You don't have enough Money", + "You don't have enough Stock": "You don't have enough Stock", "You don’t have liquidity in this pool yet": "", "You pay:": "", "You receive:": "", "You will receive": "", + "Your CMM": "Your CMM", "Your Claimable TANGO this Week": "", "Your Staked": "", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "", "{0} {1} per {2}": "", "{0} {sign} market rate": "", - "{0}/{1} Burned": "" + "{0}/{1} Burned": "", + "{error}": "{error}" } \ No newline at end of file diff --git a/locale/es.json b/locale/es.json index cd45efd803..bccf98318e 100644 --- a/locale/es.json +++ b/locale/es.json @@ -35,8 +35,12 @@ "Borrow": "Pedir prestado", "Borrowed": "Prestado", "Buy": "Comprar", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Omite los modales de confirmación y permite operaciones de alto deslizamiento. Utilícelo bajo su propia responsabilidad.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Cancelar", "Cancelled": "Cancelado", "Change": "Cambiar", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Aprobación de la comunidad", "Confirm": "Confirmar", + "Confirm Action": "", "Confirm Adding Liquidity": "Confirmar adición de liquidez", + "Confirm Creation": "", "Confirm Limit Order": "Confirmar límite de orden", "Confirm Staking": "Confirmar apuesta", "Confirm Supply": "Confirmar suministro", @@ -60,10 +66,13 @@ "Copied": "Copiada", "Copy Address": "Copiar dirección", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Crear fondo y suministro", + "Create Tango CMM": "", "Create pool": "Crear fondo", "Current": "Actual", "DAY": "", + "Delete Tango CMM": "", "Deposit": "Depositar", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Deposite tokens en Mirror para todos los rendimientos", @@ -89,6 +98,7 @@ "Expired": "Vencido", "Farm": "Granja", "Fee": "", + "Fill the parameters": "", "Find Pool": "Buscar fondo", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Importar fondo", "In Mirror:": "En Mirror:", "In Wallet:": "En la cartera:", + "Input an amount": "", "Input is estimated. You will sell at most": "El resultado es estimado. Recibirá al menos", "Insufficient Balance": "Saldo insuficiente", "Insufficient liquidity for this trade": "Liquidez insuficiente para esta operación", "Insufficient {0} balance": "Saldo {0} insuficiente", "Interface Settings": "Configuración de la interfaz", + "Invalid Price": "", "Invalid pair": "Par inválido", "Invalid recipient": "Destinatario no válido", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Saldo de Mirror: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror proporciona un rendimiento adicional en depósitos con préstamos instantáneos, estrategias y transferencias fijas lentas entre aplicaciones descentralizadas integradas, como los mercados de Lend.", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Mis posiciones de liquidez", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "Impacto de precio alto", "Price Impact Too High": "Impacto de precio demasiado alto", "Price Updated": "Precio actualizado", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Tarifa", "Rates": "Tarifas", "Recent Transactions": "Transacciones recientes", @@ -196,6 +213,8 @@ "Select a token": "Seleccione un token", "Select a token to find your liquidity": "Seleccione un token para encontrar su liquidez", "Select an order expiration": "Seleccione la fecha de vencimiento de la orden", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Enviar a:", "Share": "", "Share of Pool": "Participación en el fondo", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "Suministrando {0} {1} y {2} {3}", "Swap": "Intercambio", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "La invariante de Uniswap x*y=k no ha sido satisfecha por el intercambio. Esto generalmente significa que uno de los tokens que está intercambiando incorpora un comportamiento personalizado en la transferencia.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "La diferencia entre el precio de mercado y el precio estimado debido al tamaño de la operación.", "The input token cannot be transferred. There may be an issue with the input token.": "El token de entrada no se puede transferir. Es posible que haya un problema con el token de entrada.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "El token de salida no se puede transferir. Es posible que haya un problema con el token de salida.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "No se ha podido enviar la transacción ya que la fecha límite ha vencido. Compruebe que el plazo de la transacción no es insuficiente.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Utilice esta herramienta para encontrar pares que no aparecen automáticamente en la interfaz", "Vesting is executed within the guidelines selected by the community in": "La adquisición se ejecuta dentro de las directrices seleccionadas por la comunidad en", "View Liquidity Positions": "Ver posiciones de liquidez", + "View Your Tango CMM": "", "View on explorer": "Ver en el explorador", "Waiting for Confirmation": "A la espera de confirmación", "Wallet": "Cartera", @@ -270,10 +298,13 @@ "You Pay:": "Paga:", "You are creating a pool": "Está creando un fondo", "You are on the wrong network": "Está en la red equivocada", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Aún no tiene liquidez en este fondo", "You pay:": "", "You receive:": "Recibe:", "You will receive": "Recibirá", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Su apuesta", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} depositado", "{0} {1} per {2}": "{0} {1} por {2}", "{0} {sign} market rate": "{0} {sign} tasa de mercado", - "{0}/{1} Burned": "{0}/{1} quemado" + "{0}/{1} Burned": "{0}/{1} quemado", + "{error}": "" } \ No newline at end of file diff --git a/locale/fa.json b/locale/fa.json index 79a6bdec16..ccf032a773 100644 --- a/locale/fa.json +++ b/locale/fa.json @@ -35,8 +35,12 @@ "Borrow": "قرض گیری", "Borrowed": "قرض گرفته شد", "Buy": "خرید", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "راه های فرعی حالات را تایید می کنند و امکان معاملات با افت بالا را فراهم می آورند. با قبول ریسک، از آن استفاده کنید", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "لغو", "Cancelled": "لغو شد", "Change": "تغییر", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "تایید همانندی (گروه)", "Confirm": "تایید کنید", + "Confirm Action": "", "Confirm Adding Liquidity": "افزایش لیکوییدیتی را تایید کنید", + "Confirm Creation": "", "Confirm Limit Order": "سفارش محدود را تأیید کنید", "Confirm Staking": "تایید سهام گذاری", "Confirm Supply": "تامین را تایید کنید", @@ -60,10 +66,13 @@ "Copied": "کپی شد", "Copy Address": "آدرس را کپی کنید", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "استخر و تامین ایجاد کنید", + "Create Tango CMM": "", "Create pool": "استخر ایجاد کنید", "Current": "جاری", "DAY": "", + "Delete Tango CMM": "", "Deposit": "واریز کنید", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "برای تمامی بازده ها، توکن ها را به بنتوباکس واریز کنید", @@ -89,6 +98,7 @@ "Expired": "منقضی شده", "Farm": "مزرعه", "Fee": "", + "Fill the parameters": "", "Find Pool": "استخر را پیدا کنید", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "استخر را وارد کنید", "In Mirror:": "ﺂﯿﻨﻫ:", "In Wallet:": "در کیف پول:", + "Input an amount": "", "Input is estimated. You will sell at most": "ورودی برآوردی است. حداکثر میرانی که خواهید فروخت", "Insufficient Balance": "مانده کافی نیست", "Insufficient liquidity for this trade": "لیکوییدیتی ناکافی برای این معامله", "Insufficient {0} balance": "مانده {0} ناکافی ", "Interface Settings": "تنظیمات خط اتصال", + "Invalid Price": "", "Invalid pair": "جفت نامعتبر", "Invalid recipient": "گیرنده نامعتبر", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "آینه", "Mirror Balance: {0}": "{0} ﺂﯿﻨﻫ", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "آینه بازده بالاتری را برای سپرده‌هایی فراهم می‌کند که دارای وام سریع و استراتژیک هستند و با گاز ثابت کمتری در میان شرکت‌های یکپارچه مانند بازارهای نقدی حمل می‌شوند.", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "وضعیت‌های لیکوییدیتی من", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "تاثیر بالای قیمت", "Price Impact Too High": "تاثیر بسیار بالای قیمت", "Price Updated": "قیمت به روزرسانی شده", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "نرخ", "Rates": "نرخ ها", "Recent Transactions": "تراکنش‌های اخیر", @@ -196,6 +213,8 @@ "Select a token": "یک توکن انتخاب کنید", "Select a token to find your liquidity": "برای پیدا کردن لیکوییدیتی خود، توکنی را انتخاب کنید", "Select an order expiration": "یک انقضای سفارش را انتخاب کنید", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "فرستادن به:", "Share": "", "Share of Pool": "سهم استخر", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "تامین {0} {1} و {2} {3}", "Swap": "جابه جا کنید", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "کارهایی ", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "x * y = k ثابت تک‌جابه‌جایی با جابه‌جایی حاصل نشد. این معمولاً به این معنی است که یکی از توکن‌هایی که در حال جابه‌جایی آن هستید متضمن رفتار سفارشی در انتقال است.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "تفاوت میان قیمت بازار و قیمت برآوردی به علت اندازه معامله", "The input token cannot be transferred. There may be an issue with the input token.": "توکن ورودی قابل انتقال نیست. ممکن است توکن ورودی مشکلی داشته باشد.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "توکن خروجی قابل انتقال نیست. ممکن است توکن خروجی مشکلی داشته باشد.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "ارسال این تراکنش امکان‌پذیر نیست زیرا مهلت آن گذشته است. لطفاً بررسی کنید که مهلت تراکنش شما خیلی کم نباشد.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "از این ابزار برای یافتن جفت‌هایی استفاده کنید که به صورت خودکار در رابط کاربری نمایش داده نمی‌شوند", "Vesting is executed within the guidelines selected by the community in": "واگذاری در چارچوب دستورالعمل‌های انتخاب شده توسط جامعه اجرا می‌شود", "View Liquidity Positions": "مشاهده وضعیت‌های لیکوییدیتی خود", + "View Your Tango CMM": "", "View on explorer": "مشاهده در جستجوگر (اکسپلورو)", "Waiting for Confirmation": "در انتظار تأیید", "Wallet": "کیف پول", @@ -270,10 +298,13 @@ "You Pay:": "شما می‌پردازید:", "You are creating a pool": "شما در حال ایجاد استخر هستید", "You are on the wrong network": "شما در شبکه اشتباهی هستید", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "شما هنوز در این استخر لیکوییدیتی ندارید", "You pay:": "", "You receive:": "شما دریافت می‌کنید:", "You will receive": "شما دریافت خواهید کرد", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "سهام گذاری های شما", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} واریز شد", "{0} {1} per {2}": "{0} {1} در هر {2}", "{0} {sign} market rate": "{0} {sign} نرخ بازار", - "{0}/{1} Burned": "{0}/ {1} سوخته" + "{0}/{1} Burned": "{0}/ {1} سوخته", + "{error}": "" } \ No newline at end of file diff --git a/locale/fr.json b/locale/fr.json index 86f12b8b97..6679412b5c 100644 --- a/locale/fr.json +++ b/locale/fr.json @@ -35,8 +35,12 @@ "Borrow": "Emprunter", "Borrowed": "Emprunté", "Buy": "Acheter", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Contourne les notifications de confirmation et permet des transactions à slippage élevé. À utiliser avec précaution, en toute connaissance de cause.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Annuler", "Cancelled": "Annulé", "Change": "Changer", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Approuvé par la communauté", "Confirm": "Confirmer", + "Confirm Action": "", "Confirm Adding Liquidity": "Confirmer l'ajout de liquidité", + "Confirm Creation": "", "Confirm Limit Order": "Confirmer la limite de commande", "Confirm Staking": "Confirmer le staking", "Confirm Supply": "Confirmer le dépôt", @@ -60,10 +66,13 @@ "Copied": "Copié", "Copy Address": "Copier l'adresse", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Créer un pool et apporter de la liquidité", + "Create Tango CMM": "", "Create pool": "Créer un pool", "Current": "Actuel", "DAY": "", + "Delete Tango CMM": "", "Deposit": "Déposer ", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Déposez des tokens dans Mirror pour tous les rendements", @@ -89,6 +98,7 @@ "Expired": "Expiré", "Farm": "Ferme", "Fee": "", + "Fill the parameters": "", "Find Pool": "Trouver un pool", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Importer un pool", "In Mirror:": "En Mirror :", "In Wallet:": "En portefeuille :", + "Input an amount": "", "Input is estimated. You will sell at most": "Les intrants sont estimés. Vous vendrez au plus", "Insufficient Balance": "Solde insuffisant", "Insufficient liquidity for this trade": "Liquidité insuffisante pour cette transaction", "Insufficient {0} balance": "Solde de {0} insuffisant", "Interface Settings": "Paramètres", + "Invalid Price": "", "Invalid pair": "Paire non valide", "Invalid recipient": "Destinataire non valide", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Solde Mirror: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror offre des rendements supplémentaires sur les dépôts avec des prêts flash, des stratégies et des transferts à faible gaz entre les dapps intégrées, comme Lend", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Mes positions de liquidité", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "Impact prix élevé", "Price Impact Too High": "Impact prix trop important", "Price Updated": "Prix actualisé", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Taux", "Rates": "Taux", "Recent Transactions": "Transactions récentes", @@ -196,6 +213,8 @@ "Select a token": "Sélectionnez un token", "Select a token to find your liquidity": "Sélectionnez un token pour trouver votre liquidité", "Select an order expiration": "Sélectionnez une expiration de commande", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Envoyer à :", "Share": "", "Share of Pool": "Part du pool", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "Ajouter {0} {1} et {2} {3}", "Swap": "Swapper", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "L’invariant Uniswap x*y=k n’a pas été satisfaisant pour le swap. Cela signifie généralement que l’un des jetons que vous échangez intègre un comportement personnalisé lors du transfert.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "La différence entre le prix du marché et le prix estimé causé par la taille de l'ordre.", "The input token cannot be transferred. There may be an issue with the input token.": "Le jeton d’entrée ne peut pas être transféré. Il peut y avoir un problème avec le jeton d’entrée.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "Le jeton de sortie ne peut pas être transféré. Il peut y avoir un problème avec le jeton de sortie.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "La transaction n'a pas pu être envoyée, car la date limite est dépassée. Veuillez vérifier que la date limite de votre transaction n'est pas trop basse.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Utilisez cet outil pour rechercher des paires qui n'apparaissent pas automatiquement dans l'interface", "Vesting is executed within the guidelines selected by the community in": "L'acquisition des droits est exécutée dans le cadre des lignes directrices choisies par la communauté dans", "View Liquidity Positions": "Consulter les positions de liquidité", + "View Your Tango CMM": "", "View on explorer": "Voir sur l'explorateur", "Waiting for Confirmation": "En attente de confirmation", "Wallet": "Portefeuille", @@ -270,10 +298,13 @@ "You Pay:": "Vous payez :", "You are creating a pool": "Vous créez un pool", "You are on the wrong network": "Vous êtes connecté au mauvais réseau", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Vous n'avez pas encore de liquidité dans ce pool", "You pay:": "", "You receive:": "Vous recevez :", "You will receive": "Vous allez recevoir", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Vos X placés", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} Déposé", "{0} {1} per {2}": "{0} {1} par {2}", "{0} {sign} market rate": "{0} {sign} taux du marché", - "{0}/{1} Burned": "{0}/{1} Brûlé" + "{0}/{1} Burned": "{0}/{1} Brûlé", + "{error}": "" } \ No newline at end of file diff --git a/locale/hi.json b/locale/hi.json index 800b37522f..e89f4cfbf8 100644 --- a/locale/hi.json +++ b/locale/hi.json @@ -35,8 +35,12 @@ "Borrow": "उधार लें", "Borrowed": "उधार लिया", "Buy": "खरीदें", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "पुष्टि मोडल को बायपास करता है और अधिक स्लिपेज वाली ट्रेडों की अनुमति देता है। अपने जोखिम पर इस्तेमाल करें।", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "रद्द करें", "Cancelled": "रद्द", "Change": "बदलें", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "सामुदायिक स्वीकृति", "Confirm": "पुष्टि करें", + "Confirm Action": "", "Confirm Adding Liquidity": "लिक्विडिटी जोड़ने की पुष्टि करें", + "Confirm Creation": "", "Confirm Limit Order": "लिमिट ऑर्डर की पुष्टि करें", "Confirm Staking": "स्टेकिंग की पुष्टि करें", "Confirm Supply": "आपूर्ति की पुष्टि करें", @@ -60,10 +66,13 @@ "Copied": "कॉपी किया गया", "Copy Address": "पता कॉपी करें", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "पूल और आपूर्ति बनाएँ", + "Create Tango CMM": "", "Create pool": "पूल बनाएँ", "Current": "वर्तमान", "DAY": "", + "Delete Tango CMM": "", "Deposit": "जमा करें", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "सभी लाभ के लिए Mirror में टोकन जमा करें", @@ -89,6 +98,7 @@ "Expired": "एक्स्पायर्ड", "Farm": "खेत", "Fee": "", + "Fill the parameters": "", "Find Pool": "पूल का पता लगाएं", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "पूल इंपोर्ट करें", "In Mirror:": "Mirror में:", "In Wallet:": "वॉलेट में:", + "Input an amount": "", "Input is estimated. You will sell at most": "इनपुट का अनुमान है। आप अधिक से अधिक बेच देंगे", "Insufficient Balance": "अपर्याप्त शेषराशि", "Insufficient liquidity for this trade": "इस ट्रेड के लिए अपर्याप्त लिक्विडिटी", "Insufficient {0} balance": "अपर्याप्त {0} शेषराशि", "Interface Settings": "इंटरफ़ेस सेटिंग", + "Invalid Price": "", "Invalid pair": "अमान्य जोड़ी", "Invalid recipient": "अवैध प्राप्तकर्ता", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Mirror शेष: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror जमा पर अतिरिक्त लाभ प्रदान करता है, जिसमें उधार, रणनीतियाँ, और निश्चित, Lend बाजारों की तरह एकीकृत dapps के बीच कम गैस स्थानान्तरण शामिल हैं।", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "मेरी लिक्विडिटी पोजीशन", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "मूल्य प्रभाव अधिक", "Price Impact Too High": "मूल्य प्रभाव बहुत अधिक है", "Price Updated": "मूल्य अपडेट किया गया", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "मूल्यांकन करें", "Rates": "दरें", "Recent Transactions": "हाल ही के लेनदेन", @@ -196,6 +213,8 @@ "Select a token": "एक टोकन चुनें", "Select a token to find your liquidity": "अपनी लिक्विडिटी को खोजने के लिए टोकन का चयन करें", "Select an order expiration": "एक ऑर्डर समाप्ति का चयन करें", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "यहां भेजें:", "Share": "", "Share of Pool": "पूल का हिस्सा", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "{0} {1} और {2} {3} की आपूर्ति", "Swap": "स्वैप करें", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Uniswap अपरिवर्तनीय x*y=k स्वैप से संतुष्ट नहीं था। इसका आमतौर पर मतलब है कि आप जिन टोकनों की स्वैपिंग कर रहे हैं उनमें से एक स्थानांतरण पर कस्टम व्यवहार को शामिल करता है।", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "ट्रेड के आकार के कारण बाजार मूल्य और अनुमानित मूल्य के बीच का अंतर।", "The input token cannot be transferred. There may be an issue with the input token.": "इनपुट टोकन को स्थानांतरित नहीं किया जा सकता है। इनपुट टोकन के साथ कोई समस्या हो सकती है।", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "आउटपुट टोकन को स्थानांतरित नहीं किया जा सकता है। आउटपुट टोकन के साथ कोई समस्या हो सकती है।", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "समय सीमा बीत जाने के कारण लेन-देन नहीं भेजा जा सका। कृपया जांचें कि आपके लेन-देन की समय सीमा बहुत कम नहीं है।", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "इस टूल का उपयोग उन जोड़ियों को खोजने के लिए करें जो इंटरफ़ेस में स्वचालित रूप से प्रकट नहीं होती हैं", "Vesting is executed within the guidelines selected by the community in": "वेस्टिंग को समुदाय द्वारा चुने गए दिशा-निर्देशों के भीतर निष्पादित किया जाता है", "View Liquidity Positions": "तरलता की स्थिति देखें", + "View Your Tango CMM": "", "View on explorer": "एक्सप्लोरर पर देखें", "Waiting for Confirmation": "पुष्टि के लिए प्रतीक्षा कर रहा है", "Wallet": "वॉलेट", @@ -270,10 +298,13 @@ "You Pay:": "आप भुगतान करते हैं:", "You are creating a pool": "आप एक पूल बना रहे हैं", "You are on the wrong network": "आप गलत नेटवर्क पर हैं", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "इस पूल में आपकी लिक्विडिटी नहीं है", "You pay:": "", "You receive:": "आप प्राप्त करते हैं:", "You will receive": "आपको प्राप्त होगा", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "आपका स्टैक्ड", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} जमा किया", "{0} {1} per {2}": "{0} {1} प्रति {2}", "{0} {sign} market rate": "{0} {sign} बाजार दर", - "{0}/{1} Burned": "{0}/{1} जल गया" + "{0}/{1} Burned": "{0}/{1} जल गया", + "{error}": "" } \ No newline at end of file diff --git a/locale/it.json b/locale/it.json index 394ade3bd5..d27cd76ddd 100644 --- a/locale/it.json +++ b/locale/it.json @@ -35,8 +35,12 @@ "Borrow": "Prendi in prestito", "Borrowed": "Preso in prestito", "Buy": "Acquista", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Bypassa i modali di conferma e consente operazioni con uno slippage elevato. Usare a proprio rischio.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Elimina", "Cancelled": "Eliminato", "Change": "Cambia", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Approvazione della comunità", "Confirm": "Conferma", + "Confirm Action": "", "Confirm Adding Liquidity": "Conferma aggiunta di liquidità", + "Confirm Creation": "", "Confirm Limit Order": "Conferma ordine limite", "Confirm Staking": "Conferma staking", "Confirm Supply": "Conferma fornitura", @@ -60,10 +66,13 @@ "Copied": "Copiato", "Copy Address": "Copia indirizzo", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Crea pool e fornitura", + "Create Tango CMM": "", "Create pool": "Crea pool", "Current": "Attuale", "DAY": "", + "Delete Tango CMM": "", "Deposit": "Deposita", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Deposita token in Mirror per tutti i rendimenti", @@ -89,6 +98,7 @@ "Expired": "Scaduto", "Farm": "Farm", "Fee": "", + "Fill the parameters": "", "Find Pool": "Trova pool", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Importa pool", "In Mirror:": "Su Mirror:", "In Wallet:": "Nel wallet:", + "Input an amount": "", "Input is estimated. You will sell at most": "L'input è stimato. Venderai al massimo", "Insufficient Balance": "Saldo insufficiente", "Insufficient liquidity for this trade": "Liquidità insufficiente per questa operazione", "Insufficient {0} balance": "Saldo {0} insufficiente", "Interface Settings": "Impostazioni interfaccia", + "Invalid Price": "", "Invalid pair": "Coppia non valida", "Invalid recipient": "Destinatario non valido", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Saldo Mirror: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror offre rendimenti extra sui depositi con flash lending, strategie e trasferimenti fissi low-gas tra dApp integrate, come i mercati di Lend", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Le mie posizioni di liquidità", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "Impatto sul prezzo elevato", "Price Impact Too High": "Impatto sul prezzo troppo elevato", "Price Updated": "Prezzo aggiornato", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Rate", "Rates": "Tassi", "Recent Transactions": "Transazioni recenti", @@ -196,6 +213,8 @@ "Select a token": "Seleziona un token", "Select a token to find your liquidity": "Seleziona un token per trovare la tua liquidità", "Select an order expiration": "Seleziona una scadenza dell'ordine", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Invia a:", "Share": "", "Share of Pool": "Quota del pool", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "Fornisci {0} {1} e {2} {3}", "Swap": "Scambia", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "L'invariante di Uniswap x*y=k non è stata soddisfatta dallo scambio. Questo di solito significa che uno dei token che stai scambiando incorpora un comportamento personalizzato durante il trasferimento.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "La differenza tra il prezzo di mercato e il prezzo stimato a causa delle dimensioni dell'operazione.", "The input token cannot be transferred. There may be an issue with the input token.": "Non è stato possibile trasferire il token di input; potrebbe esserci un problema con il token di input.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "Non è stato possibile trasferire il token di output; potrebbe esserci un problema con il token di output.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "Non è stato possibile inviare la transazione perché il termine è scaduto. Verifica che il termine della transazione non sia troppo breve.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Usa questo strumento per trovare coppie che non appaiono automaticamente nell’interfaccia", "Vesting is executed within the guidelines selected by the community in": "Il vesting viene eseguito secondo le linee guida selezionate dalla community in", "View Liquidity Positions": "Mostra posizioni di liquidità", + "View Your Tango CMM": "", "View on explorer": "Visualizza sull'explorer", "Waiting for Confirmation": "In attesa di conferma", "Wallet": "Wallet", @@ -270,10 +298,13 @@ "You Pay:": "Paghi:", "You are creating a pool": "Stai creando un pool", "You are on the wrong network": "Sei connesso alla rete sbagliata", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Non hai ancora liquidità in questo pool", "You pay:": "", "You receive:": "Ricevi:", "You will receive": "Riceverai", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "In staking", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} depositato", "{0} {1} per {2}": "{0} {1} per {2}", "{0} {sign} market rate": "{0} {sign} valore di mercato", - "{0}/{1} Burned": "{0}/{1} distrutti" + "{0}/{1} Burned": "{0}/{1} distrutti", + "{error}": "" } \ No newline at end of file diff --git a/locale/ja.json b/locale/ja.json index f47e74c4a2..63a56e1264 100644 --- a/locale/ja.json +++ b/locale/ja.json @@ -35,8 +35,12 @@ "Borrow": "借入れる", "Borrowed": "借入れ済み", "Buy": "購入", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "確認モーダルを無視すると、高スリッページの取引が可能になります。ご自身の責任でご利用ください。", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "キャンセル", "Cancelled": "キャンセルしました", "Change": "変更", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "コミュニティの承認", "Confirm": "確認", + "Confirm Action": "", "Confirm Adding Liquidity": "流動性の追加を確認", + "Confirm Creation": "", "Confirm Limit Order": "指値注文を確認", "Confirm Staking": "出資を確認", "Confirm Supply": "供給を確認する", @@ -60,10 +66,13 @@ "Copied": "コピーしました", "Copy Address": "アドレスをコピー", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "プールおよび供給を作成", + "Create Tango CMM": "", "Create pool": "プールを作成", "Current": "現在", "DAY": "", + "Delete Tango CMM": "", "Deposit": "預け入れる", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "すべての利回りのためにMirrorにトークンを預け入れましょう", @@ -89,6 +98,7 @@ "Expired": "期限切れ", "Farm": "ファーム", "Fee": "", + "Fill the parameters": "", "Find Pool": "プールを検索", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "プールをインポート", "In Mirror:": "Mirror内:", "In Wallet:": "ウォレット内:", + "Input an amount": "", "Input is estimated. You will sell at most": "入力は推定値です。 最大で以下を売却します", "Insufficient Balance": "残高が不足しています", "Insufficient liquidity for this trade": "この取引の流動性が不足しています", "Insufficient {0} balance": "{0}の残高が不足しています", "Interface Settings": "インターフェース設定", + "Invalid Price": "", "Invalid pair": "ペアが無効です", "Invalid recipient": "受領者が無効です", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Mirrorの残高:{0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirrorは、Lend市場のような統合されたdAppsの間で、フラッシュ貸出し、戦略、固定された低いガスの送金で、預金の追加利回りを生み出します", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "私の流動性ポジション", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "価格への影響が高い", "Price Impact Too High": "価格への影響が高すぎる", "Price Updated": "価格が更新されました", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "レート", "Rates": "レート", "Recent Transactions": "最近の取引", @@ -196,6 +213,8 @@ "Select a token": "トークンを選択", "Select a token to find your liquidity": "トークンを選択して流動性を検索", "Select an order expiration": "注文の有効期限を選択", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "送信先:", "Share": "", "Share of Pool": "プールのシェア", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "{0}{1}および{2}{3}を供給しています", "Swap": "スワップ", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Uniswap不変量x*y=kがスワップで満たされませんでした。これは通常、スワップするトークンの1つに転送時のカスタム動作が組み込まれていることを意味します。", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "取引規模による市場価格と推定価格の差。", "The input token cannot be transferred. There may be an issue with the input token.": "入力トークンを転送できません。入力されたトークンに問題がある可能性があります。", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "出力トークンを転送できません。出力トークンに問題がある可能性があります。", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "期限が過ぎたため、取引を送信できませんでした。取引期限が短すぎないことを確認してください。", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "このツールを使用すると、インターフェースに自動表示されないペアを見つけることができます", "Vesting is executed within the guidelines selected by the community in": "権利確定は、コミュニティが選択したガイドラインに沿って行われます", "View Liquidity Positions": "流動性ポジションを表示", + "View Your Tango CMM": "", "View on explorer": "エクスプローラーで表示", "Waiting for Confirmation": "確認待ち", "Wallet": "ウォレット", @@ -270,10 +298,13 @@ "You Pay:": "支払い:", "You are creating a pool": "プールを作成しています", "You are on the wrong network": "間違ったネットワークにいます", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "このプールにはまだ流動性がありません", "You pay:": "", "You receive:": "受け取り:", "You will receive": "あなたは以下を受け取ります", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "あなたの出資", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0}の預け入れ", "{0} {1} per {2}": "{2}あたり{0}{1}", "{0} {sign} market rate": "{0}{sign}市場レート", - "{0}/{1} Burned": "{0}/{1}が焼かれました" + "{0}/{1} Burned": "{0}/{1}が焼かれました", + "{error}": "" } \ No newline at end of file diff --git a/locale/ko.json b/locale/ko.json index 501ee82d0c..7dbb144314 100644 --- a/locale/ko.json +++ b/locale/ko.json @@ -35,8 +35,12 @@ "Borrow": "대출", "Borrowed": "차용금액", "Buy": "구매", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "확인 양식을 우회하고 높은 슬리피지 거래를 허용합니다. 위험을 감수하고 사용하세요.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "취소", "Cancelled": "취소됨", "Change": "변경", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "커뮤니티 승인", "Confirm": "확인", + "Confirm Action": "", "Confirm Adding Liquidity": "유동성 추가 확인", + "Confirm Creation": "", "Confirm Limit Order": "제한 주문 확인", "Confirm Staking": "스테이킹 확인", "Confirm Supply": "공급 확인", @@ -60,10 +66,13 @@ "Copied": "복사됨", "Copy Address": "주소 복사", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "풀 생성 및 공급", + "Create Tango CMM": "", "Create pool": "풀 만들기", "Current": "현재", "DAY": "", + "Delete Tango CMM": "", "Deposit": "예금", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "모든 수익에 대한 토큰을 Mirror에 입금하세요", @@ -89,6 +98,7 @@ "Expired": "만료됨", "Farm": "파밍", "Fee": "", + "Fill the parameters": "", "Find Pool": "풀 찾기", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "풀 가져오기", "In Mirror:": "Mirror 내:", "In Wallet:": "지갑 내:", + "Input an amount": "", "Input is estimated. You will sell at most": "입력값은 예상치입니다. 최대 판매는", "Insufficient Balance": "잔액 부족", "Insufficient liquidity for this trade": "이 거래를 위한 유동성 부족", "Insufficient {0} balance": "{0} 잔액 부족", "Interface Settings": "인터페이스 설정", + "Invalid Price": "", "Invalid pair": "잘못된 쌍", "Invalid recipient": "잘못된 수신자", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Mirror 잔액 : {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror는 Lend 시장과 같은 통합 dapp 간의 플래시 대출, 전략 및 고정 저가스 전송을 통해 예금에 대한 추가 수익률을 제공합니다.", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "내 유동성 포지션", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "가격 영향 높음", "Price Impact Too High": "가격 영향이 너무 높음", "Price Updated": "가격이 업데이트되었습니다", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "요율", "Rates": "요금", "Recent Transactions": "최근 거래", @@ -196,6 +213,8 @@ "Select a token": "토큰 선택", "Select a token to find your liquidity": "토큰을 선택하여 유동성 찾기", "Select an order expiration": "주문 만료 선택", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "전송:", "Share": "", "Share of Pool": "풀 지분", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "{0} {1} 및 {2} {3} 공급 중", "Swap": "스왑", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "전체 동결 가치", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Uniswap 불변 x*y=k가 스왑을 충족하지 않았습니다. 이는 일반적으로 스왑 중인 토큰 중 하나에 전송 시 사용자 지정 행동이 포함됨을 의미합니다.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "시장 가격과 거래 규모로 인한 예상 가격의 차이.", "The input token cannot be transferred. There may be an issue with the input token.": "인풋 토큰을 전송할 수 없습니다. 인풋 코튼에 문제가 있을 수 있습니다.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "아웃풋 토큰을 전송할 수 없습니다. 아웃풋 토큰에 문제가 있을 수 있습니다.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "마감일이 지났기 때문에 거래를 전송할 수 없습니다. 거래 마감일이 너무 짧지 않은지 확인하세요.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "인터페이스에 자동으로 나타나지 않는 쌍을 찾으려면 이 도구를 사용합니다", "Vesting is executed within the guidelines selected by the community in": "베스팅은 커뮤니티가 선택한 가이드라인 내에서 실행됩니다", "View Liquidity Positions": "유동성 포지션 보기", + "View Your Tango CMM": "", "View on explorer": "탐색기에서 보기", "Waiting for Confirmation": "확인 대기 중", "Wallet": "지갑", @@ -270,10 +298,13 @@ "You Pay:": "지불:", "You are creating a pool": "풀 생성 중", "You are on the wrong network": "잘못된 네트워크에 있습니다.", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "아직 이 풀에 유동성이 없습니다", "You pay:": "", "You receive:": "수령:", "You will receive": "예상 수령", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "귀하의 지분", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} 입금됨", "{0} {1} per {2}": "{2} 당 {0} {1}", "{0} {sign} market rate": "{0} {sign} 시세율", - "{0}/{1} Burned": "{0}/{1} 구움" + "{0}/{1} Burned": "{0}/{1} 구움", + "{error}": "" } \ No newline at end of file diff --git a/locale/pt_BR.json b/locale/pt_BR.json index 781664be13..c2c67dd480 100644 --- a/locale/pt_BR.json +++ b/locale/pt_BR.json @@ -35,8 +35,12 @@ "Borrow": "Pedir emprestado", "Borrowed": "Emprestado", "Buy": "Comprar", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Ignora os modais de confirmação e permite negociações com alto índice de deslizamento. Use por sua conta e risco.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Cancelar", "Cancelled": "Cancelado", "Change": "Alterar", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Aprovação da Comunidade", "Confirm": "Confirmar", + "Confirm Action": "", "Confirm Adding Liquidity": "Confirme a adição de liquidez", + "Confirm Creation": "", "Confirm Limit Order": "Confirme o pedido de limite", "Confirm Staking": "Confirmar agrupamento", "Confirm Supply": "Confirme o fornecimento", @@ -60,10 +66,13 @@ "Copied": "Copiado", "Copy Address": "Copiar endereço", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Criar pool e abastecimento", + "Create Tango CMM": "", "Create pool": "Criar pool", "Current": "Atual", "DAY": "", + "Delete Tango CMM": "", "Deposit": "Depósito", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Tokens de depósito em Mirror para todos os rendimentos", @@ -89,6 +98,7 @@ "Expired": "Expirado", "Farm": "Fazenda", "Fee": "", + "Fill the parameters": "", "Find Pool": "Encontrar pool", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Pool de importação", "In Mirror:": "Em Mirror:", "In Wallet:": "Na carteira:", + "Input an amount": "", "Input is estimated. You will sell at most": "A entrada é estimada. Você vai vender no máximo", "Insufficient Balance": "Saldo insuficiente", "Insufficient liquidity for this trade": "Liquidez insuficiente para essa transação", "Insufficient {0} balance": "Saldo {0} insuficiente", "Interface Settings": "Configurações de interface", + "Invalid Price": "", "Invalid pair": "Par inválido", "Invalid recipient": "Destinatário inválido", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Saldo Mirror: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror fornece rendimento extra em depósitos com empréstimos rápidos, estratégias e transferências fixas de baixo consumo de gás entre dapps integrados, como os mercados de Lend", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Minhas posições de liquidez", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "Impacto de preço alto", "Price Impact Too High": "Impacto de preço muito alto", "Price Updated": "Preço Atualizado", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Avaliar", "Rates": "Cotações", "Recent Transactions": "Transações Recentes", @@ -196,6 +213,8 @@ "Select a token": "Selecione um token", "Select a token to find your liquidity": "Selecione um token para encontrar sua liquidez", "Select an order expiration": "Selecione uma expiração de pedido", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Enviar para:", "Share": "", "Share of Pool": "Participação no pool", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "Fornecendo {0} {1} e {2} {3}", "Swap": "Trocar", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "O invariante Uniswap x*y = k não foi satisfeito pela troca. Isso geralmente significa que um dos tokens que você está trocando incorpora um comportamento personalizado na transferência.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "A diferença entre o preço de mercado e o preço estimado devido ao tamanho da negociação.", "The input token cannot be transferred. There may be an issue with the input token.": "O token de entrada não pode ser transferido. Pode haver um problema com o token de entrada.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "O token de saída não pode ser transferido. Pode haver um problema com o token de saída.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "A transação não pode ser enviada porque o prazo expirou. Verifique se o prazo da transação não é muito baixo.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Use esta ferramenta para encontrar pares que não aparecem automaticamente na interface", "Vesting is executed within the guidelines selected by the community in": "A aquisição é executada dentro das diretrizes selecionadas pela comunidade em", "View Liquidity Positions": "Ver Posições de Liquidez", + "View Your Tango CMM": "", "View on explorer": "Ver no explorer", "Waiting for Confirmation": "Aguardando confirmação", "Wallet": "Carteira", @@ -270,10 +298,13 @@ "You Pay:": "Você Paga:", "You are creating a pool": "Você está criando um pool", "You are on the wrong network": "Você está na rede errada", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Você ainda não tem liquidez neste pool", "You pay:": "", "You receive:": "Você recebe:", "You will receive": "Você receberá", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Suas apostas", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} depositado", "{0} {1} per {2}": "{0} {1} por {2}", "{0} {sign} market rate": "{0} {sign} taxa de mercado", - "{0}/{1} Burned": "{0} / {1} Utilizado" + "{0}/{1} Burned": "{0} / {1} Utilizado", + "{error}": "" } \ No newline at end of file diff --git a/locale/ro.json b/locale/ro.json index 834c3b4b16..768807ebb8 100644 --- a/locale/ro.json +++ b/locale/ro.json @@ -35,8 +35,12 @@ "Borrow": "Împrumutați", "Borrowed": "Împrumutat", "Buy": "Cumpărați", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Evită modurile de confirmare și permite tranzacții cu derapaje ridicate. Folosiți pe propria răspundere.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Anulare", "Cancelled": "Anulat", "Change": "Modificare", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Aprobarea comunității", "Confirm": "Confirmați", + "Confirm Action": "", "Confirm Adding Liquidity": "Confirmați adăugarea de lichidități", + "Confirm Creation": "", "Confirm Limit Order": "Confirmați limitarea comenzii", "Confirm Staking": "Confirmați investirea", "Confirm Supply": "Confirmați oferta", @@ -60,10 +66,13 @@ "Copied": "Copiat", "Copy Address": "Copiere adresă", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Creați fond comun și ofertă", + "Create Tango CMM": "", "Create pool": "Creați un fond comun", "Current": "Actual", "DAY": "", + "Delete Tango CMM": "", "Deposit": "Depuneți", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Depuneți token-uri în Mirror pentru toate randamentele", @@ -89,6 +98,7 @@ "Expired": "Expirat", "Farm": "Fermă", "Fee": "", + "Fill the parameters": "", "Find Pool": "Găsiți fond comun", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Importați Fond comun", "In Mirror:": "În Mirror:", "In Wallet:": "În portofel:", + "Input an amount": "", "Input is estimated. You will sell at most": "Valoarea de intrare este estimată. Veți vinde cel mult", "Insufficient Balance": "Sold insuficient", "Insufficient liquidity for this trade": "Lichidități insuficiente pentru această tranzacție", "Insufficient {0} balance": "Sold {0} insuficient", "Interface Settings": "Setări interfață", + "Invalid Price": "", "Invalid pair": "Pereche nevalidă", "Invalid recipient": "Destinatar nevalid", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Sold Mirror: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror oferă un randament suplimentar la depozite cu împrumuturi flash, strategii și transferuri fixe, cu consum redus de gaze între dapp-uri integrate, cum ar fi piețele Lend", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Pozițiile lichidităților mele", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "Impactul asupra prețului este mare", "Price Impact Too High": "Impactul asupra prețului este prea mare", "Price Updated": "Preț actualizat", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Rată", "Rates": "Rate", "Recent Transactions": "Tranzacții recente", @@ -196,6 +213,8 @@ "Select a token": "Selectați un token", "Select a token to find your liquidity": "Selectați un token pentru a găsi lichiditatea", "Select an order expiration": "Selectați o dată de expirare a comenzii", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Trimite către:", "Share": "", "Share of Pool": "Cota din fondul comun", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "Oferire {0} {1} și {2} {3}", "Swap": "Swap", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Invariabila Uniswap x*y=k nu a fost acceptată de swap. Acest lucru înseamnă, de obicei, că unul dintre token-urile pe care le schimbați încorporează un comportament personalizat la transfer.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "Diferența dintre prețul pieței și prețul estimat ca urmare a dimensiunii tranzacției.", "The input token cannot be transferred. There may be an issue with the input token.": "Token-ul de intrare nu poate fi transferat. S-ar putea să existe o problemă cu token-ul de ieșire.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "Token-ul de ieșire nu poate fi transferat. S-ar putea să existe o problemă cu token-ul de ieșire.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "Tranzacția nu a putut fi trimisă deoarece termenul a expirat. Vă rugăm să verificați dacă termenul limită al tranzacției nu este prea mic.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Utilizați acest instrument pentru a găsi perechi care nu apar automat în interfață", "Vesting is executed within the guidelines selected by the community in": "Dobândirea drepturilor este realizată în cadrul liniilor directoare selectate de comunitate în", "View Liquidity Positions": "Vizualizați pozițiile lichidităților", + "View Your Tango CMM": "", "View on explorer": "Vizualizați în explorator", "Waiting for Confirmation": "Se așteaptă confirmarea", "Wallet": "Portofel", @@ -270,10 +298,13 @@ "You Pay:": "Veți plăti:", "You are creating a pool": "Creați un fond comun", "You are on the wrong network": "Vă aflați în rețeaua greșită", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Încă nu aveți lichidități în acest fond comun", "You pay:": "", "You receive:": "Veți primi:", "You will receive": "Veți primi", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Sumele dvs. investite", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} Depus", "{0} {1} per {2}": "{0} {1} per {2}", "{0} {sign} market rate": "{0} {sign} cota pieței", - "{0}/{1} Burned": "{0}/{1} ars" + "{0}/{1} Burned": "{0}/{1} ars", + "{error}": "" } \ No newline at end of file diff --git a/locale/ru.json b/locale/ru.json index 6030c98180..af883f6100 100644 --- a/locale/ru.json +++ b/locale/ru.json @@ -35,8 +35,12 @@ "Borrow": "Взять в кредит", "Borrowed": "Взято в кредит", "Buy": "Купить", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Обходит режимы подтверждения и допускает сделки с высоким проскальзыванием. Используйте на свой риск.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Отменить", "Cancelled": "Отменено", "Change": "Сменить", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Утверждение сообщества", "Confirm": "Подтвердить", + "Confirm Action": "", "Confirm Adding Liquidity": "Подтвердите добавление ликвидности", + "Confirm Creation": "", "Confirm Limit Order": "Подтвердить лимитную заявку", "Confirm Staking": "Подтвердите стейкинг", "Confirm Supply": "Подтвердите поставку", @@ -60,10 +66,13 @@ "Copied": "Скопировано", "Copy Address": "Копировать адрес", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Создать пул и поставку", + "Create Tango CMM": "", "Create pool": "Создать пул", "Current": "Последний", "DAY": "", + "Delete Tango CMM": "", "Deposit": "Депозит", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Внесите токены в Mirror для всех доходов", @@ -89,6 +98,7 @@ "Expired": "Срок действия истек", "Farm": "Ферма", "Fee": "", + "Fill the parameters": "", "Find Pool": "Найти пул", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Импортировать пул", "In Mirror:": "В Mirror:", "In Wallet:": "В кошельке:", + "Input an amount": "", "Input is estimated. You will sell at most": "Ввод оценен. Вы продадите не менее", "Insufficient Balance": "Недостаточный остаток", "Insufficient liquidity for this trade": "Недостаточная ликвидность для этой сделки", "Insufficient {0} balance": "Недостаточный остаток {0}", "Interface Settings": "Настройки интерфейса", + "Invalid Price": "", "Invalid pair": "Недействительная пара", "Invalid recipient": "Недействительный получатель", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Баланс Mirror: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror обеспечивает дополнительную доходность по депозитам с помощью мгновенного кредитования, стратегий и экономичных фиксированных переводов между такими интегрированными децентрализованными приложениями, как рынки Lend", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Мои позиции ликвидности", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "Сильное влияние на цену", "Price Impact Too High": "Слишком сильное влияние на цену", "Price Updated": "Цена обновлена", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Ставка", "Rates": "Тарифы", "Recent Transactions": "Последние транзакции", @@ -196,6 +213,8 @@ "Select a token": "Выберите токен", "Select a token to find your liquidity": "Выберите токен, чтобы узнать свою ликвидность", "Select an order expiration": "Выберите срок действия заказа", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Отправить:", "Share": "", "Share of Pool": "Доля пула", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "Поставка {0} {1} и {2} {3}", "Swap": "Обменять", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Инвариант Uniswap x*y=k не был удовлетворен при обмене. Обычно это означает, что один из токенов, которые вы обмениваете, включает пользовательское поведение при переводе.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "Разница между рыночной ценой и оценочной ценой из-за размера сделки.", "The input token cannot be transferred. There may be an issue with the input token.": "Входной токен не может быть переведен. Возможно, возникла проблема со входным токеном.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "Выходной токен не может быть переведен. Возможно, возникла проблема с выходным токеном.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "Транзакция не может быть отправлена, потому что истек ее крайний срок. Проверьте, не слишком ли мал крайний срок транзакции.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Используйте этот инструмент, чтобы находить пары, которые автоматически не отображаются в интерфейсе", "Vesting is executed within the guidelines selected by the community in": "Наделение правами осуществляется в соответствии с руководящими принципами, выбранными сообществом в", "View Liquidity Positions": "Просмотреть позиции по ликвидности", + "View Your Tango CMM": "", "View on explorer": "Посмотреть в проводнике", "Waiting for Confirmation": "Ожидание подтверждения", "Wallet": "Кошелек", @@ -270,10 +298,13 @@ "You Pay:": "Вы заплатите:", "You are creating a pool": "Вы создаете пул", "You are on the wrong network": "Вы не в той сети", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "У вас еще нет ликвидности в этом пуле", "You pay:": "", "You receive:": "Вы получите:", "You will receive": "Вы получите", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Ваша ставка", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "Внесено {0}", "{0} {1} per {2}": "{0} {1} за {2}", "{0} {sign} market rate": "{0} {sign} рыночной ставки", - "{0}/{1} Burned": "{0}/{1} сожжено" + "{0}/{1} Burned": "{0}/{1} сожжено", + "{error}": "" } \ No newline at end of file diff --git a/locale/tr.json b/locale/tr.json index 4c58464d70..446a7a2c1a 100644 --- a/locale/tr.json +++ b/locale/tr.json @@ -35,8 +35,12 @@ "Borrow": "Borç al", "Borrowed": "Borç alındı", "Buy": "Al", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "Likidite ekleyerek havuzdaki payına göre bu çiftteki her alım-satımın %0,25'ini kazanacaksın.", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Doğrulama şekillerini atlatır ve yüksek slipajlı ticarete olanak sağlar. Kendi sorumluluğunuzda kullanın.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "İptal", "Cancelled": "İptal edildi", "Change": "Değiştir", @@ -48,7 +52,9 @@ "Common bases": "Ortak tabanlar", "Community Approval": "Topluluk Onayı", "Confirm": "Onayla", + "Confirm Action": "", "Confirm Adding Liquidity": "Likidite Eklemeyi Onayla", + "Confirm Creation": "", "Confirm Limit Order": "Limit Emrini Onayla", "Confirm Staking": "Stake Yapmayı Onayla", "Confirm Supply": "Tedariği Onayla", @@ -60,10 +66,13 @@ "Copied": "Kopyalandı", "Copy Address": "Adresi Kopyala", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Havuz & Tedarik Yarat", + "Create Tango CMM": "", "Create pool": "Havuz yarat", "Current": "Şimdiki", "DAY": "GÜN", + "Delete Tango CMM": "", "Deposit": "Yatır", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "", @@ -89,6 +98,7 @@ "Expired": "Süresi Dolmuş", "Farm": "Farm", "Fee": "", + "Fill the parameters": "", "Find Pool": "Havuz Bul", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Havuz Aktar", "In Mirror:": "Mirror'da:", "In Wallet:": "Cüzdanda:", + "Input an amount": "", "Input is estimated. You will sell at most": "Girdi tahminidir. Sen en yüksekte satacaksın.", "Insufficient Balance": "Yetersiz Bakiye", "Insufficient liquidity for this trade": "Bu ticaret için yetersiz likidite", "Insufficient {0} balance": "Yetersiz {0} bakiyesi", "Interface Settings": "Arayüz Ayarları", + "Invalid Price": "", "Invalid pair": "Geçersiz çift", "Invalid recipient": "Geçersiz alıcı", "Join the community on Telegram.": "Telegram topluluğuna katıl.", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Likidite Pozisyonlarım", "My TANGO": "", "New to SmartBCH?": "SmartBCH'ye yeni misin?", @@ -173,6 +187,9 @@ "Price Impact High": "Fiyat Etkisi Yüksek", "Price Impact Too High": "Fiyat Etkisi Çok Yüksek", "Price Updated": "Fiyat Güncellendi", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Kur", "Rates": "Kurlar", "Recent Transactions": "Son İşlemler", @@ -196,6 +213,8 @@ "Select a token": "Bir token seç", "Select a token to find your liquidity": "Likiditeni bulmak için bir token seç", "Select an order expiration": "Emrin sona erme tarihini seç", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Buraya yolla:", "Share": "", "Share of Pool": "Havuzdaki Pay", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "Tedarik Faizi", "Supplying {0} {1} and {2} {3}": "{0} {1} ve {2} {3} tedariği sağlanıyor", "Swap": "Takas Et", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "Telegram", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Uniswap sabiti olan x*y=k takas tarafından sağlanamadı. Bu genellikle takas ettiğin tokenlerden birinin işlemlerde özel bir durum içerdiği anlamına gelir.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "Piyasa fiyatı ile ticaret büyüklüğüne bağlı olarak hesaplanan tahmini fiyat arasındaki fark.", "The input token cannot be transferred. There may be an issue with the input token.": "Girdi tokeni transfer edilemedi. Girdi tokeni ile ilgili bir sorun olabilir.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "Bu miktarı çekmek için şuan yeterli likidite yok. Lütfen daha az miktarda çekmeye çalışın ya da daha sonra deneyin.", "The output token cannot be transferred. There may be an issue with the output token.": "Çıktı tokeni transfer edilemedi. Çıktı tokeni ile ilgili bir sorun olabilir.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "İşlem gönderilemedi çünkü son tarih aşıldı. Lütfen işleminin sona erme tarihinin çok az olmadığını kontrol et.", "These tokens are commonly paired with other tokens.": "Bu tokenler genellikle diğer tokenlerle eşlenmiştir.", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Arayüzde otomatik olarak gözükmeyen çiftleri bulmak için bu aracı kullan", "Vesting is executed within the guidelines selected by the community in": "Vesting, topluluk tarafından seçilen yönergeler ile gerçekleştirildi", "View Liquidity Positions": "Likidite Pozisyonlarını Gör", + "View Your Tango CMM": "", "View on explorer": "Kaşifte gör", "Waiting for Confirmation": "Onay için Bekleniyor", "Wallet": "Cüzdan", @@ -270,10 +298,13 @@ "You Pay:": "Ödenilecek:", "You are creating a pool": "Bir havuz oluşturuyorsun", "You are on the wrong network": "Yanlış ağda bulunuyorsun", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Henüz bu havuzda likiditen yok", "You pay:": "", "You receive:": "Alınacak", "You will receive": "Alınacak", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Senin Stake Edilmiş", "Your browser is not supported, please install": "Tarayıcın desteklenmiyor, lütfen şunu indir", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} Yatırıldı", "{0} {1} per {2}": "{2} başına {0} {1}", "{0} {sign} market rate": "{0} {sign} piyasa kuru", - "{0}/{1} Burned": "{0}/{1} Yakıldı" + "{0}/{1} Burned": "{0}/{1} Yakıldı", + "{error}": "" } \ No newline at end of file diff --git a/locale/vi.json b/locale/vi.json index 2f0b8aadfb..1f5402c522 100644 --- a/locale/vi.json +++ b/locale/vi.json @@ -35,8 +35,12 @@ "Borrow": "Vay", "Borrowed": "Đã vay", "Buy": "Mua", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "Bỏ qua các phương thức xác nhận và cho phép các giao dịch có độ trượt giá cao. Bạn phải tự chịu rủi ro khi sử dụng.", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "Hủy bỏ", "Cancelled": "Đã hủy bỏ", "Change": "Thay đổi", @@ -48,7 +52,9 @@ "Common bases": "", "Community Approval": "Phê duyệt của cộng đồng", "Confirm": "Xác nhận", + "Confirm Action": "", "Confirm Adding Liquidity": "Xác nhận thêm thanh khoản", + "Confirm Creation": "", "Confirm Limit Order": "Xác nhận lệnh giới hạn", "Confirm Staking": "Xác nhận đặt cược", "Confirm Supply": "Xác nhận tổng cung", @@ -60,10 +66,13 @@ "Copied": "Đã sao chép", "Copy Address": "Sao chép địa chỉ", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "Tạo mạng lưới & tổng cung", + "Create Tango CMM": "", "Create pool": "Tạo mạng lưới", "Current": "Hiện tại", "DAY": "", + "Delete Tango CMM": "", "Deposit": "Ký quỹ", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "Ký quỹ token vào Mirror để nhận tất cả lợi suất", @@ -89,6 +98,7 @@ "Expired": "Đã hết hạn", "Farm": "Trang trại", "Fee": "", + "Fill the parameters": "", "Find Pool": "Tìm mạng lưới", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "", @@ -103,11 +113,13 @@ "Import Pool": "Nhập mạng lưới", "In Mirror:": "Trong Mirror:", "In Wallet:": "Trong ví", + "Input an amount": "", "Input is estimated. You will sell at most": "Đầu vào đã được ước tính. Bạn sẽ bán được nhiều nhất", "Insufficient Balance": "Số dư không đủ", "Insufficient liquidity for this trade": "Không đủ thanh khoản cho giao dịch này", "Insufficient {0} balance": "Số dư {0} không đủ", "Interface Settings": "Cài đặt giao diện", + "Invalid Price": "", "Invalid pair": "Cặp không hợp lệ", "Invalid recipient": "Người nhận không hợp lệ", "Join the community on Telegram.": "", @@ -138,6 +150,8 @@ "Mirror": "Mirror", "Mirror Balance: {0}": "Số dư Mirror: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "Mirror cung cấp thêm lợi suất ký quỹ với cho vay nhanh, chiến lược và chuyển khoản cố định, tiết kiệm giữa các ứng dụng phi tập trung được tích hợp, như thị trường Lend", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "Vị thế thanh khoản của tôi", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "Tác động giá cao", "Price Impact Too High": "Tác động giá quá cao", "Price Updated": "Đã cập nhật giá", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "Tỷ giá", "Rates": "Tỷ giá", "Recent Transactions": "Giao dịch gần đây", @@ -196,6 +213,8 @@ "Select a token": "Chọn một token", "Select a token to find your liquidity": "Chọn một token để tìm thanh khoản của bạn", "Select an order expiration": "Chọn một lệnh đã hết hạn", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "Gửi đến:", "Share": "", "Share of Pool": "Cổ phần trong mạng lưới", @@ -213,6 +232,9 @@ "Stake TANGO": "", "Stake TANGO for xTANGO": "", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "", "Supplying {0} {1} and {2} {3}": "Tổng cung {0} {1} và {2} {3}", "Swap": "Hoán đổi", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "Bất biến Uniswap x*y=k không được thỏa mãn bởi giao dịch hoán đổi. Điều này thường có nghĩa là một trong những token bạn đang hoán đổi kết hợp hành vi tùy chỉnh khi chuyển.", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "Sự khác biệt giữa giá thị trường và giá ước tính theo quy mô giao dịch.", "The input token cannot be transferred. There may be an issue with the input token.": "Không thể chuyển token đầu vào. Có thể đã xảy ra sự cố với token đầu vào.", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "Không thể chuyển token đầu ra. Có thể đã xảy ra sự cố với token đầu ra.", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "Không thể gửi giao dịch vì đã hết thời hạn. Vui lòng kiểm tra xem thời hạn giao dịch của bạn không quá thấp.", "These tokens are commonly paired with other tokens.": "", "Things you can do with your TANGO": "", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "Sử dụng công cụ này để tìm các cặp không tự động xuất hiện trong giao diện", "Vesting is executed within the guidelines selected by the community in": "Phân bổ được thực hiện theo các nguyên tắc được cộng đồng lựa chọn trong", "View Liquidity Positions": "Xem vị thế thanh khoản", + "View Your Tango CMM": "", "View on explorer": "Xem trên explorer", "Waiting for Confirmation": "Đang chờ xác nhận", "Wallet": "Ví tiền", @@ -270,10 +298,13 @@ "You Pay:": "Bạn thanh toán:", "You are creating a pool": "Bạn đang tạo một mạng lưới", "You are on the wrong network": "Bạn đang kết nối sai mạng", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "Bạn chưa có thanh khoản trong mạng lưới này", "You pay:": "", "You receive:": "Bạn nhận được:", "You will receive": "Bạn sẽ nhận được", + "Your CMM": "", "Your Claimable TANGO this Week": "", "Your Staked": "Đặt cược của bạn", "Your browser is not supported, please install": "", @@ -302,5 +333,6 @@ "{0} Deposited": "{0} Đã ký quỹ", "{0} {1} per {2}": "{0} {1} mỗi {2}", "{0} {sign} market rate": "{0} {sign} tỉ giá thị trường", - "{0}/{1} Burned": "{0}/{1} đã được đốt" + "{0}/{1} Burned": "{0}/{1} đã được đốt", + "{error}": "" } \ No newline at end of file diff --git a/locale/zh_CN.json b/locale/zh_CN.json index c0b8d79eb4..a75bd2390d 100644 --- a/locale/zh_CN.json +++ b/locale/zh_CN.json @@ -35,8 +35,12 @@ "Borrow": "借", "Borrowed": "已借入", "Buy": "购买", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "通过添加流动性,您将获得该货币对每笔交易的 0.25% 乘上您在池中所占的份额比例。手续费将被添加到池中,取消提供流动性时可同时获得这些随时间累积的手续费。", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "跳过确认、接受交易高滑点。使用时风险自行承担。", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "取消", "Cancelled": "已取消", "Change": "变更", @@ -48,7 +52,9 @@ "Common bases": "一般基准", "Community Approval": "社区批准", "Confirm": "确认", + "Confirm Action": "", "Confirm Adding Liquidity": "确认添加流动性", + "Confirm Creation": "", "Confirm Limit Order": "确认止损订单", "Confirm Staking": "确认质押", "Confirm Supply": "确认供应", @@ -60,10 +66,13 @@ "Copied": "已复制", "Copy Address": "复制地址", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "创建资金池及供应代币", + "Create Tango CMM": "", "Create pool": "创建资金池", "Current": "目前的", "DAY": "天", + "Delete Tango CMM": "", "Deposit": "存款", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "将代币存入镜子,以获得所有收益。", @@ -89,6 +98,7 @@ "Expired": "逾期", "Farm": "农场", "Fee": "", + "Fill the parameters": "", "Find Pool": "查询资金池", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "每条链上之每一笔交易的 0.05% 手续费,以您的 TangoBar 份额比例分配 TANGO。\n当您的 TANGO 被质押到 TangoBar 时,您将收到 xTANGO 作为回报。\n您的 xTANGO 将不断复利,当您取消质押时,您将收到所有最初存入的 TANGO 加上手续费转成的 TANGO 利息。", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "通过 xTANGO 获得治理权并获得 5% 的年利率(所有链上每笔交易的 0.05%)", @@ -103,11 +113,13 @@ "Import Pool": "导入资金池", "In Mirror:": "在镜子:", "In Wallet:": "在钱包中:", + "Input an amount": "", "Input is estimated. You will sell at most": "已估计输入的数量,您最多将卖出", "Insufficient Balance": "余额不足", "Insufficient liquidity for this trade": "该交易的流动性不足", "Insufficient {0} balance": "代币{0}余额不足", "Interface Settings": "进阶设定", + "Invalid Price": "", "Invalid pair": "无效的代币对", "Invalid recipient": "无效接收人", "Join the community on Telegram.": "加入Telegram社区。", @@ -138,6 +150,8 @@ "Mirror": "镜子", "Mirror Balance: {0}": "镜子余额: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "镜子通过在集成的dapp中使用闪电贷、策略以及固定和低Gas Fee的转帐,来提供额外收益", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "我的流动性仓位", "My TANGO": "", "New to SmartBCH?": "", @@ -173,6 +187,9 @@ "Price Impact High": "价格影响高", "Price Impact Too High": "价格影响过高", "Price Updated": "价格更新", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "利率", "Rates": "费率", "Recent Transactions": "最近交易", @@ -196,6 +213,8 @@ "Select a token": "选择代币", "Select a token to find your liquidity": "选择代币以找到您的流动性", "Select an order expiration": "选择订单到期期限", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "传送至:", "Share": "", "Share of Pool": "所占资金池份额", @@ -213,6 +232,9 @@ "Stake TANGO": "质押 TANGO", "Stake TANGO for xTANGO": "将 TANGO 质押成 xTANGO", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "一键将抵押品加入 xTANGO,将抵押品添加为 Aave 上的 axTANGO”", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "供应年化收益率", "Supplying {0} {1} and {2} {3}": "提供{0} {1}和{2} {3}", "Swap": "兑换", @@ -226,12 +248,17 @@ "TANGOswap": "", "TVL": "TVL", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "该交易不满足 Uniswap 恒定乘积公式 x*y=k。这通常意味着您正在交换的其中一个代币在转账时包含了自定义行为。", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "因为交易规模所导致的市场价格和预计价格之间的差距。", "The input token cannot be transferred. There may be an issue with the input token.": "输入的代币不能被转账。这可能和您输入的代币有关系。", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "", "The output token cannot be transferred. There may be an issue with the output token.": "无法转出代币。转出的代币可能有问题。", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "由于截止期限已过,交易无法传送。请检查您的交易截止期限。", "These tokens are commonly paired with other tokens.": "这些代币通常与其他代币配对", "Things you can do with your TANGO": "你可以用 TANGO 做的事情", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "使用此工具查找没有自动显示的交易配对", "Vesting is executed within the guidelines selected by the community in": "授领权是社群根据选择的指南执行", "View Liquidity Positions": "查看流动性仓位", + "View Your Tango CMM": "", "View on explorer": "在浏览器上查看", "Waiting for Confirmation": "等待确认中", "Wallet": "钱包", @@ -270,10 +298,13 @@ "You Pay:": "您支付:", "You are creating a pool": "您正在建立一个资金池", "You are on the wrong network": "您位在错误的网路", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "您的这个资金池中还没有流动性", "You pay:": "", "You receive:": "您收到:", "You will receive": "您将收到", + "Your CMM": "", "Your Claimable TANGO this Week": "您这周可获得的 TANGO", "Your Staked": "您已质押", "Your browser is not supported, please install": "不支援您的浏览器,请安装", @@ -302,5 +333,6 @@ "{0} Deposited": "{0}存入的", "{0} {1} per {2}": "{0}{1} 比 1 {2}", "{0} {sign} market rate": "{0} {sign} 市场汇率", - "{0}/{1} Burned": "{0}/{1} 销毁" + "{0}/{1} Burned": "{0}/{1} 销毁", + "{error}": "" } \ No newline at end of file diff --git a/locale/zh_TW.json b/locale/zh_TW.json index 12cf2a5292..63ed41123d 100644 --- a/locale/zh_TW.json +++ b/locale/zh_TW.json @@ -35,8 +35,12 @@ "Borrow": "借", "Borrowed": "已借入", "Buy": "購買", + "Buy {0} from CMM": "", "By adding liquidity you'll earn 0.25% of all trades on this pair proportional to your share of the pool. Fees are added to the pool, accrue in real time and can be claimed by withdrawing your liquidity.": "通過添加流動性,您將獲得該貨幣對每筆交易的 0.25% 乘上您在池中所佔的份額比例。手續費將被添加到池中,取消提供流動性時可同時獲得這些隨時間累積的手續費。", "Bypasses confirmation modals and allows high slippage trades. Use at your own risk.": "跳過確認、接受交易高滑點。使用時風險自行承擔。", + "CMM Market": "", + "CMM has not enough money": "", + "CMM has not enough stock": "", "Cancel": "取消", "Cancelled": "已取消", "Change": "變更", @@ -48,7 +52,9 @@ "Common bases": "一般基準", "Community Approval": "社區批準", "Confirm": "確認", + "Confirm Action": "", "Confirm Adding Liquidity": "確認添加流動性", + "Confirm Creation": "", "Confirm Limit Order": "確認止損訂單", "Confirm Staking": "確認質押", "Confirm Supply": "確認供應", @@ -60,10 +66,13 @@ "Copied": "已複製", "Copy Address": "複製地址", "Create Limit Order": "", + "Create Market": "", "Create Pool & Supply": "創建資金池及供應代幣", + "Create Tango CMM": "", "Create pool": "創建資金池", "Current": "目前的", "DAY": "天", + "Delete Tango CMM": "", "Deposit": "存款", "Deposit TANGO into BentoBox": "", "Deposit tokens into Mirror for all the yields": "將代幣存入镜子,以獲得所有收益。", @@ -89,6 +98,7 @@ "Expired": "逾期", "Farm": "農場", "Fee": "", + "Fill the parameters": "", "Find Pool": "查詢資金池", "For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as TANGO\nproportional to your share of the TangoBar. When your TANGO is staked into the TangoBar, you receive\nxTANGO in return.\nYour xTANGO is continuously compounding, when you unstake you will receive all the originally deposited\nTANGO and any additional from fees.": "每條鏈上之每一筆交易的 0.05% 手續費,以您的 TangoBar 份額比例分配 TANGO。\n當您的 TANGO 被質押到 TangoBar 時,您將收到 xTANGO 作為回報。\n您的 xTANGO 將不斷複利,當您取消質押時,您將收到所有最初存入的 TANGO 加上手續費轉成的 TANGO 利息。", "Gain governance rights with xTANGO and earn 5% APR (0.05% of\nall swaps from all chains)": "通過 xTANGO 獲得治理權並獲得 5% 的年利率(所有鏈上每筆交易的 0.05%)", @@ -103,11 +113,13 @@ "Import Pool": "導入資金池", "In Mirror:": "在镜子:", "In Wallet:": "在錢包中:", + "Input an amount": "", "Input is estimated. You will sell at most": "已估計輸入的數量,您最多將賣出", "Insufficient Balance": "餘額不足", "Insufficient liquidity for this trade": "該交易的流動性不足", "Insufficient {0} balance": "代幣{0}餘額不足", "Interface Settings": "進階設定", + "Invalid Price": "", "Invalid pair": "無效的代幣對", "Invalid recipient": "無效接收人", "Join the community on Telegram.": "加入Telegram社區。", @@ -138,6 +150,8 @@ "Mirror": "镜子", "Mirror Balance: {0}": "镜子餘額: {0}", "Mirror provides extra yield on deposits with flash lending, strategies, and fixed, low-gas transfers among integrated dapps, like Lend markets": "镜子通過在集成的dapp中使用閃電貸、策略以及固定和低Gas Fee的轉帳,來提供額外收益", + "Money: < 0.001": "", + "Money: {0}": "", "My Liquidity Positions": "我的流動性倉位", "My TANGO": "我的 TANGO", "New to SmartBCH?": "你是SmartBCH新手嗎?", @@ -173,6 +187,9 @@ "Price Impact High": "價格影響高", "Price Impact Too High": "價格影響過高", "Price Updated": "價格更新", + "Price to Buy": "", + "Price to Buy {0}": "", + "Price to Sell": "", "Rate": "利率", "Rates": "費率", "Recent Transactions": "最近交易", @@ -196,6 +213,8 @@ "Select a token": "選擇代幣", "Select a token to find your liquidity": "選擇代幣以找到您的流動性", "Select an order expiration": "選擇訂單到期期限", + "Sell": "", + "Sell {0} to CMM": "", "Send to:": "傳送至:", "Share": "", "Share of Pool": "所佔資金池份額", @@ -213,6 +232,9 @@ "Stake TANGO": "質押 TANGO", "Stake TANGO for xTANGO": "將 TANGO 質押成 xTANGO", "Stake into xTANGO add collateral as axTANGO on Aave all in\none click": "一鍵將抵押品加入 xTANGO,將抵押品添加為 Aave 上的 axTANGO”", + "Stock/Money": "", + "Stock: < 0.001": "", + "Stock: {0}": "", "Supply APR": "供應年化收益率", "Supplying {0} {1} and {2} {3}": "提供{0} {1}和{2} {3}", "Swap": "代幣兌換", @@ -226,12 +248,17 @@ "TANGOswap": "TANGOswap", "TVL": "總鎖倉價值", "Take Limit Order": "", + "Tango CMM": "", "Telegram": "", "The Uniswap invariant x*y=k was not satisfied by the swap. This usually means one of the tokens you are swapping incorporates custom behavior on transfer.": "交易不滿足 Uniswap 不變公式 x*y=k。這通常表示您要交易的代幣之一在轉帳時包含自定義行為。", + "The amount of {0} that the user will spend for {1}": "", + "The amount of {0} that the user will spend for {1}": "", "The difference between the market price and estimated price due to trade size.": "因為交易規模所導致的市場價格和您的價格之間的差距。", "The input token cannot be transferred. There may be an issue with the input token.": "無法轉入代幣。轉入的代幣可能有問題。", "The isn't enough liquidity available at the moment to withdraw this amount. Please try withdrawing less or later.": "目前沒有足夠的流動性來提取這筆金額。請嘗試減少提款或稍後再試。", "The output token cannot be transferred. There may be an issue with the output token.": "無法轉出代幣。轉出的代幣可能有問題。", + "The price that the user will buy {0}": "", + "The price that the user will sell {0}": "", "The transaction could not be sent because the deadline has passed. Please check that your transaction deadline is not too low.": "由於截止期限已過,交易無法傳送。請檢查您的交易截止期限。", "These tokens are commonly paired with other tokens.": "這些代幣通常與其他代幣配對", "Things you can do with your TANGO": "你可以用 TANGO 做的事情", @@ -259,6 +286,7 @@ "Use this tool to find pairs that don't automatically appear in the interface": "使用此工具查找沒有自動顯示的交易配對", "Vesting is executed within the guidelines selected by the community in": "授領權是社群根據選擇的指南執行", "View Liquidity Positions": "查看流動性倉位", + "View Your Tango CMM": "", "View on explorer": "在瀏覽器上查看", "Waiting for Confirmation": "等待確認中", "Wallet": "錢包", @@ -270,10 +298,13 @@ "You Pay:": "您支付:", "You are creating a pool": "您正在建立一個資金池", "You are on the wrong network": "您位在錯誤的網路", + "You don't have enough Money": "", + "You don't have enough Stock": "", "You don’t have liquidity in this pool yet": "您的這個資金池中還沒有流動性", "You pay:": "", "You receive:": "您收到:", "You will receive": "您將收到", + "Your CMM": "", "Your Claimable TANGO this Week": "您這週可獲得的 TANGO", "Your Staked": "您已質押", "Your browser is not supported, please install": "不支援您的瀏覽器,請安裝", @@ -302,5 +333,6 @@ "{0} Deposited": "{0}存入的", "{0} {1} per {2}": "{0}{1} 比 1 {2}", "{0} {sign} market rate": "{0} {sign} 市場匯率", - "{0}/{1} Burned": "{0}/{1} 銷毀" + "{0}/{1} Burned": "{0}/{1} 銷毀", + "{error}": "" } \ No newline at end of file