Skip to content

Commit

Permalink
Merge pull request #2738 from ecency/nt/cancel-order
Browse files Browse the repository at this point in the history
Nt/cancel order
  • Loading branch information
feruzm authored Aug 18, 2023
2 parents dd50634 + a60d889 commit a920a12
Show file tree
Hide file tree
Showing 9 changed files with 143 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ export default EStyleSheet.create({
justifyContent: 'center',
alignSelf: 'center',
},
cancelIcon:{
marginLeft:8,
},
dropdownWrapper: {
flex: 1,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { View, Text, TouchableOpacity } from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';

// Components
import { DropdownButton, PopoverWrapper, Icon, GrayWrapper } from '../../..';
import { DropdownButton, PopoverWrapper, Icon, GrayWrapper, IconButton } from '../../..';

// Styles
import styles from './walletLineItemStyles';
Expand All @@ -29,6 +29,9 @@ const WalletLineItem = ({
hintIconName,
hintDescription,
onPress,
cancelable,
cancelling,
onCancelPress,
}) => (
<TouchableOpacity onPress={onPress} disabled={!onPress} activeOpacity={0.8}>
<GrayWrapper isGray={index && index % 2 !== 0}>
Expand All @@ -40,11 +43,10 @@ const WalletLineItem = ({
styles.iconWrapper,
isCircleIcon && styles.circleIcon,
index && {
backgroundColor: `${
index && index % 2 !== 0
? EStyleSheet.value('$white')
: EStyleSheet.value('$primaryLightBackground')
}`,
backgroundColor: `${index && index % 2 !== 0
? EStyleSheet.value('$white')
: EStyleSheet.value('$primaryLightBackground')
}`,
},
]}
>
Expand Down Expand Up @@ -76,13 +78,17 @@ const WalletLineItem = ({
/>
</PopoverWrapper>
)}



</View>
)}
{!!description && (
<Text style={[styles.description, !iconName && styles.onlyText]}>{description}</Text>
)}
</View>
</View>

{!!rightText && (
<View style={styles.rightTextWrapper}>
<Text
Expand All @@ -95,6 +101,20 @@ const WalletLineItem = ({
</Text>
</View>
)}

{!!cancelable && (<IconButton
backgroundColor="transparent"
name="cancel"
iconType="MaterialIcons"
size={20}
style={styles.cancelIcon}
onPress={() => {onCancelPress && onCancelPress()}}
color="#c1c5c7"
isLoading={cancelling}
/>
)}


{isHasdropdown && (
<View style={styles.dropdownWrapper}>
<DropdownButton
Expand Down
6 changes: 5 additions & 1 deletion src/components/transaction/transactionView.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { getTimeFromNow } from '../../utils/time';
import { WalletLineItem } from '../basicUIElements';
import { getHumanReadableKeyString } from '../../utils/strings';

const TransactionView = ({ item, index }) => {
const TransactionView = ({ item, index, cancelling, onCancelPress}) => {
const intl = useIntl();
const [collapsed, setCollapsed] = useState(true);

Expand Down Expand Up @@ -42,6 +42,10 @@ const TransactionView = ({ item, index }) => {
onPress={() => {
setCollapsed(!collapsed);
}}
cancelable={item.cancelable}
cancelling={cancelling}
onCancelPress={onCancelPress}

/>
);

Expand Down
4 changes: 3 additions & 1 deletion src/config/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,9 @@
"free":"Free",
"confirm_swap":"Confirm Swap",
"swap_for" :"Swapping {fromAmount} for {toAmount}",
"swap_successful":"Successfully Swapped!",
"swap_successful":"Successfully Swapped",
"swap_pending":"Swap Pending!",
"swap_pending_body":"Swap requests may be pending, please check pending open orders in selected token details",
"new_swap":"New Swap"
},
"boost": {
Expand Down
45 changes: 45 additions & 0 deletions src/providers/hive-trade/hiveTrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,51 @@ export const limitOrderCreate = (
);
};


export const limitOrderCancel = (
currentAccount: any,
pinHash:string,
orderid: number
) => {

const digitPinCode = getDigitPinCode(pinHash);
const key = getAnyPrivateKey(
{
activeKey: currentAccount?.local?.activeKey,
},
digitPinCode,
);

if (key) {
const privateKey = PrivateKey.fromString(key);
const ops:Operation[] = [
[
"limit_order_cancel",
{
owner: currentAccount.username,
orderid: orderid
}
],
];

return new Promise((resolve, reject) => {
sendHiveOperations(ops, privateKey)
.then((result) => {
resolve(result);
})
.catch((err) => {
reject(err);
});
});
}

return Promise.reject(
new Error('Check private key permission! Required private active key or above.'),
);
};



export const generateHsLimitOrderCreatePath = (
currentAccount: any,
amountToSell: number,
Expand Down
1 change: 1 addition & 0 deletions src/redux/reducers/walletReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export interface CoinActivity {
value: string;
details: string | null;
memo: string;
cancelable: boolean;
}

export interface QuoteItem {
Expand Down
30 changes: 28 additions & 2 deletions src/screens/assetDetails/children/activitiesList.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import React, { ComponentType, JSXElementConstructor, ReactElement } from 'react';
import React, { ComponentType, JSXElementConstructor, ReactElement, useState } from 'react';
import { useIntl } from 'react-intl';
import { SectionList, Text, RefreshControl, ActivityIndicator } from 'react-native';
import EStyleSheet from 'react-native-extended-stylesheet';
import { Transaction } from '../../../components';
import { useAppSelector } from '../../../hooks';
import { CoinActivity } from '../../../redux/reducers/walletReducer';
import styles from './children.styles';
import { limitOrderCancel } from '../../../providers/hive-trade/hiveTrade';
import { walletQueries } from '../../../providers/queries';
import { useQueryClient } from '@tanstack/react-query';
import QUERIES from '../../../providers/queries/queryKeys';

interface ActivitiesListProps {
header: ComponentType<any> | ReactElement<any, string | JSXElementConstructor<any>>;
Expand All @@ -30,10 +34,32 @@ const ActivitiesList = ({
}: ActivitiesListProps) => {
const intl = useIntl();

const queryClient = useQueryClient();
const isDarkTheme = useAppSelector((state) => state.ui.isDarkTheme);
const currentAccount = useAppSelector((state) => state.account.currentAccount );
const pinHash = useAppSelector((state) => state.application.pin);

const [cancellingTrxIndex, setCancellingTrxIndex] = useState(-1);


const _onCancelPress = async (trxId:number) => {
try{
if(trxId){
setCancellingTrxIndex(trxId);
await limitOrderCancel(currentAccount, pinHash, trxId);
queryClient.invalidateQueries([QUERIES.WALLET.GET_PENDING_REQUESTS]);
setCancellingTrxIndex(-1);
}
} catch(err){
setCancellingTrxIndex(-1);
}


}

const _renderActivityItem = ({ item, index }) => {
return <Transaction item={item} index={index} />;

return <Transaction item={item} index={index} cancelling={cancellingTrxIndex === item.trxIndex} onCancelPress={()=>{_onCancelPress(item.trxIndex)}}/>;
};

const sections = [];
Expand Down
40 changes: 29 additions & 11 deletions src/screens/trade/children/swapTokenContent.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useMemo, useState } from 'react';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { View, Text, Alert, RefreshControl } from 'react-native';
import { useIntl } from 'react-intl';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
Expand Down Expand Up @@ -32,8 +32,6 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }:
const dispatch = useAppDispatch();
const navigation = useNavigation();

// queres
const assetsQuery = walletQueries.useAssetsQuery();

const currentAccount = useAppSelector((state) => state.account.currentAccount);
const currency = useAppSelector((state) => state.application.currency);
Expand All @@ -55,6 +53,15 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }:
[fromAssetSymbol],
);

const _fromAssetId = fromAssetSymbol === MarketAsset.HBD ? ASSET_IDS.HBD : ASSET_IDS.HIVE;
const _toAssetId = _toAssetSymbol === MarketAsset.HBD ? ASSET_IDS.HBD : ASSET_IDS.HIVE;


// queres
const assetsQuery = walletQueries.useAssetsQuery();
const pendingRequestsQuery = walletQueries.usePendingRequestsQuery(_fromAssetId);


// this method makes sure amount is only updated when new order book is fetched after asset change
// this avoid wrong from and to swap value on changing source asset
const _onAssetChangeComplete = () => {
Expand Down Expand Up @@ -83,12 +90,11 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }:
}, [tooMuchSlippage, offerUnavailable, isMoreThanBalance]);

// accumulate asset data properties
const _fromAssetData =
assetsData[fromAssetSymbol === MarketAsset.HBD ? ASSET_IDS.HBD : ASSET_IDS.HIVE];
const _fromAssetData = assetsData[_fromAssetId];
const _balance = _fromAssetData.balance;
const _fromFiatPrice = _fromAssetData.currentPrice;
const _toFiatPrice =
assetsData[_toAssetSymbol === MarketAsset.HBD ? ASSET_IDS.HBD : ASSET_IDS.HIVE].currentPrice;
assetsData[_toAssetId].currentPrice;
const _marketFiatPrice = marketPrice * _toFiatPrice;

const _toAmountStr = toAmount.toFixed(3);
Expand Down Expand Up @@ -124,11 +130,17 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }:
setFromAmount('0');
};

const _onSwapSuccess = () => {
const _onSwapSuccess = async (hasPending:boolean) => {

const _badgeColor = hasPending ? EStyleSheet.value('$primaryBlue') : EStyleSheet.value('$primaryGreen');
const _badgeIcon = hasPending ? "error-outline" : "check";
const _titleId = hasPending ? 'trade.swap_pending' : 'trade.swap_successful'
const _body = hasPending ? intl.formatMessage({ id: 'trade.swap_pending_body' }) : undefined;

const headerContent = (
<View
style={{
backgroundColor: EStyleSheet.value('$primaryGreen'),
backgroundColor: _badgeColor,
borderRadius: 56,
padding: 8,
}}
Expand All @@ -137,15 +149,16 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }:
style={{ borderWidth: 0 }}
size={64}
color={EStyleSheet.value('$pureWhite')}
name="check"
name={_badgeIcon}
iconType="MaterialIcons"
/>
</View>
);
dispatch(
showActionModal({
headerContent,
title: intl.formatMessage({ id: 'trade.swap_successful' }),
title: intl.formatMessage({ id: _titleId }),
body: _body,
buttons: [
{ textId: 'trade.new_swap', onPress: _reset },
{ textId: 'alert.done', onPress: () => navigation.goBack() },
Expand Down Expand Up @@ -173,9 +186,14 @@ export const SwapTokenContent = ({ initialSymbol, handleHsTransfer, onSuccess }:

await swapToken(currentAccount, pinHash, data);

await delay(1000);
const _existingPedingCount = pendingRequestsQuery.data?.length || 0;
const pendingRequests = await pendingRequestsQuery.refetch();
const _hasPending = pendingRequests.data?.length !== _existingPedingCount;

onSuccess();
setSwapping(false);
_onSwapSuccess();
_onSwapSuccess(_hasPending);
} catch (err) {
Alert.alert('fail', err.message);
setSwapping(false);
Expand Down
3 changes: 3 additions & 0 deletions src/utils/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,14 +413,17 @@ export const fetchPendingRequests = async (
.filter((request) => request.sell_price.base.includes(coinSymbol))
.map((request) => {
const { base, quote } = request?.sell_price || {};
const orderid = request.orderid
return {
trxIndex: orderid,
iconType: 'MaterialIcons',
textKey: 'open_order',
expires: request.expiration,
created: request.created,
icon: 'reorder',
value: base || '-- --',
details: base && quote ? `@ ${base} = ${quote}` : '',
cancelable: true,
} as CoinActivity;
});

Expand Down

0 comments on commit a920a12

Please sign in to comment.