def write_multisig_signed_transaction_to_file(): algod_client = connect_to_network() # Change these values with mnemonics # mnemonic1 = "PASTE phrase for account 1" # mnemonic2 = "PASTE phrase for account 2" # mnemonic3 = "PASTE phrase for account 3" mnemonic1 = "patrol target joy dial ethics flip usual fatigue bulb security prosper brand coast arch casino burger inch cricket scissors shoe evolve eternal calm absorb school" mnemonic2 = "genius inside turtle lock alone blame parent civil depend dinosaur tag fiction fun skill chief use damp daughter expose pioneer today weasel box about silly" mnemonic3 = "off canyon mystery cable pluck emotion manual legal journey grit lunch include friend social monkey approve lava steel school mango auto cactus huge ability basket" # For ease of reference, add account public and private keys to # an accounts dict. private_key_1 = mnemonic.to_private_key(mnemonic1) account_1 = mnemonic.to_public_key(mnemonic1) private_key_2 = mnemonic.to_private_key(mnemonic2) account_2 = mnemonic.to_public_key(mnemonic2) private_key_3 = mnemonic.to_private_key(mnemonic3) account_3 = mnemonic.to_public_key(mnemonic3) # create a multisig account version = 1 # multisig version threshold = 2 # how many signatures are necessary msig = Multisig(version, threshold, [account_1, account_2]) print("Multisig Address: ", msig.address()) print( "Please go to: https://bank.testnet.algorand.network/ to fund multisig account.", msig.address()) # input("Please go to: https://bank.testnet.algorand.network/ to fund multisig account." + '\n' + "Press Enter to continue...") # get suggested parameters params = algod_client.suggested_params() # comment out the next two (2) lines to use suggested fees # params.flat_fee = True # params.fee = 1000 # create a transaction sender = msig.address() recipient = account_3 amount = 10000 note = "Hello Multisig".encode() txn = PaymentTxn(sender, params, recipient, amount, None, note, None) # create a SignedTransaction object mtx = MultisigTransaction(txn, msig) # sign the transaction mtx.sign(private_key_1) mtx.sign(private_key_2) # print encoded transaction print(encoding.msgpack_encode(mtx)) # write to file dir_path = os.path.dirname(os.path.realpath(__file__)) transaction.write_to_file([mtx], dir_path + "/signed.mtx") print("Signed mtx file saved!")
def group_transactions() : # recover a account passphrase1 = <25-word-passphrase> pk_account_a = mnemonic.to_private_key(passphrase1) account_a = account.address_from_private_key(pk_account_a) # recover b account passphrase2 = <25-word-passphrase> pk_account_b = mnemonic.to_private_key(passphrase2) account_b = account.address_from_private_key(pk_account_b) # recover c account passphrase3 = <25-word-passphrase> pk_account_c = mnemonic.to_private_key(passphrase3) account_c = account.address_from_private_key(pk_account_c) # connect to node acl = connect_to_network() # get suggested parameters params = acl.suggested_params() gen = params["genesisID"] gh = params["genesishashb64"] last_round = params["lastRound"] fee = params["fee"] amount = 1000 # create transaction1 txn1 = transaction.PaymentTxn(account_a, fee, last_round, last_round+100, gh, account_c, amount) # create transaction2 txn2 = transaction.PaymentTxn(account_b, fee, last_round, last_round+100, gh, account_a, amount) # get group id and assign it to transactions gid = transaction.calculate_group_id([txn1, txn2]) txn1.group = gid txn2.group = gid # sign transaction1 stxn1 = txn1.sign(pk_account_a) # sign transaction2 stxn2 = txn2.sign(pk_account_b) signedGroup = [] signedGroup.append(stxn1) signedGroup.append(stxn2) # send them over network sent = acl.send_transactions(signedGroup) # print txid print(sent) # wait for confirmation wait_for_confirmation( acl, sent)
def transferDocument(algod_client, loc_id, bol_id, seller_pk, buyer_mnemonic, carrier_mnemonic): buyer_sk = mnemonic.to_private_key(buyer_mnemonic) buyer_pk = mnemonic.to_public_key(buyer_mnemonic) carrier_sk = mnemonic.to_private_key(carrier_mnemonic) carrier_sk = mnemonic.to_pubic_key(carrier_mnemonic) txn1 = singleTransfer(buyer_pk, seller_pk, loc_id) #some params txn2 = singleTransfer(carrier_sk, buyer_pk, bol_id) #some params atomicTransfer(algod_client, txn1, txn2, buyer_sk, carrier_sk) #some params return None
def read_multisig_unsigned_transaction_from_file(): algod_client = connect_to_network() # Change these values with mnemonics # mnemonic1 = "PASTE phrase for account 1" # mnemonic2 = "PASTE phrase for account 2" # mnemonic3 = "PASTE phrase for account 3" mnemonic1 = "patrol target joy dial ethics flip usual fatigue bulb security prosper brand coast arch casino burger inch cricket scissors shoe evolve eternal calm absorb school" mnemonic2 = "genius inside turtle lock alone blame parent civil depend dinosaur tag fiction fun skill chief use damp daughter expose pioneer today weasel box about silly" mnemonic3 = "off canyon mystery cable pluck emotion manual legal journey grit lunch include friend social monkey approve lava steel school mango auto cactus huge ability basket" # For ease of reference, add account public and private keys to # an accounts dict. private_key_1 = mnemonic.to_private_key(mnemonic1) account_1 = mnemonic.to_public_key(mnemonic1) private_key_2 = mnemonic.to_private_key(mnemonic2) account_2 = mnemonic.to_public_key(mnemonic2) private_key_3 = mnemonic.to_private_key(mnemonic3) account_3 = mnemonic.to_public_key(mnemonic3) print("Account 1 address: {}".format(account_1)) print("Account 2 address: {}".format(account_2)) print("Account 3 address: {}".format(account_3)) # read from file dir_path = os.path.dirname(os.path.realpath(__file__)) msigs = transaction.retrieve_from_file(dir_path + "/unsigned.mtx") mtx = msigs[0] # sign the transaction mtx.sign(private_key_1) mtx.sign(private_key_2) # send the transaction txid = algod_client.send_raw_transaction(encoding.msgpack_encode(mtx)) # wait for confirmation try: confirmed_txn = wait_for_confirmation(algod_client, txid, 4) print("TXID: ", txid) print("Result confirmed in round: {}".format( confirmed_txn['confirmed-round'])) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4))) print("Decoded note: {}".format( base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode())) except Exception as err: print(err)
def claim_interest(programstr, escrow_id, passphrase, amt, coupon, payment_id, interest_id, par_id, first_block, last_block, algod_client: algod_client()): add = mnemonic.to_public_key(passphrase) key = mnemonic.to_private_key(passphrase) sp = algod_client.suggested_params() sp.first = first_block sp.last = last_block sp.flat_fee = True sp.fee = 1000 print("--------------------------------------------") print("Bundling interest claim and submitting......") txn1 = AssetTransferTxn(add, sp, escrow_id, amt, interest_id) txn2 = AssetTransferTxn(add, sp, add, amt, par_id) txn3 = AssetTransferTxn(escrow_id, sp, add, amt * coupon, payment_id) t = programstr.encode() program = base64.decodebytes(t) arg = (4).to_bytes(8, 'big') lsig = LogicSig(program, args=[arg]) grp_id = calculate_group_id([txn1, txn2, txn3]) txn1.group = grp_id txn2.group = grp_id txn3.group = grp_id stxn1 = txn1.sign(key) stxn2 = txn2.sign(key) stxn3 = LogicSigTransaction(txn3, lsig) signed_group = [stxn1, stxn2, stxn3] tx_id = algod_client.send_transactions(signed_group) wait_for_confirmation(algod_client, tx_id, 200) print("Successfully committed transaction!") print("--------------------------------------------")
def import_address(self): if QtWidgets.QMessageBox.question( self, "Importing address", "Please keep in mind that, when recovering a wallet in the future, only the addresses derived from " "the Master Derivation Key are restored.\n\n" "Importing an address inside a wallet is not the same as deriving it from the wallet.\n\n" "Would you like to continue?" ) != QtWidgets.QMessageBox.StandardButton.Yes: return new_address = QtWidgets.QInputDialog.getMultiLineText( self, "Importing address", "Please fill in with the address mnemonic private key") if new_address[1]: try: self.wallet.algo_wallet.import_key( to_private_key(new_address[0])) except Exception as e: if __debug__: print(type(e), str(e), file=stderr) QtWidgets.QMessageBox.critical(self, "Could not import address", str(e)) else: self.setup_logic()
def send_tokens(receiver_pk, tx_amount): params = acl.suggested_params() gen_hash = params.gh first_valid_round = params.first tx_fee = params.min_fee last_valid_round = params.last #Your code here #generate an account mnemonic_secret = 'ship floor pattern transfer fiscal diamond maid raise never debate lemon brown siren upset gun sibling lend write cloth success glove shrug cattle ability ivory' sk = mnemonic.to_private_key(mnemonic_secret) pk = mnemonic.to_public_key(mnemonic_secret) print("my public key = ", pk) account_info = acl.account_info(pk) #prepare and sign the transaction tx = transaction.PaymentTxn(pk, tx_fee, first_valid_round, last_valid_round, gen_hash, receiver_pk, tx_amount) signed_tx = tx.sign(sk) #send the signed transaction tx_confirm = acl.send_transaction(signed_tx) #acl.status_after_block(first_valid_round+2) txid = signed_tx.transaction.get_txid() wait_for_confirmation(acl, txid) sender_pk = pk return sender_pk, txid
def test_sign(self): mn = ("advice pudding treat near rule blouse same whisper inner " + "electric quit surface sunny dismiss leader blood seat " + "clown cost exist hospital century reform able sponsor") gh = "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=" address = "PNWOET7LLOWMBMLE4KOCELCX6X3D3Q4H2Q4QJASYIEOF7YIPPQBG3YQ5YI" close = "IDUTJEUIEVSMXTU4LGTJWZ2UE2E6TIODUKU6UW3FU3UKIQQ77RLUBBBFLA" sk = mnemonic.to_private_key(mn) pk = account.address_from_private_key(sk) txn = transaction.PaymentTxn(pk, 4, 12466, 13466, gh, address, 1000, note=base64.b64decode("6gAVR0Nsv5Y="), gen="devnet-v33.0", close_remainder_to=close) stx = txn.sign(sk) golden = ("gqNzaWfEQPhUAZ3xkDDcc8FvOVo6UinzmKBCqs0woYSfodlmBMfQvGbeU" + "x3Srxy3dyJDzv7rLm26BRv9FnL2/AuT7NYfiAWjdHhui6NhbXTNA+ilY2" + "xvc2XEIEDpNJKIJWTLzpxZpptnVCaJ6aHDoqnqW2Wm6KRCH/xXo2ZlZc0" + "EmKJmds0wsqNnZW6sZGV2bmV0LXYzMy4womdoxCAmCyAJoJOohot5WHIv" + "peVG7eftF+TYXEx4r7BFJpDt0qJsds00mqRub3RlxAjqABVHQ2y/lqNyY" + "3bEIHts4k/rW6zAsWTinCIsV/X2PcOH1DkEglhBHF/hD3wCo3NuZMQg5/" + "D4TQaBHfnzHI2HixFV9GcdUaGFwgCQhmf0SVhwaKGkdHlwZaNwYXk=") self.assertEqual(golden, encoding.msgpack_encode(stx)) txid_golden = "5FJDJD5LMZC3EHUYYJNH5I23U4X6H2KXABNDGPIL557ZMJ33GZHQ" self.assertEqual(txn.get_txid(), txid_golden)
def destroy(params_dict): algod_client, params = algod_connect(params_dict) print( '\n=====================================DESTROY ASSET=====================================' ) print('asset id:', params_dict['asset']) # For destroy an asset, the account need to have all unites of the named asset # The sender have to be the manager account txn = AssetConfigTxn(sender=params_dict['sender'], sp=params, index=params_dict['asset'], strict_empty_address_check=False) private_key = mnemonic.to_private_key(params_dict['mnemonic']) stxn = txn.sign(private_key) txid = algod_client.send_transaction(stxn) print('Transaction ID:', txid) wait_for_confirmation(algod_client, txid) try: print_asset_holding(algod_client, params_dict['sender'], params_dict['asset']) print_asset_created(algod_client, params_dict['sender'], params_dict['asset']) except Exception as e: print(e)
def read_unsigned_transaction_from_file(): algod_client = connect_to_network() 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" 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'))) dir_path = os.path.dirname(os.path.realpath(__file__)) txns = transaction.retrieve_from_file(dir_path + "/unsigned.txn") # sign and submit transaction txn = txns[0] signed_txn = txn.sign(mnemonic.to_private_key(passphrase)) txid = signed_txn.transaction.get_txid() print("Signed transaction with txID: {}".format(txid)) try: txid = algod_client.send_transaction(signed_txn) # 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'])) 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 get_accounts(network): if (network == "Testnet"): # SQEZQ2G5KAI4GM3LM6VRDTTLWQO6JDOSZHNG4Q5BJ4FZ34GVNTBZWFBURU passphrase = "hotel wide vital oak frost example stove coast hero toward win tail climb hero reveal army hole old habit parade cereal such nephew absent inhale" private_key = mnemonic.to_private_key(passphrase) my_address = mnemonic.to_public_key(passphrase) print("My address: {}".format(my_address)) return [(my_address, private_key)] else: kmd = KMDClient(KMD_TOKEN, KMD_ADDRESS) wallets = kmd.list_wallets() walletID = None for wallet in wallets: if wallet["name"] == KMD_WALLET_NAME: walletID = wallet["id"] break if walletID is None: raise Exception("Wallet not found: {}".format(KMD_WALLET_NAME)) walletHandle = kmd.init_wallet_handle(walletID, KMD_WALLET_PASSWORD) try: addresses = kmd.list_keys(walletHandle) privateKeys = [ kmd.export_key(walletHandle, KMD_WALLET_PASSWORD, addr) for addr in addresses ] kmdAccounts = [(addresses[i], privateKeys[i]) for i in range(len(privateKeys))] finally: kmd.release_wallet_handle(walletHandle) return kmdAccounts
def optin(params_dict): algod_client, params = algod_connect(params_dict) print( '\n=====================================OPT-IN ASSET=====================================' ) print('asset_id:', params_dict['asset']) account_info = algod_client.account_info(params_dict['account']) holding = None idx = 0 # Verify if the account have an asset with the id: params_dict['asset'] for my_account_info in account_info['assets']: scrutinized_asset = account_info['assets'][idx] idx += 1 if scrutinized_asset['asset-id'] == params_dict['asset']: holding = True break # If the account is not holding the asset, optin the asset for this account if not holding: txn = AssetTransferTxn(sender=params_dict['account'], sp=params, receiver=params_dict['account'], amt=0, index=params_dict['asset']) private_key = mnemonic.to_private_key(params_dict['mnemonic']) stxn = txn.sign(private_key) txid = algod_client.send_transaction(stxn) print('Transaction ID: ', txid) wait_for_confirmation(algod_client, txid) print_asset_holding(algod_client, params_dict['account'], params_dict['asset'])
def write_signed_transaction_to_file(): algod_client = connect_to_network() 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 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, 100000, None, note) # sign transaction signed_txn = unsigned_txn.sign(mnemonic.to_private_key(passphrase)) # write to file dir_path = os.path.dirname(os.path.realpath(__file__)) transaction.write_to_file([signed_txn], dir_path + "/signed.txn")
def atomic_transfer(algodclient, txn1, txn2, buyer_pk, buyer_mnemonic, carrier_pk, carrier_mnemonic): #prepare transaction 1: Account 1 transfer document to Account 2 #Buyer send letter of credit to Seller # txn1 #prepare transaction 1: Account 2 transfer document to Account 1 #Seller send bill of lading to Buyer # txn2 # group transactions print("Grouping transactions...") group_id = transaction.calculate_group_id([txn1, txn2]) print("... computed groupId: ", group_id) txn1.group = group_id txn2.group = group_id # sign transactions print("Signing transactions ...") stxn1 = txn1.sign(mnemonic.to_private_key(buyer_mnemonic)) print( " ... buyer signed txn 1, i.e. to transfer Letter of Credit to seller") stxn2 = txn2.sign(mnemonic.to_private_key(carrier_mnemonic)) print( " ... carrier signed txn 2, i.e. to transfer Bill of Lading to buyer") # assemble transaction group print("Assembling transaction group ...") signedtxns = [stxn1, stxn2] # send transaction print("Sending transaction group...") tx_id = algodclient.send_transactions(signedtxns) #wat for confirmation wait_for_confirmation(algodclient, tx_id) # display confirmed transaction group # tx1 confirmed_txn = algodclient.pending_transaction_info(txn1.get_txid()) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4))) # tx2 confirmed_txn = algodclient.pending_transaction_info(txn2.get_txid()) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4)))
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 dispense(update, context): """ Transfer a custom asset from default account A to account B (Any) :param update: Default telegram argument :param context: Same as update :return: """ time.sleep(5) global dispensed global mn global test_dispenser update.message.reply_text('Sending you some test token....') to = context.user_data['address'] params = client.suggested_params() params.flat_fee = True note = "Thank you for helping in testing this program".encode('utf-8') # optin(update, context) time.sleep(4) # try: trxn = transaction.AssetTransferTxn(test_dispenser, params.fee, params.first, params.last, params.gh, to, amt=200, index=13251912, close_assets_to=None, note=note, gen=params.gen, flat_fee=params.flat_fee, lease=None, rekey_to=None) # Sign the transaction k = mnemonic.to_private_key(mn) signed_txn = trxn.sign(k) # Submit transaction to the network tx_id = client.send_transaction(signed_txn) wait_for_confirmation(update, context, client, tx_id) update.message.reply_text( "Yummy! I just sent you 200 DMT2...\nCheck the explorer for txn info.\n" "" 'Hash: ' f'{tx_id}' 'Explorer: ' 'https://algoexplorer.io') dispensed = dispensed + (to, ) logging.info( "...##Asset Transfer... \nReceiving account: {}.\nOperation: {}.\nTxn Hash: {}" .format(to, dispense.__name__, tx_id)) update.message.reply_text( "Successful! \nTransaction hash: {}".format(tx_id)) context.user_data.clear()
def __init__( self, algod, passphrase, namespace_address="X6E3EZE53KAJRPUWPRLRPRDIGIFIUUVB67LJ4RBA73GJDL5N7DRQ466RAM" ): self.algod = algod self.namespace_address = namespace_address self.sk = mnemonic.to_private_key(passphrase)
def createSignedTxn(algod_client, sender, passphrase, receiver, microAlgos, note): params = algod_client.suggested_params() note = note.encode() params.fee = 1000 params.flat_fee = True unsigned_txn = PaymentTxn(sender, params, receiver, microAlgos, None, note) signed_txn = unsigned_txn.sign(mnemonic.to_private_key(passphrase)) return signed_txn
def replenish_account(passphrase, escrow_id, amt, payment_id, algod_client): add = mnemonic.to_public_key(passphrase) key = mnemonic.to_private_key(passphrase) sp = algod_client.suggested_params() sp.flat_fee = True sp.fee = 1000 txn = AssetTransferTxn(add, sp, escrow_id, amt, payment_id) stxn = txn.sign(key) tx_id = algod_client.send_transaction(stxn) wait_for_confirmation(algod_client, tx_id, 10)
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 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 p2p_order(buyer, seller, order_details): params = algod_client.suggested_params() buyer_pk = mnemonic.to_public_key(buyer) buyer_sk = mnemonic.to_private_key(buyer) seller_pk = mnemonic.to_public_key(seller) seller_sk = mnemonic.to_private_key(seller) # activate buyer's account print("Activating Buyer's account") activate_account(order_details['asset_id'], buyer) # Token transaction print("\n Executing Token Transaction") token_txn = AssetTransferTxn( sender=seller_pk, sp=params, receiver=buyer_pk, amt=int(order_details['token_amount']), index=order_details['asset_id']) token_stxn = token_txn.sign(seller_sk) token_txid = algod_client.send_transaction(token_stxn) print(token_txid) wait_for_confirmation(algod_client, token_txid) print_asset_holding(algod_client, buyer_pk, order_details['asset_id']) # Activating USDT for seller print("Activating USDT for Seller") activate_account(USDT_asset_id, seller) # USDT Transaction print("\n USDT Transaction") usdt_txn = AssetTransferTxn( sender=buyer_pk, sp=params, receiver=seller_pk, amt=int(order_details['usdt_amount']), index=USDT_asset_id) usdt_stxn = usdt_txn.sign(buyer_sk) usdt_txid = algod_client.send_transaction(usdt_stxn) print(usdt_txid) wait_for_confirmation(algod_client, usdt_txid) print_asset_holding(algod_client, seller_pk, USDT_asset_id)
def group_transactions(): # recover a account passphrase1 = os.getenv("MNEMONIC1") pk_account_a = mnemonic.to_private_key(passphrase1) account_a = account.address_from_private_key(pk_account_a) # recover b account account_b = "4O6BRAPVLX5ID23AZWV33TICD35TI6JWOHXVLPGO4VRJATO6MZZQRKC7RI" # connect to node acl = connect_to_network() # get suggested parameters params = acl.suggested_params() gen = params["genesisID"] gh = params["genesishashb64"] last_round = params["lastRound"] fee = params["fee"] asset_index = 14035004 # create transaction1 txn1 = transaction.PaymentTxn(account_a, fee, last_round, last_round + 100, gh, account_b, 42000000) # create transaction2 txn2 = transaction.AssetTransferTxn(account_b, fee, last_round, last_round + 100, gh, account_a, 1, asset_index) # get group id and assign it to transactions gid = transaction.calculate_group_id([txn1, txn2]) txn1.group = gid txn2.group = gid # sign transaction1 stxn1 = txn1.sign(pk_account_a) # sign transaction2 with open("buildweb3/step5.lsig", "rb") as f: lsig = encoding.future_msgpack_decode(base64.b64encode(f.read())) stxn2 = transaction.LogicSigTransaction(txn2, lsig) signedGroup = [] signedGroup.append(stxn1) signedGroup.append(stxn2) # send them over network sent = acl.send_transactions(signedGroup) # print txid print(sent) # wait for confirmation wait_for_confirmation(acl, sent)
def sign_and_send(txn, passphrase, client): """ Signs and sends the transaction to the network. Returns transaction info. """ private_key = mnemonic.to_private_key(passphrase) stxn = txn.sign(private_key) txid = stxn.transaction.get_txid() client.send_transaction(stxn) txinfo = wait_for_confirmation(client, txid) return txinfo
def asset_transaction(passphrase, amt, rcv, asset_id, algod_client) -> dict: params = algod_client.suggested_params() add = mnemonic.to_public_key(passphrase) key = mnemonic.to_private_key(passphrase) params.flat_fee = True params.fee = 1000 unsigned_txn = AssetTransferTxn(add, params, rcv, amt, asset_id) signed = unsigned_txn.sign(key) txid = algod_client.send_transaction(signed) pmtx = wait_for_confirmation(algod_client, txid, 4) return pmtx
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 get_wallet_key_pairs(passphrase): """ @params{passphrase} - 25-word mnemonic string Returns a dictionary containing the public key (account address) and private key of the wallet. @returns { 'public_key': string, 'private_key': string } """ return { 'public_key': mnemonic.to_public_key(passphrase), 'private_key': mnemonic.to_private_key(passphrase) }
def sign_and_send(txn, passphrase, client): """ Signs and sends the transaction to the network. Returns transaction info. """ private_key = mnemonic.to_private_key(passphrase) stxn = txn.sign(private_key) txid = stxn.transaction.get_txid() client.send_transaction(stxn) wait_for_confirmation(client, txid, 5) print('Confirmed TXID: {}'.format(txid)) txinfo = client.pending_transaction_info(txid) return txinfo
def resolve(self, bankrIdentifier, skey): # Check if Leafbank holding Bankers' asset prior to opt-in assetId = getAssetIdv2(transaction_executor) account_info_pk = algo_client.account_info(bankrIdentifier) holding = None idx = 0 print(account_info_pk) for assetinfo in account_info_pk['assets']: scrutinized_asset = assetinfo[idx] idx = idx + 1 if assetId == scrutinized_asset['asset-id']: holding = True msg = "This address has opted in for ISA, ID {}".format(assetId) logging.info("Message: {}".format(msg)) logging.captureWarnings(True) break if not holding: # Use the AssetTransferTxn class to transfer assets and opt-in txn = AssetTransferTxn( sender=bankrIdentifier, sp=params, receiver=bankrIdentifier, amt=0, index=assetId ) # Sign the transaction # Firstly, convert mnemonics to private key--. sk = mnemonic.to_private_key(seed) sendTrxn = txn.sign(sk) # Submit transaction to the network txid = algo_client.send_transaction(sendTrxn, headers={'content-type': 'application/x-binary'}) message = "Transaction was signed with: {}.".format(txid) wait = wait_for_confirmation(txid) time.sleep(2) hasOptedIn = bool(wait is not None) if hasOptedIn: self.hasResolve = True print(assetId) # Now check the asset holding for that account. # This should now show a holding with 0 balance. assetHolding = print_asset_holding(bankrIdentifier, assetId) logging.info("...##Asset Transfer... \nLeaf Bank address: {}.\nMessage: {}\nHas Opted in: {}\nOperation: {}\nHoldings: {}\n".format( bankrIdentifier, message, hasOptedIn, Bankers.resolve.__name__, assetHolding )) return hasOptedIn
def createAsset(algod_client, passphrase, html, doc_id, doc_name): # 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 # Account 1 creates an asset called latinum and # sets Account 2 as the manager, reserve, freeze, and clawback address. # Asset Creation transaction account_pk = mnemonic.to_public_key(passphrase) account_sk = mnemonic.to_private_key(passphrase) txn = AssetConfigTxn(sender=account_pk, sp=params, total=1, default_frozen=False, unit_name=doc_id, asset_name=doc_name, manager=account_pk, reserve=account_pk, freeze=account_pk, clawback=account_pk, url=html, decimals=0) # Sign with secret key of creator stxn = txn.sign(account_sk) # Send the transaction to the network and retrieve the txid. txid = algod_client.send_transaction(stxn) print(txid) # Retrieve the asset ID of the newly created asset by first # ensuring that the creation transaction was confirmed, # then grabbing the asset id from the transaction. # Wait for the transaction to be confirmed wait_for_confirmation(algod_client, txid) 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, account_pk, asset_id) print_asset_holding(algod_client, account_pk, asset_id) except Exception as e: print(e)