feat(wallet): send - add user fees settings and memo field (#3146)

* feat(wallet): send - add user fees settings, memo field

* fix(wallet): send, custom fees validation
This commit is contained in:
Pierre Dommerc
2023-03-06 18:26:07 +01:00
committed by GitHub
parent dc4353c682
commit eca77d684b
12 changed files with 293 additions and 15 deletions
@@ -1,10 +1,13 @@
// Copyright 2022 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::nyxd::{Gas, GasPrice};
pub use cosmrs::Coin as CosmosCoin;
pub use cosmwasm_std::Coin as CosmWasmCoin;
use cosmwasm_std::{Fraction, Uint128};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::ops::Div;
#[derive(Serialize, Deserialize, Clone, Copy, Default, Debug, PartialEq, Eq)]
pub struct MismatchedDenoms;
@@ -19,6 +22,40 @@ pub struct Coin {
pub denom: String,
}
impl Div<GasPrice> for Coin {
type Output = Gas;
fn div(self, rhs: GasPrice) -> Self::Output {
&self / rhs
}
}
impl<'a> Div<GasPrice> for &'a Coin {
type Output = Gas;
fn div(self, rhs: GasPrice) -> Self::Output {
if self.denom != rhs.denom {
panic!(
"attempted to use two different denoms for gas calculation ({} and {})",
self.denom, rhs.denom
);
}
// tsk, tsk. somebody tried to divide by zero here!
let Some(gas_price_inv) = rhs.amount.inv() else {
panic!("attempted to divide by zero!")
};
let implicit_gas_limit = gas_price_inv * Uint128::new(self.amount);
if implicit_gas_limit.u128() >= u64::MAX as u128 {
u64::MAX
} else {
implicit_gas_limit.u128() as u64
}
.into()
}
}
impl Coin {
pub fn new<S: Into<String>>(amount: u128, denom: S) -> Self {
Coin {
@@ -128,3 +165,67 @@ impl CoinConverter for CosmWasmCoin {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn division_by_zero_gas_price() {
let gas_price: GasPrice = "0unym".parse().unwrap();
let amount = Coin::new(123, "unym");
let _res = amount / gas_price;
}
#[test]
#[should_panic]
fn division_by_gas_price_of_different_denom() {
let gas_price: GasPrice = "0.025unyx".parse().unwrap();
let amount = Coin::new(123, "unym");
let _res = amount / gas_price;
}
#[test]
fn gas_price_division() {
let amount = Coin::new(3938, "unym");
let gas_price = "0.025unym".parse().unwrap();
let res = amount / gas_price;
assert_eq!(157520, res.value());
let amount = Coin::new(1234567890, "unym");
let gas_price = "0.025unym".parse().unwrap();
let res = amount / gas_price;
assert_eq!(49382715600, res.value());
let amount = Coin::new(1, "unym");
let gas_price = "0.025unym".parse().unwrap();
let res = amount / gas_price;
assert_eq!(40, res.value());
let amount = Coin::new(150_000_000, "unym");
let gas_price = "0.001234unym".parse().unwrap();
let res = amount / gas_price;
assert_eq!(121555915721, res.value());
let amount = Coin::new(150_000_000, "unym");
let gas_price = "1unym".parse().unwrap();
let res = amount / gas_price;
assert_eq!(150_000_000, res.value());
let amount = Coin::new(150_000_000, "unym");
let gas_price = "1234.56unym".parse().unwrap();
let res = amount / gas_price;
assert_eq!(121500, res.value());
}
#[test]
fn gas_price_division_identity() {
let amount = Coin::new(1234567890, "unym");
let gas_price: GasPrice = "0.025unym".parse().unwrap();
let res1 = (&amount) / gas_price.clone();
let res2 = &gas_price * res1;
assert_eq!(amount, Coin::from(res2));
}
}
@@ -1,8 +1,8 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nyxd::Coin;
use crate::nyxd::Gas;
use crate::nyxd::{Coin, GasPrice};
use cosmrs::{tx, AccountId};
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
@@ -64,6 +64,12 @@ impl Display for Fee {
}
impl Fee {
pub fn manual_with_gas_price(fee: Coin, gas_price: GasPrice) -> Self {
let gas_limit = &fee / gas_price;
Fee::Manual(tx::Fee::from_amount_and_gas(fee.into(), gas_limit))
}
pub fn new_payer_granter_auto(
gas_adjustment: Option<GasAdjustment>,
payer: Option<AccountId>,
+1
View File
@@ -143,6 +143,7 @@ fn main() {
vesting::queries::vesting_start_time,
simulate::admin::simulate_update_contract_settings,
simulate::cosmos::simulate_send,
simulate::cosmos::get_custom_fees,
simulate::mixnet::simulate_bond_gateway,
simulate::mixnet::simulate_unbond_gateway,
simulate::mixnet::simulate_bond_mixnode,
@@ -33,3 +33,13 @@ pub async fn simulate_send(
let result = client.nyxd.simulate(vec![msg]).await?;
guard.create_detailed_fee(result)
}
#[tauri::command]
pub async fn get_custom_fees(
fees_amount: DecCoin,
state: tauri::State<'_, WalletState>,
) -> Result<FeeDetails, BackendError> {
let guard = state.read().await;
let fee = guard.attempt_convert_to_fixed_fee(fees_amount.clone())?;
Ok(FeeDetails::new(Some(fees_amount), fee))
}
+11
View File
@@ -88,6 +88,17 @@ pub(crate) struct WalletAccountIds {
}
impl WalletStateInner {
pub fn attempt_convert_to_fixed_fee(&self, coin: DecCoin) -> Result<Fee, BackendError> {
// first we have to convert the coin to its base denomination
let base_coin = self.attempt_convert_to_base_coin(coin)?;
// then we get the gas price for the current network
let current_client = self.current_client()?;
let gas_price = current_client.nyxd.gas_price();
Ok(Fee::manual_with_gas_price(base_coin, gas_price.clone()))
}
// note that `Coin` is ALWAYS the base coin
pub fn attempt_convert_to_base_coin(&self, coin: DecCoin) -> Result<Coin, BackendError> {
let registered_coins = self
@@ -1,5 +1,5 @@
import React from 'react';
import { Box, Stack, Typography, TypographyProps } from '@mui/material';
import { Box, Stack, SxProps, Typography, TypographyProps } from '@mui/material';
import { ModalDivider } from './ModalDivider';
export const ModalListItem: FCWithChildren<{
@@ -9,14 +9,15 @@ export const ModalListItem: FCWithChildren<{
fontWeight?: TypographyProps['fontWeight'];
light?: boolean;
value?: React.ReactNode;
}> = ({ label, value, hidden, fontWeight, divider }) => (
sxValue?: SxProps;
}> = ({ label, value, hidden, fontWeight, divider, sxValue }) => (
<Box sx={{ display: hidden ? 'none' : 'block' }}>
<Stack direction="row" justifyContent="space-between">
<Typography fontSize="smaller" fontWeight={fontWeight} sx={{ color: 'text.primary', fontSize: 14 }}>
{label}
</Typography>
{value && (
<Typography fontSize="smaller" fontWeight={fontWeight} sx={{ color: 'text.primary', fontSize: 14 }}>
<Typography fontSize="smaller" fontWeight={fontWeight} sx={{ color: 'text.primary', fontSize: 14, ...sxValue }}>
{value}
</Typography>
)}
@@ -35,6 +35,9 @@ export const SendInput = () => {
onClose={() => {}}
onAddressChange={() => {}}
onAmountChange={() => {}}
onUserFeesChange={() => {}}
onMemoChange={() => {}}
setShowMore={() => {}}
{...storybookStylesModal(theme)}
/>
);
@@ -16,6 +16,7 @@ export const SendDetailsModal = ({
onSend,
sx,
backdropProps,
memo,
}: {
fromAddress?: string;
toAddress: string;
@@ -27,6 +28,7 @@ export const SendDetailsModal = ({
onSend: (data: { val: DecCoin; to: string }) => void;
sx?: SxProps;
backdropProps?: object;
memo?: string;
}) => (
<SimpleModal
header="Send details"
@@ -43,6 +45,20 @@ export const SendDetailsModal = ({
<ModalListItem label="To" value={toAddress} divider />
<ModalListItem label="Amount" value={`${amount?.amount} ${denom.toUpperCase()}`} divider />
<ModalFee fee={fee} divider isLoading={false} />
{memo && (
<ModalListItem
label="Memo"
value={memo}
sxValue={{
textOverflow: 'ellipsis',
overflow: 'hidden',
whiteSpace: 'nowrap',
overflowWrap: 'anywhere',
maxWidth: '300px',
}}
divider
/>
)}
<ModalTotalAmount fee={fee} amount={amount?.amount} divider isLoading={false} />
</Stack>
</SimpleModal>
@@ -1,11 +1,15 @@
import React, { useEffect, useState } from 'react';
import { Stack, TextField, Typography, SxProps } from '@mui/material';
import { Stack, TextField, Typography, SxProps, FormControlLabel, Checkbox } from '@mui/material';
import Big from 'big.js';
import { CurrencyFormField } from '@nymproject/react/currency/CurrencyFormField';
import { CurrencyDenom, DecCoin } from '@nymproject/types';
import { CurrencyDenom, DecCoin, isValidRawCoin } from '@nymproject/types';
import { validateAmount } from 'src/utils';
import { SimpleModal } from '../Modals/SimpleModal';
import { ModalListItem } from '../Modals/ModalListItem';
const maxUserFees = '10.0';
const minUserFees = '0.000001'; // aka 1 unym
export const SendInputModal = ({
fromAddress,
toAddress,
@@ -19,6 +23,12 @@ export const SendInputModal = ({
onAddressChange,
sx,
backdropProps,
userFees,
memo,
onUserFeesChange,
onMemoChange,
showMore,
setShowMore,
}: {
fromAddress?: string;
toAddress: string;
@@ -26,24 +36,61 @@ export const SendInputModal = ({
balance?: string;
denom?: CurrencyDenom;
error?: string;
showMore?: boolean;
setShowMore: (show: boolean) => void;
onNext: () => void;
onClose: () => void;
onAmountChange: (value: DecCoin) => void;
onAddressChange: (value: string) => void;
sx?: SxProps;
backdropProps?: object;
userFees?: DecCoin;
memo?: string;
onUserFeesChange: (value: DecCoin) => void;
onMemoChange: (value: string) => void;
}) => {
const [isValid, setIsValid] = useState(false);
const [memoIsValid, setMemoIsValid] = useState(true);
const [feeAmountIsValid, setFeeAmountIsValid] = useState(true);
const validate = async (value: DecCoin) => {
const isValidAmount = await validateAmount(value.amount, '0');
setIsValid(isValidAmount);
};
const validateUserFees = (fees: DecCoin) => {
if (!isValidRawCoin(fees.amount) || !Number(fees.amount)) {
setFeeAmountIsValid(false);
return;
}
const f = Big(fees.amount);
if (f.gt(maxUserFees) || f.lt(minUserFees)) {
setFeeAmountIsValid(false);
return;
}
setFeeAmountIsValid(true);
};
useEffect(() => {
if (amount) validate(amount);
}, []);
useEffect(() => {
if (memo && !/^(\w|\s)+$/.test(memo)) {
setMemoIsValid(false);
return;
}
setMemoIsValid(true);
}, [memo]);
useEffect(() => {
if (userFees) {
validateUserFees(userFees);
} else {
setFeeAmountIsValid(true);
}
}, [userFees]);
return (
<SimpleModal
header="Send"
@@ -51,7 +98,7 @@ export const SendInputModal = ({
onClose={onClose}
okLabel="Next"
onOk={async () => onNext()}
okDisabled={!isValid}
okDisabled={!isValid || !memoIsValid || !feeAmountIsValid}
sx={sx}
backdropProps={backdropProps}
>
@@ -84,6 +131,35 @@ export const SendInputModal = ({
Est. fee for this transaction will be show on the next page
</Typography>
</Stack>
<FormControlLabel
control={<Checkbox onChange={() => setShowMore(!showMore)} checked={showMore} />}
label="More options"
sx={{ mt: 2 }}
/>
{showMore && (
<Stack direction="column" gap={3} mt={2} mb={3}>
<CurrencyFormField
label="Fees"
onChanged={(v) => onUserFeesChange(v)}
initialValue={userFees?.amount}
fullWidth
/>
<TextField
name="memo"
label="Memo"
onChange={(e) => onMemoChange(e.target.value)}
value={memo}
error={!memoIsValid}
helperText={
!memoIsValid
? ' The text is invalid, only alphanumeric characters and white spaces are allowed'
: undefined
}
InputLabelProps={{ shrink: true }}
fullWidth
/>
</Stack>
)}
</SimpleModal>
);
};
+41 -5
View File
@@ -1,4 +1,4 @@
import React, { useContext, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import { DecCoin } from '@nymproject/types';
import { AppContext, urls } from 'src/context';
import { useGetFee } from 'src/hooks/useGetFee';
@@ -18,11 +18,28 @@ export const SendModal = ({ onClose, hasStorybookStyles }: { onClose: () => void
const [modal, setModal] = useState<'send' | 'send details'>('send');
const [error, setError] = useState<string>();
const [sendError, setSendError] = useState(false);
const [gasError, setGasError] = useState<string>();
const [isLoading, setIsLoading] = useState(false);
const [userFees, setUserFees] = useState<DecCoin>();
const [memo, setMemo] = useState<string>();
const [txDetails, setTxDetails] = useState<TTransactionDetails>();
const [showMoreOptions, setShowMoreOptions] = useState(false);
const { clientDetails, userBalance, network } = useContext(AppContext);
const { fee, getFee, feeError } = useGetFee();
const { fee, getFee, feeError, setFeeManually } = useGetFee();
useEffect(() => {
if (userFees?.amount.length === 0) {
setUserFees(undefined);
}
}, [userFees]);
useEffect(() => {
if (!showMoreOptions) {
setUserFees(undefined);
setMemo(undefined);
}
}, [showMoreOptions]);
// removes any zero-width spaces and trailing white space
const sanitizeAddress = (address: string) => address.replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
@@ -32,7 +49,11 @@ export const SendModal = ({ onClose, hasStorybookStyles }: { onClose: () => void
setIsLoading(true);
setError(undefined);
try {
await getFee(simulateSend, { address: toAddress, amount });
if (userFees) {
await setFeeManually(userFees);
} else {
await getFee(simulateSend, { address: toAddress, amount });
}
setModal('send details');
} catch (e) {
setError(e as string);
@@ -48,14 +69,18 @@ export const SendModal = ({ onClose, hasStorybookStyles }: { onClose: () => void
setIsLoading(true);
setError(undefined);
try {
const txResponse = await send({ amount: val, address: to, memo: '', fee: fee?.fee });
const txResponse = await send({ amount: val, address: to, memo: memo || '', fee: fee?.fee });
setTxDetails({
amount: `${amount?.amount} ${clientDetails?.display_mix_denom.toUpperCase()}`,
txUrl: `${urls(network).blockExplorer}/transaction/${txResponse.tx_hash}`,
});
} catch (e) {
Console.error(e as string);
setSendError(true);
if (/Raw log: out of gas/.test(e as string)) {
setGasError('Out of gas, please increase the amount of fees');
} else {
setSendError(true);
}
} finally {
setIsLoading(false);
}
@@ -65,6 +90,10 @@ export const SendModal = ({ onClose, hasStorybookStyles }: { onClose: () => void
if (sendError) return <SendErrorModal onClose={onClose} error={feeError} />;
if (gasError) {
return <SendErrorModal onClose={onClose} error={gasError} />;
}
if (txDetails) return <SendSuccessModal txDetails={txDetails} onClose={onClose} />;
if (modal === 'send details')
@@ -78,6 +107,7 @@ export const SendModal = ({ onClose, hasStorybookStyles }: { onClose: () => void
onPrev={() => setModal('send')}
onSend={handleSend}
denom={clientDetails?.display_mix_denom || 'nym'}
memo={memo}
{...hasStorybookStyles}
/>
);
@@ -92,8 +122,14 @@ export const SendModal = ({ onClose, hasStorybookStyles }: { onClose: () => void
onNext={handleOnNext}
error={error}
denom={clientDetails?.display_mix_denom}
userFees={userFees}
memo={memo}
showMore={showMoreOptions}
onAmountChange={(value) => setAmount(value)}
onAddressChange={(value) => setToAddress(sanitizeAddress(value))}
onUserFeesChange={(value) => setUserFees(value)}
onMemoChange={(value) => setMemo(value)}
setShowMore={setShowMoreOptions}
{...hasStorybookStyles}
/>
);
+15 -1
View File
@@ -1,6 +1,7 @@
import { FeeDetails } from '@nymproject/types';
import { DecCoin, FeeDetails } from '@nymproject/types';
import { useState } from 'react';
import { Console } from 'src/utils/console';
import { getCustomFees } from '../requests';
export function useGetFee() {
const [fee, setFee] = useState<FeeDetails>();
@@ -19,6 +20,18 @@ export function useGetFee() {
setIsFeeLoading(false);
}
async function setFeeManually(amount: DecCoin) {
try {
setIsFeeLoading(true);
const fees = await getCustomFees({ feesAmount: amount });
setFee(fees);
} catch (e) {
Console.error(e);
setFeeError(e as string);
}
setIsFeeLoading(false);
}
const resetFeeState = () => {
setFee(undefined);
setIsFeeLoading(false);
@@ -30,6 +43,7 @@ export function useGetFee() {
isFeeLoading,
feeError,
getFee,
setFeeManually,
resetFeeState,
};
}
+3
View File
@@ -59,6 +59,9 @@ export const simulateWithdrawVestedCoins = async (args: any) =>
export const simulateSend = async ({ address, amount }: { address: string; amount: DecCoin }) =>
invokeWrapper<FeeDetails>('simulate_send', { address, amount });
export const getCustomFees = async ({ feesAmount }: { feesAmount: DecCoin }) =>
invokeWrapper<FeeDetails>('get_custom_fees', { feesAmount });
export const simulateClaimOperatorReward = async () => invokeWrapper<FeeDetails>('simulate_claim_operator_reward');
export const simulateVestingClaimOperatorReward = async () =>