Blockchain Storage – How to Store Value (String or Hex) in Ethereum Blockchain Transactions

blockchainpythonstorageweb3.py

I have been looking through various tutorials (many of them outdated or with broken links) to figure out how to store and retrieve a simple string or hex value in the ETH blockchain. For my purposes (and intended application I am developing) it would be best to be able to interface with the blockchain via Python.

I have tried using web3 and pyethereum with not much success. The furthest I have gotten is using the following code with the web3 interface.

What pieces am I missing and how can I properly store and retrieve a value on the ETH blockchain?

How do I create a contract and store / retrieve a value from it?

def eth_black_magic(hex_value):

    web3 = Web3(HTTPProvider('http://localhost:8545')) # what URL should I point at?

    user1 = 'xxx' # what goes here?
    user2  = 'xxx' # what goes here?

    transaction = {'from': user2, 'to':user1, 'data': hex_value}

    transaction_hash = web3.eth.sendTransaction(transaction)

Best Answer

A general approach could look like:

  1. Create a contract that has a variable, say uint public val
  2. Add a method on the contract that sets that variable, say setVal(uint)
  3. Generate the contract ABI
  4. Initialize Web3(...), with a connection to your client
  5. Create a contract object with the source code
  6. Deploy the contract with contract.deploy()
  7. Use the ABI and deployed address to create a Contract object in web3

remix could be a good option for steps 1-3. You can use web3.py for steps 4-7. Docs and tutorials should exist for all the individual steps.

Now, you are all set up with a deployed contract. You can get and set val in python with:

  • Set the variable with contract.transact().setVal(1337)
  • Get the variable with contract.call().val()