CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-wagmi--core

VanillaJS library for Ethereum blockchain interactions with reactive primitives and utilities for building Ethereum applications

Pending
Overview
Eval results
Files

contract-interactions.mddocs/

Contract Interactions

Smart contract reading, writing, simulation, and deployment. Complete contract interaction suite with type safety.

Capabilities

Read Contract

Reads data from smart contracts using view/pure functions.

/**
 * Reads from a smart contract
 * @param config - Wagmi configuration
 * @param parameters - Contract read parameters
 * @returns Contract function result
 */
function readContract<config extends Config>(
  config: config,
  parameters: ReadContractParameters<config>
): Promise<ReadContractReturnType>;

interface ReadContractParameters<config extends Config> {
  /** Contract address */
  address: Address;
  /** Contract ABI */
  abi: Abi;
  /** Function name to call */
  functionName: string;
  /** Function arguments */
  args?: readonly unknown[];
  /** Account to call from (optional) */
  account?: Address;
  /** Block number to call at */
  blockNumber?: bigint;
  /** Block tag */
  blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
  /** Chain ID to call on */
  chainId?: config['chains'][number]['id'];
}

type ReadContractReturnType = any; // Depends on contract function return type

type ReadContractErrorType = BaseErrorType | ContractFunctionExecutionErrorType;

Usage Example:

import { readContract } from '@wagmi/core'

// ERC-20 token balance
const balance = await readContract(config, {
  address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
  abi: [
    {
      name: 'balanceOf',
      type: 'function',
      stateMutability: 'view',
      inputs: [{ name: 'owner', type: 'address' }],
      outputs: [{ type: 'uint256' }],
    },
  ],
  functionName: 'balanceOf',
  args: ['0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e'],
})
console.log('Token balance:', balance.toString())

// Read at specific block
const historicalBalance = await readContract(config, {
  address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
  abi: erc20Abi,
  functionName: 'balanceOf',
  args: ['0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e'],
  blockNumber: 18500000n,
})

Read Multiple Contracts (Multicall)

Efficiently reads from multiple contracts in a single call.

/**
 * Reads from multiple smart contracts in a single call
 * @param config - Wagmi configuration
 * @param parameters - Multiple contract read parameters
 * @returns Array of contract function results
 */
function readContracts<config extends Config>(
  config: config,
  parameters: ReadContractsParameters<config>
): Promise<ReadContractsReturnType>;

interface ReadContractsParameters<config extends Config> {
  /** Array of contract calls */
  contracts: readonly {
    address: Address;
    abi: Abi;
    functionName: string;
    args?: readonly unknown[];
  }[];
  /** Block number to call at */
  blockNumber?: bigint;
  /** Block tag */
  blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
  /** Chain ID to call on */
  chainId?: config['chains'][number]['id'];
  /** Whether to allow failures */
  allowFailure?: boolean;
  /** Multicall batch size */
  batchSize?: number;
}

interface ReadContractsReturnType {
  /** Result or error for each contract call */
  result?: any;
  status: 'success' | 'failure';
  error?: BaseError;
}[]

type ReadContractsErrorType = BaseErrorType;

Usage Example:

import { readContracts } from '@wagmi/core'

// Read multiple ERC-20 token data
const results = await readContracts(config, {
  contracts: [
    {
      address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
      abi: erc20Abi,
      functionName: 'name',
    },
    {
      address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
      abi: erc20Abi,
      functionName: 'symbol',
    },
    {
      address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
      abi: erc20Abi,
      functionName: 'decimals',
    },
    {
      address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
      abi: erc20Abi,
      functionName: 'totalSupply',
    },
  ],
})

results.forEach((result, index) => {
  if (result.status === 'success') {
    console.log(`Call ${index}:`, result.result)
  } else {
    console.error(`Call ${index} failed:`, result.error)
  }
})

Write Contract

Executes state-changing contract functions.

/**
 * Writes to a smart contract
 * @param config - Wagmi configuration
 * @param parameters - Contract write parameters
 * @returns Transaction hash
 */
function writeContract<config extends Config>(
  config: config,
  parameters: WriteContractParameters<config>
): Promise<WriteContractReturnType>;

interface WriteContractParameters<config extends Config> {
  /** Contract address */
  address: Address;
  /** Contract ABI */
  abi: Abi;
  /** Function name to call */
  functionName: string;
  /** Function arguments */
  args?: readonly unknown[];
  /** Account to send from (optional, uses connected account) */
  account?: Address;
  /** Chain ID to send on */
  chainId?: config['chains'][number]['id'];
  /** Gas limit */
  gas?: bigint;
  /** Gas price (legacy) */
  gasPrice?: bigint;
  /** Max fee per gas (EIP-1559) */
  maxFeePerGas?: bigint;
  /** Max priority fee per gas (EIP-1559) */
  maxPriorityFeePerGas?: bigint;
  /** Nonce */
  nonce?: number;
  /** Value to send with transaction */
  value?: bigint;
}

type WriteContractReturnType = Hash; // Transaction hash

type WriteContractErrorType = 
  | BaseErrorType
  | ContractFunctionExecutionErrorType
  | UserRejectedRequestErrorType;

Usage Example:

import { writeContract } from '@wagmi/core'

// ERC-20 transfer
const hash = await writeContract(config, {
  address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
  abi: [
    {
      name: 'transfer',
      type: 'function',
      stateMutability: 'nonpayable',
      inputs: [
        { name: 'to', type: 'address' },
        { name: 'amount', type: 'uint256' },
      ],
      outputs: [{ type: 'bool' }],
    },
  ],
  functionName: 'transfer',
  args: ['0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e', 1000000n],
})
console.log('Transaction hash:', hash)

// Contract call with value (payable function)
const payableHash = await writeContract(config, {
  address: '0xContractAddress',
  abi: contractAbi,
  functionName: 'deposit',
  value: parseEther('0.1'), // Send 0.1 ETH
})

Simulate Contract

Simulates contract execution before sending transaction.

/**
 * Simulates contract write before execution
 * @param config - Wagmi configuration
 * @param parameters - Contract simulation parameters
 * @returns Simulation result with request data
 */
function simulateContract<config extends Config>(
  config: config,
  parameters: SimulateContractParameters<config>
): Promise<SimulateContractReturnType>;

interface SimulateContractParameters<config extends Config> {
  /** Contract address */
  address: Address;
  /** Contract ABI */
  abi: Abi;
  /** Function name to simulate */
  functionName: string;
  /** Function arguments */
  args?: readonly unknown[];
  /** Account to simulate from */
  account?: Address;
  /** Chain ID to simulate on */
  chainId?: config['chains'][number]['id'];
  /** Gas limit */
  gas?: bigint;
  /** Gas price */
  gasPrice?: bigint;
  /** Max fee per gas */
  maxFeePerGas?: bigint;
  /** Max priority fee per gas */
  maxPriorityFeePerGas?: bigint;
  /** Nonce */
  nonce?: number;
  /** Value to send */
  value?: bigint;
  /** Block number to simulate at */
  blockNumber?: bigint;
  /** Block tag */
  blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
}

interface SimulateContractReturnType {
  /** Simulation result */
  result: any;
  /** Prepared transaction request */
  request: {
    address: Address;
    abi: Abi;
    functionName: string;
    args?: readonly unknown[];
    account: Address;
    chainId: number;
    gas?: bigint;
    gasPrice?: bigint;
    maxFeePerGas?: bigint;
    maxPriorityFeePerGas?: bigint;
    nonce?: number;
    value?: bigint;
  };
}

type SimulateContractErrorType = 
  | BaseErrorType
  | ContractFunctionExecutionErrorType;

Usage Example:

import { simulateContract, writeContract } from '@wagmi/core'

try {
  // First simulate the transaction
  const { result, request } = await simulateContract(config, {
    address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
    abi: erc20Abi,
    functionName: 'transfer',
    args: ['0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e', 1000000n],
  })
  
  console.log('Simulation result:', result) // true for successful transfer
  console.log('Gas estimate:', request.gas?.toString())
  
  // If simulation succeeds, execute the transaction
  const hash = await writeContract(config, request)
  console.log('Transaction sent:', hash)
} catch (error) {
  console.error('Simulation failed:', error)
  // Handle error (insufficient balance, etc.)
}

Deploy Contract

Deploys a new smart contract.

/**
 * Deploys a smart contract
 * @param config - Wagmi configuration
 * @param parameters - Contract deployment parameters
 * @returns Transaction hash
 */
function deployContract<config extends Config>(
  config: config,
  parameters: DeployContractParameters<config>
): Promise<DeployContractReturnType>;

interface DeployContractParameters<config extends Config> {
  /** Contract ABI */
  abi: Abi;
  /** Contract bytecode */
  bytecode: Hex;
  /** Constructor arguments */
  args?: readonly unknown[];
  /** Account to deploy from */
  account?: Address;
  /** Chain ID to deploy on */
  chainId?: config['chains'][number]['id'];
  /** Gas limit */
  gas?: bigint;
  /** Gas price */
  gasPrice?: bigint;
  /** Max fee per gas */
  maxFeePerGas?: bigint;
  /** Max priority fee per gas */
  maxPriorityFeePerGas?: bigint;
  /** Nonce */
  nonce?: number;
  /** Value to send with deployment */
  value?: bigint;
}

type DeployContractReturnType = Hash; // Transaction hash

type DeployContractErrorType = 
  | BaseErrorType
  | ContractFunctionExecutionErrorType
  | UserRejectedRequestErrorType;

Usage Example:

import { deployContract, waitForTransactionReceipt } from '@wagmi/core'

// Deploy a simple contract
const hash = await deployContract(config, {
  abi: contractAbi,
  bytecode: '0x608060405234801561001057600080fd5b50...', // Contract bytecode
  args: ['Initial Value', 100n], // Constructor arguments
})

console.log('Deployment transaction:', hash)

// Wait for deployment to complete
const receipt = await waitForTransactionReceipt(config, { hash })
console.log('Contract deployed at:', receipt.contractAddress)

Execute Calls

Executes arbitrary contract calls.

/**
 * Executes a contract call
 * @param config - Wagmi configuration
 * @param parameters - Call parameters
 * @returns Call result
 */
function call<config extends Config>(
  config: config,
  parameters: CallParameters<config>
): Promise<CallReturnType>;

interface CallParameters<config extends Config> {
  /** Target account address */
  account?: Address;
  /** Contract address to call */
  to?: Address;
  /** Call data */
  data?: Hex;
  /** Gas limit */
  gas?: bigint;
  /** Gas price */
  gasPrice?: bigint;
  /** Max fee per gas */
  maxFeePerGas?: bigint;
  /** Max priority fee per gas */
  maxPriorityFeePerGas?: bigint;
  /** Value to send */
  value?: bigint;
  /** Block number to call at */
  blockNumber?: bigint;
  /** Block tag */
  blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
  /** Chain ID to call on */
  chainId?: config['chains'][number]['id'];
}

interface CallReturnType {
  /** Return data */
  data?: Hex;
}

type CallErrorType = BaseErrorType | CallExecutionErrorType;

/**
 * Executes multiple calls in a single transaction
 * @param config - Wagmi configuration
 * @param parameters - Multicall parameters
 * @returns Array of call results
 */
function multicall<config extends Config>(
  config: config,
  parameters: MulticallParameters<config>
): Promise<MulticallReturnType>;

interface MulticallParameters<config extends Config> {
  /** Array of contract calls */
  contracts: readonly {
    address: Address;
    abi: Abi;
    functionName: string;
    args?: readonly unknown[];
  }[];
  /** Account to call from */
  account?: Address;
  /** Chain ID to call on */
  chainId?: config['chains'][number]['id'];
  /** Block number to call at */
  blockNumber?: bigint;
  /** Block tag */
  blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
  /** Whether to allow failures */
  allowFailure?: boolean;
}

type MulticallReturnType = (any | null)[];

Usage Example:

import { call, multicall } from '@wagmi/core'

// Raw contract call
const result = await call(config, {
  to: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
  data: '0x70a08231000000000000000000000000742d35cc6601c2f3ac5e5c7a9d16e4e6be4e6e9e', // balanceOf encoded
})
console.log('Call result:', result.data)

// Multicall for batch operations
const results = await multicall(config, {
  contracts: [
    {
      address: '0xTokenA',
      abi: erc20Abi,
      functionName: 'balanceOf',
      args: ['0xUser'],
    },
    {
      address: '0xTokenB', 
      abi: erc20Abi,
      functionName: 'balanceOf',
      args: ['0xUser'],
    },
  ],
})
console.log('Token A balance:', results[0])
console.log('Token B balance:', results[1])

Code Generation Utilities

Generate type-safe contract interaction functions.

/**
 * Creates typed read contract function
 * @param parameters - Read contract creation parameters
 * @returns Typed read function
 */
function createReadContract<TAbi extends Abi>(
  parameters: CreateReadContractParameters<TAbi>
): CreateReadContractReturnType<TAbi>;

interface CreateReadContractParameters<TAbi extends Abi> {
  /** Contract ABI */
  abi: TAbi;
  /** Contract address or resolver */
  address?: Address | Record<number, Address>;
}

type CreateReadContractReturnType<TAbi extends Abi> = <
  TFunctionName extends string
>(
  config: Config,
  parameters: {
    functionName: TFunctionName;
    args?: unknown[];
    chainId?: number;
  }
) => Promise<any>;

/**
 * Creates typed write contract function
 * @param parameters - Write contract creation parameters
 * @returns Typed write function
 */
function createWriteContract<TAbi extends Abi>(
  parameters: CreateWriteContractParameters<TAbi>
): CreateWriteContractReturnType<TAbi>;

interface CreateWriteContractParameters<TAbi extends Abi> {
  /** Contract ABI */
  abi: TAbi;
  /** Contract address or resolver */
  address?: Address | Record<number, Address>;
}

type CreateWriteContractReturnType<TAbi extends Abi> = <
  TFunctionName extends string
>(
  config: Config,
  parameters: {
    functionName: TFunctionName;
    args?: unknown[];
    chainId?: number;
  }
) => Promise<Hash>;

/**
 * Creates typed simulate contract function
 * @param parameters - Simulate contract creation parameters
 * @returns Typed simulate function
 */
function createSimulateContract<TAbi extends Abi>(
  parameters: CreateSimulateContractParameters<TAbi>
): CreateSimulateContractReturnType<TAbi>;

interface CreateSimulateContractParameters<TAbi extends Abi> {
  /** Contract ABI */
  abi: TAbi;
  /** Contract address or resolver */
  address?: Address | Record<number, Address>;
}

type CreateSimulateContractReturnType<TAbi extends Abi> = <
  TFunctionName extends string
>(
  config: Config,
  parameters: {
    functionName: TFunctionName;
    args?: unknown[];
    chainId?: number;
  }
) => Promise<{ result: any; request: any }>;

Usage Example:

import { createReadContract, createWriteContract } from '@wagmi/core/codegen'

// Create typed contract functions
const readERC20 = createReadContract({
  abi: erc20Abi,
  address: {
    1: '0xMainnetAddress',
    137: '0xPolygonAddress',
  },
})

const writeERC20 = createWriteContract({
  abi: erc20Abi,
  address: {
    1: '0xMainnetAddress', 
    137: '0xPolygonAddress',
  },
})

// Use typed functions
const balance = await readERC20(config, {
  functionName: 'balanceOf',
  args: ['0xUser'],
  chainId: 1,
})

const transferHash = await writeERC20(config, {
  functionName: 'transfer',
  args: ['0xRecipient', 1000000n],
  chainId: 1,
})

Install with Tessl CLI

npx tessl i tessl/npm-wagmi--core

docs

account-chain-state.md

advanced-features.md

blockchain-data-reading.md

configuration.md

connection-management.md

contract-interactions.md

ens-operations.md

event-watching.md

index.md

signing-verification.md

tanstack-query.md

transaction-management.md

tile.json