-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspore-api.py
More file actions
412 lines (351 loc) · 14.5 KB
/
Copy pathspore-api.py
File metadata and controls
412 lines (351 loc) · 14.5 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
import os
import json
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS, cross_origin
import spore_api_utils as api_utils
import spore_db_utils as db_utils
import spore_price_utils as price_utils
from cmc_api import handler # Import the function from cmc_api.py
import spore_burn_utils as burn_utils
from ipfs_utils import create_challenge, verify_login, is_session_valid, logoff, get_user_info, upload_and_pin_file, unpin_file_by_cid
import tempfile
from werkzeug.utils import secure_filename
app = Flask(__name__)
CORS(app, support_credentials=True)
@app.route('/')
@cross_origin(supports_credentials=True)
def hello():
return jsonify({'success': 'ok'})
@app.route('/avax-holders',methods=['GET'])
@cross_origin(supports_credentials=True)
def avax_holders():
rejection = api_utils.validate_origin()
if rejection:
return rejection
return '5336'
@app.route('/contributors',methods=['GET'])
@cross_origin(supports_credentials=True)
def current_contributors():
rejection = api_utils.validate_origin()
if rejection:
return rejection
#open json file containing contributors
with open('contributors.json') as json_file:
json_data = json.load(json_file)
return jsonify(json_data)
@app.route('/token/prices',methods=['GET'])
@cross_origin(supports_credentials=True)
def get_token_prices():
rejection = api_utils.validate_origin()
if rejection:
return rejection
data=price_utils.calc()
return jsonify(data)
@app.route('/last-indexed',methods=['GET'])
@cross_origin(supports_credentials=True)
def last_indexed():
rejection = api_utils.validate_origin()
if rejection:
return rejection
#you will return a code 502 if the database is not connected
if not api_utils.verify_db_connection():
return jsonify({'error': 'Database not connected'}), 502
nft_buys_last_indexed, nft_prices_last_indexed = api_utils.last_indexed_nft_control()
if nft_buys_last_indexed == 0 and nft_prices_last_indexed == 0:
return jsonify({'error': 'No data indexed yet'}), 204
return jsonify({'nft_buys_last_indexed': nft_buys_last_indexed, 'nft_prices_last_indexed': nft_prices_last_indexed})
@app.route('/api', methods=['GET']) # New route for CoinMarketCap data
@cross_origin(supports_credentials=True)
def cmc_api():
try:
q = request.args.get('q')
res= handler(q)
if res:
return res
else:
return jsonify({'error': 'Invalid request1'}), 500
except Exception as e:
print (f"Error: {jsonify(e)}")
return jsonify({'error': 'Invalid request2'}), 500
@app.route('/nft/get_total_volume',methods=['GET'])
@cross_origin(supports_credentials=True)
def get_total_volume():
rejection = api_utils.validate_origin()
if rejection:
return rejection
if not api_utils.verify_db_connection():
return jsonify({'error': 'Database not connected'}), 502
total_volume = db_utils.nft_get_total_volume()
if total_volume == 0:
return jsonify({'error': 'No data indexed yet'}), 204
return jsonify({'total_volume': total_volume})
@app.route('/nft/get_floor_price',methods=['GET'])
@cross_origin(supports_credentials=True)
def get_floor_price():
rejection = api_utils.validate_origin()
if rejection:
return rejection
if not api_utils.verify_db_connection():
return jsonify({'error': 'Database not connected'}), 502
floor_price = db_utils.nft_get_floor_price()
if floor_price == 0:
return jsonify({'error': 'No data indexed yet'}), 204
return jsonify({'floor_price': floor_price})
@app.route('/nft/get_last_sale',methods=['GET'])
@cross_origin(supports_credentials=True)
def get_last_sale():
if not api_utils.verify_db_connection():
return jsonify({'error': 'Database not connected'}), 502
last_sale = db_utils.nft_get_last_sale()
if last_sale == 0:
return jsonify({'error': 'No data indexed yet'}), 204
return jsonify({'last_sale': last_sale})
@app.route('/nft/update_nft_db',methods=['GET'])
@cross_origin(supports_credentials=True)
def update_nft_db():
(indexing_in_progress, block_started, status) = db_utils.get_nft_indexing()
current_block = db_utils.get_ava_latest_block()
try:
q = request.args.get('q')
req_response=500
if q == "consult":
if not indexing_in_progress and block_started+120<current_block:
status = "reload"
db_utils.set_nft_indexing_json(False, 0, status)
(indexing_in_progress, block_started, status) = db_utils.get_nft_indexing()
json_response = {
'indexing_in_progress': indexing_in_progress,
'block_started': block_started,
'current_block': current_block,
'status': status
}
req_response=200
else:
thread_response= db_utils.nft_update_db()
(indexing_in_progress, block_started, status) = db_utils.get_nft_indexing()
json_response = {
'indexing_in_progress': indexing_in_progress,
'block_started': block_started,
'current_block': current_block,
'status': status
}
req_response=thread_response['http_status']
return jsonify(json_response), req_response
except Exception as e:
print (f"Error: {jsonify(e)}")
return jsonify({'error': 'Invalid request2'}), 500
@app.route('/nft/get_data',methods=['GET'])
@cross_origin(supports_credentials=True)
def get_nft_data():
if not api_utils.verify_db_connection():
return jsonify({'error': 'Database not connected'}), 502
try:
q = request.args.get('q')
nft_data= db_utils.nft_get_data(q)
return nft_data
except Exception as e:
print (f"Error: {jsonify(e)}")
return jsonify({'error': 'Invalid request2'}), 500
# ============================================================================
# Burn Statistics API Routes
# ============================================================================
@app.route('/burn/summary', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_summary_all():
"""Cross-chain burn summary (AVAX + BSC combined)."""
try:
data = burn_utils.get_burn_summary()
return jsonify(data)
except Exception as e:
print(f"Error in burn_summary_all: {e}")
return jsonify({'error': 'Failed to fetch burn summary'}), 500
@app.route('/burn/global', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_global():
"""Comprehensive cross-chain burn dashboard with on-chain verification."""
try:
data = burn_utils.get_global_burn_stats()
return jsonify(data)
except Exception as e:
print(f"Error in burn_global: {e}")
return jsonify({'error': 'Failed to fetch global burn stats'}), 500
@app.route('/burn/summary/<chain>', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_summary_chain(chain):
"""Single-chain burn summary."""
if chain not in ('avax', 'bsc'):
return jsonify({'error': 'Invalid chain. Use avax or bsc'}), 400
try:
data = burn_utils.get_burn_summary(chain)
return jsonify(data)
except Exception as e:
print(f"Error in burn_summary_chain: {e}")
return jsonify({'error': 'Failed to fetch burn summary'}), 500
@app.route('/burn/timeseries/<chain>', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_timeseries(chain):
"""Burn time series data for charts."""
if chain not in ('avax', 'bsc'):
return jsonify({'error': 'Invalid chain. Use avax or bsc'}), 400
bucket_type = request.args.get('bucket_type', 'monthly')
if bucket_type not in ('daily', 'weekly', 'monthly'):
return jsonify({'error': 'Invalid bucket_type. Use daily, weekly, or monthly'}), 400
limit = request.args.get('limit', None, type=int)
since = request.args.get('since', None, type=int)
try:
data = burn_utils.get_burn_time_series(chain, bucket_type, limit, since)
return jsonify(data)
except Exception as e:
print(f"Error in burn_timeseries: {e}")
return jsonify({'error': 'Failed to fetch burn time series'}), 500
@app.route('/burn/top-burners/<chain>', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_top_burners(chain):
"""Top burner wallet leaderboard."""
if chain not in ('avax', 'bsc'):
return jsonify({'error': 'Invalid chain. Use avax or bsc'}), 400
limit = request.args.get('limit', 20, type=int)
try:
data = burn_utils.get_top_burners(chain, limit)
return jsonify(data)
except Exception as e:
print(f"Error in burn_top_burners: {e}")
return jsonify({'error': 'Failed to fetch top burners'}), 500
@app.route('/burn/events/<chain>', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_events(chain):
"""Individual burn events, most recent first."""
if chain not in ('avax', 'bsc'):
return jsonify({'error': 'Invalid chain. Use avax or bsc'}), 400
limit = request.args.get('limit', 50, type=int)
since = request.args.get('since', None, type=int)
try:
data = burn_utils.get_burn_events(chain, limit, since)
return jsonify(data)
except Exception as e:
print(f"Error in burn_events: {e}")
return jsonify({'error': 'Failed to fetch burn events'}), 500
@app.route('/burn/status', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_status():
"""Indexing status for all chains."""
try:
data = burn_utils.get_indexing_status()
return jsonify(data)
except Exception as e:
print(f"Error in burn_status: {e}")
return jsonify({'error': 'Failed to fetch indexing status'}), 500
@app.route('/burn/holder/<chain>/<address>', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_holder_balance(chain, address):
"""Holder balance including reflections."""
if chain not in ('avax', 'bsc'):
return jsonify({'error': 'Invalid chain. Use avax or bsc'}), 400
try:
data = burn_utils.get_holder_balance(chain, address)
return jsonify(data)
except Exception as e:
print(f"Error in burn_holder_balance: {e}")
return jsonify({'error': 'Failed to fetch holder balance'}), 500
@app.route('/burn/reflections/<chain>/<address>', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_reflection_gains(chain, address):
"""Reflection gain breakdown for a holder."""
if chain not in ('avax', 'bsc'):
return jsonify({'error': 'Invalid chain. Use avax or bsc'}), 400
try:
data = burn_utils.get_holder_reflection_gains(chain, address)
return jsonify(data)
except Exception as e:
print(f"Error in burn_reflection_gains: {e}")
return jsonify({'error': 'Failed to fetch reflection gains'}), 500
@app.route('/burn/rate/<chain>', methods=['GET'])
@cross_origin(supports_credentials=True)
def burn_reflection_rate(chain):
"""Reflection rate time series."""
if chain not in ('avax', 'bsc'):
return jsonify({'error': 'Invalid chain. Use avax or bsc'}), 400
limit = request.args.get('limit', None, type=int)
try:
data = burn_utils.get_reflection_rate_history(chain, limit)
return jsonify(data)
except Exception as e:
print(f"Error in burn_reflection_rate: {e}")
return jsonify({'error': 'Failed to fetch reflection rate'}), 500
@app.route("/ipfs/challenge")
def api_challenge():
wallet = request.args.get("wallet", "").lower()
message = create_challenge(wallet)
return jsonify({"message": message})
@app.route("/ipfs/login", methods=["POST"])
def api_login():
data = request.json
session_id = verify_login(data["wallet"].lower(), data["message"], data["signature"])
if session_id:
return jsonify({"session_id": session_id})
return jsonify({"error": "Invalid login"}), 401
@app.route("/ipfs/session")
def api_session():
session_id = request.headers.get("Authorization", "").replace("Bearer ", "")
wallet = is_session_valid(session_id)
if wallet:
return jsonify({"valid": True, "wallet": wallet})
return jsonify({"valid": False}), 401
@app.route("/ipfs/user/info")
def ipfs_user_info():
session_id = request.headers.get("Authorization", "").replace("Bearer ", "")
data = get_user_info(session_id)
if not data:
return jsonify({"error": "Invalid session"}), 401
return jsonify(data)
@app.route("/ipfs/logoff", methods=["POST"])
def api_logoff():
session_id = request.headers.get("Authorization", "").replace("Bearer ", "")
logoff(session_id)
return jsonify({"logged_off": True})
@app.route("/ipfs/upload", methods=["POST"])
def ipfs_upload():
session_id = request.headers.get("Authorization", "").replace("Bearer ", "")
wallet = is_session_valid(session_id)
if not wallet:
return jsonify({"error": "Invalid session"}), 401
if "file" not in request.files:
return jsonify({"error": "No file provided"}), 400
file = request.files["file"]
filename = secure_filename(file.filename)
# Save file to temp file
with tempfile.NamedTemporaryFile(delete=False) as tmp:
file.save(tmp)
tmp_path = tmp.name
result = upload_and_pin_file(session_id, tmp_path, filename=filename)
# Clean up temp file
os.unlink(tmp_path)
if "error" in result:
return jsonify(result), 400
return jsonify(result), 200
@app.route("/ipfs/unpin", methods=["POST"])
def ipfs_unpin():
session_id = request.headers.get("Authorization", "").replace("Bearer ", "")
wallet = is_session_valid(session_id)
if not wallet:
return jsonify({"error": "Invalid session"}), 401
data = request.get_json()
cid = data.get("cid")
if not cid:
return jsonify({"error": "Missing CID"}), 400
result = unpin_file_by_cid(session_id, cid)
if "error" in result:
return jsonify(result), 400
return jsonify(result), 200
if os.getenv("ENVIRONMENT", "production"):
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5001))
app.run(host='127.0.0.1', port=port)
app.env = 'production' # Set the environment to development
else:
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.s
port = int(os.environ.get('PORT', 5001))
app.debug = True # Enable debugging
app.run(host='127.0.0.1', port=port)