使用代码块解决stacktoodeep你是否也有过这样的报错信息:“stacktoodeep”这是因为solidity一个函数中可容纳的变量的数量最大为16个,超过这个数量就会报错那如果想在函数中声明更多的变量该怎么办呢?可以使用代码块如下所示://SPDX-License-I
title: 使用代码块解决 Error:stack too deep date: 2024-6-24 16:58 tags: null
使用代码块解决stack too deep
你是否也有过这样的报错信息:“stack too deep”
这是因为solidity一个函数中可容纳的变量的数量最大为16个,超过这个数量就会报错 那如果想在函数中声明更多的变量该怎么办呢?
可以使用代码块 如下所示:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import "hardhat/console.sol";
contract C {
function minimalScoping() public returns (string memory){
string memory para0="0xaaaa";
string memory para1="";
string memory para2="";
string memory para3="";
string memory para4="";
string memory para5="";
string memory para6="";
string memory para7="";
string memory para8="";
string memory para9="";
{ //A
string memory para10="";
string memory para11="";
string memory para12="";
string memory para15="";
string memory para17="lllll";
}
{ //B
string memory para18="lllll";
string memory para19="lllll";
string memory para20="lllll";
string memory para21="lllll";
string memory para22="lllll";
}
return para0;
}
}
在代码块A中,无法检测到B中的变量,同理,B中无法检测到A中的变量,因此,只要将部分变量写入代码块中,就可以做到在同一函数中声明大量变量
uniswap V2的UniswapV2Pair.sol的swap函数便使用了这个机制
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
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');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!