def test_file_read_write(self): # get suggested parameters and fee gh = self.acl.versions()['genesis_hash_b64'] rnd = int(self.acl.status()['lastRound']) sp = transaction.SuggestedParams(0, rnd, rnd + 100, gh) # create transaction txn = transaction.PaymentTxn(self.account_0, sp, self.account_0, 1000) # get private key w = wallet.Wallet(wallet_name, wallet_pswd, self.kcl) private_key = w.export_key(self.account_0) # sign transaction stx = txn.sign(private_key) # write to file dir_path = os.path.dirname(os.path.realpath(__file__)) transaction.write_to_file([txn, stx], dir_path + "/raw.tx") # read from file txns = transaction.retrieve_from_file(dir_path + "/raw.tx") # check that the transactions are still the same self.assertEqual(encoding.msgpack_encode(txn), encoding.msgpack_encode(txns[0])) self.assertEqual(encoding.msgpack_encode(stx), encoding.msgpack_encode(txns[1])) # delete the file os.remove("raw.tx")
def notify(algod_client: algod.AlgodClient, user: Account, seller: Account, trade_gtxn: list): params = algod_client.suggested_params() note = { 'buy_order': 'AlgoRealm Special Card', 'asset_id': CARD_ID, 'algo_amount': trade_gtxn[2].transaction.amt / 10**6, 'algo_royalty': (trade_gtxn[3].amt + trade_gtxn[4].amt) / 10**6, 'last_valid_block': trade_gtxn[2].transaction.last_valid_round } bytes_note = msgpack.packb(note) notification_txn = transaction.PaymentTxn( sender=user.address, sp=params, receiver=seller.address, amt=0, note=bytes_note, ) signed_txn = sign(user, notification_txn) tx_id = signed_txn.transaction.get_txid() print("āļø Sending buy order notification to the Seller...\n") algod_client.send_transactions([signed_txn]) wait_for_confirmation(algod_client, tx_id) print("\nš Buy order notification:\n" "https://algoexplorer.io/tx/" + tx_id)
def fund_contract(context): context.txn = transaction.PaymentTxn(context.accounts[0], context.params, context.template.get_address(), context.fund_amt) context.txn = context.wallet.sign_transaction(context.txn) context.acl.send_transaction(context.txn) context.acl.status_after_block(context.acl.status()["lastRound"] + 3)
def fund_account(client, sender, sender_priv_key, suggested_params, account, amount): txn = transaction.PaymentTxn( sender, suggested_params, account, amount, ) signed_txn = txn.sign(sender_priv_key) tx_id = client.send_transactions([signed_txn]) return tx_id
def default_txn(context, amt, note): params = context.acl.suggested_params_as_object() context.last_round = params.first if note == "none": note = None else: note = base64.b64decode(note) context.txn = transaction.PaymentTxn(context.accounts[0], params, context.accounts[1], int(amt), note=note) context.pk = context.accounts[0]
def txnfield(my_address, receiver, amount): txn = { "sender": my_address, "receiver": receiver, "fee": params.get('minFee'), "flat_fee": True, "amt": amount, "first": params.get('lastRound'), "last": params.get('lastRound') + 1000, "note": note, "gen": params.get('genesisID'), "gh": params.get('genesishashb64') } return transaction.PaymentTxn(**txn)
def add_liquidity_call( client, user, user_priv_key, suggested_params, app_id, escrow_addr, asset_amount, algos_amount, asset_index, ): app_txn = transaction.ApplicationCallTxn( user, suggested_params, app_id, transaction.OnComplete.NoOpOC.real, app_args=['ADD_LIQUIDITY'.encode('utf-8')]) asset_add_txn = transaction.AssetTransferTxn( user, suggested_params, escrow_addr, asset_amount, asset_index, ) algos_add_txn = transaction.PaymentTxn( user, suggested_params, escrow_addr, algos_amount, ) gid = transaction.calculate_group_id( [app_txn, asset_add_txn, algos_add_txn]) app_txn.group = gid asset_add_txn.group = gid algos_add_txn.group = gid signed_app_txn = app_txn.sign(user_priv_key) signed_asset_add_txn = asset_add_txn.sign(user_priv_key) signed_algos_add_txn = algos_add_txn.sign(user_priv_key) tx_id = client.send_transactions([ signed_app_txn, signed_asset_add_txn, signed_algos_add_txn, ]) return tx_id
def withdraw_call( client, user, user_priv_key, suggested_params, app_id, escrow_addr, asset_index, algos_amount=0, asset_amount=0, ): app_txn = transaction.ApplicationCallTxn( user, suggested_params, app_id, transaction.OnComplete.NoOpOC.real, app_args=['WITHDRAW'.encode('utf-8')]) asset_withdraw_txn = transaction.AssetTransferTxn( escrow_addr, suggested_params, user, asset_amount, asset_index, ) algos_withdraw_txn = transaction.PaymentTxn( escrow_addr, suggested_params, user, algos_amount, ) gid = transaction.calculate_group_id( [app_txn, asset_withdraw_txn, algos_withdraw_txn]) app_txn.group = gid asset_withdraw_txn.group = gid algos_withdraw_txn.group = gid lsig = transaction.LogicSig( compile_program(client, open('./contracts/escrow.teal', 'rb').read())) signed_asset_withdraw_txn = transaction.LogicSigTransaction( asset_withdraw_txn, lsig) signed_algos_withdraw_txn = transaction.LogicSigTransaction( algos_withdraw_txn, lsig) signed_app_txn = app_txn.sign(user_priv_key) tx_id = client.send_transactions( [signed_app_txn, signed_asset_withdraw_txn, signed_algos_withdraw_txn]) return tx_id
def default_msig_txn(context, amt, note): params = context.acl.suggested_params_as_object() context.last_round = params.first if note == "none": note = None else: note = base64.b64decode(note) context.msig = transaction.Multisig(1, 1, context.accounts) context.txn = transaction.PaymentTxn(context.msig.address(), params, context.accounts[1], int(amt), note=note) context.mtx = transaction.MultisigTransaction(context.txn, context.msig) context.pk = context.accounts[0]
def send_tokens_algo(acl, sender_sk, txes): params = acl.suggested_params # TODO: You might want to adjust the first/last valid rounds in the suggested_params # See guide for details gen_hash = params.gh first_valid_round = params.first tx_fee = params.min_fee last_valid_round = params.last # TODO: For each transaction, do the following: # - Create the Payment transaction # - Sign the transaction tx = transaction.PaymentTxn(existing_account, tx_fee, first_valid_round, last_valid_round, gen_hash, send_to_address, send_amount, flat_fee=True) signed_tx = tx.sign(sk) # TODO: Return a list of transaction id's sender_pk = account.address_from_private_key(sender_sk) tx_ids = [] for i, tx in enumerate(txes): unsigned_tx = "Replace me with a transaction object" # TODO: Sign the transaction signed_tx = "Replace me with a SignedTransaction object" try: print( f"Sending {tx['amount']} microalgo from {sender_pk} to {tx['receiver_pk']}" ) # TODO: Send the transaction to the testnet tx_confirm = acl.send_transaction(signed_tx) tx_id = signed_tx.transaction.get_txid() txinfo = wait_for_confirmation_algo(acl, txid=tx_id) print(f"Sent {tx['amount']} microalgo in transaction: {tx_id}\n") except Exception as e: print(e) return []
def claim_nft( algod_client: algod.AlgodClient, indexer_client: indexer.IndexerClient, claimer: Account, claim_arg: str, new_majesty: str, donation_amount: int, nft_id: int, ): params = algod_client.suggested_params() claim_txn = transaction.ApplicationNoOpTxn( sender=claimer.address, sp=params, index=ALGOREALM_APP_ID, app_args=[claim_arg.encode(), new_majesty.encode()]) donation_txn = transaction.PaymentTxn( sender=claimer.address, sp=params, receiver=REWARDS_POOL, amt=donation_amount, ) nft_transfer = transaction.AssetTransferTxn( sender=ALGOREALM_LAW.address, sp=params, receiver=claimer.address, amt=1, index=nft_id, revocation_target=current_owner(indexer_client, nft_id), ) signed_group = group_and_sign( [claimer, claimer, ALGOREALM_LAW], [claim_txn, donation_txn, nft_transfer], ) nft_name = algod_client.asset_info(nft_id)['params']['name'] print(f"Claiming the {nft_name} as {new_majesty}, " f"donating {donation_amount / 10 ** 6} ALGO...\n") try: gtxn_id = algod_client.send_transactions(signed_group) wait_for_confirmation(algod_client, gtxn_id) except AlgodHTTPError: quit("\nā¹ļø Were you too stingy? Only generous hearts will rule over " "Algorand Realm!\nļø")
def test_auction(self): # get the default wallet wallets = self.kcl.list_wallets() wallet_id = None for w in wallets: if w["name"] == wallet_name: wallet_id = w["id"] # get a new handle for the wallet handle = self.kcl.init_wallet_handle(wallet_id, wallet_pswd) # generate account with kmd account_1 = self.kcl.generate_key(handle, False) # get self.account_0 private key private_key_0 = self.kcl.export_key(handle, wallet_pswd, self.account_0) # create bid bid = auction.Bid(self.account_0, 10000, 260, "bid_id", account_1, "auc_id") sb = bid.sign(private_key_0) nf = auction.NoteField(sb, constants.note_field_type_bid) # get suggested parameters and fee gh = self.acl.versions()['genesis_hash_b64'] rnd = int(self.acl.status()['lastRound']) sp = transaction.SuggestedParams(0, rnd, rnd + 100, gh) # create transaction txn = transaction.PaymentTxn(self.account_0, sp, account_1, 100000, note=base64.b64decode( encoding.msgpack_encode(nf))) # sign transaction with account signed_account = txn.sign(private_key_0) # send transaction send = self.acl.send_transaction(signed_account) self.assertEqual(send, txn.get_txid()) del_1 = self.kcl.delete_key(handle, wallet_pswd, account_1) self.assertTrue(del_1)
def test_transaction_group(self): # get the default wallet wallets = self.kcl.list_wallets() wallet_id = None for w in wallets: if w["name"] == wallet_name: wallet_id = w["id"] # get a new handle for the wallet handle = self.kcl.init_wallet_handle(wallet_id, wallet_pswd) # get private key private_key_0 = self.kcl.export_key(handle, wallet_pswd, self.account_0) # get suggested parameters and fee gh = self.acl.versions()['genesis_hash_b64'] rnd = int(self.acl.status()['lastRound']) sp = transaction.SuggestedParams(0, rnd, rnd + 100, gh) # create transaction txn = transaction.PaymentTxn(self.account_0, sp, self.account_0, 1000) # calculate group id gid = transaction.calculate_group_id([txn]) txn.group = gid # sign using kmd stxn1 = self.kcl.sign_transaction(handle, wallet_pswd, txn) # sign using transaction call stxn2 = txn.sign(private_key_0) # check that they are the same self.assertEqual(encoding.msgpack_encode(stxn1), encoding.msgpack_encode(stxn2)) try: send = self.acl.send_transactions([stxn1]) self.assertEqual(send, txn.get_txid()) except error.AlgodHTTPError as ex: self.assertIn( "TransactionPool.Remember: transaction groups not supported", str(ex))
def swap_call(client, user, user_priv_key, suggested_params, app_id, amount, escrow_addr, asset_index=None): app_txn = transaction.ApplicationCallTxn( user, suggested_params, app_id, transaction.OnComplete.NoOpOC.real, app_args=['SWAP'.encode('utf-8')]) if asset_index: swap_txn = transaction.AssetTransferTxn( user, suggested_params, escrow_addr, amount, asset_index, ) else: swap_txn = transaction.PaymentTxn( user, suggested_params, escrow_addr, amount, ) gid = transaction.calculate_group_id([app_txn, swap_txn]) app_txn.group = gid swap_txn.group = gid signed_app_txn = app_txn.sign(user_priv_key) signed_swap_txn = swap_txn.sign(user_priv_key) tx_id = client.send_transactions([signed_app_txn, signed_swap_txn]) return tx_id
# Example: creating a LogicSig transaction signed by a program that never approves the transfer. import tokens from algosdk import algod, account from algosdk.future import transaction program = b"\x01\x20\x01\x00\x22" # int 0 lsig = transaction.LogicSig(program) sender = lsig.address() receiver = account.generate_account() # create an algod client acl = algod.AlgodClient(tokens.algod_token, tokens.algod_address) # get suggested parameters sp = acl.suggested_params() # create a transaction amount = 10000 txn = transaction.PaymentTxn(sender, sp, receiver, amount) # note: transaction is signed by logic only (no delegation) # that means sender address must match to program hash lstx = transaction.LogicSigTransaction(txn, lsig) assert lstx.verify() # send them over network acl.send_transaction(lstx)
def pay(self, sender, receiver, amt: int, send=None, **kwargs): params = self.algod.suggested_params() tx = txn.PaymentTxn(sender, params, receiver, amt, **kwargs) return self.finish(tx, send)
from algosdk.future import transaction # generate three accounts private_key_1, account_1 = account.generate_account() private_key_2, account_2 = account.generate_account() private_key_3, account_3 = account.generate_account() # create a multisig account version = 1 # multisig version threshold = 2 # how many signatures are necessary msig = transaction.Multisig(version, threshold, [account_1, account_2]) # get suggested parameters acl = algod.AlgodClient(tokens.algod_token, tokens.algod_address) suggested_params = acl.suggested_params_as_object() # create a transaction sender = msig.address() amount = 10000 txn = transaction.PaymentTxn(sender, suggested_params, account_3, amount) # create a SignedTransaction object mtx = transaction.MultisigTransaction(txn, msig) # sign the transaction mtx.sign(private_key_1) mtx.sign(private_key_2) # print encoded transaction print("Encoded transaction:", encoding.msgpack_encode(mtx))
# Example: rekeying from algosdk import account, algod from algosdk.future import transaction import tokens sender_private_key, sender = account.generate_account( ) # this should be the current account rekey_private_key, rekey_address = account.generate_account() receiver = sender amount = 0 # get suggested parameters acl = algod.AlgodClient(tokens.algod_token, tokens.algod_address) suggested_params = acl.suggested_params_as_object() # To rekey an account to a new address, add the `rekey_to` argument to creation. # After sending this rekeying transaction, every transaction needs to be signed by the private key of the new address rekeying_txn = transaction.PaymentTxn(sender, suggested_params, receiver, amount, rekey_to=rekey_address)
from algosdk import algod, kmd, account from algosdk.future import transaction # generate accounts private_key_sender, sender = account.generate_account() private_key_receiver, receiver = account.generate_account() # create an algod and kmd client acl = algod.AlgodClient(tokens.algod_token, tokens.algod_address) kcl = kmd.KMDClient(tokens.kmd_token, tokens.kmd_address) # get suggested parameters sp = acl.suggested_params_as_object() # create a transaction amount = 10000 txn1 = transaction.PaymentTxn(sender, sp, receiver, amount) txn2 = transaction.PaymentTxn(receiver, sp, sender, amount) # get group id and assign it to transactions gid = transaction.calculate_group_id([txn1, txn2]) txn1.group = gid txn2.group = gid # sign transactions stxn1 = txn1.sign(private_key_sender) stxn2 = txn2.sign(private_key_receiver) # send them over network (note that the accounts need to be funded for this to work) acl.send_transactions([stxn1, stxn2])
def test_wallet(self): # initialize wallet w = wallet.Wallet(wallet_name, wallet_pswd, self.kcl) # get master derivation key mdk = w.export_master_derivation_key() # get mnemonic mn = w.get_mnemonic() # make sure mnemonic can be converted back to mdk self.assertEqual(mdk, mnemonic.to_master_derivation_key(mn)) # generate account with account and check if it's valid private_key_1, account_1 = account.generate_account() # import generated account import_key = w.import_key(private_key_1) self.assertEqual(import_key, account_1) # check that the account is in the wallet keys = w.list_keys() self.assertIn(account_1, keys) # generate account with kmd account_2 = w.generate_key() private_key_2 = w.export_key(account_2) # get suggested parameters and fee gh = self.acl.versions()['genesis_hash_b64'] rnd = int(self.acl.status()['lastRound']) sp = transaction.SuggestedParams(0, rnd, rnd + 100, gh) # create transaction txn = transaction.PaymentTxn(self.account_0, sp, account_1, 100000) # sign transaction with wallet signed_kmd = w.sign_transaction(txn) # get self.account_0 private key private_key_0 = w.export_key(self.account_0) # sign transaction with account signed_account = txn.sign(private_key_0) # check that signing both ways results in the same thing self.assertEqual(encoding.msgpack_encode(signed_account), encoding.msgpack_encode(signed_kmd)) # create multisig account and transaction msig = transaction.Multisig(1, 2, [account_1, account_2]) txn = transaction.PaymentTxn(msig.address(), sp, self.account_0, 1000) # import multisig account msig_address = w.import_multisig(msig) # check that the multisig account is listed msigs = w.list_multisig() self.assertIn(msig_address, msigs) # export multisig account exported = w.export_multisig(msig_address) self.assertEqual(len(exported.subsigs), 2) # create multisig transaction mtx = transaction.MultisigTransaction(txn, msig) # sign the multisig using kmd msig_1 = w.sign_multisig_transaction(account_1, mtx) signed_kmd = w.sign_multisig_transaction(account_2, msig_1) # sign the multisig offline mtx1 = transaction.MultisigTransaction(txn, msig) mtx1.sign(private_key_1) mtx2 = transaction.MultisigTransaction(txn, msig) mtx2.sign(private_key_2) signed_account = transaction.MultisigTransaction.merge([mtx1, mtx2]) # check that they are the same self.assertEqual(encoding.msgpack_encode(signed_account), encoding.msgpack_encode(signed_kmd)) # delete accounts del_1 = w.delete_key(account_1) del_2 = w.delete_key(account_2) del_3 = w.delete_multisig(msig_address) self.assertTrue(del_1) self.assertTrue(del_2) self.assertTrue(del_3) # test renaming the wallet w.rename(wallet_name + "1") self.assertEqual(wallet_name + "1", w.info()["wallet"]["name"]) w.rename(wallet_name) self.assertEqual(wallet_name, w.info()["wallet"]["name"]) # test releasing the handle w.release_handle() self.assertRaises(error.KMDHTTPError, self.kcl.get_wallet, w.handle) # test handle automation w.info()
def create_paytxn_flat_fee(context): context.params.flat_fee = True context.txn = transaction.PaymentTxn(context.pk, context.params, context.to, context.amt, context.close, context.note)
# create the NoteField object bid_currency = 100 max_price = 15 bid_id = 18862 auction_key = "7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q" auction_id = 93559 bid = auction.Bid(public_key, bid_currency, max_price, bid_id, auction_key, auction_id) signed_bid = bid.sign(private_key) notefield = auction.NoteField(signed_bid, constants.note_field_type_bid) # create the transaction txn = transaction.PaymentTxn(public_key, sp, receiver, amount, note=base64.b64decode( encoding.msgpack_encode(notefield))) # encode the transaction encoded_txn = encoding.msgpack_encode(txn) print("Encoded transaction:", encoded_txn, "\n") # if someone else were to want to access the notefield from an encoded # transaction, they could just decode the transaction decoded_txn = encoding.msgpack_decode(encoded_txn) decoded_notefield = encoding.msgpack_decode(base64.b64encode(decoded_txn.note)) print("Decoded notefield from encoded transaction:", decoded_notefield.dictify())
accounts = {} counter = 1 for m in [mnemonic1, mnemonic2, mnemonic3]: accounts[counter] = {} accounts[counter]['pk'] = mnemonic.to_public_key(m) accounts[counter]['sk'] = mnemonic.to_private_key(m) counter += 1 sender_address = accounts[1]['pk'] params = algod_client.suggested_params() params.flat_fee = True params.fee = 1000 send_amount = 10 receiver_address = accounts[2]['pk'] txn = transaction.PaymentTxn(sender_address, params, receiver_address, send_amount) signed_txn = txn.sign(accounts[1]['sk']) txid = algod_client.send_transaction(signed_txn) print("Transaction ID is: ", txid) #Waiting for transaction confirmation def wait_for_confirmation(client, txid): # """ # Utility function to wait until the transaction is # confirmed before proceeding. # """ last_round = client.status().get('last-round') txinfo = client.pending_transaction_info(txid) while not (txinfo.get('confirmed-round') and txinfo.get('confirmed-round') > 0):
result = re.search(r': \w+', stdout) escrow_addr = result.group(0)[2:] print("Dispense at least 202000 microAlgo to {}".format(escrow_addr)) input("Make sure you did that. Press Enter to continue...") # now, as a provider, you can withdraw Algo from the escrow if you sign the first valid acl = algod.AlgodClient(params.algod_token, params.algod_address) sp = acl.suggested_params_as_object() first_valid = sp.first data = first_valid.to_bytes(8, byteorder='big') lease = hash.sha256(data) lease_bytes = encoding.HexEncoder.decode(lease) print("first valid: {}".format(first_valid)) txn = transaction.PaymentTxn(escrow_addr, sp, provider_addr, 100000, lease=lease_bytes) with open(lsig_fname, "rb") as f: teal_bytes = f.read() lsig = transaction.LogicSig(teal_bytes) lstx = transaction.LogicSigTransaction(txn, lsig) assert(lstx.verify()) # send LogicSigTransaction to network transaction.write_to_file([lstx], "r_s_1.txn") stdout, stderr = execute(["goal", "clerk", "tealsign", "--data-b64", base64.b64encode(data), "--lsig-txn", "r_s_1.txn", "--keyfile", key_fn, "--set-lsig-arg-idx", "0"]) if stderr != "":
def create_msigpaytxn_zero_fee(context): context.txn = transaction.PaymentTxn(context.msig.address(), context.params, context.to, context.amt, context.close, context.note) context.mtx = transaction.MultisigTransaction(context.txn, context.msig)
def getting_started_example(): # 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_address = "http://hackathon.algodev.network:9100" # algod_token = "ef920e2e7e002953f4b29a8af720efe8e4ecc75ff102b165e0472834b25832c1" algod_address = "http://hackathon.algodev.network:9100" algod_token = "ef920e2e7e002953f4b29a8af720efe8e4ecc75ff102b165e0472834b25832c1" # algod_address = "http://localhost:4001" # algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" algod_client = algod.AlgodClient(algod_token, algod_address) # Generate new account for this transaction secret_key, my_address = account.generate_account() print("My address: {}".format(my_address)) print("My private key: {}".format(secret_key)) # 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") # Fund the created account print( '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(10) 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") # build transaction print("Building 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 = "HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA" note = "Hello World".encode() amount = 100000 closeto = "HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA" # Fifth argument is a close_remainder_to parameter that creates a payment txn that sends all of the remaining funds to the specified address. If you want to learn more, go to: https://developer.algorand.org/docs/reference/transactions/#payment-transaction unsigned_txn = transaction.PaymentTxn(my_address, params, receiver, amount, closeto, note) # sign transaction print("Signing transaction") signed_txn = unsigned_txn.sign(secret_key) print("Sending transaction") txid = algod_client.send_transaction(signed_txn) print('Transaction Info:') print("Signed transaction with txID: {}".format(txid)) # wait for confirmation try: print("Waiting for confirmation") confirmed_txn = transaction.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=4))) print("Decoded note: {}".format( base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode())) print("Starting Account balance: {} microAlgos".format( account_info.get('amount'))) print("Amount transfered: {} microAlgos".format(amount)) print("Fee: {} microAlgos".format(params.min_fee)) closetoamt = account_info.get('amount') - (params.min_fee + amount) print("Close to Amount: {} microAlgos".format(closetoamt) + "\n") account_info = algod_client.account_info(my_address) print("Final Account balance: {} microAlgos".format( account_info.get('amount')) + "\n")
def group_transactions(): # Initialize an algodClient algod_client = algod.AlgodClient(algod_token, algod_address, headers={"User-Agent": "DoYouLoveMe?"}) # declared account1 and account2 based on user supplied mnemonics print("Loading two existing accounts...") account_1 = get_address(mnemonic_1) account_2 = get_address(mnemonic_2) # convert mnemonic1 and mnemonic2 using the mnemonic.ToPrivateKey() helper function sk_1 = mnemonic.to_private_key(mnemonic_1) sk_2 = mnemonic.to_private_key(mnemonic_2) # display account balances print("Initial balances:") display_account_algo_balance(algod_client, account_1) display_account_algo_balance(algod_client, account_2) # get node 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 transactions print("Creating transactions...") # from account 2 to account 1 sender = account_2 receiver = account_1 amount = 12 * 1000000 txn_1 = transaction.PaymentTxn(sender, params, receiver, amount) print("...txn_1: from {} to {} for {} microAlgos".format( sender, receiver, amount)) print("...created txn_1: ", txn_1.get_txid()) # from account 1 to account 2 sender = account_1 receiver = account_2 amount = 1 txn_2 = transaction.AssetTransferTxn(sender, params, receiver, amount, 14075399) print("...txn_2: from {} to {} for {} microAlgos".format( sender, receiver, amount)) print("...created txn_2: ", txn_2.get_txid()) # combine transations print("Combining transactions...") # the SDK does this implicitly within grouping below print("Grouping transactions...") # compute group id and put it into each transaction group_id = transaction.calculate_group_id([txn_1, txn_2]) print("...computed groupId: ", group_id) txn_1.group = group_id txn_2.group = group_id # split transaction group print("Splitting unsigned transaction group...") # this example does not use files on disk, so splitting is implicit above # sign transactions print("Signing transactions...") stxn_1 = txn_1.sign(sk_2) print("...account1 signed txn_1: ", stxn_1.get_txid()) stxn_2 = txn_2.sign(sk_1) print("...account2 signed txn_2: ", stxn_2.get_txid()) # assemble transaction group print("Assembling transaction group...") signedGroup = [] signedGroup.append(stxn_1) signedGroup.append(stxn_2) # send transactions print("Sending transaction group...") tx_id = algod_client.send_transactions(signedGroup) # wait for confirmation wait_for_confirmation(algod_client, tx_id) # display account balances print("Final balances:") display_account_algo_balance(algod_client, account_1) display_account_algo_balance(algod_client, account_2) # display confirmed transaction group # tx1 confirmed_txn = algod_client.pending_transaction_info(txn_1.get_txid()) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4))) # tx2 confirmed_txn = algod_client.pending_transaction_info(txn_2.get_txid()) print("Transaction information: {}".format( json.dumps(confirmed_txn, indent=4)))
def card_order( algod_client: algod.AlgodClient, buyer: Account, seller: Account, price: int, ): params = algod_client.suggested_params() proof_crown_ownership = proof_asa_amount_eq_txn( algod_client=algod_client, sender=seller, asa_id=CROWN_ID, asa_amount=1, ) proof_sceptre_ownership = proof_asa_amount_eq_txn( algod_client=algod_client, sender=seller, asa_id=SCEPTRE_ID, asa_amount=1, ) nft_card_payment = transaction.PaymentTxn( sender=buyer.address, sp=params, receiver=seller.address, amt=price, ) royalty_amount = math.ceil(price * ROYALTY_PERC / 100) royalty_1_payment = transaction.PaymentTxn( sender=seller.address, sp=params, receiver=ROYALTY_COLLECTOR_1.address, amt=royalty_amount, ) royalty_2_payment = transaction.PaymentTxn( sender=seller.address, sp=params, receiver=ROYALTY_COLLECTOR_2.address, amt=royalty_amount, ) nft_card_xfer = transaction.AssetTransferTxn( sender=CARD_CONTRACT.address, sp=params, receiver=buyer.address, amt=1, index=CARD_ID, revocation_target=seller.address, ) trade_gtxn = [ proof_crown_ownership, proof_sceptre_ownership, nft_card_payment, royalty_1_payment, royalty_2_payment, nft_card_xfer ] transaction.assign_group_id(trade_gtxn) signed_nft_card_payment = trade_gtxn[2].sign(buyer.private_key) trade_gtxn[2] = signed_nft_card_payment trade_gtxn[5] = transaction.LogicSigTransaction(trade_gtxn[5], CARD_CONTRACT.lsig) transaction.write_to_file(trade_gtxn, 'trade_raw.gtxn', overwrite=True) print( "š Partially signed trade group transaction saved as: 'trade.gtxn'\n") return trade_gtxn
print("Second account: " + address_2 + "\n") # get the mnemonic for address_1 mn = mnemonic.from_private_key(private_key_1) print("Mnemonic for the first account: " + mn + "\n") # get suggested parameters sp = acl.suggested_params() # get last block info block_info = acl.block_info(sp.first) print("Block", sp.first, "info:", json.dumps(block_info, indent=2), "\n") # create a transaction amount = 100000 txn = transaction.PaymentTxn(existing_account, sp, address_1, amount) print("Encoded transaction:", encoding.msgpack_encode(txn), "\n") # sign transaction with kmd signed_with_kmd = kcl.sign_transaction(existing_handle, existing_wallet_pswd, txn) # get the private key for the existing account private_key = kcl.export_key(existing_handle, existing_wallet_pswd, existing_account) # sign transaction offline signed_offline = txn.sign(private_key) print("Signature: " + signed_offline.signature + "\n") # check that they're the same
def test_multisig(self): # get the default wallet wallets = self.kcl.list_wallets() wallet_id = None for w in wallets: if w["name"] == wallet_name: wallet_id = w["id"] # get a new handle for the wallet handle = self.kcl.init_wallet_handle(wallet_id, wallet_pswd) # generate two accounts with kmd account_1 = self.kcl.generate_key(handle, False) account_2 = self.kcl.generate_key(handle, False) # get their private keys private_key_1 = self.kcl.export_key(handle, wallet_pswd, account_1) private_key_2 = self.kcl.export_key(handle, wallet_pswd, account_2) # get suggested parameters and fee gh = self.acl.versions()['genesis_hash_b64'] rnd = int(self.acl.status()['lastRound']) sp = transaction.SuggestedParams(0, rnd, rnd + 100, gh) # create multisig account and transaction msig = transaction.Multisig(1, 2, [account_1, account_2]) txn = transaction.PaymentTxn(msig.address(), sp, self.account_0, 1000) # check that the multisig account is valid msig.validate() # import multisig account msig_address = self.kcl.import_multisig(handle, msig) # export multisig account exported = self.kcl.export_multisig(handle, msig_address) self.assertEqual(len(exported.subsigs), 2) # create multisig transaction mtx = transaction.MultisigTransaction(txn, msig) # sign using kmd msig_1 = self.kcl.sign_multisig_transaction(handle, wallet_pswd, account_1, mtx) signed_kmd = self.kcl.sign_multisig_transaction( handle, wallet_pswd, account_2, msig_1) # sign offline mtx1 = transaction.MultisigTransaction(txn, msig) mtx1.sign(private_key_1) mtx2 = transaction.MultisigTransaction(txn, msig) mtx2.sign(private_key_2) signed_account = transaction.MultisigTransaction.merge([mtx1, mtx2]) # check that they are the same self.assertEqual(encoding.msgpack_encode(signed_account), encoding.msgpack_encode(signed_kmd)) # delete accounts del_1 = self.kcl.delete_key(handle, wallet_pswd, account_1) del_2 = self.kcl.delete_key(handle, wallet_pswd, account_2) del_3 = self.kcl.delete_multisig(handle, wallet_pswd, msig_address) self.assertTrue(del_1) self.assertTrue(del_2) self.assertTrue(del_3)