import Web3 from 'web3'
import { CHAIN_IDS_OPTS, IChain, IContract } from '../../'

export const CHAIN_IDS = (index: IChain): number => {
	return CHAIN_IDS_OPTS[index]
}

export const makeSureChainMatchesContract = async (contract: IContract) => {
	return makeSureChainMatches(contract.recipe.chain)
}

export const makeSureChainMatches = async (chain: IChain) => {
	const chainId = CHAIN_IDS(chain)
	try {
		if (typeof window !== 'undefined') {
			await (window as unknown as any).ethereum.request({
				method: 'wallet_switchEthereumChain',
				params: [{ chainId: Web3.utils.toHex(chainId) }],
			})
		}
	} catch (err) {
		console.error(err)
		throw new Error(
			'Contract Tool Error: Could not switch to chain ' + chainId,
		)
	}
}
