useTx

A hook for sending a transaction for a contract and decoding successful responses or receiving errors. This hook is used in combination with the result of useContract.

See useink/utils helpers for compatible functions that work well with this hook.

Basic Usage

import { useTx, useContract, shouldDisable } from 'useink'
import { pickDecoded } from 'useink/utils'
import metadata from './metadata.json'

interface Result {
  color: string;
}

export const MyContractView: React.FC = () => {
  const contract = useContract('..address', metadata)
  const setColor = useTx<Result>(contract, 'setColor')
  const args = ['blue']

  return (
    <>
      <button onClick={() => setColor.signAndSend(args)} disable={shouldDisable(setColor)}>
        {shouldDisable(setColor) ? 'Changing Color...' : 'Change Color'}
      </button>

      <h2>Get the result the hard way: {setColor.result.ok ? setColor.result.value.decoded.color : '--'}</h2>
      <h2>Or the easy way: {pickDecoded(get.result)?.color || '--'}</h2>
    </>
  )
}

Return Value

export interface Tx<T> {
  signAndSend: (
    args?: unknown[],
    options?: ContractOptions,
    cb?: ContractSubmittableResultCallback,
  ) => void;
  status: Status;
  result: ContractSubmittableResult | undefined;
  resetState: () => void;
}

Transaction Statuses

useink extends transaction statuses defined in the Substrate transaction-pool pallet. These are used for pre-transaction senarios such as awaiting signature in a wallet, dry runs, or handling a JavaScript error.

export type Status =
  | 'None'             
  | 'PendingSignature' // A user is prompted to sign a transaction in their wallet extension.
  | 'DryRun'           // A pre-flight is being sent without any payments.
  | 'Errored'          // A JavaScript error occured
  | 'Future'           
  | 'Ready'            
  | 'Broadcast'        
  | 'InBlock'          
  | 'Retracted'        
  | 'FinalityTimeout'  
  | 'Finalized'        
  | 'Usurped'          
  | 'Dropped'          
  | 'Invalid';          

Want to Learn More?

Common Patterns With useTx

See shouldDisable and shouldDisableStrict.

Last updated

Was this helpful?