diff --git a/package-lock.json b/package-lock.json index c30d5acf..533efca3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1135,16 +1135,6 @@ "resolved": "https://registry.npmjs.org/@bugsnag/plugin-react/-/plugin-react-6.2.0.tgz", "integrity": "sha512-JI56D3ZhXGjH5UqeSTltdxVTPjMpfNI/Vd5XP0V/gBAJb6CeILX3hLe5G1VmxxZciVNEfG5724YKgadqp6/uWg==" }, - "@chainlink/contracts-0.0.3": { - "version": "npm:@chainlink/contracts@0.0.3", - "resolved": "https://registry.npmjs.org/@chainlink/contracts/-/contracts-0.0.3.tgz", - "integrity": "sha512-mI/FhOL4J+sN8JaQJovAOnuKJSshCgr5ZIqItknJWd8p87wcVPa5/IOPJDy35tIpSCwegyNNkAsTmts9EWH7iA==", - "requires": { - "@truffle/contract": "^4.1.8", - "@types/inquirer": "^6.5.0", - "ethers": "^4.0.44" - } - }, "@cnakazawa/watch": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@cnakazawa/watch/-/watch-1.0.4.tgz", @@ -18666,11 +18656,6 @@ } } }, - "openzeppelin-solidity-2.3.0": { - "version": "npm:openzeppelin-solidity@2.3.0", - "resolved": "https://registry.npmjs.org/openzeppelin-solidity/-/openzeppelin-solidity-2.3.0.tgz", - "integrity": "sha512-QYeiPLvB1oSbDt6lDQvvpx7k8ODczvE474hb2kLXZBPKMsxKT1WxTCHBYrCU7kS7hfAku4DcJ0jqOyL+jvjwQw==" - }, "opn": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/opn/-/opn-5.5.0.tgz", @@ -24146,10 +24131,25 @@ "web3-utils": "1.2.2" }, "dependencies": { + "@chainlink/contracts-0.0.3": { + "version": "npm:@chainlink/contracts@0.0.3", + "resolved": "https://registry.npmjs.org/@chainlink/contracts/-/contracts-0.0.3.tgz", + "integrity": "sha512-mI/FhOL4J+sN8JaQJovAOnuKJSshCgr5ZIqItknJWd8p87wcVPa5/IOPJDy35tIpSCwegyNNkAsTmts9EWH7iA==", + "requires": { + "@truffle/contract": "^4.1.8", + "@types/inquirer": "^6.5.0", + "ethers": "^4.0.44" + } + }, "commander": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz", "integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==" + }, + "openzeppelin-solidity-2.3.0": { + "version": "npm:openzeppelin-solidity@2.3.0", + "resolved": "https://registry.npmjs.org/openzeppelin-solidity/-/openzeppelin-solidity-2.3.0.tgz", + "integrity": "sha512-QYeiPLvB1oSbDt6lDQvvpx7k8ODczvE474hb2kLXZBPKMsxKT1WxTCHBYrCU7kS7hfAku4DcJ0jqOyL+jvjwQw==" } } }, diff --git a/src/pages/Trade/components/CreateOrderCard/CreateOrderCard.js b/src/pages/Trade/components/CreateOrderCard/CreateOrderCard.tsx similarity index 62% rename from src/pages/Trade/components/CreateOrderCard/CreateOrderCard.js rename to src/pages/Trade/components/CreateOrderCard/CreateOrderCard.tsx index 3f68078e..6d1c11d3 100644 --- a/src/pages/Trade/components/CreateOrderCard/CreateOrderCard.js +++ b/src/pages/Trade/components/CreateOrderCard/CreateOrderCard.tsx @@ -1,5 +1,5 @@ -import React, { useState, useEffect, useContext, useCallback } from 'react'; -import { connect } from 'react-redux'; +import React, { FC, useState, useEffect, useContext, useCallback } from 'react'; +import { connect, ConnectedProps } from 'react-redux'; import styled, { ThemeContext } from 'styled-components'; import { useTranslation } from 'react-i18next'; import isEmpty from 'lodash/isEmpty'; @@ -13,6 +13,7 @@ import { getWalletInfo } from 'ducks/wallet/walletDetails'; import { getSynthsWalletBalances } from 'ducks/wallet/walletBalances'; import { getSynthPair, getAvailableSynthsMap } from 'ducks/synths'; import { getRatesExchangeRates, getEthRate } from 'ducks/rates'; +import { RootState } from 'ducks/types'; import { getGasInfo, @@ -38,17 +39,43 @@ import { secondsToTime, } from 'utils/formatters'; -import { HeadingSmall, DataSmall } from 'components/Typography'; -import { ButtonFilter, ButtonPrimary } from 'components/Button'; +import { DataSmall } from 'components/Typography'; +import { ButtonPrimary, Button } from 'components/Button'; import DismissableMessage from 'components/DismissableMessage'; import { FormInputRow, FormInputLabel, FormInputLabelSmall } from 'shared/commonStyles'; -import { ReactComponent as ReverseArrow } from 'assets/images/reverse-arrow.svg'; +// import { ReactComponent as ReverseArrow } from 'assets/images/reverse-arrow.svg'; import NetworkInfo from './NetworkInfo'; +import { bigNumberify } from 'ethers/utils'; const INPUT_DEFAULT_VALUE = ''; -const CreateOrderCard = ({ +const mapStateToProps = (state: RootState) => ({ + synthPair: getSynthPair(state), + walletInfo: getWalletInfo(state), + synthsWalletBalances: getSynthsWalletBalances(state), + exchangeRates: getRatesExchangeRates(state), + gasInfo: getGasInfo(state), + ethRate: getEthRate(state), + transactions: getTransactions(state), + synthsMap: getAvailableSynthsMap(state), +}); + +const mapDispatchToProps = { + toggleGweiPopup, + createTransaction, + updateTransaction, +}; + +const connector = connect(mapStateToProps, mapDispatchToProps); + +type PropsFromRedux = ConnectedProps; + +type CreateOrderCardProps = PropsFromRedux; + +type OrderType = 'limit' | 'market'; + +const CreateOrderCard: FC = ({ synthPair, walletInfo: { currentWallet, walletType }, synthsWalletBalances, @@ -62,27 +89,32 @@ const CreateOrderCard = ({ synthsMap, }) => { const { t } = useTranslation(); + const [orderType, setOrderType] = useState('limit'); const { colors } = useContext(ThemeContext); - const [baseAmount, setBaseAmount] = useState(INPUT_DEFAULT_VALUE); - const [quoteAmount, setQuoteAmount] = useState(INPUT_DEFAULT_VALUE); - const [feeRate, setFeeRate] = useState(0); + const [baseAmount, setBaseAmount] = useState(INPUT_DEFAULT_VALUE); + const [quoteAmount, setQuoteAmount] = useState(INPUT_DEFAULT_VALUE); + const [limitPrice, setLimitPrice] = useState(INPUT_DEFAULT_VALUE); + const [feeRate, setFeeRate] = useState(0); const [{ base, quote }, setPair] = useState( synthPair.reversed ? { base: synthPair.quote, quote: synthPair.base } : synthPair ); - const [tradeAllBalance, setTradeAllBalance] = useState(false); + const [tradeAllBalance, setTradeAllBalance] = useState(false); const [gasLimit, setGasLimit] = useState(gasInfo.gasLimit); const [hasSetGasLimit, setHasSetGasLimit] = useState(false); - const [inputError, setInputError] = useState(null); - const [txErrorMessage, setTxErrorMessage] = useState(null); - const [feeReclamationError, setFeeReclamationError] = useState(null); - const [isSubmitting, setIsSubmitting] = useState(false); - const [hasMarketClosed, setHasMarketClosed] = useState(false); + const [inputError, setInputError] = useState(null); + const [txErrorMessage, setTxErrorMessage] = useState(null); + const [feeReclamationError, setFeeReclamationError] = useState(null); + const [isSubmitting, setIsSubmitting] = useState(false); + const [hasMarketClosed, setHasMarketClosed] = useState(false); const resetInputAmounts = () => { setBaseAmount(INPUT_DEFAULT_VALUE); setQuoteAmount(INPUT_DEFAULT_VALUE); }; + const isLimitOrder = orderType === 'limit'; + const isMarketOrder = orderType === 'market'; + const showGweiPopup = () => toggleGweiPopup(true); useEffect(() => { @@ -142,12 +174,16 @@ const CreateOrderCard = ({ (synthsWalletBalances && synthsWalletBalances.find((synth) => synth.name === base.name)) || 0; const quoteBalance = (synthsWalletBalances && synthsWalletBalances.find((synth) => synth.name === quote.name)) || 0; - + console.log(baseBalance); const rate = getExchangeRatesForCurrencies(exchangeRates, quote.name, base.name); const inverseRate = getExchangeRatesForCurrencies(exchangeRates, base.name, quote.name); const buttonDisabled = - !baseAmount || !currentWallet || inputError || isSubmitting || feeReclamationError; + !baseAmount || + !currentWallet || + inputError != null || + isSubmitting || + feeReclamationError != null; const isEmptyQuoteBalance = !quoteBalance || !quoteBalance.balance; @@ -218,16 +254,19 @@ const CreateOrderCard = ({ const setMaxBalance = () => { if (!isEmptyQuoteBalance) { setTradeAllBalance(true); - setBaseAmount(quoteBalance.balance * rate); + setBaseAmount(`${Number(quoteBalance.balance) * rate}`); setQuoteAmount(quoteBalance.balance); } }; const handleSubmit = async () => { const { + limitOrdersContract, snxJS: { Synthetix }, utils, } = snxJSConnector; + const limitOrdersContractWithSigner = limitOrdersContract.connect(snxJSConnector.signer); + const transactionId = transactions.length; setTxErrorMessage(null); setIsSubmitting(true); @@ -236,48 +275,88 @@ const CreateOrderCard = ({ ? quoteBalance.balanceBN : utils.parseEther(quoteAmount.toString()); - const gasEstimate = await Synthetix.contract.estimate.exchange( - bytesFormatter(quote.name), - amountToExchange, - bytesFormatter(base.name) - ); - const rectifiedGasLimit = normalizeGasLimit(Number(gasEstimate)); - - setGasLimit(rectifiedGasLimit); - - createTransaction({ - id: transactionId, - date: new Date(), - base: base.name, - quote: quote.name, - fromAmount: quoteAmount, - toAmount: baseAmount, - price: - base.name === SYNTHS_MAP.sUSD - ? getExchangeRatesForCurrencies(exchangeRates, quote.name, base.name) - : getExchangeRatesForCurrencies(exchangeRates, base.name, quote.name), - amount: formatCurrency(baseAmount), - priceUSD: - base.name === SYNTHS_MAP.sUSD - ? getExchangeRatesForCurrencies(exchangeRates, quote.name, SYNTHS_MAP.sUSD) - : getExchangeRatesForCurrencies(exchangeRates, base.name, SYNTHS_MAP.sUSD), - totalUSD: formatCurrency( - baseAmount * getExchangeRatesForCurrencies(exchangeRates, base.name, SYNTHS_MAP.sUSD) - ), - status: TRANSACTION_STATUS.WAITING, - }); - - const tx = await Synthetix.exchange( - bytesFormatter(quote.name), - amountToExchange, - bytesFormatter(base.name), - { - gasPrice: gasInfo.gasPrice * GWEI_UNIT, - gasLimit: rectifiedGasLimit, - } - ); + if (orderType === 'market') { + const gasEstimate = await Synthetix.contract.estimate.exchange( + bytesFormatter(quote.name), + amountToExchange, + bytesFormatter(base.name) + ); + const rectifiedGasLimit = normalizeGasLimit(Number(gasEstimate)); + + setGasLimit(rectifiedGasLimit); + + createTransaction({ + id: transactionId, + date: new Date(), + base: base.name, + quote: quote.name, + fromAmount: quoteAmount, + toAmount: baseAmount, + price: + base.name === SYNTHS_MAP.sUSD + ? getExchangeRatesForCurrencies(exchangeRates, quote.name, base.name) + : getExchangeRatesForCurrencies(exchangeRates, base.name, quote.name), + amount: formatCurrency(baseAmount), + priceUSD: + base.name === SYNTHS_MAP.sUSD + ? getExchangeRatesForCurrencies(exchangeRates, quote.name, SYNTHS_MAP.sUSD) + : getExchangeRatesForCurrencies(exchangeRates, base.name, SYNTHS_MAP.sUSD), + totalUSD: formatCurrency( + Number(baseAmount) * + getExchangeRatesForCurrencies(exchangeRates, base.name, SYNTHS_MAP.sUSD) + ), + status: TRANSACTION_STATUS.WAITING, + }); + + const tx = await Synthetix.exchange( + bytesFormatter(quote.name), + amountToExchange, + bytesFormatter(base.name), + { + gasPrice: gasInfo.gasPrice * GWEI_UNIT, + gasLimit: rectifiedGasLimit, + } + ); - updateTransaction({ status: TRANSACTION_STATUS.PENDING, ...tx }, transactionId); + updateTransaction({ status: TRANSACTION_STATUS.PENDING, ...tx }, transactionId); + } else { + console.log( + bytesFormatter(quote.name), + quoteAmount.toString(), + bytesFormatter(base.name), + quoteAmount.toString(), + '1', + { + value: '1', + } + ); + // add typings + /* + { + newOrder: ( + sourceCurrencyKey: string, + sourceAmount: string, + destinationCurrencyKey: string, + minDestinationAmount: string, + executionFee: string, + gas: { value: string } + ) => Promise; + } + */ + const tx = await limitOrdersContractWithSigner.newOrder( + bytesFormatter(quote.name), + amountToExchange, + bytesFormatter(base.name), + limitPrice, + bigNumberify(1), + { + value: bigNumberify(1), + gasPrice: gasInfo.gasPrice * GWEI_UNIT, + gasLimit: 500000, + } + ); + console.log(tx); + } setIsSubmitting(false); } catch (e) { console.log(e); @@ -297,23 +376,14 @@ const CreateOrderCard = ({ return ( - - - {t('trade.trade-card.title')} - { - setPair({ quote: base, base: quote }); - resetInputAmounts(); - }} - height={'22px'} - > - - {t('trade.trade-card.reverse-button')} - - - - - + + setOrderType('market')}> + {t('trade.trade-card.tabs.market')} + + setOrderType('limit')}> + {t('trade.trade-card.tabs.limit')} + + { setTradeAllBalance(false); - setBaseAmount(value * rate); + setBaseAmount(`${Number(value) * rate}`); setQuoteAmount(value); }} errorMessage={inputError} @@ -367,36 +437,52 @@ const CreateOrderCard = ({ } onChange={(_, value) => { setTradeAllBalance(false); - setQuoteAmount(value * inverseRate); + setQuoteAmount(`${Number(value) * inverseRate}`); setBaseAmount(value); }} /> - - {BALANCE_FRACTIONS.map((fraction, id) => ( - { - const balance = quoteBalance.balance; - const isWholeBalance = fraction === 100; - const amount = isWholeBalance ? balance : (balance * fraction) / 100; - setTradeAllBalance(isWholeBalance); - setQuoteAmount(amount); - setBaseAmount(amount * rate); - }} - > - {fraction}% - - ))} - + {isMarketOrder ? ( + + {BALANCE_FRACTIONS.map((fraction, id) => ( + { + const balance = quoteBalance.balance; + const isWholeBalance = fraction === 100; + const amount = isWholeBalance ? balance : (balance * fraction) / 100; + setTradeAllBalance(isWholeBalance); + setQuoteAmount(amount); + setBaseAmount(`${Number(amount) * Number(rate)}`); + }} + > + {fraction}% + + ))} + + ) : ( + <> + + Price:} + onChange={(_, value) => { + setLimitPrice(value); + }} + /> + + + )} + @@ -440,6 +526,19 @@ const CreateOrderCard = ({ ); }; +const StyledCardHeader = styled(Card.Header)` + padding: 0; + > * + * { + margin-left: 0; + } + display: grid; + grid-template-columns: 1fr 1fr; + padding: 4px; + grid-gap: 4px; +`; + +export const TabButton = styled(Button).attrs({ size: 'sm', palette: 'tab' })``; + const BalanceFractionRow = styled.div` display: grid; grid-column-gap: 8px; @@ -459,48 +558,12 @@ const ButtonAmount = styled.button` height: 24px; `; -const StyledFormInputLabelSmall = styled(FormInputLabelSmall)` +const StyledFormInputLabelSmall = styled(FormInputLabelSmall)<{ isInteractive: boolean }>` cursor: ${(props) => (props.isInteractive ? 'pointer' : 'default')}; `; -const HeaderContainer = styled.div` - width: 100%; - display: flex; - justify-content: space-between; - align-items: center; -`; - -const ButtonFilterInner = styled.div` - display: flex; - align-items: center; -`; - -const ReverseArrowStyled = styled(ReverseArrow)` - height: 10px; - margin-left: 8px; -`; - export const TxErrorMessage = styled(DismissableMessage)` margin-top: 8px; `; -const mapStateToProps = (state) => { - return { - synthPair: getSynthPair(state), - walletInfo: getWalletInfo(state), - synthsWalletBalances: getSynthsWalletBalances(state), - exchangeRates: getRatesExchangeRates(state), - gasInfo: getGasInfo(state), - ethRate: getEthRate(state), - transactions: getTransactions(state), - synthsMap: getAvailableSynthsMap(state), - }; -}; - -const mapDispatchToProps = { - toggleGweiPopup, - createTransaction, - updateTransaction, -}; - -export default connect(mapStateToProps, mapDispatchToProps)(CreateOrderCard); +export default connector(CreateOrderCard); diff --git a/src/pages/Trade/components/CreateOrderCard/NetworkInfo.js b/src/pages/Trade/components/CreateOrderCard/NetworkInfo.tsx similarity index 92% rename from src/pages/Trade/components/CreateOrderCard/NetworkInfo.js rename to src/pages/Trade/components/CreateOrderCard/NetworkInfo.tsx index b3d144fc..f4eeda3d 100644 --- a/src/pages/Trade/components/CreateOrderCard/NetworkInfo.js +++ b/src/pages/Trade/components/CreateOrderCard/NetworkInfo.tsx @@ -1,6 +1,5 @@ -import React from 'react'; +import React, { FC } from 'react'; import { useTranslation } from 'react-i18next'; -import PropTypes from 'prop-types'; import styled from 'styled-components'; import Tooltip from '@material-ui/core/Tooltip'; @@ -14,7 +13,17 @@ import { DataSmall } from 'components/Typography'; import { ReactComponent as QuestionMark } from 'assets/images/question-mark.svg'; import { formatPercentage } from 'utils/formatters'; -export const TransactionInfo = ({ +type TransactionInfoProps = { + gasPrice: number; + gasLimit: number; + ethRate: number | null; + usdRate: number; + amount: number; + exchangeFeeRate: number; + onEditButtonClick: () => void; +}; + +export const TransactionInfo: FC = ({ gasPrice, gasLimit, ethRate = 0, @@ -73,13 +82,6 @@ export const TransactionInfo = ({ ); }; -TransactionInfo.propTypes = { - gasPrice: PropTypes.number, - gasLimit: PropTypes.number, - ethRate: PropTypes.number, - onEditButtonClick: PropTypes.func.isRequired, -}; - const TooltipContent = styled.div` width: 200px; padding: 2px; diff --git a/src/pages/Trade/components/CreateOrderCard/index.js b/src/pages/Trade/components/CreateOrderCard/index.ts similarity index 100% rename from src/pages/Trade/components/CreateOrderCard/index.js rename to src/pages/Trade/components/CreateOrderCard/index.ts diff --git a/src/shared/translations/en.json b/src/shared/translations/en.json index d4cdd21a..9330b17f 100644 --- a/src/shared/translations/en.json +++ b/src/shared/translations/en.json @@ -418,10 +418,14 @@ } }, "trade-card": { - "title": "Buy/Sell", + "tabs": { + "limit": "limit", + "market": "market" + }, "reverse-button": "Reverse", "sell-input-label": "Sell", "buy-input-label": "Buy", + "price-input-label": "Price", "confirm-trade-button": "Confirm trade", "frozen-synth": "Synth is frozen", "retry-button": "Retry", @@ -432,7 +436,8 @@ "network-info-tooltip": { "exchange-fee": "Exchange fee", "network-fee": "Network fee (gas)" - } + }, + "wallet-approval-tooltip": "Wallet approval required on your first order. Click “Enable Wallet Access” below to start." }, "order-book-card": { "tabs": { diff --git a/src/typings/synthetix-js.d.ts b/src/typings/synthetix-js.d.ts index f2a91c75..2072c17c 100644 --- a/src/typings/synthetix-js.d.ts +++ b/src/typings/synthetix-js.d.ts @@ -1,6 +1,7 @@ declare module 'synthetix-js' { import { JsonRpcSigner, Web3Provider } from 'ethers/providers'; import { ethers } from 'ethers'; + import { BigNumberish } from 'ethers/utils'; export interface ContractSettings { networkId: 1 | 3 | 4 | 42; @@ -43,5 +44,31 @@ declare module 'synthetix-js' { ethers: { utils: typeof ethers.utils }; static signers: Signers; binaryOptionsUtils: any; + Exchanger: { + feeRateForExchange: ( + quoteCurrencyKey: string, + baseCurrencyKey: string + ) => Promise; + maxSecsLeftInWaitingPeriod: (address: string, currencyKey: string) => Promise; + }; + SystemStatus: { + synthSuspension: ( + currencyKey: string + ) => Promise<{ + suspended: boolean; + }>; + }; + Synthetix: { + contract: any; + exchange: ( + quoteCurrencyKey: string, + amount: string, + baseCurrencyKey: string, + gasProps?: { + gasPrice: number; + gasLimit: number; + } + ) => Promise; + }; } } diff --git a/src/utils/LimitOrdersClient.ts b/src/utils/LimitOrdersClient.ts deleted file mode 100644 index 2b2b7683..00000000 --- a/src/utils/LimitOrdersClient.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { ethers } from 'ethers'; - -const ABI = [ - 'function newOrder(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint minDestinationAmount, uint executionFee) payable public returns (uint)', - 'function cancelOrder(uint orderID) public', - 'function orders(uint orderID) public view returns (tuple(address submitter, bytes32 sourceCurrencyKey, uint256 sourceAmount, bytes32 destinationCurrencyKey, uint256 minDestinationAmount, uint256 weiDeposit, uint256 executionFee, uint256 executionTimestamp, uint256 destinationAmount, bool executed) user)', - 'event Order(uint indexed orderID, address indexed submitter, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint minDestinationAmount, uint executionFee, uint weiDeposit)', - 'event Execute(uint indexed orderID, address indexed submitter, address executer)', - 'function withdrawOrders(uint[] memory orderIDs) public', -]; - -const CONSTANTS = { - rinkeby: { - contractAddress: '0x0000000000000000000000000000000000000001', - }, -}; - -class LimitOrdersClient { - provider: ethers.providers.Web3Provider; - - constructor(web3Provider: ethers.providers.Web3Provider) { - this.provider = web3Provider; - } - - getContract = async () => { - const network = await this.provider.getNetwork(); - const signer = this.provider.getSigner(); - - // @ts-ignore - return new ethers.Contract(CONSTANTS[network].contractAddress, ABI, signer); - }; - submitOrder = async ({ - sourceCurrencyKey, - sourceAmount, - destinationCurrencyKey, - minDestinationAmount, - executionFee, - weiDeposit, - }: { - sourceCurrencyKey: string; - sourceAmount: string; - destinationCurrencyKey: string; - minDestinationAmount: string; - executionFee: string; - weiDeposit: string; - }) => { - const contract = await this.getContract(); - const tx = await contract.newOrder( - sourceCurrencyKey, - sourceAmount, - destinationCurrencyKey, - minDestinationAmount, - executionFee, - { - value: weiDeposit, - } - ); - - return tx.hash; - // TODO: Return order ID instead - }; - - cancelOrder = async (orderID: string) => { - const contract = await this.getContract(); - const tx = await contract.cancelOrder(orderID); - - return tx.hash; - }; - - getOrder = async (orderID: string) => { - const contract = await this.getContract(); - - return await contract.orders(orderID); - }; - - getAllActiveOrders = async () => { - const contract = await this.getContract(); - // @ts-ignore - const filter = contract.filters.Order(null, this.provider.provider.selectedAddress); - const events = await contract.queryFilter(filter, 0); - let activeOrders = []; - - for (let i = 0; i < events.length; i++) { - let orderState = await this.getOrder(events[i].data.orderID); - orderState.id = events[i].data.orderID; - if ( - // @ts-ignore - orderState.submitter.toLowerCase() === this.provider.provider.selectedAddress && - orderState.executed === false - ) { - activeOrders.push(orderState); - } - } - - return activeOrders; - }; - - withdraw = async () => { - const contract = await this.getContract(); - // @ts-ignore - const filter = contract.filters.Execute(null, this.provider.provider.selectedAddress); - const events = await contract.queryFilter(filter, 0); - let pendingWithdrawals = []; - - for (let i = 0; i < events.length; i++) { - let orderState = await this.getOrder(events[i].data.orderID); - orderState.id = events[i].data.orderID; - if ( - // @ts-ignore - orderState.submitter.toLowerCase() === this.provider.provider.selectedAddress && - orderState.executed === true - ) { - // TODO: Check fee reclamation window - pendingWithdrawals.push(orderState); - } - } - - return await contract.withdrawOrders(pendingWithdrawals.map((v) => v.id)); - }; -} - -export default LimitOrdersClient; diff --git a/src/utils/contracts/limitOrdersContract.ts b/src/utils/contracts/limitOrdersContract.ts index 673be695..e04fb406 100644 --- a/src/utils/contracts/limitOrdersContract.ts +++ b/src/utils/contracts/limitOrdersContract.ts @@ -1,9 +1,9 @@ export const limitOrdersContract = { addresses: { - 1: '0x0000000000000000000000000000000000000001', - 3: '0x0000000000000000000000000000000000000001', - 4: '0x0000000000000000000000000000000000000001', - 42: '0x0000000000000000000000000000000000000001', + 1: '0xF771A01C488c24F7755Ad1824650D3e243B65A9c', + 3: '0xF771A01C488c24F7755Ad1824650D3e243B65A9c', + 4: '0xF771A01C488c24F7755Ad1824650D3e243B65A9c', + 42: '0xF771A01C488c24F7755Ad1824650D3e243B65A9c', }, abi: [ 'function newOrder(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint minDestinationAmount, uint executionFee) payable public returns (uint)', @@ -11,7 +11,7 @@ export const limitOrdersContract = { 'function orders(uint orderID) public view returns (tuple(address submitter, bytes32 sourceCurrencyKey, uint256 sourceAmount, bytes32 destinationCurrencyKey, uint256 minDestinationAmount, uint256 weiDeposit, uint256 executionFee, uint256 executionTimestamp, uint256 destinationAmount, bool executed) user)', 'event Order(uint indexed orderID, address indexed submitter, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint minDestinationAmount, uint executionFee, uint weiDeposit)', 'event Execute(uint indexed orderID, address indexed submitter, address executer)', - 'function withdrawOrders(uint[] memory orderIDs) public', + 'function withdrawOrders(uint[] orderIDs) public', ], }; diff --git a/src/utils/networkUtils.ts b/src/utils/networkUtils.ts index e9e2c42e..5a4da3ae 100644 --- a/src/utils/networkUtils.ts +++ b/src/utils/networkUtils.ts @@ -78,9 +78,9 @@ export async function getEthereumNetwork() { return { name: SUPPORTED_NETWORKS[networkId], networkId }; } + return defaultNetwork; } catch (e) { console.log(e); - } finally { return defaultNetwork; } } diff --git a/src/utils/snxJSConnector.ts b/src/utils/snxJSConnector.ts index b10e11ed..e544821b 100644 --- a/src/utils/snxJSConnector.ts +++ b/src/utils/snxJSConnector.ts @@ -12,7 +12,6 @@ import { import { synthSummaryUtilContract } from './contracts/synthSummaryUtilContract'; import binaryOptionsMarketDataContract from './contracts/binaryOptionsMarketDataContract'; import limitOrdersContract from './contracts/limitOrdersContract'; -// import LimitOrdersClient from './LimitOrdersClient'; type SnxJSConnector = { initialized: boolean; @@ -61,7 +60,7 @@ const snxJSConnector: SnxJSConnector = { this.limitOrdersContract = new ethers.Contract( limitOrdersContract.addresses[contractSettings.networkId], limitOrdersContract.abi, - this.signer + this.provider ); }, };