6. Build a web3 web with windows
fhe-web-python/
├── app.py
├── abi.json
├── requirements.txt
├── .env
├── README.md
└── templates/
└── index.htmlfrom flask import Flask, jsonify, render_template
from web3 import Web3
from dotenv import load_dotenv
import os
import json
load_dotenv()
app = Flask(__name__)
# Kiểm tra file
if not os.path.exists('abi.json'):
raise FileNotFoundError("Không tìm thấy abi.json!")
# Kết nối
RPC_URL = os.getenv('RPC_URL')
w3 = Web3(Web3.HTTPProvider(RPC_URL))
if not w3.is_connected():
raise Exception("Không kết nối được Sepolia!")
print(f"Kết nối thành công! Block: {w3.eth.block_number}")
# Contract
CONTRACT_ADDRESS = os.getenv('CONTRACT_ADDRESS')
with open('abi.json', 'r') as f:
ABI = json.load(f)
contract = w3.eth.contract(address=CONTRACT_ADDRESS, abi=ABI)
# Account
PRIVATE_KEY = os.getenv('PRIVATE_KEY')
account = w3.eth.account.from_key(PRIVATE_KEY)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/get_count')
def get_count():
try:
encrypted = contract.functions.getCount().call()
return jsonify({'count': 'Encrypted'})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/increment', methods=['POST'])
def increment():
return send_tx('increment')
@app.route('/decrement', methods=['POST'])
def decrement():
return send_tx('decrement')
def send_tx(func_name):
try:
func = getattr(contract.functions, func_name)
# Tạo input đúng định dạng
encrypted_input = b'\x00' * 32 # bytes32
proof = b'\x00' * 64 # proof giả
tx = func(encrypted_input, proof).build_transaction({
'from': account.address,
'gas': 3000000,
'gasPrice': w3.to_wei('20', 'gwei'),
'nonce': w3.eth.get_transaction_count(account.address),
})
signed_tx = w3.eth.account.sign_transaction(tx, PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
return jsonify({'tx_hash': tx_hash.hex()})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True, port=5000)
Last updated