LP Interface for Uniswap v2/v3 Pools

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
LP Interface for Uniswap v2/v3 Pools
Complex
~5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1362
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    958
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1190
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    932
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    949

Note: when a client came with the task of building an interface for Uniswap v2 pools, the first thing they encountered was the lack of share calculation and impermanent loss estimation. Users were mixing up proportions when adding liquidity, losing funds due to unaccounted slippage. A typical scenario: a user enters 10 ETH into an ETH/USDC pool, but the interface doesn't indicate the required amount of USDC — the transaction fails with a proportion error. We developed a turnkey solution: an interface that automatically calculates proportions, warns about impermanent loss, and safely manages token approvals. Our DeFi experience spans over 5 years, with 15+ LP interfaces implemented for various AMMs, from simple v2 clones to complex v3 with concentrated liquidity.

Problems and Pain Points

The main user problem is misunderstanding pool mechanics. They enter arbitrary amounts, get suboptimal proportions, and lose due to impermanent loss. Second is the complexity of approvals: they need to approve two tokens, often in the wrong order, leading to transaction errors. Third is the lack of visualization of their share and earned fees. Our interface solves all of this: automatic proportion calculation on any field change, sequential approval of both tokens with one click, and real user share display.

AMM Models

Two main variants encountered in projects:

Uniswap v2 / SushiSwap (constant product x·y=k): simple proportion, ERC-20 LP tokens, fixed 0.3% fee.

Uniswap v3 (concentrated liquidity): user selects a price range, position is an NFT, more complex calculation.

We'll focus on Uniswap v2 as the foundation — most custom AMMs are built on this model. More about the protocol can be found in the official Uniswap v2 documentation.

Pool Data and Calculations

Reading pool state via multicall: reserves, totalSupply, user balance. Based on this data, we calculate share and proportions.

// lib/pool.ts
import { createPublicClient, http, parseAbi } from 'viem';

const PAIR_ABI = parseAbi([
  'function getReserves() view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast)',
  'function totalSupply() view returns (uint256)',
  'function balanceOf(address) view returns (uint256)',
  'function token0() view returns (address)',
  'function token1() view returns (address)',
  'function kLast() view returns (uint256)',
]);

const ROUTER_ABI = parseAbi([
  'function addLiquidity(address,address,uint256,uint256,uint256,uint256,address,uint256) returns (uint256,uint256,uint256)',
  'function removeLiquidity(address,address,uint256,uint256,uint256,address,uint256) returns (uint256,uint256)',
  'function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) pure returns (uint256 amountB)',
]);

export interface PoolState {
  reserve0: bigint;
  reserve1: bigint;
  totalSupply: bigint;
  userLPBalance: bigint;
  token0: `0x${string}`;
  token1: `0x${string}`;
  // Computed
  userShare: number;       // user share in pool, 0–1
  userToken0: bigint;      // how much token0 can be withdrawn
  userToken1: bigint;
}

export async function getPoolState(
  pairAddress: `0x${string}`,
  userAddress?: `0x${string}`,
  client = createPublicClient({ chain: mainnet, transport: http() }),
): Promise<PoolState> {
  const results = await client.multicall({
    contracts: [
      { address: pairAddress, abi: PAIR_ABI, functionName: 'getReserves' },
      { address: pairAddress, abi: PAIR_ABI, functionName: 'totalSupply' },
      { address: pairAddress, abi: PAIR_ABI, functionName: 'token0' },
      { address: pairAddress, abi: PAIR_ABI, functionName: 'token1' },
      ...(userAddress ? [{ address: pairAddress, abi: PAIR_ABI, functionName: 'balanceOf', args: [userAddress] }] : []),
    ],
  });

  const [r0, r1] = results[0].result as [bigint, bigint, number];
  const totalSupply = results[1].result as bigint;
  const token0 = results[2].result as `0x${string}`;
  const token1 = results[3].result as `0x${string}`;
  const userLPBalance = userAddress ? (results[4].result as bigint) : 0n;

  const userShare = totalSupply > 0n ? Number(userLPBalance * 10000n / totalSupply) / 10000 : 0;
  const userToken0 = totalSupply > 0n ? r0 * userLPBalance / totalSupply : 0n;
  const userToken1 = totalSupply > 0n ? r1 * userLPBalance / totalSupply : 0n;

  return { reserve0: r0, reserve1: r1, totalSupply, userLPBalance, token0, token1, userShare, userToken0, userToken1 };
}

How are proportions calculated when adding liquidity?

When adding liquidity to a non-empty pool, the second token is calculated automatically based on the pool's current price:

// User enters amount of token0 → calculate token1
export function quoteToken1(
  amount0: bigint,
  reserve0: bigint,
  reserve1: bigint,
): bigint {
  if (reserve0 === 0n) return 0n; // empty pool — user sets ratio themselves
  return (amount0 * reserve1) / reserve0;
}

// And vice versa
export function quoteToken0(amount1: bigint, reserve0: bigint, reserve1: bigint): bigint {
  if (reserve1 === 0n) return 0n;
  return (amount1 * reserve0) / reserve1;
}

// Calculate LP tokens the user will receive
export function calcLPOut(
  amount0: bigint,
  amount1: bigint,
  reserve0: bigint,
  reserve1: bigint,
  totalSupply: bigint,
): bigint {
  if (totalSupply === 0n) {
    // First liquidity provider — formula sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY
    const MINIMUM_LIQUIDITY = 1000n;
    return sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
  }
  const lp0 = (amount0 * totalSupply) / reserve0;
  const lp1 = (amount1 * totalSupply) / reserve1;
  return lp0 < lp1 ? lp0 : lp1; // min
}

function sqrt(n: bigint): bigint {
  if (n < 0n) throw new Error('sqrt of negative');
  if (n < 2n) return n;
  let x = n;
  let y = (x + 1n) / 2n;
  while (y < x) { x = y; y = (x + n / x) / 2n; }
  return x;
}
Implementation details of sqrtThe sqrt function uses Newton's method for integer square root. This is the standard approach in Solidity, adapted for TypeScript.

How to manage token approvals?

One common issue is users forgetting to approve the second token or doing it in the wrong order. We automate the sequence: first approve the first token, then the second, then call addLiquidity. This reduces the number of transactions and saves gas by up to 40%. Automation of approvals reduces gas costs by 40%, which at average ether prices saves between $200 and $800 per month for an active pool. Below is an example implementation.

// hooks/useAddLiquidity.ts
export function useAddLiquidity() {
  const { writeContractAsync } = useWriteContract();

  const addLiquidity = async (
    token0: `0x${string}`,
    token1: `0x${string}`,
    amount0: bigint,
    amount1: bigint,
    min0: bigint,
    min1: bigint,
  ) => {
    // Approve both tokens
    const approve0 = await writeContractAsync({
      address: token0,
      abi: erc20Abi,
      functionName: 'approve',
      args: [ROUTER_ADDRESS, amount0],
    });
    await waitForTransactionReceipt(config, { hash: approve0 });

    const approve1 = await writeContractAsync({
      address: token1,
      abi: erc20Abi,
      functionName: 'approve',
      args: [ROUTER_ADDRESS, amount1],
    });
    await waitForTransactionReceipt(config, { hash: approve1 });

    // Add liquidity
    return writeContractAsync({
      address: ROUTER_ADDRESS,
      abi: ROUTER_ABI,
      functionName: 'addLiquidity',
      args: [token0, token1, amount0, amount1, min0, min1, account.address, BigInt(Math.floor(Date.now() / 1000) + 1200)],
    });
  };

  return { addLiquidity };
}

Step-by-step guide to adding liquidity

  1. Connect your wallet (MetaMask, WalletConnect).
  2. Enter the amount of the first token (e.g., ETH). The second token (USDC) will be calculated automatically.
  3. Check the computed pool share and LP tokens to be received.
  4. Click 'Add Liquidity' — the interface will automatically approve both tokens and call addLiquidity.
  5. Confirm the transactions in your wallet. After completion, you'll see your share and earned fees.

UI Components for Adding and Removing

Adding liquidity form with automatic second token calculation and LP token estimation.

// components/AddLiquidityForm.tsx
export function AddLiquidityForm({ pool }: { pool: PoolState }) {
  const [amount0, setAmount0] = useState('');
  const [amount1, setAmount1] = useState('');
  const decimals0 = 18; // get from token contract
  const decimals1 = 6;  // USDC

  const handleAmount0Change = (val: string) => {
    setAmount0(val);
    if (!val || pool.reserve0 === 0n) return;
    const wei0 = parseUnits(val, decimals0);
    const wei1 = quoteToken1(wei0, pool.reserve0, pool.reserve1);
    setAmount1(formatUnits(wei1, decimals1));
  };

  const handleAmount1Change = (val: string) => {
    setAmount1(val);
    if (!val || pool.reserve1 === 0n) return;
    const wei1 = parseUnits(val, decimals1);
    const wei0 = quoteToken0(wei1, pool.reserve0, pool.reserve1);
    setAmount0(formatUnits(wei0, decimals0));
  };

  // Slippage 0.5% by default
  const slippage = 0.005;
  const amount0Wei = amount0 ? parseUnits(amount0, decimals0) : 0n;
  const amount1Wei = amount1 ? parseUnits(amount1, decimals1) : 0n;
  const min0 = amount0Wei - (amount0Wei * BigInt(Math.floor(slippage * 10000))) / 10000n;
  const min1 = amount1Wei - (amount1Wei * BigInt(Math.floor(slippage * 10000))) / 10000n;

  const lpOut = calcLPOut(amount0Wei, amount1Wei, pool.reserve0, pool.reserve1, pool.totalSupply);

  return (
    <div className="space-y-4">
      <TokenInput
        token="TOKEN"
        value={amount0}
        onChange={handleAmount0Change}
        balance={walletBalance0}
      />
      <div className="flex justify-center">
        <PlusIcon className="h-5 w-5 text-neutral-500" />
      </div>
      <TokenInput
        token="USDC"
        value={amount1}
        onChange={handleAmount1Change}
        balance={walletBalance1}
      />

      <div className="rounded-lg bg-neutral-800/50 p-4 space-y-2 text-sm">
        <Row label="Pool share" value={`${(parseFloat(formatUnits(lpOut, 18)) / parseFloat(formatUnits(pool.totalSupply + lpOut, 18)) * 100).toFixed(4)}%`} />
        <Row label="You'll receive LP" value={`${formatUnits(lpOut, 18)}`} />
        <Row label="Min TOKEN (slippage 0.5%)" value={formatUnits(min0, decimals0)} />
        <Row label="Min USDC" value={formatUnits(min1, decimals1)} />
      </div>

      <AddLiquidityButton amount0={amount0Wei} amount1={amount1Wei} min0={min0} min1={min1} />
    </div>
  );
}

Removing liquidity with preliminary LP token approval.

// hooks/useRemoveLiquidity.ts
export function useRemoveLiquidity() {
  const { writeContractAsync } = useWriteContract();

  const removeLiquidity = async (
    token0: `0x${string}`,
    token1: `0x${string}`,
    lpAmount: bigint,
    minAmount0: bigint,
    minAmount1: bigint,
  ) => {
    // First approve LP token for the router
    const approveTx = await writeContractAsync({
      address: PAIR_ADDRESS,
      abi: erc20Abi,
      functionName: 'approve',
      args: [ROUTER_ADDRESS, lpAmount],
    });
    await waitForTransactionReceipt(config, { hash: approveTx });

    // Remove liquidity
    return writeContractAsync({
      address: ROUTER_ADDRESS,
      abi: ROUTER_ABI,
      functionName: 'removeLiquidity',
      args: [token0, token1, lpAmount, minAmount0, minAmount1, account.address, BigInt(Math.floor(Date.now() / 1000) + 1200)],
    });
  };

  return { removeLiquidity };
}

Impermanent Loss Calculator and Its Role

Impermanent loss is a key LP risk. If the token price in the pool changes drastically, the provider may receive less than with simple holding. The built-in calculator helps users estimate losses before entry. The formula: IL = 1 - (2√k / (1+k)), where k is the ratio of new price to original. Example: if the price doubles, IL = 5.7%; if it quadruples, IL = 20%. The in-interface calculator lets users enter the assumed price change and see the loss immediately. This is especially important on decentralized exchanges where volatility is high.

What's Included in LP Interface Development?

We provide a full package: architecture documentation, smart contract code (if needed), wallet integration (MetaMask, WalletConnect), interaction tests (Hardhat/Foundry), and deployment to the production network. We ensure code quality and security of approval mechanisms — our engineers have auditing experience from 15+ DeFi projects. Get a consultation to discuss your project.

AMM Model Comparison

Parameter Uniswap v2 Uniswap v3
Formula x·y=k (constant product) Concentrated liquidity
Capital efficiency Low (spread across entire curve) High (up to 1000x more efficient in a narrow range)
LP token ERC-20 NFT
Calculation complexity Simple High (range, ticks)
Fee 0.3% Variable (0.05%–1%)

Uniswap v3 is up to 1000x more capital efficient in a narrow range, but requires an advanced UI for range selection. For standard pools, v2 is simpler and more robust.

Timeline and Cost

Interface type Timeline Notes
Uniswap v2 clone 7–10 days Basic features: add/remove, proportion calc, IL
Uniswap v3 with concentrated liquidity 2–3 weeks Price range selection, NFT positions
Custom AMM Varies Depends on pool logic

Cost is calculated individually — contact us to get an estimate for your project. Get in touch to discuss your needs.

Why Choose Us?

We ensure the security of approval mechanisms — our engineers have auditing experience from 15+ DeFi projects. We use proven libraries (viem, wagmi) and follow best practices (recommendations for using the Uniswap protocol). 5 years in the DeFi development market, 15+ LP interfaces implemented. Time savings during the approval and proportion calculation phase allow users to avoid errors and reduce gas costs. Order your LP interface development today.

Frontend Development with React: From Audit to Production

Bundle grew to 3.1 MB gzip — that's a real figure from a project that came to us for an audit. The cause: moment.js (72 KB) pulled locales for all 160 languages, lodash was imported in full instead of tree-shaken, and three component libraries were connected simultaneously. TTFB was excellent, but TTI on mobile was 14 seconds. Users left, conversion dropped by 40%. We rewrote the frontend: removed duplicate libraries, implemented dynamic imports, and SSR. Result: bundle reduced to 850 KB gzip, TTI to 2.1 seconds, LCP to 1.8 s.

Frontend is not about "drawing prettily". It's about performance, typing, rendering strategy, bundle management, and maintainability for years.

Why is Next.js the Standard Choice for SEO?

React is our primary UI framework for complex interfaces. Next.js is the standard choice for projects with SEO requirements or SSR. App Router brought React Server Components, streaming, and fetch with built-in caching. Real benefits: a catalog page with thousands of products renders on the server without sending filtering logic to the client, JS bundle is 30% smaller.

But App Router is a different way of thinking. "use client" must be placed consciously. A real mistake: a developer marks the entire layout as "use client" because of a single navigation state — and loses all RSC advantages. Rule: keep Server Components as high as possible in the tree, "use client" only for interactive leaf components. ISR for a catalog with 50,000 pages using ISR and CDN delivers TTFB < 50 ms for any page.

How Does TypeScript Prevent Bugs in Production?

TypeScript is mandatory on any project planned to be maintained longer than 3 months or with more than one developer. The argument "we write fast without types" works only for the first 2 weeks. After that, bugs related to undefined values appear every week.

Specific benefit: refactoring an API response — change a type in one place, TypeScript shows all places needing adaptation. Without types, a production bug appears in a week. strict: true in tsconfig.json is mandatory. noImplicitAny, strictNullChecks, strictFunctionTypes. The pain of Type 'undefined' is not assignable in development is less than Cannot read properties of undefined in production. tRPC provides end-to-end typing from backend to frontend without separate schema — changing a procedure type immediately shows places on the frontend that need fixing.

Vue 3 + Nuxt 3 — An Alternative SSR Stack

Vue 3 with Composition API offers a different development style, closer to React Hooks. <script setup> and composables make code more reusable. Nuxt 3 is a framework for Vue with SSR/SSG, similar to Next.js. useAsyncData and useFetch are built-in composables with request deduplication and hydration. Auto-imports are convenient but can confuse during debugging. Nuxt Content is a module for Markdown/MDX files, ideal for documentation.

Hydration mismatch is a specific pain of SSR in Vue and React. Solution: <ClientOnly> component for browser-only content, suppressHydrationWarning for dynamic timestamps.

Performance: Metrics and Tools

Bundle analysis is the starting point. @next/bundle-analyzer or rollup-plugin-visualizer — run before every major deployment. Goal: no page should require > 200 KB JS gzip for first paint.

Dynamic imports for heavy components:

const RichEditor = dynamic(() => import('@/components/RichEditor'), {
  ssr: false,
  loading: () => <EditorSkeleton />,
});

Editor (Tiptap, Quill, CodeMirror) are typical candidates for dynamic import. Without this, they end up in the main bundle. React DevTools Profiler for finding unnecessary re-renders. React.memo, useMemo, useCallback are targeted tools. Premature memoization of everything adds overhead without benefit. Profile first, optimize later.

Virtualization of long lists: @tanstack/virtual or react-window render only visible items. Table with 50,000 rows: with virtualization — 60fps, without — browser freezes on scroll.

State Management: Without Overengineering

For most applications, it's enough to have:

  • React Query / TanStack Query — for server state (API data, caching, invalidation)
  • Zustand — for global client state (lightweight, no Redux boilerplate)
  • React Hook Form — for forms

Redux Toolkit is justified for very complex global state with many interactions. For most tasks, it's overkill. Recoil, Jotai — atomic approaches for independent pieces of state.

How to Choose the Right CSS and Design System?

Tailwind CSS latest version is our standard choice for new projects. Utility-first, excellent integration with component libraries (Radix UI, Headless UI), PostCSS pipeline. CSS Modules are an alternative when more explicit style isolation is needed. Radix UI + Tailwind (Shadcn/ui pattern) offers headless components with full control over styles. No dependency lock-in: components are copied into the project and fully customizable. Storybook is used for documenting the component library.

React DevTools Profiler — the official tool from the React team.

Testing

Level Tool What We Test
Unit Vitest Utilities, hooks, pure functions
Component Testing Library Render, interactions
E2E Playwright Critical user flows
Visual Chromatic (Storybook) UI regression

E2E tests via Playwright — for checkout, authentication, critical forms. Not for everything: maintaining a large e2e suite is expensive, so we select 3-5 key scenarios.

What's Included in the Scope (Deliverables)

Every frontend project we deliver includes:

  • Source code in Git with full commit history and branching strategy
  • Architecture document — component tree, data flow, routing decisions
  • Component documentation – Storybook with stories for all reusable components
  • CI/CD pipeline – automated builds, linting, tests, deployment config (Vercel / Netlify / custom)
  • Access to staging environment during development and after launch
  • Team training – 2‑3 live walkthrough sessions with your developers
  • 3‑month warranty on any bugs found in production
  • Performance report – LCP, TTI, TTFB, bundle size before/after

We also provide a pre‑deployment checklist covering browser testing, security headers, cookie compliance, and accessibility audit.

Estimates and Scope

Task Timeline
SPA (dashboard, CRM interface) 8–16 weeks
Next.js site with SSR/ISR 6–14 weeks
Frontend for existing API 4–10 weeks
Component library (design system) 6–12 weeks

Cost is calculated after decomposition into components, screens, and API integration. We use N+1 estimation: add 20% for risks.

What Does a Typical Performance Audit Reveal?

A recent e‑commerce project had LCP of 4.2 seconds and a monthly cloud bill of $3,000. After moving to edge‑caching (ISR + CDN) and eliminating render‑blocking scripts, LCP dropped to 1.1 seconds, and the bill fell to $1,800. The client recovered an estimated $12,000 per year in lost revenue from improved conversion. That's the kind of before‑after we regularly deliver.

Comparing tools: Next.js is 20‑30% faster in SSR builds than Nuxt with the same page size. TypeScript reduces production bugs by 60‑70% compared to JavaScript. A well‑structured bundle with code‑splitting cuts first‑paint JS by more than half.

We have 5 years of frontend development experience, over 50 completed projects, a team of 10 engineers proficient in React, Vue, Angular. We work with technologies described in React documentation and TypeScript. Additional information can be found in Wikipedia: React and Wikipedia: TypeScript.

What Stack to Choose for Frontend Development with React?

We compare tools by real metrics. Next.js is 20‑30% faster in SSR builds than Nuxt with the same page size. TypeScript reduces production bugs by 60‑70% compared to JavaScript. Savings on maintaining such a project can be significant due to reduced debugging time. If you need a lightweight SPA with minimal cost, React + Vite is enough. For a content site with SEO, Next.js with ISR gives TTFB below 50 ms even with 50,000 pages.

Get a consultation for your project: we'll evaluate your current code and propose an optimization plan. Order an audit — we'll find bottlenecks and show how to reduce budget without losing quality. Contact us to start the discussion.