Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ethers.js example #91

Open
okwme opened this issue Aug 27, 2024 · 1 comment
Open

ethers.js example #91

okwme opened this issue Aug 27, 2024 · 1 comment

Comments

@okwme
Copy link

okwme commented Aug 27, 2024

ended up making an example gist resolving basenames using ethers.js since the docs only reference viem and onchainkit. Not sure how the base docs are managed but someone might come to this repo with the same problem so thought I'd leave a link:

https://gist.github.com/okwme/dde885bced64c92473639a8d2722883c

import { Contract, utils } from 'ethers'
import { getProvider } from './contracts' // https://docs.ethers.org/v5/api/providers/
import L2ResolverAbi from './L2ResolverAbi.json' // https://gist.github.com/hughescoin/adf1c90b67cd9b2b913b984a2cc98de9
const BASENAME_L2_RESOLVER_ADDRESS = '0xC6d566A56A1aFf6508b41f6c90ff131615583BCD'

const convertChainIdToCoinType = (chainId) => {
  // L1 resolvers to addr
  if (chainId === 1) { // 1 is mainnet chain id
    return 'addr'
  }
  const cointype = (0x80000000 | chainId) >>> 0
  return cointype.toString(16).toLocaleUpperCase()
}
const convertReverseNodeToBytes = (address, chainId) => {
  const addressFormatted = address.toLowerCase()
  const addressNode = utils.solidityKeccak256(['string'], [addressFormatted.substring(2)]) // NOTE: hash it as a string not address
  const chainCoinType = convertChainIdToCoinType(chainId)
  const baseReverseNode = utils.namehash(`${chainCoinType.toLocaleUpperCase()}.reverse`)
  const addressReverseNode = utils.solidityKeccak256(
    ['bytes32', 'bytes32'],
    [baseReverseNode, addressNode]
  )
  return addressReverseNode
}

export const getBaseName = async (address) => {
  try {
    const addressReverseNode = convertReverseNodeToBytes(address, 8453) // 8453 is base chain id
    const baseProvider = await getProvider()
    const contract = new Contract(BASENAME_L2_RESOLVER_ADDRESS, L2ResolverAbi, baseProvider)
    const basename = await contract.name(addressReverseNode)
    return basename
  } catch (e) {
    console.error('Error getting basename', e)
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@okwme and others