1

I've a contract which has a price attribute. Price goes up with each transaction.

contract MyContract{
    uint256 public price;

    .... other methods
}

For transaction I receive following event data in a callback:

{ address: '0xa6....................',
  blockNumber: 15655,
  transactionHash: '0xb..........................',
  transactionIndex: 1,
  blockHash: '0xca........................',
  logIndex: 0,
  removed: false,
  event: 'Transfer',
  args:
   { from: '0x3dc..................',
     to: '0x64b...................',
     amount: 1 
    }

}

Is there a way I could obtain the price of the contract, at a specific transaction using above event data(which has already happened)?

1

If you know the location of the price in storage (e.g. 0, if it's the first state variable), then you can use web3.eth.getStorageAt:

web3.eth.getStorageAt(address, 0, blockNumber);

EDIT

Per @carver's comment below, this doesn't really give you a per-transaction view, just a per-block view.

  • Could you please explain what is storage location? Is it the position of the attribute in the contract? If I had another single attribute before "price", "price" location will be 1? – sanandrl Jan 9 '18 at 16:22
  • It depends how big the thing before price is. If it's 256 bits, then yes. See solidity.readthedocs.io/en/develop/… for the details. – smarx Jan 9 '18 at 16:30
  • I see. But I still don't understand how I could relate transactionHash to it? Kindly check the update to the question, I added the event data I receive in the callback. – sanandrl Jan 9 '18 at 16:50
  • The transaction hash gives you the block number. You pass the block number as the third parameter to web3.eth.getStorageAt. – smarx Jan 9 '18 at 16:52
  • 1
    Note that if you have multiple transactions in a block, you will only see the price state at the end of the last transaction this way. The best answer is to change the event (or add a new one) to include the price. – carver Jan 9 '18 at 17:05

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.