Init badge-hub contract helpers

This commit is contained in:
Serkan Reis 2023-01-31 20:31:06 +03:00
parent af3aba109b
commit c6b503f01a
5 changed files with 1188 additions and 0 deletions

View File

@ -0,0 +1,809 @@
import type { MsgExecuteContractEncodeObject, SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate'
import { toUtf8 } from '@cosmjs/encoding'
import type { Coin } from '@cosmjs/proto-signing'
import { coin } from '@cosmjs/proto-signing'
import type { logs } from '@cosmjs/stargate'
import type { Timestamp } from '@stargazezone/types/contracts/minter/shared-types'
import { MsgExecuteContract } from 'cosmjs-types/cosmwasm/wasm/v1/tx'
export interface InstantiateResponse {
readonly contractAddress: string
readonly transactionHash: string
readonly logs: readonly logs.Log[]
}
export interface MigrateResponse {
readonly transactionHash: string
readonly logs: readonly logs.Log[]
}
export interface BadgeHubInstance {
readonly contractAddress: string
//Query
getConfig: () => Promise<any>
getMintableNumTokens: () => Promise<any>
getStartTime: () => Promise<any>
getMintPrice: () => Promise<any>
getMintCount: (address: string) => Promise<any>
//Execute
mint: (senderAddress: string) => Promise<string>
purge: (senderAddress: string) => Promise<string>
updateMintPrice: (senderAddress: string, price: string) => Promise<string>
setWhitelist: (senderAddress: string, whitelist: string) => Promise<string>
updateStartTime: (senderAddress: string, time: Timestamp) => Promise<string>
updateStartTradingTime: (senderAddress: string, time?: Timestamp) => Promise<string>
updatePerAddressLimit: (senderAddress: string, perAddressLimit: number) => Promise<string>
mintTo: (senderAddress: string, recipient: string) => Promise<string>
mintFor: (senderAddress: string, recipient: string, tokenId: number) => Promise<string>
batchMintFor: (senderAddress: string, recipient: string, tokenIds: string) => Promise<string>
batchMint: (senderAddress: string, recipient: string, batchNumber: number) => Promise<string>
shuffle: (senderAddress: string) => Promise<string>
withdraw: (senderAddress: string) => Promise<string>
airdrop: (senderAddress: string, recipients: string[]) => Promise<string>
burnRemaining: (senderAddress: string) => Promise<string>
}
export interface BadgeHubMessages {
mint: () => MintMessage
purge: () => PurgeMessage
updateMintPrice: (price: string) => UpdateMintPriceMessage
setWhitelist: (whitelist: string) => SetWhitelistMessage
updateStartTime: (time: Timestamp) => UpdateStartTimeMessage
updateStartTradingTime: (time: Timestamp) => UpdateStartTradingTimeMessage
updatePerAddressLimit: (perAddressLimit: number) => UpdatePerAddressLimitMessage
mintTo: (recipient: string) => MintToMessage
mintFor: (recipient: string, tokenId: number) => MintForMessage
batchMintFor: (recipient: string, tokenIds: string) => BatchMintForMessage
batchMint: (recipient: string, batchNumber: number) => CustomMessage
shuffle: () => ShuffleMessage
withdraw: () => WithdrawMessage
airdrop: (recipients: string[]) => CustomMessage
burnRemaining: () => BurnRemainingMessage
}
export interface MintMessage {
sender: string
contract: string
msg: {
mint: Record<string, never>
}
funds: Coin[]
}
export interface PurgeMessage {
sender: string
contract: string
msg: {
purge: Record<string, never>
}
funds: Coin[]
}
export interface UpdateMintPriceMessage {
sender: string
contract: string
msg: {
update_mint_price: {
price: string
}
}
funds: Coin[]
}
export interface SetWhitelistMessage {
sender: string
contract: string
msg: {
set_whitelist: {
whitelist: string
}
}
funds: Coin[]
}
export interface UpdateStartTimeMessage {
sender: string
contract: string
msg: {
update_start_time: string
}
funds: Coin[]
}
export interface UpdateStartTradingTimeMessage {
sender: string
contract: string
msg: {
update_start_trading_time: string
}
funds: Coin[]
}
export interface UpdatePerAddressLimitMessage {
sender: string
contract: string
msg: {
update_per_address_limit: {
per_address_limit: number
}
}
funds: Coin[]
}
export interface MintToMessage {
sender: string
contract: string
msg: {
mint_to: {
recipient: string
}
}
funds: Coin[]
}
export interface MintForMessage {
sender: string
contract: string
msg: {
mint_for: {
recipient: string
token_id: number
}
}
funds: Coin[]
}
export interface BatchMintForMessage {
sender: string
contract: string
msg: Record<string, unknown>[]
funds: Coin[]
}
export interface CustomMessage {
sender: string
contract: string
msg: Record<string, unknown>[]
funds: Coin[]
}
export interface ShuffleMessage {
sender: string
contract: string
msg: {
shuffle: Record<string, never>
}
funds: Coin[]
}
export interface WithdrawMessage {
sender: string
contract: string
msg: {
withdraw: Record<string, never>
}
funds: Coin[]
}
export interface BurnRemainingMessage {
sender: string
contract: string
msg: {
burn_remaining: Record<string, never>
}
funds: Coin[]
}
export interface MintPriceMessage {
public_price: {
denom: string
amount: string
}
airdrop_price: {
denom: string
amount: string
}
whitelist_price?: {
denom: string
amount: string
}
current_price: {
denom: string
amount: string
}
}
export interface BadgeHubContract {
instantiate: (
senderAddress: string,
codeId: number,
initMsg: Record<string, unknown>,
label: string,
admin?: string,
funds?: Coin[],
) => Promise<InstantiateResponse>
migrate: (
senderAddress: string,
contractAddress: string,
codeId: number,
migrateMsg: Record<string, unknown>,
) => Promise<MigrateResponse>
use: (contractAddress: string) => BadgeHubInstance
messages: (contractAddress: string) => BadgeHubMessages
}
export const badgeHub = (client: SigningCosmWasmClient, txSigner: string): BadgeHubContract => {
const use = (contractAddress: string): BadgeHubInstance => {
//Query
const getConfig = async (): Promise<any> => {
const res = await client.queryContractSmart(contractAddress, {
config: {},
})
return res
}
const getMintableNumTokens = async (): Promise<any> => {
const res = await client.queryContractSmart(contractAddress, {
mintable_num_tokens: {},
})
return res
}
const getStartTime = async (): Promise<any> => {
const res = await client.queryContractSmart(contractAddress, {
start_time: {},
})
return res
}
const getMintPrice = async (): Promise<MintPriceMessage> => {
const res = await client.queryContractSmart(contractAddress, {
mint_price: {},
})
return res
}
const getMintCount = async (address: string): Promise<any> => {
const res = await client.queryContractSmart(contractAddress, {
mint_count: { address },
})
return res
}
//Execute
const mint = async (senderAddress: string): Promise<string> => {
const price = (await getMintPrice()).public_price.amount
const res = await client.execute(
senderAddress,
contractAddress,
{
mint: {},
},
'auto',
'',
[coin(price, 'ustars')],
)
return res.transactionHash
}
const purge = async (senderAddress: string): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
purge: {},
},
'auto',
'',
)
return res.transactionHash
}
const updateMintPrice = async (senderAddress: string, price: string): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
update_mint_price: {
price: (Number(price) * 1000000).toString(),
},
},
'auto',
'',
)
return res.transactionHash
}
const setWhitelist = async (senderAddress: string, whitelist: string): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
set_whitelist: { whitelist },
},
'auto',
'',
)
return res.transactionHash
}
const updateStartTime = async (senderAddress: string, time: Timestamp): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
update_start_time: time,
},
'auto',
'',
)
return res.transactionHash
}
const updateStartTradingTime = async (senderAddress: string, time?: Timestamp): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
update_start_trading_time: time || null,
},
'auto',
'',
)
return res.transactionHash
}
const updatePerAddressLimit = async (senderAddress: string, perAddressLimit: number): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
update_per_address_limit: { per_address_limit: perAddressLimit },
},
'auto',
'',
)
return res.transactionHash
}
const mintTo = async (senderAddress: string, recipient: string): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
mint_to: { recipient },
},
'auto',
'',
)
return res.transactionHash
}
const mintFor = async (senderAddress: string, recipient: string, tokenId: number): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
mint_for: { token_id: tokenId, recipient },
},
'auto',
'',
)
return res.transactionHash
}
const batchMintFor = async (senderAddress: string, recipient: string, tokenIds: string): Promise<string> => {
const executeContractMsgs: MsgExecuteContractEncodeObject[] = []
if (tokenIds.includes(':')) {
const [start, end] = tokenIds.split(':').map(Number)
for (let i = start; i <= end; i++) {
const msg = {
mint_for: { token_id: i, recipient },
}
const executeContractMsg: MsgExecuteContractEncodeObject = {
typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
value: MsgExecuteContract.fromPartial({
sender: txSigner,
contract: contractAddress,
msg: toUtf8(JSON.stringify(msg)),
}),
}
executeContractMsgs.push(executeContractMsg)
}
} else {
const tokenNumbers = tokenIds.split(',').map(Number)
for (let i = 0; i < tokenNumbers.length; i++) {
const msg = {
mint_for: { token_id: tokenNumbers[i], recipient },
}
const executeContractMsg: MsgExecuteContractEncodeObject = {
typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
value: MsgExecuteContract.fromPartial({
sender: txSigner,
contract: contractAddress,
msg: toUtf8(JSON.stringify(msg)),
}),
}
executeContractMsgs.push(executeContractMsg)
}
}
const res = await client.signAndBroadcast(txSigner, executeContractMsgs, 'auto', 'batch mint for')
return res.transactionHash
}
const batchMint = async (senderAddress: string, recipient: string, batchNumber: number): Promise<string> => {
const executeContractMsgs: MsgExecuteContractEncodeObject[] = []
for (let i = 0; i < batchNumber; i++) {
const msg = {
mint_to: { recipient },
}
const executeContractMsg: MsgExecuteContractEncodeObject = {
typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
value: MsgExecuteContract.fromPartial({
sender: senderAddress,
contract: contractAddress,
msg: toUtf8(JSON.stringify(msg)),
}),
}
executeContractMsgs.push(executeContractMsg)
}
const res = await client.signAndBroadcast(senderAddress, executeContractMsgs, 'auto', 'batch mint')
return res.transactionHash
}
const airdrop = async (senderAddress: string, recipients: string[]): Promise<string> => {
const executeContractMsgs: MsgExecuteContractEncodeObject[] = []
for (let i = 0; i < recipients.length; i++) {
const msg = {
mint_to: { recipient: recipients[i] },
}
const executeContractMsg: MsgExecuteContractEncodeObject = {
typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
value: MsgExecuteContract.fromPartial({
sender: senderAddress,
contract: contractAddress,
msg: toUtf8(JSON.stringify(msg)),
}),
}
executeContractMsgs.push(executeContractMsg)
}
const res = await client.signAndBroadcast(senderAddress, executeContractMsgs, 'auto', 'airdrop')
return res.transactionHash
}
const shuffle = async (senderAddress: string): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
shuffle: {},
},
'auto',
'',
[coin(500000000, 'ustars')],
)
return res.transactionHash
}
const withdraw = async (senderAddress: string): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
withdraw: {},
},
'auto',
'',
)
return res.transactionHash
}
const burnRemaining = async (senderAddress: string): Promise<string> => {
const res = await client.execute(
senderAddress,
contractAddress,
{
burn_remaining: {},
},
'auto',
'',
)
return res.transactionHash
}
return {
contractAddress,
getConfig,
getMintableNumTokens,
getStartTime,
getMintPrice,
getMintCount,
mint,
purge,
updateMintPrice,
setWhitelist,
updateStartTime,
updateStartTradingTime,
updatePerAddressLimit,
mintTo,
mintFor,
batchMintFor,
batchMint,
airdrop,
shuffle,
withdraw,
burnRemaining,
}
}
const migrate = async (
senderAddress: string,
contractAddress: string,
codeId: number,
migrateMsg: Record<string, unknown>,
): Promise<MigrateResponse> => {
const result = await client.migrate(senderAddress, contractAddress, codeId, migrateMsg, 'auto')
return {
transactionHash: result.transactionHash,
logs: result.logs,
}
}
const instantiate = async (
senderAddress: string,
codeId: number,
initMsg: Record<string, unknown>,
label: string,
): Promise<InstantiateResponse> => {
const result = await client.instantiate(senderAddress, codeId, initMsg, label, 'auto', {
funds: [coin('3000000000', 'ustars')],
})
return {
contractAddress: result.contractAddress,
transactionHash: result.transactionHash,
logs: result.logs,
}
}
const messages = (contractAddress: string) => {
const mint = (): MintMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
mint: {},
},
funds: [],
}
}
const purge = (): PurgeMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
purge: {},
},
funds: [],
}
}
const updateMintPrice = (price: string): UpdateMintPriceMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
update_mint_price: {
price: (Number(price) * 1000000).toString(),
},
},
funds: [],
}
}
const setWhitelist = (whitelist: string): SetWhitelistMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
set_whitelist: {
whitelist,
},
},
funds: [],
}
}
const updateStartTime = (startTime: string): UpdateStartTimeMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
update_start_time: startTime,
},
funds: [],
}
}
const updateStartTradingTime = (startTime: string): UpdateStartTradingTimeMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
update_start_trading_time: startTime,
},
funds: [],
}
}
const updatePerAddressLimit = (limit: number): UpdatePerAddressLimitMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
update_per_address_limit: {
per_address_limit: limit,
},
},
funds: [],
}
}
const mintTo = (recipient: string): MintToMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
mint_to: {
recipient,
},
},
funds: [],
}
}
const mintFor = (recipient: string, tokenId: number): MintForMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
mint_for: {
recipient,
token_id: tokenId,
},
},
funds: [],
}
}
const batchMintFor = (recipient: string, tokenIds: string): BatchMintForMessage => {
const msg: Record<string, unknown>[] = []
if (tokenIds.includes(':')) {
const [start, end] = tokenIds.split(':').map(Number)
for (let i = start; i <= end; i++) {
msg.push({
mint_for: { token_id: i.toString(), recipient },
})
}
} else {
const tokenNumbers = tokenIds.split(',').map(Number)
for (let i = 0; i < tokenNumbers.length; i++) {
msg.push({ mint_for: { token_id: tokenNumbers[i].toString(), recipient } })
}
}
return {
sender: txSigner,
contract: contractAddress,
msg,
funds: [],
}
}
const batchMint = (recipient: string, batchNumber: number): CustomMessage => {
const msg: Record<string, unknown>[] = []
for (let i = 0; i < batchNumber; i++) {
msg.push({ mint_to: { recipient } })
}
return {
sender: txSigner,
contract: contractAddress,
msg,
funds: [],
}
}
const airdrop = (recipients: string[]): CustomMessage => {
const msg: Record<string, unknown>[] = []
for (let i = 0; i < recipients.length; i++) {
msg.push({ mint_to: { recipient: recipients[i] } })
}
return {
sender: txSigner,
contract: contractAddress,
msg,
funds: [],
}
}
const shuffle = (): ShuffleMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
shuffle: {},
},
funds: [],
}
}
const withdraw = (): WithdrawMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
withdraw: {},
},
funds: [],
}
}
const burnRemaining = (): BurnRemainingMessage => {
return {
sender: txSigner,
contract: contractAddress,
msg: {
burn_remaining: {},
},
funds: [],
}
}
return {
mint,
purge,
updateMintPrice,
setWhitelist,
updateStartTime,
updateStartTradingTime,
updatePerAddressLimit,
mintTo,
mintFor,
batchMintFor,
batchMint,
airdrop,
shuffle,
withdraw,
burnRemaining,
}
}
return { use, instantiate, migrate, messages }
}

View File

@ -0,0 +1,2 @@
export * from './contract'
export * from './useContract'

View File

@ -0,0 +1,210 @@
import type { BadgeHubInstance } from '../index'
import { useBadgeHubContract } from '../index'
export type ExecuteType = typeof EXECUTE_TYPES[number]
export const EXECUTE_TYPES = [
'mint',
'purge',
'update_mint_price',
'set_whitelist',
'update_start_time',
'update_start_trading_time',
'update_per_address_limit',
'mint_to',
'mint_for',
'shuffle',
'withdraw',
'burn_remaining',
] as const
export interface ExecuteListItem {
id: ExecuteType
name: string
description?: string
}
export const EXECUTE_LIST: ExecuteListItem[] = [
{
id: 'mint',
name: 'Mint',
description: `Mint new tokens for a given address`,
},
{
id: 'purge',
name: 'Purge',
description: `Purge`,
},
{
id: 'update_mint_price',
name: 'Update Mint Price',
description: `Update mint price`,
},
{
id: 'set_whitelist',
name: 'Set Whitelist',
description: `Set whitelist contract address`,
},
{
id: 'update_start_time',
name: 'Update Start Time',
description: `Update start time for minting`,
},
{
id: 'update_start_trading_time',
name: 'Update Start Trading Time',
description: `Update start trading time for minting`,
},
{
id: 'update_per_address_limit',
name: 'Update Per Address Limit',
description: `Update token per address limit`,
},
{
id: 'mint_to',
name: 'Mint To',
description: `Mint tokens to a given address`,
},
{
id: 'mint_for',
name: 'Mint For',
description: `Mint tokens for a given address with a given token ID`,
},
{
id: 'shuffle',
name: 'Shuffle',
description: `Shuffle the token IDs`,
},
{
id: 'burn_remaining',
name: 'Burn Remaining',
description: `Burn remaining tokens`,
},
]
export interface DispatchExecuteProps {
type: ExecuteType
[k: string]: unknown
}
type Select<T extends ExecuteType> = T
/** @see {@link VendingMinterInstance} */
export type DispatchExecuteArgs = {
contract: string
messages?: BadgeHubInstance
txSigner: string
} & (
| { type: undefined }
| { type: Select<'mint'> }
| { type: Select<'purge'> }
| { type: Select<'update_mint_price'>; price: string }
| { type: Select<'set_whitelist'>; whitelist: string }
| { type: Select<'update_start_time'>; startTime: string }
| { type: Select<'update_start_trading_time'>; startTime?: string }
| { type: Select<'update_per_address_limit'>; limit: number }
| { type: Select<'mint_to'>; recipient: string }
| { type: Select<'mint_for'>; recipient: string; tokenId: number }
| { type: Select<'shuffle'> }
| { type: Select<'withdraw'> }
| { type: Select<'burn_remaining'> }
)
export const dispatchExecute = async (args: DispatchExecuteArgs) => {
const { messages, txSigner } = args
if (!messages) {
throw new Error('cannot dispatch execute, messages is not defined')
}
switch (args.type) {
case 'mint': {
return messages.mint(txSigner)
}
case 'purge': {
return messages.purge(txSigner)
}
case 'update_mint_price': {
return messages.updateMintPrice(txSigner, args.price)
}
case 'set_whitelist': {
return messages.setWhitelist(txSigner, args.whitelist)
}
case 'update_start_time': {
return messages.updateStartTime(txSigner, args.startTime)
}
case 'update_start_trading_time': {
return messages.updateStartTradingTime(txSigner, args.startTime)
}
case 'update_per_address_limit': {
return messages.updatePerAddressLimit(txSigner, args.limit)
}
case 'mint_to': {
return messages.mintTo(txSigner, args.recipient)
}
case 'mint_for': {
return messages.mintFor(txSigner, args.recipient, args.tokenId)
}
case 'shuffle': {
return messages.shuffle(txSigner)
}
case 'withdraw': {
return messages.withdraw(txSigner)
}
case 'burn_remaining': {
return messages.burnRemaining(txSigner)
}
default: {
throw new Error('unknown execute type')
}
}
}
export const previewExecutePayload = (args: DispatchExecuteArgs) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { messages } = useBadgeHubContract()
const { contract } = args
switch (args.type) {
case 'mint': {
return messages(contract)?.mint()
}
case 'purge': {
return messages(contract)?.purge()
}
case 'update_mint_price': {
return messages(contract)?.updateMintPrice(args.price)
}
case 'set_whitelist': {
return messages(contract)?.setWhitelist(args.whitelist)
}
case 'update_start_time': {
return messages(contract)?.updateStartTime(args.startTime)
}
case 'update_start_trading_time': {
return messages(contract)?.updateStartTradingTime(args.startTime as string)
}
case 'update_per_address_limit': {
return messages(contract)?.updatePerAddressLimit(args.limit)
}
case 'mint_to': {
return messages(contract)?.mintTo(args.recipient)
}
case 'mint_for': {
return messages(contract)?.mintFor(args.recipient, args.tokenId)
}
case 'shuffle': {
return messages(contract)?.shuffle()
}
case 'withdraw': {
return messages(contract)?.withdraw()
}
case 'burn_remaining': {
return messages(contract)?.burnRemaining()
}
default: {
return {}
}
}
}
export const isEitherType = <T extends ExecuteType>(type: unknown, arr: T[]): type is T => {
return arr.some((val) => type === val)
}

View File

@ -0,0 +1,53 @@
import type { BadgeHubInstance } from '../contract'
export type QueryType = typeof QUERY_TYPES[number]
export const QUERY_TYPES = ['config', 'mintable_num_tokens', 'start_time', 'mint_price', 'mint_count'] as const
export interface QueryListItem {
id: QueryType
name: string
description?: string
}
export const QUERY_LIST: QueryListItem[] = [
{ id: 'config', name: 'Config', description: 'View current config' },
{ id: 'mintable_num_tokens', name: 'Total Mintable Tokens', description: 'View the total amount of mintable tokens' },
{ id: 'start_time', name: 'Start Time', description: 'View the start time for minting' },
{ id: 'mint_price', name: 'Mint Price', description: 'View the mint price' },
{
id: 'mint_count',
name: 'Total Minted Count',
description: 'View the total amount of minted tokens for an address',
},
]
export interface DispatchQueryProps {
address: string
messages: BadgeHubInstance | undefined
type: QueryType
}
export const dispatchQuery = (props: DispatchQueryProps) => {
const { address, messages, type } = props
switch (type) {
case 'config': {
return messages?.getConfig()
}
case 'mintable_num_tokens': {
return messages?.getMintableNumTokens()
}
case 'start_time': {
return messages?.getStartTime()
}
case 'mint_price': {
return messages?.getMintPrice()
}
case 'mint_count': {
return messages?.getMintCount(address)
}
default: {
throw new Error('unknown query type')
}
}
}

View File

@ -0,0 +1,114 @@
import type { Coin } from '@cosmjs/proto-signing'
import type { logs } from '@cosmjs/stargate'
import { useWallet } from 'contexts/wallet'
import { useCallback, useEffect, useState } from 'react'
import type { BadgeHubContract, BadgeHubInstance, BadgeHubMessages, MigrateResponse } from './contract'
import { badgeHub as initContract } from './contract'
/*export interface InstantiateResponse {
/** The address of the newly instantiated contract *-/
readonly contractAddress: string
readonly logs: readonly logs.Log[]
/** Block height in which the transaction is included *-/
readonly height: number
/** Transaction hash (might be used as transaction ID). Guaranteed to be non-empty upper-case hex *-/
readonly transactionHash: string
readonly gasWanted: number
readonly gasUsed: number
}*/
interface InstantiateResponse {
readonly contractAddress: string
readonly transactionHash: string
readonly logs: readonly logs.Log[]
}
export interface UseBadgeHubContractProps {
instantiate: (
codeId: number,
initMsg: Record<string, unknown>,
label: string,
admin?: string,
funds?: Coin[],
) => Promise<InstantiateResponse>
migrate: (contractAddress: string, codeId: number, migrateMsg: Record<string, unknown>) => Promise<MigrateResponse>
use: (customAddress: string) => BadgeHubInstance | undefined
updateContractAddress: (contractAddress: string) => void
getContractAddress: () => string | undefined
messages: (contractAddress: string) => BadgeHubMessages | undefined
}
export function useBadgeHubContract(): UseBadgeHubContractProps {
const wallet = useWallet()
const [address, setAddress] = useState<string>('')
const [badgeHub, setBadgeHub] = useState<BadgeHubContract>()
useEffect(() => {
setAddress(localStorage.getItem('contract_address') || '')
}, [])
useEffect(() => {
const BadgeHubBaseContract = initContract(wallet.getClient(), wallet.address)
setBadgeHub(BadgeHubBaseContract)
}, [wallet])
const updateContractAddress = (contractAddress: string) => {
setAddress(contractAddress)
}
const instantiate = useCallback(
(codeId: number, initMsg: Record<string, unknown>, label: string, admin?: string): Promise<InstantiateResponse> => {
return new Promise((resolve, reject) => {
if (!badgeHub) {
reject(new Error('Contract is not initialized.'))
return
}
badgeHub.instantiate(wallet.address, codeId, initMsg, label, admin).then(resolve).catch(reject)
})
},
[badgeHub, wallet],
)
const migrate = useCallback(
(contractAddress: string, codeId: number, migrateMsg: Record<string, unknown>): Promise<MigrateResponse> => {
return new Promise((resolve, reject) => {
if (!badgeHub) {
reject(new Error('Contract is not initialized.'))
return
}
console.log(wallet.address, contractAddress, codeId)
badgeHub.migrate(wallet.address, contractAddress, codeId, migrateMsg).then(resolve).catch(reject)
})
},
[badgeHub, wallet],
)
const use = useCallback(
(customAddress = ''): BadgeHubInstance | undefined => {
return badgeHub?.use(address || customAddress)
},
[badgeHub, address],
)
const getContractAddress = (): string | undefined => {
return address
}
const messages = useCallback(
(customAddress = ''): BadgeHubMessages | undefined => {
return badgeHub?.messages(address || customAddress)
},
[badgeHub, address],
)
return {
instantiate,
use,
updateContractAddress,
getContractAddress,
messages,
migrate,
}
}