/
ranchimallflo_api.py
1186 lines (989 loc) · 49.9 KB
/
ranchimallflo_api.py
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
from collections import defaultdict
import sqlite3
import json
import os
import requests
import sys
import time
from datetime import datetime
from quart import jsonify, make_response, Quart, render_template, request, flash, redirect, url_for, send_file
from quart_cors import cors
import subprocess
import asyncio
from typing import Optional
from config import *
import parsing
import subprocess
from apscheduler.schedulers.background import BackgroundScheduler
import atexit
import pathlib
import io
import zipfile
import tarfile
import pdb
app = Quart(__name__)
app.clients = set()
app = cors(app, allow_origin="*")
# helper functions
def retryRequest(tempserverlist, apicall):
if len(tempserverlist) != 0:
try:
response = requests.get(
'{}api/{}'.format(tempserverlist[0], apicall))
except:
tempserverlist.pop(0)
return retryRequest(tempserverlist, apicall)
else:
if response.status_code == 200:
return json.loads(response.content)
else:
tempserverlist.pop(0)
return retryRequest(tempserverlist, apicall)
else:
print("None of the APIs are responding for the call {}".format(apicall))
sys.exit(0)
def multiRequest(apicall, net):
testserverlist = ['http://0.0.0.0:9000/', 'https://testnet.flocha.in/',
'https://testnet-flosight.duckdns.org/']
mainserverlist = ['http://0.0.0.0:9001/', 'https://livenet.flocha.in/',
'https://testnet-flosight.duckdns.org/']
if net == 'mainnet':
return retryRequest(mainserverlist, apicall)
elif net == 'testnet':
return retryRequest(testserverlist, apicall)
def blockdetailhelper(blockdetail):
if blockdetail.isdigit():
blockHash = None
blockHeight = int(blockdetail)
else:
blockHash = str(blockdetail)
blockHeight = None
# open the latest block database
conn = sqlite3.connect(os.path.join(dbfolder, 'latestCache.db'))
c = conn.cursor()
if blockHash:
c.execute(
f"select jsonData from latestBlocks where blockHash='{blockHash}'")
elif blockHeight:
c.execute(
f"select jsonData from latestBlocks where blockNumber='{blockHeight}'")
blockJson = c.fetchall()
return blockJson
def transactiondetailhelper(transactionHash):
# check if legit transaction hash
# open the latest block database
conn = sqlite3.connect(os.path.join(dbfolder, 'latestCache.db'))
c = conn.cursor()
c.execute(f"select jsonData,parsedFloData from latestTransactions where transactionHash='{transactionHash}'")
transactionJsonData = c.fetchall()
return transactionJsonData
def update_transaction_confirmations(transactionJson):
url = f"{apiUrl}tx/{transactionJson['txid']}"
response = requests.get(url)
if response.status_code == 200:
response_data = response.json()
transactionJson['confirmations'] = response_data['confirmations']
return transactionJson
@app.route('/')
async def welcome():
return 'welcome'
# FLO TOKEN APIs
@app.route('/api/v1.0/broadcastTx/<raw_transaction_hash>')
async def broadcastTx(raw_transaction_hash):
p1 = subprocess.run(['flo-cli',f"-datadir={FLO_DATA_DIR}",'sendrawtransaction',raw_transaction_hash], capture_output=True)
return jsonify(args=p1.args,returncode=p1.returncode,stdout=p1.stdout.decode(),stderr=p1.stderr.decode())
@app.route('/api/v1.0/getTokenList', methods=['GET'])
async def getTokenList():
filelist = []
for item in os.listdir(os.path.join(dbfolder, 'tokens')):
if os.path.isfile(os.path.join(dbfolder, 'tokens', item)):
filelist.append(item[:-3])
return jsonify(tokens=filelist, result='ok')
@app.route('/api/v1.0/getTokenInfo', methods=['GET'])
async def getTokenInfo():
token = request.args.get('token')
if token is None:
return jsonify(result='error', description='token name hasnt been passed')
dblocation = dbfolder + '/tokens/' + str(token) + '.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
else:
return jsonify(result='error', description='token doesn\'t exist')
c.execute('SELECT * FROM transactionHistory WHERE id=1')
incorporationRow = c.fetchall()[0]
c.execute('SELECT COUNT (DISTINCT address) FROM activeTable')
numberOf_distinctAddresses = c.fetchall()[0][0]
c.execute('select max(id) from transactionHistory')
numberOf_transactions = c.fetchall()[0][0]
c.execute(
'select contractName, contractAddress, blockNumber, blockHash, transactionHash from tokenContractAssociation')
associatedContracts = c.fetchall()
conn.close()
associatedContractList = []
for item in associatedContracts:
tempdict = {}
item = list(item)
tempdict['contractName'] = item[0]
tempdict['contractAddress'] = item[1]
tempdict['blockNumber'] = item[2]
tempdict['blockHash'] = item[3]
tempdict['transactionHash'] = item[4]
associatedContractList.append(tempdict)
return jsonify(result='ok', token=token, incorporationAddress=incorporationRow[1], tokenSupply=incorporationRow[3],
time=incorporationRow[6], blockchainReference=incorporationRow[7],
activeAddress_no=numberOf_distinctAddresses, totalTransactions=numberOf_transactions, associatedSmartContracts=associatedContractList)
@app.route('/api/v1.0/getTokenTransactions', methods=['GET'])
async def getTokenTransactions():
token = request.args.get('token')
senderFloAddress = request.args.get('senderFloAddress')
destFloAddress = request.args.get('destFloAddress')
limit = request.args.get('limit')
if token is None:
return jsonify(result='error', description='token name hasnt been passed')
dblocation = dbfolder + '/tokens/' + str(token) + '.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
conn.row_factory = sqlite3.Row
c = conn.cursor()
else:
return jsonify(result='error', description='token doesn\'t exist')
if senderFloAddress and not destFloAddress:
if limit is None:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE sourceFloAddress="{}" ORDER BY id DESC'.format(senderFloAddress))
else:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE sourceFloAddress="{}" ORDER BY id DESC LIMIT {}'.format(senderFloAddress, limit))
elif not senderFloAddress and destFloAddress:
if limit is None:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE destFloAddress="{}" ORDER BY id DESC'.format(destFloAddress))
else:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE destFloAddress="{}" ORDER BY id DESC LIMIT {}'.format(destFloAddress, limit))
elif senderFloAddress and destFloAddress:
if limit is None:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE sourceFloAddress="{}" AND destFloAddress="{}" ORDER BY id DESC'.format(senderFloAddress, destFloAddress))
else:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE sourceFloAddress="{}" AND destFloAddress="{}" ORDER BY id DESC LIMIT {}'.format(senderFloAddress, destFloAddress, limit))
else:
if limit is None:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory ORDER BY id DESC')
else:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory ORDER BY id DESC LIMIT {}'.format(limit))
transactionJsonData = c.fetchall()
conn.close()
rowarray_list = {}
for row in transactionJsonData:
transactions_object = {}
transactions_object['transactionDetails'] = json.loads(row[0])
transactions_object['transactionDetails'] = update_transaction_confirmations(transactions_object['transactionDetails'])
transactions_object['parsedFloData'] = json.loads(row[1])
rowarray_list[transactions_object['transactionDetails']['txid']] = transactions_object
return jsonify(result='ok', token=token, transactions=rowarray_list)
@app.route('/api/v1.0/getTokenBalances', methods=['GET'])
async def getTokenBalances():
token = request.args.get('token')
if token is None:
return jsonify(result='error', description='token name hasnt been passed')
dblocation = dbfolder + '/tokens/' + str(token) + '.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
else:
return jsonify(result='error', description='token doesn\'t exist')
c.execute(
'SELECT address,SUM(transferBalance) FROM activeTable GROUP BY address')
addressBalances = c.fetchall()
returnList = {}
for address in addressBalances:
returnList[address[0]] = address[1]
return jsonify(result='ok', token=token, balances=returnList)
# FLO address APIs
@app.route('/api/v1.0/getFloAddressInfo', methods=['GET'])
async def getFloAddressInfo():
floAddress = request.args.get('floAddress')
if floAddress is None:
return jsonify(result='error', description='floAddress hasn\'t been passed')
dblocation = dbfolder + '/system.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
c.execute('select token from tokenAddressMapping where tokenAddress="{}"'.format(floAddress))
tokenNames = c.fetchall()
c.execute(f"select contractName, status, tokenIdentification, contractType, transactionHash, blockNumber, blockHash from activecontracts where contractAddress='{floAddress}'")
incorporatedContracts = c.fetchall()
if len(tokenNames) != 0:
detailList = {}
for token in tokenNames:
token = token[0]
dblocation = dbfolder + '/tokens/' + str(token) + '.db'
if os.path.exists(dblocation):
tempdict = {}
conn = sqlite3.connect(dblocation)
c = conn.cursor()
c.execute('SELECT SUM(transferBalance) FROM activeTable WHERE address="{}"'.format(floAddress))
balance = c.fetchall()[0][0]
tempdict['balance'] = balance
tempdict['token'] = token
detailList[token] = tempdict
else:
# Address is not associated with any token
return jsonify(result='error', description='FLO address is not associated with any tokens')
if len(incorporatedContracts) != 0:
incorporatedSmartContracts = []
for contract in incorporatedContracts:
tempdict = {}
tempdict['contractName'] = contract[0]
tempdict['contractAddress'] = floAddress
tempdict['status'] = contract[1]
tempdict['tokenIdentification'] = contract[2]
tempdict['contractType'] = contract[3]
tempdict['transactionHash'] = contract[4]
tempdict['blockNumber'] = contract[5]
tempdict['blockHash'] = contract[6]
incorporatedSmartContracts.append(tempdict)
return jsonify(result='ok', floAddress=floAddress, floAddressBalances=detailList, incorporatedSmartContracts=incorporatedContracts)
else:
return jsonify(result='ok', floAddress=floAddress, floAddressBalances=detailList, incorporatedSmartContracts=None)
@app.route('/api/v1.0/getFloAddressBalance', methods=['GET'])
async def getAddressBalance():
floAddress = request.args.get('floAddress')
token = request.args.get('token')
if floAddress is None:
return jsonify(result='error', description='floAddress hasn\'t been passed')
if token is None:
dblocation = dbfolder + '/system.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
c.execute(
'select token from tokenAddressMapping where tokenAddress="{}"'.format(floAddress))
tokenNames = c.fetchall()
if len(tokenNames) != 0:
detailList = {}
for token in tokenNames:
token = token[0]
dblocation = dbfolder + '/tokens/' + str(token) + '.db'
if os.path.exists(dblocation):
tempdict = {}
conn = sqlite3.connect(dblocation)
c = conn.cursor()
c.execute(
'SELECT SUM(transferBalance) FROM activeTable WHERE address="{}"'.format(floAddress))
balance = c.fetchall()[0][0]
tempdict['balance'] = balance
tempdict['token'] = token
detailList[token] = tempdict
return jsonify(result='ok', floAddress=floAddress, floAddressBalances=detailList)
else:
# Address is not associated with any token
return jsonify(result='error', description='FLO address is not associated with any tokens')
else:
dblocation = dbfolder + '/tokens/' + str(token) + '.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
else:
return jsonify(result='error', description='token doesn\'t exist')
c.execute(
'SELECT SUM(transferBalance) FROM activeTable WHERE address="{}"'.format(floAddress))
balance = c.fetchall()[0][0]
conn.close()
return jsonify(result='ok', token=token, floAddress=floAddress, balance=balance)
@app.route('/api/v1.0/getFloAddressTransactions', methods=['GET'])
async def getFloAddressTransactions():
floAddress = request.args.get('floAddress')
token = request.args.get('token')
limit = request.args.get('limit')
if floAddress is None:
return jsonify(result='error', description='floAddress has not been passed')
if token is None:
dblocation = dbfolder + '/system.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
c.execute('select token from tokenAddressMapping where tokenAddress="{}"'.format(floAddress))
tokenNames = c.fetchall()
else:
dblocation = dbfolder + '/tokens/' + str(token) + '.db'
if os.path.exists(dblocation):
tokenNames = [[str(token), ]]
else:
return jsonify(result='error', description='token doesn\'t exist')
if len(tokenNames) != 0:
allTransactionList = {}
for tokenname in tokenNames:
tokenname = tokenname[0]
dblocation = dbfolder + '/tokens/' + str(tokenname) + '.db'
if os.path.exists(dblocation):
tempdict = {}
conn = sqlite3.connect(dblocation)
c = conn.cursor()
if limit is None:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE sourceFloAddress="{}" OR destFloAddress="{}" ORDER BY id DESC'.format(floAddress, floAddress))
else:
c.execute('SELECT jsonData, parsedFloData FROM transactionHistory WHERE sourceFloAddress="{}" OR destFloAddress="{}" ORDER BY id DESC LIMIT {}'.format(floAddress, floAddress, limit))
transactionJsonData = c.fetchall()
conn.close()
for row in transactionJsonData:
transactions_object = {}
transactions_object['transactionDetails'] = json.loads(row[0])
transactions_object['transactionDetails'] = update_transaction_confirmations(transactions_object['transactionDetails'])
transactions_object['parsedFloData'] = json.loads(row[1])
allTransactionList[transactions_object['transactionDetails']['txid']] = transactions_object
if token is None:
return jsonify(result='ok', floAddress=floAddress, transactions=allTransactionList)
else:
return jsonify(result='ok', floAddress=floAddress, transactions=allTransactionList, token=token)
else:
return jsonify(result='error', description='No token transactions present present on this address')
# SMART CONTRACT APIs
@app.route('/api/v1.0/getSmartContractList', methods=['GET'])
async def getContractList():
contractName = request.args.get('contractName')
contractAddress = request.args.get('contractAddress')
conn = sqlite3.connect(os.path.join(dbfolder, 'system.db'))
c = conn.cursor()
contractList = []
if contractName and contractAddress:
c.execute('select * from activecontracts where contractName="{}" and contractAddress="{}"'.format(
contractName, contractAddress))
allcontractsDetailList = c.fetchall()
for idx, contract in enumerate(allcontractsDetailList):
contractDict = {}
contractDict['contractName'] = contract[1]
contractDict['contractAddress'] = contract[2]
contractDict['status'] = contract[3]
contractDict['tokenIdentification'] = contract[4]
contractDict['contractType'] = contract[5]
contractDict['transactionHash'] = contract[6]
contractDict['blockNumber'] = contract[7]
contractDict['incorporationDate'] = contract[8]
if contract[9]:
contractDict['expiryDate'] = contract[9]
if contract[10]:
contractDict['closeDate'] = contract[10]
contractList.append(contractDict)
elif contractName and not contractAddress:
c.execute(
'select * from activecontracts where contractName="{}"'.format(contractName))
allcontractsDetailList = c.fetchall()
for idx, contract in enumerate(allcontractsDetailList):
contractDict = {}
contractDict['contractName'] = contract[1]
contractDict['contractAddress'] = contract[2]
contractDict['status'] = contract[3]
contractDict['tokenIdentification'] = contract[4]
contractDict['contractType'] = contract[5]
contractDict['transactionHash'] = contract[6]
contractDict['blockNumber'] = contract[7]
contractDict['incorporationDate'] = contract[8]
if contract[9]:
contractDict['expiryDate'] = contract[9]
if contract[10]:
contractDict['closeDate'] = contract[10]
contractList.append(contractDict)
elif not contractName and contractAddress:
c.execute(
'select * from activecontracts where contractAddress="{}"'.format(contractAddress))
allcontractsDetailList = c.fetchall()
for idx, contract in enumerate(allcontractsDetailList):
contractDict = {}
contractDict['contractName'] = contract[1]
contractDict['contractAddress'] = contract[2]
contractDict['status'] = contract[3]
contractDict['tokenIdentification'] = contract[4]
contractDict['contractType'] = contract[5]
contractDict['transactionHash'] = contract[6]
contractDict['blockNumber'] = contract[7]
contractDict['incorporationDate'] = contract[8]
if contract[9]:
contractDict['expiryDate'] = contract[9]
if contract[10]:
contractDict['closeDate'] = contract[10]
contractList.append(contractDict)
else:
c.execute('select * from activecontracts')
allcontractsDetailList = c.fetchall()
for idx, contract in enumerate(allcontractsDetailList):
contractDict = {}
contractDict['contractName'] = contract[1]
contractDict['contractAddress'] = contract[2]
contractDict['status'] = contract[3]
contractDict['tokenIdentification'] = contract[4]
contractDict['contractType'] = contract[5]
contractDict['transactionHash'] = contract[6]
contractDict['blockNumber'] = contract[7]
contractDict['incorporationDate'] = contract[8]
if contract[9]:
contractDict['expiryDate'] = contract[9]
if contract[10]:
contractDict['closeDate'] = contract[10]
contractList.append(contractDict)
return jsonify(smartContracts=contractList, result='ok')
@app.route('/api/v1.0/getSmartContractInfo', methods=['GET'])
async def getContractInfo():
contractName = request.args.get('contractName')
contractAddress = request.args.get('contractAddress')
if contractName is None:
return jsonify(result='error', description='Smart Contract\'s name hasn\'t been passed')
if contractAddress is None:
return jsonify(result='error', description='Smart Contract\'s address hasn\'t been passed')
contractDbName = '{}-{}.db'.format(contractName.strip(),
contractAddress.strip())
filelocation = os.path.join(dbfolder, 'smartContracts', contractDbName)
if os.path.isfile(filelocation):
# Make db connection and fetch data
conn = sqlite3.connect(filelocation)
c = conn.cursor()
c.execute(
'SELECT attribute,value FROM contractstructure')
result = c.fetchall()
contractStructure = {}
conditionDict = {}
counter = 0
for item in result:
if list(item)[0] == 'exitconditions':
conditionDict[counter] = list(item)[1]
counter = counter + 1
else:
contractStructure[list(item)[0]] = list(item)[1]
if len(conditionDict) > 0:
contractStructure['exitconditions'] = conditionDict
del counter, conditionDict
returnval = contractStructure
returnval['userChoice'] = contractStructure['exitconditions']
returnval.pop('exitconditions')
c.execute('select count(participantAddress) from contractparticipants')
noOfParticipants = c.fetchall()[0][0]
returnval['numberOfParticipants'] = noOfParticipants
c.execute('select sum(tokenAmount) from contractparticipants')
totalAmount = c.fetchall()[0][0]
returnval['tokenAmountDeposited'] = totalAmount
conn.close()
conn = sqlite3.connect(os.path.join(dbfolder, 'system.db'))
c = conn.cursor()
c.execute('select status, incorporationDate, expiryDate, closeDate from activecontracts where contractName=="{}" and contractAddress=="{}"'.format(
contractName.strip(), contractAddress.strip()))
results = c.fetchall()
if len(results) == 1:
for result in results:
returnval['status'] = result[0]
returnval['incorporationDate'] = result[1]
if result[2]:
returnval['expiryDate'] = result[2]
if result[3]:
returnval['closeDate'] = result[3]
if returnval['status'] == 'closed':
conn = sqlite3.connect(filelocation)
c = conn.cursor()
if returnval['contractType'] == 'one-time-event':
# pull out trigger information
# check if the trigger was succesful or failed
c.execute(
f"select transactionType, transactionSubType from contractTransactionHistory where transactionType='trigger'")
triggerntype = c.fetchall()
if len(triggerntype) == 1:
triggerntype = list(triggerntype[0])
returnval['triggerType'] = triggerntype[1]
if 'userChoice' in returnval:
# Contract is of the type external trigger
if triggerntype[0] == 'trigger' and triggerntype[1] is None:
# this is a normal trigger
# find the winning condition
c.execute(
'select userchoice from contractparticipants where winningAmount is not null limit 1')
returnval['winningChoice'] = c.fetchall()[0][0]
# find the winning participants
c.execute(
'select participantAddress, winningAmount from contractparticipants where winningAmount is not null')
winnerparticipants = c.fetchall()
returnval['numberOfWinners'] = len(
winnerparticipants)
else:
return jsonify(result='error', description='There is more than 1 trigger in the database for the smart contract. Please check your code, this shouldnt happen')
return jsonify(result='ok', contractName=contractName, contractAddress=contractAddress, contractInfo=returnval)
else:
return jsonify(result='error', details='Smart Contract with the given name doesn\'t exist')
@app.route('/api/v1.0/getSmartContractParticipants', methods=['GET'])
async def getcontractparticipants():
contractName = request.args.get('contractName')
contractAddress = request.args.get('contractAddress')
if contractName is None:
return jsonify(result='error', description='Smart Contract\'s name hasn\'t been passed')
if contractAddress is None:
return jsonify(result='error', description='Smart Contract\'s address hasn\'t been passed')
contractDbName = '{}-{}.db'.format(contractName.strip(),
contractAddress.strip())
filelocation = os.path.join(dbfolder, 'smartContracts', contractDbName)
if os.path.isfile(filelocation):
# Make db connection and fetch data
conn = sqlite3.connect(filelocation)
c = conn.cursor()
c.execute(
'SELECT attribute,value FROM contractstructure')
result = c.fetchall()
contractStructure = {}
conditionDict = {}
counter = 0
for item in result:
if list(item)[0] == 'exitconditions':
conditionDict[counter] = list(item)[1]
counter = counter + 1
else:
contractStructure[list(item)[0]] = list(item)[1]
if len(conditionDict) > 0:
contractStructure['exitconditions'] = conditionDict
del counter, conditionDict
if 'exitconditions' in contractStructure:
# contract is of the type external trigger
# check if the contract has been closed
c.execute(
'select * from contractTransactionHistory where transactionType="trigger"')
trigger = c.fetchall()
if len(trigger) == 1:
c.execute(
'select value from contractstructure where attribute="tokenIdentification"')
token = c.fetchall()
token = token[0][0]
c.execute(
'SELECT id,participantAddress, tokenAmount, userChoice, transactionHash, winningAmount FROM contractparticipants')
result = c.fetchall()
conn.close()
returnval = {}
for row in result:
returnval[row[1]] = {'participantFloAddress': row[1], 'tokenAmount': row[2], 'userChoice': row[3],
'transactionHash': row[4], 'winningAmount': row[5], 'tokenIdentification': token}
return jsonify(result='ok', contractName=contractName, contractAddress=contractAddress,
participantInfo=returnval)
elif len(trigger) == 0:
c.execute(
'SELECT id,participantAddress, tokenAmount, userChoice, transactionHash FROM contractparticipants')
result = c.fetchall()
conn.close()
returnval = {}
for row in result:
returnval[row[1]] = {'participantFloAddress': row[1], 'tokenAmount': row[2], 'userChoice': row[3],
'transactionHash': row[4]}
return jsonify(result='ok', contractName=contractName, contractAddress=contractAddress,
participantInfo=returnval)
else:
return jsonify(result='error', description='More than 1 trigger present. This is unusual, please check your code')
elif 'payeeAddress' in contractStructure:
# contract is of the type internal trigger
c.execute(
'SELECT id,participantAddress, tokenAmount, userChoice, transactionHash FROM contractparticipants')
result = c.fetchall()
conn.close()
returnval = {}
for row in result:
returnval[row[1]] = {'participantFloAddress': row[1], 'tokenAmount': row[2], 'userChoice': row[3],
'transactionHash': row[4]}
return jsonify(result='ok', contractName=contractName, contractAddress=contractAddress, participantInfo=returnval)
else:
return jsonify(result='error', description='Smart Contract with the given name doesn\'t exist')
@app.route('/api/v1.0/getParticipantDetails', methods=['GET'])
async def getParticipantDetails():
floAddress = request.args.get('floAddress')
contractName = request.args.get('contractName')
contractAddress = request.args.get('contractAddress')
if floAddress is None:
return jsonify(result='error', description='FLO address hasn\'t been passed')
dblocation = os.path.join(dbfolder, 'system.db')
if (contractName and contractAddress is None) or (contractName is None and contractAddress):
return jsonify(result='error', description='pass both, contractName and contractAddress as url parameters')
if os.path.isfile(dblocation):
# Make db connection and fetch data
conn = sqlite3.connect(dblocation)
c = conn.cursor()
# Check if its a participant address
queryString = f"SELECT id, address,contractName, contractAddress, tokenAmount, transactionHash, blockNumber, blockHash FROM contractAddressMapping where address='{floAddress}' and addressType='participant'"
c.execute(queryString)
result = c.fetchall()
if len(result) != 0:
participationDetailsList = []
for row in result:
detailsDict = {}
detailsDict['contractName'] = row[2]
detailsDict['contractAddress'] = row[3]
detailsDict['tokenAmount'] = row[4]
detailsDict['transactionHash'] = row[5]
c.execute(f"select status, tokenIdentification, contractType, blockNumber, blockHash, incorporationDate, expiryDate, closeDate from activecontracts where contractName='{detailsDict['contractName']}' and contractAddress='{detailsDict['contractAddress']}'")
temp = c.fetchall()
detailsDict['status'] = temp[0][0]
detailsDict['tokenIdentification'] = temp[0][1]
detailsDict['contractType'] = temp[0][2]
detailsDict['blockNumber'] = temp[0][3]
detailsDict['blockHash'] = temp[0][4]
detailsDict['incorporationDate'] = temp[0][5]
if temp[0][6]:
detailsDict['expiryDate'] = temp[0][6]
if temp[0][7]:
detailsDict['closeDate'] = temp[0][7]
# check if the contract has been closed
contractDbName = '{}-{}.db'.format(detailsDict['contractName'].strip(),
detailsDict['contractAddress'].strip())
filelocation = os.path.join(
dbfolder, 'smartContracts', contractDbName)
if os.path.isfile(filelocation):
# Make db connection and fetch data
conn = sqlite3.connect(filelocation)
c = conn.cursor()
c.execute(
'SELECT attribute,value FROM contractstructure')
result = c.fetchall()
contractStructure = {}
conditionDict = {}
counter = 0
for item in result:
if list(item)[0] == 'exitconditions':
conditionDict[counter] = list(item)[1]
counter = counter + 1
else:
contractStructure[list(item)[0]] = list(item)[1]
if len(conditionDict) > 0:
contractStructure['exitconditions'] = conditionDict
del counter, conditionDict
if 'exitconditions' in contractStructure:
# contract is of the type external trigger
# check if the contract has been closed
c.execute(
'select * from contractTransactionHistory where transactionType="trigger"')
trigger = c.fetchall()
if detailsDict['status'] == 'closed':
c.execute(
f"SELECT userChoice, winningAmount FROM contractparticipants where participantAddress='{floAddress}'")
result = c.fetchall()
conn.close()
detailsDict['userChoice'] = result[0][0]
detailsDict['winningAmount'] = result[0][1]
else:
c.execute(
f"SELECT userChoice FROM contractparticipants where participantAddress='{floAddress}'")
result = c.fetchall()
conn.close()
detailsDict['userChoice'] = result[0][0]
participationDetailsList.append(detailsDict)
return jsonify(result='ok', floAddress=floAddress, type='participant', participatedContracts=participationDetailsList)
else:
return jsonify(result='error', description='Address hasn\'t participanted in any other contract')
else:
return jsonify(result='error', description='System error. System db is missing')
@app.route('/api/v1.0/getSmartContractTransactions', methods=['GET'])
async def getsmartcontracttransactions():
contractName = request.args.get('contractName')
contractAddress = request.args.get('contractAddress')
if contractName is None:
return jsonify(result='error', description='Smart Contract\'s name hasn\'t been passed')
if contractAddress is None:
return jsonify(result='error', description='Smart Contract\'s address hasn\'t been passed')
contractDbName = '{}-{}.db'.format(contractName.strip(),
contractAddress.strip())
filelocation = os.path.join(dbfolder, 'smartContracts', contractDbName)
if os.path.isfile(filelocation):
# Make db connection and fetch data
conn = sqlite3.connect(filelocation)
c = conn.cursor()
c.execute('select jsonData, parsedFloData from contractTransactionHistory')
result = c.fetchall()
conn.close()
returnval = {}
for item in result:
transactions_object = {}
transactions_object['transactionDetails'] = json.loads(item[0])
transactions_object['transactionDetails'] = update_transaction_confirmations(transactions_object['transactionDetails'])
transactions_object['parsedFloData'] = json.loads(item[1])
returnval[transactions_object['transactionDetails']['txid']] = transactions_object
return jsonify(result='ok', contractName=contractName, contractAddress=contractAddress, contractTransactions=returnval)
else:
return jsonify(result='error', description='Smart Contract with the given name doesn\'t exist')
@app.route('/api/v1.0/getBlockDetails/<blockdetail>', methods=['GET'])
async def getblockdetails(blockdetail):
blockJson = blockdetailhelper(blockdetail)
if len(blockJson) != 0:
blockJson = json.loads(blockJson[0][0])
return jsonify(result='ok', blockDetails=blockJson)
else:
return jsonify(result='error', description='Block doesn\'t exist in database')
@app.route('/api/v1.0/getTransactionDetails/<transactionHash>', methods=['GET'])
async def gettransactiondetails(transactionHash):
transactionJsonData = transactiondetailhelper(transactionHash)
if len(transactionJsonData) != 0:
transactionJson = json.loads(transactionJsonData[0][0])
transactionJson = update_transaction_confirmations(transactionJson)
parseResult = json.loads(transactionJsonData[0][1])
return jsonify(parsedFloData=parseResult, transactionDetails=transactionJson, transactionHash=transactionHash, result='ok')
else:
return jsonify(result='error', description='Transaction doesn\'t exist in database')
@app.route('/api/v1.0/getLatestTransactionDetails', methods=['GET'])
async def getLatestTransactionDetails():
numberOfLatestBlocks = request.args.get('numberOfLatestBlocks')
dblocation = dbfolder + '/latestCache.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
else:
return 'Latest transactions db doesn\'t exist. This is unusual, please report on https://github.com/ranchimall/ranchimallflo-api'
if numberOfLatestBlocks is not None:
c.execute('SELECT * FROM latestTransactions WHERE blockNumber IN (SELECT DISTINCT blockNumber FROM latestTransactions ORDER BY blockNumber DESC LIMIT {}) ORDER BY id ASC;'.format(int(numberOfLatestBlocks)))
latestTransactions = c.fetchall()
c.close()
tempdict = {}
for idx, item in enumerate(latestTransactions):
item = list(item)
tx_parsed_details = {}
tx_parsed_details['transactionDetails'] = json.loads(item[3])
tx_parsed_details['transactionDetails'] = update_transaction_confirmations(tx_parsed_details['transactionDetails'])
tx_parsed_details['parsedFloData'] = json.loads(item[5])
tx_parsed_details['parsedFloData']['transactionType'] = item[4]
tx_parsed_details['transactionDetails']['blockheight'] = int(item[2])
tempdict[json.loads(item[3])['txid']] = tx_parsed_details
else:
c.execute('''SELECT * FROM latestTransactions WHERE blockNumber IN (SELECT DISTINCT blockNumber FROM latestTransactions ORDER BY blockNumber DESC) ORDER BY id ASC;''')
latestTransactions = c.fetchall()
c.close()
tempdict = {}
for idx, item in enumerate(latestTransactions):
item = list(item)
tx_parsed_details = {}
tx_parsed_details['transactionDetails'] = json.loads(item[3])
tx_parsed_details['transactionDetails'] = update_transaction_confirmations(tx_parsed_details['transactionDetails'])
tx_parsed_details['parsedFloData'] = json.loads(item[5])
tx_parsed_details['parsedFloData']['transactionType'] = item[4]
tx_parsed_details['transactionDetails']['blockheight'] = int(item[2])
tempdict[json.loads(item[3])['txid']] = tx_parsed_details
return jsonify(result='ok', latestTransactions=tempdict)
@app.route('/api/v1.0/getLatestBlockDetails', methods=['GET'])
async def getLatestBlockDetails():
limit = request.args.get('limit')
dblocation = dbfolder + '/latestCache.db'
if os.path.exists(dblocation):
conn = sqlite3.connect(dblocation)
c = conn.cursor()
else:
return 'Latest transactions db doesn\'t exist. This is unusual, please report on https://github.com/ranchimall/ranchimallflo-api'
if limit is None:
c.execute('''SELECT * FROM ( SELECT * FROM latestBlocks ORDER BY blockNumber DESC LIMIT 4) ORDER BY id ASC;''')
else:
int(limit)
c.execute('SELECT * FROM ( SELECT * FROM latestBlocks ORDER BY blockNumber DESC LIMIT {}) ORDER BY id ASC;'.format(limit))
latestBlocks = c.fetchall()
c.close()
tempdict = {}
for idx, item in enumerate(latestBlocks):
tempdict[json.loads(item[3])['hash']] = json.loads(item[3])
return jsonify(result='ok', latestBlocks=tempdict)
@app.route('/api/v1.0/getBlockTransactions/<blockdetail>', methods=['GET'])
async def getblocktransactions(blockdetail):
blockJson = blockdetailhelper(blockdetail)
if len(blockJson) != 0:
blockJson = json.loads(blockJson[0][0])
blocktxlist = blockJson['tx']
blocktxs = {}
for i in range(len(blocktxlist)):
temptx = transactiondetailhelper(blocktxlist[i])
transactionJson = json.loads(temptx[0][0])
transactionJson = update_transaction_confirmations(transactionJson)
parseResult = json.loads(temptx[0][1])
blocktxs[blocktxlist[i]] = {
"parsedFloData" : parseResult,
"transactionDetails" : transactionJson
}
return jsonify(result='ok', transactions=blocktxs, blockKeyword=blockdetail)
else:
return jsonify(result='error', description='Block doesn\'t exist in database')
@app.route('/api/v1.0/categoriseString/<urlstring>')
async def categoriseString(urlstring):
# check if the hash is of a transaction
response = requests.get('{}tx/{}'.format(apiUrl, urlstring))
if response.status_code == 200:
return jsonify(type='transaction')
else:
response = requests.get('{}block/{}'.format(apiUrl, urlstring))
if response.status_code == 200:
return jsonify(type='block')
else:
# check urlstring is a token name
tokenfolder = os.path.join(dbfolder, 'tokens')
onlyfiles = [f[:-3]
for f in os.listdir(tokenfolder) if os.path.isfile(os.path.join(tokenfolder, f))]
if urlstring.lower() in onlyfiles:
return jsonify(type='token')
else:
contractfolder = os.path.join(dbfolder, 'system.db')
conn = sqlite3.connect(contractfolder)
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()
contractList = c.execute(
'select contractname from activeContracts').fetchall()
if urlstring.lower() in contractList:
return jsonify(type='smartContract')
else:
return jsonify(type='noise')
@app.route('/api/v1.0/getTokenSmartContractList', methods=['GET'])
async def getTokenSmartContractList():
# list of tokens
filelist = []
for item in os.listdir(os.path.join(dbfolder, 'tokens')):
if os.path.isfile(os.path.join(dbfolder, 'tokens', item)):
filelist.append(item[:-3])
# list of smart contracts
conn = sqlite3.connect(os.path.join(dbfolder, 'system.db'))
c = conn.cursor()
contractList = []
c.execute('select * from activecontracts')
allcontractsDetailList = c.fetchall()