Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(swap): Slippage screen #2639

Merged
merged 20 commits into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/wallet-mobile/src/features/Swap/common/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export const useStrings = () => {
eachVerifiedToken: intl.formatMessage(messages.eachVerifiedToken),
verifiedBadge: intl.formatMessage(messages.verifiedBadge),
enterSlippage: intl.formatMessage(messages.enterSlippage),
slippageToleranceError: intl.formatMessage(messages.slippageToleranceError),
pools: (qty: number) => intl.formatMessage(globalMessages.pools, {qty}),
openOrders: intl.formatMessage(messages.openOrders),
noAssetsFound: intl.formatMessage(messages.noAssetsFound),
Expand Down Expand Up @@ -98,6 +99,10 @@ export const messages = defineMessages({
id: 'swap.swapScreen.slippageTolerance',
defaultMessage: '!!!Slippage Tolerance',
},
slippageToleranceError: {
id: 'swap.swapScreen.slippageToleranceError',
defaultMessage: '!!!Slippage must be a number between 0 and 100 and have up to 1 decimal',
},
slippageToleranceInfo: {
id: 'swap.swapScreen.slippageToleranceInfo',
defaultMessage: '!!!Slippage Tolerance Info',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
import {useSwap} from '@yoroi/swap'
import React, {useEffect, useRef, useState} from 'react'
import {StyleSheet, Text, TextInput, TouchableOpacity, View} from 'react-native'
import {
KeyboardAvoidingView,
Platform,
ScrollView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native'

import {Button} from '../../../../../../../components'
import {COLORS} from '../../../../../../../theme'
import {useNavigateTo} from '../../../../../common/navigation'
import {useStrings} from '../../../../../common/strings'

type ChoiceKind = '0%' | '0.1%' | '0.5%' | '1%' | '2%' | '3%' | 'Manual'

interface Choice {
label: string
label: ChoiceKind
value: string | number
}

const Choices: Choice[] = [
const CHOICES: Choice[] = [
{label: '0%', value: 0},
{label: '0.1%', value: 0.1},
{label: '0.5%', value: 0.5},
Expand All @@ -22,108 +33,152 @@ const Choices: Choice[] = [
{label: 'Manual', value: ''},
]

const MAX_DECIMALS = 1

export const EditSlippageScreen = () => {
const [selectedChoice, setSelectedChoice] = useState('1%')
const [inputValue, setInputValue] = useState('1')
const {slippageChanged, createOrder} = useSwap()
const defaultSelectedChoice = getChoiceBySlippage(createOrder.slippage)
const defaultInputValue = defaultSelectedChoice.label === 'Manual' ? createOrder.slippage.toString() : ''
const [selectedChoiceLabel, setSelectedChoiceLabel] = useState<ChoiceKind>(defaultSelectedChoice.label)
const [inputValue, setInputValue] = useState(defaultInputValue)
const inputRef = useRef<TextInput | null>(null)
const navigate = useNavigateTo()
const strings = useStrings()
const {slippageChanged} = useSwap()

const handleChoicePress = (choice: Choice) => {
setSelectedChoice(choice.label)
setInputValue(choice.label === 'Manual' ? '' : String(choice.value))
const selectedChoice = getChoiceByLabel(selectedChoiceLabel)
const isSelectedChoiceManual = selectedChoiceLabel === 'Manual'

const handleChoicePress = (kind: ChoiceKind) => {
setSelectedChoiceLabel(kind)
}

const handleInputChange = (text: string) => {
setInputValue(text)
setInputValue(normalizeInputValue(text))
}

const onSubmit = () => {
slippageChanged(isSelectedChoiceManual ? Number(inputValue) : Number(selectedChoice.value))
navigate.startSwap()
}

useEffect(() => {
if (selectedChoice === 'Manual' && inputRef.current) {
if (isSelectedChoiceManual && inputRef.current) {
inputRef.current.focus()
}
}, [selectedChoice])
}, [isSelectedChoiceManual])

const isInputEnabled = selectedChoice === 'Manual'
const isInputEnabled = isSelectedChoiceManual
const hasError = isSelectedChoiceManual && !validateSlippage(inputValue)
const isButtonDisabled = hasError || (isSelectedChoiceManual && inputValue.length === 0)

return (
<View style={styles.container}>
<View>
<Text style={styles.header}>{strings.defaultSlippage}</Text>

<Text style={styles.textInfo}>{strings.slippageInfo}</Text>

<View style={styles.choicesContainer}>
{Choices.map((choice, index) => (
<TouchableOpacity
key={index}
style={[styles.choiceButton, selectedChoice === choice.label && styles.selectedChoiceButton]}
onPress={() => handleChoicePress(choice)}
>
<Text style={[styles.choiceLabel, selectedChoice === choice.label && styles.selectedChoiceLabel]}>
{choice.label}
</Text>
</TouchableOpacity>
))}
</View>

<View style={[styles.inputContainer, !isInputEnabled && styles.disabledInputContainer]}>
<Text style={[styles.label]}>{strings.slippageTolerance}</Text>

<TextInput
ref={inputRef}
value={inputValue}
onChangeText={handleInputChange}
editable={isInputEnabled}
selectTextOnFocus={isInputEnabled}
autoFocus={isInputEnabled}
style={[!isInputEnabled && styles.disabledInput]}
/>
</View>

{selectedChoice === 'Manual' && (
<Text style={[styles.textInfo, styles.bottomText]}>{strings.enterSlippage}</Text>
)}
</View>

<Button
testID="applyButton"
shelleyTheme
title={strings.apply}
onPress={() => {
slippageChanged(Number(inputValue))
navigate.startSwap()
}}
/>
<KeyboardAvoidingView
style={styles.flex}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
keyboardVerticalOffset={102}
>
<ScrollView bounces={false} style={styles.flex}>
<Text style={styles.header}>{strings.defaultSlippage}</Text>

<Text style={styles.description}>{strings.slippageInfo}</Text>

<View style={styles.choicesContainer}>
{CHOICES.map((choice, index) => (
<TouchableOpacity
key={index}
style={[styles.choiceButton, selectedChoiceLabel === choice.label && styles.selectedChoiceButton]}
onPress={() => handleChoicePress(choice.label)}
>
<Text style={[styles.choiceLabel, selectedChoiceLabel === choice.label && styles.selectedChoiceLabel]}>
{choice.label}
</Text>
</TouchableOpacity>
))}
</View>

<View
style={[
styles.inputContainer,
!isInputEnabled && styles.disabledInputContainer,
hasError && styles.errorInput,
]}
>
<Text style={[styles.label, hasError && styles.errorText]}>{strings.slippageTolerance}</Text>

<TextInput
ref={inputRef}
value={isInputEnabled ? inputValue : selectedChoice.value.toString()}
onChangeText={handleInputChange}
editable={isInputEnabled}
key={isInputEnabled ? 'enabled' : 'disabled'}
selectTextOnFocus={isInputEnabled}
autoFocus={isInputEnabled}
style={[!isInputEnabled && styles.disabledInput, styles.input]}
/>

<Text style={[styles.percentLabel]}>%</Text>
</View>

{isSelectedChoiceManual && !hasError && (
<Text style={[styles.textInfo, styles.bottomText]}>{strings.enterSlippage}</Text>
)}

{isSelectedChoiceManual && hasError && (
<Text style={[styles.bottomText, styles.errorText]}>{strings.slippageToleranceError}</Text>
)}
</ScrollView>

<Button
testID="applyButton"
shelleyTheme
title={strings.apply}
disabled={isButtonDisabled}
onPress={onSubmit}
/>
</KeyboardAvoidingView>
</View>
)
}

const styles = StyleSheet.create({
flex: {
flex: 1,
},
container: {
flexDirection: 'column',
justifyContent: 'space-between',
flex: 1,
backgroundColor: COLORS.WHITE,
paddingHorizontal: 16,
paddingTop: 13,
paddingBottom: 16,
},
header: {
fontSize: 16,
fontWeight: '500',
paddingVertical: 12,
fontFamily: 'Rubik-Medium',
color: '#242838',
},
textInfo: {
fontSize: 12,
color: COLORS.TEXT_INPUT,
},
description: {
fontSize: 12,
lineHeight: 18,
fontFamily: 'Rubik-Regular',
color: '#6B7384',
},
bottomText: {
paddingTop: 16,
color: '#4A5065',
lineHeight: 16,
fontSize: 12,
fontFamily: 'Rubik-Regular',
},
choicesContainer: {
flexDirection: 'row',
paddingVertical: 16,
flexWrap: 'wrap',
},
choiceButton: {
padding: 8,
Expand All @@ -136,6 +191,7 @@ const styles = StyleSheet.create({
fontSize: 15,
fontWeight: '500',
color: COLORS.BLACK,
fontFamily: 'Rubik-Medium',
},
selectedChoiceLabel: {
color: COLORS.BLACK,
Expand All @@ -145,6 +201,7 @@ const styles = StyleSheet.create({
borderWidth: 1,
borderColor: '#C4CAD7',
padding: 16,
position: 'relative',
},
label: {
position: 'absolute',
Expand All @@ -154,11 +211,58 @@ const styles = StyleSheet.create({
paddingHorizontal: 5,
fontSize: 12,
color: COLORS.ERROR_TEXT_COLOR_DARK,
fontFamily: 'Rubik-Regular',
},
disabledInput: {
color: COLORS.TEXT_INPUT,
},
disabledInputContainer: {
backgroundColor: '#F0F3F5',
},
errorText: {
color: COLORS.ALERT_TEXT_COLOR,
fontSize: 12,
},
errorInput: {
borderColor: COLORS.ALERT_TEXT_COLOR,
},
input: {
height: 24,
padding: 0,
fontSize: 16,
fontFamily: 'Rubik-Regular',
},
percentLabel: {
lineHeight: 24,
fontFamily: 'Rubik-Regular',
fontWeight: '400',
color: '#6B7384',
position: 'absolute',
padding: 16,
fontSize: 16,
right: 0,
top: 0,
},
})

const validateSlippage = (slippage: string) => {
const slippageNumber = Number(slippage)
return (
!isNaN(slippageNumber) &&
slippageNumber >= 0 &&
slippageNumber <= 100 &&
(slippageNumber * 10 ** MAX_DECIMALS) % 1 === 0
)
}

const getChoiceBySlippage = (slippage: number): Choice => {
return CHOICES.find((choice) => choice.value === slippage) ?? {label: 'Manual', value: slippage}
}

const getChoiceByLabel = (label: ChoiceKind): Choice => {
return CHOICES.find((choice) => choice.label === label) ?? {label: 'Manual', value: ''}
}

const normalizeInputValue = (value: string) => {
return value.length === 0 ? '0' : value.replace(',', '.').replace(/^0+(?=\d)/, '')
Copy link
Collaborator Author

@michaeljscript michaeljscript Aug 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. When the input is an empty string, convert to '0'
  2. Convert ',' to '.'
  3. Remove leading zeros for inputs like '03'

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔 @MichalSzorad can you check to use intl number formatter? It might affect these rules. I think @nistadev updated extension.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @stackchain I'll have a look

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stackchain Would we need a library like this one d2l-intl to be able to parse the number?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added parsing using BigNumber, but I don't think we can format the output using BigNumber, can we? Eg when the user types 3. we do not want to convert the number to 3 and this seems what BigNumber is doing

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is still WIP, as I'm trying to integrate the util made by Jordi

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is now integrated @stackchain

}
1 change: 1 addition & 0 deletions apps/wallet-mobile/src/i18n/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
"swap.swapScreen.selectToken": "Select token",
"swap.swapScreen.marketPrice": "Market price",
"swap.swapScreen.slippageTolerance": "Slippage tolerance",
"swap.swapScreen.slippageToleranceError": "Slippage must be a number between 0 and 100 and have up to 1 decimal",
"swap.swapScreen.slippageToleranceInfo": "Slippage tolerance is set as a percentage of the total swap value. Your transactions will not be executed if the price moves by more than this amount",
"swap.swapScreen.selectPool": "Select pool",
"swap.swapScreen.eachVerifiedToken": "Each verified tokens gets",
Expand Down
Loading