How to clone Uniswap V2: deploy the contracts and run the frontend

GoldRush TeamUpdated 17 min read

Fork Uniswap V2 on Sepolia: deploy WETH9, the Factory and Router02 in Remix, set the init code hash, point the V2 SDK and interface at them, and read your pair.

To clone Uniswap V2 you deploy four contracts, WETH9, UniswapV2Factory, UniswapV2Router02 and Multicall, then point a copy of the Uniswap V2 SDK and the old V2 web interface at their addresses. The one step people get wrong is the init code hash: the router computes pair addresses from a hash of the pair contract's bytecode, and your compiled pair never has the same hash as Uniswap's, so you have to read yours from the factory and paste it into the router before deploying it.

This guide does the whole thing on the Sepolia testnet: how V2's contracts fit together, deploying them in Remix, the frontend, and reading your pair's swaps and reserves back with the GoldRush DEX API. Allow about an hour for the contracts and another for the frontend.

What you need to clone Uniswap V2

  • MetaMask (or another injected wallet) on Sepolia, with some Sepolia ETH from a faucet for gas.
  • Remix in your browser. No Hardhat or Foundry project is needed.
  • Some Solidity: you'll read the contracts, not write them.
  • For the frontend: Git, nvm, Node.js 14 and Yarn 1. The V2 interface is a 2020 Create React App project and expects that toolchain.
  • For reading your pair's data: Node.js 18 or later and a GoldRush API key in the GOLDRUSH_API_KEY environment variable. The script is one ES module file, pair-activity.mjs (the .mjs extension lets it use top-level await).

How Uniswap V2 works

Uniswap V2 is an automated market maker (AMM). Instead of an order book, each pair contract holds reserves of two ERC-20 tokens and prices every trade with the constant product rule, x * y = k: after a swap (and its 0.30% fee), the product of the two reserves must not go down. Liquidity providers deposit both tokens and get LP tokens back; traders swap against the reserves.

V2 replaced Uniswap V1, and the differences are why most forks start from V2:

Uniswap V1 Uniswap V2
Written in Vyper Written in Solidity
Every pool is a token/ETH pool; token to token is 2 hops Any ERC-20/ERC-20 pair; ETH is wrapped as WETH
No price oracle Time-weighted price accumulators other contracts can read
No flash swaps Flash swaps: take tokens out first, pay or return them in the same transaction
No protocol fee A protocol fee switch (feeTo) that takes 0.05% of the 0.30% fee when it's turned on

The Uniswap V2 whitepaper and V2 docs cover each of these in depth.

Core vs periphery

V2's contracts are split in two. The core (v2-core) holds the funds and enforces the rules, and is deliberately minimal:

  • UniswapV2Factory creates pairs. createPair(tokenA, tokenB) deploys one pair per token pair with CREATE2, records it in getPair and allPairs, and emits PairCreated. It also holds feeTo and feeToSetter, which control the protocol fee.
  • UniswapV2Pair is the pool: it holds the reserves, mints and burns LP tokens (mint, burn), executes swap, and emits Mint, Burn, Swap and Sync.
  • UniswapV2ERC20 is the LP token every pair inherits, an ERC-20 with permit for gasless approvals.

The periphery (v2-periphery) is what users and apps call. It holds no funds between transactions, so it can be replaced:

  • UniswapV2Router02 adds and removes liquidity and swaps along multi-hop paths, with slippage limits and deadlines, and wraps ETH to WETH for you. Use Router02; Router01 has a bug in some of its functions and should not be deployed.
  • UniswapV2Library is the router's maths: sorting tokens, computing a pair's address (pairFor), and quoting swap amounts.
  • UniswapV2Migrator moved liquidity from V1 to V2. A clone has no V1, so skip it.

Why clone V2 and not V3 or V4

V3 (2021) added concentrated liquidity, where each position covers a price range, and V4 (launched January 2025) moved every pool into one singleton contract and added hooks, flash accounting and native ETH pairs. Both are far more complex to deploy and run. V2's model is what most AMM forks, SushiSwap among them, are built on, its code is GPL-licensed, and once you understand it, V3's and V4's designs are easier to follow.

Step 1: get the contracts

Uniswap's V2 code is split across two repositories with npm dependencies. To deploy from Remix, use a flattened copy: Sayrarh/UniswapV2-Tutorial at commit a7c3b2a, which this guide's steps are written against, puts each part in one file under contracts/. It is a personal repository, not Uniswap's, and it hasn't been audited: compare it with v2-core and v2-periphery before anything holds real funds.

File What's in it Compiler
Core.sol UniswapV2ERC20, UniswapV2Pair, UniswapV2Factory, their interfaces, SafeMath, Math, UQ112x112 0.5.16
Router.sol UniswapV2Router02, its interfaces, UniswapV2Library, TransferHelper 0.6.6
Weth9.sol WETH9, the wrapped-ETH token the router uses for ETH pairs ^0.4.18
Multicall.sol Multicall, which batches read calls; the frontend needs it >=0.5.0

The factory in this copy adds one line that Uniswap's original doesn't have, a public constant you'll need in step 3:

bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(UniswapV2Pair).creationCode));

Create the four files in a Remix workspace (or upload the repository). Each file pins its own compiler version, so set the matching version in the Solidity compiler tab before compiling each one. At that commit, all four compile without errors with solc 0.5.16 (Core.sol, Multicall.sol), 0.6.6 (Router.sol) and 0.4.18 (Weth9.sol); we checked with the npm solc compiler on 22 November 2026, not in Remix.

Step 2: deploy WETH9 and the factory

In Remix's Deploy & run transactions tab, set the environment to Injected Provider - MetaMask and check that MetaMask is on Sepolia.

  1. WETH9. Compile Weth9.sol and deploy WETH9. It takes no constructor arguments. Copy its address. Sepolia already has WETH contracts, but deploying your own keeps the example self-contained; what matters is that the router and the frontend use the same WETH address.
  2. UniswapV2Factory. Compile Core.sol and deploy UniswapV2Factory with one argument, _feeToSetter: the address allowed to turn the protocol fee on and change who can. Use your own wallet address. Copy the factory's address.

Confirm each transaction in MetaMask. Both contracts appear under Deployed Contracts, where you can call their functions, and on Sepolia Etherscan.

The factory's functions you'll use:

Function What it does
createPair(tokenA, tokenB) Deploys the pair for two tokens, if it doesn't exist yet
getPair(tokenA, tokenB) The pair's address, or the zero address if there isn't one
allPairs(i), allPairsLength() Every pair the factory has created, by index
setFeeTo(address), feeTo() Turns the protocol fee on (any non-zero address receives it) or off
setFeeToSetter(address) Hands control of the fee to another address
INIT_CODE_PAIR_HASH() The hash of the pair's creation code (this copy only)

Step 3: set the init code hash

Pairs are deployed with CREATE2, so a pair's address is a function of the factory's address, the two token addresses and the hash of the pair contract's creation code. The router never asks the factory where a pair is: UniswapV2Library.pairFor computes it. If the hash in pairFor isn't your pair's hash, every router call computes an address where no pair exists and fails.

The hash depends on the exact bytecode, which changes with the compiler version and optimizer settings, and with any edit to the pair contract. So read it from your own factory:

  1. Under Deployed Contracts, call INIT_CODE_PAIR_HASH on your factory. It returns a 0x… value.
  2. In Router.sol, find pairFor in UniswapV2Library and replace the hash inside hex"…" with yours, without the 0x prefix:
pair = address(    uint(        keccak256(            abi.encodePacked(                hex"ff",                factory,                keccak256(abi.encodePacked(token0, token1)),                hex"<your INIT_CODE_PAIR_HASH without 0x>" // init code hash            )        )    ));

Keep the value: the SDK needs it too, with the 0x.

Step 4: deploy Router02 and Multicall

  1. UniswapV2Router02. Compile Router.sol. Without the optimizer the router is larger than the 24,576-byte contract size limit (EIP-170) and the deployment fails, so in the compiler tab's advanced configuration turn Enable optimization on before compiling. Compiled with solc 0.6.6, UniswapV2Router02's deployed code was 26,887 bytes without the optimizer and 17,891 bytes with it (200 runs). Deploy UniswapV2Router02 with _factory (your factory's address) and _WETH (your WETH9's address).
  2. Multicall. Compile and deploy Multicall.sol. It takes no arguments. The frontend uses it to batch its balance and reserve reads.

You now have four addresses: WETH9, factory, router and Multicall. Note the block your first pair is created in, too: step 5 creates it, and the GoldRush code at the end reads from that block.

Step 5: create a pair and add liquidity

Deploy two ERC-20 test tokens (any OpenZeppelin ERC-20 with a minted supply will do), then:

  1. Call approve(router, amount) on each token, so the router can move them.
  2. Call addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline) on the router. If the pair doesn't exist, the router asks the factory to create it, then deposits both tokens and mints LP tokens to to. deadline is a Unix timestamp in seconds.
  3. For a token/ETH pair, use addLiquidityETH and send the ETH as the transaction value; the router wraps it in your WETH9.
  4. Swap with swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline), where path is [tokenIn, tokenOut], or a longer path to route through other pairs.

Call getPair(tokenA, tokenB) on the factory to get the pair's address, and getReserves() on the pair to see the balances move. If addLiquidity reverts, the usual cause is a wrong init code hash (step 3) or a missing approval.

Clone the frontend

The V2 web interface talks to the contracts through the V2 SDK, which hard-codes Uniswap's factory address, init code hash and chain list. So you rebuild the SDK with your values, then point the interface at your SDK and your router. Both live in Uniswap's GitHub history, pinned to the versions the V2 interface was built against:

Repository Version
Uniswap/v2-sdk commit 00a1eca (@uniswap/sdk 3.0.2)
Uniswap/interface tag v2.6.4

Put them side by side in one folder, and use Node 14:

mkdir uniswap-v2-clone && cd uniswap-v2-clonenvm install 14.21.3 && nvm use 14.21.3npm install -g yarn@1.22.22 git clone https://github.com/Uniswap/v2-sdk.git v2-sdkgit -C v2-sdk checkout 00a1eca9456d37c3d467f56e57a0496d1bf28e40 git clone --branch v2.6.4 --depth 1 https://github.com/Uniswap/interface.git interface

A tip before editing: the SDK's ChainId is an enum, and the interface types many objects as { [chainId in ChainId]: … }. Once you add Sepolia to the enum, TypeScript requires an entry for it in every one of those objects, so the compiler errors double as the checklist below.

Rebuild the SDK with your contracts

In v2-sdk/src/constants.ts, add your chain to ChainId and replace the factory address and init code hash with yours (the hash keeps its 0x here):

export enum ChainId {    MAINNET = 1,    ROPSTEN = 3,    RINKEBY = 4,    GÖRLI = 5,    KOVAN = 42,    SEPOLIA = 11155111,} export const FACTORY_ADDRESS = "0xYourFactoryAddress"; export const INIT_CODE_HASH = "0xYourInitCodePairHash";

In v2-sdk/src/entities/token.ts, add your WETH9 to the WETH map:

  [ChainId.SEPOLIA]: new Token(ChainId.SEPOLIA, '0xYourWeth9Address', 18, 'WETH', 'Wrapped Ether')

v2-sdk/src/entities/currency.ts defines the native currency as new Currency(18, 'ETH', 'Ether'). Sepolia's native token is ETH, so leave it. On a chain with another native token, change the symbol, name and decimals there: on Polygon, for example, new Currency(18, 'POL', 'Polygon Ecosystem Token').

Then install and build. The build writes the package to dist/:

cd v2-sdkyarnyarn buildcd ..

Point the interface at your SDK and router

  1. package.json. Under devDependencies, change "@uniswap/sdk" to "file:../v2-sdk", then run yarn in interface/. The two folders must stay side by side.
  2. .env. The interface reads its default network from REACT_APP_CHAIN_ID and REACT_APP_NETWORK_URL. Set them to "11155111" and a Sepolia RPC URL, or it keeps reading from mainnet before a wallet connects.
  3. src/constants/index.ts. Set ROUTER_ADDRESS to your Router02, and add [ChainId.SEPOLIA]: [WETH[ChainId.SEPOLIA]] to WETH_ONLY.
  4. src/connectors/index.ts. Add 11155111 to supportedChainIds in the injected connector (or replace the list with it, to support Sepolia only). Change appName if you like.
  5. src/constants/multicall/index.ts. Add [ChainId.SEPOLIA]: '0xYourMulticallAddress' to MULTICALL_NETWORKS.
  6. src/components/Header/index.tsx. Add [ChainId.SEPOLIA]: 'Sepolia' to NETWORK_LABELS, the badge shown next to the wallet.
  7. src/constants/v1/index.ts. V1_FACTORY_ADDRESSES needs an entry for every chain. Your chain has no Uniswap V1, so add [ChainId.SEPOLIA] with a placeholder; the original version of this guide used your V2 factory's address.
  8. src/state/lists/hooks.ts. Add [ChainId.SEPOLIA]: {} to EMPTY_LIST.
  9. src/utils/index.ts. Add 11155111: 'sepolia.' to ETHERSCAN_PREFIXES, so transaction links go to sepolia.etherscan.io.

Start it:

cd interfaceyarn start

Open the local URL it prints, switch MetaMask to Sepolia, click Connect to a wallet and choose MetaMask. It should connect without a "wrong network" error, show the Sepolia badge, and let you import your test tokens by address, add liquidity and swap through your router.

Make it look like yours

All three of these are in src/components/Header/index.tsx:

  • Logo. Lines 8 to 11 import logo.svg, logo_white.svg, wordmark.svg and wordmark_white.svg from src/assets/svg/. Replace those files, or change the import paths and keep the import names.
  • Native token symbol. The wallet balance is rendered as {userEthBalance?.toSignificant(4)} ETH (line 164). On a chain whose native token isn't ETH, change ETH, for example to POL on Polygon.
  • Version switch. The V1/V2 toggle is pointless without a V1. Remove the VersionSwitch import and the <VersionSwitch /> element.

Read your pair's swaps and reserves

A DEX needs data beyond its own UI: a trade history, volume, a chart of reserves. You could index your pair's events yourself; the GoldRush log events by contract address endpoint (part of the GoldRush Foundational API) already returns every event a contract has emitted, on Sepolia as on mainnet. It costs 0.01 per item.

A clone's pair emits the same events as Uniswap's, with the same topics, so this script decodes them from the raw topics and data itself; it doesn't depend on GoldRush recognising your contract. Every change to the reserves ends with a Sync event, so the last Sync holds the current reserves:

// pair-activity.mjs: every Swap, Mint, Burn and Sync your Uniswap V2 pair has emitted, and its current reserves.// Usage: GOLDRUSH_API_KEY=... node pair-activity.mjs <pair address> <block the pair was created in> [chain]const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; // topic0 of each UniswapV2Pair event: keccak256 of its signature. A clone emits the same events, so the same topics.const TOPICS = {    "0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822": "Swap", // Swap(address,uint256,uint256,uint256,uint256,address)    "0x4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f": "Mint", // Mint(address,uint256,uint256)    "0xdccd412f0b1252819cb1fd330b93224ca42612892bb3f4f789976e6d81936496": "Burn", // Burn(address,uint256,uint256,address)    "0x1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1": "Sync", // Sync(uint112,uint112)}; // The n-th 32-byte word of the log's data, and an address from an indexed topic.const word = (data, n) => BigInt(`0x${data.slice(2 + 64 * n, 66 + 64 * n)}`);const address = (topic) => `0x${topic.slice(26)}`; // All log events the pair emitted from fromBlock on, one page at a time.async function getPairLogs(chain, pair, fromBlock) {    const logs = [];    for (let page = 0; ; page++) {        const url =            `${API}/${chain}/events/address/${pair}/` +            `?starting-block=${fromBlock}&ending-block=latest&page-size=100&page-number=${page}`;        const res = await fetch(url, { headers });        if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);        const { data } = await res.json();        logs.push(...data.items);        if (!data.pagination?.has_more) return logs;    }} // Decode a pair event from its raw topics and data, so it works for any clone, verified or not.function decode(log) {    const [topic0, topic1, topic2] = log.raw_log_topics;    const name = TOPICS[topic0];    const data = log.raw_log_data ?? "0x";    const base = { name, block: log.block_height, time: log.block_signed_at, tx: log.tx_hash };    switch (name) {        case "Swap":            return {                ...base,                sender: address(topic1),                to: address(topic2),                amount0In: word(data, 0),                amount1In: word(data, 1),                amount0Out: word(data, 2),                amount1Out: word(data, 3),            };        case "Mint":            return { ...base, sender: address(topic1), amount0: word(data, 0), amount1: word(data, 1) };        case "Burn":            return {                ...base,                sender: address(topic1),                to: address(topic2),                amount0: word(data, 0),                amount1: word(data, 1),            };        case "Sync":            return { ...base, reserve0: word(data, 0), reserve1: word(data, 1) };        default:            return null; // Transfer and Approval of the LP token itself    }} const [pair, fromBlock, chain = "eth-sepolia"] = process.argv.slice(2);const events = (await getPairLogs(chain, pair, fromBlock))    .sort((a, b) => a.block_height - b.block_height || a.log_offset - b.log_offset)    .map(decode)    .filter(Boolean); const count = (name) => events.filter((e) => e.name === name).length;console.log(`${count("Swap")} swaps, ${count("Mint")} adds, ${count("Burn")} removes`); // Every change to the reserves ends with a Sync, so the last Sync holds the current reserves.const last = events.findLast((e) => e.name === "Sync");if (last) console.log(`reserves at block ${last.block}: ${last.reserve0} token0, ${last.reserve1} token1 (raw units)`);for (const e of events.filter((e) => e.name === "Swap").slice(-3)) {    console.log(`${e.time} swap: in ${e.amount0In}/${e.amount1In}, out ${e.amount0Out}/${e.amount1Out} -> ${e.to}`);}

Run it with your pair's address and the block step 5 created it in. Reserves and amounts are in each token's smallest unit: divide by 10 ** decimals to display them. token0 is whichever of the two token addresses sorts lower, which you can confirm with token0() on the pair. The same endpoint on your factory's address returns its PairCreated events, one per pair, if you want to list them all.

When your DEX goes to mainnet, the GoldRush DEX pool spot price endpoint returns a Uniswap V2 or V3 pool's (or fork's) two tokens with each one's price in the other and in USD, on Ethereum, Polygon, Base, Optimism, BNB Smart Chain (BSC) and Gnosis, for 1 per call. It doesn't cover testnets, so on Sepolia the Sync events above are the way to get the price. On a mainnet, add this to the end of pair-activity.mjs (it reuses API, headers, chain and pair from the script):

// The pair's two tokens and their prices, from the DEX pool spot price endpoint (mainnets only).const res = await fetch(`${API}/pricing/spot_prices/${chain}/pools/${pair}/?quote-currency=USD`, { headers });if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);const [pool] = (await res.json()).data;console.log(`1 ${pool.token_0_ticker} = ${pool.token_0_price} ${pool.token_1_ticker} ($${pool.token_0_price_quote})`);

Handle errors from the GoldRush log events endpoint

When a request fails, the API answers with a non-2xx status and the same envelope as a success, with data set to null. The docs show this body for a chain name it doesn't recognize, with HTTP status 501:

{    "data": null,    "error": true,    "error_message": "Chain nosuchchain-mainnet not supported.",    "error_code": 501}

getPairLogs throws the status and the body, so the script stops with 501 {"data":null,"error":true,…}. error_code always equals the HTTP status, and error_message says what went wrong:

  • 501: the chain name passed as the third argument (such as eth-sepolia) is misspelled or not supported. The same request keeps returning 501.
  • 401: the API key is missing or wrong. A request with no Authorization header at all gets an HTML 401 page instead of JSON, which is why the script reads the body as text before throwing.
  • 429 or a 5xx: rate limit or a busy backend. Retry after a pause, with backoff.

Failed requests cost no credits. The error handling page lists every code and what to do about it.

Customize your Uniswap V2 fork

A working fork is mostly renaming and a few deliberate changes:

  • Names. Rename the contracts, the LP token's name and symbol in UniswapV2ERC20 (Uniswap V2, UNI-V2), and the interface's branding. Any change to the pair contract changes its bytecode, so repeat step 3 and update the SDK's INIT_CODE_HASH afterwards.
  • The swap fee. 0.30% is hard-coded in three places: the pair's invariant check in swap (balance0.mul(1000).sub(amount0In.mul(3))), getAmountOut and getAmountIn in UniswapV2Library (997), and the SDK's pair maths. Change all three together, or the router's quotes will fail the pair's check.
  • The protocol fee. Call setFeeTo from the feeToSetter address to send a share of fees to a treasury.
  • Security. V2's code is battle-tested, but your changes aren't. Get any modified contract audited before it holds real funds, and test against the known V2 pitfalls (tokens with transfer fees, rebasing tokens, price manipulation of the spot price).

Frequently asked questions

Can I clone Uniswap V2 on chains other than Ethereum?

Yes. The contracts run on any EVM chain. Deploy the same four contracts there, then use that chain's ID in the SDK's ChainId, WETH, the interface's connectors and every other place listed above, and change the native currency in currency.ts and the header if it isn't ETH (for example POL on Polygon). Use the chain's wrapped native token, or your own WETH9 deployment, as the router's WETH.

What is INIT_CODE_PAIR_HASH and why does my clone fail without it?

It's the keccak256 hash of the pair contract's creation code. Pairs are deployed with CREATE2, and the router computes each pair's address from the factory address, the two tokens and this hash instead of looking it up. Your compiled pair has a different hash from Uniswap's, so with Uniswap's hash in pairFor the router computes addresses with no contract behind them and addLiquidity and swaps revert. Read the hash from your factory and put it in the router (without 0x) and in the SDK's INIT_CODE_HASH (with 0x).

Why does Router02 fail to deploy in Remix?

Without the optimizer, UniswapV2Router02 compiles to more than the 24,576-byte contract size limit, and the deployment fails. Turn on Enable optimization in the Solidity compiler tab's advanced configuration, recompile and deploy again.

Should I use the latest Uniswap interface instead of v2.6.4?

Not for a V2 clone. The current interface is built around Uniswap's later protocols and its own deployments; v2.6.4 is the release built for V2 alone with @uniswap/sdk 3.x, and its configuration is a handful of constants. The trade-off is its age: it needs Node 14, and you should expect to update dependencies if you plan to run it in production.

How do I get trade history and reserves for my Uniswap V2 clone?

Read the pair's events. Every swap emits Swap and every reserve change ends with Sync, so a pair's event log is its full history. The GoldRush log events by contract address endpoint returns them for a contract on any supported chain, including Sepolia, and the script above decodes them into swaps, liquidity adds and removes, and current reserves. On a mainnet the DEX pool spot price endpoint also returns the pair's current prices directly.

Next steps

Get new guides by email

New tutorials and best practices for building with blockchain data, sent as they're published.