-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
611 lines (534 loc) · 22.1 KB
/
api_server.py
File metadata and controls
611 lines (534 loc) · 22.1 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
"""
Flask API server for SumSub document uploads
Example REST API endpoints for uploading documents
"""
import os
import json
from flask import Flask, request, jsonify
from flask_cors import CORS
from sumsub_client import SumSubClient
from functools import lru_cache
from dotenv import load_dotenv
import os
from web3 import Web3
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
# Enable CORS for all routes and origins - simple configuration
CORS(app, resources={r"/*": {"origins": "*"}})
def api_route(st):
return st
@lru_cache()
def get_client():
"""
Lazy initialization of SumSub client.
Reads credentials from environment variables.
"""
return SumSubClient()
@lru_cache()
def get_web3():
"""
Initialize Web3 connection to Rails testnet.
Reads RPC URL from RAILS_RPC_URL environment variable.
"""
rpc_url = os.getenv('RAILS_RPC_URL')
if not rpc_url:
raise ValueError("RAILS_RPC_URL environment variable is required")
w3 = Web3(Web3.HTTPProvider(rpc_url))
return w3
@lru_cache()
def get_kyc_nft_contract():
"""
Get the KYC NFT contract instance.
"""
w3 = get_web3()
# Load contract address
contract_address = os.getenv('KYCNFT_CONTRACT_ADDRESS', '0x996dA15db8b9E938d8bEc848E27f6567990493BB')
# Load ABI
abi_path = os.path.join(os.path.dirname(__file__), 'abis', 'KYCNFT.json')
with open(abi_path, 'r') as f:
abi = json.load(f)
contract = w3.eth.contract(address=Web3.to_checksum_address(contract_address), abi=abi)
return contract
def get_account():
"""
Get the account from private key in .env file.
"""
private_key = os.getenv('PRIVATE_KEY')
if not private_key:
raise ValueError("PRIVATE_KEY environment variable is required")
w3 = get_web3()
account = w3.eth.account.from_key(private_key)
return account
@app.route(api_route('/applicants'), methods=['POST'])
def create_applicant():
"""
Create a new applicant
Request body:
{
"external_user_id": "user_12345",
"level_name": "basic-kyc-level", # Optional, can use SUMSUB_LEVEL_NAME env var
"email": "user@example.com",
"phone": "+1234567890",
"fixed_info": {
"firstName": "John",
"lastName": "Doe",
"dob": "1990-01-01",
"country": "US"
}
}
"""
try:
data = request.json
app.logger.info(f"Received create_applicant request: {data}")
client = get_client()
applicant = client.create_applicant(
external_user_id=data.get('external_user_id'),
level_name=data.get('level_name'), # Optional, will use env var if not provided
email=data.get('email'),
phone=data.get('phone'),
fixed_info=data.get('fixed_info')
)
app.logger.info(f"Applicant created: {applicant}")
return jsonify({
'success': True,
'applicant': applicant
}), 201
except Exception as e:
app.logger.error(f"create_applicant error: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route(api_route('/applicants/<applicant_id>/documents/passport'), methods=['POST'])
def upload_passport(applicant_id):
"""
Upload a passport document
Form data:
- file: passport image file
- country: (optional) ISO country code
"""
try:
app.logger.info(f"Received upload_passport for applicant_id={applicant_id}, files={list(request.files.keys())}, form={request.form}")
if 'file' not in request.files:
app.logger.warning("upload_passport: No file provided in request")
return jsonify({
'success': False,
'error': 'No file provided'
}), 400
file = request.files['file']
country = request.form.get('country')
client = get_client()
result = client.upload_passport(
applicant_id=applicant_id,
file_obj=file,
country=country
)
app.logger.info(f"Passport uploaded for applicant_id={applicant_id}, result={result}")
return jsonify({
'success': True,
'result': result
}), 200
except Exception as e:
app.logger.error(f"upload_passport error for applicant_id={applicant_id}: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route(api_route('/applicants/<applicant_id>/documents/id-card'), methods=['POST'])
def upload_id_card(applicant_id):
"""
Upload an ID card document
Form data:
- file: ID card image file
- country: (optional) ISO country code
- side: (optional) "FRONT" or "BACK"
"""
try:
app.logger.info(f"Received upload_id_card for applicant_id={applicant_id}, files={list(request.files.keys())}, form={request.form}")
if 'file' not in request.files:
app.logger.warning("upload_id_card: No file provided in request")
return jsonify({
'success': False,
'error': 'No file provided'
}), 400
file = request.files['file']
country = request.form.get('country')
side = request.form.get('side') # FRONT or BACK
client = get_client()
result = client.upload_id_card(
applicant_id=applicant_id,
file_obj=file,
country=country,
side=side
)
app.logger.info(f"ID card uploaded for applicant_id={applicant_id}, side={side}, result={result}")
return jsonify({
'success': True,
'result': result
}), 200
except Exception as e:
app.logger.error(f"upload_id_card error for applicant_id={applicant_id}: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route(api_route('/applicants/<applicant_id>/documents/drivers-license'), methods=['POST'])
def upload_drivers_license(applicant_id):
"""
Upload a driver's license document
Form data:
- file: driver's license image file
- country: (optional) ISO country code
- side: (optional) "FRONT" or "BACK"
"""
try:
app.logger.info(f"Received upload_drivers_license for applicant_id={applicant_id}, files={list(request.files.keys())}, form={request.form}")
if 'file' not in request.files:
app.logger.warning("upload_drivers_license: No file provided in request")
return jsonify({
'success': False,
'error': 'No file provided'
}), 400
file = request.files['file']
country = request.form.get('country')
side = request.form.get('side')
client = get_client()
result = client.upload_drivers_license(
applicant_id=applicant_id,
file_obj=file,
country=country,
side=side
)
app.logger.info(f"Driver's license uploaded for applicant_id={applicant_id}, side={side}, result={result}")
return jsonify({
'success': True,
'result': result
}), 200
except Exception as e:
app.logger.error(f"upload_drivers_license error for applicant_id={applicant_id}: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route(api_route('/applicants/<applicant_id>/documents/selfie'), methods=['POST'])
def upload_selfie(applicant_id):
"""
Upload a selfie photo
Form data:
- file: selfie image file
"""
try:
app.logger.info(f"Received upload_selfie for applicant_id={applicant_id}, files={list(request.files.keys())}, form={request.form}")
if 'file' not in request.files:
app.logger.warning("upload_selfie: No file provided in request")
return jsonify({
'success': False,
'error': 'No file provided'
}), 400
file = request.files['file']
client = get_client()
result = client.upload_selfie(
applicant_id=applicant_id,
file_obj=file
)
app.logger.info(f"Selfie uploaded for applicant_id={applicant_id}, result={result}")
return jsonify({
'success': True,
'result': result
}), 200
except Exception as e:
app.logger.error(f"upload_selfie error for applicant_id={applicant_id}: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route(api_route('/applicants/<applicant_id>/documents'), methods=['POST'])
def upload_document(applicant_id):
"""
Upload any document type
Form data:
- file: document file
- doc_type: Document type (PASSPORT, ID_CARD, DRIVERS, RESIDENCE_PERMIT, etc.)
- country: (optional) ISO country code
"""
try:
app.logger.info(f"Received upload_document for applicant_id={applicant_id}, files={list(request.files.keys())}, form={request.form}")
if 'file' not in request.files:
app.logger.warning("upload_document: No file provided in request")
return jsonify({
'success': False,
'error': 'No file provided'
}), 400
file = request.files['file']
doc_type = request.form.get('doc_type', 'PASSPORT')
country = request.form.get('country')
client = get_client()
result = client.upload_document(
applicant_id=applicant_id,
file_obj=file,
id_doc_type=doc_type,
country=country
)
app.logger.info(f"Document uploaded for applicant_id={applicant_id}, doc_type={doc_type}, result={result}")
return jsonify({
'success': True,
'result': result
}), 200
except Exception as e:
app.logger.error(f"upload_document error for applicant_id={applicant_id}: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route(api_route('/applicants/<applicant_id>/status'), methods=['GET'])
def get_applicant_status(applicant_id):
"""Get applicant status"""
try:
app.logger.info(f"Received get_applicant_status for applicant_id={applicant_id}")
client = get_client()
status = client.get_applicant_status(applicant_id)
app.logger.info(f"Status for applicant_id={applicant_id}: {status}")
return jsonify({
'success': True,
'status': status
}), 200
except Exception as e:
app.logger.error(f"get_applicant_status error for applicant_id={applicant_id}: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route('/api/nft/mint', methods=['POST'])
def mint_nft():
"""
Mint a KYC NFT
"""
try:
# Get contract and account
contract = get_kyc_nft_contract()
account = get_account()
w3 = get_web3()
# Parse input JSON - expects 'to', 'userId', 'platform', etc.
data = request.get_json(force=True)
to_address_raw = data.get('to')
user_id = data.get('userId') or data.get('applicantId') # Accept either key
platform = data.get('platform', 'unknown-platform')
# Explicitly fetch status from SumSub API using get_applicant_status
status = client.get_applicant_status(user_id)
firstName = status.get('info', {}).get('firstName')
lastName = status.get('info', {}).get('lastName')
kycStatus = status.get('reviewStatus') or status.get('status')
if not to_address_raw:
return jsonify({
'success': False,
'error': "Missing 'to' (Ethereum address) in request"
}), 400
if not user_id:
return jsonify({
'success': False,
'error': "Missing 'userId' (SumSub applicantId) in request"
}), 400
if not Web3.is_address(to_address_raw):
return jsonify({
'success': False,
'error': f"Invalid Ethereum address: {to_address_raw}"
}), 400
to_address = Web3.to_checksum_address(to_address_raw)
# Fetch applicant info and KYC status from SumSub API
try:
client = get_client()
status_response = client.get_applicant_status(user_id)
applicant = client.get_applicant(user_id)
info = applicant.get("info", {})
review_status = status_response.get("reviewStatus") or status_response.get("status") or "unknown"
except Exception as e:
return jsonify({
'success': False,
'error': f"Failed to fetch applicant data: {str(e)}"
}), 400
firstName = info.get("firstName", "Unknown")
lastName = info.get("lastName", "Unknown")
kycStatus = review_status
print(f"📝 Minting NFT for applicant/account:")
print(f" To: {to_address}")
print(f" First Name: {firstName}")
print(f" Last Name: {lastName}")
print(f" KYC Status: {kycStatus}")
print(f" Platform: {platform}")
print(f" userId/applicantId: {user_id}")
print(f" From: {account.address}")
# Estimate gas first
try:
print("⛽ Estimating gas...")
gas_estimate = contract.functions.mint(
to_address,
firstName,
lastName,
kycStatus,
platform
).estimate_gas({'from': account.address})
print(f"✅ Gas estimate: {gas_estimate:,}")
gas_limit = int(gas_estimate * 1.2) # Add 20% buffer
except Exception as gas_error:
error_message = str(gas_error)
print(f"⚠️ Gas estimation failed: {error_message}")
# Check if address already has an NFT
if "already has a KYC NFT" in error_message.lower() or "Address already has" in error_message:
print("ℹ️ Address already has a KYC NFT, retrieving existing token ID...")
try:
existing_token_id = contract.functions.getTokenIdByAddress(to_address).call()
print(f"✅ Found existing token ID: {existing_token_id}")
return jsonify({
'success': True,
'message': 'Address already has a KYC NFT',
'tokenId': existing_token_id,
'existing': True
}), 200
except Exception as lookup_error:
print(f"⚠️ Failed to get existing token ID: {lookup_error}")
return jsonify({
'success': False,
'error': f'Address already has a KYC NFT, but could not retrieve token ID: {str(lookup_error)}'
}), 400
# For other gas estimation errors, use default
print("⚠️ Using default gas limit")
gas_limit = 500000 # Default fallback
# Build transaction
print("📝 Building transaction...")
tx = contract.functions.mint(
to_address,
firstName,
lastName,
kycStatus,
platform
).build_transaction({
'from': account.address,
'nonce': w3.eth.get_transaction_count(account.address),
'gas': gas_limit,
'gasPrice': w3.eth.gas_price
})
print(f"✅ Transaction built, gas: {gas_limit:,}")
# Sign transaction
signed_tx = w3.eth.account.sign_transaction(tx, account.key)
# Send transaction
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
# Wait for transaction receipt
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
# Get token ID from events
token_id = None
if tx_receipt.status == 1:
print(f"📋 Transaction receipt status: {tx_receipt.status}")
print(f"📋 Number of logs in receipt: {len(tx_receipt.logs)}")
# Method 1: Try to get token ID by address (most reliable for this contract)
try:
print(f"📋 Attempting to get token ID by address: {to_address}")
token_id = contract.functions.getTokenIdByAddress(to_address).call()
print(f"✅ Got token ID from address lookup: {token_id}")
except Exception as addr_error:
print(f"⚠️ Address lookup failed: {addr_error}")
# Method 2: Parse KYCNFTMinted event from receipt
try:
print("📋 Attempting to parse KYCNFTMinted event...")
event_logs = contract.events.KYCNFTMinted().process_receipt(tx_receipt)
print(f"📋 Parsed event logs count: {len(event_logs) if event_logs else 0}")
if event_logs and len(event_logs) > 0:
# Get the token ID from the first event
event_args = event_logs[0].args
print(f"📋 Event args: {event_args}")
token_id = event_args.tokenId
print(f"✅ Extracted token ID from event: {token_id}")
else:
print("⚠️ No KYCNFTMinted events found in receipt")
print(f"📋 Available log addresses: {[log.address.hex() for log in tx_receipt.logs]}")
print(f"📋 Contract address: {contract.address}")
except Exception as event_error:
print(f"⚠️ Error parsing events: {event_error}")
import traceback
traceback.print_exc()
# Method 3: Fallback to totalSupply if event parsing failed
if token_id is None:
try:
print("📋 Attempting totalSupply fallback...")
total_supply = contract.functions.totalSupply().call()
print(f"📋 Total supply: {total_supply}")
if total_supply > 0:
# Try 0-indexed first (most common)
try:
token_id = total_supply - 1
owner = contract.functions.ownerOf(token_id).call()
if owner.lower() == to_address.lower():
print(f"✅ Got token ID from totalSupply (0-indexed): {token_id}")
else:
raise ValueError("Owner mismatch")
except:
# Try 1-indexed
try:
token_id = total_supply
owner = contract.functions.ownerOf(token_id).call()
if owner.lower() == to_address.lower():
print(f"✅ Got token ID from totalSupply (1-indexed): {token_id}")
else:
token_id = None
print("⚠️ Could not verify token ownership")
except:
token_id = None
print("⚠️ TotalSupply fallback verification failed")
except Exception as supply_error:
print(f"⚠️ TotalSupply fallback failed: {supply_error}")
else:
print(f"❌ Transaction failed with status: {tx_receipt.status}")
return jsonify({
'success': True,
'transactionHash': tx_hash.hex(),
'tokenId': token_id,
'receipt': {
'status': tx_receipt.status,
'blockNumber': tx_receipt.blockNumber,
'gasUsed': tx_receipt.gasUsed
}
}), 200
except ValueError as e:
print(f"ValueError in mint_nft: {str(e)}")
return jsonify({
'success': False,
'error': str(e)
}), 400
except Exception as e:
print(f"Exception in mint_nft: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({
'success': False,
'error': str(e)
}), 500
@app.route(api_route('/health'), methods=['GET'])
def health():
"""Health check endpoint"""
app.logger.info("Health check requested")
return jsonify({'status': 'healthy'}), 200
@app.route('/api/test', methods=['GET', 'POST', 'OPTIONS'])
def test_endpoint():
"""Test endpoint to verify CORS is working"""
if request.method == 'OPTIONS':
# Handle preflight request
return '', 200
return jsonify({
'success': True,
'message': 'CORS is working correctly',
'method': request.method,
'origin': request.headers.get('Origin', 'Not provided')
}), 200
if __name__ == '__main__':
print("Starting SumSub API Server...")
print("Available endpoints:")
print(f" POST {api_route('/applicants')} - Create applicant")
print(f" POST {api_route('/applicants/<id>/documents/passport')} - Upload passport")
print(f" POST {api_route('/applicants/<id>/documents/id-card')} - Upload ID card")
print(f" POST {api_route('/applicants/<id>/documents/drivers-license')} - Upload driver's license")
print(f" POST {api_route('/applicants/<id>/documents/selfie')} - Upload selfie")
print(f" POST {api_route('/applicants/<id>/documents')} - Upload any document")
print(f" GET {api_route('/applicants/<id>/status')} - Get applicant status")
print(f" POST {api_route('/applicants/<id>/verify')} - Initiate verification")
print(f"\nServer running on http://localhost:5000")
app.run(host='0.0.0.0', port=5000, debug=True)