UNPKG

@sky-mavis/tanto-connect

Version:
90 lines (86 loc) 3.32 kB
'use strict'; var connectors = require('../../common/connectors.cjs'); require('../../common/constant.cjs'); require('../../types/eip6963.cjs'); var connectorError = require('../../types/connector-error.cjs'); require('@walletconnect/ethereum-provider'); var safeProvider = require('../../providers/safe-provider.cjs'); require('@sky-mavis/waypoint'); require('../../common/chain.cjs'); var eip1193 = require('../../types/eip1193.cjs'); var BaseConnector = require('../base/BaseConnector.cjs'); class SafeConnector extends BaseConnector.BaseConnector { constructor(configs, provider) { super({ ...connectors.DEFAULT_CONNECTORS_CONFIG.SAFE, ...configs }, provider); } async connect() { const provider = await this.getProvider(); if (!provider) { throw new connectorError.ConnectorError(connectorError.ConnectorErrorType.PROVIDER_NOT_FOUND); } const accounts = await this.getAccounts(); const chainId = await this.getChainId(); if (accounts?.length && !!chainId) { const connectResults = { provider, chainId, account: accounts[0], }; this.setupProviderListeners(); this.onConnect(connectResults); return connectResults; } throw new connectorError.ConnectorError(connectorError.ConnectorErrorType.CONNECT_FAILED); } async disconnect() { this.onDisconnect(); this.removeProviderListeners(); } async isAuthorized() { const accounts = await this.getAccounts(); return accounts.length > 0; } async getAccounts() { const provider = await this.getProvider(); return provider?.request({ method: 'eth_accounts', }); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async switchChain(chain) { throw new connectorError.ConnectorError(connectorError.ConnectorErrorType.SWITCH_CHAIN_NOT_SUPPORTED); } async getChainId() { const provider = await this.getProvider(); const chainId = await provider?.request({ method: 'eth_chainId', }); return Number(chainId); } async requestAccounts() { const provider = await this.getProvider(); return provider?.request({ method: 'eth_requestAccounts', }); } async addChain() { throw new connectorError.ConnectorError(connectorError.ConnectorErrorType.ADD_CHAIN_NOT_SUPPORTED); } async requestProvider() { return await safeProvider.requestSafeProvider(); } setupProviderListeners() { this.removeProviderListeners(); if (this.provider) { this.provider.on(eip1193.EIP1193Event.DISCONNECT, this.onDisconnect); this.provider.on(eip1193.EIP1193Event.ACCOUNTS_CHANGED, this.onAccountsChanged); } } removeProviderListeners() { if (this.provider) { this.provider.removeListener(eip1193.EIP1193Event.DISCONNECT, this.onDisconnect); this.provider.removeListener(eip1193.EIP1193Event.ACCOUNTS_CHANGED, this.onAccountsChanged); } } } exports.SafeConnector = SafeConnector;