Esempio n. 1
0
def destroyAsset(algod_client, alice, asset_id, bob):
    print("--------------------------------------------")
    print("Destroying Alice's token......")
    params = algod_client.suggested_params()
    # comment these two lines if you want to use suggested params
    # params.fee = 1000
    # params.flat_fee = True

    # Asset destroy transaction
    txn = AssetConfigTxn(sender=alice['pk'],
                         sp=params,
                         index=asset_id,
                         strict_empty_address_check=False)

    # Sign with secret key of creator
    stxn = txn.sign(alice['sk'])
    # Send the transaction to the network and retrieve the txid.
    txid = algod_client.send_transaction(stxn)
    print(txid)
    # Wait for the transaction to be confirmed
    confirmed_txn = wait_for_confirmation(algod_client, txid, 4)
    print("TXID: ", txid)
    print("Result confirmed in round: {}".format(
        confirmed_txn['confirmed-round']))
    print("Alice's Token is destroyed.")
def closeout_account(algod_client, account):
    # build transaction
    print("--------------------------------------------")
    print("Closing out account......")
    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 = "closing out account".encode()

    # 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 = PaymentTxn(account["pk"], params, receiver, 0, receiver,
                              note)

    # sign transaction
    signed_txn = unsigned_txn.sign(account["sk"])
    txid = algod_client.send_transaction(signed_txn)
    print('Transaction Info:')
    print("Signed transaction with txID: {}".format(txid))

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

    account_info = algod_client.account_info(account["pk"])
    print("Account balance: {} microAlgos".format(account_info.get('amount')) +
          "\n")
    print("Account Closed")
Esempio n. 3
0
def transferAlgosToBob(algod_client, bob, alice):
    print("--------------------------------------------")
    print("Transfering Algos to Bob....")
    account_info = algod_client.account_info(bob["pk"])
    print("Account balance: {} microAlgos".format(account_info.get('amount')) +
          "\n")

    # build transaction
    params = algod_client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    # params.flat_fee = True
    # params.fee = 1000

    # minimum balance 100000, plus 100000 for asset optin,
    # plus 3000 for 3 tx (optin, transfer, algo closeout) = 203000 microalgos
    # amount = 203000;
    unsigned_txn = PaymentTxn(alice["pk"], params, bob["pk"], 203000)

    # sign transaction
    signed_txn = unsigned_txn.sign(alice['sk'])

    #submit transaction
    txid = algod_client.send_transaction(signed_txn)
    print("Successfully sent transaction with txID: {}".format(txid))

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

    except Exception as err:
        print(err)
        return

    print("Transaction information: {}".format(
        json.dumps(confirmed_txn, indent=4)))

    account_info = algod_client.account_info(bob["pk"])
    print("Account balance: {} microAlgos".format(account_info.get('amount')) +
          "\n")
Esempio n. 4
0
def transferAssets(algod_client, alice, bob, asset_id):
    print("--------------------------------------------")
    print("Transfering Alice's token to Bob......")
    params = algod_client.suggested_params()
    # comment these two lines if you want to use suggested params
    # params.fee = 1000
    # params.flat_fee = True
    txn = AssetTransferTxn(sender=alice['pk'],
                           sp=params,
                           receiver=bob["pk"],
                           amt=100,
                           index=asset_id)
    stxn = txn.sign(alice['sk'])
    txid = algod_client.send_transaction(stxn)
    print(txid)
    # Wait for the transaction to be confirmed
    confirmed_txn = wait_for_confirmation(algod_client, txid, 4)
    print("TXID: ", txid)
    print("Result confirmed in round: {}".format(
        confirmed_txn['confirmed-round']))
    # The balance should now be 10.
    print_asset_holding(algod_client, bob['pk'], asset_id)
Esempio n. 5
0
def optIn(algod_client, bob, asset_id):
    print("--------------------------------------------")
    print("Opt-in for Alice's token......")
    # Check if asset_id is in Bob's asset holdings prior
    # to opt-in
    params = algod_client.suggested_params()
    # comment these two lines if you want to use suggested params
    # params.fee = 1000
    # params.flat_fee = True

    account_info = algod_client.account_info(bob['pk'])
    holding = None
    idx = 0
    for my_account_info in account_info['assets']:
        scrutinized_asset = account_info['assets'][idx]
        idx = idx + 1
        if (scrutinized_asset['asset-id'] == asset_id):
            holding = True
            break

    if not holding:
        # Use the AssetTransferTxn class to transfer assets and opt-in
        txn = AssetTransferTxn(sender=bob['pk'],
                               sp=params,
                               receiver=bob["pk"],
                               amt=0,
                               index=asset_id)
        stxn = txn.sign(bob['sk'])
        txid = algod_client.send_transaction(stxn)
        print(txid)
        # Wait for the transaction to be confirmed
        confirmed_txn = wait_for_confirmation(algod_client, txid, 4)
        print("TXID: ", txid)
        print("Result confirmed in round: {}".format(
            confirmed_txn['confirmed-round']))
        # Now check the asset holding for that account.
        # This should now show a holding with a balance of 0.
        print_asset_holding(algod_client, bob['pk'], asset_id)
Esempio n. 6
0
def create_non_fungible_token():
    # For ease of reference, add account public and private keys to
    # an accounts dict.
    print("--------------------------------------------")
    print("Creating account...")
    accounts = {}
    m = create_account()
    accounts[1] = {}
    accounts[1]['pk'] = mnemonic.to_public_key(m)
    accounts[1]['sk'] = mnemonic.to_private_key(m)

    # Change algod_token and algod_address to connect to a different client
    algod_token = "2f3203f21e738a1de6110eba6984f9d03e5a95d7a577b34616854064cf2c0e7b"
    algod_address = "https://academy-algod.dev.aws.algodev.network/"
    algod_client = algod.AlgodClient(algod_token, algod_address)

    print("--------------------------------------------")
    print("Creating Asset...")
    # CREATE ASSET
    # Get network params for transactions before every transaction.
    params = algod_client.suggested_params()
    # comment these two lines if you want to use suggested params
    # params.fee = 1000
    # params.flat_fee = True

    # JSON file
    dir_path = os.path.dirname(os.path.realpath(__file__))
    f = open(dir_path + '/aliceNFTmetadata.json', "r")

    # Reading from file
    metadataJSON = json.loads(f.read())
    metadataStr = json.dumps(metadataJSON)

    hash = hashlib.new("sha512_256")
    hash.update(b"arc0003/amj")
    hash.update(metadataStr.encode("utf-8"))
    json_metadata_hash = hash.digest()

    # Account 1 creates an asset called latinum and
    # sets Account 1 as the manager, reserve, freeze, and clawback address.
    # Asset Creation transaction
    txn = AssetConfigTxn(sender=accounts[1]['pk'],
                         sp=params,
                         total=1,
                         default_frozen=False,
                         unit_name="ALICE001",
                         asset_name="Alice's Artwork 001",
                         manager=accounts[1]['pk'],
                         reserve=None,
                         freeze=None,
                         clawback=None,
                         strict_empty_address_check=False,
                         url="https://path/to/my/asset/details",
                         metadata_hash=json_metadata_hash,
                         decimals=0)

    # Sign with secret key of creator
    stxn = txn.sign(accounts[1]['sk'])

    # Send the transaction to the network and retrieve the txid.
    txid = algod_client.send_transaction(stxn)
    print("Asset Creation Transaction ID: {}".format(txid))

    # Wait for the transaction to be confirmed
    confirmed_txn = wait_for_confirmation(algod_client, txid, 4)
    print("TXID: ", txid)
    print("Result confirmed in round: {}".format(
        confirmed_txn['confirmed-round']))
    try:
        # Pull account info for the creator
        # account_info = algod_client.account_info(accounts[1]['pk'])
        # get asset_id from tx
        # Get the new asset's information from the creator account
        ptx = algod_client.pending_transaction_info(txid)
        asset_id = ptx["asset-index"]
        print_created_asset(algod_client, accounts[1]['pk'], asset_id)
        print_asset_holding(algod_client, accounts[1]['pk'], asset_id)
    except Exception as e:
        print(e)

    print("--------------------------------------------")
    print(
        "You have successfully created your own Non-fungible token! For the purpose of the demo, we will now delete the asset."
    )
    print("Deleting Asset...")

    # Asset destroy transaction
    txn = AssetConfigTxn(sender=accounts[1]['pk'],
                         sp=params,
                         index=asset_id,
                         strict_empty_address_check=False)

    # Sign with secret key of creator
    stxn = txn.sign(accounts[1]['sk'])
    # Send the transaction to the network and retrieve the txid.
    txid = algod_client.send_transaction(stxn)
    print("Asset Destroy Transaction ID: {}".format(txid))

    # Wait for the transaction to be confirmed
    confirmed_txn = wait_for_confirmation(algod_client, txid, 4)
    print("TXID: ", txid)
    print("Result confirmed in round: {}".format(
        confirmed_txn['confirmed-round']))
    # Asset was deleted.
    try:
        print_asset_holding(algod_client, accounts[1]['pk'], asset_id)
        print_created_asset(algod_client, accounts[1]['pk'], asset_id)
        print("Asset is deleted.")
    except Exception as e:
        print(e)

    print("--------------------------------------------")
    print("Sending closeout transaction back to the testnet dispenser...")
    closeout_account(algod_client, accounts[1])
Esempio n. 7
0
def create_asset(alice):
  # accounts = dictionary holding public key, secret key of accounts.
  # Change algod_token and algod_address to connect to a different client
  algod_token = "2f3203f21e738a1de6110eba6984f9d03e5a95d7a577b34616854064cf2c0e7b"
  algod_address = "https://academy-algod.dev.aws.algodev.network/"
  algod_client = algod.AlgodClient(algod_token, algod_address)

  print("--------------------------------------------")
  print("Creating Asset...")
  # CREATE ASSET
  # Get network params for transactions before every transaction.
  params = algod_client.suggested_params()
  # comment these two lines if you want to use suggested params
  # params.fee = 1000
  # params.flat_fee = True

  # JSON file
  dir_path = os.path.dirname(os.path.realpath(__file__))
  f = open (dir_path + '/aliceAssetMetaData.json', "r")
  
  # Reading from file
  metadataJSON = json.loads(f.read())
  metadataStr = json.dumps(metadataJSON)

  hash = hashlib.new("sha512_256")
  hash.update(b"arc0003/amj")
  hash.update(metadataStr.encode("utf-8"))
  json_metadata_hash = hash.digest()

  # Account 1 creates an asset called ALICEOI and
  # sets Account 1 as the manager, reserve, freeze, and clawback address.
  # Asset Creation transaction
  txn = AssetConfigTxn(
      sender=alice['pk'],
      sp=params,
      total=1000,
      default_frozen=False,
      unit_name="ALICEOI",
      asset_name="Alice's Artwork Coins@arc3",
      manager=alice['pk'],
      reserve=alice['pk'],
      freeze=alice['pk'],
      clawback=alice['pk'],
      url="https://path/to/my/asset/details", 
      metadata_hash=json_metadata_hash,
      decimals=0)

  # Sign with secret key of creator
  stxn = txn.sign(alice['sk'])

  # Send the transaction to the network and retrieve the txid.
  txid = algod_client.send_transaction(stxn)
  print("Asset Creation Transaction ID: {}".format(txid))

  # Wait for the transaction to be confirmed
  confirmed_txn = wait_for_confirmation(algod_client, txid, 4)
  print("TXID: ", txid)
  print("Result confirmed in round: {}".format(confirmed_txn['confirmed-round']))
  try:
      # Pull account info for the creator
      # account_info = algod_client.account_info(accounts[1]['pk'])
      # get asset_id from tx
      # Get the new asset's information from the creator account
      ptx = algod_client.pending_transaction_info(txid)
      asset_id = ptx["asset-index"]
      print_created_asset(algod_client, alice['pk'], asset_id)
      print_asset_holding(algod_client, alice['pk'], asset_id)
  except Exception as e:
      print(e)
  
  return asset_id
Esempio n. 8
0
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")