Bucket 4: Virtual Account withdrawals, sign locally

Overview

Virtual Account withdrawals that send a private key, mnemonic or secret to Tatum are being deprecated. Instead you sign the blockchain transaction on your own side and send Tatum only the signed transaction. Your keys never leave your servers.

This page covers the 44 Virtual Account endpoints in the full deprecation list. It is part of the V3 wallets migration guide.

  • Who is affected: any integration that withdraws from a Virtual Account with POST /v3/offchain/{chain}/transfer and a mnemonic, privateKey, fromPrivateKey, secret or keyPair.
  • Deprecation date: January 25, 2027.
  • What to do: replace each of those calls with three: store the withdrawal, sign the transaction locally, broadcast it. Your ledger accounts, deposit addresses and balances stay as they are.

How it works

StepCallWhat happens
  1. Store
POST /v3/offchain/withdrawal with senderAccountId, address, amount, fee (and attr for an XRP destination tag or XLM memo)Tatum reserves amount + fee on the ledger account and returns the withdrawal id. For BTC, LTC, DOGE and BCH it also returns the inputs to spend in data.
  1. Sign
Your code, with your keyBuild the transaction from exactly the values you stored and sign it. Read the chain data you need (nonce, fee, inputs) from the Tatum RPC gateway.
  1. Broadcast
POST /v3/offchain/withdrawal/broadcast with txData, currency, withdrawalIdTatum checks the transaction against the stored withdrawal, sends it to the chain and completes the withdrawal (completed: true).
If 2 or 3 failsDELETE /v3/offchain/withdrawal/{id}Releases the reserved amount and fee. Only for a transaction that did not reach the chain.

The same API key works for all calls. Chain data comes from the RPC gateway, https://{network}.gateway.tatum.io, with the key in the x-api-key header.

Before you start

  • Node.js 18 or higher and your Tatum API key.
  • The signing library for each chain you withdraw on (see Chains). The examples were tested with the versions listed, so pin them.
  • The keys of the addresses that hold your Virtual Account's funds:
    • xpub-based accounts (EVM chains, TRON, BTC, LTC, DOGE, BCH): the key of the deposit address you send from, or for UTXO chains the key of each input's derivationKey. Tatum derives addresses with BIP44 m/44'/{coin}'/0'/0/{index} from the xpub's mnemonic. Testnets use coin type 1, except TRON (195). Mainnet coin types: [TBD: table per chain].
    • address-based accounts (XRP, XLM, SOL, EGLD, ALGO): the key of the account's address. EGLD keys derive with SLIP-10 ed25519 m/44'/508'/0'/0'/0'.

Chains

CurrencyGateway (mainnet)LibrarytxData
ETH, BSC, MATIC, CELO, KLAY, KCS, ONE, XDC, ETH_ARB, ETH_BASE, ETH_OPethereum-mainnet, bsc-mainnet, polygon-mainnet, celo-mainnet, kaia-mainnet, kucoin-mainnet, harmony-mainnet-s0, xdc-mainnet, arbitrum-one-mainnet, base-mainnet, optimism-mainnetethers 6.17Signed raw transaction, 0x…
BTC, LTC, DOGE, BCHbitcoin-mainnet, litecoin-mainnet, dogecoin-mainnet, bitcoin-cash-mainnetbitcore-lib 10.10 (-ltc, -doge, -cash)Serialized transaction, hex
SOLsolana-mainnet@solana/web3.js 1.99{"txId":"<signature>"} as a string; you send the transaction yourself
XRPripple-mainnetxrpl 5.4tx_blob
XLMstellar-mainnet@stellar/stellar-sdk 17.5Transaction envelope, base64 XDR
TRONtron-mainnettronweb 6.5JSON.stringify(signedTransaction)
EGLDmultiversx-mainnetNode cryptoSigned transaction as a JSON string
ALGOalgorand-mainnet-algodalgosdk 3.9Signed transaction, hex
ADAcardano-mainnetTBDTBD

The withdrawal flow in code

Every example below plugs into this function. w holds the values you store and sign with.

const KEY = process.env.TATUM_API_KEY
const headers = { 'x-api-key': KEY, 'content-type': 'application/json' }

async function tatum(method, path, body) {
  const res = await fetch(`https://api.tatum.io${path}`, { method, headers, body: body && JSON.stringify(body) })
  const data = res.status === 204 ? null : await res.json()
  if (!res.ok) throw Object.assign(new Error(data?.message ?? res.statusText), { status: res.status })
  return data
}

// w = { senderAccountId, address, amount, fee, attr? }; sign = async (w, stored) => txData
async function withdraw(currency, w, sign) {
  const stored = await tatum('POST', '/v3/offchain/withdrawal', w)
  let txData
  try {
    txData = await sign(w, stored)
  } catch (e) {
    if (!e.sent) await tatum('DELETE', `/v3/offchain/withdrawal/${stored.id}`) // nothing reached the chain
    throw e
  }
  try {
    return await tatum('POST', '/v3/offchain/withdrawal/broadcast', { currency, txData, withdrawalId: stored.id })
  } catch (e) {
    // Rejected by Tatum (4xx): the transaction was not sent. A timeout or 5xx: it may be on chain, check first.
    if (e.status >= 400 && e.status < 500) await tatum('DELETE', `/v3/offchain/withdrawal/${stored.id}`)
    throw e
  }
}

Examples by chain

The examples show mainnet gateways. For testnets use the matching testnet gateway (for example ethereum-sepolia, bitcoin-testnet, solana-devnet). Amounts are converted with Number for brevity, so use a decimal library in production.

EVM chains (ETH, BSC, MATIC, CELO, KLAY, KCS, ONE, XDC, ETH_ARB, ETH_BASE, ETH_OP)

Estimate first: the fee you store is gasLimit × gasPrice. Then sign with the same values.

import { ethers } from 'ethers'

function provider(gateway) {
  const req = new ethers.FetchRequest(`https://${gateway}.gateway.tatum.io`)
  req.setHeader('x-api-key', KEY)
  return new ethers.JsonRpcProvider(req, undefined, { staticNetwork: true, batchMaxCount: 1 })
}

async function estimateEvm(w, from, gateway) {
  const p = provider(gateway)
  const gasLimit = await p.estimateGas({ from, to: w.address, value: ethers.parseEther(w.amount) })
  const gasPrice = BigInt(await p.send('eth_gasPrice', []))
  return { gasLimit, gasPrice, fee: ethers.formatEther(gasLimit * gasPrice) }
}

async function signEvm(w, privateKey, gateway, { gasLimit, gasPrice }) {
  const p = provider(gateway)
  const wallet = new ethers.Wallet(privateKey, p)
  return wallet.signTransaction({
    type: 0,
    to: w.address,
    value: ethers.parseEther(w.amount),
    nonce: await p.getTransactionCount(wallet.address, 'pending'),
    gasLimit,
    gasPrice,
    chainId: (await p.getNetwork()).chainId,
  })
}

// const gas = await estimateEvm(w, depositAddress, 'ethereum-mainnet')
// await withdraw('ETH', { ...w, fee: gas.fee }, () => signEvm(w, privateKey, 'ethereum-mainnet', gas))

On mainnet you can also take gasLimit and gasPrice (both in wei) from POST /v4/blockchainOperations/gas with chain, from, to, amount for ETH, BSC, CELO, KLAY, KCS, ETH_BASE and ETH_OP.

BTC, LTC, DOGE, BCH

The store response lists the inputs Tatum reserved. Spend exactly those, send the change to your xpub's address at index 0, and leave exactly the fee you stored. The entry with vIn: "-1" is the change amount, not an input.

import bitcore from 'bitcore-lib' // LTC: bitcore-lib-ltc, DOGE: bitcore-lib-doge, BCH: bitcore-lib-cash

// keyFor(i) returns the bitcore PrivateKey of xpub index i; changeAddress is xpub index 0
async function signUtxo(w, stored, keyFor, changeAddress, gateway) {
  const rpc = async (method, params) =>
    (await (await fetch(`https://${gateway}.gateway.tatum.io`, { method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) })).json()).result
  const sats = (v) => Math.round(Number(v) * 1e8)
  const utxos = [], keys = []
  for (const input of stored.data) {
    if (input.vIn === '-1') continue
    const out = (await rpc('getrawtransaction', [input.vIn, true])).vout[input.vInIndex]
    utxos.push({ txId: input.vIn, outputIndex: input.vInIndex, script: out.scriptPubKey.hex, satoshis: sats(out.value) })
    keys.push(keyFor(input.address?.derivationKey ?? 0))
  }
  return new bitcore.Transaction().from(utxos).to(w.address, sats(w.amount)).change(changeAddress).fee(sats(w.fee)).sign(keys).serialize()
}

// await withdraw('BTC', w, (w, stored) => signUtxo(w, stored, keyFor, changeAddress, 'bitcoin-mainnet'))
SOL

Tatum does not send SOL transactions. Send it through the gateway, wait for confirmation, then broadcast the signature as txData. Once the transaction is sent, never cancel the withdrawal: report the signature again instead.

import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram, Transaction } from '@solana/web3.js'

async function sendSol(w, secretKey) {
  const conn = new Connection('https://solana-mainnet.gateway.tatum.io', { commitment: 'confirmed', httpHeaders: { 'x-api-key': KEY } })
  const payer = Keypair.fromSecretKey(secretKey)
  const tx = new Transaction().add(
    SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: new PublicKey(w.address), lamports: Math.round(Number(w.amount) * LAMPORTS_PER_SOL) }),
  )
  tx.recentBlockhash = (await conn.getLatestBlockhash()).blockhash
  tx.feePayer = payer.publicKey
  tx.sign(payer)
  const signature = await conn.sendRawTransaction(tx.serialize())
  for (let i = 0; i < 40; i++) { // poll; websocket subscriptions are not available through the gateway
    const status = (await conn.getSignatureStatuses([signature])).value[0]
    if (status?.err) throw Object.assign(new Error(`SOL transaction failed: ${JSON.stringify(status.err)}`), { sent: true })
    if (['confirmed', 'finalized'].includes(status?.confirmationStatus)) return JSON.stringify({ txId: signature })
    await new Promise((r) => setTimeout(r, 1500))
  }
  throw Object.assign(new Error(`SOL transaction ${signature} not confirmed yet`), { sent: true })
}

// await withdraw('SOL', w, () => sendSol(w, secretKey))
XRP

DestinationTag is the attr you stored. Fee is the fee you stored.

import * as xrpl from 'xrpl'

async function signXrp(w, secret) {
  const rpc = async (method, params = {}) =>
    (await (await fetch('https://ripple-mainnet.gateway.tatum.io', { method: 'POST', headers, body: JSON.stringify({ method, params: [params] }) })).json()).result
  const wallet = xrpl.Wallet.fromSeed(secret)
  const { account_data } = await rpc('account_info', { account: wallet.address, ledger_index: 'current' })
  const { ledger_current_index } = await rpc('fee')
  return wallet.sign({
    TransactionType: 'Payment',
    Account: wallet.address,
    Destination: w.address,
    DestinationTag: Number(w.attr),
    Amount: xrpl.xrpToDrops(w.amount),
    Fee: xrpl.xrpToDrops(w.fee),
    Sequence: account_data.Sequence,
    LastLedgerSequence: ledger_current_index + 20,
  }).tx_blob
}
XLM

The memo is the attr you stored. The fee is in stroops (1 XLM = 10,000,000 stroops).

import { Account, Asset, Keypair, Memo, Networks, Operation, TransactionBuilder } from '@stellar/stellar-sdk'

async function signXlm(w, secret) {
  const kp = Keypair.fromSecret(secret)
  const { sequence } = await (await fetch(`https://stellar-mainnet.gateway.tatum.io/accounts/${kp.publicKey()}`, { headers })).json()
  const tx = new TransactionBuilder(new Account(kp.publicKey(), sequence), {
    fee: String(Math.round(Number(w.fee) * 1e7)),
    networkPassphrase: Networks.PUBLIC,
  })
    .addOperation(Operation.payment({ destination: w.address, asset: Asset.native(), amount: w.amount }))
    .addMemo(Memo.text(w.attr))
    .setTimeout(300)
    .build()
  tx.sign(kp)
  return tx.toEnvelope().toXDR('base64')
}
TRON

The TRON network fee (bandwidth, energy, activation of a new address) is not part of the transaction. Store a fee that covers it.

import { TronWeb } from 'tronweb'

async function signTron(w, privateKey) {
  const tronWeb = new TronWeb({ fullHost: 'https://tron-mainnet.gateway.tatum.io', headers: { 'x-api-key': KEY } })
  const from = tronWeb.address.fromPrivateKey(privateKey)
  const unsigned = await tronWeb.transactionBuilder.sendTrx(w.address, Math.round(Number(w.amount) * 1e6), from)
  return JSON.stringify(await tronWeb.trx.sign(unsigned, privateKey))
}
EGLD

The signature covers the JSON of the transaction fields in exactly this order. The fee is gasPrice × gasLimit.

import crypto from 'node:crypto'
import { bech32 } from 'bech32'

async function signEgld(w, privateKeyHex) {
  const GW = 'https://multiversx-mainnet.gateway.tatum.io'
  const priv = crypto.createPrivateKey({
    key: Buffer.concat([Buffer.from('302e020100300506032b657004220420', 'hex'), Buffer.from(privateKeyHex, 'hex')]),
    format: 'der',
    type: 'pkcs8',
  })
  const pub = crypto.createPublicKey(priv).export({ format: 'der', type: 'spki' }).subarray(-32)
  const sender = bech32.encode('erd', bech32.toWords(pub))
  const { data: cfg } = await (await fetch(`${GW}/network/config`, { headers })).json()
  const { data: acc } = await (await fetch(`${GW}/address/${sender}`, { headers })).json()
  const tx = {
    nonce: acc.account.nonce,
    value: (BigInt(Math.round(Number(w.amount) * 1e6)) * 10n ** 12n).toString(),
    receiver: w.address,
    sender,
    gasPrice: cfg.config.erd_min_gas_price,
    gasLimit: cfg.config.erd_min_gas_limit,
    chainID: cfg.config.erd_chain_id,
    version: 1,
  }
  tx.signature = crypto.sign(null, Buffer.from(JSON.stringify(tx)), priv).toString('hex')
  return JSON.stringify(tx)
}
ALGO
import algosdk from 'algosdk'

async function signAlgo(w, mnemonic) {
  const algod = new algosdk.Algodv2({ 'x-api-key': KEY }, 'https://algorand-mainnet-algod.gateway.tatum.io', '')
  const { sk, addr } = algosdk.mnemonicToSecretKey(mnemonic)
  const tx = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
    sender: addr,
    receiver: w.address,
    amount: Math.round(Number(w.amount) * 1e6),
    suggestedParams: await algod.getTransactionParams().do(),
  })
  return Buffer.from(tx.signTxn(sk)).toString('hex')
}

Things to know

  • Sign exactly what you stored. That means the recipient, amount, destination tag or memo, and for UTXO chains the inputs. Tatum rejects a transaction that does not match the stored withdrawal.
  • Cancel only what never reached the chain. A withdrawal that is not broadcast keeps its amount and fee reserved until you cancel it, and there is no expiry. After a timeout, look the transaction up on chain before you cancel. A completed withdrawal cannot be cancelled.
  • Completed means sent, not confirmed. completed: true means the network accepted the transaction. Watch for confirmation yourself. A transaction can still fail on chain (for example out of gas), and its fee is spent.
  • Declare the real fee. The fee you store is what your ledger account is charged. Estimate it for each withdrawal, and don't hard-code gas limits or prices.
  • One withdrawal at a time per sending address. Two withdrawals signed in parallel can use the same nonce or sequence. On BTC, LTC, DOGE and BCH a second withdrawal is refused while one is pending.
  • Keep the API key in the x-api-key header, never in a URL. The free plan allows 3 gateway requests per second, and some libraries (tronweb, ethers) make several requests per transaction.

Did this page help you?