import { LCDClient } from "@terra-money/terra.js" ; import { Buffer } from "buffer" ; import keccak256 from "keccak256" ; import { useCurrentChain } from "../contexts/ChainsContext" ; import useLCDClient from "../hooks/useLCD" ; const registryMap = { mainnet : "terra19gqw63xnt9237d2s8cdrzstn98g98y7hkl80gs" , testnet : "terra1fmmced3dms3ha2st4y2qj8w5v2zyel7xpg8wpq" } ; export const useTns = ( ) => { const { name } = useCurrentChain ( ) ; const lcd = useLCDClient ( ) ; const registryAddress = registryMap [ name ] ; return { getTerraAddress : ( name ) => getTerraAddress ( lcd , registryAddress , name ) } ; } ; param name returns export const isTnsName = ( name ) => { const baseNames = [ "ust" ] ; return baseNames . some ( baseName => { const dotBaseName = "." + baseName ; return ( ! name . startsWith ( "." ) && ! name . includes ( ".." ) && name . endsWith ( dotBaseName ) ) ; } ) ; } ; param name returns const getTerraAddress = async ( lcd , registryAddress , name ) => { const resolverAddress = await getResolverAddress ( lcd , registryAddress , name ) ; if ( ! resolverAddress ) return null ; const result = await lcd . wasm . contractQuery < { address : string ; } > ( resolverAddress , { get_terra_address : { node : node ( name ) } } ) . catch ( ( ) => null ) ; return result ?. address ?? null ; } ; param name returns const getResolverAddress = async ( lcd , registryAddress , name ) => { const result = await lcd . wasm . contractQuery < { resolver : string ; } > ( registryAddress , { get_record : { name } } ) . catch ( ( ) => null ) ; return result ?. resolver ?? null ; } ; param name returns The result of namehash function in a  Buffer form
  const namehash = ( name ) : Buffer => { if ( name ) { const [ label , remainder ] = name . split ( "." ) ; return keccak256 ( Buffer . concat ( [ namehash ( remainder ) , keccak256 ( label ) ] ) ) ; } return Buffer . from ( "" . padStart ( 64 , "0" ) , "hex" ) ; } ; param name returns const node = ( name ) => { return Array . from ( Uint8Array . from ( namehash ( name ) ) ) ; } ;