Skip to content

Custom Account

A function to create a Custom Account.

A Custom Account is an interface that has the ability to sign transactions and messages with your own custom implementation of the signable methods.

Import

import { toAccount } from 'viem/accounts'

Usage

import { createWalletClient, http } from 'viem'
import {  
  signMessage, 
  signTransaction, 
  signTypedData, 
  privateKeyToAddress,
  toAccount 
} from 'viem/accounts'
import { mainnet } from 'viem/chains'
 
const privateKey = '0x...'
const account = toAccount({
  address: getAddress(privateKey),
  async signMessage({ message }) {
    return signMessage({ message, privateKey })
  },
  async signTransaction(transaction, { serializer }) {
    return signTransaction({ privateKey, transaction, serializer })
  },
  async signTypedData(typedData) {
    return signTypedData({ ...typedData, privateKey })
  },
})
 
const client = createWalletClient({
  account,
  chain: mainnet,
  transport: http()
})

Parameters

address

  • Type: Address

The Address of the Account.

const account = toAccount({
  address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 
  async signMessage({ message }) {
    return signMessage({ message, privateKey })
  },
  async signTransaction(transaction, { serializer }) {
    return signTransaction({ privateKey, transaction, serializer })
  },
  async signTypedData(typedData) {
    return signTypedData({ ...typedData, privateKey })
  },
})

signMessage

Function to sign a message in EIP-191 format.

const account = toAccount({
  address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
 
  async signMessage({ message }) { 
    return signMessage({ message, privateKey })
  },
  async signTransaction(transaction, { serializer }) {
    return signTransaction({ privateKey, transaction, serializer })
  },
  async signTypedData(typedData) {
    return signTypedData({ ...typedData, privateKey })
  },
})

signTransaction

Function to sign a transaction.

const account = toAccount({
  address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
  async signMessage({ message }) {
    return signMessage({ message, privateKey })
  },
  async signTransaction(transaction, { serializer }) {  
    return signTransaction({ privateKey, transaction, serializer })
  },
  async signTypedData(typedData) {
    return signTypedData({ ...typedData, privateKey })
  },
})

signTypedData

Function to sign EIP-712 typed data.

const account = toAccount({
  address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
  async signMessage({ message }) {
    return signMessage({ message, privateKey })
  },
  async signTransaction(transaction, { serializer }) {
    return signTransaction({ privateKey, transaction, serializer })
  },
  async signTypedData(typedData) {  
    return signTypedData({ ...typedData, privateKey })
  },
})