Skip to content

Commit

Permalink
fixup! feat(suite): wip
Browse files Browse the repository at this point in the history
  • Loading branch information
enjojoy committed Oct 14, 2024
1 parent 2671d18 commit e3506f0
Showing 1 changed file with 63 additions and 55 deletions.
118 changes: 63 additions & 55 deletions packages/suite/src/views/wallet/send/Outputs/Amount/TokenSelect.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { useMemo, useEffect, useState } from 'react';
import { Controller } from 'react-hook-form';
import { AssetLogo, Column, Row, Select } from '@trezor/components';
// import styled from 'styled-components';
import { useSendFormContext } from 'src/hooks/wallet';
import { Account } from 'src/types/wallet';
import { Output } from '@suite-common/wallet-types';
import { useDispatch, useSelector } from 'src/hooks/suite';
import { updateFiatRatesThunk, selectCurrentFiatRates } from '@suite-common/wallet-core';
import { Timestamp, TokenAddress } from '@suite-common/wallet-types';
// import { TooltipSymbol, Translation } from 'src/components/suite';
import { NetworkSymbol } from '@suite-common/wallet-config';
import { networks, NetworkSymbol } from '@suite-common/wallet-config';
import {
enhanceTokensWithRates,
formatTokenSymbol,
Expand All @@ -29,11 +27,9 @@ import { getCoingeckoId } from '@suite-common/wallet-config';
import { getContractAddressForNetwork } from '@suite-common/wallet-utils';
import { Card } from '@trezor/components';
import { spacings } from '@trezor/theme';

// const UnrecognizedTokensHeading = styled.div`
// display: flex;
// align-items: center;
// `;
import { CoinmarketCryptoSelectItemProps } from 'src/types/coinmarket/coinmarket';
import { parseCryptoId, toTokenCryptoId } from 'src/utils/wallet/coinmarket/coinmarketUtils';
import { CryptoId } from 'invity-api';

export const buildTokenOptions = (
accountTokens: Account['tokens'],
Expand All @@ -44,10 +40,10 @@ export const buildTokenOptions = (
const result: SelectAssetOptionCurrencyProps[] = [
{
type: 'currency',
value: '',
value: networks[symbol].coingeckoNativeId || '',
label: symbol.toUpperCase(),
cryptoName: '',
coingeckoId: getCoingeckoId(symbol) ?? '',
coingeckoId: networks[symbol].coingeckoNativeId || '',
},
];

Expand All @@ -57,7 +53,7 @@ export const buildTokenOptions = (
tokens.shownWithBalance.forEach(token => {
result.push({
type: 'currency',
value: token.contract,
value: toTokenCryptoId(symbol, token.contract), //is this correct?
label: formatTokenSymbol(token.symbol || token.contract),
cryptoName: '',
coingeckoId: getCoingeckoId(symbol) ?? '',
Expand All @@ -73,7 +69,7 @@ export const buildTokenOptions = (
// <Translation id="TR_HIDDEN_TOKENS" />
// </UnrecognizedTokensHeading>
// ),
value: token.contract,
value: toTokenCryptoId(symbol, token.contract),
label: formatTokenSymbol(token.symbol || token.contract),
hidden: true,
cryptoName: '',
Expand All @@ -96,7 +92,7 @@ export const buildTokenOptions = (
// />
// </UnrecognizedTokensHeading>
// ),
value: token.contract,
value: toTokenCryptoId(symbol, token.contract),
label: formatTokenSymbol(token.symbol || token.contract),
unverified: true,
cryptoName: '',
Expand Down Expand Up @@ -148,10 +144,11 @@ export const TokenSelect = ({ output, outputId }: TokenSelectProps) => {
const tokenInputName = `outputs.${outputId}.token` as const;
const amountInputName = `outputs.${outputId}.amount` as const;
const currencyInputName = `outputs.${outputId}.currency` as const;
const tokenValue = getDefaultValue(tokenInputName, output.token) || '';

const isSetMaxActive = getDefaultValue('setMaxOutputId') === outputId;
const dataEnabled = getDefaultValue('options', []).includes('ethereumData');
const options = buildTokenOptions(sortedTokens, account.symbol, coinDefinitions);
const tokenValue = getDefaultValue(tokenInputName, output.token) || options[0].value;

// Amount needs to be re-validated again AFTER token change propagation (decimal places, available balance)
// watch token change and use "useSendFormFields.setAmount" util for validation (if amount is set)
Expand All @@ -178,12 +175,38 @@ export const TokenSelect = ({ output, outputId }: TokenSelectProps) => {
}
}, [sendFormPrefill, setValue, tokenInputName, setDraftSaveRequest, dispatch]);

const handleSelectChange = (selectedCryptoId: string) => {
// const findOption = options.find(
// option => option.type === 'currency' && option.value === selectedCryptoId,
// ) as CoinmarketCryptoSelectItemProps | undefined;
const handleSelectChange = async (selectedCryptoId: string) => {
const findOption = options.find(
option => option.type === 'currency' && option.value === selectedCryptoId,
) as CoinmarketCryptoSelectItemProps | undefined;

if (!findOption) return;

// if (!findOption) return;
setValue(tokenInputName, findOption);

await dispatch(
updateFiatRatesThunk({
tickers: [
{
symbol: account.symbol as NetworkSymbol,
tokenAddress: selectedCryptoId as TokenAddress, // TODO: check if this is correct (IT'S NOT), GET CONTRACT ADDRESS FROM THE SELECTED TOKEN. Where is cryproId coming from?
},
],
localCurrency: currencyValue.value as FiatCurrencyCode,
rateType: 'current',
fetchAttemptTimestamp: Date.now() as Timestamp,
}),
);
// clear errors in Amount input
clearErrors(amountInputName);
// remove Amount if isSetMaxActive or ETH data options are enabled
if (isSetMaxActive || dataEnabled) setAmount(outputId, '');
// remove ETH data option
if (dataEnabled) toggleOption('ethereumData');
// compose (could be prevented because of Amount error from re-validation above)
composeTransaction(amountInputName);

setValue(tokenInputName, findOption.value);

// if (isCoinmarketExchangeContext(context)) {
// context.setValue(FORM_RECEIVE_CRYPTO_CURRENCY_SELECT, findOption);
Expand All @@ -194,27 +217,6 @@ export const TokenSelect = ({ output, outputId }: TokenSelectProps) => {
// onChange={async (selected: SelectAssetOptionCurrencyProps) => {
// // change selected value
// onChange(selected.value);
// await dispatch(
// updateFiatRatesThunk({
// tickers: [
// {
// symbol: account.symbol as NetworkSymbol,
// tokenAddress: selected.value as TokenAddress,
// },
// ],
// localCurrency: currencyValue.value as FiatCurrencyCode,
// rateType: 'current',
// fetchAttemptTimestamp: Date.now() as Timestamp,
// }),
// );
// // clear errors in Amount input
// clearErrors(amountInputName);
// // remove Amount if isSetMaxActive or ETH data options are enabled
// if (isSetMaxActive || dataEnabled) setAmount(outputId, '');
// // remove ETH data option
// if (dataEnabled) toggleOption('ethereumData');
// // compose (could be prevented because of Amount error from re-validation above)
// composeTransaction(amountInputName);
// }}

setIsModalActive(false);
Expand All @@ -234,7 +236,6 @@ export const TokenSelect = ({ output, outputId }: TokenSelectProps) => {
control={control}
name={tokenInputName}
data-testid={tokenInputName}
defaultValue={options[0].value}
render={({ field: { value } }) => (
<Card margin={{ bottom: spacings.sm }} paddingType="normal">
<Select
Expand All @@ -247,27 +248,34 @@ export const TokenSelect = ({ output, outputId }: TokenSelectProps) => {
justifyContent: 'flex-start !important',
}),
}}
formatOptionLabel={(option: SelectAssetOptionCurrencyProps) => {
const address = option.value as TokenAddress;
formatOptionLabel={(value: CryptoId) => {
const findOption = options.find(
option => option.type === 'currency' && option.value === value,
) as CoinmarketCryptoSelectItemProps | undefined;

const { networkId, contractAddress } = parseCryptoId(value);

return (
<Row justifyContent="flex-start" gap={spacings.sm}>
{option.value ? (
<AssetLogo
coingeckoId={option.coingeckoId || ''}
contractAddress={getContractAddressForNetwork(
account.symbol as NetworkSymbol,
address,
)}
size={20}
placeholder={option.label}
/>
{findOption ? (
<>
<AssetLogo
coingeckoId={findOption.coingeckoId || ''}
contractAddress={getContractAddressForNetwork(
account.symbol as NetworkSymbol,
contractAddress as TokenAddress,
)}
size={20}
placeholder={findOption.label}
/>
{findOption.label}
</>
) : (
<CoinLogo symbol={account.symbol} size={20} />
)}
<Column>
{option.label}
{option.cryptoName}
{findOption.label}
{findOption.cryptoName}
</Column>
</Row>
);
Expand Down

0 comments on commit e3506f0

Please sign in to comment.