I am implementing a simple tokensale platform using web3.js.

It should display to the user 'You have already sent us 2.3 ETH and recieved 1003 tokens'.

It is easy to find out how many tokens the user has by using balanceOf(), but how can I find how much ETH that user sent to the contract. I can't calculate it based on tokens held, because the rate would change.

In the contract I have:

mapping (address => uint256) public amountPurchased;

I am currently using:

contractAbi = JSON.parse('[{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"amountPurchased","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]');

var crowdsaleContract = web3.eth.contract(contractAbi);

var crowdsale = crowdsaleContract.at('[TOKENSALE ADDRESS]');

crowdsale.amountPurchased.call(userAddress, function(err, result){

but the result is always 0

  • either by reading the log or by adding the recived ethers in your payable fct Apr 16 '18 at 8:20

You could use a mapping(address => uint) spendByAddress to capture total spend (in Wei) and increase this total every time a user sends ether to your payable function. When new donations are received you could then query spendByAddress[msg.sender] to return the total amount of Ether received from that address.

The same approach could be used to map total token allocation too, so you keep track of how many tokens they've received over time, even if they've sold/transferred them elsewhere after they bought them from you.

  • I have a mapping like this in my contract. I have updated my original post to show how I am trying to access it, thanks.
    – koukotsu
    Apr 16 '18 at 9:09
  • in your ABI you're defining amountPurchased but in your script you're calling totalPurchase - try calling amountPurchased instead
    – TC8
    Apr 16 '18 at 9:34
  • ah yeh, I noticed that, it has been changed now, but still same result. Not sure what else the issue could be.
    – koukotsu
    Apr 16 '18 at 9:42
  • 1. Try checking for errors with if(!error) {alert(result)} else {alert(error)} and see if something else is the issue here, and 2. Your ABI doesn't include any payable functions (or any other functions, for that matter) - have you successfully sent the contract any Ether for the result to actually be >0?
    – TC8
    Apr 16 '18 at 9:50
  • I have tried that but it returns no error. I only need to read the 1 mapping so I don't need the full ABI, right?
    – koukotsu
    Apr 16 '18 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.