To execute the transfer
or transferFrom
ERC-20 token functions in a Solidity contract, ie:
// moves token from contract to personal address
ERC20Token.transfer(msg.sender, tokenamount);
// moves token from personal account to contract
ERC20Token.transferFrom(msg.sender, address(this), tokenamount);
I must first execute the approve
function in javascript outside solidity, like this:
contract = w3.eth.contract(address=contract_address, abi=contract_abi['abi'])
nonce = w3.eth.getTransactionCount(wallet_address)
txn_dict = contract.functions.approve(contract_address, amount).buildTransaction({
'gas': 500000,
'gasPrice': w3.toWei(gas_p, 'gwei'),
'nonce': nonce,
})
signed_txn = w3.eth.account.signTransaction(txn_dict, private_key=wallet_private_key)
result = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
I was wondering if it was possible to put that 'approve' method into the Solidity contract, but then thought, this would be bad because a malicious contract might execute the approve
& transfer
functions within the same block, allowing a token overspend. Is that the right way to think about it? [I could be wrong in my assumption that you cannot approve an ERC-20 token expenditure within a Solidity contract]
It's interesting because, on one hand, I could imagine the token's allowance amount would be modified when a transfer function was called, or not, depending on whether the Solidity contracts are run sequentially in a block, or simultaneously.