mHealth-Api / scripts /deploy_chatlogger.py
Emmanuel Frimpong Asante
implement blockchain logging for chat messages and add Ganache setup
7e750b9
#!/usr/bin/env python
"""
Compile & deploy ChatLogger.sol to the Ganache chain running on GANACHE_RPC_URL
then print the new contract address to STDOUT (no extra text).
β€’ Requires env vars: GANACHE_RPC_URL, GANACHE_PK
β€’ Writes ABI to app/core/chatlogger_abi.json so blockchain.py can load it.
"""
import json
import os
import pathlib
from web3 import Web3
from solcx import install_solc, compile_source
# --------------------------------------------------------------------------- #
# Compile contract
# --------------------------------------------------------------------------- #
install_solc("0.8.20")
SRC_PATH = pathlib.Path("contracts/ChatLogger.sol")
ABI_PATH = pathlib.Path("app/core/chatlogger_abi.json")
source_code = SRC_PATH.read_text()
compiled = compile_source(
source_code,
solc_version="0.8.20",
output_values=["abi", "bin"],
)
_, iface = compiled.popitem()
abi, bytecode = iface["abi"], iface["bin"]
# --------------------------------------------------------------------------- #
# Deploy
# --------------------------------------------------------------------------- #
DEFAULT_PK = "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
private_key = os.getenv("GANACHE_PK", DEFAULT_PK)
w3 = Web3(Web3.HTTPProvider(os.getenv("GANACHE_RPC_URL", "http://127.0.0.1:8545")))
acct = w3.eth.account.from_key(private_key)
# ── build txn ──────────────────────────────────────────────────────────────
txn = (
w3.eth.contract(abi=abi, bytecode=bytecode)
.constructor()
.build_transaction(
{
"from": acct.address,
"nonce": w3.eth.get_transaction_count(acct.address),
"gas": 3_000_000,
"gasPrice": w3.to_wei("1", "gwei"),
}
)
)
signed = acct.sign_transaction(txn)
raw_tx = signed.raw_transaction if hasattr(signed, "raw_transaction") else signed.rawTransaction
tx_hash = w3.eth.send_raw_transaction(raw_tx)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
address = receipt.contractAddress
# --------------------------------------------------------------------------- #
# Persist ABI for runtime use and echo address
# --------------------------------------------------------------------------- #
ABI_PATH.parent.mkdir(parents=True, exist_ok=True)
ABI_PATH.write_text(json.dumps(abi, indent=2))
print(address, flush=True) # Docker CMD captures this