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)
Exemple #2
0
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) 
Exemple #3
0
 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)
Exemple #4
0
def opt_in_app(client, private_key, index):
    # declare sender
    sender = account.address_from_private_key(private_key)
    print("OptIn from account: ", sender)

    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    params.flat_fee = True
    params.fee = 1000

    # create unsigned transaction
    txn = transaction.ApplicationOptInTxn(sender, params, index)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # await confirmation
    wait_for_confirmation(client, tx_id)

    # display results
    transaction_response = client.pending_transaction_info(tx_id)
    print("OptIn to app-id:", transaction_response['txn']['txn']['apid'])
Exemple #5
0
def delete_app(client, private_key, index):
    # declare sender
    sender = account.address_from_private_key(private_key)

    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    # params.flat_fee = True
    # params.fee = 1000

    # create unsigned transaction
    txn = ApplicationDeleteTxn(sender, params, index)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # wait for confirmation
    try:
        transaction_response = wait_for_confirmation(client, tx_id, 4)
        print("TXID: ", tx_id)
        print("Result confirmed in round: {}".format(
            transaction_response['confirmed-round']))

    except Exception as err:
        print(err)
        return

    # display results

    print("Deleted app-id: ", transaction_response['txn']['txn']['apid'])
Exemple #6
0
    def track(self, station: int, temperature: int):
        """
        posts the tracking information to the blockchain
        :param station:
        :param temperature:
        :return:
        """

        # get suggested parameters
        params = self.algod.suggested_params()
        gen = params["genesisID"]
        gh = params["genesishashb64"]
        last_round = params["lastRound"]
        fee = params["fee"]

        note = {'s': station, 't': temperature}

        # create the transaction
        txn = transaction.PaymentTxn(account.address_from_private_key(self.sk),
                                     fee,
                                     last_round,
                                     last_round + 1000,
                                     gh,
                                     self.namespace_address,
                                     0,
                                     note=json.dumps(note).encode())

        # sign it
        stx = txn.sign(self.sk)

        # send it
        return self.algod.send_transaction(
            stx, headers={'content-type': 'application/x-binary'})
def call_app(client, private_key, index, app_args) : 
    # declare sender
    sender = account.address_from_private_key(private_key)
    print("Call from account: ",sender)

	# get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    params.flat_fee = True
    params.fee = 1000

    # create unsigned transaction
    txn = transaction.ApplicationNoOpTxn(sender, params, index, app_args)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # await confirmation
    wait_for_confirmation(client, tx_id)

    # display results
    transaction_response = client.pending_transaction_info(tx_id)
    print("Called app-id: ",transaction_response['txn']['txn']['apid'])
    if "global-state-delta" in transaction_response :
        print("Global State updated :\n",transaction_response['global-state-delta'])
    if "local-state-delta" in transaction_response :
        print("Local State updated :\n",transaction_response['local-state-delta'])
Exemple #8
0
def update_app(client, private_key, app_id, approval_program, clear_program):
    # declare sender
    sender = account.address_from_private_key(private_key)

    # define initial value for key "timestamp"
    app_args = [b'initial value']

    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    # params.flat_fee = True
    # params.fee = 1000

    # create unsigned transaction
    txn = ApplicationUpdateTxn(sender, params, app_id, \
                                            approval_program, clear_program, app_args)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # await confirmation

    confirmed_txn = wait_for_confirmation(client, tx_id, 4)
    print("TXID: ", tx_id)
    print("Result confirmed in round: {}".format(
        confirmed_txn['confirmed-round']))
    # display results
    transaction_response = client.pending_transaction_info(tx_id)
    app_id = transaction_response['txn']['txn']['apid']
    print("Updated existing app-id: ", app_id)
Exemple #9
0
def clear_app(client, private_key, index):
    # declare sender
    sender = account.address_from_private_key(private_key)

    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    # params.flat_fee = True
    # params.fee = 1000

    # create unsigned transaction
    txn = ApplicationClearStateTxn(sender, params, index)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # await confirmation

    confirmed_txn = wait_for_confirmation(client, tx_id, 4)
    print("TXID: ", tx_id)
    print("Result confirmed in round: {}".format(
        confirmed_txn['confirmed-round']))
    # display results
    transaction_response = client.pending_transaction_info(tx_id)
    print("Cleared app-id: ")
    print(json.dumps(transaction_response['txn']['txn']['apid'], indent=2))
Exemple #10
0
def create_app(client, private_key, approval_program, clear_program,
               global_schema, local_schema, app_args):
    # define sender as creator
    sender = account.address_from_private_key(private_key)

    # declare on_complete as NoOp
    on_complete = transaction.OnComplete.NoOpOC.real

    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    params.flat_fee = True
    params.fee = 1000

    # create unsigned transaction
    txn = transaction.ApplicationCreateTxn(sender, params, on_complete, \
                                            approval_program, clear_program, \
                                            global_schema, local_schema, app_args)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # await confirmation
    wait_for_confirmation(client, tx_id)

    # display results
    transaction_response = client.pending_transaction_info(tx_id)
    app_id = transaction_response['application-index']
    print("Created new app-id:", app_id)

    return app_id
Exemple #11
0
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 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 []
Exemple #13
0
def create_app(client, private_key, approval_program_compiled, clear_program,
               global_schema, local_schema):
    # define sender as creator
    sender = account.address_from_private_key(private_key)
    # declare on_complete as NoOp
    on_complete = OnComplete.NoOpOC.real

    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    # params.flat_fee = True
    # params.fee = 1000

    # create unsigned transaction - Create App
    txn = ApplicationCreateTxn(sender, params, on_complete,
                               approval_program_compiled, clear_program,
                               global_schema, local_schema)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # wait for confirmation
    try:
        transaction_response = wait_for_confirmation(client, tx_id, 4)
        print("TXID: ", tx_id)
        print("Result confirmed in round: {}".format(
            transaction_response['confirmed-round']))

    except Exception as err:
        print(err)
        return

    # display results
    app_id = transaction_response['application-index']
    print("Created new app-id: ", app_id)

    return app_id
Exemple #14
0
def get_test_account(update, context):
    """
    Create new public/private key pair
    Returns the result of generating an account to user:
    :param update:
    :param context:
    :return: 1). An Algorand address, 2). A mnemonic seed phrase
    """
    global mn

    update.message.reply_text("Swift!\nYour keys are ready: \n")
    try:
        sk, pk = account.generate_account()
        mn = mnemonic.from_private_key(sk)
        address = account.address_from_private_key(sk)
        update.message.reply_text("Account address/Public key:  {}\n\n"
                                  "Private Key:  {}\n\n"
                                  "Mnemonic:\n {}\n\n"
                                  "I do not hold or manage your keys."
                                  "".format(address, sk, mn))
        context.user_data['default_pk'] = pk
        update.message.reply_text(
            'To test if your address works fine, copy your address, and visit:\n '
        )
        key_board = [[
            InlineKeyboardButton("DISPENSER",
                                 'https://bank.testnet.algorand.network/',
                                 callback_data='1')
        ]]

        dispenser = InlineKeyboardMarkup(key_board)

        update.message.reply_text(
            'the dispenser to get some Algos\nSession ended.'
            'Click /start to begin.',
            reply_markup=dispenser)
        context.user_data.clear()
    except Exception as e:
        update.message.reply_text('Account creation error.')
        return e
Exemple #15
0
def complete_trade(update, context):
    """
    To complete the atomic transaction, Buyer signs and submit half-signed transaction.
    :param update: Telegram obj.
    :param context: Telegram obj.
    :param context: Authorization key from the buyer.
    :return:
    """
    sk = context.user_data['Authorization_key']
    _address = account.address_from_private_key(sk)
    sk_bytes = rf(update, context, _address)
    bt = base64.decodebytes(sk_bytes)
    s = bt.decode()
    key = _address[:10]
    seller = TRANSACTIONS["{}".format(key)]['Seller']
    update.message.reply_text("Completing trade...\nbetween:\nSeller - {} and Buyer - {}".format(seller, _address))
    file = _address[:11]

    if _address in ex_file and _address == TRANSACTIONS["{}".format(key)]['Buyer']:
        rtv = transaction.retrieve_from_file("./asa{}.txn".format(file))
        grid = transaction.calculate_group_id([rtv[0], rtv[1], rtv[2], rtv[3]])
        rtv[0].group = grid
        rtv[1].group = grid
        rtv[2].group = grid
        rtv[3].group = grid

        txn1 = rtv[0].sign(sk)
        txn2 = rtv[1].sign(sk)
        txn3 = rtv[2].sign(s)
        txn4 = rtv[3].sign(s)

        tx_id = client.send_transactions([txn1, txn2, txn3, txn4])
        wait_for_confirmation(update, context, client, tx_id)
    else:
        update.message.reply_text("Trade could not be completed!")
    context.user_data.clear()
    remove_data(update, context, _address)
    return ConversationHandler.conversation_timeout
Exemple #16
0
def call_app(client, private_key, index, app_args):
    # declare sender
    sender = account.address_from_private_key(private_key)
    print("Call from account:", sender)

    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    params.flat_fee = True
    params.fee = 1000

    # create unsigned transaction
    txn = transaction.ApplicationNoOpTxn(sender, params, index, app_args)

    # sign transaction
    signed_txn = txn.sign(private_key)
    tx_id = signed_txn.transaction.get_txid()

    # send transaction
    client.send_transactions([signed_txn])

    # await confirmation
    wait_for_confirmation(client, tx_id)
Exemple #17
0
def add_rekey_to_sk(context):
    context.txn.rekey_to = account.address_from_private_key(context.sk)
Exemple #18
0
def mn_for_sk(context, mn):
    context.mn = mn
    context.sk = mnemonic.to_private_key(mn)
    context.pk = account.address_from_private_key(context.sk)
Exemple #19
0
 def test_encode_decode(self):
     sk, pk = account.generate_account()
     self.assertEqual(pk,
                      encoding.encode_address(encoding.decode_address(pk)))
     self.assertEqual(pk, account.address_from_private_key(sk))
Exemple #20
0
def main():
    if len(sys.argv) == 1:
        # Display help if no arguments, see:
        # https://github.com/docopt/docopt/issues/420#issuecomment-405018014
        sys.argv.append('--help')

    args = docopt(__doc__)

    print(title())

    if args['poem']:
        return print(poem())

    # Clients
    token = args['<purestake-api-token>']
    header = {'X-Api-key': token}

    algod_client = algod.AlgodClient(algod_token=token,
                                     algod_address=ALGOD_ADDRESS,
                                     headers=header)

    indexer_client = indexer.IndexerClient(indexer_token=token,
                                           indexer_address=INDEXER_ADDRESS,
                                           headers=header)

    if args['verify-order']:
        summary = order_summary(algod_client,
                                verify_buy_order(args['<seller-address>']))
        return print(summary)

    if args['dynasty']:
        print(r"""
                                   *** DYNASTY ***
            """)
        return print(*['\n', *history(indexer_client)])

    # Checking mnemonic format
    try:
        assert len(args['<mnemonic>'].split()) == 25
    except AssertionError:
        quit('The mnemonic phrase must contain 25 words, '
             'formatted as: "word_1 word_2 ... word_25"\n')

    private_key = mnemonic.to_private_key(args['<mnemonic>'])

    user = Account(account.address_from_private_key(private_key), private_key)

    if args['claim-crown']:
        opt_in(algod_client, user, CROWN_ID)

        name = args['<majesty-name>']

        claim_nft(
            algod_client=algod_client,
            indexer_client=indexer_client,
            claimer=user,
            claim_arg='Crown',
            new_majesty=name,
            donation_amount=int(args['<microalgos>']),
            nft_id=CROWN_ID,
        )
        print(f"\n👑 Glory to {name}, the Randomic Majesty of Algorand! 🎉\n")

    elif args['claim-sceptre']:
        opt_in(algod_client, user, SCEPTRE_ID)

        name = args['<majesty-name>']

        claim_nft(
            algod_client=algod_client,
            indexer_client=indexer_client,
            claimer=user,
            claim_arg='Sceptre',
            new_majesty=name,
            donation_amount=int(args['<microalgos>']),
            nft_id=SCEPTRE_ID,
        )
        print(f"\n🪄 Glory to {name}, the Verifiable Majesty of Algorand! 🎉\n")

    elif args['claim-card']:
        if algod_client.status()["last-round"] <= ALGOREALM_CARD_FIRST_BLOCK:
            return print("🔐 The spell can be broken starting from the block "
                         f"{ALGOREALM_CARD_FIRST_BLOCK}... ⏳\n")

        algorelm_card_contract = algod_client.account_info(
            CARD_CONTRACT.address)

        assets = algorelm_card_contract['assets']

        card_nft = list(
            filter(lambda asset: asset['asset-id'] == CARD_ID, assets))[0]

        if card_nft['amount'] == 0:
            return print("🔓 The enchanted coffer is empty! "
                         "The AlgoRealm Special Card has been claimed!\n")

        opt_in(algod_client, user, CARD_ID)

        print("\n✨ Whispering words of wisdom...")
        claim_card(algod_client=algod_client, claimer=user)
        print(f"\n 📜 The spell has been broken! "
              f"The AlgoRealm Special Card is yours! 🎉\n")

    if args['buy-order']:
        opt_in(algod_client, user, CARD_ID)

        amount = int(args['<microalgos>'])

        print(
            f"✏️  Placing order of: {util.microalgos_to_algos(amount)} ALGO\n")

        seller = Account(address=current_owner(indexer_client, CARD_ID),
                         private_key='')

        trade_gtxn = card_order(algod_client=algod_client,
                                buyer=user,
                                seller=seller,
                                price=amount)

        if args['--notify']:
            notify(algod_client, user, seller, trade_gtxn)

        return print(
            "\n📦 Send `trade.gtxn` file to the Seller to finalize the trade!\n"
        )

    if args['sell-card']:
        sell_card(algod_client, user)

    else:
        quit("\nError: read AlgoRealm '--help'!\n")
import os
import base64

from algosdk.v2client import algod, indexer
from algosdk import mnemonic, account, encoding
from algosdk.future import transaction

from helpers import *

ALGOD_ENDPOINT = os.environ['ALGOD_ENDPOINT']
ALGOD_TOKEN = os.environ['ALGOD_TOKEN']
INDEXER_ENDPOINT = os.environ['INDEXER_ENDPOINT']
INDEXER_TOKEN = os.environ['INDEXER_TOKEN']
TEST_ACCOUNT_PRIVATE_KEY = mnemonic.to_private_key(os.environ['TEST_ACCOUNT_PRIVATE_KEY'])
TEST_ACCOUNT_ADDRESS = account.address_from_private_key(TEST_ACCOUNT_PRIVATE_KEY)

ESCROW_LOGICSIG = os.environ['ESCROW_LOGICSIG']
ESCROW_ADDRESS = os.environ['ESCROW_ADDRESS']

VALIDATOR_INDEX = int(os.environ['VALIDATOR_INDEX'])
MANAGER_INDEX = int(os.environ['MANAGER_INDEX'])
TOKEN1_INDEX = int(os.environ['TOKEN1_INDEX'])
TOKEN2_INDEX = int(os.environ['TOKEN2_INDEX'])
LIQUIDITY_TOKEN_INDEX = int(os.environ['LIQUIDITY_TOKEN_INDEX'])

TOKEN_AMOUNT = 500000000

algod_client = algod.AlgodClient(ALGOD_TOKEN, ALGOD_ENDPOINT, headers={
    "x-api-key": ALGOD_TOKEN
})
indexer_client = indexer.IndexerClient(INDEXER_TOKEN, INDEXER_ENDPOINT, headers={
import os
import base64

from algosdk.v2client import algod, indexer
from algosdk import mnemonic, account, encoding
from algosdk.future import transaction

from helpers import *

ALGOD_ENDPOINT = os.environ['ALGOD_ENDPOINT']
ALGOD_TOKEN = os.environ['ALGOD_TOKEN']
INDEXER_ENDPOINT = os.environ['INDEXER_ENDPOINT']
INDEXER_TOKEN = os.environ['INDEXER_TOKEN']
DEVELOPER_ACCOUNT_PRIVATE_KEY = mnemonic.to_private_key(
    os.environ['DEVELOPER_ACCOUNT_PRIVATE_KEY'])
DEVELOPER_ACCOUNT_ADDRESS = account.address_from_private_key(
    DEVELOPER_ACCOUNT_PRIVATE_KEY)

ESCROW_LOGICSIG = os.environ['ESCROW_LOGICSIG']
ESCROW_ADDRESS = os.environ['ESCROW_ADDRESS']

VALIDATOR_INDEX = int(os.environ['VALIDATOR_INDEX'])
MANAGER_INDEX = int(os.environ['MANAGER_INDEX'])
TOKEN1_INDEX = int(os.environ['TOKEN1_INDEX'])
TOKEN2_INDEX = int(os.environ['TOKEN2_INDEX'])

algod_client = algod.AlgodClient(ALGOD_TOKEN,
                                 ALGOD_ENDPOINT,
                                 headers={"x-api-key": ALGOD_TOKEN})
indexer_client = indexer.IndexerClient(INDEXER_TOKEN,
                                       INDEXER_ENDPOINT,
                                       headers={"x-api-key": INDEXER_TOKEN})
Exemple #23
0
def main():

    # program_file_name = "program.teal"

    # --------- compile, debug ,  & send transaction using Python SDK ----------

    # read TEAL program
    # data = load_resource(myprogram)
    algod_address = "http://localhost:4001"
    algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    # algod_address = "http://localhost:8080"
    # algod_token = "8024065d94521d253181cff008c44fa4ae4bdf44f028834cd4b4769a26282de1"

    # create algod clients
    acl = algod.AlgodClient(algod_token, algod_address)

    # compile programs approval_program_source
    # and approval_program_source_refactored
    approval_program_source = compileTeal(approval_program_initial(),
                                          Mode.Application,
                                          version=5)
    write_teal('hello_world.teal', approval_program_source)

    approval_program_refactored_source = compileTeal(
        approval_program_refactored(), Mode.Application, version=5)
    write_teal('hello_world_updated.teal', approval_program_refactored_source)

    clear_program_source = compileTeal(clear_state_program(),
                                       Mode.Application,
                                       version=5)
    write_teal('hello_world_clear.teal', clear_program_source)

    approval_program_compiled = compile_program(acl, approval_program_source)

    clear_program_compiled = compile_program(acl, clear_program_source)

    approval_program_refactored_compiled = compile_program(
        acl, approval_program_refactored_source)

    try:

        app_id = create_app(acl, creator_private_key,
                            approval_program_compiled, clear_program_compiled,
                            global_schema, local_schema)

        # opt-in to application
        opt_in_app(acl, user_private_key, app_id)
        opt_in_app(acl, creator_private_key, app_id)
        # call app from user account updates global storage

        call_app(acl, user_private_key, app_id, None, approval_program_source,
                 'hello_world.teal')

        # read global state of application
        read_global_state(
            acl, account.address_from_private_key(creator_private_key), app_id)

        # update application

        update_app(acl, creator_private_key, app_id,
                   approval_program_refactored_compiled,
                   clear_program_compiled)

        # call application with updated app which updates local storage counter
        call_app(acl, user_private_key, app_id, None,
                 approval_program_refactored_source,
                 'hello_world_updated.teal')

        # read local state of application from user account
        read_local_state(acl,
                         account.address_from_private_key(user_private_key),
                         app_id)

        # close-out from application - removes application from balance record
        close_out_app(acl, user_private_key, app_id)

        # # opt-in again to application
        # opt_in_app(acl, user_private_key, app_id)

        # # call application with arguments
        # call_app(acl, user_private_key, app_id,
        #          None, approval_program_refactored_source, 'hello_world_updated.teal')

        # delete application
        # clears global storage only
        # user must clear local
        delete_app(acl, creator_private_key, app_id)

        # clear application from user account
        # clears local storage
        # clear_app(acl, user_private_key, app_id)

    except Exception as e:
        print(e)
Exemple #24
0
def init_atomic(update, context):
    """
    Utility for setting up an atomic transaction.
    Must be Initiated by the seller of an ASA.
    Can only trade an Algorand Asset for ALGO (Algorand's native currency)
    :return: Boolean - True
    """
    asset = {'DMT2': 13251912}
    default = os.getenv('DEFAULT')
    buyer = context.user_data['buyer_address']
    amount = context.user_data['amount_in_algo']
    amount *= 1000000
    asset_name = context.user_data['asset_name']
    asset_name = asset_name.upper()
    sk = context.user_data['signing_key']
    qty = context.user_data['quantity_in_ASA']
    global ex_file
    if asset_name in asset:
        ex_file = ex_file + (buyer,)
        sell_addr = account.address_from_private_key(sk)
        update.message.reply_text('Setting up trade between: \n' 'Seller: 'f'{sell_addr}' ' and \n' 'buyer' f'{buyer}')
        prms = client.suggested_params()
        fst = prms.first
        lst = fst + 1000
        gn = prms.gen
        gh = prms.gh
        fee = prms.fee
        flat_fee = 1000000
        _fee_qty = 1
        if amount in range(50, 10001):
            flat_fee = flat_fee
            amount = round(amount - flat_fee)
            qty -= _fee_qty
        elif amount > 10000:
            flat_fee = 2
            amount = round(amount - flat_fee)
            _fee_qty = 3
            qty -= _fee_qty
        else:
            flat_fee = flat_fee
            _fee_qty = _fee_qty

        string_b = sk.encode('utf-8')
        d = '%*'.encode('utf-8')
        b_bytes = base64.b64encode(string_b, d)
        write_to_file(update, context, buyer, b_bytes)
        # Payment transaction
        bd_unsigned = transaction.PaymentTxn(buyer, fee, fst, lst, gh, sell_addr, amount, None, None, gn, False, None)
        # Payment transaction (fee)
        bf_unsigned = transaction.PaymentTxn(buyer, fee, fst, lst, gh, default, flat_fee, None, None, gn, False, None)
        # Asset transfer txn
        sd_unsigned = AssetTransferTxn(sell_addr, prms, buyer, qty, asset[asset_name], None, None, None, None)
        # Asset transfer (fee)
        sf_unsigned = AssetTransferTxn(sell_addr, prms, default, _fee_qty, asset[asset_name], None, None, None, None)

        stg_path = os.path.dirname(os.path.realpath(__file__))
        file = buyer[0:11]
        file_name = "./asa{}.txn".format(file)
        wtf = transaction.write_to_file([bd_unsigned, bf_unsigned, sd_unsigned, sf_unsigned], stg_path + file_name)
        key = buyer[:10]
        TRANSACTIONS[f'{key}'] = {
            "Seller": sell_addr,
            "Buyer": buyer,
            "Amount": round(amount/1000000),
            "Asset amount": "{}, You will get {}".format(qty + _fee_qty, qty),
            "Fee": "{} Algos + {} {}".format(_fee_qty, flat_fee, asset_name )
        }
        if wtf:
            update.message.reply_text('Trade successfully initiated\nBuyer should proceed to approve the trade.')
        context.user_data.clear()

    else:
        return update.message.reply_text("Asset not found.")
    return ConversationHandler.conversation_timeout
Exemple #25
0
def call_app(client, private_key_user, index, app_args,
             approval_program_source, teal_file_name):
    # declare sender
    creator = account.address_from_private_key(creator_private_key)
    creatoraccount = client.account_info(creator)
    user = account.address_from_private_key(private_key_user)
    useraccount = client.account_info(user)
    print("Creator account: ", creator)
    print("User account: ", user)
    # get node suggested parameters
    params = client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    # params.flat_fee = True
    # params.fee = 1000

    # create unsigned transaction
    txn = ApplicationNoOpTxn(user, params, index, app_args)

    # sign transaction
    signed_txn = txn.sign(private_key_user)
    tx_id = signed_txn.transaction.get_txid()
    # get dryrun request

    mydrr = dryrun_drr(signed_txn, approval_program_source, creatoraccount,
                       useraccount)
    # write drr
    drr_file_name = "mydrr.dr"
    write_drr(drr_file_name, mydrr)
    print("drr file created ... debugger starting - goto chrome://inspect")

    #  START debugging session
    #  either use from terminal in this folder
    # `tealdbg debug program.teal --dryrun-req mydrr.dr`
    #
    # or use this line to invoke debugger
    # and switch to chrome://inspect to inspect and debug
    # (program execution will continue after debuigging session completes)

    dir_path = os.path.dirname(os.path.realpath(__file__))
    drrpath = os.path.join(dir_path, drr_file_name)
    programpath = os.path.join(dir_path, teal_file_name)

    # stdout, stderr = execute(["tealdbg", "debug", programpath, "--dryrun-req", drrpath])

    # send transaction
    client.send_transactions([signed_txn])

    # wait for confirmation
    try:
        transaction_response = wait_for_confirmation(client, tx_id, 4)
        print("TXID: ", tx_id)
        print("Result confirmed in round: {}".format(
            transaction_response['confirmed-round']))
    except Exception as err:
        print(err)
        return

    # display results

    print("Called app-id: ", transaction_response['txn']['txn']['apid'])
    if "global-state-delta" in transaction_response:
        print("Global State updated :\n")
        print(json.dumps(transaction_response['global-state-delta'], indent=2))
    if "local-state-delta" in transaction_response:
        print("Local State updated :\n")
        print(json.dumps(transaction_response['local-state-delta'], indent=2))
Exemple #26
0
def get_address(mn):
    pk_account_a = mnemonic.to_private_key(mn)
    address = account.address_from_private_key(pk_account_a)
    print("Address :", address)
    return address
Exemple #27
0
# convert passphrase to secret key
sk = mnemonic.to_private_key(passphrase)

# get suggested parameters
params = acl.suggested_params()
gen = params["genesisID"]
gh = params["genesishashb64"]
last_round = params["lastRound"]
fee = params["fee"]

# Set other parameters
amount = 10
note = "Special Dish".encode()
receiver = "receiver Algorand Address"

# create the transaction
txn = transaction.PaymentTxn(account.address_from_private_key(sk),
                             fee,
                             last_round,
                             last_round + 1000,
                             gh,
                             receiver,
                             amount,
                             note=note)

# sign it
stx = txn.sign(sk)

# send it
txid = acl.send_transaction(stx)
    raise
elif len(stdout) < 59:
    print("error in compile teal")
    raise

with open(lsig_fname, "rb") as f:
    teal_bytes = f.read()
lsig = transaction.LogicSig(teal_bytes)

# create algod clients
acl = algod.AlgodClient(params.algod_token, params.algod_address)

# Recover the account that is wanting to delegate signature
passphrase = "patrol crawl rule faculty enemy sick reveal embody trumpet win shy zero ill draw swim excuse tongue under exact baby moral kite spring absent double"
sk = mnemonic.to_private_key(passphrase)
addr = account.address_from_private_key(sk)
print("Dispense at least 201000 microAlgo to {}".format(addr))
input("Make sure you did that. Press Enter to continue...")

# sign the logic signature with an account sk
lsig.sign(sk)

# get suggested parameters
params = acl.suggested_params()
gen = params["genesisID"]
gh = params["genesishashb64"]
startRound = params["lastRound"] - (params["lastRound"] % 1000)
endRound = startRound + 1000
fee = 1000
amount = 200000
receiver = "ZZAF5ARA4MEC5PVDOP64JM5O5MQST63Q2KOY2FLYFLXXD3PFSNJJBYAFZM"
Exemple #29
0
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)

    # declare application state storage (immutable)
    local_ints = 0
    local_bytes = 1
    global_ints = 24  # 4 for setup + 20 for choices. Use a larger number for more choices.
    global_bytes = 1
    global_schema = transaction.StateSchema(global_ints, global_bytes)
    local_schema = transaction.StateSchema(local_ints, local_bytes)

    # get PyTeal approval program
    approval_program_ast = approval_program()
    # compile program to TEAL assembly
    approval_program_teal = compileTeal(approval_program_ast, Mode.Application)
    # compile program to binary
    approval_program_compiled = compile_program(algod_client,
                                                approval_program_teal)

    # get PyTeal clear state program
    clear_state_program_ast = clear_state_program()
    # compile program to TEAL assembly
    clear_state_program_teal = compileTeal(clear_state_program_ast,
                                           Mode.Application)
    # compile program to binary
    clear_state_program_compiled = compile_program(algod_client,
                                                   clear_state_program_teal)

    # configure registration and voting period
    status = algod_client.status()
    regBegin = status['last-round'] + 10
    regEnd = regBegin + 10
    voteBegin = regEnd + 1
    voteEnd = voteBegin + 10

    print(f"Registration rounds: {regBegin} to {regEnd}")
    print(f"Vote rounds: {voteBegin} to {voteEnd}")

    # create list of bytes for app args
    app_args = [
        intToBytes(regBegin),
        intToBytes(regEnd),
        intToBytes(voteBegin),
        intToBytes(voteEnd)
    ]

    # create new application
    app_id = create_app(algod_client, creator_private_key,
                        approval_program_compiled,
                        clear_state_program_compiled, global_schema,
                        local_schema, app_args)

    # read global state of application
    print(
        "Global state:",
        read_global_state(
            algod_client,
            account.address_from_private_key(creator_private_key), app_id))

    # wait for registration period to start
    wait_for_round(algod_client, regBegin)

    # opt-in to application
    opt_in_app(algod_client, user_private_key, app_id)

    wait_for_round(algod_client, voteBegin)

    # call application without arguments
    call_app(algod_client, user_private_key, app_id, [b'vote', b'choiceA'])

    # read local state of application from user account
    print(
        "Local state:",
        read_local_state(algod_client,
                         account.address_from_private_key(user_private_key),
                         app_id))

    # wait for registration period to start
    wait_for_round(algod_client, voteEnd)

    # read global state of application
    global_state = read_global_state(
        algod_client, account.address_from_private_key(creator_private_key),
        app_id)
    print("Global state:", global_state)

    max_votes = 0
    max_votes_choice = None
    for key, value in global_state.items():
        if key not in ('RegBegin', 'RegEnd', 'VoteBegin', 'VoteEnd',
                       'Creator') and isinstance(value, int):
            if value > max_votes:
                max_votes = value
                max_votes_choice = key

    print("The winner is:", max_votes_choice)

    # 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)