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

refactor: swap & tokens optimizations #2046

Merged
merged 4 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ export const JsonRpcCommonTransaction = ({
<Text
onPress={onPressApproveSpender}
variant={TextVariant.t11}
color={Color.textBlue1}>
color={Color.textGreen1}>
{Contracts.getById(parsedInput?.args?.[0])?.name ?? ''}
{STRINGS.NBSP}
{shortAddress(parsedInput?.args?.[0], '•', true)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ export const JsonRpcSwapTransaction = observer(
<Text
onPress={onPressRoutingSource}
variant={TextVariant.t11}
color={Color.textBlue1}>
color={Color.textGreen1}>
{Contracts.getById(tx?.to!)?.name}
{STRINGS.NBSP}
{shortAddress(tx?.to!, '•', true)}
Expand Down
7 changes: 6 additions & 1 deletion src/components/json-viewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const CustomNode = ({value}: {value: any}) => {
<Text
variant={TextVariant.t13}
color={Color.textBlue1}
selectable
onPress={handleAddressPress}>
"{part0}
<Text variant={TextVariant.t14} color={Color.textBlue1}>
Expand All @@ -43,7 +44,11 @@ const CustomNode = ({value}: {value: any}) => {
);
}

return <Text>{value}</Text>;
return (
<Text onPress={handleAddressPress} selectable>
{value}
</Text>
);
};

export const JsonViewer = ({
Expand Down
61 changes: 36 additions & 25 deletions src/models/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {storage} from '@app/services/mmkv';
import {
AddressType,
HaqqCosmosAddress,
HaqqEthereumAddress,
IContract,
IToken,
IndexerToken,
Expand Down Expand Up @@ -109,7 +110,7 @@ class TokensStore implements MobXStore<IToken> {
} else {
this.data = {
...this.data,
[AddressUtils.toHaqq(id)]: params,
[AddressUtils.toEth(id)]: params,
};
}

Expand All @@ -127,7 +128,7 @@ class TokensStore implements MobXStore<IToken> {
const newData = {
...this.data,
};
delete newData[AddressUtils.toHaqq(id)];
delete newData[AddressUtils.toEth(id)];

this.data = newData;
return true;
Expand Down Expand Up @@ -163,7 +164,7 @@ class TokensStore implements MobXStore<IToken> {
}

getById(id: string) {
return this.data[AddressUtils.toHaqq(id)];
return this.data[AddressUtils.toEth(id)];
}

update(id: string | undefined, item: Omit<IToken, 'id'>) {
Expand All @@ -179,7 +180,7 @@ class TokensStore implements MobXStore<IToken> {

this.data = {
...this.data,
[AddressUtils.toHaqq(id)]: {
[AddressUtils.toEth(id)]: {
...itemToUpdate,
...item,
value: updatedValue,
Expand All @@ -195,31 +196,35 @@ class TokensStore implements MobXStore<IToken> {

runInAction(() => {
this._isLoading = true;
this.tokens = {};
});

const wallets = Wallet.getAll();
const accounts = wallets.map(w => w.cosmosAddress);
const updates = await Indexer.instance.updates(accounts, this.lastUpdate);

const addressesMap = new Map(
updates.addresses.map(address => [address.id, address]),
updates.addresses.map(address => [
AddressUtils.toEth(address.id),
address,
]),
);

runInAction(() => {
this.tokens = {};
});
const _tokens = {} as Record<HaqqEthereumAddress, IToken[]>;
const _data = {} as Record<HaqqEthereumAddress, IToken>;

for (const t of updates.tokens) {
for await (const t of updates.tokens) {
try {
const isPositive = new Balance(t.value).isPositive();
if (!isPositive) {
continue;
}

const contractAddress = AddressUtils.toEth(t.contract);
const contract =
addressesMap.get(t.contract) ||
this.getContract(t.contract) ||
(await Whitelist.verifyAddress(t.contract));
addressesMap.get(contractAddress) ||
this.getContract(contractAddress) ||
(await Whitelist.verifyAddress(contractAddress));

if (!contract) {
Logger.error(
Expand All @@ -235,8 +240,8 @@ class TokensStore implements MobXStore<IToken> {
contract_updated_at: contract.updated_at,
value: new Balance(
t.value,
contract.decimals || app.provider.decimals,
contract.symbol || app.provider.denom,
contract.decimals ?? app.provider.decimals,
contract.symbol ?? app.provider.denom,
),
decimals: contract.decimals,
is_erc20: contract.is_erc20,
Expand All @@ -254,15 +259,14 @@ class TokensStore implements MobXStore<IToken> {

const walletAddress = AddressUtils.toEth(t.address);

runInAction(() => {
if (!this.tokens[walletAddress]?.length) {
this.tokens[walletAddress] = [
this.generateNativeToken(Wallet.getById(walletAddress)!),
];
}
if (!_tokens[walletAddress]?.length) {
_tokens[walletAddress] = [
this.generateNativeToken(Wallet.getById(walletAddress)!),
];
}

this.tokens[walletAddress].push(token);
});
_tokens[walletAddress].push(token);
_data[AddressUtils.toEth(token.id)] = token;
} catch (e) {
Logger.error(
'TokensStore.fetchTokens',
Expand All @@ -271,7 +275,14 @@ class TokensStore implements MobXStore<IToken> {
}
}

this._isLoading = false;
runInAction(() => {
this.tokens = _tokens;
this.data = {
...this.data,
..._data,
};
this._isLoading = false;
});
});

public generateNativeToken = (wallet: Wallet): IToken => {
Expand Down Expand Up @@ -341,7 +352,7 @@ class TokensStore implements MobXStore<IToken> {
const contractFromCache = this.getContract(token.contract);

const result: IToken = {
id: contractFromCache.id,
id: AddressUtils.toHaqq(contractFromCache.id),
devkudasov marked this conversation as resolved.
Show resolved Hide resolved
contract_created_at: contractFromCache.created_at,
contract_updated_at: contractFromCache.updated_at,
value: new Balance(
Expand Down Expand Up @@ -374,7 +385,7 @@ class TokensStore implements MobXStore<IToken> {
Contracts.create(contract.id, contract);
};

private getContract = (id: HaqqCosmosAddress) => {
private getContract = (id: HaqqCosmosAddress | HaqqEthereumAddress) => {
return Contracts.getById(id);
};

Expand Down
47 changes: 22 additions & 25 deletions src/screens/SwapStack/swap-screen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,8 @@ const getMinAmountForDecimals = (d: number | null, symbol: string | null) => {
if (!d) {
return MIN_SWAP_AMOUNT;
}
const zero = Array.from({length: d - 1})
.fill('0')
.join('');
const min = `0.${zero}1`;
const amountBN = ethers.utils.parseUnits(min, d);
return new Balance(amountBN, d, symbol || app.provider.denom);

return new Balance(Number(`0.${'0'.repeat(d! - 1)}1`), d, symbol!);
};

export const SwapScreen = observer(() => {
Expand Down Expand Up @@ -286,7 +282,7 @@ export const SwapScreen = observer(() => {
awaitForEventDone(Events.onBalanceSync),
]);
}
await refreshTokenBalances(currentWallet.address, tokenIn);
await refreshTokenBalances(currentWallet.address, t0Available);

if (isWrapTx || isUnwrapTx) {
amountsOut.setAmount(amountsIn.amount);
Expand Down Expand Up @@ -443,7 +439,10 @@ export const SwapScreen = observer(() => {
closeOnSelect: true,
renderCell: (
// eslint-disable-next-line @typescript-eslint/no-shadow
value: AwaitValue<{wallet: Wallet; tokens: IToken[]}>,
value: AwaitValue<{
wallet: Wallet;
tokens: (IToken & {tag: string})[];
}>,
_,
onPress,
) => {
Expand All @@ -462,11 +461,8 @@ export const SwapScreen = observer(() => {
return {
...t,
value:
Token.tokens[
AddressUtils.toEth(value?.wallet?.address)
// @ts-ignore
].find(c => c.id === t.tag?.split?.('_')[1])?.value ??
new Balance(0, 0, t?.symbol!),
tokens.find(c => c.id === t.tag?.split?.('_')[1])
?.value ?? new Balance(0, 0, t?.symbol!),
};
})}
onPressToken={(w, newValue, idx) => {
Expand Down Expand Up @@ -523,7 +519,7 @@ export const SwapScreen = observer(() => {

const refreshTokenBalances = async (
wallet = currentWallet.address,
t0 = tokenIn,
t0 = t0Available,
) => {
if (!t0 || !wallet) {
return {};
Expand All @@ -532,13 +528,13 @@ export const SwapScreen = observer(() => {
const tokenValue =
// @ts-ignore
t0.value ||
Token.tokens?.[wallet]?.find(t => AddressUtils.equals(t.id, t0.id!))
Token.tokens?.[wallet]?.find(t => AddressUtils.equals(t.id, tokenIn?.id!))
?.value;
const availableIslm = app.getAvailableBalance(wallet);

const symbol = t0.symbol || app.provider.denom;
const isNativeCurrency = symbol.toUpperCase() === app.provider.denom;
const decimals = t0.decimals || app.provider.decimals;
const symbol = t0.getSymbol() || app.provider.denom;
const isNativeCurrency = symbol === app.provider.denom;
const decimals = t0.getPrecission() || app.provider.decimals;
const zeroBalance = new Balance('0x0', decimals, symbol);
const value = new Balance(
(isNativeCurrency ? availableIslm : tokenValue) || zeroBalance,
Expand Down Expand Up @@ -597,7 +593,7 @@ export const SwapScreen = observer(() => {
);
setCurrentRoute(route! || filteredRoutes[0]);
}
await refreshTokenBalances(wallet.address, token);
await refreshTokenBalances(wallet.address, t0Available);
amountsIn.setMin();
return await estimate();
} catch (err) {
Expand Down Expand Up @@ -642,7 +638,7 @@ export const SwapScreen = observer(() => {
);
setCurrentRoute(route! || filteredRoutes[0]);
}
await refreshTokenBalances(wallet.address, tokenIn);
await refreshTokenBalances(wallet.address, t0Available);
return await estimate();
} catch (err) {
Logger.error(err, 'onPressChangeTokenOut');
Expand Down Expand Up @@ -962,11 +958,12 @@ export const SwapScreen = observer(() => {
const onPressMax = async () => {
Keyboard.dismiss();
vibrate(HapticEffects.impactLight);
const {value} = await refreshTokenBalances(currentWallet.address, tokenIn);
const balance = value || t0Available;
await refreshTokenBalances(currentWallet.address, t0Available);

amountsIn.setAmount(
balance.toBalanceString('auto', tokenIn?.decimals!, false),
t0Available.toBalanceString('auto', tokenIn?.decimals!, false),
);

await estimate();
};

Expand All @@ -979,7 +976,7 @@ export const SwapScreen = observer(() => {
wallets: walletsWithBalances?.length ? walletsWithBalances : wallets,
initialAddress: currentWallet.address,
});
await refreshTokenBalances(address as HaqqEthereumAddress, tokenIn);
await refreshTokenBalances(address as HaqqEthereumAddress, t0Available);
setCurrentWallet(() => Wallet.getById(address)!);
}, [currentWallet, refreshTokenBalances, tokenIn]);

Expand Down Expand Up @@ -1017,7 +1014,7 @@ export const SwapScreen = observer(() => {
useEffect(() => {
if (currentRoute) {
logger.log('useEffect estimate()');
refreshTokenBalances(currentWallet.address, tokenIn).then(() =>
refreshTokenBalances(currentWallet.address, t0Available).then(() =>
estimate(),
);
}
Expand Down
Loading
Loading