Trade and launch from code
Read a token, quote, buy, sell and launch on GIWA Sepolia with viem, in files you can copy and run.
Set up#
Each example is a whole TypeScript file that uses viem. Save it under any name and run it with an up-to-date Node.js (22.23.4, 24.22.1 or newer), with no build step. The ones that send a transaction read a testnet key from PRIVATE_KEY.
npm install viem
node quote.ts
PRIVATE_KEY=0x... node buy.tsRead a token#
Every launch pairs its token with WETH in a 1% Uniswap V3 pool. The pool factory finds that pool from the token’s address. graduationStatus on the launch factory returns the ETH paired in the pool so far and the token’s threshold.
import { createPublicClient, formatEther, http, parseAbi } from "viem";
import { giwaSepolia } from "viem/chains";
const client = createPublicClient({ chain: giwaSepolia, transport: http() });
const token = "0x58fb4d3da82f5d610ad36e6e39e674c17b32ffd1"; // deus cat ($DCAT)
// The token's pool: Uniswap V3, against WETH, at the 1% tier.
const pool = await client.readContract({
address: "0x151b311C24AEC109C2cA652C3327E7e58551De6f", // Uniswap V3 factory
abi: parseAbi(["function getPool(address, address, uint24) view returns (address)"]),
functionName: "getPool",
args: [token, "0x4200000000000000000000000000000000000006", 10_000], // WETH, 1% fee tier
});
// The ETH paired in the pool so far, the graduation threshold, and whether it is reached.
const [paired, threshold, graduated] = await client.readContract({
address: "0xb3B575A35844CB4Ad77beB243f6daadC9Ad42e0e", // launch factory
abi: parseAbi(["function graduationStatus(address) view returns (uint256, uint256, bool)"]),
functionName: "graduationStatus",
args: [token],
});
console.log({ pool, paired: formatEther(paired), threshold: formatEther(threshold), graduated });Get a quote#
The Uniswap quoter returns how much a trade would receive at the pool’s current price, the 1% pool fee included. It runs as a simulated call, so it costs nothing and needs no wallet. For a sell, swap tokenIn and tokenOut.
import { createPublicClient, formatEther, http, parseAbi, parseEther } from "viem";
import { giwaSepolia } from "viem/chains";
const client = createPublicClient({ chain: giwaSepolia, transport: http() });
// The quoter answers through a simulated call: free, and no wallet needed.
const { result } = await client.simulateContract({
address: "0x4E05e8d5C89cB33896f91b083d0A6186B63aDb45", // Uniswap QuoterV2
abi: parseAbi([
"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96)) returns (uint256, uint160, uint32, uint256)",
]),
functionName: "quoteExactInputSingle",
args: [
{
tokenIn: "0x4200000000000000000000000000000000000006", // WETH
tokenOut: "0x58fb4d3da82f5d610ad36e6e39e674c17b32ffd1", // deus cat
amountIn: parseEther("0.001"),
fee: 10_000, // the 1% pool
sqrtPriceLimitX96: 0n, // no price limit
},
],
});
// The first value returned is the amount out, in wei.
console.log(`0.001 ETH buys about ${formatEther(result[0])} tokens`);Buy#
A buy sends ETH to the swap router, which wraps it to WETH and pays the pool. amountOutMinimum protects against the price moving before the transaction lands: here the trade reverts if it would receive more than 1% less than the quote.
import { createWalletClient, http, parseAbi, parseEther, publicActions } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { giwaSepolia } from "viem/chains";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); // a testnet key
// One client that reads, simulates and sends.
const client = createWalletClient({ account, chain: giwaSepolia, transport: http() }).extend(publicActions);
const swap = {
tokenIn: "0x4200000000000000000000000000000000000006", // WETH
tokenOut: "0x58fb4d3da82f5d610ad36e6e39e674c17b32ffd1", // deus cat
amountIn: parseEther("0.001"),
fee: 10_000, // the 1% pool
sqrtPriceLimitX96: 0n, // no price limit
} as const;
// Quote first, then accept at most 1% less.
const { result: quote } = await client.simulateContract({
address: "0x4E05e8d5C89cB33896f91b083d0A6186B63aDb45", // Uniswap QuoterV2
abi: parseAbi([
"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96)) returns (uint256, uint160, uint32, uint256)",
]),
functionName: "quoteExactInputSingle",
args: [swap],
});
// Send ETH as the value; the router wraps it to WETH for the pool. The tokens go to the wallet.
const { request } = await client.simulateContract({
address: "0x70B359CA97E2bC84543178f1ED487a04DeAC2ba2", // Uniswap SwapRouter02
abi: parseAbi([
"function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96)) payable returns (uint256)",
]),
functionName: "exactInputSingle",
args: [{ ...swap, recipient: account.address, amountOutMinimum: (quote[0] * 99n) / 100n }],
value: swap.amountIn,
});
const hash = await client.writeContract(request);
console.log((await client.waitForTransactionReceipt({ hash })).status, hash);Sell#
The router takes the tokens from the wallet, so a sell first needs an allowance. This example approves only the amount it sells. The swap pays WETH to the router, and unwrapWETH9 sends it on to the wallet as ETH, both in one transaction.
import { createWalletClient, encodeFunctionData, http, parseAbi, parseEther, publicActions } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { giwaSepolia } from "viem/chains";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); // a testnet key
// One client that reads, simulates and sends.
const client = createWalletClient({ account, chain: giwaSepolia, transport: http() }).extend(publicActions);
const token = "0x58fb4d3da82f5d610ad36e6e39e674c17b32ffd1"; // deus cat
const router = "0x70B359CA97E2bC84543178f1ED487a04DeAC2ba2"; // Uniswap SwapRouter02
const amountIn = parseEther("1000"); // tokens to sell
// The router takes the tokens from the wallet, so it needs an allowance first. This approves only the amount sold.
const erc20 = parseAbi([
"function allowance(address owner, address spender) view returns (uint256)",
"function approve(address spender, uint256 amount) returns (bool)",
]);
const allowance = await client.readContract({ address: token, abi: erc20, functionName: "allowance", args: [account.address, router] });
if (allowance < amountIn) {
const { request } = await client.simulateContract({ address: token, abi: erc20, functionName: "approve", args: [router, amountIn] });
await client.waitForTransactionReceipt({ hash: await client.writeContract(request) });
}
const swap = {
tokenIn: token,
tokenOut: "0x4200000000000000000000000000000000000006", // WETH
amountIn,
fee: 10_000, // the 1% pool
sqrtPriceLimitX96: 0n, // no price limit
} as const;
const { result: quote } = await client.simulateContract({
address: "0x4E05e8d5C89cB33896f91b083d0A6186B63aDb45", // Uniswap QuoterV2
abi: parseAbi([
"function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96)) returns (uint256, uint160, uint32, uint256)",
]),
functionName: "quoteExactInputSingle",
args: [swap],
});
const minOut = (quote[0] * 99n) / 100n; // 1% slippage
// Swap into WETH held by the router, then unwrap it to ETH for the wallet, in one transaction.
const routerAbi = parseAbi([
"function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96)) payable returns (uint256)",
"function unwrapWETH9(uint256 amountMinimum, address recipient) payable",
"function multicall(bytes[] data) payable returns (bytes[])",
]);
const { request } = await client.simulateContract({
address: router,
abi: routerAbi,
functionName: "multicall",
args: [
[
encodeFunctionData({ abi: routerAbi, functionName: "exactInputSingle", args: [{ ...swap, recipient: router, amountOutMinimum: minOut }] }),
encodeFunctionData({ abi: routerAbi, functionName: "unwrapWETH9", args: [minOut, account.address] }),
],
],
});
const hash = await client.writeContract(request);
console.log((await client.waitForTransactionReceipt({ hash })).status, hash);Launch a token#
launchToken creates the token, opens its pool and locks the liquidity in one call, as described in Create a token. The value must cover the launch fee, read from the factory here; anything above it is the creator buy. The salt only has to be new for each launch.
import { bytesToHex, createWalletClient, http, parseAbi, parseEther, publicActions } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { giwaSepolia } from "viem/chains";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); // a testnet key
// One client that reads, simulates and sends.
const client = createWalletClient({ account, chain: giwaSepolia, transport: http() }).extend(publicActions);
const factory = "0xb3B575A35844CB4Ad77beB243f6daadC9Ad42e0e"; // launch factory
const abi = parseAbi([
"function launchFee() view returns (uint256)",
"function launchToken((string name, string symbol, string logo, string description, (string twitter, string telegram, string discord, string website, string farcaster) socials, address feeWallet) params, uint256 launchConfigId, uint256 dexId, bytes32 salt) payable returns (address)",
]);
const launchFee = await client.readContract({ address: factory, abi, functionName: "launchFee" }); // read live, it can change
// The simulation also returns the new token's address, before anything is sent.
const { request, result: token } = await client.simulateContract({
address: factory,
abi,
functionName: "launchToken",
args: [
{
name: "Example Token",
symbol: "EXMPL",
logo: "", // an ipfs:// or https:// image URL, or empty for the first letter
description: "Launched from a script.",
socials: { twitter: "", telegram: "", discord: "", website: "", farcaster: "" },
feeWallet: account.address, // receives the creator buy and the creator's share of fees
},
0n, // launch config 0, the only one today
0n, // DEX config 0: Uniswap V3
bytesToHex(crypto.getRandomValues(new Uint8Array(32))), // any salt not used before
],
value: launchFee + parseEther("0.001"), // the fee, plus an optional creator buy
});
const hash = await client.writeContract(request);
console.log((await client.waitForTransactionReceipt({ hash })).status, `token ${token}`);Before you send#
- Use a wallet made for testing, holding only testnet ETH, and read each file before you run it: the ones that send spend that wallet's ETH or tokens.
- Each file simulates its transaction before sending it. A call that would fail stops there with the contract's reason, and nothing is spent.
- On the launch block, pool buys other than the creator buy revert, and for two more blocks a buy is capped per wallet. A script buying a new token should wait until the block after the token's restrictionEndBlock().
- The 1% slippage is an example. A tighter limit fails more often when others trade at the same time; a looser one accepts a worse price.
- The addresses are GIWA Sepolia's. Mainnet will have its own, listed under Network and contracts once it is live.