Skip to main content

Overview

The useInterwovenKit hook provides access to wallet connection state, account information, UI controls, transaction utilities, and AutoSign functionality for interacting with the Initia blockchain.
This hook must be used within a component wrapped by InterwovenKitProvider to access wallet functionality. For simple reads, prefer smaller hooks (useAddress, useUsernameQuery) to avoid overhead.

Prerequisites

  • Must be rendered within InterwovenKitProvider.
  • Must be used within a React Query QueryClientProvider.
  • Must be used within a wagmi WagmiProvider.
  • Client-only (no SSR): Put this in a use client provider tree, or use a dynamic import in Next.js.

Quickstart

'use client'

import { useInterwovenKit } from '@initia/interwovenkit-react'

function ConnectButton() {
  const { isConnected, openConnect, openWallet } = useInterwovenKit()
  return (
    <button onClick={isConnected ? openWallet : openConnect}>
      {isConnected ? 'Open wallet' : 'Connect'}
    </button>
  )
}
This example assumes providers are already set up. For complete setup configurations, see Provider Setup.

Account Information

The hook provides multiple address formats and account details for the currently connected wallet:
address
string
Current address in either Bech32 or hex format, depending on the configured chain type (hex for minievm, bech32 for others). Returns an empty string when not connected.
initiaAddress
string
Bech32-formatted Initia wallet address of the connected account. Returns an empty string when not connected.
hexAddress
string
Hex-encoded Ethereum-compatible address of the connected account. Returns an empty string when not connected.
username
string | null | undefined
Optional username linked to the account. Returns null if no username is associated, or undefined before the query has produced a value.
offlineSigner
OfflineAminoSigner
Offline signer for Cosmos transactions.
isConnected
boolean
Whether a wallet is currently connected.
isOpen
boolean
Whether the InterwovenKit drawer/modal is currently open.
function AccountInfo() {
  const { address, initiaAddress, hexAddress, username, isConnected } =
    useInterwovenKit()

  if (!isConnected) return <div>Not connected</div>

  return (
    <div>
      <div>Address: {address}</div>
      <div>Initia Address: {initiaAddress}</div>
      <div>Hex Address: {hexAddress}</div>
      {username && <div>Username: {username}</div>}
    </div>
  )
}

UI Controls

The hook provides methods for controlling wallet-related UI components:
openConnect
() => void
Opens a drawer for connecting an external wallet.
openWallet
() => void
Opens the main wallet drawer showing balances for the connected account.
openBridge
(defaultValues?: Partial<FormValues>) => void
Opens the bridge drawer to onboard assets with optional pre-populated values.
disconnect
() => void
Disconnects the current wallet connection.

Bridge Form Values

The openBridge method accepts optional FormValues to pre-populate the bridge form:
srcChainId
string
Source chain ID for the bridge transaction.
srcDenom
string
Source token denomination to bridge from.
dstChainId
string
Destination chain ID for the bridge transaction.
dstDenom
string
Destination token denomination to bridge to.
quantity
string
Initial bridge amount (use human-readable values, e.g., “1” for 1 INIT).
sender
string
Sender address.
recipient
string
Recipient address.
slippagePercent
string
Slippage tolerance percentage.
cosmosWalletName
string
Optional Cosmos wallet name.
All bridge form values are optional. You can pre-populate any subset of fields to improve the user experience.
function BridgeButton() {
  const { openBridge } = useInterwovenKit()

  return (
    <button
      onClick={() =>
        openBridge({
          srcChainId: 'interwoven-1',
          srcDenom: 'uinit',
          dstChainId: 'my-rollup-1',
          dstDenom: 'uinit',
          quantity: '100',
        })
      }
    >
      Bridge Assets
    </button>
  )
}

Transaction Methods

The hook provides utilities for estimating, simulating, signing, and sending transactions on the blockchain:
estimateGas
(tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>) => Promise<number>
Estimates the gas required for a transaction before execution.
simulateTx
(tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>) => Promise<unknown>
Simulates a transaction without broadcasting, returning the transaction result.
requestTxSync
(tx: TxRequest) => Promise<string>
Signs and broadcasts a transaction, returning the transaction hash immediately without waiting for block inclusion. Shows transaction approval UI before signing.
requestTxBlock
(tx: TxRequest, timeoutMs?: number, intervalMs?: number) => Promise<DeliverTxResponse>
Signs, broadcasts, and waits for block inclusion, returning the complete transaction response. Shows transaction approval UI before signing. Defaults to timeoutMs: 30000 (30 seconds) and intervalMs: 500 (0.5 seconds).
submitTxSync
(tx: TxParams) => Promise<string>
Signs and broadcasts a transaction with pre-calculated fee, returning the transaction hash immediately without waiting for block inclusion. Does not show UI.
submitTxBlock
(tx: TxParams, timeoutMs?: number, intervalMs?: number) => Promise<DeliverTxResponse>
Signs, broadcasts, and waits for block inclusion with pre-calculated fee, returning the complete transaction response. Does not show UI. Defaults to timeoutMs: 30000 (30 seconds) and intervalMs: 500 (0.5 seconds).
waitForTxConfirmation
(options: WaitForTxOptions) => Promise<IndexedTx>
Polls for transaction confirmation on-chain using a transaction hash.
Use requestTxSync for better UX when you want to show immediate feedback, then use waitForTxConfirmation to track the final transaction status. Use requestTxBlock when you need the complete transaction result immediately.

Transaction Request Interface

The TxRequest interface defines parameters for transaction operations that include gas estimation:
messages
EncodeObject[]
required
Array of encoded transaction messages to include in the transaction.
memo
string
Optional memo to attach to the transaction.
chainId
string
Target chain ID for the transaction. Defaults to the provider’s defaultChainId.
gasAdjustment
number
default:"1.4"
Multiplier applied to the estimated gas amount for safety margin.
gas
number
Explicit gas limit for the transaction. If provided, skips gas estimation.
gasPrices
Coin[] | null
Explicit gas prices. If provided, skips the fee denomination selection UI.
spendCoins
Coin[]
Coins to spend for the transaction fee.

Transaction Params Interface

The TxParams interface defines parameters for transactions with pre-calculated fees:
messages
EncodeObject[]
required
Array of encoded transaction messages to include in the transaction.
memo
string
Optional memo to attach to the transaction.
chainId
string
Target chain ID for the transaction. Defaults to the provider’s defaultChainId.
fee
StdFee
required
Pre-calculated fee for the transaction.

Transaction Confirmation Options

The WaitForTxOptions interface defines parameters for tracking transaction confirmation:
txHash
string
required
Hash of the transaction to track for confirmation.
chainId
string
Chain ID where the transaction was broadcast.
timeoutMs
number
default:"30000"
Maximum time in milliseconds to wait for transaction confirmation before failing. Defaults to 30000 (30 seconds).
intervalMs
number
default:"500"
Polling interval in milliseconds for checking transaction status. Defaults to 500 (0.5 seconds).

Transaction Examples

import { useInterwovenKit } from '@initia/interwovenkit-react'
import type { EncodeObject, StdFee } from '@cosmjs/stargate'

function SendTransaction() {
  const { requestTxBlock, submitTxSync, waitForTxConfirmation } =
    useInterwovenKit()

  // Example: Request transaction with UI approval
  const handleRequestTx = async (messages: EncodeObject[]) => {
    try {
      const response = await requestTxBlock({ messages })
      console.log('Transaction confirmed:', response.transactionHash)
    } catch (error) {
      console.error('Transaction failed:', error)
    }
  }

  // Example: Submit transaction directly without UI
  const handleSubmitTx = async (messages: EncodeObject[], fee: StdFee) => {
    try {
      const txHash = await submitTxSync({ messages, fee })
      console.log('Transaction hash:', txHash)

      // Optionally wait for confirmation
      const confirmed = await waitForTxConfirmation({ txHash })
      console.log('Transaction confirmed:', confirmed)
    } catch (error) {
      console.error('Transaction failed:', error)
    }
  }

  return (
    <div>
      <button
        onClick={() =>
          handleRequestTx([
            /* messages */
          ])
        }
      >
        Send with UI
      </button>
      <button
        onClick={() =>
          handleSubmitTx(
            [
              /* messages */
            ],
            {
              /* fee */
            },
          )
        }
      >
        Send without UI
      </button>
    </div>
  )
}

AutoSign

The hook provides AutoSign state and control methods for automatic transaction signing:
autoSign.expiredAtByChain
Record<string, Date | null | undefined>
Expiration dates for AutoSign permissions by chain ID.
autoSign.isEnabledByChain
Record<string, boolean>
Whether AutoSign is enabled for each chain.
autoSign.isLoading
boolean
Whether AutoSign status is being loaded.
autoSign.enable
(chainId?: string) => Promise<void>
Opens UI to enable AutoSign for a chain. Optionally specify a chain ID, or defaults to the provider’s defaultChainId if omitted.
autoSign.disable
(chainId?: string) => Promise<void>
Disables AutoSign for a chain. Optionally specify a chain ID, or defaults to the provider’s defaultChainId if omitted.
AutoSign requires Privy integration. See AutoSign setup for complete AutoSign configuration.
function AutoSignControls() {
  const { autoSign } = useInterwovenKit()
  const chainId = 'interwoven-1'

  return (
    <div>
      {autoSign.isLoading ? (
        <div>Loading AutoSign status...</div>
      ) : (
        <>
          <div>
            AutoSign enabled:{' '}
            {autoSign.isEnabledByChain[chainId] ? 'Yes' : 'No'}
          </div>
          {autoSign.expiredAtByChain[chainId] && (
            <div>
              Expires: {autoSign.expiredAtByChain[chainId]?.toLocaleString()}
            </div>
          )}
          <button onClick={() => autoSign.enable(chainId)}>
            Enable AutoSign
          </button>
          <button onClick={() => autoSign.disable(chainId)}>
            Disable AutoSign
          </button>
        </>
      )}
    </div>
  )
}

Notes

  • Transaction helpers throw MoveError on Move VM errors (see MoveError).
  • requestTx* methods show a transaction approval UI before signing.
  • submitTx* methods sign and broadcast directly without UI.
  • waitForTxConfirmation polls until confirmed or timeout.

Type reference (advanced)

function useInterwovenKit(): InterwovenKitResult

type InterwovenKitResult = {
  address: string
  initiaAddress: string
  hexAddress: string
  username: string | null | undefined
  offlineSigner: OfflineAminoSigner
  isConnected: boolean
  isOpen: boolean
  openConnect: () => void
  openWallet: () => void
  openBridge: (defaultValues?: Partial<FormValues>) => void
  disconnect: () => void
  autoSign: AutoSignState
  estimateGas: (
    tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>,
  ) => Promise<number>
  simulateTx: (
    tx: Pick<TxRequest, 'messages' | 'memo' | 'chainId'>,
  ) => Promise<unknown>
  requestTxSync: (tx: TxRequest) => Promise<string>
  requestTxBlock: (
    tx: TxRequest,
    timeoutMs?: number,
    intervalMs?: number,
  ) => Promise<DeliverTxResponse>
  submitTxSync: (tx: TxParams) => Promise<string>
  submitTxBlock: (
    tx: TxParams,
    timeoutMs?: number,
    intervalMs?: number,
  ) => Promise<DeliverTxResponse>
  waitForTxConfirmation: (options: WaitForTxOptions) => Promise<IndexedTx>
}

type FormValues = {
  srcChainId: string
  srcDenom: string
  dstChainId: string
  dstDenom: string
  quantity: string
  sender: string
  cosmosWalletName?: string
  recipient: string
  slippagePercent: string
}

type TxRequest = {
  messages: EncodeObject[]
  memo?: string
  chainId?: string
  gas?: number
  gasAdjustment?: number
  gasPrices?: Coin[] | null
  spendCoins?: Coin[]
}

type TxParams = {
  messages: EncodeObject[]
  memo?: string
  chainId?: string
  fee: StdFee
}

type WaitForTxOptions = {
  txHash: string
  chainId?: string
  timeoutMs?: number
  intervalMs?: number
}

type AutoSignState = {
  expiredAtByChain: Record<string, Date | null | undefined>
  isEnabledByChain: Record<string, boolean>
  isLoading: boolean
  enable: (chainId?: string) => Promise<void>
  disable: (chainId?: string) => Promise<void>
}
Types OfflineAminoSigner, EncodeObject, Coin, StdFee, DeliverTxResponse, and IndexedTx are from external packages. See @cosmjs/amino, @cosmjs/proto-signing, cosmjs-types, @cosmjs/stargate for details.