This line doesn't make sense:
ERC20Interface(token).approve(msg.sender, amount);
There are two actors in an approve
call: the token owner and the token spender.
The token owner calls approve(spender, amount)
so that the spender can then spend those tokens.
Here, the contract is the token owner and the user who called the function is the spender.
I think what you want is for the user to call approve(contract, amount)
before calling hodl
, and then you want to do token.transferFrom(msg.sender, this, amount)
to transfer those tokens from the user to the contract.
1) Depends on what you mean with a "trigger". Smart contracts can never do anything without someone/something issuing them a transaction. So contracts can't "monitor" things by themselves or run in the background in that sense. Otherwise, yes, a smart contract can transfer tokens to another contract/address.
2) Because all action is initiated through a transaction, the original transaction sender is the "signer". The one who issues the original transaction also has to pay (with gas) for all the transactions that occur in the possible chain of contracts.
EDIT
After the asker added more information about the problem:
Sending tokens to another address is done by calling the transfer
method in the ERC20 token contract. That method should actually just modify the contract A's inner state, so transferring tokens from contract B only requires B to call A's transfer
function. B does not need to "send" any tokens itself - it only needs to call the transfer
function to change the ownership of said tokens.
Best Answer
For 1 you may use
web3.eth.getCode(address)
function of Web3 API. For contract addresses it returns contract byte code, while for non-contract addresses it returns something like"0x"
.For 3 it depends on what "public" means for you. If you mean whether smart contract has verified source code published at Etherscan.io, then you may use either API call to obtain source code by contract address, or download full list of all contract addresses that has source code verified: https://etherscan.io/apis#contracts .
The 2 is most tricky, because there is no reliable way to know whether smart contract implements particular interface or not, other than analyzing its source code. Though there could be some hints. You may check whether smart contract ever logged
Transfer(address indexed, address indexed, uint256)
(for ERC-20) orTransfer(address indexed, address indexed, uint256 indexed)
(for ERC-721) event, but this way you will not recognize token contracts whose tokens were never transferred yet.