Solidity // StableMath._calcOutGivenIn function _calcOutGivenIn( uint256 amplificationParameter, uint256[] memory balances, uint256 tokenIndexIn, uint256 tokenIndexOut, uint256 tokenAmountIn, uint256 invariant ) internal pure returns (uint256) { /************************************************************************************************************** // outGivenIn token x for y - polynomial equation to solve// // ay = amount out to calculate// // by = balance token out// // y = by - ay (finalBalanceOut)// // D = invariantDD^(n+1)// // A = amplification coefficienty^2 + ( S + ----------- D) * y -------------- = 0// // n = number of tokens(A * n^n)A * n^2n * P// // S = sum of final balances but y// // P = product of final balances but y// **************************************************************************************************************/
// Amount out, so we round down overall. balances[tokenIndexIn] = balances[tokenIndexIn].add(tokenAmountIn);
// No need to use checked arithmetic since `tokenAmountIn` was actually added to the same balance right before // calling `_getTokenBalanceGivenInvariantAndAllOtherBalances` which doesn't alter the balances array. balances[tokenIndexIn] = balances[tokenIndexIn] - tokenAmountIn;
其中充当BPT 价格基准的部分为不变值 D,也就是操控 BPT 价格需要操控 D。往下分析 D 的计算过程:
Solidity // StableMath._calculateInvariant function _calculateInvariant(uint256 amplificationParameter, uint256[] memory balances) internal pure returns (uint256) { /********************************************************************************************** // invariant// // D = invariantD^(n+1)// // A = amplification coefficientAn^n S + D = A D n^n + -----------// // S = sum of balancesn^n P// // P = product of balances// // n = number of tokens// **********************************************************************************************/
// Always round down, to match Vyper's arithmetic (which always truncates).
uint256 sum = 0; // S in the Curve version uint256 numTokens = balances.length; for (uint256 i = 0; i < numTokens; i++) { sum = sum.add(balances[i]); // balances 是缩放后的值 } if (sum == 0) { return 0; }
uint256 prevInvariant; // Dprev in the Curve version uint256 invariant = sum; // D in the Curve version uint256 ampTimesTotal = amplificationParameter * numTokens; // Ann in the Curve version
// 迭代计算 D... // D 的计算影响 balances 的精度 for (uint256 i = 0; i < 255; i++) { uint256 D_P = invariant;
// amountOut tokens are exiting the Pool, so we round down. return _downscaleDown(amountOut, scalingFactors[indexOut]); }
缩放操作:
Solidity // ScalingHelpers.sol function _upscaleArray(uint256[] memory amounts, uint256[] memory scalingFactors) pure { uint256 length = amounts.length; InputHelpers.ensureInputLengthMatch(length, scalingFactors.length);
for (uint256 i = 0; i < length; ++i) { amounts[i] = FixedPoint.mulDown(amounts[i], scalingFactors[i]); // 向下舍入 } }
// FixedPoint.mulDown function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; _require(a == 0 || product / a == b, Errors.MUL_OVERFLOW);
// We access both token indexes without checking existence, because we will do it manually immediately after. EnumerableMap.IERC20ToBytes32Map storage poolBalances = _generalPoolsBalances[request.poolId]; uint256 indexIn = poolBalances.unchecked_indexOf(request.tokenIn); uint256 indexOut = poolBalances.unchecked_indexOf(request.tokenOut);
if (indexIn == 0 || indexOut == 0) { // The tokens might not be registered because the Pool itself is not registered. We check this to provide a // more accurate revert reason. _ensureRegisteredPool(request.poolId); _revert(Errors.TOKEN_NOT_REGISTERED); }
// EnumerableMap stores indices *plus one* to use the zero index as a sentinel value - because these are valid, // we can undo this. indexIn -= 1; indexOut -= 1;
uint256 tokenAmount = poolBalances.length(); uint256[] memory currentBalances = new uint256[](tokenAmount);
request.lastChangeBlock = 0; for (uint256 i = 0; i < tokenAmount; i++) { // Because the iteration is bounded by `tokenAmount`, and no tokens are registered or deregistered here, we // know `i` is a valid token index and can use `unchecked_valueAt` to save storage reads. bytes32 balance = poolBalances.unchecked_valueAt(i);
if (i == indexIn) { tokenInBalance = balance; } else if (i == indexOut) { tokenOutBalance = balance; } }
// 执行交换 // Perform the swap request callback and compute the new balances for 'token in' and 'token out' after the swap amountCalculated = pool.onSwap(request, currentBalances, indexIn, indexOut); (uint256 amountIn, uint256 amountOut) = _getAmounts(request.kind, request.amount, amountCalculated); tokenInBalance = tokenInBalance.increaseCash(amountIn); tokenOutBalance = tokenOutBalance.decreaseCash(amountOut);
// 更新存储 // Because no tokens were registered or deregistered between now or when we retrieved the indexes for // 'token in' and 'token out', we can use `unchecked_setAt` to save storage reads. poolBalances.unchecked_setAt(indexIn, tokenInBalance); poolBalances.unchecked_setAt(indexOut, tokenOutBalance); }