import BN from 'bn.js' ; export interface EthereumProvider { send ( method , params ) : Promise < string > ; send ( method , params ) : Promise < string > ; send ( method , params ) : Promise < string > ; send ( method , params ) : Promise < string > ; send ( method , params ) : Promise < string > ; send ( method , params ) : Promise < string > ; send ( method , params ) : Promise < null | EthereumTransaction > ; send ( method , params ) : Promise < null | EthereumTransactionReceipt > ; send ( method , params ) : Promise < unknown > ; } interface EthereumTransaction { blockHash : string | null ; } interface EthereumTransactionReceipt { status : string ; to : string | null ; from : string ; blockHash : string ; blockNumber : string ; transactionHash : string ; transactionIndex : string ; } export async function getNetworkId ( provider ) { return provider . send ( 'net_version' , [ ] ) ; } export async function getChainId ( provider ) { const id = await provider . send ( 'eth_chainId' , [ ] ) ; return new BN ( id . replace ( /^0x/ , '' ) , 'hex' ) . toNumber ( ) ; } export async function getClientVersion ( provider ) { return provider . send ( 'web3_clientVersion' , [ ] ) ; } export async function getStorageAt ( provider , address , position , block = 'latest' ) { const storage = await provider . send ( 'eth_getStorageAt' , [ address , position , block ] ) ; const padded = storage . replace ( /^0x/ , '' ) . padStart ( 64 , '0' ) ; return '0x' + padded ; } export async function getCode ( provider , address , block = 'latest' ) { return provider . send ( 'eth_getCode' , [ address , block ] ) ; } export async function call ( provider , address , data , block = 'latest' ) { return provider . send ( 'eth_call' , [ { to : address , data : data , } , block , ] ) ; } export async function hasCode ( provider , address , block ? ) { const code = await getCode ( provider , address , block ) ; return code !== '0x' ; } export async function getTransactionByHash ( provider , txHash ) { return provider . send ( 'eth_getTransactionByHash' , [ txHash ] ) ; } export async function getTransactionReceipt ( provider , txHash ) { const receipt = await provider . send ( 'eth_getTransactionReceipt' , [ txHash ] ) ; if ( receipt ?. status ) { receipt . status = receipt . status . match ( /^0x0+$/ ) ? '0x0' : receipt . status . replace ( /^0x0+/ , '0x' ) ; } return receipt ; } export const networkNames = Object . freeze ( { 1 : 'mainnet' , 2 : 'morden' , 3 : 'ropsten' , 4 : 'rinkeby' , 5 : 'goerli' , 42 : 'kovan' , } ) ; export async function isDevelopmentNetwork ( provider ) { const chainId = await getChainId ( provider ) ; if ( chainId === 1337 || chainId === 31337 ) { return true ; } else { const clientVersion = await getClientVersion ( provider ) ; const [ name ] = clientVersion . split ( '/' , 1 ) ; return name === 'HardhatNetwork' || name === 'EthereumJS TestRPC' ; } } export function isReceiptSuccessful ( receipt ) { return receipt . status === '0x1' ; }