Docs · For builders
Launch and trade from code
viem and a key in an environment variable. Swap in a browser wallet and they work the same. Zero's RPC and chain ID and Submarine's API address are placeholders, filled in at launch.Set up
import { createPublicClient, createWalletClient, http, parseAbi, parseEther, parseEventLogs, formatEther, type Address } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
const RPC = 'https://testnet.zero.layerzero.network';
const chain = { id: 1337, name: 'Zero', nativeCurrency: { name: 'ZRO', symbol: 'ZRO', decimals: 18 }, rpcUrls: { default: { http: [RPC] } } } as const;
const client = createPublicClient({ chain, transport: http(RPC) });
const wallet = createWalletClient({ chain, transport: http(RPC), account: privateKeyToAccount(process.env.KEY as `0x${string}`) });
// Read the addresses live, so a redeploy doesn't break this.
const { deployment } = await (await fetch('<Submarine API URL>/health')).json();
const LAUNCHPAD = deployment.launchpad as Address;
const ROUTER = deployment.router as Address;
const PAD = parseAbi([
'function launch(string name, string symbol, string uri, uint256 minTokensOut, uint256 wholeSupply, uint16 devFeeBps, uint16 holdersBps, uint16 burnBps, bool antiSnipe) payable returns (address)',
'function launch(string name, string symbol, string uri, uint256 minTokensOut, uint256 wholeSupply, uint16 devFeeBps, uint16 holdersBps, uint16 burnBps, bool antiSnipe, uint16 maxWalletBps, uint32 maxWalletSecs) payable returns (address)',
'function lowerFee(address token, uint16 devFeeBps) returns (uint16)',
'function launchFee() view returns (uint256)',
'function curves(address) view returns (address creator, uint40 createdAt, bool graduated, uint16 feeBps, uint16 holdersBps, uint16 burnBps, bool antiSnipe, uint128 raised, uint128 sold, uint128 supply, uint16 protocolBps)',
'function priceOf(address) view returns (uint256)',
'function buyFeeBps(address) view returns (uint256)',
'function buyFeeBpsFor(address token, address trader) view returns (uint256)',
'function claimCreatorFees()',
'function creatorFees(address) view returns (uint256)',
'event TokenLaunched(address indexed token, address indexed creator, string name, string symbol, string uri, uint256 timestamp, uint256 supply, uint16 feeBps, uint16 holdersBps, uint16 burnBps, bool antiSnipe)',
]);
const ROUTER_ABI = parseAbi([
'function quoteBuy(address token, uint256 zroIn) view returns (uint256)',
'function quoteSell(address token, uint256 tokensIn) view returns (uint256)',
'function buy(address token, uint256 minOut, address recipient, uint256 deadline) payable returns (uint256)',
'function sell(address token, uint256 tokensIn, uint256 minOut, address recipient, uint256 deadline) returns (uint256)',
'function buyPartner(address token, uint256 minOut, address recipient, uint256 deadline, address partner, uint8 kind) payable returns (uint256)',
'function sellPartner(address token, uint256 tokensIn, uint256 minOut, address recipient, uint256 deadline, address partner, uint8 kind) returns (uint256)',
'function isFeeFree(address) view returns (bool)',
'function volumeOf(address) view returns (uint256)',
'function rankOf(address) view returns (uint256)',
'function discountOf(address) view returns (uint256)',
]);
const ERC20 = parseAbi([
'function approve(address spender, uint256 amount) returns (bool)',
'function balanceOf(address) view returns (uint256)',
]);Save the picture and links
A picture is too big for the chain, so it is saved first and the token carries a short link to it. The answer's uri is what goes into launch. You can also pass any picture link of your own as the uri and skip this.
const meta = await fetch('<Submarine API URL>/api/v1/meta', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
image: 'data:image/png;base64,iVBORw0…', // PNG, JPEG, WebP or GIF, 2 MB at most
description: 'A token about cats.', // 600 characters at most
website: 'https://example.com',
twitter: 'https://x.com/example',
}),
}).then((r) => r.json());
// meta.uri is the link to launch withLaunch a token
| Argument | Allowed | Example |
|---|---|---|
name | 1 to 64 bytes (the site stops at 48 characters) | "Cat Coin" |
symbol | 1 to 16 bytes | "CAT" |
uri | At most 512 bytes | meta.uri |
wholeSupply | 10⁹ to 10¹⁵ whole tokens | 1_000_000_000n |
devFeeBps | Your own fee on top of the 1% base: 0 to 1,000 (none to 10%) | 200 |
holdersBps, burnBps | Shares of your own fee only, adding up to 10,000 or less. You get the rest. Both 0 when devFeeBps is 0 | 5000, 5000 |
antiSnipe | Buys pay 50% at launch, falling to the token's fee over 60 seconds | false |
maxWalletBps, maxWalletSecs | Only in the 11-argument launch: the most one wallet may hold, 100 to 500 basis points of the supply, for 900 to 86,400 seconds. Both 0 for none. The first buy has to fit under it | 100, 3600 |
value | launchFee() plus your first buy, if any | launchFee + 200 ZRO |
const launchFee = await client.readContract({ address: LAUNCHPAD, abi: PAD, functionName: 'launchFee' });
const firstBuy = parseEther('200');
const hash = await wallet.writeContract({
address: LAUNCHPAD,
abi: PAD,
functionName: 'launch',
args: ['Cat Coin', 'CAT', meta.uri, minFirstBuy, 1_000_000_000n, 200, 5000, 5000, false], // 2% own fee, half to holders, half to the burn
value: launchFee + firstBuy,
});
const receipt = await client.waitForTransactionReceipt({ hash });
// The new token's address is on the TokenLaunched event.
const [launched] = parseEventLogs({ abi: PAD, logs: receipt.logs, eventName: 'TokenLaunched' });
const token = launched.args.token;
// launched.args.feeBps is 300: the 1% base plus the 2% own fee.The 1% base is fixed and isn't an argument: 0.4% of each trade goes to Submarine and 0.6% to you, on the curve and later on the pool, whatever you choose for the rest.
With a max wallet, call the 11-argument launch with the two extra arguments. The token then emits MaxWalletSet right after TokenLaunched, and its walletCap() answers the cap in wei of the token until it ends, then 0. A first buy that doesn't fit reverts the whole launch with MaxWallet. See Max wallet.
The first buy, worked out
There is no token to quote yet, so work out minTokensOut from the curve itself. These are the contract's own formulas, rounding the same way:
function firstBuyOut(zroIn: bigint, feeBps: bigint, wholeSupply: bigint): bigint {
const supply = wholeSupply * 10n ** 18n;
const vTokens = (supply * 16n) / 15n; // VIRTUAL_TOKENS
const vZro = parseEther('2000'); // VIRTUAL_ZRO, in ZRO
const fee = (zroIn * feeBps + 9999n) / 10000n; // rounded up. feeBps is the whole fee: 100 + devFeeBps
const net = zroIn - fee;
const left = (vZro * vTokens + (vZro + net) - 1n) / (vZro + net); // rounded up
return vTokens - left;
}
const expected = firstBuyOut(parseEther('200'), 300n, 1_000_000_000n); // 100 base + 200 own
const minFirstBuy = (expected * 99n) / 100n; // allow 1%On a fresh token with no own fee (1% in all) and a supply of 1 billion, 400 ZRO buys 176,293,823 tokens: the fee is 4 ZRO, 396 ZRO goes into the curve, and the market cap moves from 1,875 ZRO to about 2,691 ZRO.
Quote
Quote through the router. It asks every venue and answers with the best price after every fee, whether the token is still on its curve or already in a pool.
const out = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'quoteBuy', args: [token, parseEther('40')] });
const back = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'quoteSell', args: [token, out] });
console.log(formatEther(out), 'tokens for 40 ZRO, which sell back for', formatEther(back));Buy and sell
const deadline = BigInt(Math.floor(Date.now() / 1000) + 120);
// Buy with 1% slippage, the site's Auto.
const quote = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'quoteBuy', args: [token, parseEther('40')] });
await wallet.writeContract({
address: ROUTER, abi: ROUTER_ABI, functionName: 'buy',
args: [token, (quote * 99n) / 100n, wallet.account.address, deadline],
value: parseEther('40'),
});
// Sell everything, in a later block than the buy. Submarine's tokens need no approval for the router; another token would.
const bal = await client.readContract({ address: token, abi: ERC20, functionName: 'balanceOf', args: [wallet.account.address] });
const zro = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'quoteSell', args: [token, bal] });
await wallet.writeContract({
address: ROUTER, abi: ROUTER_ABI, functionName: 'sell',
args: [token, bal, (zro * 99n) / 100n, wallet.account.address, deadline],
});The router checks what really arrived against your minimum, so a token that takes something from a transfer can't slip past it. Buy for yourself (recipient equal to the sender) and the trade also counts as your activity, which is what copy trading follows.
A trade through the router adds to your volume, and your rank's discount comes off Submarine's cut from the next one. The router's quotes are for a wallet without a rank, so a ranked wallet gets a little more than quoted and a minimum taken from the quote stays safe. A trade sent straight to the launchpad, or to the pool through Infinity, pays the same fee, the full 0.4% included, and adds no volume.
BoughtThisBlock. Wait for the buy's receipt before you sell.Trading through a partner
An app, a bot or an agent that trades for its users can name itself as the partner. The router then pays it 30% of Submarine's cut of the trade, and the user pays exactly what buy or sell would cost. kind is 1 for a call and 2 for a builder.
const BUILDER = '0xYourWallet' as Address; // must not be the trader
await wallet.writeContract({
address: ROUTER, abi: ROUTER_ABI, functionName: 'buyPartner',
args: [token, (quote * 99n) / 100n, wallet.account.address, deadline, BUILDER, 2],
value: parseEther('40'),
});The router emits Partner with what it paid. A partner that is the trader, the router or zero, or a kind other than 1 or 2, reverts with BadPartner. To get the same call built and checked for you, use /api/v1/quote.
Read a curve
const [creator, createdAt, graduated, feeBps, holdersBps, burnBps, antiSnipe, raised, sold, supply, protocolBps] =
await client.readContract({ address: LAUNCHPAD, abi: PAD, functionName: 'curves', args: [token] });
const ownFee = feeBps - 100; // the creator's own fee; holdersBps and burnBps are shares of it
// protocolBps is always 40, Submarine's 0.4% before a rank discount
const progress = Number(raised) / 6000e18; // 6,000 ZRO moves it to a pool
const price = await client.readContract({ address: LAUNCHPAD, abi: PAD, functionName: 'priceOf', args: [token] }); // wei per whole token
const marketCap = (Number(price) / 1e18) * (Number(supply) / 1e18); // in ZRO
const buyFeeNow = await client.readContract({ address: LAUNCHPAD, abi: PAD, functionName: 'buyFeeBps', args: [token] });
// What this wallet pays through the router, with its rank taken off (all of Submarine's cut if it is fee-free), and the rank itself.
const myFee = await client.readContract({ address: LAUNCHPAD, abi: PAD, functionName: 'buyFeeBpsFor', args: [token, wallet.account.address] });
const volume = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'volumeOf', args: [wallet.account.address] }); // ZRO, in wei
const rank = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'rankOf', args: [wallet.account.address] }); // 0 Starter to 5 Legend
const feeFree = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'isFeeFree', args: [wallet.account.address] });Claim fees and rewards
// A creator's share, from every token they launched.
await wallet.writeContract({ address: LAUNCHPAD, abi: PAD, functionName: 'claimCreatorFees' });
// A holder's rewards, on a token that pays its holders.
const HOLDER = parseAbi(['function rewardOf(address) view returns (uint256)', 'function claim()', 'function claimFor(address)']);
const due = await client.readContract({ address: token, abi: HOLDER, functionName: 'rewardOf', args: [wallet.account.address] });
if (due > 0n) await wallet.writeContract({ address: token, abi: HOLDER, functionName: 'claim' });Lower your fee
// From the wallet that launched the token: your own fee on top of the 1% base, lowered to 100 bps, so 2% in all. It can never go back up.
await wallet.writeContract({ address: LAUNCHPAD, abi: PAD, functionName: 'lowerFee', args: [token, 100] });devFeeBps must be below the own fee now, or the call reverts with FeeNotLower; anyone but the creator gets NotCreator. It emits FeeLowered, and on a graduated token the pool's own FeeLowered too.
Place an order
const LIMITS = parseAbi([
'function placeBuy(address token, uint256 minOut, uint40 expiry) payable returns (uint256)',
'function placeSellLegs(address token, uint256 amount, uint40 expiry, (uint8 kind, uint128 share, uint128 minOut, uint128 trigger, uint16 trailBps)[] legs) returns (uint256)',
'function runFee() view returns (uint256)',
]);
// Buy 200 ZRO of tokens once 200 ZRO (less the run fee) gets at least 10 million tokens, within a day.
const expiry = Math.floor(Date.now() / 1000) + 86400;
await wallet.writeContract({
address: deployment.limitOrders, abi: LIMITS, functionName: 'placeBuy',
args: [token, parseEther('10000000'), expiry], value: parseEther('200'),
});
// One escrow, two ways out: half at double the value, all of it at a 40% loss.
const amount = parseEther('1000000');
const value = await client.readContract({ address: ROUTER, abi: ROUTER_ABI, functionName: 'quoteSell', args: [token, amount] });
await wallet.writeContract({
address: deployment.limitOrders, abi: LIMITS, functionName: 'placeSellLegs',
args: [token, amount, 0, [
{ kind: 0, share: amount / 2n, minOut: value, trigger: 0n, trailBps: 0 }, // LIMIT: half at 2x
{ kind: 1, share: amount, minOut: (value * 3n) / 10n, trigger: (value * 6n) / 10n, trailBps: 0 }, // STOP at -40%, never below -70%
]],
});The minimum of a limit order is after every fee and the run fee. See Limit orders and automation for what each kind means.
Link a referrer
const REF = parseAbi(['function link(address referrer)', 'function claim()', 'function earned(address) view returns (uint256)']);
await wallet.writeContract({ address: deployment.referrals, abi: REF, functionName: 'link', args: [REFERRER] });When a call reverts
| Error | Usually means |
|---|---|
Slippage | The price moved past your minimum. Quote again |
Expired | The deadline passed before the transaction landed |
AlreadyGraduated | Selling on the curve after it moved to a pool. Trade through the router instead |
NoRoute | No venue can trade this token |
BadMetadata | Name, symbol or uri too long or empty |
BadTerms | Supply, own fee or shares out of range, or shares set with no own fee |
WrongLaunchFee | value is below launchFee() |
BadOrder | An order's amount, minimum, expiry or legs are out of range |
BoughtThisBlock | The wallet got these coins from the market in this block. Try again from the next one |
MaxWallet | The token's max wallet is still on, and this would leave the receiving wallet above it |
BadPartner | The partner is the trader, the router or zero, or kind isn't 1 or 2 |
FeeNotLower, NotCreator | lowerFee with a fee that isn't lower, or from a wallet that didn't launch the token |
Every function and error is on the contract reference.