0

I have a common problem while converting a 18 decimal WMatic to a 6 decimal USDC price on polygon mainnet. I have the following scenario:

I took a flash loan of 70 WMatic from Aave. I deposited that 70 WMatic + 30 WMatic (from my wallet) to a lending platform like Compound III. After successfully depositing to Compound III, I want to borrow some USDC based on my collateral (Compound III doesn't allow borrowing & deposit of the same token), which I will swap to WMatic to payback the flash loan (with some fees).

So my question here is how can I calculate the exact amount of USDC I should borrow to successfully payback the flash loan in solidity?

I have tried it several times but end up calculating wrong amount in solidity.

1 Answer 1

1

It all depends on the DEX you will use to swap. If you go for UniV2 (or a fork), you can use this method:

uint256 amountOut = 70 ether;  // the amount of WMATIC you need
(uint256 reserveIn, uint256 reserveOut) = UniswapV2Library.getReserves(FACTORY_ADDRESS, USDC_ADDRESS, WMATIC_ADDRESS);
uint256 amountIn = UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);

(You need to import UniswapV2Library in your contract.)

In any case, I don't think Chainlink is useful here. Also you don't have to care about the decimals of the token. To borrow amountIn USDC from Compound you can use something like:

cUSDC.borrow(amountIn);

and to make the swap you can use the swapTokensForExactTokens of the router.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.