Skip to content

Swap from a script, no API key ​

One file takes you from nothing to a settled swap. It needs no API key and no browser, so it works the same for a person at a terminal, a backend job or an AI agent.

You need Node 20 or later and one package:

bash
npm install viem

The one thing the script can't do is fund its own wallet. The first run makes a wallet and prints what to send it. On testnet that means the faucets on the Testnet page, and those need a person in a browser.

The script ​

Save this as swap.mjs. As written it sells 100 cNGN for USDT on BSC testnet (chain 97).

js
// swap.mjs: swap on Textile FX from a script. No API key, no browser.
//
//   npm install viem
//   node swap.mjs
//
// The first run makes a wallet, saves its key to ./taker.key and tells you
// what to send it. Fund it, run the script again, and it swaps. Every run that
// gets a quote is one swap, so don't run it again to "make sure".
import { randomBytes } from 'node:crypto'
import { readFileSync, writeFileSync } from 'node:fs'

import {
  createPublicClient,
  createWalletClient,
  defineChain,
  encodeFunctionData,
  erc20Abi,
  http,
  toHex,
} from 'viem'
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'

// BSC testnet, 100 cNGN into USDT. Override any of these from the environment.
const API = process.env.TEXTILE_API ?? 'https://api.textilecredit.com/v2'
const CHAIN_ID = Number(process.env.CHAIN_ID ?? 97)
const RPC_URL =
  process.env.RPC_URL ?? 'https://data-seed-prebsc-1-s1.binance.org:8545'
const SELL_TOKEN =
  process.env.SELL_TOKEN ?? '0x8a078b182bA9649c03982c2a80CDcc81cdc99dA8' // cNGN, 6 decimals
const BUY_TOKEN =
  process.env.BUY_TOKEN ?? '0x337610d27c682E347C9cD60BD4b3b107C9d34dDd' // USDT, 18 decimals
const SELL_AMOUNT = BigInt(process.env.SELL_AMOUNT ?? '100000000') // atomic units
const KEY_FILE = process.env.TAKER_KEY_FILE ?? './taker.key'

// Exit codes, so a caller can branch without reading the output.
const DONE = 0 // swapped
const FAILED = 1 // nothing was swapped
const NEEDS_FUNDS = 2
const NO_QUOTE = 3
const UNCONFIRMED = 4 // the swap was sent and may still land: check, don't retry

const stop = (code, message) => {
  console.log(message)
  process.exit(code)
}

// 1. The wallet. Made once and kept in a file only you can read. The `wx`
//    flag refuses to write over a file that is already there, so two first
//    runs at the same moment can't each make a key: the second one reads the
//    first one's.
try {
  writeFileSync(KEY_FILE, generatePrivateKey(), { mode: 0o600, flag: 'wx' })
} catch (err) {
  if (err.code !== 'EEXIST') throw err
}
const account = privateKeyToAccount(readFileSync(KEY_FILE, 'utf8').trim())

const chain = defineChain({
  id: CHAIN_ID,
  name: `chain ${CHAIN_ID}`,
  nativeCurrency: { name: 'Native', symbol: 'NATIVE', decimals: 18 },
  rpcUrls: { default: { http: [RPC_URL] } },
})
const pub = createPublicClient({ chain, transport: http() })
const wallet = createWalletClient({ account, chain, transport: http() })

// Every error from the API has a stable `code`, and most have a
// `details.reason`. Keep both: they are what you branch on, not the message.
async function api(path, { method = 'GET', body, claim } = {}) {
  const res = await fetch(`${API}${path}`, {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...(claim ? { 'X-Rfq-Claim': claim } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
    // A firm request blocks while makers answer. 75 s covers the worst case.
    signal: AbortSignal.timeout(75_000),
  })
  const json = await res.json()
  if (!res.ok) {
    const { code, message, details } = json.error ?? {}
    throw Object.assign(new Error(message ?? `HTTP ${res.status}`), {
      status: res.status,
      code,
      reason: details?.reason,
      details,
    })
  }
  return json.data
}

// Proof of control: a signature showing you hold the wallet you name as
// `taker`. It moves nothing and approves nothing. Fresh for every request.
async function signTakerProof() {
  const nonce = toHex(randomBytes(32))
  const issuedAt = Date.now() // milliseconds, and within 60 s of our clock
  const signature = await account.signTypedData({
    domain: { name: 'Textile Taker Control', version: '1', chainId: CHAIN_ID },
    types: {
      TakerControl: [
        { name: 'taker', type: 'address' },
        { name: 'chainId', type: 'uint256' },
        { name: 'nonce', type: 'bytes32' },
        { name: 'issuedAt', type: 'uint256' },
      ],
    },
    primaryType: 'TakerControl',
    message: {
      taker: account.address,
      chainId: BigInt(CHAIN_ID),
      nonce,
      issuedAt: BigInt(issuedAt),
    },
  })
  return { nonce, issuedAt, signature }
}

// Send one transaction and wait for it. A revert is certain: it was mined and
// did nothing, and the error says so with `reverted`. A transaction that was
// sent and never confirmed is a third outcome, and the error says so with
// `sentHash`: it can still land later.
const send = async (tx) => {
  const hash = await wallet.sendTransaction({
    to: tx.to,
    data: tx.data,
    value: BigInt(tx.value ?? 0),
  })
  const receipt = await pub.waitForTransactionReceipt({ hash }).catch((err) => {
    throw Object.assign(err, { sentHash: hash })
  })
  if (receipt.status !== 'success') {
    throw Object.assign(new Error(`Transaction ${hash} reverted`), {
      reverted: true,
    })
  }
  return hash
}

const pair = {
  chainId: CHAIN_ID,
  sellToken: SELL_TOKEN,
  buyToken: BUY_TOKEN,
  sellAmount: SELL_AMOUNT.toString(),
}

try {
  console.log(`Taker wallet: ${account.address}`)

  // 2. Preview. Free, no wallet, no signature. Tells you the pair is live
  //    and roughly what you would get.
  const preview = await api('/rfq/preview', { method: 'POST', body: pair })
  if (preview.status !== 'preview') {
    stop(NO_QUOTE, `No indicative price right now: ${preview.reason}`)
  }
  console.log(`Indicative: sell ${SELL_AMOUNT} for about ${preview.buyAmount}`)

  // 3. Funds. A firm quote needs the sell token in the wallet first, and the
  //    two transactions need gas.
  const [sellBalance, gasBalance] = await Promise.all([
    pub.readContract({
      address: SELL_TOKEN,
      abi: erc20Abi,
      functionName: 'balanceOf',
      args: [account.address],
    }),
    pub.getBalance({ address: account.address }),
  ])
  if (sellBalance < SELL_AMOUNT || gasBalance === 0n) {
    stop(
      NEEDS_FUNDS,
      [
        `Fund ${account.address} on chain ${CHAIN_ID}, then run this again:`,
        `  sell token ${SELL_TOKEN}: has ${sellBalance}, needs ${SELL_AMOUNT}`,
        `  native gas token: has ${gasBalance}, needs enough for two transactions`,
      ].join('\n')
    )
  }

  // 4. Firm quote. One signed quote bound to this wallet, or a no-quote.
  const firm = await api('/rfq/request', {
    method: 'POST',
    body: { ...pair, taker: account.address, takerProof: await signTakerProof() },
  })
  if (firm.status === 'no_quote') {
    stop(NO_QUOTE, `No quote: ${firm.reason}. Nothing was spent. Try again.`)
  }
  const { rfqId, claimToken, quote, transactions } = firm
  console.log(`Firm quote ${rfqId}: pay ${quote.takerPays}, receive ${quote.buyAmount}`)

  // 5. Approve the sell token to `quote.spender`, if it isn't already.
  const allowance = await pub.readContract({
    address: SELL_TOKEN,
    abi: erc20Abi,
    functionName: 'allowance',
    args: [account.address, quote.spender],
  })
  if (allowance < BigInt(quote.takerPays)) {
    // USDT-style tokens refuse to change a non-zero allowance. Clear it first.
    if (allowance > 0n) {
      await send({
        to: SELL_TOKEN,
        data: encodeFunctionData({
          abi: erc20Abi,
          functionName: 'approve',
          args: [quote.spender, 0n],
        }),
      })
    }
    await send(transactions.approval)
    console.log('Approved')
  }

  // 6. Swap. The quote has a deadline; never send it late.
  if (Date.now() + 5_000 > Date.parse(quote.expiresAt)) {
    throw new Error('The quote ran out during the approval. Run this again.')
  }
  // An error while sending doesn't prove the swap didn't go out: the node can
  // accept a transaction and the answer still get lost. The wallet's
  // transaction count settles it. If it moved, or can't be read, the swap may
  // be on its way, and that must never be reported as "nothing was swapped".
  const pendingCount = () =>
    pub.getTransactionCount({ address: account.address, blockTag: 'pending' })
  const countBefore = await pendingCount()
  const txHash = await send(transactions.swap).catch(async (err) => {
    if (err.reverted) throw err // mined, and nothing was swapped
    const mayBeSent =
      Boolean(err.sentHash) ||
      (await pendingCount().then(
        (count) => count > countBefore,
        () => true
      ))
    if (!mayBeSent) throw err
    stop(
      UNCONFIRMED,
      err.sentHash
        ? `The swap ${err.sentHash} was sent and isn't confirmed yet. Look it up before you run this again: it may still go through.`
        : `The swap may have been sent, but its hash was lost (${err.shortMessage ?? err.message}). Check the wallet's latest transactions before you run this again.`
    )
  })
  console.log(`Swapped: ${txHash}`)

  // 7. Tell Textile the hash, then read the status back. The swap is final on
  //    chain by now, so nothing here may turn it into a failure: a caller that
  //    saw one could run this again and swap twice. Reporting is a courtesy.
  //    The fill is read from the chain either way.
  try {
    await api(`/rfq/${rfqId}/submit`, {
      method: 'POST',
      body: { txHash },
      claim: claimToken,
    })
    const status = await api(`/rfq/${rfqId}`, { claim: claimToken })
    console.log(`Status: ${status.status}`)
  } catch (err) {
    console.log(`Swapped, but the report didn't go through: ${err.message}`)
  }
  process.exit(DONE)
} catch (err) {
  if (err.reason === 'insufficient_funds') {
    stop(
      NEEDS_FUNDS,
      `The wallet needs ${err.details.required} of the sell token and has ${err.details.available}.`
    )
  }
  const what = [err.code, err.reason].filter(Boolean).join(' / ')
  // viem errors carry a one-line `shortMessage`; the full one runs to a page.
  stop(FAILED, `Failed${what ? ` (${what})` : ''}: ${err.shortMessage ?? err.message}`)
}

Run it ​

bash
node swap.mjs

The first run stops at the funding step:

Taker wallet: 0x26d9443076f951F3Bb4A1eA35BbdA5019206F2aC
Indicative: sell 100000000 for about 68962218899175000
Fund 0x26d9443076f951F3Bb4A1eA35BbdA5019206F2aC on chain 97, then run this again:
  sell token 0x8a078b182bA9649c03982c2a80CDcc81cdc99dA8: has 0, needs 100000000
  native gas token: has 0, needs enough for two transactions

Send that wallet the sell token and some gas, then run the same command again. It starts from the top and this time goes through to the swap:

Taker wallet: 0x26d9443076f951F3Bb4A1eA35BbdA5019206F2aC
Indicative: sell 100000000 for about 68962218899175000
Firm quote rfq_…: pay 100000000, receive …
Approved
Swapped: 0x…
Status: submitted

submitted means Textile has your transaction hash. It turns into filled once the fill has been read from the chain.

The exit code says how it ended, so a caller doesn't have to read the output:

Exit codeMeansWhat to do
0The swap was sent and confirmedNothing. Running it again is a second swap
2The wallet needs fundsSend what the output lists, run again
3No maker quoted this size right nowRun again. Nothing was spent
4The swap was sent, or may have been, and isn't confirmedLook at the wallet's transactions before you run it again. It may still go through
1Nothing was swapped: the API refused, or a transaction reverted. The output has the API's code and details.reasonSee Errors & limits

The script exits 1 only when nothing shows the swap went out. Once the swap is confirmed it exits 0 whatever happens next: if the report to Textile fails it says so and still exits 0. A swap that is mined and reverts is certain too, so that is a 1. If sending the swap fails any other way, it checks whether the wallet's transaction count moved. If it did, or it can't tell, it exits 4. A caller that retries only on 1, 2 and 3 can't swap twice by accident.

What each step does ​

The wallet. The key is made on the first run and saved to taker.key, readable only by you. The file is never overwritten, so starting the script twice at once still leaves one wallet. That's fine for testnet. On mainnet, treat the file as you would any hot key, or swap privateKeyToAccount for the viem account your KMS or MPC provider gives you. That only works as it is for a signer that signs and broadcasts within seconds, with nobody in the loop. The proof is valid for 60 seconds and the quote for about a minute, and the script signs once and sends two transactions inside that time.

A wallet that holds a signature or a transaction for approval can't use this script unchanged. That means a Safe collecting co-signers, a custody policy queue or a hardware wallet. Such a wallet needs the nonceSecret or eip191 form of the proof, an approval made ahead of time, and a fresh quote requested once it's ready to send the swap at once.

Preview. POST /v2/rfq/preview is free and needs no wallet. It reads the prices makers have published and promises nothing. The script uses it to check the pair is live before it asks you for funds.

Funds. A firm quote reserves a maker's inventory for you, so the API reads your wallet's balance first and refuses a wallet that can't pay (proof of funds). The script checks the same thing itself so it can tell you what's missing.

The firm quote. POST /v2/rfq/request with a takerProof: a signature that shows you hold the wallet you named. It moves no funds and approves nothing. The script signs a fresh one for every request, which always works. The answer is one firm quote bound to your wallet, or no_quote. The call blocks while makers answer, usually under a second, so the timeout is 75 seconds. Proof of control has the details.

The approval. You approve the sell token to quote.spender with a plain ERC-20 approve. The response gives you that transaction ready to send as transactions.approval. Read the spender from each quote: it's the settlement reactor for most quotes and a vault's order executor for some. You never approve Permit2. That's the maker's side.

The swap. transactions.swap is the whole trade in one transaction. It settles in full or reverts. A quote lasts about a minute, so the script checks quote.expiresAt after the approval and won't send a quote that has run out.

The report. POST /v2/rfq/{id}/submit tells Textile the transaction hash, and GET /v2/rfq/{id} reads the status back. Both need the claimToken from the quote in an X-Rfq-Claim header. Reporting is a courtesy. The fill is read from the chain either way, so a failed report never makes the script fail.

Trade something else ​

Every setting comes from the environment:

VariableDefaultWhat it is
CHAIN_ID97The chain to trade on
RPC_URLA public BSC testnet nodeAn RPC endpoint for that chain
SELL_TOKENcNGN on chain 97Address of the token you pay with
BUY_TOKENUSDT on chain 97Address of the token you receive
SELL_AMOUNT100000000How much to sell, in the sell token's smallest unit
TAKER_KEY_FILE./taker.keyWhere the wallet key is kept

Token and contract addresses for every chain are in the address book. Check each token's decimals there: 100000000 is 100 cNGN (6 decimals), and it would be a tiny fraction of an 18-decimal token.

For example, 250 cNGN instead of 100:

bash
SELL_AMOUNT=250000000 node swap.mjs

To move to another chain, set CHAIN_ID, RPC_URL and the two token addresses together. Base Sepolia (84532) is the other testnet, and its tokens are on the Testnet page. Testnet makers aren't online on every pair all the time, so a no_quote there usually means nobody is quoting that pair right now, not that your request is wrong.

The same script works on mainnet with a mainnet chain, RPC and token addresses. The smallest trade there is about $1, and the funds are real.

If it stops ​

  • no_quote is a normal answer, not an error. no_makers_online and no_valid_quote are worth an immediate retry. See No quote.
  • insufficient_funds means the wallet holds less of the sell token than the quote needs, or other live quotes have already reserved it.
  • rate_limited means you've asked too often, or you already hold four live quotes. A quote keeps its slot until it fills or its deadline passes. If the response has a Retry-After header, wait that long. See Errors & limits.
  • "The quote ran out during the approval" means the approval took most of the quote's minute. Run the script again. The approval stays in place, so the second run goes straight to the swap.

Next ​