This repository has been archived by the owner on Nov 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
240 lines (198 loc) · 7.27 KB
/
main.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
#!/usr/bin/env python3
import json
from flask import Flask, request
from flask import render_template
from algosdk import kmd
from algosdk import mnemonic, v2client
from algosdk.abi import Contract
from algosdk.encoding import (
base64,
is_valid_address,
msgpack,
msgpack_encode,
future_msgpack_decode
)
from algosdk.future.transaction import (
OnComplete,
StateSchema,
PaymentTxn,
AssetTransferTxn,
ApplicationCreateTxn,
ApplicationCallTxn,
SignedTransaction,
wait_for_confirmation
)
from algosdk.atomic_transaction_composer import (
AtomicTransactionComposer,
AccountTransactionSigner,
TransactionWithSigner
)
app = Flask(__name__)
# Sandbox Node
algod_token = 'a' *64
algod_addr = 'http://127.0.0.1:4001'
algod_client = v2client.algod.AlgodClient(algod_token, algod_addr)
# Sandbox Accounts
kmd_token = 'a' * 64
kmd_addr = 'http://127.0.0.1:4002'
kmd_client = kmd.KMDClient(kmd_token, kmd_addr)
wallet_id = kmd_client.list_wallets()[0]['id']
wallet_hnd = kmd_client.init_wallet_handle(wallet_id, "")
accounts_pk = kmd_client.list_keys(wallet_hnd)
accounts_sk = {}
for acc in accounts_pk:
accounts_sk[acc] = kmd_client.export_key(wallet_hnd, "", acc)
kmd_client.release_wallet_handle(wallet_hnd)
def get_method(c: Contract, name: str):
for m in c.methods:
if m.name == name:
return m
raise Exception("No method with the name {}".format(name))
def update_appid(app_id: int, genesis_hash: str):
# Update the appID in the ABI.json file.
with open('static/demo_interface.json') as json_file:
abi = json.load(json_file)
abi['networks'] = {genesis_hash: {'appID': app_id}}
with open('static/demo_contract.json', 'w') as json_file:
json.dump(abi, json_file, indent=4)
# Index
@app.route('/')
def root():
return render_template('index.html')
# Deploy Demo.teal
@app.route("/deploy_app", methods=['POST'])
def deploy_app():
deployer_pk = accounts_pk[0]
# Get TEAL
with open('static/demo.teal') as f:
approval_teal = f.read()
with open('static/clear.teal') as f:
clear_teal = f.read()
# Compile TEAL
approval_prog = base64.b64decode(algod_client.compile(approval_teal)['result'])
clear_prog = base64.b64decode(algod_client.compile(approval_teal)['result'])
# Deploy
sp = algod_client.suggested_params()
sp.flat_fee = True
sp.fee = 1_000
deploy_txn = ApplicationCreateTxn(
deployer_pk,
sp,
OnComplete.NoOpOC,
approval_prog,
clear_prog,
StateSchema(0, 0),
StateSchema(0, 0)
)
deploy_stxn = deploy_txn.sign(accounts_sk[deployer_pk])
txid = algod_client.send_transaction(deploy_stxn)
res = wait_for_confirmation(algod_client, txid)
genesis_hash = sp.gh
app_id = res['application-index']
update_appid(app_id, genesis_hash)
return {'success': True, 'AppID': app_id}
# Fund ALGO
@app.route("/fund_algo", methods=['POST'])
def fund_algo():
# Verify they sent us the data we need.
data = json.loads(request.data)
if not is_valid_address(data['receiver']):
return {'success': False, 'message': "Receiver address invalid."}
receiver = data['receiver']
sender = accounts_pk[0]
sp = algod_client.suggested_params()
sp.flat_fee = True
sp.fee = 1_000
algo_txn = PaymentTxn(sender, sp, receiver, 10_000_000)
algo_stxn = algo_txn.sign(accounts_sk[sender])
txid = algod_client.send_transaction(algo_stxn)
res = wait_for_confirmation(algod_client, txid)
return {'success': True, 'message': "10 Algo sent."}
###############################
# Atomic Transaction Composer #
###############################
# Demo 1: Send Payment
# Create a Payment Transaction and add it to the ATC with an ATS.
@app.route("/get_payment", methods=['POST'])
def demo1():
# Verify they sent us the data we need.
data = json.loads(request.data)
if not is_valid_address(data['sender']):
return {'success': False, 'message': "Sender address invalid."}
if not is_valid_address(data['receiver']):
return {'success': False, 'message': "Receiver address invalid."}
if not isinstance(data['amount'], int):
return {'success': False, 'message': "Amount not valid."}
# Fetch and set the suggested parameters.
sp = algod_client.suggested_params()
sp.flat_fee = True
sp.fee = 1_000
# Create an ATC object, an ATS object (with no defined sender), then add
# your Payment Transaction into the ATC object.
atc = AtomicTransactionComposer()
ats = AccountTransactionSigner(None)
ptxn = PaymentTxn(data['sender'], sp, data['receiver'], data['amount'])
tws = TransactionWithSigner(ptxn, ats)
atc.add_transaction(tws)
# We need to return a group of transactions in a format that the frontend
# can interpret as a set of unsigned transactions to sign. We can use
# `atc.build_group()` for this process.
txgroup = []
for tx in atc.build_group():
txgroup.append({'txn': msgpack_encode(tx.txn)})
return {'success': True, 'data': txgroup}
# Demo 2: Payment + Asset Transfer + Application Call
@app.route("/get_application_call", methods=['POST'])
def demo2():
# Verify they sent us the data we need.
data = json.loads(request.data)
if not is_valid_address(data['sender']):
return {'success': False, 'message': "Sender address invalid."}
# Fetch and set the suggested parameters.
sp = algod_client.suggested_params()
sp.flat_fee = True
sp.fee = 1_000
# Read the Contract ABI JSON file.
with open("static/demo_contract.json") as f:
js = f.read()
# Create a Contract object from the ABI description.
contract = Contract.from_json(js)
app_id = contract.networks[sp.gh].app_id
# Create an ATC object and an ATS object (with no defined sender)
atc = AtomicTransactionComposer()
ats = AccountTransactionSigner(None)
# Create two transactions, a Payment transacation and an Application Call.
ptxn = PaymentTxn(data['sender'], sp, data['sender'], 1)
aptxn = ApplicationCallTxn(data['sender'], sp, app_id, OnComplete.NoOpOC)
# Pair the transactions with the signer.
ptws = TransactionWithSigner(ptxn, ats)
aptws = TransactionWithSigner(aptxn, ats)
# Add a method call to the application transaction, including the payment
# transaction as a method argument.
atc.add_method_call(
app_id,
get_method(contract, "demo"),
data['sender'],
sp,
aptws,
method_args=[ptws]
)
# We need to return a group of transactions in a format that the frontend
# can interpret as a set of unsigned transactions to sign. We can use
# `atc.build_group()` for this process.
txgroup = []
for tx in atc.build_group():
txgroup.append({'txn': msgpack_encode(tx.txn)})
return {'success': True, 'data': txgroup}
# Ingest Signed Transactions and submit them to the node.
@app.route("/submit", methods=['POST'])
def submit():
stxns = []
for t in json.loads(request.data):
#print(t['txID'])
#print(t['blob'])
#stx = base64.b64decode(t['blob'])
stx = future_msgpack_decode(t['blob'])
stxns.append(stx)
algod_client.send_transactions(stxns)
return {'success': True, 'message': "Transactions received."}