# Uniswap v2 factory **Published by:** [web3zoom](https://paragraph.com/@web3zoom/) **Published on:** 2025-08-02 **URL:** https://paragraph.com/@web3zoom/uniswap-v2-factory ## Content 看了uniswap v2 很多遍,对于其中代码的熟悉程度在慢慢提高,因此做了些笔记来记录其中的要点: factory合约的作用: 创建代币对createPair: 通过使用salt方式,通过create2方法对生成代币对地址,同时还初始化了代币对合约。 对代币对进行排序: (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); 这样做的好处: 1、保证交易对的一致性,并避免某些错误(例如:同一对代币不同的排序会导致流动性池地址不同,进而导致交易失败或价格错误)。 2、防止潜在攻击,比如:重入攻击 3、流动性池子管理,可能会影响交易价格和滑点 4、价格计算,避免不必要的价格波动 pragma solidity =0.5.16; import './interfaces/IUniswapV2Factory.sol'; import './UniswapV2Pair.sol'; contract UniswapV2Factory is IUniswapV2Factory { address public feeTo; address public feeToSetter; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(UniswapV2Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IUniswapV2Pair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external { require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); feeToSetter = _feeToSetter; } } ## Publication Information - [web3zoom](https://paragraph.com/@web3zoom/): Publication homepage - [All Posts](https://paragraph.com/@web3zoom/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@web3zoom): Subscribe to updates - [Twitter](https://twitter.com/primer2011): Follow on Twitter