import type { Coin } from '@cosmjs/proto-signing' import type { logs } from '@cosmjs/stargate' import { useCallback, useEffect, useState } from 'react' import { useWallet } from 'utils/wallet' import type { BaseMinterContract, BaseMinterInstance, BaseMinterMessages, MigrateResponse } from './contract' import { baseMinter as initContract } from './contract' interface InstantiateResponse { readonly contractAddress: string readonly transactionHash: string readonly logs: readonly logs.Log[] } export interface UseBaseMinterContractProps { instantiate: ( codeId: number, initMsg: Record, label: string, admin?: string, funds?: Coin[], ) => Promise migrate: (contractAddress: string, codeId: number, migrateMsg: Record) => Promise use: (customAddress: string) => BaseMinterInstance | undefined updateContractAddress: (contractAddress: string) => void getContractAddress: () => string | undefined messages: (contractAddress: string) => BaseMinterMessages | undefined } export function useBaseMinterContract(): UseBaseMinterContractProps { const wallet = useWallet() const [address, setAddress] = useState('') const [baseMinter, setBaseMinter] = useState() useEffect(() => { setAddress(localStorage.getItem('contract_address') || '') }, []) useEffect(() => { if (!wallet.isWalletConnected) { return } const load = async () => { const client = await wallet.getSigningCosmWasmClient() const BaseMinterBaseContract = initContract(client, wallet.address || '') setBaseMinter(BaseMinterBaseContract) } load().catch(console.error) // eslint-disable-next-line react-hooks/exhaustive-deps }, [wallet.isWalletConnected, wallet.address]) const updateContractAddress = (contractAddress: string) => { setAddress(contractAddress) } const instantiate = useCallback( (codeId: number, initMsg: Record, label: string, admin?: string): Promise => { return new Promise((resolve, reject) => { if (!baseMinter) { reject(new Error('Contract is not initialized.')) return } baseMinter .instantiate(wallet.address || '', codeId, initMsg, label, admin) .then(resolve) .catch(reject) }) }, [baseMinter, wallet], ) const migrate = useCallback( (contractAddress: string, codeId: number, migrateMsg: Record): Promise => { return new Promise((resolve, reject) => { if (!baseMinter) { reject(new Error('Contract is not initialized.')) return } console.log(wallet.address, contractAddress, codeId) baseMinter .migrate(wallet.address || '', contractAddress, codeId, migrateMsg) .then(resolve) .catch(reject) }) }, [baseMinter, wallet], ) const use = useCallback( (customAddress = ''): BaseMinterInstance | undefined => { return baseMinter?.use(address || customAddress) }, [baseMinter, address], ) const getContractAddress = (): string | undefined => { return address } const messages = useCallback( (customAddress = ''): BaseMinterMessages | undefined => { return baseMinter?.messages(address || customAddress) }, [baseMinter, address], ) return { instantiate, use, updateContractAddress, getContractAddress, messages, migrate, } }