-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
1531 lines (1313 loc) · 56.6 KB
/
Copy pathapi.py
File metadata and controls
1531 lines (1313 loc) · 56.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import signal
import subprocess
import sys
import threading
import time
import webbrowser
import os
from datetime import datetime
from flask import Flask, jsonify, request, send_from_directory, session, redirect, url_for
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
import psycopg2
import pandas as pd
import joblib
from model import hybrid_predict as model_hybrid_predict, forecast_next24_series
from blockchain_integration import BlockchainManager
from eth_account import Account
import json
DB_CONFIG = {
"host": "localhost",
"database": "energy_data", # Database exists
"user": "divyanshagrawal", # Using your system username
"password": "", # Empty password for local development
}
SIM_SCRIPT = os.path.join(os.path.dirname(__file__), "meter_sim.py")
PID_FILE = os.path.join(os.path.dirname(__file__), ".meter_sim.pid")
LOG_FILE = os.path.join(os.path.dirname(__file__), ".meter_sim.log")
# Model training/retraining
MODEL_SCRIPT = os.path.join(os.path.dirname(__file__), "model.py")
MODEL_PID_FILE = os.path.join(os.path.dirname(__file__), ".model_train.pid")
MODEL_LOG_FILE = os.path.join(os.path.dirname(__file__), ".model_train.log")
MODEL_LAST_FILE = os.path.join(os.path.dirname(__file__), ".model_last_retrain.txt")
BASE_MODEL_FILE = os.path.join(os.path.dirname(__file__), "base_model.pkl")
# Initialize blockchain manager
blockchain_manager = BlockchainManager()
app = Flask(__name__)
app.secret_key = 'your-secret-key-change-this-in-production' # Required for session management
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SECURE'] = False # Set to True in production with HTTPS
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # More compatible for development
app.config['SESSION_COOKIE_DOMAIN'] = None # Let Flask handle domain automatically
app.config['SESSION_COOKIE_PATH'] = '/' # Ensure cookie is sent for all paths
# Allow browser requests from file:// (Origin: null) and localhost origins
CORS(app, origins=["http://localhost:5001", "http://127.0.0.1:5001", "null", "http://localhost:*", "http://127.0.0.1:*"], supports_credentials=True, allow_headers=["Content-Type", "Authorization"], methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
def get_db_conn():
return psycopg2.connect(**DB_CONFIG)
# Helper functions for token balance persistence
def save_user_token_balance(user_id, wallet_address, balance):
"""Save user's token balance to database"""
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""UPDATE users
SET token_balance = %s, wallet_address = %s, updated_at = NOW()
WHERE id = %s""",
(balance, wallet_address, user_id)
)
conn.commit()
print(f"💾 Saved balance for user {user_id}: {balance} tokens")
return True
except Exception as e:
print(f"❌ Error saving token balance: {e}")
return False
def get_user_token_balance(user_id):
"""Get user's token balance from database"""
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT token_balance, wallet_address FROM users WHERE id = %s",
(user_id,)
)
row = cur.fetchone()
if row:
return float(row[0] or 0), row[1]
return 0.0, None
except Exception as e:
print(f"❌ Error getting token balance: {e}")
return 0.0, None
def restore_user_blockchain_balance(user_id, wallet_address):
"""Restore user's blockchain balance from database after redeployment"""
try:
db_balance, stored_address = get_user_token_balance(user_id)
if db_balance > 0:
# Get current blockchain balance
current_balance = blockchain_manager.get_kwh_balance(wallet_address)
# If blockchain balance is less than DB balance, mint the difference
if current_balance < db_balance:
needed = db_balance - current_balance
print(f"🔄 Restoring {needed} tokens to user {user_id} (wallet: {wallet_address})")
result = blockchain_manager.mint_kwh_tokens(
wallet_address,
needed,
execute=True
)
if result.get('success'):
print(f"✅ Restored {needed} tokens to {wallet_address}")
return True
else:
print(f"❌ Failed to restore tokens: {result.get('error')}")
return False
else:
print(f"✓ Blockchain balance ({current_balance}) matches or exceeds DB balance ({db_balance})")
return True
else:
print(f"ℹ User {user_id} has 0 balance in DB, nothing to restore")
return True
except Exception as e:
print(f"❌ Error restoring blockchain balance: {e}")
return False
def sync_user_balance_to_db(user_id, wallet_address):
"""Sync current blockchain balance to database"""
try:
current_balance = blockchain_manager.get_kwh_balance(wallet_address)
save_user_token_balance(user_id, wallet_address, current_balance)
return True
except Exception as e:
print(f"❌ Error syncing balance to DB: {e}")
return False
def sync_balance_by_wallet_address(wallet_address):
"""Find user by wallet address and sync their balance"""
if not wallet_address:
return False
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
# Find user by wallet address in current session or stored address
cur.execute(
"SELECT id FROM users WHERE wallet_address = %s",
(wallet_address,)
)
row = cur.fetchone()
if row:
user_id = row[0]
return sync_user_balance_to_db(user_id, wallet_address)
else:
# Wallet not found in DB - this is okay for ephemeral wallets
print(f"ℹ️ Wallet {wallet_address} not found in DB (ephemeral wallet)")
return False
except Exception as e:
print(f"❌ Error finding user by wallet: {e}")
return False
# Simple JSON storage for trading orders
ORDERS_FILE = os.path.join(os.path.dirname(__file__), "orders.json")
# Trading conversion and market pricing
CONVERSION_RATE_KWH_PER_TOKEN = 0.01 # 1 token = 0.01 kWh
MARKET_PRICE_PER_KWH_WEI = int(os.getenv('MARKET_PRICE_PER_KWH_WEI', '1000000000000000')) # 1e15 wei per kWh
def _price_per_token_wei():
try:
return int(MARKET_PRICE_PER_KWH_WEI * CONVERSION_RATE_KWH_PER_TOKEN)
except Exception:
return 0
def _load_orders():
try:
with open(ORDERS_FILE, 'r') as f:
return json.load(f)
except Exception:
return []
def _save_orders(orders):
try:
with open(ORDERS_FILE, 'w') as f:
json.dump(orders, f, indent=2)
return True
except Exception:
return False
# Blockchain API routes
@app.route('/api/blockchain/status', methods=['GET'])
def blockchain_status():
"""Check blockchain connection status"""
try:
is_connected = blockchain_manager.is_connected()
# Additional connection details
block_number = None
chain_id = None
if is_connected:
try:
block_number = blockchain_manager.w3.eth.block_number
chain_id = blockchain_manager.w3.eth.chain_id
except Exception as e:
print(f"Error getting blockchain details: {e}")
return jsonify({
"connected": is_connected,
"provider": blockchain_manager.provider_url,
"contracts_loaded": list(blockchain_manager.contracts.keys()),
"block_number": block_number,
"chain_id": chain_id,
"accounts_available": len(blockchain_manager.accounts) if blockchain_manager.accounts else 0
})
except Exception as e:
return jsonify({
"connected": False,
"provider": blockchain_manager.provider_url,
"error": str(e)
}), 500
@app.route('/api/blockchain/register-meter', methods=['POST'])
def register_meter():
"""Register a new meter on the blockchain"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.json
if not data or not data.get('meter_id') or not data.get('pub_key') or not data.get('admin_account'):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
result = blockchain_manager.register_meter(
data['meter_id'],
data['pub_key'],
data['admin_account']
)
return jsonify(result)
@app.route('/api/blockchain/mint-tokens', methods=['POST'])
def mint_tokens():
"""Mint KWh tokens to a user address"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.json
if not data or not data.get('to_address') or not data.get('amount'):
return jsonify({"success": False, "error": "Missing required parameters: to_address and amount"}), 400
try:
amount = float(data['amount'])
if amount <= 0:
return jsonify({"success": False, "error": "Amount must be greater than 0"}), 400
except (ValueError, TypeError):
return jsonify({"success": False, "error": "Invalid amount value"}), 400
# Use execute=True to mint directly from deployer account
result = blockchain_manager.mint_kwh_tokens(
data['to_address'],
amount,
execute=True
)
if result.get('success'):
return jsonify(result), 200
else:
return jsonify(result), 400
@app.route('/api/blockchain/create-escrow', methods=['POST'])
def create_escrow():
"""Create an escrow for a trade"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.json
if not data or not data.get('trade_id') or not data.get('amount') or not data.get('buyer_account'):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
result = blockchain_manager.create_escrow(
data['trade_id'],
float(data['amount']),
data['buyer_account']
)
return jsonify(result)
@app.route('/api/blockchain/create-settlement', methods=['POST'])
def create_settlement():
"""Create a settlement in the market"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.json
if not data or not data.get('settlement_id') or not data.get('amount') or not data.get('price') or not data.get('engine_account'):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
result = blockchain_manager.create_settlement(
data['settlement_id'],
float(data['amount']),
int(data['price']),
data.get('engine_account'),
execute=bool(data.get('execute', False))
)
return jsonify(result)
@app.post('/api/trading/create-settlement')
def trading_create_settlement():
"""Execute settlement directly using default engine account (Hardhat unlocked)"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.get_json(force=True)
if not data:
return jsonify({"success": False, "error": "No data provided"}), 400
sid = data.get('settlement_id') or f"trade-{int(time.time()*1000)}"
try:
amount = float(data.get('amount', 0))
price = int(float(data.get('price', 0)))
if amount <= 0:
return jsonify({"success": False, "error": "Amount must be greater than 0"}), 400
if price <= 0:
return jsonify({"success": False, "error": "Price must be greater than 0"}), 400
except (ValueError, TypeError) as e:
return jsonify({"success": False, "error": f"Invalid amount or price: {str(e)}"}), 400
result = blockchain_manager.create_settlement(
sid,
amount,
price,
engine_account=None,
execute=True
)
return jsonify(result), (200 if result.get('success') else 400)
# Trading orders API
@app.get('/api/trading/market')
def get_market_info():
"""Return conversion and current market price info."""
return jsonify({
"success": True,
"conversion_rate_kwh_per_token": CONVERSION_RATE_KWH_PER_TOKEN,
"price_per_kwh_wei": MARKET_PRICE_PER_KWH_WEI,
"price_per_token_wei": _price_per_token_wei(),
})
@app.get('/api/trading/orders')
def list_orders():
"""List all trading orders (visible to all users)"""
orders = _load_orders()
orders.sort(key=lambda o: o.get('created_at', 0), reverse=True)
return jsonify({"success": True, "orders": orders})
@app.post('/api/trading/orders')
def create_order():
"""Create a new trading order (buy or sell)"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.get_json(force=True)
trade_type = (data.get('tradeType') or '').lower()
if trade_type not in ('buy', 'sell'):
return jsonify({"success": False, "error": "Invalid trade type"}), 400
try:
amount_kwh = float(data.get('energyAmount'))
except Exception:
return jsonify({"success": False, "error": "Invalid energy amount"}), 400
created_by = session.get('wallet_address')
order_id = f"ord-{int(time.time()*1000)}"
price_per_kwh_wei = MARKET_PRICE_PER_KWH_WEI
price_per_token_wei = _price_per_token_wei()
tokens = int(amount_kwh / CONVERSION_RATE_KWH_PER_TOKEN)
total_price_wei = int(amount_kwh * price_per_kwh_wei)
order = {
"id": order_id,
"type": trade_type,
"amount_kwh": amount_kwh,
"price_per_kwh_wei": price_per_kwh_wei,
"price_per_token_wei": price_per_token_wei,
"tokens": tokens,
"total_price_wei": total_price_wei,
"status": "open",
"created_by": created_by,
"created_at": int(time.time())
}
orders = _load_orders()
orders.append(order)
if not _save_orders(orders):
return jsonify({"success": False, "error": "Failed to save order"}), 500
return jsonify({"success": True, "order": order})
@app.post('/api/trading/buy')
def buy_order():
"""Buy an existing sell order with INSTANT transfer.
Flow:
1. Buyer's tokens transferred directly to seller
2. Order status changes to 'filled'
3. Trade completes immediately
"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.get_json(force=True)
order_id = data.get('orderId')
if not order_id:
return jsonify({"success": False, "error": "Missing orderId"}), 400
orders = _load_orders()
target = next((o for o in orders if o.get('id') == order_id), None)
if not target:
return jsonify({"success": False, "error": "Order not found"}), 404
if target.get('status') != 'open' or target.get('type') != 'sell':
return jsonify({"success": False, "error": "Order not available for purchase"}), 400
buyer_addr = session.get('wallet_address')
if not buyer_addr:
return jsonify({"success": False, "error": "No wallet address in session"}), 400
# Prevent user from buying their own order
if target.get('created_by') == buyer_addr:
return jsonify({"success": False, "error": "You cannot buy your own order"}), 400
seller_addr = target.get('created_by')
if not seller_addr:
return jsonify({"success": False, "error": "Order has no seller address"}), 400
# Get the token amount to transfer
token_amount = float(target.get('amount_kwh', 0))
# BUYER MUST HAVE TOKENS - validate buyer has enough balance
try:
buyer_balance = blockchain_manager.get_kwh_balance(buyer_addr)
if buyer_balance < token_amount:
return jsonify({
"success": False,
"error": f"Insufficient tokens to buy. Required: {token_amount} KWH, Available: {buyer_balance} KWH"
}), 400
except Exception as e:
print(f"Warning: Could not check buyer balance: {e}")
# INSTANT TRANSFER - no escrow
print(f"BUYING INSTANTLY: Transferring {token_amount} KWH from buyer {buyer_addr} to seller {seller_addr}")
transfer_result = blockchain_manager.transfer_kwh_tokens(
buyer_addr,
seller_addr,
token_amount,
execute=True
)
if not transfer_result.get('success'):
return jsonify({
"success": False,
"error": f"Token transfer failed: {transfer_result.get('error')}"
}), 400
# Create an on-chain settlement entry for record keeping
sid = f"{order_id}-buy-{int(time.time()*1000)}"
settle = blockchain_manager.create_settlement(
sid,
token_amount,
int(target.get('total_price_wei', 0)),
engine_account=None,
execute=True
)
# Update order status
target['status'] = 'filled'
target['buyer'] = buyer_addr
target['filled_at'] = int(time.time())
target['transfer_tx'] = transfer_result.get('tx_hash')
if settle.get('success'):
target['settlement_tx'] = settle.get('tx_hash')
print(f"✓ Order {order_id} filled with settlement tx {settle.get('tx_hash')}")
else:
print(f"⚠ Order {order_id} filled but settlement failed: {settle.get('error')}")
# Sync both buyer and seller balances to database
buyer_user_id = session.get('user_id')
if buyer_user_id:
sync_user_balance_to_db(buyer_user_id, buyer_addr)
# Also sync seller's balance (find user by wallet address)
sync_balance_by_wallet_address(seller_addr)
_save_orders(orders)
return jsonify({
"success": True,
"order": target,
"transfer": transfer_result,
"onchain": settle
})
@app.post('/api/trading/sell')
def sell_to_buy_order():
"""Sell energy to an existing buy order. Seller receives tokens, NO tokens required to sell."""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.get_json(force=True)
order_id = data.get('orderId')
if not order_id:
return jsonify({"success": False, "error": "Missing orderId"}), 400
orders = _load_orders()
target = next((o for o in orders if o.get('id') == order_id), None)
if not target:
return jsonify({"success": False, "error": "Order not found"}), 404
if target.get('status') != 'open' or target.get('type') != 'buy':
return jsonify({"success": False, "error": "Order not available to sell into"}), 400
seller_addr = session.get('wallet_address')
if not seller_addr:
return jsonify({"success": False, "error": "No wallet address in session"}), 400
# Prevent user from selling to their own order
if target.get('created_by') == seller_addr:
return jsonify({"success": False, "error": "You cannot sell to your own order"}), 400
buyer_addr = target.get('created_by')
if not buyer_addr:
return jsonify({"success": False, "error": "Order has no buyer address"}), 400
# Get the token amount to transfer
token_amount = float(target.get('amount_kwh', 0))
# BUYER MUST HAVE TOKENS - validate buyer (who created the buy order) has enough
try:
buyer_balance = blockchain_manager.get_kwh_balance(buyer_addr)
if buyer_balance < token_amount:
return jsonify({
"success": False,
"error": f"Buyer has insufficient tokens. Required: {token_amount} KWH, Available: {buyer_balance} KWH"
}), 400
except Exception as e:
print(f"Warning: Could not check buyer balance: {e}")
# NO BALANCE CHECK FOR SELLER - sellers don't need tokens, they provide energy!
# Transfer tokens from BUYER to SELLER (buyer pays, seller receives)
print(f"SELLING: Transferring {token_amount} KWH from buyer {buyer_addr} to seller {seller_addr}")
transfer_result = blockchain_manager.transfer_kwh_tokens(
buyer_addr,
seller_addr,
token_amount,
execute=True
)
if not transfer_result.get('success'):
return jsonify({
"success": False,
"error": f"Token transfer failed: {transfer_result.get('error')}"
}), 400
# Create settlement record
sid = f"{order_id}-sell-{int(time.time()*1000)}"
settle = blockchain_manager.create_settlement(
sid,
token_amount,
int(target.get('total_price_wei', 0)),
engine_account=None,
execute=True
)
# Update order status
target['status'] = 'filled'
target['seller'] = seller_addr
target['filled_at'] = int(time.time())
target['transfer_tx'] = transfer_result.get('tx_hash')
if settle.get('success'):
target['settlement_tx'] = settle.get('tx_hash')
print(f"✓ Order {order_id} filled with settlement tx {settle.get('tx_hash')}")
else:
print(f"⚠ Order {order_id} filled but settlement failed: {settle.get('error')}")
# Sync seller balance to database (current user)
seller_user_id = session.get('user_id')
if seller_user_id:
sync_user_balance_to_db(seller_user_id, seller_addr)
# Also sync buyer's balance (find user by wallet address)
sync_balance_by_wallet_address(buyer_addr)
_save_orders(orders)
return jsonify({
"success": True,
"order": target,
"transfer": transfer_result,
"onchain": settle
})
@app.post('/api/trading/confirm-delivery')
def confirm_delivery():
"""Confirm delivery of energy (buyer or seller confirms)"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.get_json(force=True)
order_id = data.get('orderId')
if not order_id:
return jsonify({"success": False, "error": "Missing orderId"}), 400
orders = _load_orders()
target = next((o for o in orders if o.get('id') == order_id), None)
if not target:
return jsonify({"success": False, "error": "Order not found"}), 404
if target.get('status') != 'escrowed':
return jsonify({"success": False, "error": "Order not in escrow"}), 400
user_addr = session.get('wallet_address')
if not user_addr:
return jsonify({"success": False, "error": "No wallet address in session"}), 400
buyer_addr = target.get('buyer')
seller_addr = target.get('created_by')
# Check if user is buyer or seller
if user_addr != buyer_addr and user_addr != seller_addr:
return jsonify({"success": False, "error": "You are not part of this trade"}), 400
is_buyer = (user_addr == buyer_addr)
# Check if already confirmed
if is_buyer and target.get('buyer_confirmed'):
return jsonify({"success": False, "error": "You have already confirmed delivery"}), 400
if not is_buyer and target.get('seller_confirmed'):
return jsonify({"success": False, "error": "You have already confirmed delivery"}), 400
# Confirm delivery on blockchain
print(f"{'Buyer' if is_buyer else 'Seller'} {user_addr} confirming delivery for order {order_id}")
confirm_result = blockchain_manager.confirm_delivery(
trade_id=order_id,
confirmer_account=user_addr,
execute=True
)
if not confirm_result.get('success'):
return jsonify({
"success": False,
"error": f"Confirmation failed: {confirm_result.get('error')}"
}), 400
# Update order status
if is_buyer:
target['buyer_confirmed'] = True
target['buyer_confirmed_at'] = int(time.time())
else:
target['seller_confirmed'] = True
target['seller_confirmed_at'] = int(time.time())
# If both confirmed, mark as complete
if target.get('buyer_confirmed') and target.get('seller_confirmed'):
target['status'] = 'filled'
target['filled_at'] = int(time.time())
target['settlement_tx'] = confirm_result.get('tx_hash')
print(f"✓ Order {order_id} completed! Both parties confirmed.")
message = "Trade completed! Tokens released to seller."
# Sync balances for both parties (tokens moved from escrow to seller)
user_id = session.get('user_id')
if user_id:
sync_user_balance_to_db(user_id, user_addr)
else:
message = f"Delivery confirmed by {'buyer' if is_buyer else 'seller'}. Waiting for other party to confirm."
_save_orders(orders)
return jsonify({
"success": True,
"order": target,
"message": message,
"confirmation": confirm_result
})
@app.post('/api/trading/cancel-escrow')
def cancel_escrow():
"""Cancel escrow and refund buyer (only after timeout)"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.get_json(force=True)
order_id = data.get('orderId')
if not order_id:
return jsonify({"success": False, "error": "Missing orderId"}), 400
orders = _load_orders()
target = next((o for o in orders if o.get('id') == order_id), None)
if not target:
return jsonify({"success": False, "error": "Order not found"}), 404
if target.get('status') != 'escrowed':
return jsonify({"success": False, "error": "Order not in escrow"}), 400
buyer_addr = target.get('buyer')
user_addr = session.get('wallet_address')
if user_addr != buyer_addr:
return jsonify({"success": False, "error": "Only the buyer can cancel escrow"}), 400
# Check if timeout has been reached
escrow_status = blockchain_manager.get_escrow_status(order_id)
if not escrow_status.get('success'):
return jsonify({"success": False, "error": "Could not check escrow status"}), 400
if not escrow_status.get('canCancel'):
return jsonify({
"success": False,
"error": "Cannot cancel yet. Timeout not reached or seller has already confirmed."
}), 400
# Cancel escrow on blockchain
print(f"Buyer {buyer_addr} cancelling escrow for order {order_id}")
cancel_result = blockchain_manager.cancel_escrow(
trade_id=order_id,
buyer_account=buyer_addr,
execute=True
)
if not cancel_result.get('success'):
return jsonify({
"success": False,
"error": f"Cancellation failed: {cancel_result.get('error')}"
}), 400
# Update order status
target['status'] = 'cancelled'
target['cancelled_at'] = int(time.time())
target['cancel_tx'] = cancel_result.get('tx_hash')
# Sync buyer balance (refunded)
buyer_user_id = session.get('user_id')
if buyer_user_id:
sync_user_balance_to_db(buyer_user_id, buyer_addr)
_save_orders(orders)
return jsonify({
"success": True,
"order": target,
"message": "Escrow cancelled. Tokens refunded to buyer.",
"cancellation": cancel_result
})
@app.get('/api/trading/escrow-status/<order_id>')
def get_escrow_status(order_id):
"""Get escrow status for an order"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
escrow_status = blockchain_manager.get_escrow_status(order_id)
return jsonify(escrow_status)
@app.route('/api/blockchain/update-contracts', methods=['POST'])
def update_contracts():
"""Update contract addresses after deployment"""
if not session.get('user_id'):
return jsonify({"success": False, "error": "Authentication required"}), 401
data = request.json
if not data or not data.get('addresses'):
return jsonify({"success": False, "error": "Missing contract addresses"}), 400
# Update each contract address
updated = []
for contract_name, address in data['addresses'].items():
if blockchain_manager.update_contract_address(contract_name, address):
updated.append(contract_name)
return jsonify({
"success": True,
"updated_contracts": updated,
"contracts_loaded": list(blockchain_manager.contracts.keys())
})
@app.get("/api/consumption/latest")
def latest_consumption():
try:
user_id = get_current_user_id()
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT ts, consumption_kwh
FROM meter_readings
WHERE user_id = %s
ORDER BY ts DESC
LIMIT 1
""",
(user_id,)
)
row = cur.fetchone()
if not row:
return jsonify({"data": None}), 200
return jsonify({
"user_id": user_id,
"timestamp": row[0].isoformat(),
"consumption_kwh": float(row[1])
}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.get("/api/consumption/summary")
def consumption_summary():
try:
user_id = get_current_user_id()
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT
COALESCE(SUM(consumption_kwh), 0) AS total_kwh,
COALESCE(AVG(consumption_kwh), 0) AS avg_kwh,
COUNT(*) AS samples
FROM meter_readings
WHERE user_id = %s
""",
(user_id,)
)
total_kwh, avg_kwh, samples = cur.fetchone()
return jsonify({
"total_kwh": float(total_kwh),
"avg_kwh": float(avg_kwh),
"samples": int(samples)
}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
# New: billing summary (month to date)
@app.get("/api/billing/summary")
def billing_summary():
try:
user_id = get_current_user_id()
# Basic flat tariff; can be extended to TOU later
price_per_kwh = float(os.getenv("PRICE_PER_KWH", "0.12"))
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT COALESCE(SUM(consumption_kwh), 0)
FROM meter_readings
WHERE user_id = %s
AND DATE_TRUNC('month', ts) = DATE_TRUNC('month', NOW())
""",
(user_id,),
)
total_kwh = float(cur.fetchone()[0] or 0.0)
est_cost = total_kwh * price_per_kwh
return jsonify({
"user_id": user_id,
"month": datetime.utcnow().strftime("%Y-%m"),
"total_kwh": total_kwh,
"price_per_kwh": price_per_kwh,
"estimated_cost": est_cost
}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
# New: consumption history endpoint
@app.get("/api/consumption/history")
def consumption_history():
try:
user_id = get_current_user_id()
range_param = request.args.get("range")
limit_param = request.args.get("limit")
limit_val = None
if limit_param:
try:
limit_val = max(1, min(5000, int(limit_param)))
except Exception:
limit_val = None
if not range_param and not limit_val:
range_param = "24h"
with get_db_conn() as conn:
with conn.cursor() as cur:
if limit_val is not None:
print(f"DEBUG: Using limit mode with limit_val={limit_val}, user_id={user_id}")
cur.execute(
"""
SELECT ts, consumption_kwh
FROM meter_readings
WHERE user_id = %s
ORDER BY ts DESC
LIMIT %s
""",
(user_id, limit_val),
)
rows = cur.fetchall()
print(f"DEBUG: Fetched {len(rows)} rows from database")
# reverse to chronological order
rows = rows[::-1]
elif range_param == "24h":
cur.execute(
"""
SELECT ts, consumption_kwh
FROM meter_readings
WHERE user_id = %s AND ts >= NOW() - INTERVAL '24 hours'
ORDER BY ts
""",
(user_id,),
)
else:
cur.execute(
"""
SELECT ts, consumption_kwh
FROM meter_readings
WHERE user_id = %s AND ts >= NOW() - INTERVAL '7 days'
ORDER BY ts
""",
(user_id,),
)
rows = cur.fetchall()
series = [{"timestamp": r[0].isoformat(), "kwh": float(r[1])} for r in rows]
return jsonify({"range": range_param, "limit": limit_val, "series": series}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
def _read_pid():
if os.path.exists(PID_FILE):
with open(PID_FILE, "r") as f:
try:
return int(f.read().strip())
except Exception:
return None
return None
def _write_pid(pid: int):
with open(PID_FILE, "w") as f:
f.write(str(pid))
def _clear_pid():
if os.path.exists(PID_FILE):
os.remove(PID_FILE)
def _read_model_pid():
if os.path.exists(MODEL_PID_FILE):
with open(MODEL_PID_FILE, "r") as f:
try:
return int(f.read().strip())
except Exception:
return None
return None
def _write_model_pid(pid: int):
with open(MODEL_PID_FILE, "w") as f:
f.write(str(pid))
def _clear_model_pid():
if os.path.exists(MODEL_PID_FILE):
os.remove(MODEL_PID_FILE)
def _read_last_retrain_ts():
if os.path.exists(MODEL_LAST_FILE):
try:
with open(MODEL_LAST_FILE, 'r') as f:
return f.read().strip()
except Exception:
return None
return None
def _write_last_retrain_ts():
with open(MODEL_LAST_FILE, 'w') as f:
f.write(datetime.utcnow().isoformat())
@app.post("/api/sim/start")
def start_sim():
user_id = get_current_user_id()
existing = _read_pid()
if existing and _process_alive(existing):
return jsonify({"status": "already_running", "pid": existing}), 200
try:
if not os.path.exists(SIM_SCRIPT):
return jsonify({"error": f"meter_sim.py not found at {SIM_SCRIPT}"}), 400
log_fp = open(LOG_FILE, "a")
env = os.environ.copy()
env.setdefault("USER_ID", str(user_id))
proc = subprocess.Popen([sys.executable, SIM_SCRIPT], stdout=log_fp, stderr=log_fp, cwd=os.path.dirname(__file__), env=env)
_write_pid(proc.pid)
# If the process exited immediately, surface error
ret = proc.poll()
if ret is not None:
try:
with open(LOG_FILE, "r") as lf:
tail = lf.readlines()[-20:]
except Exception:
tail = []
return jsonify({"error": "simulation process exited immediately", "returncode": ret, "log_tail": tail}), 500
return jsonify({"status": "started", "pid": proc.pid, "user_id": user_id}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.post("/api/sim/stop")