Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the amount of token sent to a smart contract via the fallback function in solidity

Let’s say I have a token A and a smart contract B.
A user sent some amount of A to to the contract B by direct transfer through his wallet.
In the fallback function of the smart contract B, how will I get the amount of token A that was sent?

msg.value did’nt give me anything since it’s not Eth that was sent.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When your contract receives ERC-20 tokens, the fallback() function is not invoked – nor any other function. Meaning, your contract does not get notified about incoming ERC-20 transfers unless you pull them with transferFrom().

contract YourContract {
    function pullTokens() external {
        // need to have prior approval
        tokenContract.transferFrom(msg.sender, address(this), amount);
    }
}

Note: Some other fungible token standards define these notification functions for recipient contracts – for example ERC-777 and its function tokensReceived().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading