Skip to content

Commit

Permalink
fix: minor cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
gutsyphilip committed May 3, 2022
2 parents 6e52bcf + 9c3bb69 commit 7a0087a
Show file tree
Hide file tree
Showing 5 changed files with 149 additions and 124 deletions.
15 changes: 6 additions & 9 deletions packages/frontend/src/components/Routing.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import styled, { ThemeProvider } from 'styled-components';
import {
CREATE_IMPLICIT_ACCOUNT,
IMPORT_ACCOUNT_WITH_LINK_V2,
CREATE_USN_CONTRACT,
} from '../../../../features';
import TwoFactorVerifyModal from '../components/accounts/two_factor/TwoFactorVerifyModal';
import {
Expand Down Expand Up @@ -93,10 +92,10 @@ import { Profile } from './profile/Profile';
import { ReceiveContainerWrapper } from './receive-money/ReceiveContainerWrapper';
import { SendContainerWrapper } from './send/SendContainerWrapper';
import { StakingContainer } from './staking/StakingContainer';
import SwapContainerWrapper from './Swap/SwapContainerWrapper';
import Terms from './terms/Terms';
import { SwapNear } from './wrap/SwapNear';


import '../index.css';

const { fetchTokenFiatValues, getTokenWhiteList } = tokenFiatValueActions;
Expand Down Expand Up @@ -621,13 +620,11 @@ class Routing extends Component {
path="/buy"
component={BuyNear}
/>
{CREATE_USN_CONTRACT && (
<PrivateRoute
exact
path="/swap-money"
component={SwapContainerWrapper}
/>
)}
<PrivateRoute
exact
path='/swap'
component={SwapNear}
/>
<PrivateRoute
exact
path="/swap"
Expand Down
6 changes: 3 additions & 3 deletions packages/frontend/src/components/wallet/Wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import DownArrowIcon from '../svg/DownArrowIcon';
import SendIcon from '../svg/SendIcon';
import Swap from '../svg/SwapIcon';
import TopUpIcon from '../svg/TopUpIcon';
import Wrap from '../svg/WrapIcon';
import WrapIcon from '../svg/WrapIcon';
import ActivitiesWrapper from './ActivitiesWrapper';
import CreateCustomNameModal from './CreateCustomNameModal';
import CreateFromImplicitSuccessModal from './CreateFromImplicitSuccessModal';
Expand Down Expand Up @@ -447,11 +447,11 @@ const FungibleTokens = ({
<FormButton
color="dark-gray"
linkTo="/swap"
trackingId="Click Receive on Wallet page"
trackingId="Click Swap on Wallet page"
data-test-id="balancesTab.swap"
>
<div>
<Wrap color="white" />
<WrapIcon color="white" />
</div>
<Translate id="button.swap" />
</FormButton>
Expand Down
147 changes: 48 additions & 99 deletions packages/frontend/src/components/wrap/SwapNear.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as nearApiJs from 'near-api-js';
import { parseNearAmount } from 'near-api-js/lib/utils/format';
import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import styled from 'styled-components';
Expand All @@ -14,18 +14,12 @@ import {
selectTokensLoading,
} from '../../redux/slices/tokens';
import { fungibleTokensService } from '../../services/FungibleTokens';
import { validateInput } from '../../utils/wrap-unwrap';
import Container from '../common/styled/Container.css';
import { validateInput } from './components/helper';
import Success from './components/Success';
import { SwapAmountForm } from './components/SwapAmountForm';
import { SwapReviewForm } from './components/SwapReviewForm';

const {
utils: {
format: { parseNearAmount },
},
} = nearApiJs;

const { fetchTokens } = tokensActions;
const { checkAndHideLedgerModal } = ledgerActions;

Expand Down Expand Up @@ -58,54 +52,6 @@ const StyledContainer = styled(Container)`
height: initial !important;
margin: initial !important;
}
&.go-back {
position: absolute;
top: 0;
left: -13px;
min-height: 42px !important;
height: 42px !important;
min-width: 42px !important;
width: 42px !important;
border-radius: 50% !important;
:hover {
background-color: #eeefee !important;
}
@media (max-width: 991px) {
top: -9px;
left: 1px;
}
}
&.learn-more {
font-size: 14px !important;
font-weight: 400 !important;
text-decoration: none !important;
margin-top: 10px !important;
:hover {
text-decoration: underline !important;
}
}
&.black,
&.gray-gray {
width: 100% !important;
display: flex !important;
align-items: center;
justify-content: center;
border: 0 !important;
svg {
margin: -3px 0 0 10px !important;
}
}
&.gray-gray svg {
margin-right: 4px !important;
}
}
h3 {
Expand Down Expand Up @@ -198,6 +144,51 @@ export function SwapNear({ match, location, history }) {
setError(!validateInput(amountTokenFrom, maxFrom.fullNum));
}, [amountTokenFrom, maxFrom]);


const handleSwapToken = async (
accountId,
wrapAmount,
toWNear
) => {
await Mixpanel.withTracking(
'SWAP token',
async () => {
setSwappingToken(true);

const result =
await fungibleTokensService.wrapNear({
accountId,
wrapAmount:
parseNearAmount(wrapAmount),
toWNear,
});
setTransactionHash(result.transaction.hash);
setActiveView(VIEWS.SUCCESS);

const id = Mixpanel.get_distinct_id();
Mixpanel.identify(id);
Mixpanel.people.set({
last_send_token: new Date().toString(),
});
},
(e) => {
dispatch(
showCustomAlert({
success: false,
messageCodeHeader: 'error',
messageCode:
'walletErrorCodes.sendFungibleToken.error',
errorMessage: e.message,
})
);
setSwappingToken('failed');
return;
}
);

dispatch(checkAndHideLedgerModal());
};

const getCurrentViewComponent = (view) => {
switch (view) {
case VIEWS.SWAP_AMOUNT:
Expand Down Expand Up @@ -232,49 +223,7 @@ export function SwapNear({ match, location, history }) {
activeTokenTo={activeTokenTo}
mockRateData={mockRateData}
accountId={accountId}
handleSwapToken={async (
accountId,
wrapAmount,
toWNear
) => {
await Mixpanel.withTracking(
'SWAP token',
async () => {
setSwappingToken(true);

const result =
await fungibleTokensService.wrapNear({
accountId,
wrapAmount:
parseNearAmount(wrapAmount),
toWNear,
});
setTransactionHash(result.transaction.hash);
setActiveView(VIEWS.SUCCESS);

const id = Mixpanel.get_distinct_id();
Mixpanel.identify(id);
Mixpanel.people.set({
last_send_token: new Date().toString(),
});
},
(e) => {
dispatch(
showCustomAlert({
success: false,
messageCodeHeader: 'error',
messageCode:
'walletErrorCodes.sendFungibleToken.error',
errorMessage: e.message,
})
);
setSwappingToken('failed');
return;
}
);

dispatch(checkAndHideLedgerModal());
}}
handleSwapToken={handleSwapToken}
swappingToken={swappingToken}
/>
);
Expand Down
28 changes: 15 additions & 13 deletions packages/frontend/src/components/wrap/components/SwapAmountForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import React, { useState, useEffect } from 'react';
import { Translate } from 'react-localize-redux';
import styled from 'styled-components';

import { getFormatBalance } from '../../../utils/wrap-unwrap';
import BackArrowButton from '../../common/BackArrowButton';
import FormButton from '../../common/FormButton';
import SwapIcon from '../../svg/WrapIcon';
import { VIEWS } from '../SwapNear';
import { getFormatBalance } from './helper';
import SwapFromForm from './SwapFromForm';
import SwapFromTo from './SwapFromTo';

Expand Down Expand Up @@ -111,6 +111,19 @@ export function SwapAmountForm({
}
}, [amountTokenFrom, amountTokenTo, error]);

const handleSwapForm = () => {
const temp = amountTokenTo;
const tempMax = maxTo;
const tempToken = activeTokenTo;
setActiveTokenTo(activeTokenFrom);
setActiveTokenFrom(tempToken);
setAmountTokenTo(amountTokenFrom);
setAmountTokenFrom(temp);
setMaxTo(maxFrom);
setMaxFrom(tempMax);
setMockRateData(1 / mockRateData);
};

return (
<StyledContainer>
<div className="header">
Expand All @@ -130,18 +143,7 @@ export function SwapAmountForm({
<div className="margin">
<FormButton
color="small-rounded"
onClick={() => {
const temp = amountTokenTo;
const tempMax = maxTo;
const tempToken = activeTokenTo;
setActiveTokenTo(activeTokenFrom);
setActiveTokenFrom(tempToken);
setAmountTokenTo(amountTokenFrom);
setAmountTokenFrom(temp);
setMaxTo(maxFrom);
setMaxFrom(tempMax);
setMockRateData(1 / mockRateData);
}}
onClick={handleSwapForm}
>
<SwapIcon className="hoverFill" />
</FormButton>
Expand Down
77 changes: 77 additions & 0 deletions packages/frontend/src/utils/wrap-unwrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { removeTrailingZeros } from './amounts';

export const getFormatBalance = (num, decimals) => {
if (!num || num === '0') {
return {
numToShow: '0',
fullNum: '0',
};
}
let number = '';
let dotPlace = '';
for (let i = num.length - 1; i >= 0; i--) {
if (number.length === decimals) {
number = '.' + number;
dotPlace = i;
}
number = num[i] + number;
}
if (dotPlace || dotPlace === 0) {
return {
numToShow: removeTrailingZeros(number.slice(0, dotPlace + 7)),
fullNum: removeTrailingZeros(number),
};
} else {
if (decimals - number.length > 0) {
let countOfZeros = decimals - number.length;
number = '0.' + '0'.repeat(countOfZeros) + number;
return {
numToShow: removeTrailingZeros(
number.slice(0, 3 + countOfZeros)
),
fullNum: removeTrailingZeros(number),
};
} else {
number = '0.' + number;
return {
numToShow: removeTrailingZeros(number.slice(0, 4)),
fullNum: removeTrailingZeros(number),
};
}
}
};

const getValue = (str, decimals) => {
const strArr = str.split('.');
if (!strArr[1]) {
return strArr[0];
}
let number = strArr[1];
for (let i = 0; i < decimals; i++) {
if (!strArr[1][i]) {
number += 0;
continue;
}
}
return `${strArr[0]}.${number}`;
};

export const validateInput = (value, max) => {
if (!value || +value === 0) {
return false;
}
value = value.replace(/,/g, '.');
const strArr = value.split('.');
if (strArr[1] && strArr[1].length > 24) {
return false;
}
const myTokens = getValue(max, 24);
const inputTokens = getValue(value, 24);
if (+inputTokens > +myTokens) {
return false;
}
if (+inputTokens === +myTokens && inputTokens > myTokens) {
return false;
}
return true;
};

0 comments on commit 7a0087a

Please sign in to comment.