当前位置:网站首页>IDO预售代币合约系统开发技术说明及源码分析
IDO预售代币合约系统开发技术说明及源码分析
2022-08-02 21:56:00 【DD_MrsFu123】
Core逻辑
Core逻辑实现了单个交易对的逻辑。通过UniswapV2Factory可以创建一个个Pair(交易池)。每个具体实现逻辑在UniswapV2Pair中。
1. mint
每个交易对创建流动性。
function mint(address to) external lock returns (uint liquidity) {
因为在调用mint函数之前,在addLiquidity函数已经完成了转账,所以,从这个函数的角度,两种代币数量的计算方式如下:
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
当前的balance是当前的reserve加上注入的流动性的代币数量。
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
_mint(to, liquidity);
流动性liquidity的计算方式在第一次提供流动性时和其他时候稍稍不同。第一次提供流动性的计算公式如下:
liquidity = sqrt(x0*y0) - min
其中min是10^3。也就是说,第一次提供流动性是有最小流动性要求的。其他提供流动性的计算公式如下:
liquidity = min((x0/reserve0*totalsupply), (y0/reserve1*totalsupply))
也就说,按照注入的流动性和当前的reserve的占比一致。
2. burn
burn函数用在抽取流动性。burn逻辑和mint逻辑类似。
function burn(address to) external lock returns (uint amount0, uint amount1) {
3. swap
swap函数实现两种代币的兑换。
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
一个交易池的swap操作支持两个方向的兑换,可以从TokenA换到TokenB,或者TokenB换到TokenA。
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
因为在swapExactTokensForTokens的getAmountOut函数已经确定兑换处的金额。所以,先直接转账。
在不做swap之前,balance应该和reserve相等的。通过balance和reserve的差值,可以反推出输入的代币数量:
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
确保反推的输入代币数量不小于零。
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
边栏推荐
猜你喜欢
随机推荐
Software testing pen questions 1 (with answers)
Word operation: adjust the English font individually
ML之PDP:基于titanic泰坦尼克是否获救二分类预测数据集利用PDP部分依赖图对RF随机森林和LightGBM模型实现可解释性案例
Summary of @Transactional transaction invocation and effective scenarios
行业 SaaS 微服务稳定性保障实战
万物智联时代,悄然走入生活
If the watermark according to how to realize the function
AcWing 2983. 玩具
Add and delete all these years, finally planted in MySQL architecture design!
多租户的多种实现方案
Matplotlib drawing core principles explain (more detailed)
mysql根据多字段分组——group by带两个或多个参数
【TypeScript】深入学习TypeScript模块化
VS保存后Unity不刷新
采用QT进行OpenGL开发(三)着色器编程
面试了个985毕业的,回答“性能调优”题时表情令我毕生难忘
搭建直播平台,使用node生成验证码图片,并进行验证
牛客刷题:数组排序
学习Autodock分子对接
成功解决TypeError: can‘t multiply sequence by non-int of type ‘float‘