Skip to content

Instantly share code, notes, and snippets.

@gcrsaldanha
Created June 15, 2020 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcrsaldanha/e1a3903e3ec50a8a7b90ad2497746b43 to your computer and use it in GitHub Desktop.
Save gcrsaldanha/e1a3903e3ec50a8a7b90ad2497746b43 to your computer and use it in GitHub Desktop.
HTTP + Ethereum example
'''
Important docs
https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.getTransaction
https://web3py.readthedocs.io/en/stable/web3.eth.html#web3.eth.Eth.getTransactionReceipt
'''
import hashlib
import json
import os
from flask import Flask, request, jsonify
from hexbytes import HexBytes
from web3 import Web3, HTTPProvider
from eth_typing.ethpm import URI
from web3.datastructures import AttributeDict
ETH_PROVIDER_ADDRESS: URI = URI('http://127.0.0.1:7545') # I'm using Ganache as my blockchain provider
contract_json_path = os.environ.get('DEPLOYED_CONTRACT_BUILD') # path to the compile contract (JSON)
contract_address = os.environ.get('DEPLOYED_CONTRACT_ADDRESS') # address on the blockchain of deployed smart contract (hex)
with open(contract_json_path) as f:
info_json = json.load(f)
contract_abi = info_json["abi"] # necessary to load the contract in the app.py
app = Flask(__name__)
w3 = Web3(HTTPProvider(ETH_PROVIDER_ADDRESS))
payer_account = w3.eth.accounts[0]
w3.eth.defaultAccount = w3.eth.accounts[0]
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
def add_to_blockchain(hashed_data):
tx_hash = contract.functions.saveTransaction(hashed_data, w3.eth.defaultAccount).transact()
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
return tx_receipt
@app.route('/add-transaction', methods=['POST'])
def add_transaction():
if not request.data:
return jsonify({'error': 'Data must be passed in payload'}), 400
payload = request.json.get('payload', None)
if not payload:
return jsonify({'error': 'payload cannot be empty'}), 400
hashed_data = hashlib.sha256(payload.encode()).hexdigest()
wpc_response = add_to_blockchain(hashed_data)
return 'success'
@app.route('/list-transactions', methods=['GET'])
def list_transactions():
# TODO: not sure we will need it.
return jsonify([])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment