GamerC0der commited on
Commit
945efa5
·
verified ·
1 Parent(s): d5b3eab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +389 -43
app.py CHANGED
@@ -1,12 +1,89 @@
1
- from flask import Flask, render_template, request, redirect, url_for, jsonify
2
  from flask_sqlalchemy import SQLAlchemy
 
3
  import uuid
4
- from datetime import datetime
5
  import requests
6
  import time
7
  import threading
8
  from cryptography.fernet import Fernet
9
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  app = Flask(__name__)
12
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///astrapay.db'
@@ -14,6 +91,21 @@ app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
14
  app.config['SECRET_KEY'] = 'your-secret-key-here'
15
 
16
  db = SQLAlchemy(app)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  def get_encryption_key():
19
  key_file = 'encryption.key'
@@ -37,14 +129,59 @@ def encrypt_value(value):
37
  def decrypt_value(encrypted_value):
38
  return cipher_suite.decrypt(encrypted_value.encode()).decode()
39
 
40
- ENCRYPTED_CONNECT_SID = encrypt_value('s%3A7Bwbww_JK7pW55D-B57-3b7bi-FzrzEZ.ezXPafCUs8%2B9L632zAZaBD51TQfSnUXUwbga8Z9kyAo')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  ENCRYPTED_API_URL = encrypt_value('https://astra-bank-moh1812.replit.app/api/transactions')
42
  ENCRYPTED_REFERER = encrypt_value('https://astra-bank-moh1812.replit.app/')
43
  ENCRYPTED_ETAG = encrypt_value('W/"6e3-L0zHI4rHMa4nHmyewyA/4y+lL6c"')
44
  ENCRYPTED_BANK_BASE_URL = encrypt_value('https://astra-bank-moh1812.replit.app')
45
 
46
  class PaymentLink(db.Model):
47
- id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
48
  amount = db.Column(db.Integer, nullable=False)
49
  description = db.Column(db.String(500), nullable=False)
50
  recipient_email = db.Column(db.String(255), nullable=True)
@@ -54,53 +191,104 @@ class PaymentLink(db.Model):
54
  def __repr__(self):
55
  return f'<PaymentLink {self.id}: {self.amount} Astras>'
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  def get_transactions():
58
  url = decrypt_value(ENCRYPTED_API_URL)
59
  referer = decrypt_value(ENCRYPTED_REFERER)
60
- etag = decrypt_value(ENCRYPTED_ETAG)
61
  connect_sid = decrypt_value(ENCRYPTED_CONNECT_SID)
62
 
63
  headers = {
64
  'accept': '*/*',
65
  'accept-language': 'en-US,en;q=0.9',
66
- 'if-none-match': etag,
 
67
  'priority': 'u=1, i',
68
  'referer': referer,
69
  'sec-ch-ua': '"Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"',
70
- 'sec-ch-ua-mobile': '?0',
71
- 'sec-ch-ua-platform': '"macOS"',
72
  'sec-fetch-dest': 'empty',
73
  'sec-fetch-mode': 'cors',
74
  'sec-fetch-site': 'same-origin',
75
- 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'
76
  }
77
 
78
  cookies = {
79
- 'sidebar_state': 'true',
80
  'connect.sid': connect_sid
81
  }
82
 
83
  try:
 
84
  response = requests.get(url, headers=headers, cookies=cookies, timeout=10)
85
- return response.json()
 
 
 
 
 
 
 
 
86
  except Exception as e:
87
- print(f"Error fetching transactions: {e}")
88
  return []
89
 
90
- def check_for_payment(amount, existing_transaction_ids):
91
  try:
 
92
  transactions = get_transactions()
93
-
 
 
 
 
 
94
  for transaction in transactions:
95
- transaction_id = transaction.get('id')
96
- if (transaction_id not in existing_transaction_ids and
97
- transaction.get('amount') == amount and
98
  transaction.get('transactionType') == 'received'):
99
- return transaction
100
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  return None
102
  except Exception as e:
103
- print(f"Error checking for payment: {e}")
104
  return None
105
 
106
  def get_user_uuid(email):
@@ -199,23 +387,30 @@ def create_payment_link():
199
  try:
200
  data = request.get_json()
201
 
202
- if not data or 'amount' not in data or 'description' not in data:
203
  return jsonify({'error': 'Missing required fields'}), 400
204
 
205
  amount = data['amount']
206
  description = data['description']
207
- recipient_email = data.get('recipient_email', '').strip() if data.get('recipient_email') else None
208
 
209
  if not isinstance(amount, int) or amount <= 0:
210
  return jsonify({'error': 'Invalid amount'}), 400
211
 
 
 
 
212
  if not description or len(description.strip()) == 0:
213
  return jsonify({'error': 'Description cannot be empty'}), 400
214
 
 
 
 
215
  payment_link = PaymentLink(
 
216
  amount=amount,
217
  description=description.strip(),
218
- recipient_email=recipient_email if recipient_email else None
219
  )
220
 
221
  db.session.add(payment_link)
@@ -236,14 +431,14 @@ def create_payment_link():
236
  @app.route('/init-payment-check/<payment_id>')
237
  def init_payment_check(payment_id):
238
  try:
239
- payment_link = PaymentLink.query.get_or_404(payment_id)
240
-
241
- transactions = get_transactions()
242
- existing_ids = [tx.get('id') for tx in transactions]
243
 
244
  return jsonify({
245
- 'existing_transaction_ids': existing_ids,
246
- 'amount': payment_link.amount
 
247
  })
248
 
249
  except Exception as e:
@@ -252,16 +447,11 @@ def init_payment_check(payment_id):
252
  @app.route('/check-payment/<payment_id>')
253
  def check_payment_status(payment_id):
254
  try:
255
- payment_link = PaymentLink.query.get_or_404(payment_id)
 
 
256
 
257
- existing_ids_str = request.args.get('existing_ids', '')
258
- if existing_ids_str:
259
- existing_ids = existing_ids_str.split(',')
260
- else:
261
- transactions = get_transactions()
262
- existing_ids = [tx.get('id') for tx in transactions]
263
-
264
- payment_transaction = check_for_payment(payment_link.amount, existing_ids)
265
 
266
  if payment_transaction:
267
  return jsonify({
@@ -282,7 +472,7 @@ def check_payment_status(payment_id):
282
  @app.route('/pay/<payment_id>', methods=['POST'])
283
  def process_payment(payment_id):
284
  try:
285
- payment_link = PaymentLink.query.get_or_404(payment_id)
286
 
287
  if payment_link.paid:
288
  return jsonify({'error': 'Payment already completed'}), 400
@@ -292,15 +482,17 @@ def process_payment(payment_id):
292
 
293
  if payment_link.recipient_email:
294
  try:
 
 
295
  user_uuid = get_user_uuid(payment_link.recipient_email)
296
  if user_uuid:
297
  success, result = send_money(
298
  to_user_id=user_uuid,
299
- amount=payment_link.amount,
300
  description=payment_link.description
301
  )
302
  if success:
303
- print(f"Successfully sent {payment_link.amount} Astras to {payment_link.recipient_email}")
304
  else:
305
  print(f"Failed to send money: {result}")
306
  else:
@@ -314,11 +506,41 @@ def process_payment(payment_id):
314
  db.session.rollback()
315
  return jsonify({'error': str(e)}), 500
316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  @app.route('/pay/<payment_id>')
318
  def view_payment(payment_id):
319
- payment_link = PaymentLink.query.get_or_404(payment_id)
 
 
320
  return render_template('payment.html',
321
  amount=payment_link.amount,
 
 
322
  description=payment_link.description,
323
  paid=payment_link.paid,
324
  payment_id=payment_link.id,
@@ -328,5 +550,129 @@ def view_payment(payment_id):
328
  def bank():
329
  return render_template('bank.html')
330
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
  if __name__ == '__main__':
332
- app.run(debug=True, host='0.0.0.0', port=7860)
 
 
 
1
+ from flask import Flask, render_template, request, redirect, url_for, jsonify, session
2
  from flask_sqlalchemy import SQLAlchemy
3
+ from flask_socketio import SocketIO, emit
4
  import uuid
5
+ from datetime import datetime, timezone
6
  import requests
7
  import time
8
  import threading
9
  from cryptography.fernet import Fernet
10
  import os
11
+ import random
12
+ import string
13
+
14
+ STOCK_START_TIME = None
15
+ STOCK_START_PRICE_AN = 1.27
16
+ STOCK_START_PRICE_ASTRAFOODS = 2.50
17
+ STOCK_START_PRICE_NOVASWEETS = 0.85
18
+
19
+ def get_an_price():
20
+ if STOCK_START_TIME is None:
21
+ return STOCK_START_PRICE_AN
22
+
23
+ elapsed = time.time() - STOCK_START_TIME
24
+ steps = int(elapsed / 0.5)
25
+
26
+ if steps == 0:
27
+ return STOCK_START_PRICE_AN
28
+
29
+ random.seed(int(STOCK_START_TIME))
30
+ price = STOCK_START_PRICE_AN
31
+
32
+ for i in range(steps):
33
+ volatility = random.uniform(-0.15, 0.15)
34
+ trend = 0.000014
35
+ change = volatility + trend
36
+ price += change
37
+ if price < 0.01:
38
+ price = 0.01
39
+
40
+ return round(price, 2)
41
+
42
+ def get_astrafoods_price():
43
+ if STOCK_START_TIME is None:
44
+ return STOCK_START_PRICE_ASTRAFOODS
45
+
46
+ elapsed = time.time() - STOCK_START_TIME
47
+ steps = int(elapsed / 0.5)
48
+
49
+ if steps == 0:
50
+ return STOCK_START_PRICE_ASTRAFOODS
51
+
52
+ random.seed(int(STOCK_START_TIME) + 1000)
53
+ price = STOCK_START_PRICE_ASTRAFOODS
54
+
55
+ for i in range(steps):
56
+ volatility = random.uniform(-0.02, 0.02)
57
+ trend = 0.0000028
58
+ change = volatility + trend
59
+ price += change
60
+ if price < 0.01:
61
+ price = 0.01
62
+
63
+ return round(price, 2)
64
+
65
+ def get_novasweets_price():
66
+ if STOCK_START_TIME is None:
67
+ return STOCK_START_PRICE_NOVASWEETS
68
+
69
+ elapsed = time.time() - STOCK_START_TIME
70
+ steps = int(elapsed / 0.5)
71
+
72
+ if steps == 0:
73
+ return STOCK_START_PRICE_NOVASWEETS
74
+
75
+ random.seed(int(STOCK_START_TIME) + 2000)
76
+ price = STOCK_START_PRICE_NOVASWEETS
77
+
78
+ for i in range(steps):
79
+ volatility = random.uniform(-0.20, 0.20)
80
+ trend = 0.000021
81
+ change = volatility + trend
82
+ price += change
83
+ if price < 0.01:
84
+ price = 0.01
85
+
86
+ return round(price, 2)
87
 
88
  app = Flask(__name__)
89
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///astrapay.db'
 
91
  app.config['SECRET_KEY'] = 'your-secret-key-here'
92
 
93
  db = SQLAlchemy(app)
94
+ socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
95
+
96
+ def background_stock_updates():
97
+ while True:
98
+ if STOCK_START_TIME is not None:
99
+ price_an = get_an_price()
100
+ price_astrafoods = get_astrafoods_price()
101
+ price_novasweets = get_novasweets_price()
102
+
103
+ socketio.emit('stock_update', {
104
+ 'an': price_an,
105
+ 'astrafoods': price_astrafoods,
106
+ 'novasweets': price_novasweets
107
+ })
108
+ time.sleep(0.5)
109
 
110
  def get_encryption_key():
111
  key_file = 'encryption.key'
 
129
  def decrypt_value(encrypted_value):
130
  return cipher_suite.decrypt(encrypted_value.encode()).decode()
131
 
132
+ def calculate_fee(amount):
133
+ """Calculate astratrader fee based on tiered structure"""
134
+ if amount < 10:
135
+ return 0
136
+ elif amount < 25:
137
+ return 1
138
+ elif amount < 100:
139
+ return 3
140
+ elif amount < 250:
141
+ return 5
142
+ elif amount < 300:
143
+ return 6
144
+ elif amount < 500:
145
+ return 8
146
+ elif amount < 1000:
147
+ return 10
148
+ elif amount < 2500:
149
+ return 22
150
+ elif amount < 3000:
151
+ return 24
152
+ elif amount < 5000:
153
+ return 24
154
+ else:
155
+ return 50
156
+
157
+ def calculate_claim_amounts(amount):
158
+ """Calculate send amount (+1%) and claim amount (-1%) for claim links"""
159
+ send_amount = max(1, int(amount * 1.01))
160
+
161
+ claim_amount = max(1, int(amount * 0.99))
162
+
163
+ return send_amount, claim_amount
164
+
165
+ def generate_unique_code(length=4):
166
+ """Generate a unique alphanumeric code (must be called within app context)"""
167
+ chars = string.ascii_uppercase + string.digits
168
+ max_attempts = 100
169
+
170
+ for _ in range(max_attempts):
171
+ code = ''.join(random.choice(chars) for _ in range(length))
172
+ if not PaymentLink.query.filter_by(id=code).first() and not ClaimLink.query.filter_by(id=code).first():
173
+ return code
174
+
175
+ return ''.join(random.choice(chars) for _ in range(length))
176
+
177
+ ENCRYPTED_CONNECT_SID = encrypt_value('s%3AchprkBWT1gzUWdCkJcWneCauTP73rb1-.tLvwxPgi6HFX3f1ULUt120nsbCJgODtlWpdp0cIluM0a')
178
  ENCRYPTED_API_URL = encrypt_value('https://astra-bank-moh1812.replit.app/api/transactions')
179
  ENCRYPTED_REFERER = encrypt_value('https://astra-bank-moh1812.replit.app/')
180
  ENCRYPTED_ETAG = encrypt_value('W/"6e3-L0zHI4rHMa4nHmyewyA/4y+lL6c"')
181
  ENCRYPTED_BANK_BASE_URL = encrypt_value('https://astra-bank-moh1812.replit.app')
182
 
183
  class PaymentLink(db.Model):
184
+ id = db.Column(db.String(4), primary_key=True)
185
  amount = db.Column(db.Integer, nullable=False)
186
  description = db.Column(db.String(500), nullable=False)
187
  recipient_email = db.Column(db.String(255), nullable=True)
 
191
  def __repr__(self):
192
  return f'<PaymentLink {self.id}: {self.amount} Astras>'
193
 
194
+ class ClaimLink(db.Model):
195
+ id = db.Column(db.String(4), primary_key=True)
196
+ amount = db.Column(db.Integer, nullable=False)
197
+ send_amount = db.Column(db.Integer, nullable=False)
198
+ claim_amount = db.Column(db.Integer, nullable=False)
199
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
200
+ verified = db.Column(db.Boolean, default=False)
201
+ claimed = db.Column(db.Boolean, default=False)
202
+ claimer_email = db.Column(db.String(255), nullable=True)
203
+
204
+ def __repr__(self):
205
+ return f'<ClaimLink {self.id}: {self.amount} Astras>'
206
+
207
  def get_transactions():
208
  url = decrypt_value(ENCRYPTED_API_URL)
209
  referer = decrypt_value(ENCRYPTED_REFERER)
 
210
  connect_sid = decrypt_value(ENCRYPTED_CONNECT_SID)
211
 
212
  headers = {
213
  'accept': '*/*',
214
  'accept-language': 'en-US,en;q=0.9',
215
+ 'cache-control': 'no-cache',
216
+ 'pragma': 'no-cache',
217
  'priority': 'u=1, i',
218
  'referer': referer,
219
  'sec-ch-ua': '"Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"',
220
+ 'sec-ch-ua-mobile': '?1',
221
+ 'sec-ch-ua-platform': '"Android"',
222
  'sec-fetch-dest': 'empty',
223
  'sec-fetch-mode': 'cors',
224
  'sec-fetch-site': 'same-origin',
225
+ 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36'
226
  }
227
 
228
  cookies = {
 
229
  'connect.sid': connect_sid
230
  }
231
 
232
  try:
233
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Fetching transactions from API: {url}")
234
  response = requests.get(url, headers=headers, cookies=cookies, timeout=10)
235
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] API Response Status: {response.status_code}")
236
+
237
+ transactions = response.json()
238
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] API Response: Received {len(transactions) if isinstance(transactions, list) else 'N/A'} transactions")
239
+
240
+ if isinstance(transactions, list) and len(transactions) > 0:
241
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Latest transaction: ID={transactions[0].get('id')}, Amount={transactions[0].get('amount')}, Type={transactions[0].get('transactionType')}, CreatedAt={transactions[0].get('createdAt')}")
242
+
243
+ return transactions
244
  except Exception as e:
245
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Error fetching transactions: {e}")
246
  return []
247
 
248
+ def check_for_payment(amount):
249
  try:
250
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Checking for payment: Amount={amount}")
251
  transactions = get_transactions()
252
+ current_time = time.time()
253
+ one_minute_ago = current_time - 60
254
+
255
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Checking transactions from last minute (since {datetime.fromtimestamp(one_minute_ago).strftime('%Y-%m-%d %H:%M:%S')})")
256
+
257
+ matching_transactions = []
258
  for transaction in transactions:
259
+ if (transaction.get('amount') == amount and
 
 
260
  transaction.get('transactionType') == 'received'):
261
+
262
+ matching_transactions.append(transaction)
263
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Found matching transaction: ID={transaction.get('id')}, Amount={transaction.get('amount')}, CreatedAt={transaction.get('createdAt')}")
264
+
265
+ created_at_str = transaction.get('createdAt')
266
+ if created_at_str:
267
+ try:
268
+ iso_str = created_at_str.replace('Z', '+00:00')
269
+ created_at = datetime.fromisoformat(iso_str)
270
+ created_at_timestamp = created_at.timestamp()
271
+
272
+ age_seconds = current_time - created_at_timestamp
273
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Transaction age: {age_seconds:.2f} seconds")
274
+
275
+ if created_at_timestamp >= one_minute_ago:
276
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] ✓ Payment found! Transaction ID: {transaction.get('id')}")
277
+ return transaction
278
+ else:
279
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Transaction too old (>{age_seconds:.2f}s), skipping")
280
+ except Exception as e:
281
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Error parsing timestamp: {e}")
282
+ continue
283
+
284
+ if matching_transactions:
285
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Found {len(matching_transactions)} matching transaction(s) but none within last minute")
286
+ else:
287
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] No matching transactions found for amount {amount}")
288
+
289
  return None
290
  except Exception as e:
291
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Error checking for payment: {e}")
292
  return None
293
 
294
  def get_user_uuid(email):
 
387
  try:
388
  data = request.get_json()
389
 
390
+ if not data or 'amount' not in data or 'description' not in data or 'recipient_email' not in data:
391
  return jsonify({'error': 'Missing required fields'}), 400
392
 
393
  amount = data['amount']
394
  description = data['description']
395
+ recipient_email = data.get('recipient_email', '').strip()
396
 
397
  if not isinstance(amount, int) or amount <= 0:
398
  return jsonify({'error': 'Invalid amount'}), 400
399
 
400
+ if amount > 10000:
401
+ return jsonify({'error': 'Maximum 10,000 Astras per payment link'}), 400
402
+
403
  if not description or len(description.strip()) == 0:
404
  return jsonify({'error': 'Description cannot be empty'}), 400
405
 
406
+ if not recipient_email:
407
+ return jsonify({'error': 'Recipient email is required'}), 400
408
+
409
  payment_link = PaymentLink(
410
+ id=generate_unique_code(),
411
  amount=amount,
412
  description=description.strip(),
413
+ recipient_email=recipient_email
414
  )
415
 
416
  db.session.add(payment_link)
 
431
  @app.route('/init-payment-check/<payment_id>')
432
  def init_payment_check(payment_id):
433
  try:
434
+ payment_link = PaymentLink.query.get_or_404(payment_id.upper())
435
+ fee = calculate_fee(payment_link.amount)
436
+ total_amount = payment_link.amount + fee
 
437
 
438
  return jsonify({
439
+ 'amount': payment_link.amount,
440
+ 'fee': fee,
441
+ 'total_amount': total_amount
442
  })
443
 
444
  except Exception as e:
 
447
  @app.route('/check-payment/<payment_id>')
448
  def check_payment_status(payment_id):
449
  try:
450
+ payment_link = PaymentLink.query.get_or_404(payment_id.upper())
451
+ fee = calculate_fee(payment_link.amount)
452
+ total_amount = payment_link.amount + fee
453
 
454
+ payment_transaction = check_for_payment(total_amount)
 
 
 
 
 
 
 
455
 
456
  if payment_transaction:
457
  return jsonify({
 
472
  @app.route('/pay/<payment_id>', methods=['POST'])
473
  def process_payment(payment_id):
474
  try:
475
+ payment_link = PaymentLink.query.get_or_404(payment_id.upper())
476
 
477
  if payment_link.paid:
478
  return jsonify({'error': 'Payment already completed'}), 400
 
482
 
483
  if payment_link.recipient_email:
484
  try:
485
+ fee = calculate_fee(payment_link.amount)
486
+ amount_to_send = payment_link.amount - fee
487
  user_uuid = get_user_uuid(payment_link.recipient_email)
488
  if user_uuid:
489
  success, result = send_money(
490
  to_user_id=user_uuid,
491
+ amount=amount_to_send,
492
  description=payment_link.description
493
  )
494
  if success:
495
+ print(f"Successfully sent {amount_to_send} Astras to {payment_link.recipient_email} (fee: {fee})")
496
  else:
497
  print(f"Failed to send money: {result}")
498
  else:
 
506
  db.session.rollback()
507
  return jsonify({'error': str(e)}), 500
508
 
509
+ @app.route('/check-link/<link_id>')
510
+ def check_link(link_id):
511
+ """Check if a link ID exists and return its type"""
512
+ try:
513
+ payment_link = PaymentLink.query.filter_by(id=link_id.upper()).first()
514
+ if payment_link:
515
+ return jsonify({
516
+ 'exists': True,
517
+ 'type': 'payment'
518
+ })
519
+
520
+ claim_link = ClaimLink.query.filter_by(id=link_id.upper()).first()
521
+ if claim_link:
522
+ return jsonify({
523
+ 'exists': True,
524
+ 'type': 'claim'
525
+ })
526
+
527
+ # Not found
528
+ return jsonify({
529
+ 'exists': False
530
+ }), 404
531
+
532
+ except Exception as e:
533
+ return jsonify({'error': str(e)}), 500
534
+
535
  @app.route('/pay/<payment_id>')
536
  def view_payment(payment_id):
537
+ payment_link = PaymentLink.query.get_or_404(payment_id.upper())
538
+ fee = calculate_fee(payment_link.amount)
539
+ total_amount = payment_link.amount + fee
540
  return render_template('payment.html',
541
  amount=payment_link.amount,
542
+ fee=fee,
543
+ total_amount=total_amount,
544
  description=payment_link.description,
545
  paid=payment_link.paid,
546
  payment_id=payment_link.id,
 
550
  def bank():
551
  return render_template('bank.html')
552
 
553
+ @app.route('/create-claim-link', methods=['POST'])
554
+ def create_claim_link():
555
+ try:
556
+ data = request.get_json()
557
+
558
+ if not data or 'amount' not in data:
559
+ return jsonify({'error': 'Missing required fields'}), 400
560
+
561
+ amount = data['amount']
562
+
563
+ if not isinstance(amount, int) or amount <= 0:
564
+ return jsonify({'error': 'Invalid amount'}), 400
565
+
566
+ if amount > 10000:
567
+ return jsonify({'error': 'Maximum 10,000 Astras per claim link'}), 400
568
+
569
+ send_amount, claim_amount = calculate_claim_amounts(amount)
570
+
571
+ claim_link = ClaimLink(
572
+ id=generate_unique_code(),
573
+ amount=amount,
574
+ send_amount=send_amount,
575
+ claim_amount=claim_amount
576
+ )
577
+
578
+ db.session.add(claim_link)
579
+ db.session.commit()
580
+
581
+ claim_url = url_for('view_claim', claim_id=claim_link.id, _external=True)
582
+
583
+ return jsonify({
584
+ 'success': True,
585
+ 'claim_id': claim_link.id,
586
+ 'claim_url': claim_url,
587
+ 'send_amount': send_amount,
588
+ 'claim_amount': claim_amount
589
+ })
590
+
591
+ except Exception as e:
592
+ db.session.rollback()
593
+ return jsonify({'error': str(e)}), 500
594
+
595
+ @app.route('/claim/<claim_id>')
596
+ def view_claim(claim_id):
597
+ claim_link = ClaimLink.query.get_or_404(claim_id.upper())
598
+ return render_template('claim.html',
599
+ amount=claim_link.amount,
600
+ send_amount=claim_link.send_amount,
601
+ claim_amount=claim_link.claim_amount,
602
+ verified=claim_link.verified,
603
+ claimed=claim_link.claimed,
604
+ claimer_email=claim_link.claimer_email,
605
+ claim_id=claim_link.id)
606
+
607
+ @app.route('/check-claim-verification/<claim_id>')
608
+ def check_claim_verification(claim_id):
609
+ try:
610
+ claim_link = ClaimLink.query.get_or_404(claim_id.upper())
611
+
612
+ if claim_link.verified:
613
+ return jsonify({'verified': True})
614
+
615
+ payment_transaction = check_for_payment(claim_link.send_amount)
616
+
617
+ if payment_transaction:
618
+ claim_link.verified = True
619
+ db.session.commit()
620
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Claim link {claim_id} verified")
621
+ return jsonify({'verified': True})
622
+ else:
623
+ return jsonify({'verified': False})
624
+
625
+ except Exception as e:
626
+ print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Error checking claim verification: {e}")
627
+ return jsonify({'error': str(e)}), 500
628
+
629
+ @app.route('/claim/<claim_id>', methods=['POST'])
630
+ def process_claim(claim_id):
631
+ try:
632
+ data = request.get_json()
633
+ claim_link = ClaimLink.query.get_or_404(claim_id.upper())
634
+
635
+ if claim_link.claimed:
636
+ return jsonify({'error': 'Claim link already used'}), 400
637
+
638
+ if not claim_link.verified:
639
+ return jsonify({'error': 'Claim link not verified yet'}), 400
640
+
641
+ if not data or 'email' not in data:
642
+ return jsonify({'error': 'Email is required'}), 400
643
+
644
+ email = data['email'].strip()
645
+ if not email:
646
+ return jsonify({'error': 'Email cannot be empty'}), 400
647
+
648
+ user_uuid = get_user_uuid(email)
649
+ if not user_uuid:
650
+ return jsonify({'error': 'User not found'}), 404
651
+
652
+ success, result = send_money(
653
+ to_user_id=user_uuid,
654
+ amount=claim_link.claim_amount,
655
+ description=f'Claim link {claim_id}'
656
+ )
657
+
658
+ if success:
659
+ claim_link.claimed = True
660
+ claim_link.claimer_email = email
661
+ db.session.commit()
662
+ return jsonify({'success': True, 'message': f'{claim_link.claim_amount} Astras sent to {email}'})
663
+ else:
664
+ return jsonify({'error': f'Failed to send money: {result}'}), 500
665
+
666
+ except Exception as e:
667
+ db.session.rollback()
668
+ return jsonify({'error': str(e)}), 500
669
+
670
+
671
+ @socketio.on('connect')
672
+ def handle_connect():
673
+ pass
674
+
675
  if __name__ == '__main__':
676
+ thread = threading.Thread(target=background_stock_updates, daemon=True)
677
+ thread.start()
678
+ socketio.run(app, debug=True, host='0.0.0.0', port=7860)