### Getting Started with SDK Core Source: https://github.com/uniswap/docs/blob/main/docs/sdk/core/reference/README.md Demonstrates how to import and use core classes like Token and CurrencyAmount to represent ERC-20 tokens and their amounts. ```APIDOC ## Getting Started ```typescript import { Token, CurrencyAmount, TradeType } from '@uniswap/sdk-core' // Create a token const USDC = new Token(1, '0xA0b86a33E6417c29C8F6e3b6E4E12A82aA4Ca8e9', 6, 'USDC', 'USD Coin') // Create an amount const amount = CurrencyAmount.fromRawAmount(USDC, '1000000') // 1 USDC ``` For practical integration examples, see the [SDK v3 Guides](../../v3/guides/01-background.md) and [SDK v4 Guides](../../v4/overview.md). ``` -------------------------------- ### Example Contract Setup with Uniswap v4 Interfaces Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/swap-routing.mdx Sets up a Solidity contract with necessary imports for Uniswap v4 core, periphery, universal router, and Permit2. Initializes key interfaces for router, pool manager, and Permit2. ```solidity // SPDX-License-Identifier: MIT pragma solidity 0.8.26; import { IUniversalRouter } from "@uniswap/universal-router/contracts/interfaces/IUniversalRouter.sol"; import { Commands } from "@uniswap/universal-router/contracts/libraries/Commands.sol"; import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import { IV4Router } from "@uniswap/v4-periphery/src/interfaces/IV4Router.sol"; import { Actions } from "@uniswap/v4-periphery/src/libraries/Actions.sol"; import { IPermit2 } from "@uniswap/permit2/src/interfaces/IPermit2.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { StateLibrary } from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol"; import { Currency } from "@uniswap/v4-core/src/types/Currency.sol"; contract Example { using StateLibrary for IPoolManager; IUniversalRouter public immutable router; IPoolManager public immutable poolManager; IPermit2 public immutable permit2; constructor(address _router, address _poolManager, address _permit2) { router = IUniversalRouter(_router); poolManager = IPoolManager(_poolManager); permit2 = IPermit2(_permit2); } // We'll add more functions here } ``` -------------------------------- ### Working with Currencies Example Source: https://github.com/uniswap/docs/blob/main/docs/sdk/core/reference/modules.md Example demonstrating how to create instances of native Ether and ERC-20 tokens using the SDK. ```APIDOC ## Working with Currencies ```typescript import { Token, Ether } from '@uniswap/sdk-core' // Native ETH const ETH = Ether.onChain(1) // ERC-20 Token const USDC = new Token( 1, // chainId '0xA0b86a33E6417c29C8F6e3b6E4E12A82aA4Ca8e9', // address 6, // decimals 'USDC', // symbol 'USD Coin' // name ) ``` ``` -------------------------------- ### Working with Amounts Example Source: https://github.com/uniswap/docs/blob/main/docs/sdk/core/reference/modules.md Example showing how to create and format currency amounts using the CurrencyAmount class. ```APIDOC ## Working with Amounts ```typescript import { CurrencyAmount } from '@uniswap/sdk-core' const amount = CurrencyAmount.fromRawAmount(USDC, '1000000') // 1 USDC const readable = amount.toSignificant(6) // "1.000000" ``` For more detailed usage, see the individual class documentation and the [SDK Guides](../../v3/guides/01-background.md). ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/uniswap/docs/blob/main/docs/contracts/liquidity-launchpad/quickstart/setup.md Install and run pre-commit hooks for code quality checks. This is an optional step. ```bash pre-commit install pre-commit run --all-files ``` -------------------------------- ### Define Example Configuration Source: https://github.com/uniswap/docs/blob/main/docs/sdk/v4/guides/advanced/pool-data.md Sets up an example configuration including environment, RPC endpoints, and pool key parameters. Ensure a pool exists for the chosen configuration. ```typescript export const CurrentConfig: ExampleConfig = { env: Environment.MAINNET, rpc: { local: 'http://localhost:8545', mainnet: 'https://mainnet.infura.io/v3/YOUR_API_KEY', }, ... poolKey: { currency0: ETH_TOKEN.address, currency1: USDC_TOKEN.address, fee: FEE_AMOUNT_LOW, tickSpacing: TICK_SPACING_TEN, hooks: EMPTY_HOOK, }, } ``` -------------------------------- ### Install Dependencies with Foundry Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/create-pool.mdx Install the necessary Uniswap v4 core and periphery libraries using Foundry. ```bash forge install uniswap/v4-core forge install uniswap/v4-periphery ``` -------------------------------- ### Clone and Install Dependencies Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/hooks/your-first-hook.md Clone the v4-template repository and install the necessary Foundry dependencies. This setup is required before creating your custom hook. ```bash git clone https://github.com/uniswapfoundation/v4-template.git cd v4-template # requires foundry forge install forge test ``` -------------------------------- ### Get Quote and Build Transaction Source: https://github.com/uniswap/docs/blob/main/docs/api/trading/overview.md This example demonstrates how to get a quote and build a transaction for a token swap using the Trading API. It includes parameters for input/output tokens, amounts, chain IDs, and routing preferences. ```APIDOC ## POST /v1/quote ### Description Generates a quote for a token swap and prepares a transaction for execution. This endpoint is crucial for initiating swap operations within the Uniswap ecosystem. ### Method POST ### Endpoint https://trade-api.gateway.uniswap.org/v1/quote ### Headers - `Content-Type`: `application/json` - `x-api-key`: `YOUR_API_KEY` - `x-universal-router-version`: `2.0` ### Request Body - **generatePermitAsTransaction** (boolean) - Optional - Whether to generate a permit as a transaction. - **autoSlippage** (string) - Optional - Specifies the slippage tolerance, e.g., `DEFAULT`. - **routingPreference** (string) - Optional - Preference for routing, e.g., `BEST_PRICE`. - **spreadOptimization** (string) - Optional - Spread optimization strategy, e.g., `EXECUTION`. - **urgency** (string) - Optional - Urgency of the transaction, e.g., `urgent`. - **permitAmount** (string) - Optional - Amount for permit, e.g., `FULL`. - **type** (string) - Required - Type of swap, e.g., `EXACT_INPUT`. - **amount** (string) - Required - The input amount for the swap. - **tokenInChainId** (string) - Required - The chain ID of the input token. - **tokenOutChainId** (string) - Required - The chain ID of the output token. - **tokenIn** (string) - Required - The address of the input token. - **tokenOut** (string) - Required - The address of the output token. - **swapper** (string) - Required - The address of the user initiating the swap. ### Request Example ```json { "generatePermitAsTransaction": false, "autoSlippage": "DEFAULT", "routingPreference": "BEST_PRICE", "spreadOptimization": "EXECUTION", "urgency": "urgent", "permitAmount": "FULL", "type": "EXACT_INPUT", "amount": "1000000000000000000", "tokenInChainId": "1", "tokenOutChainId": "1", "tokenIn": "0x0000000000000000000000000000000000000000", "tokenOut": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "swapper": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" } ``` ### Response (Response details not provided in the source text.) ``` -------------------------------- ### Basic Subscriber Implementation Example Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/16-subscriber.mdx A simple example demonstrating how to implement the `ISubscriber` interface in a Solidity contract to track subscriptions. ```APIDOC ## Implement Subscriber First, create your contract implementing the ISubscriber interface: ```solidity contract MySubscriber is ISubscriber { // Track subscribed positions mapping(uint256 => bool) public isSubscribed; // Implementation of interface methods function notifySubscribe(uint256 tokenId, bytes memory data) external { // Store subscription status isSubscribed[tokenId] = true; } // Implement notifyUnsubscribe, notifyModifyLiquidity, and notifyBurn as required function notifyUnsubscribe(uint256 tokenId) external { // Handle unsubscribe logic isSubscribed[tokenId] = false; } function notifyModifyLiquidity(uint256 tokenId, int256 liquidityChange, BalanceDelta feesAccrued) external { // Handle liquidity modification logic } function notifyBurn(uint256 tokenId, address owner, PositionInfo info, uint256 liquidity, BalanceDelta feesAccrued) external { // Handle position burn logic } } ``` ## Deploy Subscriber Once implemented, deploy your contract: ```solidity MySubscriber subscriber = new MySubscriber(); ``` Store the deployed address for users to reference when subscribing their positions. ``` -------------------------------- ### Example CCA Deployment Script Source: https://github.com/uniswap/docs/blob/main/docs/contracts/liquidity-launchpad/quickstart/example-configuration.md This script demonstrates the deployment of a Continuous Clearing Auction (CCA) factory, a mock ERC20 token, and the auction contract itself. It configures auction parameters, mints tokens to the auction contract, and calls `onTokensReceived` to finalize setup. Ensure you have the necessary Forge dependencies and environment variables set. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Script} from "forge-std/Script.sol"; import {ContinuousClearingAuctionFactory} from "../src/ContinuousClearingAuctionFactory.sol"; import {AuctionParameters} from "../src/interfaces/IContinuousClearingAuction.sol"; import {IDistributionContract} from "../src/interfaces/external/IDistributionContract.sol"; import {AuctionStepsBuilder} from "../test/utils/AuctionStepsBuilder.sol"; import {ERC20Mock} from '@openzeppelin/contracts/mocks/token/ERC20Mock.sol'; import {console2} from "forge-std/console2.sol"; contract ExampleCCADeploymentScript is Script { using AuctionStepsBuilder for bytes; function setUp() public {} function run() public { address deployer = vm.envAddress("DEPLOYER"); vm.startBroadcast(); ContinuousClearingAuctionFactory factory = new ContinuousClearingAuctionFactory(); console2.log("Factory deployed to:", address(factory)); ERC20Mock token = new ERC20Mock(); uint256 totalSupply = 1_000_000_000e18; // 1 billion tokens bytes memory auctionStepsData = AuctionStepsBuilder.init().addStep(20_000, 50).addStep(100_000, 49).addStep(4_100_000, 1); AuctionParameters memory parameters = AuctionParameters({ currency: address(0), tokensRecipient: deployer, fundsRecipient: deployer, startBlock: uint64(block.number), endBlock: uint64(block.number + 100), claimBlock: uint64(block.number + 100), tickSpacing: 79228162514264334008320, validationHook: address(0), floorPrice: 79228162514264334008320, requiredCurrencyRaised: 0, auctionStepsData: auctionStepsData }); IDistributionContract auction = IDistributionContract(factory.initializeDistribution(address(token), totalSupply, abi.encode(parameters), bytes32(0))); token.mint(address(auction), totalSupply); auction.onTokensReceived(); console2.log("Auction deployed to:", address(auction)); vm.stopBroadcast(); } } ``` -------------------------------- ### Install OpenZeppelin Hooks Library Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/hooks/setup.mdx Install the OpenZeppelin Hooks library using Forge if you are starting from scratch. This command adds the library to your project's dependencies. ```bash forge install OpenZeppelin/uniswap-hooks ``` -------------------------------- ### Install Uniswap AI Swap Integration Skill Source: https://github.com/uniswap/docs/blob/main/docs/api/trading/overview.md Install the Uniswap AI skills package with the swap integration skill for AI-assisted trading. ```bash npx skills add uniswap/uniswap-ai --skill swap-integration ``` -------------------------------- ### Example Fee Calculation Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/concepts/fee-structure.mdx This Solidity example calculates the total swap fee given specific protocol and LP fee values in pips. ```solidity swapFee = 50 + 3000 - (50 * 3000) / 1_000_000; = 50 + 3000 - 150 / 1_000_000; = 50 + 3000 - 0.15; = 3049.85 pips ``` -------------------------------- ### Install Uniswap v4 SDK and Core SDK Source: https://github.com/uniswap/docs/blob/main/docs/sdk/v4/overview.md Install the v4 SDK and the Core SDK using npm. These are required to interact with the v4 smart contracts. ```bash npm i --save @uniswap/v4-sdk npm i --save @uniswap/sdk-core ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/uniswap/docs/blob/main/docs/contracts/liquidity-launchpad/quickstart/setup.md Install all project dependencies using the Forge package manager. ```bash forge install ``` -------------------------------- ### Start Local Development Server Source: https://github.com/uniswap/docs/blob/main/README.md Start a local development server using yarn. Changes are reflected live without needing to restart the server. ```bash yarn run start ``` -------------------------------- ### Install web3-react Core with npm Source: https://github.com/uniswap/docs/blob/main/docs/sdk/web3-react/overview.md Install the core package of web3-react using npm. This package provides the essential methods for interacting with web3 connectors. ```bash npm install --save @web3-react/core ``` -------------------------------- ### Install web3-react Core with yarn Source: https://github.com/uniswap/docs/blob/main/docs/sdk/web3-react/overview.md Install the core package of web3-react using yarn. This package provides the essential methods for interacting with web3 connectors. ```bash yarn add @web3-react/core ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/uniswap/docs/blob/main/README.md Install project dependencies using yarn. ```bash yarn install ``` -------------------------------- ### Install Foundry Source: https://github.com/uniswap/docs/blob/main/docs/contracts/liquidity-launchpad/quickstart/setup.md Install Foundry, a necessary tool for developing with CCA locally. This command downloads and executes the Foundry installation script. ```bash curl -L https://foundry.paradigm.xyz | bash ``` -------------------------------- ### Install TypeDoc for Markdown Generation Source: https://github.com/uniswap/docs/blob/main/README.md Install TypeDoc and the typedoc-plugin-markdown for generating markdown documentation from TypeScript comments. TypeScript may also need to be installed. ```bash npm install --save-dev typedoc typedoc-plugin-markdown ``` ```bash npm install --save-dev typescript ``` -------------------------------- ### Setup for Uniswap v4 SDK Source: https://github.com/uniswap/docs/blob/main/docs/sdk/v4/guides/liquidity/fetching-positions.md Initializes viem clients and imports necessary modules for interacting with Uniswap v4. ```typescript import { createPublicClient, http, Address, zeroAddress, } from 'viem' import { unichain } from 'viem/chains' import request from 'graphql-request' const POSITION_MANAGER_ADDRESS = '0x4529a01c7a0410167c5740c487a8de60232617bf' //unichain const publicClient = createPublicClient({ chain: unichain, transport: http(), }) ``` -------------------------------- ### Install Uniswap v4 SDK and Core Dependencies Source: https://context7.com/uniswap/docs/llms.txt Install the v4 SDK and core dependencies using npm. Include additional packages for swapping via Universal Router or fetching pool data with ethers-multicall. ```bash npm i --save @uniswap/v4-sdk npm i --save @uniswap/sdk-core # For swapping npm i --save @uniswap/universal-router-sdk # For pool data fetching npm i --save ethers-multicall ``` -------------------------------- ### Install Uniswap v4 Dependencies Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/hooks/setup.mdx Install the necessary Uniswap v4 core and periphery contracts as project dependencies using Foundry. ```bash forge install Uniswap/v4-core && forge install Uniswap/v4-periphery ``` -------------------------------- ### Initialize Pool with PoolKey and Starting Price Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/create-pool.mdx Call the initialize function on the PoolManager contract to create a pool with the specified PoolKey and starting price. This method does not add initial liquidity. ```solidity IPoolManager(manager).initialize(pool, startingPrice); ``` -------------------------------- ### Install Uniswap v4 Dependencies Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/swap-routing.mdx Install the necessary Uniswap v4 core, periphery, permit2, and universal-router contracts using forge. Ensure remappings are correctly set up in remappings.txt. ```bash forge install uniswap/v4-core forge install uniswap/v4-periphery forge install uniswap/permit2 forge install uniswap/universal-router forge install OpenZeppelin/openzeppelin-contracts ``` ```plaintext @uniswap/v4-core/=lib/v4-core/ @uniswap/v4-periphery/=lib/v4-periphery/ @uniswap/permit2/=lib/permit2/ @uniswap/universal-router/=lib/universal-router/ @openzeppelin/contracts/=lib/openzeppelin-contracts/ ``` -------------------------------- ### Install Dependencies for Uniswap v4 Swaps Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/swap.mdx Install the necessary dependencies for interacting with Uniswap v4 and related protocols using Foundry. Ensure your remappings.txt file is updated accordingly. ```bash forge install uniswap/v4-core forge install uniswap/v4-periphery forge install uniswap/permit2 forge install uniswap/universal-router forge install uniswap/v3-core forge install uniswap/v2-core forge install OpenZeppelin/openzeppelin-contracts ``` -------------------------------- ### Example BeforeSwap Hook Implementation with Fee Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/types/beforeswapdelta-guide.mdx This example demonstrates a `beforeSwap` hook that implements a 1% fee. It calculates the fee, sets the `delta` to reflect the fee taken from the specified token, and returns the original amount as `amountIn`. ```solidity function _beforeSwap( address, PoolKey calldata, IPoolManager.SwapParams calldata params, bytes calldata ) internal override returns (int256 amountIn, BeforeSwapDelta delta, uint24) { int128 specifiedAmount = params.amountSpecified.toInt128(); int128 fee = specifiedAmount / 100; // 1% fee int128 adjustedAmount = specifiedAmount - fee; delta = BeforeSwapDelta.from(-fee, 0); // Fee taken from specified token amountIn = params.amountSpecified; // Original amount return (amountIn, delta, 0); } ``` -------------------------------- ### Complete Liquidity Hook Contract Example Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/hooks/liquidity.mdx A full example of a Uniswap V4 hook contract that implements `beforeAddLiquidity` and `beforeRemoveLiquidity`. It tracks counts for each hook and defines the hook permissions. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol"; import {Hooks} from "v4-core/src/libraries/Hooks.sol"; import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol"; import {PoolKey} from "v4-core/src/types/PoolKey.sol"; import {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol"; import {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol"; import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "v4-core/src/types/BeforeSwapDelta.sol"; contract LiquidityHook is BaseHook { using PoolIdLibrary for PoolKey; // NOTE: --------------------------------------------------------- // state variables should typically be unique to a pool // a single hook contract should be able to service multiple pools // --------------------------------------------------------------- mapping(PoolId => uint256 count) public beforeAddLiquidityCount; mapping(PoolId => uint256 count) public beforeRemoveLiquidityCount; constructor(IPoolManager _poolManager) BaseHook(_poolManager) {} function getHookPermissions() public pure override returns (Hooks.Permissions memory) { return Hooks.Permissions({ beforeInitialize: false, afterInitialize: false, beforeAddLiquidity: true, afterAddLiquidity: false, beforeRemoveLiquidity: true, afterRemoveLiquidity: false, beforeSwap: false, afterSwap: false, beforeDonate: false, afterDonate: false, beforeAddLiquidityReturnDelta: false, afterSwapReturnDelta: false, afterAddLiquidityReturnDelta: false, afterRemoveLiquidityReturnDelta: false }); } // ----------------------------------------------- // NOTE: see IHooks.sol for function documentation // ----------------------------------------------- function _beforeAddLiquidity( address, // sender PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata, // params bytes calldata // hookData ) internal override returns (bytes4) { beforeAddLiquidityCount[key.toId()]++; return BaseHook.beforeAddLiquidity.selector; } function _beforeRemoveLiquidity( address, // sender PoolKey calldata key, IPoolManager.ModifyLiquidityParams calldata, // params bytes calldata // hookData ) internal override returns (bytes4) { beforeRemoveLiquidityCount[key.toId()]++; return BaseHook.beforeRemoveLiquidity.selector; } } ``` -------------------------------- ### Set Up Basic Hook with Fee Percentage Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/custom-accounting.mdx This example demonstrates setting up a basic hook contract with a predefined fee percentage and enabling necessary permissions for swap operations. Ensure the hook is compatible with the PoolManager. ```solidity // SPDX-License-Identifier: MIT pragma solidity 0.8.26; import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol"; import {Hooks} from "v4-core/src/libraries/Hooks.sol"; import {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol"; import {PoolKey} from "v4-core/src/types/PoolKey.sol"; import {Currency} from "v4-core/src/types/Currency.sol"; import {BeforeSwapDelta, toBeforeSwapDelta} from "v4-core/src/types/BeforeSwapDelta.sol"; contract HookFeeExample is BaseHook { uint256 public constant HOOK_FEE_PERCENTAGE = 10;// 0.01% fee uint256 public constant FEE_DENOMINATOR = 100000; constructor(IPoolManager _poolManager) BaseHook(_poolManager) {} function getHookPermissions() public pure override returns (Hooks.Permissions memory) { return Hooks.Permissions({ beforeInitialize: false, afterInitialize: false, beforeAddLiquidity: false, beforeRemoveLiquidity: false, afterAddLiquidity: false, afterRemoveLiquidity: false, beforeSwap: true, afterSwap: false, beforeDonate: false, afterDonate: false, beforeSwapReturnDelta: true, afterSwapReturnDelta: false, afterAddLiquidityReturnDelta: false, afterRemoveLiquidityReturnDelta: false }); } } ``` -------------------------------- ### V4Planner Constructor Source: https://github.com/uniswap/docs/blob/main/docs/sdk/v4/reference/classes/V4Planner.md Initializes a new instance of the V4Planner class. This is the starting point for building a sequence of operations. ```APIDOC ## new V4Planner() ### Description Initializes a new instance of the V4Planner class. ### Returns - [`V4Planner`](V4Planner.md) - A new V4Planner instance. ``` -------------------------------- ### Setting Up MintOptions for V4 SDK Source: https://github.com/uniswap/docs/blob/main/docs/sdk/v4/guides/liquidity/minting-position.md Demonstrates how to construct the `MintOptions` object with required and optional parameters for minting liquidity. Ensure you have the necessary imports and correctly format values like slippage tolerance and deadline. ```typescript import { Percent, // Other necessary imports like Ether, NativeCurrency, etc. } from '@uniswap/sdk-core' import { MintOptions } from '@uniswap/v4-sdk' // Assume ETH_TOKEN, USDC_TOKEN, publicClient, and Ether are defined elsewhere // const ETH_TOKEN = ... // const USDC_TOKEN = ... // const publicClient = ... // Example code showing how to set up MintOptions // These parameters typically come from user input or application state // 1. slippageTolerance (required): Maximum allowed price movement // Convert from a percentage (e.g., 0.5%) to a Percent object // Here, 50 out of 10000 = 0.5% const slippageTolerance = 0.5 // 0.5% slippage tolerance const slippagePct = new Percent(Math.floor(slippageTolerance * 100), 10000) // 2. deadline (required): Transaction expiry timestamp in seconds // Usually current time + some buffer (e.g., 20 minutes) const deadlineSeconds = 20 * 60 // 20 minutes const currentBlock = await publicClient.getBlock() const currentBlockTimestamp = Number(currentBlock.timestamp) const deadline = currentBlockTimestamp + deadlineSeconds // 3. recipient (required): Address to receive the position NFT // Typically the user's wallet address const userAddress = '0xYourAddressHere' // Replace with actual user address // Create the basic MintOptions object with required fields const mintOptions: MintOptions = { recipient: userAddress, slippageTolerance: slippagePct, deadline: deadline.toString(), // 4. useNative (optional): Use native ETH useNative: ETH_TOKEN.isNative ? Ether.onChain(ETH_TOKEN.chainId) : USDC_TOKEN.isNative ? Ether.onChain(USDC_TOKEN.chainId) : undefined, // 5. batchPermit (optional): For gasless approvals via Permit2 // We'll set this later if needed // 6. hookData (optional): Data for pool hooks // Only needed for pools with custom hooks hookData: '0x', // Default empty bytes // 7-8. For new pools only: // createPool: true, // Uncomment if creating a new pool // sqrtPriceX96: '1234567890123456789', // Initial price, required if createPool is true // 9. For migrations only: // migrate: false, // Normally omitted unless migrating from v3 } ``` -------------------------------- ### Create Token and CurrencyAmount Source: https://github.com/uniswap/docs/blob/main/docs/sdk/core/reference/README.md Demonstrates how to create a Token instance and a CurrencyAmount from raw amount. Ensure necessary imports are included. ```typescript import { Token, CurrencyAmount, TradeType } from '@uniswap/sdk-core' // Create a token const USDC = new Token(1, '0xA0b86a33E6417c29C8F6e3b6E4E12A82aA4Ca8e9', 6, 'USDC', 'USD Coin') // Create an amount const amount = CurrencyAmount.fromRawAmount(USDC, '1000000') // 1 USDC ``` -------------------------------- ### Set Up Example Contract for Uniswap v4 Swaps Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/swap.mdx Import necessary contracts and libraries for interacting with Uniswap v4. This contract initializes the Universal Router, PoolManager, and Permit2 interfaces. ```solidity // SPDX-License-Identifier: MIT pragma solidity 0.8.26; import { UniversalRouter } from "@uniswap/universal-router/contracts/UniversalRouter.sol"; import { Commands } from "@uniswap/universal-router/contracts/libraries/Commands.sol"; import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import { IV4Router } from "@uniswap/v4-periphery/src/interfaces/IV4Router.sol"; import { Actions } from "@uniswap/v4-periphery/src/libraries/Actions.sol"; import { IPermit2 } from "@uniswap/permit2/src/interfaces/IPermit2.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { StateLibrary } from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; contract Example { using StateLibrary for IPoolManager; UniversalRouter public immutable router; IPoolManager public immutable poolManager; IPermit2 public immutable permit2; constructor(address _router, address _poolManager, address _permit2) { router = UniversalRouter(payable(_router)); poolManager = IPoolManager(_poolManager); permit2 = IPermit2(_permit2); } // We'll add more functions here } ``` -------------------------------- ### Initialize Viem Client and StateView Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/state-view.mdx Sets up a viem client and a StateView contract instance for interacting with the StateView contract offchain. ```typescript import { createPublicClient, http } from 'viem'; import { mainnet } from 'viem/chains'; // Initialize the client const client = createPublicClient({ chain: mainnet, transport: http() }); // Set up StateView contract instance const stateView = getContract({ address: STATE_VIEW_ADDRESS, abi: stateViewABI, client }) ``` -------------------------------- ### Set Up Forked Repository Source: https://github.com/uniswap/docs/blob/main/CONTRIBUTING.md Commands to set up your local fork with the latest changes from the main branch. ```bash cd uniswap-docs git remote add upstream https://github.com/Uniswap/uniswap-docs.git git fetch upstream git pull --rebase upstream main git checkout -b "my-contribution" ``` -------------------------------- ### Get Next Token ID Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/periphery/interfaces/IPositionManager.md Used to get the ID that will be used for the next minted liquidity position. ```solidity function nextTokenId() external view returns (uint256); ``` -------------------------------- ### initialize Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/libraries/Pool.md Initializes a pool with a given square root price and LP fee. ```APIDOC ## initialize ### Description Initializes a pool with a given square root price and LP fee. ### Method internal ### Signature function initialize(State storage self, uint160 sqrtPriceX96, uint24 lpFee) internal returns (int24 tick) ``` -------------------------------- ### PointsHook Example Source: https://context7.com/uniswap/docs/llms.txt An example of a custom hook that awards POINTS tokens to users based on their swap and liquidity addition activities. ```APIDOC ## PointsHook (Solidity) ### Description This hook extends `BaseHook` to implement custom logic for awarding `PointsToken` to users. It hooks into the `afterSwap` and `afterAddLiquidity` lifecycle events. ### Permissions - `afterAddLiquidity`: `true` - `afterSwap`: `true` ### Callbacks - `_afterSwap`: Awards POINTS tokens based on ETH spent during swaps in ETH pools. - `_afterAddLiquidity`: Awards POINTS tokens based on ETH added as liquidity in ETH pools. ### Usage Deploy this hook to an address whose flags match `Hooks.AFTER_SWAP_FLAG | Hooks.AFTER_ADD_LIQUIDITY_FLAG`. ``` -------------------------------- ### Start Local Anvil Node Source: https://github.com/uniswap/docs/blob/main/docs/contracts/liquidity-launchpad/quickstart/setup.md Start a local Ethereum node using Anvil, which is part of Foundry. This node will run on localhost:8545. ```bash anvil ``` -------------------------------- ### Donation Router Contract Setup Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/ERC-6909.mdx Sets up the DonationRouter contract with necessary imports, defines a struct for callback data, and initializes the PoolManager. ```Solidity // SPDX-License-Identifier: MIT pragma solidity 0.8.24; import { IPoolManager } from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import { PoolKey } from "@uniswap/v4-core/src/types/PoolKey.sol"; import { BalanceDelta } from "@uniswap/v4-core/src/types/BalanceDelta.sol"; import { Currency } from "@uniswap/v4-core/src/types/Currency.sol"; contract DonationRouter { IPoolManager public immutable poolManager; // This struct helps us pack donation parameters to pass through // the unlock/callback pattern struct CallbackData { PoolKey key; uint256 amount0; uint256 amount1; bytes hookData; } constructor(IPoolManager _poolManager) { poolManager = _poolManager; } } ``` -------------------------------- ### Complete Add/Remove Liquidity Workflow Example Source: https://github.com/uniswap/docs/blob/main/docs/sdk/v4/guides/liquidity/add-remove-liquidity.md Demonstrates a full cycle of adding liquidity to a position, waiting, and then removing a portion of it. Assumes helper functions like getPositionDetails, addLiquidityToPosition, and walletClient are defined elsewhere. ```typescript async function completeAddRemoveWorkflow() { const tokenId = 123456n // 1. Fetch position details const positionDetails = await getPositionDetails(tokenId) console.log(`Position: ${positionDetails.token0.symbol}/${positionDetails.token1.symbol}`) // 2. Add liquidity const addResult = await addLiquidityToPosition( positionDetails, '1000000000000000', // 0.001 ETH '1000000', // 1 USDC 0.05 // 5% slippage ) console.log(`Added liquidity: ${addResult.txHash}`) // 3. Wait and verify await new Promise((resolve) => setTimeout(resolve, 5000)) const updatedPosition = await getPositionDetails(tokenId) // 4. Remove 50% of liquidity const removeResult = await removeLiquidityFromPosition( updatedPosition, 0.5, // 50% 0.05, // 5% slippage false // don't burn token ) console.log(`Removed 50% liquidity: ${removeResult.txHash}`) return { addResult, removeResult } } ``` -------------------------------- ### Basic BeforeSwap Hook Example Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/types/beforeswapdelta-guide.mdx Demonstrates the minimal structure of a beforeSwap hook using BeforeSwapDelta. It converts amountSpecified to int128, sets unspecifiedAmount to 0, creates a BeforeSwapDelta, and returns original swap parameters. ```solidity function _beforeSwap( address, // sender PoolKey calldata, // poolKey IPoolManager.SwapParams calldata params, // swap parameters bytes calldata // data ) internal override returns (int256 amountIn, BeforeSwapDelta delta, uint24 lpFeeOverride) { // Convert the specified amount to int128 int128 specifiedAmount = params.amountSpecified.toInt128(); // In this example, we're not modifying the unspecified amount int128 unspecifiedAmount = 0; // Calculated based on your custom logic // Create the BeforeSwapDelta delta = toBeforeSwapDelta(specifiedAmount, unspecifiedAmount); // Return the original amount as amountIn amountIn = params.amountSpecified; // Return 0 for lpFeeOverride as we're not changing the LP fee return (amountIn, delta, 0); } ``` -------------------------------- ### Initialize Foundry Project Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/manage-liquidity/setup-liquidity.mdx Initialize a new Foundry project in the current directory. The `--force` flag will overwrite existing files if necessary. ```bash forge init . --force ``` -------------------------------- ### constructor Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/test/TestERC20.md Initializes the TestERC20 contract with a specified amount of tokens to mint. ```APIDOC ## constructor ### Description Initializes the TestERC20 contract with a specified amount of tokens to mint. ### Parameters - **amountToMint** (uint256) - The initial amount of tokens to mint. ``` -------------------------------- ### Initialize Pool Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/IPoolManager.mdx Initializes a new pool with specified parameters. Requires a PoolKey and the initial square root price. ```solidity function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick); ``` -------------------------------- ### Get Currency Delta - Solidity Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/libraries/TransientStateLibrary.md Get the current delta for a caller in the given currency. The target is the credited account address and the currency is the one for which to lookup the delta. ```solidity function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256); ``` -------------------------------- ### Get Signed Amount1 Delta Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/libraries/SqrtPriceMath.md Helper function to get the signed currency1 delta. It calculates the amount of currency1 corresponding to a given liquidity delta between two prices. ```solidity function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256); ``` -------------------------------- ### Compare Static vs. Dynamic Price Calculations Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/unlock-callback.mdx Illustrates the difference between using a static price assumption for calculations and interacting with a pool to reflect real-time price changes. ```solidity // Static math calculation LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96: 3000, // Fixed price ... ); // Interacts with the pool and uses actual execution (reflects real-time price) poolManager.modifyLiquidity( sqrtRatioX96: 3001, // Updated price ... ); ``` -------------------------------- ### Get Signed Amount0 Delta Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/libraries/SqrtPriceMath.md Helper function to get the signed currency0 delta. It calculates the amount of currency0 corresponding to a given liquidity delta between two prices. ```solidity function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256); ``` -------------------------------- ### Minting a New Position with Position Manager Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/position-manager.mdx Example of creating a new liquidity position using the Position Manager. It demonstrates encoding the MINT_POSITION and SETTLE_PAIR actions. ```Solidity bytes memory actions = abi.encodePacked( uint8(Actions.MINT_POSITION), // Create the position uint8(Actions.SETTLE_PAIR) // Provide the tokens ); ``` -------------------------------- ### Get Pool Slot0 Data Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/periphery/interfaces/IStateView.md Retrieves the Slot0 data for a given pool, including sqrtPriceX96, tick, protocolFee, and lpFee. Use this to get core pool price and fee information. ```solidity function getSlot0(PoolId poolId) external view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee); ``` -------------------------------- ### Get Pool Slot0 Data Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/periphery/lens/StateView.md Retrieves the core state of a pool, including its current price, tick, and fee configurations. Use this to get a snapshot of the pool's essential parameters. ```solidity function getSlot0(PoolId poolId) external view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee); ``` -------------------------------- ### Deploy and Use Subscriber Contract Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/16-subscriber.mdx Demonstrates the basic steps to deploy a subscriber contract and then subscribe a position to it using the `positionManager`. ```solidity // 1. Deploy the subscriber LiquidityRewardsSubscriber subscriber = new LiquidityRewardsSubscriber(positionManager); // 2. Users then subscribe their positions positionManager.subscribe(tokenId, subscriber, ""); ``` -------------------------------- ### Get Position Info by Position ID Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/reference/core/libraries/StateLibrary.md Retrieves detailed information about a liquidity position, including liquidity and fee growth, using the unique `positionId`. This is a gas-efficient way to get position details. ```solidity function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128); ``` -------------------------------- ### Uniswap v4 Contract Setup for Fee Calculation Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/guides/15-calculate-lp-fees.mdx Sets up the necessary contracts, libraries, and interfaces for calculating LP fees in Uniswap v4. Includes placeholders for contract addresses. ```solidity pragma solidity ^0.8.24; import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol"; import {FixedPoint128} from "@uniswap/v4-core/src/libraries/FixedPoint128.sol"; import {Position} from "@uniswap/v4-core/src/libraries/Position.sol"; import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol"; import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol"; import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol"; import {BalanceDelta, toBalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol"; import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol"; import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol"; import {IPositionManager} from "src/interfaces/IPositionManager.sol"; import {PositionConfig} from "src/types/PositionConfig.sol"; contract CalculateFeeExample { using SafeCast for uint256; using StateLibrary for IPoolManager; IPositionManager posm = IPositionManager(); IPoolManager manager = IPoolManager(); function getUncollectedFees(PositionConfig memory config, uint256 tokenId) external view returns (BalanceDelta uncollectedFees) {} function getLifetimeFees(PositionConfig memory config, uint256 tokenId) external view returns (BalanceDelta lifetimeFees) {} } ``` -------------------------------- ### Compile a Basic Hook Contract Source: https://github.com/uniswap/docs/blob/main/docs/contracts/v4/quickstart/hooks/setup.mdx Create a Counter Hook contract to verify your environment setup. This contract tracks swap and liquidity modification events. ```solidity // SPDX-License-Identifier: MIT\npragma solidity ^0.8.24;\n\nimport {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";\n\nimport {Hooks} from "v4-core/src/libraries/Hooks.sol";\nimport {IPoolManager} from "v4-core/src/interfaces/IPoolManager.sol";\nimport {PoolKey} from "v4-core/src/types/PoolKey.sol";\nimport {PoolId, PoolIdLibrary} from "v4-core/src/types/PoolId.sol";\nimport {BalanceDelta} from "v4-core/src/types/BalanceDelta.sol";\nimport {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "v4-core/src/types/BeforeSwapDelta.sol";\n\ncontract CounterHook is BaseHook {\n using PoolIdLibrary for PoolKey;\n\n // NOTE: ---------------------------------------------------------\n // state variables should typically be unique to a pool\n // a single hook contract should be able to service multiple pools\n // ---------------------------------------------------------------\n\n mapping(PoolId => uint256 count) public beforeSwapCount;\n mapping(PoolId => uint256 count) public afterSwapCount;\n\n mapping(PoolId => uint256 count) public beforeAddLiquidityCount;\n mapping(PoolId => uint256 count) public beforeRemoveLiquidityCount;\n\n constructor(IPoolManager _poolManager) BaseHook(_poolManager) {}\n\n function getHookPermissions() public pure override returns (Hooks.Permissions memory) {\n return Hooks.Permissions({\n beforeInitialize: false,\n afterInitialize: false,\n beforeAddLiquidity: true,\n afterAddLiquidity: false,\n beforeRemoveLiquidity: true,\n afterRemoveLiquidity: false,\n beforeSwap: true,\n afterSwap: true,\n beforeDonate: false,\n afterDonate: false,\n beforeSwapReturnDelta: false,\n afterSwapReturnDelta: false,\n afterAddLiquidityReturnDelta: false,\n afterRemoveLiquidityReturnDelta: false\n });\n }\n\n // -----------------------------------------------\n // NOTE: see IHooks.sol for function documentation\n // -----------------------------------------------\n\n function _beforeSwap(address, PoolKey calldata key, IPoolManager.SwapParams calldata, bytes calldata)\n internal\n override\n returns (bytes4, BeforeSwapDelta, uint24)\n {\n beforeSwapCount[key.toId()]++;\n return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);\n }\n\n function _afterSwap(address, PoolKey calldata key, IPoolManager.SwapParams calldata, BalanceDelta, bytes calldata)\n internal\n override\n returns (bytes4, int128)\n {\n afterSwapCount[key.toId()]++;\n return (BaseHook.afterSwap.selector, 0);\n }\n\n function _beforeAddLiquidity(\n address,\n PoolKey calldata key,\n IPoolManager.ModifyLiquidityParams calldata,\n bytes calldata\n ) internal override returns (bytes4) {\n beforeAddLiquidityCount[key.toId()]++;\n return BaseHook.beforeAddLiquidity.selector;\n }\n\n function _beforeRemoveLiquidity(\n address,\n PoolKey calldata key,\n IPoolManager.ModifyLiquidityParams calldata,\n bytes calldata\n ) internal override returns (bytes4) {\n beforeRemoveLiquidityCount[key.toId()]++;\n return BaseHook.beforeRemoveLiquidity.selector;\n }\n} ``` -------------------------------- ### Install Uniswap AI Plugins for Claude Code Source: https://github.com/uniswap/docs/blob/main/docs/llms/overview.md Commands to add the Uniswap marketplace and install individual plugins within Claude Code for specific functionalities like v4 hook development or swap integration. ```bash # Add the Uniswap marketplace /plugin marketplace add uniswap/uniswap-ai # Install individual plugins claude plugin add uniswap-hooks # v4 hook development claude plugin add uniswap-trading # Swap integration (+ pay-with-any-token skill) claude plugin add uniswap-viem # EVM / viem / wagmi claude plugin add uniswap-driver # Token discovery & deep links claude plugin add uniswap-cca # CCA auction configuration ``` -------------------------------- ### V3 Swap Exact Input Command Parameters Source: https://github.com/uniswap/docs/blob/main/docs/contracts/universal-router/02-technical-reference.md Use this command for deterministic trades where the input amount is known. It calls the `v3SwapExactInput` function. ```solidity address recipient uint256 amountIn uint256 amountOutMin bytes path bool payerIsUser ``` -------------------------------- ### Get Quote for Exact Input Source: https://github.com/uniswap/docs/blob/main/docs/sdk/v4/guides/swaps/quoting.md Use the `callStatic.quoteExactInputSingle` method on the Quoter contract to simulate a swap and get the expected output amount for a given input. This method is preferred over direct on-chain calls due to gas costs. ```typescript const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle({ poolKey: CurrentConfig.poolKey, zeroForOne: CurrentConfig.zeroForOne, exactAmount: CurrentConfig.amountIn, hookData: CurrentConfig.hookData, }) console.log(formatUnits(quotedAmountOut.amountOut, USDC_TOKEN.decimals)); ```