Ejemplo n.º 1
0
def transfer_token1_token2_to_user(token1_asset_id, token2_asset_id):
    print(
        f"Transferring {int(TOKEN1_AMOUNT/2)} {TOKEN1_ASSET_NAME} ({TOKEN1_UNIT_NAME}) with Asset ID: {token1_asset_id} and {int(TOKEN2_AMOUNT/2)} {TOKEN2_ASSET_NAME} ({TOKEN2_UNIT_NAME}) with Asset ID: {token2_asset_id} to User..."
    )

    txn_1 = transaction.AssetTransferTxn(
        sender=DEVELOPER_ACCOUNT_ADDRESS,
        sp=algod_client.suggested_params(),
        receiver=TEST_ACCOUNT_ADDRESS,
        amt=int(TOKEN1_AMOUNT / 2),
        index=token1_asset_id).sign(DEVELOPER_ACCOUNT_PRIVATE_KEY)

    txn_2 = transaction.AssetTransferTxn(
        sender=DEVELOPER_ACCOUNT_ADDRESS,
        sp=algod_client.suggested_params(),
        receiver=TEST_ACCOUNT_ADDRESS,
        amt=int(TOKEN2_AMOUNT / 2),
        index=token2_asset_id).sign(DEVELOPER_ACCOUNT_PRIVATE_KEY)

    tx_id_1 = algod_client.send_transaction(txn_1)
    tx_id_2 = algod_client.send_transaction(txn_2)

    wait_for_transaction(tx_id_1)
    wait_for_transaction(tx_id_2)

    print(
        f"Transferred {int(TOKEN1_AMOUNT/2)} {TOKEN1_ASSET_NAME} ({TOKEN1_UNIT_NAME}) with Asset ID: {token1_asset_id} to User successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id_1}"
    )

    print(
        f"Transferred {int(TOKEN2_AMOUNT/2)} {TOKEN2_ASSET_NAME} ({TOKEN2_UNIT_NAME}) with Asset ID: {token2_asset_id} to User successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id_2}"
    )

    print()
Ejemplo n.º 2
0
def opt_escrow_into_token(escrow_logicsig, token_idx):
    print(f"Opting Escrow into Token with Asset ID: {token_idx}...")
    program = base64.b64decode(escrow_logicsig)

    lsig = transaction.LogicSig(program)

    txn = transaction.AssetTransferTxn(
        sender=lsig.address(),
        sp=algod_client.suggested_params(),
        receiver=lsig.address(),
        amt=0,
        index=token_idx,
    )

    lsig_txn = transaction.LogicSigTransaction(txn, lsig)

    tx_id = algod_client.send_transaction(lsig_txn)

    wait_for_transaction(tx_id)

    print(
        f"Opted Escrow into Token with Asset ID: {token_idx} successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id}"
    )

    print()
Ejemplo n.º 3
0
def transfer_liquidity_token_to_escrow(liquidity_token_asset_id,
                                       escrow_logicsig):
    print(
        f"Transferring {LIQUIDITY_TOKEN_AMOUNT} liquidity token with Asset ID: {liquidity_token_asset_id} to Escrow..."
    )

    program = base64.b64decode(escrow_logicsig)

    lsig = transaction.LogicSig(program)

    txn = transaction.AssetTransferTxn(
        sender=DEVELOPER_ACCOUNT_ADDRESS,
        sp=algod_client.suggested_params(),
        receiver=lsig.address(),
        amt=LIQUIDITY_TOKEN_AMOUNT,
        index=liquidity_token_asset_id).sign(DEVELOPER_ACCOUNT_PRIVATE_KEY)

    tx_id = algod_client.send_transaction(txn)

    wait_for_transaction(tx_id)

    print(
        f"Transferred {LIQUIDITY_TOKEN_AMOUNT} liquidity token with Asset ID: {liquidity_token_asset_id} to Escrow successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id}"
    )

    print()
def withdraw_liquidity():
    print("Building withdraw liquidity atomic transaction group...")

    encoded_app_args = [
        bytes("w", "utf-8"),
        bytes("5", "utf-8"),
        bytes("5", "utf-8"),
    ]

    # Transaction to Validator
    txn_1 = transaction.ApplicationCallTxn(
        sender=TEST_ACCOUNT_ADDRESS,
        sp=algod_client.suggested_params(),
        index=VALIDATOR_INDEX,
        on_complete=transaction.OnComplete.NoOpOC,
        accounts=[ESCROW_ADDRESS],
        app_args=encoded_app_args,
    )

    # Transaction to Manager
    txn_2 = transaction.ApplicationCallTxn(
        sender=TEST_ACCOUNT_ADDRESS,
        sp=algod_client.suggested_params(),
        index=MANAGER_INDEX,
        on_complete=transaction.OnComplete.NoOpOC,
        accounts=[ESCROW_ADDRESS],
        app_args=encoded_app_args,
    )

    # Transaction to Escrow
    txn_3 = transaction.AssetTransferTxn(
        sender=TEST_ACCOUNT_ADDRESS,
        sp=algod_client.suggested_params(),
        receiver=ESCROW_ADDRESS,
        amt=TOKEN_AMOUNT,
        index=LIQUIDITY_TOKEN_INDEX
    )

    # Get group ID and assign to transactions
    gid = transaction.calculate_group_id([txn_1, txn_2, txn_3])
    txn_1.group = gid
    txn_2.group = gid
    txn_3.group = gid

    # Sign transactions
    stxn_1 = txn_1.sign(TEST_ACCOUNT_PRIVATE_KEY)
    stxn_2 = txn_2.sign(TEST_ACCOUNT_PRIVATE_KEY)
    stxn_3 = txn_3.sign(TEST_ACCOUNT_PRIVATE_KEY)

    # Broadcast the transactions
    signed_txns = [stxn_1, stxn_2, stxn_3]
    tx_id = algod_client.send_transactions(signed_txns)

    # Wait for transaction
    wait_for_transaction(tx_id)

    print(f"Withdraw liquidity transaction sent from User to AlgoSwap successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id}")

    print()
Ejemplo n.º 5
0
def revoke_txn(context, amount):
    params = context.acl.suggested_params_as_object()
    context.txn = transaction.AssetTransferTxn(context.pk,
                                               params,
                                               context.pk,
                                               int(amount),
                                               context.asset_index,
                                               revocation_target=context.rcv)
Ejemplo n.º 6
0
 def axfer(self,
           sender,
           receiver,
           amt: int,
           index: int,
           send=None,
           **kwargs):
     params = self.algod.suggested_params()
     tx = txn.AssetTransferTxn(sender, params, receiver, amt, index,
                               **kwargs)
     return self.finish(tx, send)
Ejemplo n.º 7
0
def escrow_opt_in_to_asset(
    client,
    suggested_params,
    address,
    asset_index,
):
    lsig = transaction.LogicSig(
        compile_program(client,
                        open('./contracts/escrow.teal', 'rb').read()))
    asset_opt_in = transaction.AssetTransferTxn(address, suggested_params,
                                                address, 0, asset_index)
    signed_asset_opt_in = transaction.LogicSigTransaction(asset_opt_in, lsig)
    tx_id = client.send_transactions([signed_asset_opt_in])
    return tx_id
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
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️")
Ejemplo n.º 11
0
def opt_user_into_token(asset_id):
    print(f"Opting user into token with Asset ID: {asset_id}...")

    txn = transaction.AssetTransferTxn(
        sender=TEST_ACCOUNT_ADDRESS,
        sp=algod_client.suggested_params(),
        receiver=TEST_ACCOUNT_ADDRESS,
        amt=0,
        index=asset_id).sign(TEST_ACCOUNT_PRIVATE_KEY)

    tx_id = algod_client.send_transaction(txn)

    wait_for_transaction(tx_id)

    print(
        f"Opted user into token with Asset ID: {asset_id} successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id}"
    )

    print()
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
def claim_card(algod_client: algod.AlgodClient, claimer: Account):
    params = algod_client.suggested_params()

    proof_crown_ownership = proof_asa_amount_eq_txn(
        algod_client=algod_client,
        sender=claimer,
        asa_id=CROWN_ID,
        asa_amount=1,
    )

    proof_sceptre_ownership = proof_asa_amount_eq_txn(
        algod_client=algod_client,
        sender=claimer,
        asa_id=SCEPTRE_ID,
        asa_amount=1,
    )

    nft_card_xfer = transaction.AssetTransferTxn(
        sender=CARD_CONTRACT.address,
        sp=params,
        receiver=claimer.address,
        amt=1,
        index=CARD_ID,
        revocation_target=CARD_CONTRACT.address,
    )

    signed_group = group_and_sign(
        [claimer, claimer, CARD_CONTRACT],
        [proof_crown_ownership, proof_sceptre_ownership, nft_card_xfer],
    )

    try:
        gtxn_id = algod_client.send_transactions(signed_group)
        wait_for_confirmation(algod_client, gtxn_id)
    except AlgodHTTPError:
        quit("\nOnly the generous heart of the Great Majesty of Algorand "
             "can break the spell!\n"
             "Conquer both the 👑 Crown of Entropy and the 🪄 Sceptre "
             "of Proof first!\n")
Ejemplo n.º 14
0
def transfer_assets_to_creator(context, amount):
    params = context.acl.suggested_params_as_object()
    context.txn = transaction.AssetTransferTxn(context.rcv, params, context.pk,
                                               int(amount),
                                               context.asset_index)
Ejemplo n.º 15
0
# Example: accepting assets

from algosdk import account
from algosdk.future import transaction

private_key, address = account.generate_account()

fee_per_byte = 10
first_valid_round = 1000
last_valid_round = 2000
genesis_hash = "SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="
receiver = address  # to start accepting assets, set receiver to sender
amount = 0  # to start accepting assets, set amount to 0

index = 1234  # identifying index of the asset

# create the asset accept transaction
sp = transaction.SuggestedParams(fee_per_byte, first_valid_round,
                                 last_valid_round, genesis_hash)
txn = transaction.AssetTransferTxn(address, sp, receiver, amount, index)

# sign the transaction
signed_txn = txn.sign(private_key)
Ejemplo n.º 16
0
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
def withdraw_protocol_fees():
    print("Building withdraw protocol fees atomic transaction group...")

    encoded_app_args = [bytes("p", "utf-8")]

    # Get unclaimed TOKEN1 and TOKEN2 protocol fees
    protocol_unused_token1 = protocol_unused_token2 = 0
    account_info = algod_client.account_info(ESCROW_ADDRESS)
    local_state = account_info['apps-local-state']
    for block in local_state:
        if block['id'] == MANAGER_INDEX:
            for kvs in block['key-value']:
                decoded_key = base64.b64decode(kvs['key'])
                prefix_bytes = decoded_key[:2]
                prefix_key = prefix_bytes.decode('utf-8')

                if (prefix_key == "P1"):
                    protocol_unused_token1 = kvs['value']['uint']
                elif (prefix_key == "P2"):
                    protocol_unused_token2 = kvs['value']['uint']

    print(
        f"Unused Protocol Fees is Token 1 = {protocol_unused_token1} and Token 2 = {protocol_unused_token2}"
    )

    if protocol_unused_token1 != 0 and protocol_unused_token2 != 0:
        # Transaction to Validator
        txn_1 = transaction.ApplicationCallTxn(
            sender=DEVELOPER_ACCOUNT_ADDRESS,
            sp=algod_client.suggested_params(),
            index=VALIDATOR_INDEX,
            on_complete=transaction.OnComplete.NoOpOC,
            accounts=[ESCROW_ADDRESS],
            app_args=encoded_app_args)

        # Transaction to Manager
        txn_2 = transaction.ApplicationCallTxn(
            sender=DEVELOPER_ACCOUNT_ADDRESS,
            sp=algod_client.suggested_params(),
            index=MANAGER_INDEX,
            on_complete=transaction.OnComplete.NoOpOC,
            accounts=[ESCROW_ADDRESS],
            app_args=encoded_app_args)

        # Transaction to send Token 1 from Escrow to Developer
        txn_3 = transaction.AssetTransferTxn(
            sender=ESCROW_ADDRESS,
            sp=algod_client.suggested_params(),
            receiver=DEVELOPER_ACCOUNT_ADDRESS,
            amt=protocol_unused_token1,
            index=TOKEN1_INDEX)

        # Transaction to send Token 2 from Escrow to Developer
        txn_4 = transaction.AssetTransferTxn(
            sender=ESCROW_ADDRESS,
            sp=algod_client.suggested_params(),
            receiver=DEVELOPER_ACCOUNT_ADDRESS,
            amt=protocol_unused_token2,
            index=TOKEN2_INDEX)

        # Make Logicsig
        program = base64.b64decode(ESCROW_LOGICSIG)
        lsig = transaction.LogicSig(program)

        # Get group ID and assign to transactions
        gid = transaction.calculate_group_id([txn_1, txn_2, txn_3, txn_4])
        txn_1.group = gid
        txn_2.group = gid
        txn_3.group = gid
        txn_4.group = gid

        # Sign transactions
        stxn_1 = txn_1.sign(DEVELOPER_ACCOUNT_PRIVATE_KEY)
        stxn_2 = txn_2.sign(DEVELOPER_ACCOUNT_PRIVATE_KEY)
        stxn_3 = transaction.LogicSigTransaction(txn_3, lsig)
        stxn_4 = transaction.LogicSigTransaction(txn_4, lsig)

        # Broadcast the transactions
        signed_txns = [stxn_1, stxn_2, stxn_3, stxn_4]
        tx_id = algod_client.send_transactions(signed_txns)

        # Wait for transaction
        wait_for_transaction(tx_id)

        print(
            f"Withdrew protocol fees for Token 1 and Token 2 from AlgoSwap to Developer successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id}"
        )
    print()
Ejemplo n.º 18
0
def get_token1_refund():
    print("Attempting to get refund of Token 1 from Escrow...")

    encoded_app_args = [bytes("r", "utf-8")]

    # Calculate unused_token1
    unused_token1 = 0
    account_info = algod_client.account_info(TEST_ACCOUNT_ADDRESS)
    local_state = account_info['apps-local-state']
    for block in local_state:
        if block['id'] == MANAGER_INDEX:
            for kvs in block['key-value']:
                decoded_key = base64.b64decode(kvs['key'])
                prefix_bytes = decoded_key[:2]
                prefix_key = prefix_bytes.decode('utf-8')
                addr_bytes = decoded_key[2:]
                b32_encoded_addr = base64.b32encode(addr_bytes).decode('utf-8')
                escrow_addr = encoding.encode_address(
                    base64.b32decode(b32_encoded_addr))

                if (prefix_key == "U1" and ESCROW_ADDRESS == escrow_addr):
                    unused_token1 = int(kvs['value']['uint'])

    print(f"User unused Token 1 is {unused_token1}")

    if unused_token1 != 0:
        # Transaction to Validator
        txn_1 = transaction.ApplicationCallTxn(
            sender=TEST_ACCOUNT_ADDRESS,
            sp=algod_client.suggested_params(),
            index=VALIDATOR_INDEX,
            on_complete=transaction.OnComplete.NoOpOC,
            accounts=[ESCROW_ADDRESS],
            app_args=encoded_app_args)

        # Transaction to Manager
        txn_2 = transaction.ApplicationCallTxn(
            sender=TEST_ACCOUNT_ADDRESS,
            sp=algod_client.suggested_params(),
            index=MANAGER_INDEX,
            on_complete=transaction.OnComplete.NoOpOC,
            accounts=[ESCROW_ADDRESS],
            app_args=encoded_app_args)

        # Make LogicSig
        program = base64.b64decode(ESCROW_LOGICSIG)
        lsig = transaction.LogicSig(program)

        # Transaction to get refund of Token 1 from Escrow
        txn_3 = transaction.AssetTransferTxn(
            sender=ESCROW_ADDRESS,
            sp=algod_client.suggested_params(),
            receiver=TEST_ACCOUNT_ADDRESS,
            amt=unused_token1,
            index=TOKEN1_INDEX)

        # Get group ID and assign to transactions
        gid = transaction.calculate_group_id([txn_1, txn_2, txn_3])
        txn_1.group = gid
        txn_2.group = gid
        txn_3.group = gid

        # Sign transactions
        stxn_1 = txn_1.sign(TEST_ACCOUNT_PRIVATE_KEY)
        stxn_2 = txn_2.sign(TEST_ACCOUNT_PRIVATE_KEY)
        stxn_3 = transaction.LogicSigTransaction(txn_3, lsig)

        # Broadcast the transactions
        signed_txns = [stxn_1, stxn_2, stxn_3]
        tx_id = algod_client.send_transactions(signed_txns)

        print(
            f"Got refund of Token 1 from AlgoSwap to User successfully! Tx ID: https://testnet.algoexplorer.io/tx/{tx_id}"
        )

    print()
Ejemplo n.º 19
0
def accept_asset_txn(context):
    params = context.acl.suggested_params_as_object()
    context.txn = transaction.AssetTransferTxn(context.rcv, params,
                                               context.rcv, 0,
                                               context.asset_index)
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)))
Ejemplo n.º 21
0
# Example: sending assets

from algosdk import account
from algosdk.future import transaction

sender_private_key, sender_address = account.generate_account()

fee_per_byte = 10
first_valid_round = 1000
last_valid_round = 2000
genesis_hash = "SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="
_, close_assets_to = account.generate_account()
_, receiver = account.generate_account()
amount = 100  # amount of assets to transfer

index = 1234  # identifying index of the asset

# create the asset transfer transaction
sp = transaction.SuggestedParams(fee_per_byte, first_valid_round,
                                 last_valid_round, genesis_hash)
txn = transaction.AssetTransferTxn(sender_address, sp, receiver, amount, index,
                                   close_assets_to)

# sign the transaction
signed_txn = txn.sign(sender_private_key)
Ejemplo n.º 22
0
# Example: revoking assets

from algosdk import account
from algosdk.future import transaction

# this transaction must be sent by the asset's clawback manager
clawback_private_key, clawback_address = account.generate_account()

fee_per_byte = 10
first_valid_round = 1000
last_valid_round = 2000
genesis_hash = "SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="
_, receiver = account.generate_account()  # where to send the revoked assets
_, target = account.generate_account()  # address to revoke assets from
amount = 100

index = 1234  # identifying index of the asset

# create the asset transfer transaction
sp = transaction.SuggestedParams(fee_per_byte, first_valid_round,
                                 last_valid_round, genesis_hash)
txn = transaction.AssetTransferTxn(clawback_address,
                                   sp,
                                   receiver,
                                   amount,
                                   index,
                                   revocation_target=target)

# sign the transaction
signed_txn = txn.sign(clawback_private_key)