I'm trying to understand the "getAmountsOut" function from Uniswap / Pancakeswap, line by line:
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'PancakeLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
source: https://bscscan.com/address/0x10ed43c718714eb63d5aa57b78b54704e256024e#code (line 336)
My superficial understanding is that, given an amount you are putting in, you want to find out how much you would get, given the current reserves and assuming no one else changes the reserves before you do a swap.
My Question:
But how does the code above accomplish that?
My Analysis of each line:
The require statement is just a check that makes sure we are looking at at least 2 tokens. Fair enough so far.
The amounts = new uint[](path.length)
is new to me, what is this called and what is it doing?
the amounts[0] = amountsIn;
is just replacing the value of amounts 0.
Also, I notice the function returns a uint[] memory amounts
, however I don't see a return
statement at the end of the function. Is a return statement not required? And is the variable "amounts" being declared in the signature of the function? I know that's how it works with parameters, but never assumed that the returns (...)
portion also can be used in this way. Is my understanding here correct?
The rest of the lines are also a bit confusing for me. If anyone else can explain them, would mean a lot.