Skip to content

Commit

Permalink
Merge pull request #559 from telosnetwork/557-walletconnect-qr-login-…
Browse files Browse the repository at this point in the history
…method-has-an-incorrect-local-injected-provider-dependency

fixing WC-QR login removing injected provider dependancy
  • Loading branch information
pmjanus authored Aug 23, 2023
2 parents 5c5e41c + e85f8ab commit caea7e2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 29 deletions.
27 changes: 0 additions & 27 deletions src/antelope/stores/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ import {
import { AccountModel, EvmAccountModel } from 'src/antelope/stores/account';
import { EVMAuthenticator } from 'src/antelope/wallets';
import { filter } from 'rxjs';
import { convertCurrency } from 'src/antelope/stores/utils/currency-utils';

export interface BalancesState {
__balances: { [label: Label]: TokenBalance[] };
Expand Down Expand Up @@ -169,39 +168,13 @@ export const useBalancesStore = defineStore(store_name, {
const chain_settings = useChainStore().getChain(label).settings as EVMChainSettings;
const sysToken = chain_settings.getSystemToken();
const wrpToken = chain_settings.getWrappedSystemToken();
const stkToken = chain_settings.getStakedSystemToken();

// get the price for both system and wrapped tokens
const price = (await chain_settings.getUsdPrice()).toString();
const marketInfo = { price } as MarketSourceInfo;
sysToken.market = new TokenMarketData(marketInfo);
wrpToken.market = new TokenMarketData(marketInfo);

// first we need the contract instance to be able to execute queries
const evm = useEVMStore();
const authenticator = useAccountStore().getEVMAuthenticator(label);
const contract = await evm.getContract(authenticator, stkToken.address, stkToken.type);
if (!contract) {
throw new AntelopeError('antelope.balances.error_token_contract_not_found', { address: stkToken.address });
}
const contractInstance = await contract.getContractInstance();

// Now we preview a deposit of 1 SYS to get the ratio
const oneSys = ethers.utils.parseUnits('1.0', sysToken.decimals);
const ratio:BigNumber = await contractInstance.previewDeposit(oneSys);
const ratioNumber = ethers.utils.formatUnits(ratio, stkToken.decimals);

// Now we calculate the price of 1 STK = (price of 1 SYS) / ratio
const stkPrice = convertCurrency(oneSys, sysToken.decimals, stkToken.decimals, ratioNumber);
const stkPriceNumber = ethers.utils.formatUnits(stkPrice, sysToken.decimals);

// Finally we update the STK token price
const stkMarketInfo = { price:stkPriceNumber } as MarketSourceInfo;
// TODO: this is removed until we decide what to do whith the STK token price
// https://github.com/telosnetwork/telos-wallet/issues/544
// stkToken.market = new TokenMarketData(stkMarketInfo);
this.trace('updateSystemTokensPrices', `STLOS price: ${toRaw(stkMarketInfo)}`);

} catch (error) {
console.error(error);
// we won't thorw an error here, as it is not critical
Expand Down
37 changes: 35 additions & 2 deletions src/antelope/wallets/authenticators/WalletConnectAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export class WalletConnectAuth extends EVMAuthenticator {
private _debouncedPrepareTokenConfigResolver: ((value: unknown) => void) | null;
private web3Modal: Web3Modal;
private unsubscribeWeb3Modal: null | (() => void) = null;
private usingQR = false;

options: Web3ModalConfig;
wagmiClient: EthereumClient;
Expand Down Expand Up @@ -78,6 +79,20 @@ export class WalletConnectAuth extends EVMAuthenticator {
this.clearAuthenticator();
const address = getAccount().address as addressString;

// We are successfully logged in. Let's find out if we are using QR
this.usingQR = false;
const injected = new InjectedConnector();
const provider = toRaw(await injected.getProvider());
if (typeof provider === 'undefined') {
this.usingQR = true;
} else {
const providerAddress = (provider._state?.accounts) ? provider._state?.accounts[0] : '';
const sameAddress = providerAddress === address;
this.usingQR = !sameAddress;
this.trace('walletConnectLogin', 'providerAddress:', providerAddress, 'address:', address, 'sameAddress:', sameAddress);
}
this.trace('walletConnectLogin', 'using QR:', this.usingQR);

// We are already logged in. Now let's try to force the wallet to connect to the correct network
try {
if (!usePlatformStore().isMobile) {
Expand Down Expand Up @@ -149,7 +164,7 @@ export class WalletConnectAuth extends EVMAuthenticator {
this.trace('login', 'web3Modal.openModal()');

this.unsubscribeWeb3Modal = this.web3Modal.subscribeModal(async (newState) => {
this.trace('login', 'web3Modal.subscribeModal ', newState, wagmiConnected);
this.trace('login', 'web3Modal.subscribeModal ', toRaw(newState), wagmiConnected);

if (newState.open === true) {
this.trace(
Expand Down Expand Up @@ -198,6 +213,8 @@ export class WalletConnectAuth extends EVMAuthenticator {
// having this two properties attached to the authenticator instance may bring some problems
// so after we use them we nned to clear them to avoid that problems
clearAuthenticator(): void {
this.trace('clearAuthenticator');
this.usingQR = false;
this.options = null as unknown as Web3ModalConfig;
this.wagmiClient = null as unknown as EthereumClient;
}
Expand Down Expand Up @@ -354,11 +371,17 @@ export class WalletConnectAuth extends EVMAuthenticator {

async web3Provider(): Promise<ethers.providers.Web3Provider> {
let web3Provider = null;
if (usePlatformStore().isMobile) {
if (usePlatformStore().isMobile || this.usingQR) {
const p:RpcEndpoint = (useChainStore().getChain(this.label).settings as EVMChainSettings).getRPCEndpoint();
const url = `${p.protocol}://${p.host}:${p.port}${p.path ?? ''}`;
web3Provider = new ethers.providers.JsonRpcProvider(url);
this.trace('web3Provider', 'JsonRpcProvider ->', web3Provider);

// This is a hack to make the QR code work.
// this code is going to be used in EVMAuthenticator.ts login method
const listAccounts: () => Promise<`0x${string}`[]> = async () => [getAccount().address as addressString];
web3Provider.listAccounts = listAccounts;

} else {
web3Provider = new ethers.providers.Web3Provider(await this.externalProvider());
this.trace('web3Provider', 'Web3Provider ->', web3Provider);
Expand Down Expand Up @@ -387,4 +410,14 @@ export class WalletConnectAuth extends EVMAuthenticator {
});
}

async ensureCorrectChain(): Promise<ethers.providers.Web3Provider> {
this.trace('ensureCorrectChain', 'QR:', this.usingQR);
if (this.usingQR) {
// we don't have tools to check the chain when using QR
return this.web3Provider();
} else {
return super.ensureCorrectChain();
}
}

}

0 comments on commit caea7e2

Please sign in to comment.