@web3auth/web3auth-wagmi-connector
Version:
wagmi connector to connect with web3auth SDK
169 lines (166 loc) • 6.46 kB
JavaScript
import { createConnector, ChainNotConfiguredError } from '@wagmi/core';
import * as pkg from '@web3auth/base';
import { UserRejectedRequestError, getAddress, SwitchChainError } from 'viem';
const {
ADAPTER_STATUS,
CHAIN_NAMESPACES,
WALLET_ADAPTERS,
log
} = pkg;
function isIWeb3AuthModal(obj) {
return typeof obj.initModal !== "undefined";
}
function Web3AuthConnector(parameters) {
let walletProvider = null;
const {
web3AuthInstance,
loginParams,
modalConfig,
id,
name,
type
} = parameters;
return createConnector(config => ({
id: id || "web3auth",
name: name || "Web3Auth",
type: type || "Web3Auth",
async connect({
chainId
} = {}) {
try {
config.emitter.emit("message", {
type: "connecting"
});
const provider = await this.getProvider();
provider.on("accountsChanged", this.onAccountsChanged);
provider.on("chainChanged", this.onChainChanged);
provider.on("disconnect", this.onDisconnect.bind(this));
if (!web3AuthInstance.connected) {
if (isIWeb3AuthModal(web3AuthInstance)) {
await web3AuthInstance.connect();
} else if (loginParams) {
await web3AuthInstance.connectTo(WALLET_ADAPTERS.AUTH, loginParams);
} else {
log.error("please provide valid loginParams when using @web3auth/no-modal");
throw new UserRejectedRequestError("please provide valid loginParams when using @web3auth/no-modal");
}
}
let currentChainId = await this.getChainId();
if (chainId && currentChainId !== chainId) {
var _chain$id;
const chain = await this.switchChain({
chainId
}).catch(error => {
if (error.code === UserRejectedRequestError.code) throw error;
return {
id: currentChainId
};
});
currentChainId = (_chain$id = chain === null || chain === void 0 ? void 0 : chain.id) !== null && _chain$id !== void 0 ? _chain$id : currentChainId;
}
const accounts = await this.getAccounts();
return {
accounts,
chainId: currentChainId
};
} catch (error) {
log.error("error while connecting", error);
this.onDisconnect();
throw new UserRejectedRequestError("Something went wrong");
}
},
async getAccounts() {
const provider = await this.getProvider();
return (await provider.request({
method: "eth_accounts"
})).map(x => getAddress(x));
},
async getChainId() {
const provider = await this.getProvider();
const chainId = await provider.request({
method: "eth_chainId"
});
return Number(chainId);
},
async getProvider() {
if (walletProvider) {
return walletProvider;
}
if (web3AuthInstance.status === ADAPTER_STATUS.NOT_READY) {
if (isIWeb3AuthModal(web3AuthInstance)) {
await web3AuthInstance.initModal({
modalConfig
});
} else if (loginParams) {
await web3AuthInstance.init();
} else {
log.error("please provide valid loginParams when using @web3auth/no-modal");
throw new UserRejectedRequestError("please provide valid loginParams when using @web3auth/no-modal");
}
}
walletProvider = web3AuthInstance.provider;
return walletProvider;
},
async isAuthorized() {
try {
const accounts = await this.getAccounts();
return !!accounts.length;
} catch {
return false;
}
},
async switchChain({
chainId
}) {
try {
var _chain$blockExplorers, _chain$nativeCurrency, _chain$nativeCurrency2, _chain$nativeCurrency3, _chain$nativeCurrency4, _chain$nativeCurrency5;
const chain = config.chains.find(x => x.id === chainId);
if (!chain) throw new SwitchChainError(new ChainNotConfiguredError());
await web3AuthInstance.addChain({
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: `0x${chain.id.toString(16)}`,
rpcTarget: chain.rpcUrls.default.http[0],
displayName: chain.name,
blockExplorerUrl: ((_chain$blockExplorers = chain.blockExplorers) === null || _chain$blockExplorers === void 0 ? void 0 : _chain$blockExplorers.default.url) || "",
ticker: ((_chain$nativeCurrency = chain.nativeCurrency) === null || _chain$nativeCurrency === void 0 ? void 0 : _chain$nativeCurrency.symbol) || "ETH",
tickerName: ((_chain$nativeCurrency2 = chain.nativeCurrency) === null || _chain$nativeCurrency2 === void 0 ? void 0 : _chain$nativeCurrency2.name) || "Ethereum",
decimals: ((_chain$nativeCurrency3 = chain.nativeCurrency) === null || _chain$nativeCurrency3 === void 0 ? void 0 : _chain$nativeCurrency3.decimals) || 18,
logo: (_chain$nativeCurrency4 = chain.nativeCurrency) !== null && _chain$nativeCurrency4 !== void 0 && _chain$nativeCurrency4.symbol ? `https://images.toruswallet.io/${(_chain$nativeCurrency5 = chain.nativeCurrency) === null || _chain$nativeCurrency5 === void 0 ? void 0 : _chain$nativeCurrency5.symbol.toLowerCase()}.svg` : "https://images.toruswallet.io/eth.svg"
});
log.info("Chain Added: ", chain.name);
await web3AuthInstance.switchChain({
chainId: `0x${chain.id.toString(16)}`
});
log.info("Chain Switched to ", chain.name);
config.emitter.emit("change", {
chainId
});
return chain;
} catch (error) {
log.error("Error: Cannot change chain", error);
throw new SwitchChainError(error);
}
},
async disconnect() {
await web3AuthInstance.logout();
const provider = await this.getProvider();
provider.removeListener("accountsChanged", this.onAccountsChanged);
provider.removeListener("chainChanged", this.onChainChanged);
},
onAccountsChanged(accounts) {
if (accounts.length === 0) config.emitter.emit("disconnect");else config.emitter.emit("change", {
accounts: accounts.map(x => getAddress(x))
});
},
onChainChanged(chain) {
const chainId = Number(chain);
config.emitter.emit("change", {
chainId
});
},
onDisconnect() {
config.emitter.emit("disconnect");
}
}));
}
export { Web3AuthConnector };