def algod_connect(params_dict): if params_dict['purestake'] == True: # Configure address and token of the Purestake node algod_address = params_dict['address'] algod_token = params_dict['token'] purestake_token = {'X-Api-key': algod_token} # Initializes an algod client with purestake algod_client = algod.AlgodClient(algod_token, algod_address, headers=purestake_token) else: # Configure address and token of the node algod_address = params_dict['address'] algod_token = params_dict['token'] # Initializes an algod client algod_client = algod.AlgodClient(algod_token, algod_address) # Recover required values for all types of transactions params = algod_client.suggested_params() # Return a tuple with algod_client witch is needed for the connexion and the defaults transactions's params return (algod_client, params)
def send_note(): # Use sandbox or your address and token algod_address = "<your-algod-node-and-port>" algod_token = "<your-api-token>" algod_client = algod.AlgodClient(algod_token, algod_address) algod_address = "http://localhost:4001" algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_client = algod.AlgodClient(algod_token, algod_address) #passphrase = "<your-25-word-mnemonic>" passphrase = "price clap dilemma swim genius fame lucky crack torch hunt maid palace ladder unlock symptom rubber scale load acoustic drop oval cabbage review abstract embark" private_key = mnemonic.to_private_key(passphrase) my_address = mnemonic.to_public_key(passphrase) print("My address: {}".format(my_address)) params = algod_client.suggested_params() # comment out the next two (2) lines to use suggested fees # params.flat_fee = True # params.fee = 1000 note = '{"firstName":"JohnChris", "lastName":"Doe"}'.encode() # note = 'JohnChris'.encode() receiver = "GD64YIY3TWGDMCNPP553DZPPR6LDUSFQOIJVFDPPXWEG3FVOJCCDBBHU5A" unsigned_txn = PaymentTxn(my_address, params, receiver, 100000, None, note) # sign transaction signed_txn = unsigned_txn.sign(private_key) # wait for confirmation try: # send transaction txid = algod_client.send_transaction(signed_txn) print("Send transaction with txID: {}".format(txid)) confirmed_txn = wait_for_confirmation(algod_client, txid, 4) except Exception as err: print(err) return print( "txID: {}".format(txid), " confirmed in round: {}".format( confirmed_txn.get("confirmed-round", 0))) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=2))) print("Decoded note: {}".format( base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode())) person_dict = json.loads( base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode()) print("First Name = {}".format(person_dict['firstName']))
def connectToNode(algod_address, algod_token, headers={'User-Agent': '?'}): print("## START connection to node function ##\n") # create an algod client algod_client = algod.AlgodClient(algod_token, algod_address, headers) # check node status status = algod_client.status() print(json.dumps(status, indent=4)) # check suggested transansaction parameters try: params = algod_client.suggested_params() # print(json.dumps(params, indent=4)) # is not JSON serializable print('{\n "fee": ' + str(params.fee)) print(' "genesis-hash": ' + params.gh) print(' "genesis-id": ' + params.gen) print(' "last-round": ' + str(params.last)) print(' "min-fee": ' + str(params.min_fee) + '\n}') except Exception as e: print(e) print("# END connection to node function #\n") return algod_client
def connect(update, context): """ Connect to an algorand node :param update: :param context: :return: """ url = os.environ[ 'URL'] # getenv('URL') # Serve the endpoint to client node (https://purestake.com) algod_token = ALGODTOKEN # Your personal token (https://purestake.com) headers = {"X-API-Key": algod_token} try: return algod.AlgodClient(algod_token, url, headers) except Exception as e: update.message.reply_text( "Something went wrong.\nCould not connect to a node at this time.") # # 1321532644:AAGqn9oxTberzIY3TDgRnbMPNsrUfHgOUH8 # TOKEN=1153325972:AAGGR338rP148klz2-dhvXm_8wJJ8sC0QI4 # ALGODTOKEN=eVXi2wPlDE8uF15mkil5Z2FzRm20GTJg8r3R7ldv # DEFAULT2_ACCOUNT=HATMERJZOZ2U7Z2L7EKYHZHVNRFZOE75XN4PK5JVWVEL6M62EA4IWQZHJU # DEFAULT2_MNEMONTIC=vital ignore hen exact mirror cruel flee hint topic stairs check bomb milk hammer volume husband chronic wrap hub mass wool rather festival above imitate # URL=https://testnet-algorand.api.purestake.io/ps2
def connect_to_network(): # Specify your node address and token. This must be updated. # algod_address = "" # ADD ADDRESS # algod_token = "" # ADD TOKEN algod_address = "http://localhost:4001" algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_client = algod.AlgodClient(algod_token, algod_address) return algod_client
def send_note(): algod_address = "https://testnet-algorand.api.purestake.io/ps2" algod_token = "WgL4G2ZZf22GsqUIKHvCY9BSJyXQzZS8aTIpnMnp" headers = { "X-API-Key": algod_token, } algod_client = algod.AlgodClient(algod_token, algod_address, headers) # In addition to setting up the client and transaction # See GitHub for wait_for_confirmation() definition # get suggested parameters from Algod params = algod_client.suggested_params() gen = params.gen gh = params.gh first_valid_round = params.first last_valid_round = params.last fee = params.min_fee send_amount = 1 passphrase = "giraffe push drop glove cave cancel around roof talk example surprise atom foil outside anger right pistol stadium agent scheme patient script enrich able green" private_key = mnemonic.to_private_key(passphrase) my_address = mnemonic.to_public_key(passphrase) print("My address: {}".format(my_address)) params = algod_client.suggested_params() print(params) # comment out the next two (2) lines to use suggested fees params.flat_fee = True params.fee = 1000 note = 'd8fc8839456e636d5cd3cb7e8642ce5a4d2b3a53bc02690d2b2ea0b0639c57eb'.encode( ) #content should be the hash receiver = "GOXL7P62EJNZF6B2ISN3EHT3NX6NWD4HQ77ER7WJRQRO5YGHNGT3RGL5LA" unsigned_txn = PaymentTxn(my_address, params, receiver, 1000000, None, note) # sign transaction signed_txn = unsigned_txn.sign(private_key) # send transaction txid = algod_client.send_transaction(signed_txn) print("Send transaction with txID: {}".format(txid)) # wait for confirmation try: confirmed_txn = wait_for_confirmation(algod_client, txid, 4) except Exception as err: print(err) return print( "txID: {}".format(txid), " confirmed in round: {}".format( confirmed_txn.get("confirmed-round", 0))) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=2))) print("Decoded note: {}".format( base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode()))
def algod_client(): algod_address = os.environ.get("ALGOD_ADDRESS") algod_token = "" api_key = os.environ.get("API_KEY") headers = { "X-API-KEY": api_key, } alc = algod.AlgodClient(algod_token, algod_address, headers) return alc
def main() : # initialize an algodClient algod_client = algod.AlgodClient(algod_token, algod_address) # define private keys creator_private_key = get_private_key_from_mnemonic(creator_mnemonic) user_private_key = get_private_key_from_mnemonic(user_mnemonic) # compile programs approval_program = compile_program(algod_client, approval_program_source_initial) clear_program = compile_program(algod_client, clear_program_source) # create new application app_id = create_app(algod_client, creator_private_key, approval_program, clear_program, global_schema, local_schema) # opt-in to application opt_in_app(algod_client, user_private_key, app_id) # call application without arguments call_app(algod_client, user_private_key, app_id, None) # read local state of application from user account read_local_state(algod_client, account.address_from_private_key(user_private_key), app_id) # read global state of application read_global_state(algod_client, account.address_from_private_key(creator_private_key), app_id) # update application approval_program = compile_program(algod_client, approval_program_source_refactored) update_app(algod_client, creator_private_key, app_id, approval_program, clear_program) # call application with arguments now = datetime.datetime.now().strftime("%H:%M:%S") app_args = [now.encode("utf-8")] call_app(algod_client, user_private_key, app_id, app_args) # read local state of application from user account read_local_state(algod_client, account.address_from_private_key(user_private_key), app_id) # close-out from application close_out_app(algod_client, user_private_key, app_id) # opt-in again to application opt_in_app(algod_client, user_private_key, app_id) # call application with arguments call_app(algod_client, user_private_key, app_id, app_args) # read local state of application from user account read_local_state(algod_client, account.address_from_private_key(user_private_key), app_id) # delete application delete_app(algod_client, creator_private_key, app_id) # clear application from user account clear_app(algod_client, user_private_key, app_id)
def algorandSequence(): algod_address = "https://testnet-algorand.api.purestake.io/ps2" algod_token = "" headers = { "X-API-Key": "zLAOcinLq31BhPezSnHQL3NF7qBwHtku6XwN8igq", } algod_client = algod.AlgodClient(algod_token, algod_address, headers) status = algod_client.status() print(json.dumps(status, indent=4)) passphrase = "thunder fun scout myself talk repeat hurry miracle puppy run vocal vicious shove fever idea lens above diesel action pulp before cigar horror above mass" private_key = mnemonic.to_private_key(passphrase) my_address = mnemonic.to_public_key(passphrase) print("My address: {}".format(my_address)) account_info = algod_client.account_info(my_address) print("Account balance: {} microAlgos".format(account_info.get('amount'))) params = algod_client.suggested_params() note = "Hello World".encode() receiver = "GD64YIY3TWGDMCNPP553DZPPR6LDUSFQOIJVFDPPXWEG3FVOJCCDBBHU5A" data = { "sender": my_address, "receiver": receiver, "fee": params.get('minFee'), "flat_fee": True, "amt": 20, "first": params.get('lastRound'), "last": params.get('lastRound') + 1000, "note": note, "gen": params.get('genesisID'), "gh": params.get('genesishashb64') } txn = transaction.PaymentTxn(**data) signed_txn = txn.sign(private_key) txid = signed_txn.transaction.get_txid() print("Signed transaction with txID: {}".format(txid)) algod_client.send_transaction( signed_txn, headers={'content-type': 'application/x-binary'}) wait_for_confirmation(algod_client, txid) try: confirmed_txn = algod_client.transaction_info(my_address, txid) except Exception as err: print(err) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4))) print("Decoded note: {}".format( base64.b64decode(confirmed_txn.get('noteb64')).decode()))
def connect(): """ Connect to an algorand node :return: """ url = os.getenv('URL') headers = {"X-API-Key": ALGODTOKEN} try: return algod.AlgodClient(ALGODTOKEN, url, headers) except Exception as e: return e
def do_txn(args: Dict[str, Any], default_account_name: str): """Build and send transaction""" client = algod.AlgodClient( "", "https://testnet.algoexplorerapi.io", headers={'User-Agent': 'DanM'}) pub_key = extract_matching_pub_key(default_account_name, [line.strip( "[]\n") for line in open(credentials_file_path).readlines()]) passphrase = extract_matching_passphrase(default_account_name, [line.strip( "[]\n") for line in open(credentials_file_path).readlines()]) txn = Transaction(client, algoetf_addr, pub_key, creator_passphrase, int(args.buy[0])) print(txn.buy())
def connect(update, context): """ Connect to an algorand node :param update: :param context: :return: """ url = os.environ['URL'] # getenv('URL') # Serve the endpoint to client node (https://purestake.com) algod_token = ALGODTOKEN # Your personal token (https://purestake.com) headers = {"X-API-Key": algod_token} try: return algod.AlgodClient(algod_token, url, headers) except Exception as e: return e
def connect(): # Here I use a third party API service to connect to the algod client # since I don't enough resources to run a full node. # Algorand has provided more information on how you can connect # to the client even if you cannot run a node and still have # access to a lot of features just as if you're running a node. # https://developer.algorand.org algod_url = url # algod_auth = os.environ.get('ALGODTOKEN') headers = {"X-API-Key": algod_token} try: return algod.AlgodClient(algod_token, algod_url, headers) except Exception as e: print(e)
def share_file(files): # Dodawanie pliku do ipfs-a print("Dodawanie pliku do IPFS-a.") url = f"{Config.ipfs_api_address}/api/v0/add" params = (('wrap-with-directory', True), ) response = requests.post(url, files=files, params=params) if response.status_code != 200: print(response.text) raise Exception(f"Invalid status code: '{response.status_code}'.") result = response.text.splitlines() cid = json.loads(result[1]).get('Hash') print("Plik dodano do IPFS-a.") # Dodawanie informacji do blockchain-a Algorand print("Dodawanie informacji do blockchain-a Algorand.") algod_token = Config.algod_token algod_address = Config.algod_api_address purestake_token = {'X-Api-key': algod_token} algod_client = algod.AlgodClient(algod_token, algod_address, headers=purestake_token) # ustawienie parametrów transakcji params = algod_client.suggested_params() gh = params.gh first_valid_round = params.first last_valid_round = params.last fee = params.min_fee send_amount = 0 note = f"{{'cid': {cid}}}".encode() sender = Config.algod_public_key receiver = Config.algod_public_key # utworzenie i zatwierdzenie transakcji tx = transaction.PaymentTxn(sender, fee, first_valid_round, last_valid_round, gh, receiver, send_amount, note=note, flat_fee=True) signed_tx = tx.sign(Config.algod_private_key) tx_id = algod_client.send_transaction(signed_tx) # wysłanie transakcji print(f"Poprawnie zlecono transakcję o ID {tx_id}") wait_for_confirmation( algod_client, tx_id=signed_tx.transaction.get_txid()) # oczekiwanie na potwierdzenie return cid
def ALGOtransaction(send_to_address, amount, TransactionNote): # setup http client w/guest key provided by purestake ip_address = "https://testnet-algorand.api.purestake.io/ps2" token = "YOUR TOKEN" headers = { "X-API-Key": token, } mnemonic1 = "your mnemonic" account_private_key = mnemonic.to_private_key(mnemonic1) account_public_key = 'YOUR PUPLIC KEY' algodclient = algod.AlgodClient(token, ip_address, headers) # get suggested parameters from algod params = algodclient.suggested_params() gh = params.gh first_valid_round = params.first last_valid_round = params.last fee = params.min_fee send_amount = amount existing_account = account_public_key # create and sign transaction tx = transaction.PaymentTxn(existing_account, fee, first_valid_round, last_valid_round, gh, send_to_address, send_amount, flat_fee=True, note=TransactionNote.encode()) signed_tx = tx.sign(account_private_key) try: tx_confirm = algodclient.send_transaction(signed_tx) print('transaction sent with id', signed_tx.transaction.get_txid()) wait_for_confirmation(algodclient, txid=signed_tx.transaction.get_txid()) return constants.TRANSACTION_GOOD except Exception as e: print(e) return constants.TRANSACTION_BAD
def connect_to_algo(connection_type=''): #Connect to Algorand node maintained by PureStake algod_token = "B3SU4KcVKi94Jap2VXkK83xx38bsv95K5UZm2lab" headers = {"X-API-Key": algod_token} if connection_type == "indexer": # TODO: return an instance of the v2client indexer. This is used for checking payments for tx_id's algod_address = "https://testnet-algorand.api.purestake.io/idx2" ind = indexer.IndexerClient(indexer_token=algod_token, indexer_address=algod_address) return ind else: # TODO: return an instance of the client for sending transactions # Tutorial Link: https://developer.algorand.org/tutorials/creating-python-transaction-purestake-api/ algod_address = "https://testnet-algorand.api.purestake.io/ps2" acl = algod.AlgodClient(algod_token, algod_address, headers) return acl return None
def __init__(self): self.algod_address = "https://testnet-algorand.api.purestake.io/ps2" self.algod_token = "zLAOcinLq31BhPezSnHQL3NF7qBwHtku6XwN8igq" headers = { "X-Api-key": self.algod_token, # "X-Algo-API-Token": "asdf" } passphrase = "wedding shine wash pet apple force car taxi illegal scrap walnut virtual champion display glimpse barrel pioneer chat finish twenty increase hope patrol about stage" self.private_key = mnemonic.to_private_key(passphrase) self.my_address = mnemonic.to_public_key(passphrase) print("My address: {}".format(self.my_address)) self.algod_client = algod.AlgodClient(self.algod_token, self.algod_address, headers) self.status = self.algod_client.status() # print(json.dumps(self.status, indent=4)) self.account_info = self.algod_client.account_info(self.my_address) print("Account balance: {} microAlgos".format(self.account_info.get('amount')))
def getting_started_example(): algod_address = "http://localhost:4001" algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_client = algod.AlgodClient(algod_token, algod_address) passphrase = "price clap dilemma swim genius fame lucky crack torch hunt maid palace ladder unlock symptom rubber scale load acoustic drop oval cabbage review abstract embark" # generate a public/private key pair private_key = mnemonic.to_private_key(passphrase) my_address = mnemonic.to_public_key(passphrase) print("My address: {}".format(my_address)) account_info = algod_client.account_info(my_address) print("Account balance: {} microAlgos".format(account_info.get('amount'))) # build transaction params = algod_client.suggested_params() # comment out the next two (2) lines to use suggested fees params.flat_fee = True params.fee = 1000 receiver = "GD64YIY3TWGDMCNPP553DZPPR6LDUSFQOIJVFDPPXWEG3FVOJCCDBBHU5A" note = "Hello World".encode() unsigned_txn = PaymentTxn(my_address, params, receiver, 1000000, None, note) # sign transaction signed_txn = unsigned_txn.sign(mnemonic.to_private_key(passphrase)) txid = algod_client.send_transaction(signed_txn) print("Signed transaction with txID: {}".format(txid)) # wait for confirmation try: confirmed_txn = wait_for_confirmation(algod_client, txid, 4) except Exception as err: print(err) return print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4))) print("Decoded note: {}".format( base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode()))
def send_note(): algod_address = "http://localhost:4001" algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_client = algod.AlgodClient(algod_token, algod_address) passphrase = "" private_key = mnemonic.to_private_key(passphrase) my_address = mnemonic.to_public_key(passphrase) print(f'My address: {my_address}') params = algod_client.suggested_params() # comment out the next two (2) lines to use suggested fees params.flat_fee = True params.fee = 1000 json_note = parse_into_json() note = json_note.encode() receiver = "" unsigned_txn = PaymentTxn(my_address, params, receiver, 100000, None, note) # sign transaction signed_txn = unsigned_txn.sign(private_key) # sign transaction signed_txn = unsigned_txn.sign(private_key) # send transaction txid = algod_client.send_transaction(signed_txn) print("Send transaction with txID: {}".format(txid)) # wait for confirmation try: confirmed_txn = wait_for_confirmation(algod_client, txid, 4) except Exception as err: print(err) return print( "txID: {}".format(txid), "confirmed in round: {}".format( confirmed_txn.get("confirmed-round", 0))) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=2))) print("Decoded note: {}".format( base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode()))
def __init__(self, config): self.config = config with open(tealpath(config['contracts']['listing']), mode='r') as f: self.template_bytes = f.read() url = "{}:{}".format(config['algod']['server'], config['algod']['port']) if config['algod']['port'] == 0: url = config['algod']['server'] self.client = algod.AlgodClient(config['algod']['token'], url, headers={'User-Agent': 'DoYouLoveMe?'}) result = self.client.compile(self.populate_tmpl_vars()) self.assembled_bytes = base64.b64decode(result["result"]) self.set_start_positions()
def getting_started_example(): algod_address = "http://localhost:4001" algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_client = algod.AlgodClient(algod_token, algod_address) passphrase = "Your 25-word mnemonic generated and displayed above" # generate a public/private key pair private_key = mnemonic.to_private_key(passphrase) my_address = mnemonic.to_public_key(passphrase) print("My address: {}".format(my_address)) account_info = algod_client.account_info(my_address) print("Account balance: {} microAlgos".format(account_info.get('amount'))) # build transaction params = algod_client.suggested_params() # comment out the next two (2) lines to use suggested fees params.flat_fee = True params.fee = 1000 receiver = "GD64YIY3TWGDMCNPP553DZPPR6LDUSFQOIJVFDPPXWEG3FVOJCCDBBHU5A" note = "Hello World".encode() unsigned_txn = PaymentTxn(my_address, params, receiver, 1000000, None, note) # sign transaction signed_txn = unsigned_txn.sign(mnemonic.to_private_key(passphrase)) txid = algod_client.send_transaction(signed_txn) print("Signed transaction with txID: {}".format(txid)) # wait for confirmation wait_for_confirmation(algod_client, txid) # read transction try: confirmed_txn = algod_client.pending_transaction_info(txid) except Exception as err: print(err) print("Transaction information: {}".format(json.dumps(confirmed_txn, indent=4))) print("Decoded note: {}".format(base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode()))
def connectToNode(algod_address, algod_token, verbose=False): # create an algod client algod_client = algod.AlgodClient(algod_token, algod_address) # check node status status = algod_client.status() if (verbose): print(json.dumps(status, indent=4)) # check suggested transansaction parameters try: params = algod_client.suggested_params() if (verbose): # print(json.dumps(params, indent=4)) # is not JSON serializable print('{\n "fee": ' + str(params.fee)) print(' "genesis-hash": ' + params.gh) print(' "genesis-id": ' + params.gen) print(' "last-round": ' + str(params.last)) print(' "min-fee": ' + str(params.min_fee) + '\n}') except Exception as e: print(e) return algod_client
def create_account(fund=True): # 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) #Generate new account for this transaction secret_key, my_address = account.generate_account() m = mnemonic.from_private_key(secret_key) print("My address: {}".format(my_address)) # Check your balance. It should be 0 microAlgos account_info = algod_client.account_info(my_address) print("Account balance: {} microAlgos".format(account_info.get('amount')) + "\n") if fund: #Fund the created account print( 'Go to the below link to fund the created account using testnet faucet: \n https://dispenser.testnet.aws.algodev.network/?account={}' .format(my_address)) completed = "" while completed.lower() != 'yes': completed = input("Type 'yes' once you funded the account: ") print('Fund transfer in process...') # Wait for the faucet to transfer funds time.sleep(5) print('Fund transferred!') # Check your balance. It should be 5000000 microAlgos account_info = algod_client.account_info(my_address) print("Account balance: {} microAlgos".format( account_info.get('amount')) + "\n") return m
return txinfo # Setup HTTP client w/guest key provided by PureStake algod_address = 'https://testnet-algorand.api.purestake.io/ps2' algod_token = "" headers = { "X-API-Key": "B3SU4KcVKi94Jap2VXkK83xx38bsv95K5UZm2lab", } # Initalize throw-away account for this example - check that is has funds before running script mnemonic_phrase = 'code thrive mouse code badge example pride stereo sell viable adjust planet text close erupt embrace nature upon february weekend humble surprise shrug absorb faint' account_private_key = mnemonic.to_private_key(mnemonic_phrase) account_public_key = mnemonic.to_public_key(mnemonic_phrase) algodclient = algod.AlgodClient(algod_token, algod_address, headers) # get suggested parameters from Algod params = algodclient.suggested_params() gh = params.gh first_valid_round = params.first last_valid_round = params.last fee = params.min_fee send_amount = 10 existing_account = account_public_key send_to_address = 'AEC4WDHXCDF4B5LBNXXRTB3IJTVJSWUZ4VJ4THPU2QGRJGTA3MIDFN3CQA' # Create and sign transaction tx = transaction.PaymentTxn(existing_account,
from algosdk import * from algosdk.v2client import algod from algosdk.v2client.models import DryrunSource, DryrunRequest from algosdk.future.transaction import * from sandbox import get_accounts import base64 import os # token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # url = "http://localhost:4001" token = "ef920e2e7e002953f4b29a8af720efe8e4ecc75ff102b165e0472834b25832c1" url = "http://hackathon.algodev.network:9100" client = algod.AlgodClient(token, url) def demo(): # Create acct addr, pk = get_accounts("Testnet")[0] print("Using {}".format(addr)) # Create app # app_id = 43005850 app_id = create_app(addr, pk) print("Created App with id: {}".format(app_id)) # new AVM call to get Application address app_addr = logic.get_application_address(app_id) print("Application Address: {}".format(app_addr)) sp = client.suggested_params() tx_group = assign_group_id([ get_fund_txn(addr, sp, app_addr, 500000),
import os from flask import Flask, request, jsonify from algosdk.v2client import algod from algosdk import encoding, error from mugo_algorand.wallet import * from mugo_algorand.transaction import * from mugo_algorand.contract import compile_smart_contract from mugo_algorand.util import read_local_state, read_global_state app = Flask(__name__) algod_client = algod.AlgodClient( algod_token='', algod_address='https://api.testnet.algoexplorer.io', headers={ 'User-Agent': 'DoYouLoveMe?' }) ESCROW_MNEMONIC = os.getenv('ESCROW_MNEMONIC', '') @app.route('/create-wallet', methods=['PUT']) def create_wallet_endpoint(): passphrase = create_wallet() return jsonify(mnemonic=passphrase), 201 @app.route('/get-public-address/<string:passphrase>', methods=['GET']) def get_public_address_endpoint(passphrase): wallet = get_wallet_key_pairs(passphrase) return jsonify(address=wallet['public_key']), 200 @app.route('/check-wallet-balance', methods=['POST']) def check_wallet_balance_endpoint():
print("Waiting for confirmation") last_round += 1 client.status_after_block(last_round) txinfo = client.pending_transaction_info(txid) print("Transaction {} confirmed in round {}.".format( txid, txinfo.get('confirmed-round'))) return txinfo try: # Create an algod client algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_address = "http://localhost:4001" receiver = "<receiver_address>" algod_client = algod.AlgodClient(algod_token, algod_address) myprogram = "samplearg.teal" # Read TEAL program data = open(myprogram, 'r').read() # Compile TEAL program # // This code is meant for learning purposes only # // It should not be used in production # // samplearg.teal # arg_0 # btoi # int 123 # == # // bto1
def connectToNetwork(self): # establish connection return algod.AlgodClient(self.algod_token, self.algod_address, self.headers)
def create_non_fungible_token(): # 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) # 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 dir_path = os.path.dirname(os.path.realpath(__file__)) f = open(dir_path + '/aliceNFTmetadata.json', "r") # Reading from file metadataJSON = json.loads(f.read()) metadataStr = json.dumps(metadataJSON) hash = hashlib.new("sha512_256") hash.update(b"arc0003/amj") hash.update(metadataStr.encode("utf-8")) json_metadata_hash = hash.digest() # Account 1 creates an asset called latinum 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="ALICE001", asset_name="Alice's Artwork 001", manager=accounts[1]['pk'], reserve=None, freeze=None, clawback=None, strict_empty_address_check=False, url="https://path/to/my/asset/details", 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 confirmed_txn = wait_for_confirmation(algod_client, txid, 4) print("TXID: ", txid) print("Result confirmed in round: {}".format( confirmed_txn['confirmed-round'])) 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) except Exception as e: print(e) 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 confirmed_txn = wait_for_confirmation(algod_client, txid, 4) print("TXID: ", txid) print("Result confirmed in round: {}".format( confirmed_txn['confirmed-round'])) # 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(algod_client, accounts[1])
def getting_started_example(): algod_address = "http://localhost:4001" algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_client = algod.AlgodClient(algod_token, algod_address) # Part 1 # rekey from Account 3 to allow to sign from Account 1 # Part 2 # send from account 3 to account 2 and sign from Account 1 # demo notes: delete 3 accounts and change these passphrases # never use mnemonics in production code, replace for demo purposes only account1_passphrase = "install blossom apart critic exhibit rather author ability arrest mango segment salute damage deer release obey help whip illness fever best relief voyage absent asset" account2_passphrase = "butter private lunar heavy explain panic melt dog want athlete animal stay bless spoon switch language check know zone return parade blossom apple ability injury" account3_passphrase = "cup major panther cycle merit fox over cram tower trumpet road option flee evoke plate one aspect napkin wife banana poet august kitchen absorb local" account1 = mnemonic.to_public_key(account1_passphrase) account2 = mnemonic.to_public_key(account2_passphrase) account3 = mnemonic.to_public_key(account3_passphrase) print("Account 1 : {}".format(account1)) print("Account 2 : {}".format(account2)) print("Account 3 : {}".format(account3)) # Part 1 # build transaction params = algod_client.suggested_params() # comment out the next two (2) lines to use suggested fees # params.flat_fee = True # params.fee = 1000 # opt-in send tx to same address as sender and use 0 for amount w rekey account # to account 1 amount = int(0) rekeyaccount = account1 sender = account3 receiver = account3 unsigned_txn = PaymentTxn(sender, params, receiver, amount, None, None, None, rekeyaccount) # sign transaction with account 3 signed_txn = unsigned_txn.sign( mnemonic.to_private_key(account3_passphrase)) txid = algod_client.send_transaction(signed_txn) print("Signed transaction with txID: {}".format(txid)) # wait for confirmation confirmed_txn = wait_for_confirmation(algod_client, txid, 4) print("TXID: ", txid) print("Result confirmed in round: {}".format( confirmed_txn['confirmed-round'])) # read transction try: confirmed_txn = algod_client.pending_transaction_info(txid) account_info = algod_client.account_info(account3) except Exception as err: print(err) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4))) print("Account 3 information : {}".format( json.dumps(account_info, indent=4))) # Part 2 # send payment from account 3 # to acct 2 and signed by account 1 account1 = mnemonic.to_public_key(account1_passphrase) private_key_account1 = mnemonic.to_private_key(account1_passphrase) account2 = mnemonic.to_public_key(account2_passphrase) account3 = mnemonic.to_public_key(account3_passphrase) amount = int(1000000) receiver = account2 unsigned_txn = PaymentTxn(account3, params, receiver, amount, None, None, None, account1) # sign transaction signed_txn = unsigned_txn.sign( mnemonic.to_private_key(account1_passphrase)) txid = algod_client.send_transaction(signed_txn) print("Signed transaction with txID: {}".format(txid)) # wait for confirmation confirmed_txn = wait_for_confirmation(algod_client, txid, 4) print("TXID: ", txid) print("Result confirmed in round: {}".format( confirmed_txn['confirmed-round'])) account_info_rekey = algod_client.account_info(account3) print("Account 3 information (from) : {}".format( json.dumps(account_info_rekey, indent=4))) account_info_rekey = algod_client.account_info(account2) print("Account 2 information (to) : {}".format( json.dumps(account_info_rekey, indent=4)))