2023-01-10 10:37:45 +00:00
|
|
|
import { toUtf8 } from '@cosmjs/encoding'
|
2023-10-11 23:36:14 +00:00
|
|
|
import type { ChainContext } from '@cosmos-kit/core'
|
2023-01-10 10:37:45 +00:00
|
|
|
import toast from 'react-hot-toast'
|
|
|
|
|
|
|
|
import { SG721_NAME_ADDRESS } from './constants'
|
|
|
|
import { isValidAddress } from './isValidAddress'
|
|
|
|
|
2023-10-11 23:36:14 +00:00
|
|
|
export const resolveAddress = async (name: string, wallet: ChainContext): Promise<string> => {
|
2023-01-12 08:45:57 +00:00
|
|
|
if (!name.trim().endsWith('.stars')) return name.trim()
|
2023-01-10 10:37:45 +00:00
|
|
|
|
2023-10-11 23:36:14 +00:00
|
|
|
if (wallet.isWalletConnected) {
|
|
|
|
const tokenUri = await (
|
|
|
|
await wallet.getCosmWasmClient()
|
|
|
|
)
|
2023-01-10 10:37:45 +00:00
|
|
|
.queryContractRaw(
|
|
|
|
SG721_NAME_ADDRESS,
|
|
|
|
toUtf8(
|
|
|
|
Buffer.from(
|
|
|
|
`0006${Buffer.from('tokens').toString('hex')}${Buffer.from(
|
2023-01-12 08:45:57 +00:00
|
|
|
name.trim().substring(0, name.trim().lastIndexOf('.')),
|
2023-01-10 10:37:45 +00:00
|
|
|
).toString('hex')}`,
|
|
|
|
'hex',
|
|
|
|
).toString(),
|
|
|
|
),
|
|
|
|
)
|
|
|
|
.then((res) => {
|
|
|
|
const parsedTokenUri = JSON.parse(new TextDecoder().decode(res as Uint8Array)).token_uri
|
|
|
|
console.log(parsedTokenUri)
|
|
|
|
if (parsedTokenUri && isValidAddress(parsedTokenUri)) return parsedTokenUri as string
|
2023-01-12 08:45:57 +00:00
|
|
|
toast.error(`Resolved address is empty or invalid for the name: ${name.trim()}`)
|
2023-01-10 10:37:45 +00:00
|
|
|
return name
|
|
|
|
})
|
|
|
|
.catch((e) => {
|
|
|
|
console.log(e)
|
2023-01-12 08:45:57 +00:00
|
|
|
toast.error(`Error resolving address for the name: ${name.trim()}`)
|
2023-01-10 10:37:45 +00:00
|
|
|
return name
|
|
|
|
})
|
|
|
|
return tokenUri
|
|
|
|
}
|
|
|
|
toast.error('Wallet is not connected. Unable to resolve address.')
|
|
|
|
return name
|
|
|
|
}
|