The best practice for implementing this scenario would be to have the buyer first approve the contract to transfer the USDC from their account before calling the buyback function. This way, the contract can call the transferFrom() function without needing the buyer's address.
Here is an example of how this could be implemented:
The buyer calls the approve() function on the USDC contract, passing in the address of the buyback contract and the amount of USDC they wish to use for the buyback.
css
usdcAddress.approve(address(buybackContract), price);
The buyer then calls the buyback function on the buyback contract, passing in the address of the ERC20 token they wish to sell and the amount of tokens they wish to sell.
scss
buybackContract.buyback(tokenAddress, tokenAmount);
The buyback function in the buyback contract checks that the buyer has approved the contract to transfer the necessary amount of USDC, then calls the transferFrom() function on the USDC contract to transfer the funds from the buyer's account to the contract's account.
less
require(usdcAddress.allowance(msg.sender, address(buybackContract)) >= price, "Not enough approved USDC.");
usdcAddress.transferFrom(msg.sender, address(buybackContract), price);
Finally, the buyback function calls the transfer() function on the ERC20 token contract to transfer the bought tokens to the contract's address.
tokenAddress.transfer(address(buybackContract), tokenAmount);
It is important to note that the buyer has to trust the contract enough to approve it to transfer their funds, and also the contract should be designed to ensure the buyer's funds are safe and the buyer can get the correct amount of tokens they paid for.
Additionally, it's important to consider the gas fees and make sure the contract has enough balance to pay the gas fees before executing the transaction.
token.approve(type(uint256).max, operator)
as the owner approving operator to make infinite withdrawals withtransferFrom
. Unfortunately it doesn't seems to be the case for the current USDC implementation.