Flashloan (V3)
Last updated
Last updated
Pulsar pools provide flash
method to flashloan.
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/core/contracts/interfaces/callback/IAlgebraFlashCallback.sol';
import '@cryptoalgebra/periphery/contracts/libraries/TransferHelper.sol';
contract SimpleFlasher {
// Variables so we can verify callback
address poolCalled;
uint256 amount0;
uint256 amount1;
function flash(
address pool,
address recipient,
uint256 _amount0,
uint256 _amount1
) external {
// setting the variables
poolCalled = pool;
amount0 = _amount0;
amount1 = _amount1;
// requesting flash loan to `recipient` address
IAlgebraPool(pool).flash(recipient, amount0, amount1, bytes(''));
// cleaning up
poolCalled = address(0);
amount0 = 0;
amount1 = 0;
}
function algebraFlashCallback(
uint256 fee0,
uint256 fee1,
bytes calldata data
) external override {
require(msg.sender == poolCalled, "only pool can call");
// do the magic here ...
// repay to pool
TransferHelper.safeTransfer(IAlgebraPool(msg.sender).token0(), msg.sender, amount0 + fee0);
TransferHelper.safeTransfer(IAlgebraPool(msg.sender).token1(), msg.sender, amount1 + fee1);
}
}
import '@cryptoalgebra/core/contracts/interfaces/IAlgebraPool.sol';
import '@cryptoalgebra/core/contracts/interfaces/callback/IAlgebraFlashCallback.sol';
import '@cryptoalgebra/periphery/contracts/libraries/CallbackValidation.sol';
import '@cryptoalgebra/periphery/contracts/libraries/TransferHelper.sol';
contract MoreOptimalFlasher {
address immutable poolDeployer; // address of AlgebraPoolDeployer contract
constructor(_poolDeployer) {
poolDeployer = _poolDeployer;
}
function flash(
address pool,
address recipient,
uint256 amount0,
uint256 amount1
) external {
address token0 = IAlgebraPool(pool).token0();
address token1 = IAlgebraPool(pool).token1();
// requesting flash loan to `recipient` address
IAlgebraPool(pool).flash(recipient, amount0, amount1, abi.encode(token0, token1, amount0, amount1));
}
function algebraFlashCallback(
uint256 fee0,
uint256 fee1,
bytes calldata data
) external override {
(address token0, address token1, uint256 amount0, uint256 amount1) = abi.decode(data, (address, adrress, uint256, uint256));
CallbackValidation.verifyCallback(poolDeployer, token0, token1) // check if method is called by algebra pool, revert otherwise
// do the magic here ...
// repay to pool
TransferHelper.safeTransfer(token0, msg.sender, amount0 + fee0);
TransferHelper.safeTransfer(token1, msg.sender, amount1 + fee1);
}
}