This is the code I've been using, I simply want to be able to deposit tokens into a smart contract and allow the owner to withdraw. I am not sure how to modify this to allow the owner to withdraw the stored tokens inside the smart contract, can anyone help me out?
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
interface USDC {
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
contract transferUSDc {
USDC public USDc;
address owner;
mapping(address => uint) public stakingBalance;
constructor() {
USDc = USDC(0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56);
owner = msg.sender;
}
function depositTokens(uint $USDC) public {
// amount should be > 0
// transfer USDC to this contract
USDc.transferFrom(msg.sender, address(this), $USDC * 10 ** 6);
// update staking balance
stakingBalance[msg.sender] = stakingBalance[msg.sender] + $USDC * 10 ** 6;
}
// Unstaking Tokens (Withdraw)
function withdrawalTokens(address _addressChange) public {
// requires withdrawal tokens function to only be called by creator of contract
require (msg.sender == owner);
// reset balance to 0
stakingBalance[_addressChange] = 0;
}
function checkBalance(address _address) public view returns (uint) {
return stakingBalance[_address];
}
function ownerWithdrawal(uint _amount) public {
require (msg.sender == owner);
USDc.transferFrom(address(this), msg.sender, _amount * 10 ** 6);
}
}
I've tried modifying the contract, but nothing has changed.
how to modify this to allow the owner to withdraw the stored tokens inside the smart contract
You can invoke the transfer()
function on the token contract from your contract. The token sender is the caller of the transfer()
function, which is your contract.
function withdrawalTokens(address _addressChange) public {
require (msg.sender == owner);
// to prevent reentrancy attack
uint256 amountToWithdraw = stakingBalance[_addressChange];
stakingBalance[_addressChange] = 0;
// transfer
// from this contract address (caller of `transfer()`)
// to the caller of the `withdrawalTokens()` function (the `owner` address)
USDc.transfer(msg.sender, amountToWithdraw);
}