Search code examples
solidity

How can I check how much ether has been transferred from one address to another?


It's common for contracts to use a field to keep track of the ether it's been sent.

mapping(address => uint256) balances;

But is there a way to query the blockchain from with the contract to see how much the contract has ever been sent from another address?


Solution

  • Usually contracts dont keep track of how much ether they have been sent. The example of the balances mapping is the typical implementation of erc20 contracts to keep tracks of users balances of the token that erc20 contract is issuing.

    You can query the eth balance of any contract, ie. how much eth that contract owns at the moment. It's also possible to find out how much eth any individual address sent to a contract since all transaction data is public, however you would need to aggregate and add up all of these transactions with some script. There also may be some services that can do this for you that people have developed.

    If you are asking can you obtain the data of how much eth each user sent to a contract on chain, it depends on if you are writing the contract or not. You can build in a payable function for users to call that keep track of how much each user sent. You can also do this with the fallback function, which is triggered whenever users send any eth to the contract directly.

    If you want to do this for a contract already deployed by someone else, there's not a clean way to get that data on chain, aka into a smart contract without using some kind of oracle to fetch data from offchain. Either the contract builds up the data inside of it as people pay eth to it (and stores that data in its local contract state), or it needs be calculated off chain, which it easily can be if you have access to all the blockchain data, however you will need to check every transaction to the contract to add all that information up.