-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.py
More file actions
625 lines (476 loc) · 18.1 KB
/
api.py
File metadata and controls
625 lines (476 loc) · 18.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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
from flask_cors import CORS, cross_origin
from flask import Flask, request
from dotenv import load_dotenv
import json
import string
import os
from kinetic_sdk import KineticSdk, Commitment
from kinetic_sdk.keypair import Keypair
from kinetic_sdk.models.transaction_type import TransactionType
load_dotenv()
app = Flask(__name__)
CORS(app)
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - Kin Python SDK App')
app_index = int(os.environ.get('APP_INDEX'))
print(' - App Index', app_index)
kinetic_client = None
kinetic_client_env = 'devnet'
# print(os.environ.get('BYTE_ARRAY'))
# app_hot_wallet = Keypair.from_secret(
# os.environ.get('BYTE_ARRAY'))
print(os.environ.get('MNEMONIC'))
app_hot_wallet = Keypair.from_secret(
os.environ.get('MNEMONIC'))
app_user_name = 'App'
app_public_key = app_hot_wallet.public_key.to_base58().decode()
print(' - App Public Key:', app_public_key)
app_user = {
'name': app_user_name,
'publicKey': app_public_key,
'keypair': app_hot_wallet,
}
devnet_users = []
mainnet_users = []
transactions = list([])
def save_user(name: string, keypair: Keypair):
# %%%%%%%%%%%% IMPORTANT %%%%%%%%%%%%
# TODO - Save your account data securely
new_user = {
'name': name,
'publicKey': keypair.public_key.to_base58().decode(),
'keypair': keypair,
}
if kinetic_client_env == 'devnet':
devnet_users.append(new_user)
if kinetic_client_env == 'mainnet':
mainnet_users.append(new_user)
def delete_user(name: string):
global devnet_users
global mainnet_users
if kinetic_client_env == 'devnet':
filtered_arr = [p for p in devnet_users if p['name'] != name]
devnet_users = filtered_arr
if kinetic_client_env == 'mainnet':
filtered_arr = [p for p in mainnet_users if p['name'] != name]
mainnet_users = filtered_arr
def save_transaction(transaction: string):
# TODO save your transaction data if required
transactions.append(transaction)
def get_sanitised_user_data(user: string):
name = user['name']
print('name: ', name)
public_key = user['publicKey']
print('public_key: ', public_key)
return {
'name': name,
'publicKey': public_key
}
def get_user(name: string):
user = None
if kinetic_client_env == 'devnet' and devnet_users:
user = next((x for x in devnet_users if x['name'] == name), None)
if kinetic_client_env == 'mainnet' and mainnet_users:
user = next((x for x in mainnet_users if x['name'] == name), None)
if name == 'App':
user = app_user
return user
def get_users():
print('get_users: ')
users_response = []
env = 1
if kinetic_client_env == 'devnet':
users_response = list(map(get_sanitised_user_data, devnet_users))
if kinetic_client_env == 'mainnet':
users_response = list(map(get_sanitised_user_data, mainnet_users))
env = 0
# insert app user into array
users_response.insert(0, get_sanitised_user_data(app_user))
return users_response, env
@cross_origin()
@app.route('/status', methods=['GET'])
def status():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - get /status')
users_response, env = get_users()
app_index_response = 0
environment_response = 'devnet'
if (kinetic_client is not None and hasattr(kinetic_client, 'config')):
print('kinetic_client: ', kinetic_client.config)
app_index_response = kinetic_client.config['app']['index']
environment_response = kinetic_client.config['environment']['name']
response = {'appIndex': app_index_response,
'env': environment_response,
'users': users_response,
'transactions': transactions}
return response
def reset_on_setup_error():
global app_token_accounts
app_token_accounts = []
app_user['kinTokenAccounts'] = app_token_accounts
global kinetic_client
kinetic_client = None
global kinetic_client_env
kinetic_client_env = 'devnet'
@cross_origin()
@app.route('/setup', methods=['POST'])
def setup():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - post /setup')
env_string = request.args.get('env')
print('env_string', env_string)
try:
environment = 'devnet'
endpoint = os.environ.get(
'KINETIC_ENDPOINT') or 'https://sandbox.kinetic.host'
if env_string in ('Prod', 'Mainnet'):
environment = 'mainnet'
endpoint = os.environ.get('KINETIC_ENDPOINT')
print('environment: ', environment)
print('endpoint: ', endpoint)
print('app_index: ', app_index)
new_kinetic_client = KineticSdk.setup(
endpoint=endpoint, environment=environment, index=app_index)
print('new_kinetic_client: ', new_kinetic_client.config)
balance = None
try:
# check it exists
balance = new_kinetic_client.get_balance(
account=app_hot_wallet.public_key)
if not balance['tokens']:
raise Exception("No Token Account")
except Exception as e:
print('Error:', e)
# if not, create it
new_kinetic_client.create_account(
owner=app_hot_wallet, commitment=Commitment('Confirmed'))
balance = new_kinetic_client.get_balance(
account=app_hot_wallet.public_key)
print('balance', balance)
global kinetic_client
kinetic_client = new_kinetic_client
global kinetic_client_env
kinetic_client_env = environment
print('Setup successful')
response = '', 200
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
reset_on_setup_error()
response = '', 400
return response
@cross_origin()
@app.route('/account', methods=['POST'])
def account():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - post /account')
try:
name = request.args.get('name')
print('name', name)
mnemonic = Keypair.generate_mnemonic()
print('mnemonic: ', mnemonic)
print(type(mnemonic))
keypair = Keypair.from_secret(mnemonic)
# keypair = Keypair.random()
print('keypair: ', keypair)
commitment = Commitment('Confirmed')
print('commitment: ', commitment)
account = kinetic_client.create_account(
owner=keypair, commitment=commitment)
print('Account created', keypair.public_key.to_base58().decode(),
account['signature'])
save_user(name, keypair)
save_transaction(account['signature'])
response = '', 201
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/close-account', methods=['POST'])
def close_account():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - post /close-account')
try:
name = request.args.get('user')
print('name', name)
user = get_user(name)
account_id = user['publicKey']
print('account_id: ', account_id)
transaction = kinetic_client.close_account(
account=account_id)
print('balance', balance)
delete_user(name)
save_transaction(transaction['signature'])
response = '', 201
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/balance', methods=['GET'])
def balance():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - get /balance')
try:
name = request.args.get('user')
print('name', name)
user = get_user(name)
account_id = user['publicKey']
print('account_id: ', account_id)
balance = kinetic_client.get_balance(
account=account_id)
print('balance', balance)
balance_in_kin = balance['balance']
response = str(balance_in_kin)
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/airdrop', methods=['POST'])
def airdrop():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - post /airdrop')
try:
name = request.args.get('to')
print('name', name)
amount = request.args.get('amount')
print('amount', amount)
user = get_user(name)
print('user: ', user)
account_id = user['publicKey']
print('account_id: ', account_id)
airdrop = kinetic_client.request_airdrop(
account=account_id, amount=amount, commitment=Commitment('Confirmed'))
print('airdrop: ', airdrop)
save_transaction(airdrop['signature'])
response = '', 200
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
def get_transaction_type(type_string):
if type_string == 'P2P':
return TransactionType.P2P
if type_string == 'Earn':
return TransactionType.EARN
if type_string == 'Spend':
return TransactionType.SPEND
return TransactionType.NONE
@cross_origin()
@app.route('/send', methods=['POST'])
def send():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - post /send')
try:
from_name = request.json.get('from')
print('from_name', from_name)
to_name = request.json.get('to')
print('to_name', to_name)
amount = request.json.get('amount')
print('amount', amount)
type_string = request.json.get('type')
print('type_string', type_string)
owner = get_user(from_name)['keypair']
print('owner: ', owner)
destination = get_user(to_name)['publicKey']
print('destination: ', destination)
tx_type = get_transaction_type(type_string)
print('tx_type: ', tx_type)
transfer = kinetic_client.make_transfer(
commitment=Commitment('Confirmed'),
amount=amount,
destination=destination,
owner=owner,
tx_type=tx_type,
reference='some reference',
# sender_create=False
)
transaction_id = transfer['signature']
print('transfer complete: ', transaction_id)
save_transaction(transaction_id)
response = '', 200
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/earn_batch', methods=['POST'])
def earn_batch():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - post /earn_batch')
try:
from_name = request.json.get('from')
print('from_name', from_name)
from_user = get_user(from_name)
owner = from_user['keypair']
print('sender: ', owner.public_key)
payments = request.json.get('batch')
print('payments: ', payments)
destinations = []
print('destinations: ', destinations)
for payment in payments:
to_user = get_user(payment["to"])
destination = to_user["keypair"].public_key
amount = payment['amount']
destinations.append({'destination': destination, 'amount': amount})
print('destinations: ', destinations)
batch_transfer = kinetic_client.make_transfer_batch(
commitment=Commitment('Confirmed'),
owner=owner,
destinations=destinations,
reference='some reference',
# sender_create=False
)
transaction_id = batch_transfer['signature']
print('batch transfer complete: ', transaction_id)
save_transaction(transaction_id)
response = '', 200
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/transaction', methods=['GET'])
def transaction():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - get /transaction')
try:
transaction_id = request.args.get('transaction_id')
print('transaction_id: ', transaction_id)
transaction = kinetic_client.get_transaction(signature=transaction_id)
print('transaction: ', transaction)
response = str(transaction)
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/history', methods=['GET'])
def history():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - get /history')
try:
name = request.args.get('user')
print('name', name)
user = get_user(name)
history = kinetic_client.get_history(
account=user['keypair'].public_key)
print('history', history)
response = str(history)
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/account-info', methods=['GET'])
def account_info():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - get /account-info')
try:
name = request.args.get('user')
print('name', name)
user = get_user(name)
account_info = kinetic_client.get_account_info(
account=user['keypair'].public_key)
print('account_info', account_info)
response = str(account_info)
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
@cross_origin()
@app.route('/token-accounts', methods=['GET'])
def token_accounts():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - get /token-accounts')
try:
name = request.args.get('user')
print('name', name)
user = get_user(name)
token_accounts = kinetic_client.get_token_accounts(
account=user['keypair'].public_key)
print('token_accounts', token_accounts)
response = str(token_accounts)
return response
except Exception as e:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('Error:', e)
response = '', 400
return response
# Webhooks
# I use localtunnel for doing local development
# https://theboroer.github.io/localtunnel-www/
# You could also use ngrok
# https://ngrok.com/
@cross_origin()
@app.route('/events', methods=['POST'])
def events():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - Event Webhook')
print('request: ', request.json)
response = '', 200
return response
@cross_origin()
@app.route('/verify', methods=["POST"])
def sign_transaction():
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print(' - Verify Transaction Webhook')
print('request: ', request.json)
# TODO
# Verify the transaction
# Return 400 if no good
# Return 200 to allow the transaction
response = '', 200
return response
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
port = os.environ.get('PORT') or 3001
if __name__ == '__main__':
app.run(debug=True, port=port)