I’m trying to code my own flash loan program to provide users with funds and I’ve come across one pickle that I can’t figure out. I want to allow users to be able to get a flash loan with my smart contract but I need a way to ensure that I get my funds back if anything goes wrong.
I checked with ChatGPT and it stated that there were ways that I could revert the transaction back to its initial state after someone has taken a flash loan.
My code so far is:
`// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract Ownable {
address payable public owner;
constructor() {
owner = payable(msg.sender);
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this function");
_;
}
}
contract Forwarder is Ownable {
address public latestWalletAddress;
// Counter for generating wallet addresses
uint256 private walletCounter;
// Mapping to store generated wallet addresses
mapping(uint256 => address) public wallets;
// Event to emit when a new wallet is generated
event WalletGenerated(address indexed walletAddress);
receive() external payable {
// Receive funds
}
function forward(address payable _recipient) external onlyOwner {
_recipient.transfer(address(this).balance);
}
function sendFundsBack(address payable _recipient) external onlyOwner {
address balanceThis2 = generateWallet();
_recipient.transfer(balanceThis2.balance);
}
function generateWallet() internal returns (address) {
//wallet is attached to addressContract it will acceptthe funds but in another wallet
uint256 addressContract = address(this).balance;
// Increment wallet counter
walletCounter++;
// Derive address from the counter
address walletAddress = address(uint160(uint256(keccak256(abi.encodePacked(owner, walletCounter)))));
// Store the wallet address
wallets[walletCounter] = walletAddress;
// Emit event for the new wallet address
emit WalletGenerated(walletAddress);
return walletAddress;
}
function withdrawtoOwner(address payable destination) external {
require(msg.sender == owner, "Only the owner can withdraw");
require(destination != address(0), "Invalid destination address");
require(address(this).balance > 0, "Contract balance is zero");
destination.transfer(address(this).balance);
}
}
`
This is code to send a transaction to another wallet after I have sent funds to the smart contract Manually. I just need someone to help me add in a function that reverts the transaction back to me even if the funds are sent to another wallet.