Skip to content

Commit

Permalink
Resolve ui bug #8
Browse files Browse the repository at this point in the history
  • Loading branch information
Thiendekaco committed Mar 2, 2024
1 parent 4c5ad35 commit c381d75
Show file tree
Hide file tree
Showing 9 changed files with 146 additions and 91 deletions.
1 change: 1 addition & 0 deletions packages/core/src/preflight-notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export async function preflightNotifications(
// check sufficient balance if required parameters are available
if (balance && gas && price) {
const transactionCost = gas.times(price).plus(value)
console.log(gas, price, balance);

// if transaction cost is greater than the current balance
if (transactionCost.gt(new BigNumber(balance))) {
Expand Down
52 changes: 42 additions & 10 deletions packages/core/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,17 @@ export function trackWallet(
}).pipe(share())

// when account changed, set it to first account and subscribe to events
accountsChanged$.subscribe(async (addressList) => {
accountsChanged$.subscribe(async (addressList_) => {

if (!addressList_ && addressList_.length <= 0) {
disconnect({ label, type })
return
}
// sync accounts with internal state
// in the case of an account has been manually disconnected
// in the case of an account has been manually disconnected;
const addressList = addressList_ .filter((a) => {
return type === 'evm' ? a.toLowerCase().startsWith('0x') : !a.toLowerCase().startsWith('0x')
})
try {
await syncWalletConnectedAccounts(label, type)
} catch (error) {
Expand All @@ -181,20 +189,31 @@ export function trackWallet(
// this could happen if user locks wallet,
// or if disconnects app from wallet
if (!addressList && addressList.length <= 0) {
disconnect({ label, type })
return
await disconnect({ label, type })
return;
}

const { wallets } = state.get()
const { accounts } = wallets
const walletFinded = wallets
.find(wallet => wallet.label === label && wallet.type === type)

if(!walletFinded) {
await disconnect({ label, type });
return;
}
const { accounts } = walletFinded;

const [existingAccounts] = partition(
accounts,
account => addressList.find(( address ) => address.includes(account.address))
account => addressList.find(
( address ) => address.includes(account.address)
)
)

const newAccounts = addressList.filter((address) => !existingAccounts.find((account) => address.includes(account.address)))
const newAccounts = addressList.filter(
(address) =>
!existingAccounts.find((account) => address.includes(account.address)
))

// update accounts without ens/uns and balance first
updateWallet(label, type, {
Expand All @@ -211,7 +230,8 @@ export function trackWallet(

// if not existing account and notifications,
// then subscribe to transaction events
if (state.get().notify.enabled && !( existingAccounts && existingAccounts.length > 0 )) {
if (state.get().notify.enabled
&& !( existingAccounts && existingAccounts.length > 0 )) {
const sdk = await getBNMulitChainSdk()

if (sdk) {
Expand All @@ -238,7 +258,17 @@ export function trackWallet(
// also when accounts change, update Balance and ENS/UNS
accountsChanged$
.pipe(
switchMap(async (addressList) => {
switchMap(async (addressList_) => {

if (!addressList_ && addressList_.length <= 0) {
return
}


const addressList = addressList_ .filter((a) => {
return type === 'evm' ? a.toLowerCase().startsWith('0x') : !a.toLowerCase().startsWith('0x')
})

if (!addressList && addressList.length <= 0) {
return
}
Expand All @@ -257,7 +287,9 @@ export function trackWallet(
)

return await Promise.all(addressList.map((address) => {
const balanceProm = getBalance(address, chain, primaryWallet.type )
const balanceProm = getBalance(
address, chain, primaryWallet.type
)
const secondaryTokenBal = updateSecondaryTokens(
primaryWallet,
address,
Expand Down
24 changes: 8 additions & 16 deletions packages/core/src/views/connect/ConnectingWallet.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import WalletAppBadge from '../shared/WalletAppBadge.svelte'
import en from '../../i18n/en.json'
import { state } from '../../store/index.js'
import { shareReplay, startWith } from 'rxjs'
import { shareReplay, startWith, withLatestFrom } from 'rxjs'
import { errorIcon } from '../../icons';
import { qrModalConnect$, uriConnect$ } from '../../streams.js';
import { MOBILE_WINDOW_WIDTH } from '../../constants.js';
Expand All @@ -19,19 +19,16 @@
let windowWidth: number
$: uri = '';
uriConnect$.subscribe((_uri)=>{
uri = _uri;
setTimeout(()=> {
openQrModal();
}, 500)
})
qrModalConnect$.subscribe( async ({ isOpen, modal })=>{
qrModalConnect$
.pipe(withLatestFrom(uriConnect$))
.subscribe(([{ isOpen, modal }, uri])=>{
if(isOpen && modal && uri !== ''){
try{
await modal.openModal({ uri })
setTimeout(()=>{
modal.openModal({ uri })
}, 500)
}catch (e) {
console.log(e)
}
Expand All @@ -40,12 +37,7 @@
}
})
function openQrModal() {
qrModalConnect$.next({
...qrModalConnect$.value,
isOpen: true
})
}
const appMetadata$ = state
.select('appMetadata')
.pipe(startWith(state.get().appMetadata), shareReplay(1))
Expand Down
56 changes: 25 additions & 31 deletions packages/core/src/views/connect/Index.svelte
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
<script lang="ts">
import type { EIP1193Provider, SubstrateProvider, WalletModule, Chain } from '@subwallet-connect/common'
import {ProviderRpcErrorCode, ProviderRpcErrorMessage} from '@subwallet-connect/common';
import type { EIP1193Provider, SubstrateProvider, WalletModule } from '@subwallet-connect/common'
import { ProviderRpcError, ProviderRpcErrorCode, ProviderRpcErrorMessage } from '@subwallet-connect/common';
import EventEmitter from 'eventemitter3';
import { BigNumber } from 'ethers'
import { _ } from 'svelte-i18n'
import en from '../../i18n/en.json'
import { enable, listenAccountsChanged, listenChainChanged } from '../../provider.js'
import {
enable,
getBalance,
getChainId,
getEns,
getUns,
listenAccountsChanged,
listenStateModal,
listenUriChange,
requestAccounts,
trackWallet
} from '../../provider.js'
import { state } from '../../store/index.js'
import { connectWallet$, onDestroy$, uriConnect$, qrModalConnect$, disconnectWallet$ } from '../../streams.js'
import { connectWallet$, onDestroy$, qrModalConnect$, uriConnect$ } from '../../streams.js'
import { addWallet, updateAccount } from '../../store/actions.js'
import {
validEnsChain,
isSVG,
setLocalStore,
getLocalStore
} from '../../utils.js'
import { getLocalStore, isSVG, setLocalStore, validEnsChain } from '../../utils.js'
import CloseButton from '../shared/CloseButton.svelte'
import Modal from '../shared/Modal.svelte'
import Agreement from './Agreement.svelte'
Expand All @@ -40,28 +46,10 @@
takeUntil
} from 'rxjs'
import {
getChainId,
requestAccounts,
trackWallet,
getBalance,
getEns,
getUns,
listenStateModal,
listenUriChange
} from '../../provider.js'
import type {
ConnectedChain,
ConnectOptions,
i18n, Uns, WalletConnectState,
WalletState,
WalletWithLoadingIcon
} from '../../types.js'
import type { ConnectOptions, i18n, Uns, WalletConnectState, WalletState, WalletWithLoadingIcon } from '../../types.js'
import { updateSecondaryTokens } from '../../update-balances'
export let autoSelect: ConnectOptions['autoSelect']
const appMetadata$ = state
Expand Down Expand Up @@ -262,6 +250,14 @@
chain = chainId
}
})
if(qrModalConnect$.value.modal){
qrModalConnect$.value.modal
.subscribeModal(({ open }) => {
if(!open && !(selectedWallet.accounts && selectedWallet.accounts.length !== 0)){
connectionRejected = true;
}
})
}
try {
Expand All @@ -274,8 +270,6 @@
address : undefined
})))
]);
console.log(valueResponse, '1231')
if(!valueResponse ) return;
const { address, signer, metadata } = valueResponse;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ type Props = ThemeProps;

const renderEmpty = () => <GeneralEmptyList />;

export const searchAccountFunction = (item: string, searchText: string): boolean => {
return item.toLowerCase().includes(searchText.toLowerCase()) || (item || '').toLowerCase().includes(searchText.toLowerCase());
export const searchAccountFunction = (item: Account, searchText: string): boolean => {
return item.address.toLowerCase().includes(searchText.toLowerCase());
};

const modalId = SELECT_ACCOUNT_MODAL;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }
if (maxLength && value.length > maxLength) {
value = value.slice(0, maxLength);
}

value = value.replace(/[^0-9.]/g, '');
setValidateValue(false);
form.setFieldValue('value', value);
}
Expand Down Expand Up @@ -363,7 +365,6 @@ function Component ({ className, senderAccount, evmProvider, substrateProvider }
>
<Input
placeholder={'Amount'}
type={'number'}
className={'__amount-transfer-input'}
onBlur={form.submit}
tooltip={'Amount'}
Expand Down
47 changes: 36 additions & 11 deletions packages/demo/src/utils/api/evmApi.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import {ethers} from 'ethers'
import type {Web3Provider} from '@ethersproject/providers';
import type {EIP1193Provider} from "@subwallet-connect/common";
import type { Web3Provider } from '@ethersproject/providers';
import type { EIP1193Provider } from "@subwallet-connect/common";
import web3Onboard from '../../web3-onboard';
import {RequestArguments} from "../../types";
import {METHOD_MAP, SIGN_METHODS} from "../methods";
import { RequestArguments } from "../../types";
import { METHOD_MAP, SIGN_METHODS } from "../methods";
import BigNumber from 'bignumber.js'
import type { TxDetails } from "@subwallet-connect/core/src/types";

export class evmApi {
private readonly provider ?: Web3Provider;
Expand All @@ -19,6 +20,18 @@ export class evmApi {
return (await this.provider.getBalance(senderAddress)).toString();
}

private async getEstimateGas (txDetails: TxDetails) {
if(! this.provider) return Promise.resolve('0');

return this.provider.estimateGas(txDetails).then((rs) => rs.toString());
}
private async getGasPrice () {
if(! this.provider) return Promise.resolve('0');

return this.provider.getGasPrice().then((rs) => rs.toString());
}



public async isAvailableAmount ( amount: string, senderAddress: string, recipientAddress: string ) {
if(!this.provider) return false;
Expand All @@ -28,8 +41,8 @@ export class evmApi {
}

const [ gas, price ] = await Promise.all([
this.provider.getGasPrice().then(res => new BigNumber(res.toString())),
this.provider.estimateGas(txDetails).then(res => new BigNumber(res.toString())),
this.getEstimateGas(txDetails).then(res => new BigNumber(res.toString())),
this.getGasPrice().then(res => new BigNumber(res.toString())),
])
const transactionCost = gas.times(price).plus(amount);
const balance = new BigNumber(await this.getMaxTransfer(amount, senderAddress, recipientAddress));
Expand All @@ -39,7 +52,7 @@ export class evmApi {
public async sendTransaction (senderAddress: string, recipientAddress: string, amount: string ) {
if(! this.provider) return;

const signer = this.provider.getUncheckedSigner();
const signer = this.provider.getSigner(senderAddress);
const txDetails = {
to: recipientAddress,
value: amount
Expand All @@ -49,11 +62,23 @@ export class evmApi {
fn(tx.hash);
return tx.hash;
}
const gasPrice = () => this.getGasPrice();

const estimateGas = () => this.getEstimateGas(txDetails);


const balanceValue = await this.getMaxTransfer(amount, senderAddress, recipientAddress)

// convert to hook when available
const transactionHash =
await web3Onboard.state.actions.preflightNotifications({
sendTransaction,
gasPrice,
estimateGas,
balance: balanceValue,
txDetails: txDetails
})

return await web3Onboard.state.actions.preflightNotifications({
sendTransaction,
txDetails: txDetails
})
}


Expand Down
Loading

0 comments on commit c381d75

Please sign in to comment.