diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..a829ccb1f --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,78 @@ +# Contributor Covenant Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at community@sovryn.app. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..5bf29ad7d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,45 @@ +## Contributing + + + + + +### Bug Reports + +To encourage active collaboration, Sovryn strongly encourages pull requests, not just bug reports. "Bug reports" may also be sent in the form of a pull request containing a failing test. + +However, if you file a bug report, your issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible. The goal of a bug report is to make it easy for yourself - and others - to replicate the bug and develop a fix. + +Remember, bug reports are created in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the bug report will automatically see any activity or that others will jump to fix it. Creating a bug report serves to help yourself and others start on the path of fixing the problem. If you want to chip in, you can help out by fixing any bugs listed in our [issue trackers](https://github.com/issues?q=is%3Aopen+is%3Aissue+label%3Abug+user%3Adistributedcollective). + +### Support Questions + +Sovryn's GitHub issue trackers are not intended to provide help or support. Instead, use one of the following channels: + +- [Discord](https://discord.gg/J22WS6z) +- [Gitbook Tutorials](https://sovryn-1.gitbook.io/sovryn) +- [Sovryn Blog](https://sovryn.app/blog/) + +### Core Development Discussion + +You may propose new features or improvements of existing dapp behavior in the Sovryn Ideas issue board. If you propose a new feature, please be willing to implement at least some of the code that would be needed to complete the feature. + +Informal discussion regarding bugs, new features, and implementation of existing features takes place in the #sorcery channel of the Sovryn Discord server. + +### Which Branch? + +**All** bug fixes should be sent to the latest stable (master) branch. Bug fixes should never be sent to the development branch unless they fix features that exist only in the upcoming release. + +**Minor** features that are fully backward compatible with the current release may be sent to the latest stable branch. + +**Major** new features should always be sent to the development branch, which contains the upcoming release. + +If you are unsure if your feature qualifies as a major or minor, please ask Victor Creed in the #sorcery channel of the Sovryn Discord server. + +### Working With UI + +All UI designs used for this repository should be available publically in [Google Drive folder as Adobe XD files](https://drive.google.com/drive/folders/1e_VljWpANJe0o4VmIkKU5Ewo56l9iMaM?usp=sharing) + +## Security Vulnerabilities + +If you discover a security vulnerability within DApp, please send an e-mail to Victor Creed via creed-victor@protonmail.com. All security vulnerabilities will be promptly addressed. diff --git a/README.md b/README.md index 91b67e654..656cdf76b 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,10 @@ Informal discussion regarding bugs, new features, and implementation of existing If you are unsure if your feature qualifies as a major or minor, please ask Victor Creed in the #sorcery channel of the Sovryn Discord server. +### Working With UI + +All UI designs used for this repository should be available publically in [Google Drive folder as Adobe XD files](https://drive.google.com/drive/folders/1e_VljWpANJe0o4VmIkKU5Ewo56l9iMaM?usp=sharing) + ## Security Vulnerabilities If you discover a security vulnerability within DApp, please send an e-mail to Victor Creed via creed-victor@protonmail.com. All security vulnerabilities will be promptly addressed. diff --git a/src/app/components/BorrowInterestRate/index.tsx b/src/app/components/BorrowInterestRate/index.tsx index c318ee136..65de3a608 100644 --- a/src/app/components/BorrowInterestRate/index.tsx +++ b/src/app/components/BorrowInterestRate/index.tsx @@ -3,12 +3,8 @@ * BorrowInterestRate * */ -import React, { useEffect, useState } from 'react'; -import { bignumber } from 'mathjs'; -import { Asset } from 'types/asset'; +import React from 'react'; import { weiToFixed } from 'utils/blockchain/math-helpers'; -import { useLending_nextBorrowInterestRate } from 'app/hooks/trading/useLending_nextBorrowInterestRate'; -import { usePriceFeeds_QueryRate } from 'app/hooks/price-feeds/useQueryRate'; import { LoadableValue } from '../LoadableValue'; import { FieldGroup } from '../FieldGroup'; import { DummyField } from '../DummyField'; @@ -16,59 +12,17 @@ import { useTranslation } from 'react-i18next'; import { translations } from '../../../locales/i18n'; interface Props { - asset: Asset; - collateral: Asset; - leverage: number; - weiAmount: string; + value: string; + loading: boolean; labelColor: string; } -export function BorrowInterestRate(props: Props) { +export function BorrowInterestRate({ value, loading, labelColor }: Props) { const { t } = useTranslation(); - const { value: result } = usePriceFeeds_QueryRate( - props.collateral, - props.asset, - ); - - const [totalDeposit, setTotalDeposit] = useState('0'); - const [borrowAmount, setBorrowAmount] = useState(totalDeposit); - - // Calculate loan tokens we depositing. - useEffect(() => { - let _totalDeposit = '0'; // loanTo - // let totalDeposit = props.loanTokenSent; - - if (props.weiAmount !== '0') { - // props.collateralTokenSent != '0' - if (result.rate !== '0') { - _totalDeposit = bignumber(props.weiAmount) - .mul(result.rate) - .div(result.precision) - .add(_totalDeposit) - .toFixed(0); - } - } - setTotalDeposit(_totalDeposit); - // eslint-disable-next-line - }, [JSON.stringify(result), props]); - - useEffect(() => { - setBorrowAmount( - bignumber(totalDeposit) - .mul(props.leverage - 1) - .toFixed(0), - ); - }, [totalDeposit, props.leverage]); - - const { value, loading } = useLending_nextBorrowInterestRate( - props.asset, - borrowAmount, - ); - return ( void; + inputFocus?: boolean; } export function FormSelect(props: Props) { @@ -46,6 +48,9 @@ export function FormSelect(props: Props) { ({ open: open }))` + display: flex; + flex-direction: column; + justify-content: flex-start; + background: black; + transform: ${({ open }) => (open ? 'translateX(0)' : 'translateX(-100%)')}; + height: 100%; + text-align: left; + padding: 4rem 2rem 2rem; + position: absolute; + top: 0; + left: 0; + right: 0; + transition: transform 0.3s ease-in-out; + z-index: 9; + width: 100%; + li { + list-style-type: none; + } + a { + font-size: 1.2rem; + text-transform: uppercase; + padding: 1.5rem 0; + font-weight: bold; + letter-spacing: 0.5rem; + color: white; + text-decoration: none; + transition: color 0.3s linear; + text-align: center; + } + `; + const StyledBurger = styled.button.attrs(_ => ({ open: open }))` + position: absolute; + top: 1.3rem; + display: flex; + flex-direction: column; + justify-content: space-around; + width: 2rem; + height: 2rem; + background: transparent; + border: none; + cursor: pointer; + padding: 0; + z-index: 10; + &:focus { + outline: none; + } + + div { + width: 2rem; + height: 0.25rem; + background: white; + border-radius: 10px; + transition: all 0.3s linear; + position: relative; + transform-origin: 1px; + :first-child { + transform: ${({ open }) => (open ? 'rotate(45deg)' : 'rotate(0)')}; + } + :nth-child(2) { + opacity: ${({ open }) => (open ? '0' : '1')}; + transform: ${({ open }) => + open ? 'translateX(20px)' : 'translateX(0)'}; + } + :nth-child(3) { + transform: ${({ open }) => (open ? 'rotate(-45deg)' : 'rotate(0)')}; + } + } + `; + const Menu = ({ open, setOpen }) => { + return {menuItems}; + }; + const Burger = ({ open, setOpen }) => { + return ( + setOpen(!open)}> +
+
+
+ + ); + }; const pages = [ { to: '/', title: t(translations.mainMenu.trade), exact: true }, { to: '/lend', title: t(translations.mainMenu.lend) }, { to: '/liquidity', title: t(translations.mainMenu.liquidity) }, { to: '/wallet', title: t(translations.mainMenu.wallet) }, - t(translations.mainMenu.stats), + { to: '/stats', title: t(translations.mainMenu.stats) }, { to: 'https://sovryn-1.gitbook.io/sovryn/', title: t(translations.mainMenu.faqs), }, ]; - const menuItems = pages.map((item, index) => { let link: { to: string; @@ -42,14 +124,6 @@ export function Header() { onClick?: () => void; } = item as any; - if (typeof item === 'string') { - link = { - to: `/${item.toLowerCase()}`, - title: item, - exact: false, - }; - } - if (link.to.startsWith('http')) { return ( {menuItems}; + useEffect(() => { + const body = document.body; + if (open) { + body.classList.add('overflow-hidden'); + } else { + body.classList.remove('overflow-hidden'); + } + return () => { + body.classList.remove('overflow-hidden'); + }; + }, [open]); return ( <>
- {dropDownMenu}}> - - +
+ + +
diff --git a/src/app/components/PageHeader/index.tsx b/src/app/components/PageHeader/index.tsx index 6f073d098..903e3098c 100644 --- a/src/app/components/PageHeader/index.tsx +++ b/src/app/components/PageHeader/index.tsx @@ -34,11 +34,15 @@ const H1 = styled.h1` ${media.md`font-size: 53px; text-align: left;`} `; -export default function PageHeader() { +interface Props { + content?: React.ReactNode; +} + +export default function PageHeader(props: Props) { return ( SOV -

SOV GENESIS PRE-ORDER

+

{props.content}

); } diff --git a/src/app/components/SalesButton/index.tsx b/src/app/components/SalesButton/index.tsx index 5a8a52d3f..fa94a1759 100644 --- a/src/app/components/SalesButton/index.tsx +++ b/src/app/components/SalesButton/index.tsx @@ -22,6 +22,10 @@ export const StyledButton = styled.button.attrs(_ => ({ transition: background 0.3s; padding: 0 4.2%; margin: 0 auto; + &:disabled { + opacity: 0.5; + cursor: not-allowed; + } &:hover { text-decoration: none; color: var(--gold); @@ -41,10 +45,6 @@ export const StyledButton = styled.button.attrs(_ => ({ background: var(--gold50) !important; } } - &:disabled { - opacity: 0.5; - cursor: not-allowed; - } `} `; diff --git a/src/app/components/UserAssets/index.tsx b/src/app/components/UserAssets/index.tsx index 7fd93fc4f..40d597b3b 100644 --- a/src/app/components/UserAssets/index.tsx +++ b/src/app/components/UserAssets/index.tsx @@ -20,7 +20,11 @@ import { useCachedAssetPrice } from '../../hooks/trading/useCachedAssetPrice'; import { Asset } from '../../../types/asset'; import { usePriceFeeds_tradingPairRates } from '../../hooks/price-feeds/usePriceFeeds_tradingPairRates'; import { Skeleton } from '../PageSkeleton'; -import { numberToUSD } from '../../../utils/display-text/format'; +import { + numberToUSD, + weiToNumberFormat, +} from '../../../utils/display-text/format'; + // import { actions } from 'app/containers/FastBtcForm/slice'; export function UserAssets() { @@ -116,7 +120,7 @@ function AssetRow({ item }: AssetProps) { @@ -136,26 +140,37 @@ function AssetRow({ item }: AssetProps) { {/* onClick={() => dispatch(actions.showDialog(true))}*/} {/* />*/} {/*)}*/} -
)} -
- - setTokenToCollarate(item.key)} - value={tokenToCollarate} - items={collaterals} - /> - -
-
- - {t(translations.lend.borrowingContainer.collateralAmount)}{' '} - {maxAmount !== '0' && !loadingLimit && ( - - (Max: {weiTo4(maxAmount)} {tokenToCollarate}) - - )} - - } - > - - {weiToFixed(collateralTokenSent, 6)} {tokenToCollarate} - - +
+
+
+ { + <> + {t(translations.lend.borrowingContainer.tokenAssetCollateral)}{' '} + {maxAmount !== '0' && !loadingLimit && ( + + (Max: {weiTo4(maxAmount)} {tokenToCollarate}) + + )} + + } +
+
+ + setTokenToCollarate(item.key)} + value={tokenToCollarate} + items={collaterals} + /> + +
+
+ + + {weiToFixed(collateralTokenSent, 6)} {tokenToCollarate} + + +
+
diff --git a/src/app/containers/MarginTradeForm/PricePrediction.tsx b/src/app/containers/MarginTradeForm/PricePrediction.tsx new file mode 100644 index 000000000..fb589e87e --- /dev/null +++ b/src/app/containers/MarginTradeForm/PricePrediction.tsx @@ -0,0 +1,60 @@ +import React, { useEffect, useState } from 'react'; +import { TradingPosition } from '../../../types/trading-position'; +import { Asset } from '../../../types/asset'; +import { useGetEstimatedMarginDetails } from '../../hooks/trading/useGetEstimatedMarginDetails'; +import { useCurrentPositionPrice } from '../../hooks/trading/useCurrentPositionPrice'; +import { LoadableValue } from '../../components/LoadableValue'; +import { toNumberFormat } from '../../../utils/display-text/format'; + +interface Props { + position: TradingPosition; + leverage: number; + loanToken: Asset; + collateralToken: Asset; + useLoanTokens: boolean; + weiAmount: string; +} + +export function PricePrediction({ + loanToken, + collateralToken, + useLoanTokens, + weiAmount, + leverage, + ...props +}: Props) { + const [collateralAmount, setCollateralAmount] = useState('0'); + const [loanTokenAmount, setLoanTokenAmount] = useState('0'); + + useEffect(() => { + setLoanTokenAmount(useLoanTokens ? weiAmount : '0'); + setCollateralAmount(useLoanTokens ? '0' : weiAmount); + }, [useLoanTokens, weiAmount, leverage]); + + const { value } = useGetEstimatedMarginDetails( + loanToken, + leverage, + loanTokenAmount, + collateralAmount, + collateralToken, + ); + + const { price, loading } = useCurrentPositionPrice( + loanToken, + collateralToken, + value.principal, + props.position === TradingPosition.SHORT, + ); + + return ( + + $ + {toNumberFormat(price, 2)} + + } + /> + ); +} diff --git a/src/app/containers/MarginTradeForm/TradeConfirmationDialog.tsx b/src/app/containers/MarginTradeForm/TradeConfirmationDialog.tsx new file mode 100644 index 000000000..bf5c61530 --- /dev/null +++ b/src/app/containers/MarginTradeForm/TradeConfirmationDialog.tsx @@ -0,0 +1,16 @@ +import React from 'react'; +import { Dialog } from '../Dialog'; +import { TradeButton } from '../../components/TradeButton'; + +interface Props { + isOpen: boolean; + onClose: (success: boolean) => void; +} + +export function TradeConfirmationDialog(props: Props) { + return ( + props.onClose(false)}> + props.onClose(true)} /> + + ); +} diff --git a/src/app/containers/MarginTradeForm/index.tsx b/src/app/containers/MarginTradeForm/index.tsx index 50ad16d2d..dbd8f52fe 100644 --- a/src/app/containers/MarginTradeForm/index.tsx +++ b/src/app/containers/MarginTradeForm/index.tsx @@ -38,6 +38,9 @@ import { disableNewTrades, disableNewTradesText, } from '../../../utils/classifiers'; +import { useBorrowInterestRate } from '../../hooks/trading/useBorrowInterestRate'; +import { PricePrediction } from './PricePrediction'; +import { DummyField } from '../../components/DummyField'; const s = translations.marginTradeForm; @@ -109,7 +112,11 @@ export function MarginTradeForm() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [state]); - const { loanToken, collateralToken } = useTrading_resolvePairTokens( + const { + loanToken, + collateralToken, + useLoanTokens, + } = useTrading_resolvePairTokens( pair, position, pair.getAssetForPosition(position), @@ -118,6 +125,11 @@ export function MarginTradeForm() { const { diff } = useTrading_testRates(loanToken, collateralToken, weiAmount); + const { + value: interestValue, + loading: interestLoading, + } = useBorrowInterestRate(loanToken, collateral, leverage, weiAmount); + return ( <>
+
+
+ + + + + +
+
diff --git a/src/app/containers/SalesPage/GetAccess/index.tsx b/src/app/containers/SalesPage/GetAccess/index.tsx new file mode 100644 index 000000000..ded2e1a15 --- /dev/null +++ b/src/app/containers/SalesPage/GetAccess/index.tsx @@ -0,0 +1,403 @@ +import React, { useCallback, useState, useRef, useEffect } from 'react'; +import styled from 'styled-components/macro'; +import { useSelector } from 'react-redux'; +import { Slider } from '@blueprintjs/core'; +import { Asset } from 'types/asset'; +import axios from 'axios'; +import { validateEmail } from 'utils/helpers'; +import { TradingPairDictionary } from 'utils/dictionaries/trading-pair-dictionary'; +import { weiTo2 } from 'utils/blockchain/math-helpers'; +import { backendUrl, currentChainId } from 'utils/classifiers'; +import { media } from 'styles/media'; +import { selectSalesPage } from '../selectors'; +import Loader from '../loader'; +import { useCachedAssetPrice } from '../../../hooks/trading/useCachedAssetPrice'; +import { selectTradingPage } from '../../TradingPage/selectors'; +import SalesButton from '../../../components/SalesButton'; +import { StyledButton } from '../../../components/SalesButton'; + +const StyledContent = styled.div` + background: var(--sales-background); + max-width: 1235px; + min-height: 620px; + margin: 40px auto; + border-radius: 20px; + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; + position: relative; + padding: 30px 15px; + .content-header { + font-size: 28px; + text-align: center; + margin-bottom: 40px; + } + .content-title { + margin-top: 38px; + font-size: 20px; + line-height: 34px; + font-family: 'Montserrat'; + text-align: center; + font-weight: 100; + margin-bottom: 38px; + } + a { + margin-top: 110px; + color: var(--gold); + font-weight: normal; + } + .text-small { + font-size: 14px; + font-family: 'Work Sans'; + line-height: 17px; + &-bottom { + font-size: 12px; + } + } + .bp3-slider { + margin: 0 4.2rem; + max-width: calc(100% - 170px); + &-handle { + background-color: white; + border-radius: 50%; + top: 1px; + .bp3-slider-label { + left: auto !important; + right: auto !important; + top: 23px; + font-size: 14px; + margin: 0; + display: flex; + width: auto; + flex-wrap: nowrap; + justify-content: center; + margin-left: 0.5rem; + } + } + &-track { + background: #c1c1c1; + height: 8px; + } + &-label { + transform: translate(-50%, -3px); + left: -40px !important; + font-size: 18px; + & + .bp3-slider-label { + right: -135px !important; + left: auto !important; + } + } + &-progress.bp3-intent-primary { + background-color: #fec004; + height: 8px; + } + } + .sliderAmount { + background: #f4f4f4; + border-radius: 8px; + height: 50px; + width: 100%; + text-align: center; + color: black; + font-size: 18px; + line-height: 20px; + font-family: 'Work Sans'; + display: flex; + justify-content: center; + align-items: center; + margin-bottom: 25px; + font-weight: 500; + cursor: text; + & > *:not(.bp3-divider) { + margin-right: 0; + } + span { + font-size: 14px; + font-weight: 100; + padding-left: 5px; + } + } + .form-group { + display: flex; + flex-direction: column; + margin-bottom: 36px; + min-width: 296px; + label { + font-size: 14px; + margin-bottom: 8px; + line-height: 17px; + } + } + ${media.xl` + .sliderAmount { + width: 289px; + input { + width: 289px; + } + } + .bp3-slider { + max-width: 300px; + } + `} +`; + +const StyledInput = styled.input.attrs(_ => ({ type: 'text' }))` + background: #f4f4f4; + border-radius: 8px; + height: 50px; + width: 100%; + text-align: center; + color: black; + font-size: 18px; + line-height: 20px; + font-family: 'Work Sans'; + display: flex; + justify-content: center; + align-items: center; + font-weight: 500; + outline-style: none; + box-shadow: none; + &:focus { + box-shadow: none; + border-radius: 8px; + } + ${media.xl` + width: 289px; + `} +`; + +const StyledInputNumber = styled.input.attrs(_ => ({ type: 'number' }))` + background: #f4f4f4; + border-radius: 8px; + height: 50px; + width: 100%; + text-align: center; + color: black; + font-size: 14px; + font-family: 'Work Sans'; + font-weight: 100; + ${media.xl` + width: 289px; + `} +`; + +interface Props { + hideBackButton?: boolean; +} + +export default function GetAccess(props: Props) { + const [email, setEmail] = useState(''); + const [username, setUsername] = useState(''); + const [response, setResponse] = useState(''); + const [enterCount, setEnterCount] = useState(false); + const emailValid = validateEmail(email); + const valid = !!email && emailValid; + const [amount, setAmount] = useState(0); + const { tradingPair } = useSelector(selectTradingPage); + const { requestAccessLoading } = useSelector(selectSalesPage); + const pair = TradingPairDictionary.get(tradingPair); + const { value: price } = useCachedAssetPrice(pair.getAsset(), Asset.DOC); + const usdPrice = weiTo2(Number(price) * amount); + const maxAmount = 100; + const searchInput = useRef(null as any); + const referralSrv = backendUrl[currentChainId]; + + const addtoWhitelist = useCallback(() => { + setResponse('pending'); + axios + .post(referralSrv + '/join-waitlist', { + email: email, + discord: username, + amount: amount, + }) + .then(res => { + setResponse('success'); + }) + .catch(error => { + setResponse('error'); + }); + }, [referralSrv, email, username, amount]); + + useEffect(() => { + if (enterCount) { + searchInput.current.focus(); + } + }, [enterCount]); + + const getChangeHandler = () => { + return (value: number) => { + if (value > maxAmount) { + setAmount(maxAmount); + } else { + setAmount(value); + } + }; + }; + const setInputAmount = (val: number) => { + if (val > maxAmount) { + setAmount(maxAmount); + } else { + setAmount(val); + } + }; + + const renderBTCLabel = val => { + return `${val} BTC`; + }; + + return ( + <> + {response === 'pending' ? ( + + We are currently processing your request +

+ } + /> + ) : ( + <> +
+ + {response !== 'success' && ( +
+

+ Genesis Pre-Sale sold out in Minutes! +

+

+ Register for secure your place in the Origin Pre-Sale +

+ +
+
+
+
+ + setUsername(e.target.value)} + /> +
+
+ + setEmail(e.target.value)} + /> + {!!email && !emailValid && ( + + Enter valid email address. + + )} +
+
+
+
+
+
+ + {enterCount ? ( + setEnterCount(false)} + className="sliderAmount" + onChange={e => + setInputAmount(Number(e.target.value)) + } + /> + ) : ( +
{ + setEnterCount(true); + }} + > + {amount} ≈ ${usdPrice} +
+ )} + setEnterCount(false)} + onChange={getChangeHandler()} + /> +

+ Sharing with us your intended contribution is + optional. It does not constrain you to actually + participate but it helps us to better understand our + community. +

+
+
+
+
+

+ By joining the waitlist you agree to receive the latest + news about the SOV ecosystem +

+ {response === 'error' && ( +
+ An error has occurred +
+ )} + +
+
+
+ )} + {response === 'success' && ( +
+

+ Congratulations you are on the waitlist! +

+

+ We will email you with instructions of how to participate + prior to the launch +

+

+ In the meantime why not learn about all things SOVRYN by + reading our Blackpaper +

+ +
+
+ + Read Blackpaper + +
+
+
+ )} +
+ + )} + + ); +} diff --git a/src/app/containers/SalesPage/index.tsx b/src/app/containers/SalesPage/index.tsx index 037e10567..9b0eff01e 100644 --- a/src/app/containers/SalesPage/index.tsx +++ b/src/app/containers/SalesPage/index.tsx @@ -25,13 +25,11 @@ import { sliceKey as salesSlice, reducer as salesReducer, } from './slice'; -import { SaleInfoBar } from './SaleInfoBar'; import { salesPageSaga } from './saga'; import { AddSoToNifty } from './AddSoToNifty'; import { AddSoToMetamask } from './AddToMetamask'; -import { Icon } from '@blueprintjs/core/lib/esm/components/icon/icon'; -import { currentNetwork } from '../../../utils/classifiers'; import { StyledButton } from '../../components/SalesButton'; +import GetAccess from './GetAccess'; function detectInjectableWallet() { if (window.ethereum?.isNiftyWallet) { @@ -114,36 +112,10 @@ export function SalesPage() { className="container font-family-montserrat" style={{ maxWidth: '1730px', letterSpacing: 'normal' }} > - - - - - {currentNetwork === 'testnet' && ( -
-
-
- -
-
- This is testnet, not the actual sale. Do not send real funds! -
-
-
- )} - - {currentNetwork === 'mainnet' && ( -
-
-
- -
-
- Pre-order is over, all allocated cSOV tokens was purchased! -
-
-
- )} - + <> + SOV PUBLIC PRE-SALE WHITELIST} /> + + diff --git a/src/app/containers/SalesPage/screen6/index.tsx b/src/app/containers/SalesPage/screen6/index.tsx index c1384d26c..e52dbdbe1 100644 --- a/src/app/containers/SalesPage/screen6/index.tsx +++ b/src/app/containers/SalesPage/screen6/index.tsx @@ -97,6 +97,10 @@ const StyledButtonGroup = styled.div` justify-content: center; align-items: center; cursor: pointer; + &:disabled { + opacity: 0.5; + cursor: not-allowed; + } ${media.xl` max-width: 130px; width: 100%; @@ -113,10 +117,6 @@ const StyledButtonGroup = styled.div` background: var(--gold50) !important; } } - &:disabled { - opacity: 0.5; - cursor: not-allowed; - } `} ${(props: StyledProps) => props.active && diff --git a/src/app/containers/TradingPairSelector/index.tsx b/src/app/containers/TradingPairSelector/index.tsx index b34584aaa..08b0de141 100644 --- a/src/app/containers/TradingPairSelector/index.tsx +++ b/src/app/containers/TradingPairSelector/index.tsx @@ -25,6 +25,7 @@ import { StyledAssetLogo } from './styled'; import { useBorrowAssetPrice } from '../../hooks/trading/useBorrowAssetPrice'; import { Asset } from '../../../types/asset'; import { weiTo2 } from '../../../utils/blockchain/math-helpers'; +import { isMobile } from '../../../utils/helpers'; const Selector = Select.ofType(); @@ -74,6 +75,7 @@ export function TradingPairSelector(props: Props) { return ( } itemRenderer={renderItem} itemPredicate={filterItem} diff --git a/src/app/containers/WalletConnector/index.tsx b/src/app/containers/WalletConnector/index.tsx index 3a02b0867..5212360b2 100644 --- a/src/app/containers/WalletConnector/index.tsx +++ b/src/app/containers/WalletConnector/index.tsx @@ -1,14 +1,7 @@ import React, { useCallback } from 'react'; import { useTranslation } from 'react-i18next'; import { reactLocalStorage } from 'reactjs-localstorage'; -import { - Icon, - Menu, - MenuDivider, - MenuItem, - Popover, - Spinner, -} from '@blueprintjs/core'; +import { Icon, Menu, MenuItem, Popover, Spinner } from '@blueprintjs/core'; import styled from 'styled-components/macro'; import { actions } from 'app/containers/EngageWalletDialog/slice'; import { useSelector, useDispatch } from 'react-redux'; @@ -72,8 +65,6 @@ const WalletConnectorContainer: React.FC = props => { - - = props => { history.push('/referrals')} + onClick={() => history.push('/referral')} /> } diff --git a/src/app/hooks/price-feeds/usePriceFeeds_getCurrentMargin.ts b/src/app/hooks/price-feeds/usePriceFeeds_getCurrentMargin.ts new file mode 100644 index 000000000..84647d15a --- /dev/null +++ b/src/app/hooks/price-feeds/usePriceFeeds_getCurrentMargin.ts @@ -0,0 +1,28 @@ +import { Asset } from 'types/asset'; +import { getTokenContract } from 'utils/blockchain/contract-helpers'; +import { useCacheCallWithValue } from '../useCacheCallWithValue'; + +interface CurrentMargin { + currentMargin: string; + collateralToLoanRate: string; +} + +export function usePriceFeeds_getCurrentMargin( + loanToken: Asset, + collateralToken: Asset, + principal: string, + collateral: string, +) { + return useCacheCallWithValue( + 'priceFeed', + 'getCurrentMargin', + { + currentMargin: '0', + collateralToLoanRate: '0', + }, + getTokenContract(loanToken).address, + getTokenContract(collateralToken).address, + principal, + collateral, + ); +} diff --git a/src/app/hooks/price-feeds/usePriceFeeds_queryPrecision.ts b/src/app/hooks/price-feeds/usePriceFeeds_queryPrecision.ts new file mode 100644 index 000000000..3805ebd75 --- /dev/null +++ b/src/app/hooks/price-feeds/usePriceFeeds_queryPrecision.ts @@ -0,0 +1,16 @@ +import { Asset } from 'types/asset'; +import { getTokenContract } from 'utils/blockchain/contract-helpers'; +import { useCacheCallWithValue } from '../useCacheCallWithValue'; + +export function usePriceFeeds_queryPrecision( + loanToken: Asset, + collateralToken: Asset, +) { + return useCacheCallWithValue( + 'priceFeed', + 'queryPrecision', + '0', + getTokenContract(loanToken).address, + getTokenContract(collateralToken).address, + ); +} diff --git a/src/app/hooks/trading/useBorrowInterestRate.ts b/src/app/hooks/trading/useBorrowInterestRate.ts new file mode 100644 index 000000000..f156b3540 --- /dev/null +++ b/src/app/hooks/trading/useBorrowInterestRate.ts @@ -0,0 +1,51 @@ +import { usePriceFeeds_QueryRate } from '../price-feeds/useQueryRate'; +import { useEffect, useState } from 'react'; +import { bignumber } from 'mathjs'; +import { useLending_nextBorrowInterestRate } from './useLending_nextBorrowInterestRate'; +import { Asset } from '../../../types/asset'; + +export function useBorrowInterestRate( + asset: Asset, + collateral: Asset, + leverage: number, + weiAmount: string, +) { + const { value: result } = usePriceFeeds_QueryRate(collateral, asset); + + const [totalDeposit, setTotalDeposit] = useState('0'); + const [borrowAmount, setBorrowAmount] = useState(totalDeposit); + + // Calculate loan tokens we depositing. + useEffect(() => { + let _totalDeposit = '0'; // loanTo + // let totalDeposit = props.loanTokenSent; + + if (weiAmount !== '0') { + // props.collateralTokenSent != '0' + if (result.rate !== '0') { + _totalDeposit = bignumber(weiAmount) + .mul(result.rate) + .div(result.precision) + .add(_totalDeposit) + .toFixed(0); + } + } + setTotalDeposit(_totalDeposit); + // eslint-disable-next-line + }, [JSON.stringify(result), weiAmount]); + + useEffect(() => { + setBorrowAmount( + bignumber(totalDeposit) + .mul(leverage - 1) + .toFixed(0), + ); + }, [totalDeposit, leverage]); + + const { value, loading } = useLending_nextBorrowInterestRate( + asset, + borrowAmount, + ); + + return { value, loading }; +} diff --git a/src/app/hooks/trading/useGetEstimatedMarginDetails.ts b/src/app/hooks/trading/useGetEstimatedMarginDetails.ts index b34f2673e..4bbc3d6ef 100644 --- a/src/app/hooks/trading/useGetEstimatedMarginDetails.ts +++ b/src/app/hooks/trading/useGetEstimatedMarginDetails.ts @@ -1,10 +1,16 @@ +import { toWei } from 'web3-utils'; import { Asset } from 'types/asset'; import { getLendingContractName, getTokenContract, } from 'utils/blockchain/contract-helpers'; import { useCacheCallWithValue } from '../useCacheCallWithValue'; -import { toWei } from 'web3-utils'; + +interface MarginDetails { + principal: string; + collateral: string; + interestRate: string; +} export function useGetEstimatedMarginDetails( loanContract: Asset, @@ -13,7 +19,7 @@ export function useGetEstimatedMarginDetails( collateralTokenSent: string, collateralToken: Asset, ) { - return useCacheCallWithValue( + return useCacheCallWithValue( getLendingContractName(loanContract), 'getEstimatedMarginDetails', { diff --git a/src/app/hooks/trading/useTrading_totalDeposit.ts b/src/app/hooks/trading/useTrading_totalDeposit.ts new file mode 100644 index 000000000..d72820535 --- /dev/null +++ b/src/app/hooks/trading/useTrading_totalDeposit.ts @@ -0,0 +1,82 @@ +import { useCallback, useEffect, useState } from 'react'; +import { bignumber } from 'mathjs'; +import { Asset } from 'types/asset'; +import { contractReader } from 'utils/sovryn/contract-reader'; +import { getTokenContract } from 'utils/blockchain/contract-helpers'; + +export function useTrading_totalDeposit( + loanToken: Asset, + collateralToken: Asset, + collateralTokenSent: string, + loanTokenSent: string, +) { + const [totalDeposit, setTotalDeposit] = useState(loanTokenSent); + + const getOracleRate = useCallback(async () => { + return ((await contractReader.call('priceFeed', 'queryRate', [ + getTokenContract(collateralToken).address, + getTokenContract(loanToken).address, + ])) as unknown) as { rate: string; precision: string }; + }, [collateralToken, loanToken]); + + const getSwapExpectedReturn = useCallback( + async (loanTokenAmount: string) => { + return await contractReader.call( + 'sovrynProtocol', + 'getSwapExpectedReturn', + [ + getTokenContract(loanToken).address, + getTokenContract(collateralToken).address, + loanTokenAmount, + ], + ); + }, + [collateralToken, loanToken], + ); + + useEffect(() => { + if (collateralTokenSent !== '0') { + //get the oracle rate from collateral -> loan + getOracleRate() + .then(async ({ rate, precision }) => { + // compute the loan token amount with the oracle rate + let loanTokenAmount = bignumber(collateralTokenSent) + .mul(rate) + .div(precision) + .toFixed(0); + // see how many collateralTokens we would get if exchanging this amount of loan tokens to collateral tokens + const collateralTokenAmount = (await getSwapExpectedReturn( + loanTokenAmount, + )) as string; + //probably not the same due to the price difference + if (collateralTokenAmount !== collateralTokenSent) { + //scale the loan token amount accordingly, so we'll get the expected position size in the end + loanTokenAmount = bignumber(loanTokenAmount) + .mul(collateralTokenAmount) + .div(collateralTokenSent) + .toFixed(0); + } + setTotalDeposit( + bignumber(loanTokenAmount).add(totalDeposit).toFixed(0), + ); + }) + .catch(console.error); + } else { + setTotalDeposit(loanTokenSent); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ + loanToken, + collateralToken, + collateralTokenSent, + loanTokenSent, + getOracleRate, + getSwapExpectedReturn, + ]); + + useEffect(() => { + // + }, []); + + return totalDeposit; +} diff --git a/src/assets/images/tokens/bpro.svg b/src/assets/images/tokens/bpro.svg index a411d7fa4..ccf749f75 100644 --- a/src/assets/images/tokens/bpro.svg +++ b/src/assets/images/tokens/bpro.svg @@ -1,12 +1,8 @@ - - - - moc/config/icon-riskpro - Created with Sketch. - - - - - - + + + + + + + diff --git a/src/assets/images/tokens/doc.svg b/src/assets/images/tokens/doc.svg index bb1a57fbd..85c5bc1d4 100644 --- a/src/assets/images/tokens/doc.svg +++ b/src/assets/images/tokens/doc.svg @@ -1,12 +1,6 @@ - - - - moc/config/icon-stable - Created with Sketch. - - - - - - + + + + + diff --git a/src/assets/images/tokens/sov.svg b/src/assets/images/tokens/sov.svg index 09fbb4c0a..7b72f1fe3 100644 --- a/src/assets/images/tokens/sov.svg +++ b/src/assets/images/tokens/sov.svg @@ -1,11 +1,19 @@ - - - - moc/config/icon-riskpro - Created with Sketch. - - - - - + + + + + + + + + + + + + + + + + + diff --git a/src/assets/images/tokens/usdt.svg b/src/assets/images/tokens/usdt.svg index 4b55f5ddd..7e8ad5f42 100644 --- a/src/assets/images/tokens/usdt.svg +++ b/src/assets/images/tokens/usdt.svg @@ -1 +1,8 @@ - + + + + + + + + diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json index 09ec052d6..e9819ddfb 100644 --- a/src/locales/en/translation.json +++ b/src/locales/en/translation.json @@ -100,7 +100,8 @@ "fields": { "currency": "Currency", "currency_placeholder": "Choose currency", - "amount": "Amount" + "amount": "Amount", + "startPrice": "Start Price" }, "buttons": { "submit": "Place Trade" @@ -270,8 +271,7 @@ }, "borrowingContainer": { "amount": "Amount to borrow", - "token": "Token to collarate", - "collateralAmount": "Collateral amount", + "tokenAssetCollateral": "Asset to collateralize and amount", "borrow": "Borrow", "chooseDays": "Choose days" } @@ -531,7 +531,8 @@ "actions": { "deposit": "Top-Up", "swap": "Swap", - "trade": "Trade" + "trade": "Trade", + "claimSov": "Claim SOV" } }, "topUpHistory": { diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json index 69ccbbcb9..5d81a3923 100644 --- a/src/locales/es/translation.json +++ b/src/locales/es/translation.json @@ -237,8 +237,7 @@ }, "borrowingContainer": { "amount": "Cantidad del Préstamo", - "token": "Token de Garantía", - "collateralAmount": "Cantidad de Colateral", + "tokenAssetCollateral": "Activo a colateralizar y cantidad", "borrow": "Préstamo", "chooseDays": "Elegir Días" } diff --git a/src/locales/pt_br/translation.json b/src/locales/pt_br/translation.json index 47e9ff0de..7a03ba3d9 100644 --- a/src/locales/pt_br/translation.json +++ b/src/locales/pt_br/translation.json @@ -100,7 +100,8 @@ "fields": { "currency": "Ativo", "currency_placeholder": "Escolha o ativo", - "amount": "Quantidade" + "amount": "Quantidade", + "startPrice": "Preço inicial" }, "buttons": { "submit": "Realizar operação" @@ -270,8 +271,7 @@ }, "borrowingContainer": { "amount": "Valor do empréstimo", - "token": "Ativo a ser colaterizado", - "collateralAmount": "Quantidade colaterizada", + "tokenAssetCollateral": "Ativo a ser colaterizado e quantidade", "borrow": "Tomar empréstimo", "chooseDays": "Quantidade de dias" } @@ -370,7 +370,7 @@ } } }, - "SOVConnectTutorial": { + "SOVConnectTutorial": { "browser_wallet": "Carteira de navegador", "mobile_wallet": "Carteira de celular", "hardware_wallet": "Carteira física", @@ -425,8 +425,8 @@ }, "mobileNotReady": { "submit": "Enviar", - "p1": "A Sovryn ainda não foi otimizada para celular.", - "p2": "Cadastre seu e-mail para saber quando a versão otimizada para celular estará disponível!", + "p1": "A Sovryn ainda não foi otimizada para celulares.", + "p2": "Cadastre seu e-mail para ser notificado do lançamento da versão otimizada para celulares!", "p3": "Até lá, por que não tentar a versão para navegadores?", "errorText": "Erro ao enviar formulário", "success": "Sucesso!", @@ -480,7 +480,7 @@ "title": "Pendente para o usuário", "text": "Por favor, confirme a transação na sua carteira." }, - "pending": { + "pending": { "title": "Transação pendente", "text": "Sua transação está sendo processada." }, @@ -563,8 +563,8 @@ "tradeButtons": { "deposit": "Depositar e emprestar {{asset}}", "redeem": "Resgatar empréstimo {{asset}}" - }, - "liquidity": { + }, + "liquidity": { "redeem": { "line_1": "Não há {{currency}} suficiente no pool de empréstimo.", "line_2": "O pool atual tem somente {{amount}} {{currency}} disponível.", @@ -574,7 +574,7 @@ "line_1": "Não há {{currency}} suficiente no pool de empréstimos disponíveis para serem emprestados.", "line_2": "O pool atual tem somente {{amount}} {{currency}} disponível.", "line_3": "O pool irá aumentar quando os usuários quitarem seus empréstimos." - } + } } }, "activeBorrowTable": { diff --git a/src/styles/sass/new-design.scss b/src/styles/sass/new-design.scss index ad8ebeaf9..ca8461fb7 100644 --- a/src/styles/sass/new-design.scss +++ b/src/styles/sass/new-design.scss @@ -299,6 +299,10 @@ button.button-round { &:focus { background: rgba(254, 192, 4, 0.5) !important; } + + &:disabled { + opacity: 0.5; + } } .is-pointer { diff --git a/src/utils/blockchain/abi/bzxAbi.json b/src/utils/blockchain/abi/bzxAbi.json index bb9199216..5bcd84194 100644 --- a/src/utils/blockchain/abi/bzxAbi.json +++ b/src/utils/blockchain/abi/bzxAbi.json @@ -3393,5 +3393,36 @@ "payable": false, "stateMutability": "nonpayable", "type": "function" + }, + { + "constant": true, + "inputs": [ + { + "internalType": "address", + "name": "sourceToken", + "type": "address" + }, + { + "internalType": "address", + "name": "destToken", + "type": "address" + }, + { + "internalType": "uint256", + "name": "sourceTokenAmount", + "type": "uint256" + } + ], + "name": "getSwapExpectedReturn", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "payable": false, + "stateMutability": "view", + "type": "function" } ] diff --git a/src/utils/helpers.ts b/src/utils/helpers.ts index 596bae783..9150943e3 100644 --- a/src/utils/helpers.ts +++ b/src/utils/helpers.ts @@ -127,3 +127,9 @@ export function isChecked(value: any) { value = String(value || false).toLowerCase(); return ['true', '1', 'on', 'yes'].includes(value); } + +export const isMobile = () => { + return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( + navigator.userAgent, + ); +};