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

A-1206908284153320: switch to api v2 #133

Merged
merged 11 commits into from
Apr 1, 2024
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
1 change: 1 addition & 0 deletions src/components/basic/Input/Input.css
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

.input::placeholder {
color: rgb(var(--color-dark-gray));
opacity: 0.2;
font-size: 1.5rem;
}

Expand Down
4 changes: 2 additions & 2 deletions src/components/composed/Balance/Balance.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ test('Render account balance with ML', () => {

expect(balanceParagraphs[0].textContent).toBe(BALANCE_SAMPLE + ' ML')
expect(balanceParagraphs[1].textContent).toBe(
BALANCE_SAMPLE * EXCHANGE_RATE_SAMPLE + ',00 USD',
BALANCE_SAMPLE * EXCHANGE_RATE_SAMPLE + '.00 USD',
)
})

Expand All @@ -49,7 +49,7 @@ test('Render account balance with BTC', () => {

expect(balanceParagraphs[0].textContent).toBe(BALANCE_SAMPLE + ' BTC')
expect(balanceParagraphs[1].textContent).toBe(
BALANCE_SAMPLE * EXCHANGE_RATE_SAMPLE + ',00 USD',
BALANCE_SAMPLE * EXCHANGE_RATE_SAMPLE + '.00 USD',
)
})

Expand Down
10 changes: 5 additions & 5 deletions src/components/composed/CryptoFiatField/CryptoFiatField.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const CryptoFiatField = ({
const [value, setValue] = useState(inputValue)
const [validity, setValidity] = useState(parentValidity)
const amountErrorMessage = 'Amount set is bigger than this wallet balance.'
const amountFormatErrorMessage = 'Amount format is invalid. Use 0,00 instead.'
const amountFormatErrorMessage = 'Amount format is invalid. Use 0.00 instead.'
const zeroErrorMessage = 'Amount must be greater than 0.'
const isDelegationMode =
transactionMode === AppInfo.ML_TRANSACTION_MODES.DELEGATION &&
Expand Down Expand Up @@ -77,7 +77,7 @@ const CryptoFiatField = ({
// Consider the correct format for 0,00 that might also be 0.00
const displayedBottomValue =
networkType === AppInfo.NETWORK_TYPES.TESTNET
? `≈ 0,00 ${fiatName}`
? `≈ 0.00 ${fiatName}`
: formattedBottomValue

const calculateFiatValue = (value) => {
Expand Down Expand Up @@ -141,12 +141,12 @@ const CryptoFiatField = ({
setAmountValidity(true)
setValidity('valid')
}
setValue(value || 0)
updateValue(value || 0)
setValue(value || '')
updateValue(value || '')

const validity = AppInfo.amountRegex.test(value)

if (!validity) {
if (parsedValue > 0 && !validity) {
setValidity('invalid')
setAmountValidity(false)
setErrorMessage(amountFormatErrorMessage)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ test('Render TextField component', () => {
})

expect(input).toHaveValue(maxValueInToken.toString())
expect(bottomNote).toHaveTextContent('≈ 10054453,50 USD')
expect(bottomNote).toHaveTextContent('≈ 10054453.50 USD')

// expect(switchButton).toBeInTheDocument()
// expect(arrowIcons).toHaveLength(2)
Expand Down Expand Up @@ -102,7 +102,7 @@ test('Render TextField component fdf', async () => {
const maxValueInCrypto = maxValueInToken - totalFeeCrypto

fireEvent.click(actionButton)
expect(cryptoInput).toHaveValue(maxValueInCrypto.toString().replace('.', ','))
expect(cryptoInput).toHaveValue(maxValueInCrypto.toString())

// fireEvent.click(switchButton)
// const fiatInput = screen.getByTestId('input')
Expand Down Expand Up @@ -156,7 +156,7 @@ test('Render TextField when networkType is testnet', () => {
})

expect(input).toHaveValue(maxValueInToken.toString())
expect(bottomNote).toHaveTextContent('≈ 0,00 USD')
expect(bottomNote).toHaveTextContent('≈ 0.00 USD')

// expect(switchButton).toBeInTheDocument()

Expand Down
5 changes: 5 additions & 0 deletions src/components/composed/CurrentStaking/CurrentStaking.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { TransactionContext, SettingsContext, AccountContext } from '@Contexts'

import './CurrentStaking.css'
import Timer from '../../basic/Timer/Timer'
import { useEffectOnce } from '../../../hooks/etc/useEffectOnce'

const CurrentStaking = ({ addressList }) => {
const { networkType } = useContext(SettingsContext)
Expand Down Expand Up @@ -39,6 +40,10 @@ const CurrentStaking = ({ addressList }) => {
getTransactions,
} = useMlWalletInfo(addressList)

useEffectOnce(() => {
getDelegations()
})

const onNextButtonClick = () => {
setDelegationStep(2)
}
Expand Down
22 changes: 19 additions & 3 deletions src/components/containers/SendTransaction/SendTransaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const SendTransaction = ({
confirmTransaction,
goBackToWallet,
preEnterAddress,
setAdjustedFee,
}) => {
const { walletType, balanceLoading } = useContext(AccountContext)
const { feeLoading, transactionMode, currentDelegationInfo } =
Expand Down Expand Up @@ -72,7 +73,9 @@ const SendTransaction = ({
}

const openConfirmation = async () => {
if (!isFormValid) return
setPopupState(true)
setTxErrorMessage('')
onSendTransaction &&
onSendTransaction({
to: addressTo,
Expand Down Expand Up @@ -106,6 +109,19 @@ const SendTransaction = ({
setPassValidity(false)
setPass('')
setAllowClosing(true)
} else if (e.message.includes('minimum fee')) {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

For the cases when fee was not calculates properly, then provided by server.

// need to adjust fee
setAskPassword(false)
setPassPristinity(false)
setPassValidity(false)
setPass('')
setFee(e.message.split('minimum fee ')[1]) // Override fee with minimum fee
setTotalFeeCryptoParent(e.message.split('minimum fee ')[1])
setAdjustedFee(e.message.split('minimum fee ')[1])
setTxErrorMessage('Transaction fee adjusted')
console.error(e)
setAllowClosing(true)
setPopupState(true)
} else {
// handle other errors
setAskPassword(false)
Expand Down Expand Up @@ -243,10 +259,10 @@ const SendTransaction = ({
// TODO with 22-digit numbers, this is not working
if (amount + totalFee > maxValue || !validity) {
setAmountValidity(false)
setPassErrorMessage('Insufficient funds')
setTxErrorMessage('Insufficient funds')
} else if (amount + totalFee <= maxValue && validity) {
setAmountValidity(true)
setPassErrorMessage('')
setTxErrorMessage('')
}
}, [
totalFeeCrypto,
Expand Down Expand Up @@ -336,7 +352,7 @@ const SendTransaction = ({
fiatName={fiatName}
totalFeeFiat={totalFeeFiat}
totalFeeCrypto={totalFeeCrypto}
// txErrorMessage={txErrorMessage} // TODO move update on confirmation stage
txErrorMessage={txErrorMessage} // TODO move update on confirmation stage
fee={fee}
onConfirm={handleConfirm}
onCancel={handleCancel}
Expand Down
2 changes: 1 addition & 1 deletion src/components/containers/Wallet/Delegation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('Delegation', () => {
)
expect(screen.getByTestId('delegation-date')).toHaveTextContent(date)
expect(screen.getByTestId('delegation-amount')).toHaveTextContent(
'Amount: 0,001',
'Amount: 0.001',
)
})

Expand Down
2 changes: 1 addition & 1 deletion src/hooks/UseWalletInfo/useBtcWalletInfo.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ test('UseBtcWalletInfo hook', async () => {
transactionsList = result.current.btcTransactionsList
})

expect(balance).toBe('0,02881771')
expect(balance).toBe('0.02881771')
// TODO: +1 because of the message transaction. This is a temporary solution
expect(transactionsList.length).toBe(rawTransactions.length + 1)
})
Expand Down
11 changes: 7 additions & 4 deletions src/hooks/UseWalletInfo/useMlWalletInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ const useMlWalletInfo = (addresses) => {
const mergedDelegations = delegations.map((delegation, index) => {
return {
...delegation,
creation_time: delegation_details[index].creation_time.timestamp,
balance: delegation.balance.atoms,
creation_block_height: delegation_details[index].creation_block_height,
// TODO: add time
}
})

Expand All @@ -119,9 +121,9 @@ const useMlWalletInfo = (addresses) => {
if (effectCalled.current) return
effectCalled.current = true

getTransactions()
getDelegations()
getBalance()
// getTransactions()
// getDelegations()
// getBalance()
}, [getBalance, getTransactions, getDelegations])

return {
Expand All @@ -134,6 +136,7 @@ const useMlWalletInfo = (addresses) => {
mlDelegationsBalance,
getDelegations,
getTransactions,
getBalance,
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/hooks/etc/useEffectOnce.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useEffect, useRef } from 'react'
export function useEffectOnce(effect) {
const called = useRef(false)
useEffect(() => {
if (!called.current) {
called.current = true
effect()
}
}, [effect])
}
1 change: 0 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ const App = () => {
'This script should only be loaded in a browser extension.'
) {
// not extension env
console.log('not extension env')
return
}
// other error throw further
Expand Down
7 changes: 6 additions & 1 deletion src/pages/Dashboard/Dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import useOneDayAgoHist from 'src/hooks/UseOneDayAgoHist/useOneDayAgoHist'
import { useNavigate } from 'react-router-dom'
import { BTC } from '@Helpers'
import { AppInfo } from '@Constants'
import { useEffectOnce } from 'src/hooks/etc/useEffectOnce'

const DashboardPage = () => {
const { addresses, accountName, setWalletType, accountID } =
Expand All @@ -37,7 +38,7 @@ const DashboardPage = () => {

const [connectedWalletType, setConnectedWalletType] = useState('')
const { btcBalance } = useBtcWalletInfo(currentBtcAddress)
const { mlBalance } = useMlWalletInfo(currentMlAddresses)
const { mlBalance, getBalance } = useMlWalletInfo(currentMlAddresses)
const { exchangeRate: btcExchangeRate } = useExchangeRates('btc', 'usd')
const { exchangeRate: mlExchangeRate } = useExchangeRates('ml', 'usd')
const { yesterdayExchangeRate: btcYesterdayExchangeRate } =
Expand Down Expand Up @@ -172,6 +173,10 @@ const DashboardPage = () => {
getCurrentAccount(accountID).then((account) => setAccount(account))
}, [accountID])

useEffectOnce(() => {
getBalance()
}, [])

return (
<>
<Header noBackButton />
Expand Down
46 changes: 27 additions & 19 deletions src/pages/SendTransaction/SendTransaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { ML } from '@Cryptos'
import { Mintlayer } from '@APIs'

import './SendTransaction.css'
import { useEffectOnce } from '../../hooks/etc/useEffectOnce'

const SendTransactionPage = () => {
const { addresses, accountID, walletType } = useContext(AccountContext)
Expand All @@ -36,6 +37,7 @@ const SendTransactionPage = () => {
: addresses.mlTestnetAddresses
const [totalFeeFiat, setTotalFeeFiat] = useState(0)
const [totalFeeCrypto, setTotalFeeCrypto] = useState(0)
const [adjustedFee, setAdjustedFee] = useState(0)
const navigate = useNavigate()
const tokenName = walletType.name === 'Mintlayer' ? 'ML' : 'BTC'
const fiatName = 'USD'
Expand All @@ -48,7 +50,11 @@ const SendTransactionPage = () => {

const { exchangeRate } = useExchangeRates(tokenName, fiatName)
const { btcBalance } = useBtcWalletInfo(currentBtcAddress)
const { mlBalance } = useMlWalletInfo(currentMlAddresses)
const { mlBalance, getBalance } = useMlWalletInfo(currentMlAddresses)

useEffectOnce(() => {
getBalance()
})

const maxValueToken = walletType.name === 'Mintlayer' ? mlBalance : btcBalance

Expand Down Expand Up @@ -92,20 +98,20 @@ const SendTransactionPage = () => {
const address = transactionInfo.to
const amountToSend = MLHelpers.getAmountInAtoms(
transactionInfo.amount,
).toString()
)
const unusedChangeAddress = await ML.getUnusedAddress(changeAddress)
const utxos = await Mintlayer.getWalletUtxos(mlAddressList)
const parsedUtxos = utxos
.map((utxo) => JSON.parse(utxo))
.filter((utxo) => utxo.length > 0)
const fee = await MLTransaction.calculateFee(
parsedUtxos,
address,
unusedChangeAddress,
amountToSend,
networkType,
)
const feeInCoins = MLHelpers.getAmountInCoins(fee)
const fee = await MLTransaction.calculateFee({
utxosTotal: parsedUtxos,
address: address,
changeAddress: unusedChangeAddress,
amountToUse: amountToSend,
network: networkType,
})
const feeInCoins = MLHelpers.getAmountInCoins(Number(fee))
setTotalFeeFiat(Format.fiatValue(feeInCoins * exchangeRate))
setTotalFeeCrypto(feeInCoins)
setFeeLoading(false)
Expand Down Expand Up @@ -151,7 +157,7 @@ const SendTransactionPage = () => {
const confirmMlTransaction = async (password) => {
const amountToSend = MLHelpers.getAmountInAtoms(
transactionInformation.amount,
).toString()
)
const { mlPrivKeys } = await Account.unlockAccount(accountID, password)
const privKey =
networkType === 'mainnet'
Expand All @@ -173,14 +179,15 @@ const SendTransactionPage = () => {
const parsedUtxos = utxos
.map((utxo) => JSON.parse(utxo))
.filter((utxo) => utxo.length > 0)
const result = await MLTransaction.sendTransaction(
parsedUtxos,
keysList,
transactionInformation.to,
unusedChageAddress,
amountToSend,
networkType,
)
const result = await MLTransaction.sendTransaction({
utxosTotal: parsedUtxos,
keysList: keysList,
address: transactionInformation.to,
changeAddress: unusedChageAddress,
amountToUse: amountToSend,
network: networkType,
...(adjustedFee && { adjustedFee: MLHelpers.getAmountInAtoms(adjustedFee) })
})
return result
}

Expand All @@ -195,6 +202,7 @@ const SendTransactionPage = () => {
totalFeeFiat={totalFeeFiat}
totalFeeCrypto={totalFeeCrypto}
setTotalFeeCrypto={setTotalFeeCrypto}
setAdjustedFee={setAdjustedFee}
transactionData={transactionData}
exchangeRate={exchangeRate}
maxValueInToken={maxValueToken}
Expand Down
Loading