CNS SDK
Install
yarn add @cnsdomains/core
Initialize SDK
import ethers from 'ethers'
import { CNS, CronosTestnet } from '@cnsdomains/core'
// get the provider
const provider = new ethers.providers.JsonRpcProvider(CronosTestnet.rpcUrls[0])
// initialize the cns sdk
const cns = new CNS(CronosTestnet.chainId, provider)
Get Profile
From User Address
const address = '0x8eC623a26182E342AcB4a6F7414d3bbE6b02F748'
// 3 RPC calls, one to fetch resolver address, other reverse record and multicall for records
const profile = await cns.getProfile(address)
// More than 3 calls, if avatar is NFT image
const profileAll = await cns.getProfile(address, {
referral: true,
avatar: true,
banner: true,
})
From CNS Name
const name = 'john.cro'
const profile = await cns.getProfile(name)
const profileAll = await cns.getProfile(name, {
referral: true,
avatar: true,
banner: true,
})
See [[CNS.getProfile]] and [[CNSProfile]]
Reverse Record For Multiple Address
// initialize the cns sdk
const cns = new CNS(CronosTestnet.chainId, provider)
const addresses = [
'0x8eC623a26182E342AcB4a6F7414d3bbE6b02F748',
'0x8eC623a26182E342AcB4a6F7414d3bbE6b02F748',
'0x8eC623a26182E342AcB4a6F7414d3bbE6b02F748',
]
const names = await cns.getNames(addresses)
For React Apps
useCNS()
hook
Internally, we use useCNS
hook to initialize sdk, here is the trim down version of that,
import { CNS } from '@cnsdomains/core'
export function useCNS() {
// get the provider and chainId
// `useWeb3React` is from web3-react v8
const { provider, chainId } = useWeb3React()
return useMemo(() => {
return provider && chainId ? new CNS(chainId, provider) : undefined
}, [provider, chainId])
}
Show User's Name instead of their Address
function User() {
// get user address
const [cnsProfile, cnsProfile] = useState()
const { account } = useWeb3React()
const cns = useCNS()
useEffect(() => {
cns.getProfile(account).then((p) => setPrimaryCNS(p))
}, [account])
return account ? (
<div>{cnsProfile.primaryCNS ?? shortenAddress(account)}</div>
) : null
}