[Ethereum] How to read any token units received in a Smart Contract? (Ether and other Tokens)

contract-developmentsoliditytokenstransactions

I would like to know how to identify units of specific tokens received in a Smart Contract.

I am building a Smart Contract that can receive ether or other ethereum tokens and in exchange for the tokens received another token will be issued.

Which code can I use in the Smart Contract to identify how many ether or any other token are received?

And in which function should it be used?

Best Answer

The answers given so far do not address the question. The Idea is that you create a smart contract. This smart contract can receive ether or other tokens. The question is, how can be checked how many tokens of a particular 'type' were received?

In general, a token (ERC20 like) is just a balance. When you see tokens in your wallet, this is the wallet accessing the balance in the contract (because the contract for that token has issued an event indicating a change in the balance). This mean, you do not really receive the tokens in your wallet.

Now, assume you created the token_1 using a contract. Another contract has created the token_2. If I send the token_2 to your contract address, what happens is that the balance of the contract that created Token_2 updates the balance and adds your contract's address to the bookkeeping. Your contract will not react to this, and this is why usually sending tokens to wrong contract's address results in lost funds.

You will need to listen to the events of the other contract to know who and how much of a particular token has been sent to you, but this can not be done in the smart contract, you will need an off-chain code that read the events.

I hope this help.

Related Topic