深入了解阿凡達泰山眾籌商城系統(tǒng)開發(fā)詳情版及源碼功能
拆分后的交易計算 交易是否能夠結(jié)束的關(guān)鍵計算在SwapMath.computeSwapStep中完成,這里計算了交易是否能在目標(biāo)價格范圍內(nèi)結(jié)束,以及消耗的tokenIn和得到的tokenOut.這里摘取此函數(shù)部分代碼進行分析(這里僅摘取exactIn時的代碼): function computeSwapStep( uint160 sqrtRatioCurrentX96, uint160 sqrtRatioTargetX96, uint128 liquidity, int256 amountRemaining, uint24 feePips ) internal pure returns(邏輯及源碼I35模板7O98開發(fā)o7I8 uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount ) {案例及需求:mrsfu123 //判斷交易的方向,即價格降低或升高 bool zeroForOne=sqrtRatioCurrentX96>=sqrtRatioTargetX96; //判斷是否指定了精確的tokenIn數(shù)量 bool exactIn=amountRemaining>=0; ... if(exactIn){ //先將tokenIn的余額扣除掉最大所需的手續(xù)費 uint256 amountRemainingLessFee=FullMath.mulDiv(uint256(amountRemaining),1e6-feePips,1e6); //通過公式計算出到達目標(biāo)價所需要的tokenIn數(shù)量,這里對x token和y token計算的公式是不一樣的 amountIn=zeroForOne ?SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96,sqrtRatioCurrentX96,liquidity,true) :SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96,sqrtRatioTargetX96,liquidity,true);方案及源碼:yy625019 //判斷余額是否充足,如果充足,那么這次交易可以到達目標(biāo)交易價格,否則需要計算出當(dāng)前tokenIn能到達的目標(biāo)交易價 if(amountRemainingLessFee>=amountIn)sqrtRatioNextX96=sqrtRatioTargetX96; else //當(dāng)余額不充足的時候計算能夠到達的目標(biāo)交易價 sqrtRatioNextX96=SqrtPriceMath.getNextSqrtPriceFromInput( sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne ); }else{ ... }