Solidity Library Issues – Troubleshooting Why Library Method Returns 0 in Solidity

librarysolidity

Have this library method which I use several times in a contract, but in one specific function returns 0 even though I'm logging in the value generated in the library per se and checking that it does return a value.

So why is it 0 when I call it from within the contract in this specific function only?

Library:

library FixedPointMathLib { 
   function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal view returns (uint256) {
        uint z;
        assembly {
            z := mul(x, y)

            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            z := div(z, denominator)
        }
        console.log(z); //returns a value in both convertToShares() and convertToAssets()
        return z;
    }
...
}

Contract:

contract ERC4626 {
   AppStorage s;
   using FixedPointMathLib for uint256;

   function convertToShares(uint256 assets) public view virtual returns (uint256) { 
        return s.index.mulDivDown(assets * 100, 10 ** 22); //returns a value
   }

   function convertToAssets(uint256 shares) public view virtual returns (uint256) {
        uint vaultBalance = IERC20(s.crvTricrypto).balanceOf(address(this));

        uint256 assets = shares.mulDivDown(vaultBalance, 100 * 1 ether) / 10 ** 36;
        console.log(assets); // <------- returns 0
        
        return assets;
    }
...
}

Best Answer

In convertToAssets, you're dividing the result of mulDivDown by 10 ** 36. That's a pretty large number, and you would get 0 if the result of mulDivDown was lower than that number.

Related Topic