Skip to content

Commit

Permalink
feat(bridge-ui-v2): Improve refreshing users balance (#14651)
Browse files Browse the repository at this point in the history
  • Loading branch information
KorbinianK authored Sep 6, 2023
1 parent 8783d5e commit 8028a49
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 44 deletions.
22 changes: 10 additions & 12 deletions packages/bridge-ui-v2/src/components/Bridge/Amount.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,12 @@
import { warningToast } from '$components/NotificationToast';
import { checkBalanceToBridge, getMaxAmountToBridge } from '$libs/bridge';
import { InsufficientAllowanceError, InsufficientBalanceError, RevertedWithFailedError } from '$libs/error';
import { ETHToken, getBalance as getTokenBalance } from '$libs/token';
import { ETHToken, getBalance as getTokenBalance,TokenType } from '$libs/token';
import { renderBalance } from '$libs/util/balance';
import { debounce } from '$libs/util/debounce';
import { getLogger } from '$libs/util/logger';
import { renderBalance } from '$libs/util/renderBalance';
import { uid } from '$libs/util/uid';
import { account } from '$stores/account';
import { ethBalance } from '$stores/balance';
import { network } from '$stores/network';
import {
Expand Down Expand Up @@ -102,16 +101,15 @@
$errorComputingBalance = false;
try {
$tokenBalance = await getTokenBalance({
token,
srcChainId,
destChainId,
userAddress,
});
if (token.name === ETHToken.name) {
$ethBalance = $tokenBalance;
if (token.type !== TokenType.ETH) {
$tokenBalance = await getTokenBalance({
token,
srcChainId,
destChainId,
userAddress,
});
} else {
$ethBalance = await getTokenBalance({
$tokenBalance = await getTokenBalance({
token: ETHToken,
srcChainId,
destChainId,
Expand Down
4 changes: 4 additions & 0 deletions packages/bridge-ui-v2/src/components/Bridge/Bridge.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
} from '$libs/error';
import { bridgeTxService } from '$libs/storage';
import { ETHToken, getAddress, isDeployedCrossChain, tokens, TokenType } from '$libs/token';
import { refreshUserBalance } from '$libs/util/balance';
import { getConnectedWallet } from '$libs/util/getConnectedWallet';
import { type Account, account } from '$stores/account';
import { type Network, network } from '$stores/network';
Expand Down Expand Up @@ -247,6 +248,9 @@
// Update balance after bridging
amountComponent.updateBalance();
// Refresh user's balance
refreshUserBalance();
} catch (err) {
console.error(err);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
let isAddressValid = false;
let contractAddress = '';
let imageUrls = Array<string>();
let imageUrls = [];
$: tokenIds = $tokenIdStore;
$: isButtonDisabled = !($tokenIdStore?.length ?? 0);
Expand Down
6 changes: 6 additions & 0 deletions packages/bridge-ui-v2/src/components/Bridge/Recipient.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
import AddressInput from './AddressInput.svelte';
import { recipientAddress } from './state';
// Public API
export const clearRecipient = () => {
addressInput.clear(); // update UI
$recipientAddress = null; // update state
};
let dialogId = `dialog-${uid()}`;
let addressInput: AddressInput;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,14 @@
import { t } from 'svelte-i18n';
import { Button } from '$components/Button';
import { DesktopOrLarger } from '$components/DesktopOrLarger';
import { EthIcon, Icon } from '$components/Icon';
import { Spinner } from '$components/Spinner';
import { web3modal } from '$libs/connect';
import { renderEthBalance } from '$libs/util/balance';
import { noop } from '$libs/util/noop';
import { renderBalance } from '$libs/util/renderBalance';
import { ethBalance } from '$stores/balance';
export let connected = false;
// Will help us to programmatically show or hide the balance of
// the web3modal core button
let isDesktopOrLarger: boolean;
let web3modalOpen = false;
let unsubscribeWeb3Modal = noop;
Expand All @@ -35,23 +30,19 @@
onDestroy(unsubscribeWeb3Modal);
</script>

<DesktopOrLarger bind:is={isDesktopOrLarger} />

<!--
We are gonna make use of Web3Modal core button when we are connected,
which comes with interesting features out of the box.
https://docs.walletconnect.com/2.0/web/web3modal/html/wagmi/components
-->
{#if connected}
<Button class="hidden sm:flex px-[20px] py-2 mr-[8px] rounded-full" type="neutral" on:click={connectWallet}>
<span class="body-regular f-items-center space-x-2">
<svelte:component this={EthIcon} size={20} />
<span>{renderBalance($ethBalance)}</span>
{#if $ethBalance >= 0}
<span>{renderEthBalance($ethBalance)}</span>
{:else}
<Spinner /> <span>Fetching balance...</span>
{/if}
</span>
</Button>
<w3m-core-button balance="hide" />
{:else}
<!-- TODO: fixing the width for English. i18n? -->
<Button class="px-[20px] py-2 rounded-full w-[215px]" type="neutral" loading={web3modalOpen} on:click={connectWallet}>
<span class="body-regular f-items-center space-x-2">
{#if web3modalOpen}
Expand Down
25 changes: 25 additions & 0 deletions packages/bridge-ui-v2/src/libs/util/balance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { type FetchBalanceResult, getAccount, getPublicClient } from '@wagmi/core';
import { formatEther } from 'viem';

import { truncateString } from '$libs/util/truncateString';
import { ethBalance } from '$stores/balance';

export function renderBalance(balance: Maybe<FetchBalanceResult>) {
if (!balance) return '0.00';

const maxlength = Number(balance.formatted) < 0.000001 ? balance.decimals : 6;
return `${truncateString(balance.formatted, maxlength, '')} ${balance.symbol}`;
}

export function renderEthBalance(balance: bigint, maxlength = 8): string {
return `${truncateString(formatEther(balance).toString(), maxlength, '')} ETH`;
}

export const refreshUserBalance = async () => {
const account = getAccount();
let balance = BigInt(0);
if (account?.address) {
balance = await getPublicClient().getBalance({ address: account.address });
}
ethBalance.set(balance);
};
10 changes: 0 additions & 10 deletions packages/bridge-ui-v2/src/libs/util/renderBalance.ts

This file was deleted.

8 changes: 5 additions & 3 deletions packages/bridge-ui-v2/src/libs/wagmi/watcher.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { watchAccount, watchNetwork /*, watchPublicClient, watchWalletClient*/ } from '@wagmi/core';
import { watchAccount, watchNetwork } from '@wagmi/core';

import { isSupportedChain } from '$libs/chain';
import { refreshUserBalance } from '$libs/util/balance';
import { getLogger } from '$libs/util/logger';
import { account } from '$stores/account';
import { switchChainModal } from '$stores/modal';
Expand All @@ -12,7 +13,7 @@ let isWatching = false;
let unWatchNetwork: () => void;
let unWatchAccount: () => void;

export function startWatching() {
export async function startWatching() {
if (!isWatching) {
// Action for subscribing to network changes.
// See https://wagmi.sh/core/actions/watchNetwork
Expand All @@ -32,14 +33,15 @@ export function startWatching() {
// When we switch networks, we are actually selecting
// the source chain.
network.set(chain);
refreshUserBalance();
});

// Action for subscribing to account changes.
// See https://wagmi.sh/core/actions/watchAccount
unWatchAccount = watchAccount((data) => {
log('Account changed', data);

account.set(data);
refreshUserBalance();
});

isWatching = true;
Expand Down
3 changes: 1 addition & 2 deletions packages/bridge-ui-v2/src/stores/balance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { FetchBalanceResult } from '@wagmi/core';
import { writable } from 'svelte/store';

export const ethBalance = writable<Maybe<FetchBalanceResult>>(null);
export const ethBalance = writable<bigint>();

0 comments on commit 8028a49

Please sign in to comment.