-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
246 lines (217 loc) · 8.63 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
240
241
242
243
244
245
246
import json
import hashlib
import csv
from algosdk import mnemonic
from algosdk.v2client import algod
from algosdk.future.transaction import AssetConfigTxn
from createAccount import create_account
from closeoutAccount import closeout_account
from qr import gen_qr
import pdb
def create_non_fungible_token(_asset_name, _url, _destroy_asset = False, _append_file = True, _generate_qr = True):
"""
hash = hashlib.new("sha512_256")
hash.update(b"arc0003/amj")
hash.update(metadataStr.encode("utf-8"))
json_metadata_hash = hash.digest()
"""
if _generate_qr:
# Generate QR
print('Generating QR')
qr_fname = str(_asset_name) + 'NFT'
gen_qr(qr_fname, _url, qr_fname)
# For ease of reference, add account public and private keys to
# an accounts dict.
print("--------------------------------------------")
print("Creating account...")
accounts = {}
m = create_account()
accounts[1] = {}
accounts[1]['pk'] = mnemonic.to_public_key(m)
accounts[1]['sk'] = mnemonic.to_private_key(m)
# Using Rand Labs Developer API
# see https://github.com/algorand/py-algorand-sdk/issues/169
# Change algod_token and algod_address to connect to a different client
algod_token = "2f3203f21e738a1de6110eba6984f9d03e5a95d7a577b34616854064cf2c0e7b"
algod_address = "https://academy-algod.dev.aws.algodev.network/"
algod_client = algod.AlgodClient(algod_token, algod_address)
print("--------------------------------------------")
print("Creating Asset...")
# CREATE ASSET
# Get network params for transactions before every transaction.
params = algod_client.suggested_params()
# comment these two lines if you want to use suggested params
# params.fee = 1000
# params.flat_fee = True
# JSON file
#f = open ('quantletNFTmetadata.json', "r")
metadataJSON = {
"name": "bb",
"description": "bb",
"image": qr_fname,
"image_integrity": "sha256-/tih/7ew0eziEZIVD4qoTWb0YrElAuRG3b40SnEstyk=",
"properties": {
"simple_property": "bb",
"rich_property": {
"name": "bb",
"value": "001",
"display_value": "001",
"class": "emphasis",
"css": {
"color": "#ffffff",
"font-weight": "bold",
"text-decoration": "underline"
}
},
"array_property": {
"name": "bb",
"value": [1, 2, 3, 4],
"class": "emphasis"
}
}
}
# Reading from file
#metadataJSON = json.loads(f.read())
metadataStr = json.dumps(metadataJSON)
m = hashlib.sha256()
m.update(b"arc0003/amj")
m.update(metadataStr.encode("utf-8"))
json_metadata_hash = m.digest()
# Account 1 creates an asset called and
# sets Account 1 as the manager, reserve, freeze, and clawback address.
# Asset Creation transaction
txn = AssetConfigTxn(
sender=accounts[1]['pk'],
sp=params,
total=1,
default_frozen=False,
unit_name="q1",
asset_name=_asset_name,
manager=accounts[1]['pk'],
reserve=None,
freeze=None,
clawback=None,
strict_empty_address_check=False,
url=_url,
metadata_hash=json_metadata_hash,
decimals=0)
# Sign with secret key of creator
stxn = txn.sign(accounts[1]['sk'])
# Send the transaction to the network and retrieve the txid.
txid = algod_client.send_transaction(stxn)
print("Asset Creation Transaction ID: {}".format(txid))
# Wait for the transaction to be confirmed
wait_for_confirmation(algod_client,txid,4)
try:
# Pull account info for the creator
# account_info = algod_client.account_info(accounts[1]['pk'])
# get asset_id from tx
# Get the new asset's information from the creator account
ptx = algod_client.pending_transaction_info(txid)
asset_id = ptx["asset-index"]
print_created_asset(algod_client, accounts[1]['pk'], asset_id)
print_asset_holding(algod_client, accounts[1]['pk'], asset_id)
# Inspect
asset_link = 'https://testnet.algoexplorer.io/asset/' + str(asset_id)
print('NFT available under: ', asset_link)
except Exception as e:
print(e)
if _destroy_asset:
print("--------------------------------------------")
print("You have successfully created your own Non-fungible token! For the purpose of the demo, we will now delete the asset.")
print("Deleting Asset...")
# Asset destroy transaction
txn = AssetConfigTxn(
sender=accounts[1]['pk'],
sp=params,
index=asset_id,
strict_empty_address_check=False
)
# Sign with secret key of creator
stxn = txn.sign(accounts[1]['sk'])
# Send the transaction to the network and retrieve the txid.
txid = algod_client.send_transaction(stxn)
print("Asset Destroy Transaction ID: {}".format(txid))
# Wait for the transaction to be confirmed
wait_for_confirmation(algod_client, txid, 4)
# Asset was deleted.
try:
print_asset_holding(algod_client, accounts[1]['pk'], asset_id)
print_created_asset(algod_client, accounts[1]['pk'], asset_id)
print("Asset is deleted.")
except Exception as e:
print(e)
print("--------------------------------------------")
print("Sending closeout transaction back to the testnet dispenser...")
closeout_account(accounts[1]["pk"], accounts[1]["sk"], algod_client)
if _append_file:
print('Appending Asset Link to File')
fields=[_asset_name, _url, asset_link]
with open(r'assets.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(fields)
# utility for waiting on a transaction confirmation
def wait_for_confirmation(client, transaction_id, timeout):
"""
Wait until the transaction is confirmed or rejected, or until 'timeout'
number of rounds have passed.
Args:
transaction_id (str): the transaction to wait for
timeout (int): maximum number of rounds to wait
Returns:
dict: pending transaction information, or throws an error if the transaction
is not confirmed or rejected in the next timeout rounds
"""
start_round = client.status()["last-round"] + 1;
current_round = start_round
while current_round < start_round + timeout:
try:
pending_txn = client.pending_transaction_info(transaction_id)
except Exception:
return
if pending_txn.get("confirmed-round", 0) > 0:
return pending_txn
elif pending_txn["pool-error"]:
raise Exception(
'pool error: {}'.format(pending_txn["pool-error"]))
client.status_after_block(current_round)
current_round += 1
raise Exception(
'pending tx not found in timeout rounds, timeout value = : {}'.format(timeout))
# Utility function used to print created asset for account and assetid
def print_created_asset(algodclient, account, assetid):
# note: if you have an indexer instance available it is easier to just use this
# response = myindexer.accounts(asset_id = assetid)
# then use 'account_info['created-assets'][0] to get info on the created asset
account_info = algodclient.account_info(account)
idx = 0;
for my_account_info in account_info['created-assets']:
scrutinized_asset = account_info['created-assets'][idx]
idx = idx + 1
if (scrutinized_asset['index'] == assetid):
print("Asset ID: {}".format(scrutinized_asset['index']))
print(json.dumps(my_account_info['params'], indent=4))
break
# Utility function used to print asset holding for account and assetid
def print_asset_holding(algodclient, account, assetid):
# note: if you have an indexer instance available it is easier to just use this
# response = myindexer.accounts(asset_id = assetid)
# then loop thru the accounts returned and match the account you are looking for
account_info = algodclient.account_info(account)
idx = 0
for my_account_info in account_info['assets']:
scrutinized_asset = account_info['assets'][idx]
idx = idx + 1
if (scrutinized_asset['asset-id'] == assetid):
print("Asset ID: {}".format(scrutinized_asset['asset-id']))
print(json.dumps(scrutinized_asset, indent=4))
break
if __name__ == '__main__':
qlets = {
'SDA_2021_St_Gallen': 'https://github.com/QuantLet/SDA_2021_St_Gallen',
'FRM_Crypto': 'https://github.com/QuantLet/FRM_Crypto',
'Hedging-Effectiveness-Plots': 'https://github.com/QuantLet/Hedging-Effectiveness-Plots'
}
for asset, url in qlets.items():
pdb.set_trace()
create_non_fungible_token(asset, url)