Skip to content

add more examples scripts #399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/more_examples/.env-example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
network="testnet"
wallet_mnemonic="select calm scorpion mask furnace nerve fade slam bid suggest avoid remove half depend turn little midnight fossil submit cart sick glance inner slide"
blockfrost_api_key="preprod...."
5 changes: 5 additions & 0 deletions examples/more_examples/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.env
/keys/*
!keys/.gitkeep
tempfile.pdf
tempfile_copy.pdf
78 changes: 78 additions & 0 deletions examples/more_examples/01_address.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import os

from blockfrost import ApiError, ApiUrls, BlockFrostApi, BlockFrostIPFS
from dotenv import load_dotenv

from pycardano import *

load_dotenv()
network = os.getenv("network")
wallet_mnemonic = os.getenv("wallet_mnemonic")


if network == "testnet":
base_url = ApiUrls.preprod.value
cardano_network = Network.TESTNET
else:
base_url = ApiUrls.mainnet.value
cardano_network = Network.MAINNET


new_wallet = crypto.bip32.HDWallet.from_mnemonic(wallet_mnemonic)
payment_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/0/0")
staking_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/2/0")
payment_skey = ExtendedSigningKey.from_hdwallet(payment_key)
staking_skey = ExtendedSigningKey.from_hdwallet(staking_key)


print("Enterprise address (only payment):")
print("Payment Derivation path: m/1852'/1815'/0'/0/0")

enterprise_address = Address(
payment_part=payment_skey.to_verification_key().hash(), network=cardano_network
)
print(enterprise_address)

print(" ")
print("Staking enabled address:")
print("Payment Derivation path: m/1852'/1815'/0'/0/0")
print("Staking Derivation path: m/1852'/1815'/0'/2/0")

staking_enabled_address = Address(
payment_part=payment_skey.to_verification_key().hash(),
staking_part=staking_skey.to_verification_key().hash(),
network=cardano_network,
)
print(staking_enabled_address)

print(" ")
next_step = input("Press Enter to continue...")
print(" ")

for i in range(5):
derivation_path = f"m/1852'/1815'/0'/0/{i}"

payment_key = new_wallet.derive_from_path(derivation_path)
payment_skey = ExtendedSigningKey.from_hdwallet(payment_key)

enterprise_address = Address(
payment_part=payment_skey.to_verification_key().hash(), network=cardano_network
)
print(f"Address {derivation_path}: {enterprise_address}")

print(" ")
next_step = input("Press Enter to continue...")
print(" ")

for i in range(5):
derivation_path = f"m/1852'/1815'/0'/0/{i}"

payment_key = new_wallet.derive_from_path(derivation_path)
payment_skey = ExtendedSigningKey.from_hdwallet(payment_key)

staking_enabled_address = Address(
payment_part=payment_skey.to_verification_key().hash(),
staking_part=staking_skey.to_verification_key().hash(),
network=cardano_network,
)
print(f"Address {derivation_path}: {staking_enabled_address}")
67 changes: 67 additions & 0 deletions examples/more_examples/02_query_address.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import os
import sys

from blockfrost import ApiError, ApiUrls, BlockFrostApi, BlockFrostIPFS
from dotenv import load_dotenv

from pycardano import *

load_dotenv()
network = os.getenv("network")
wallet_mnemonic = os.getenv("wallet_mnemonic")
blockfrost_api_key = os.getenv("blockfrost_api_key")


if network == "testnet":
base_url = ApiUrls.preprod.value
cardano_network = Network.TESTNET
else:
base_url = ApiUrls.mainnet.value
cardano_network = Network.MAINNET


new_wallet = crypto.bip32.HDWallet.from_mnemonic(wallet_mnemonic)
payment_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/0/0")
staking_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/2/0")
payment_skey = ExtendedSigningKey.from_hdwallet(payment_key)
staking_skey = ExtendedSigningKey.from_hdwallet(staking_key)


main_address = Address(
payment_part=payment_skey.to_verification_key().hash(),
staking_part=staking_skey.to_verification_key().hash(),
network=cardano_network,
)

print(" ")
print(f"Derived address: {main_address}")
print(" ")

api = BlockFrostApi(project_id=blockfrost_api_key, base_url=base_url)

try:
utxos = api.address_utxos(main_address)
except Exception as e:
if e.status_code == 404:
print("Address does not have any UTXOs. ")
if network == "testnet":
print(
"Request tADA from the faucet: https://docs.cardano.org/cardano-testnets/tools/faucet/"
)
else:
print(e.message)
sys.exit(1)

print(f"hash \t\t\t\t\t\t\t\t\t amount")
print(
"--------------------------------------------------------------------------------------"
)

for utxo in utxos:
tokens = ""
for token in utxo.amount:
if token.unit != "lovelace":
tokens += f"{token.quantity} {token.unit} + "
print(
f"{utxo.tx_hash}#{utxo.tx_index} \t {int(utxo.amount[0].quantity)/1000000} ADA [{tokens}]"
)
70 changes: 70 additions & 0 deletions examples/more_examples/03_distribute.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import os
import sys

from blockfrost import ApiError, ApiUrls, BlockFrostApi, BlockFrostIPFS
from dotenv import load_dotenv

from pycardano import *

load_dotenv()
network = os.getenv("network")
wallet_mnemonic = os.getenv("wallet_mnemonic")
blockfrost_api_key = os.getenv("blockfrost_api_key")


if network == "testnet":
base_url = ApiUrls.preprod.value
cardano_network = Network.TESTNET
else:
base_url = ApiUrls.mainnet.value
cardano_network = Network.MAINNET


new_wallet = crypto.bip32.HDWallet.from_mnemonic(wallet_mnemonic)
payment_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/0/0")
staking_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/2/0")
payment_skey = ExtendedSigningKey.from_hdwallet(payment_key)
staking_skey = ExtendedSigningKey.from_hdwallet(staking_key)


main_address = Address(
payment_part=payment_skey.to_verification_key().hash(),
staking_part=staking_skey.to_verification_key().hash(),
network=cardano_network,
)

print(" ")
print(f"Derived address: {main_address}")
print(" ")

api = BlockFrostApi(project_id=blockfrost_api_key, base_url=base_url)

try:
utxos = api.address_utxos(main_address)
except Exception as e:
if e.status_code == 404:
print("Address does not have any UTXOs. ")
if network == "testnet":
print(
"Request tADA from the faucet: https://docs.cardano.org/cardano-testnets/tools/faucet/"
)
else:
print(e.message)
sys.exit(1)


cardano = BlockFrostChainContext(project_id=blockfrost_api_key, base_url=base_url)

builder = TransactionBuilder(cardano)

for i in range(20):
output = TransactionOutput(main_address, Value(4000000))
builder.add_output(output)

builder.add_input_address(main_address)
signed_tx = builder.build_and_sign([payment_skey], change_address=main_address)
result = cardano.submit_tx(signed_tx.to_cbor())
print(f"Number of inputs: \t {len(signed_tx.transaction_body.inputs)}")
print(f"Number of outputs: \t {len(signed_tx.transaction_body.outputs)}")
print(f"Fee: \t\t\t {signed_tx.transaction_body.fee/1000000} ADA")
print(f"Transaction submitted! ID: {result}")
106 changes: 106 additions & 0 deletions examples/more_examples/04_consolidate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import os
import sys

from blockfrost import ApiError, ApiUrls, BlockFrostApi, BlockFrostIPFS
from dotenv import load_dotenv

from pycardano import *

load_dotenv()
network = os.getenv("network")
wallet_mnemonic = os.getenv("wallet_mnemonic")
blockfrost_api_key = os.getenv("blockfrost_api_key")


if network == "testnet":
base_url = ApiUrls.preprod.value
cardano_network = Network.TESTNET
else:
base_url = ApiUrls.mainnet.value
cardano_network = Network.MAINNET


new_wallet = crypto.bip32.HDWallet.from_mnemonic(wallet_mnemonic)
payment_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/0/0")
staking_key = new_wallet.derive_from_path(f"m/1852'/1815'/0'/2/0")
payment_skey = ExtendedSigningKey.from_hdwallet(payment_key)
staking_skey = ExtendedSigningKey.from_hdwallet(staking_key)


main_address = Address(
payment_part=payment_skey.to_verification_key().hash(),
staking_part=staking_skey.to_verification_key().hash(),
network=cardano_network,
)

print(" ")
print(f"Derived address: {main_address}")
print(" ")

api = BlockFrostApi(project_id=blockfrost_api_key, base_url=base_url)

try:
utxos = api.address_utxos(main_address)
except Exception as e:
if e.status_code == 404:
print("Address does not have any UTXOs. ")
if network == "testnet":
print(
"Request tADA from the faucet: https://docs.cardano.org/cardano-testnets/tools/faucet/"
)
else:
print(e.message)
sys.exit(1)


cardano = BlockFrostChainContext(project_id=blockfrost_api_key, base_url=base_url)

builder = TransactionBuilder(cardano)

inputs = []

total_ada_used = 0

for utxo in utxos:
input = TransactionInput.from_primitive([utxo.tx_hash, utxo.tx_index])
inputs.append(input)
builder.add_input(input)
total_ada_used += int(utxo.amount[0].quantity)

output = TransactionOutput(main_address, Value(total_ada_used))

tx_body = TransactionBody(inputs=inputs, outputs=[output], fee=100000)

signature = payment_skey.sign(tx_body.hash())
vk = PaymentVerificationKey.from_signing_key(payment_skey)
vk_witnesses = [VerificationKeyWitness(vk, signature)]
signed_tx = Transaction(tx_body, TransactionWitnessSet(vkey_witnesses=vk_witnesses))

calculated_fee = fee(cardano, len(signed_tx.to_cbor()))


total_ada_available = total_ada_used - calculated_fee
output = TransactionOutput(main_address, Value(total_ada_available))

tx_body = TransactionBody(inputs=inputs, outputs=[output], fee=calculated_fee)

signature = payment_skey.sign(tx_body.hash())
vk = PaymentVerificationKey.from_signing_key(payment_skey)
vk_witnesses = [VerificationKeyWitness(vk, signature)]
signed_tx = Transaction(tx_body, TransactionWitnessSet(vkey_witnesses=vk_witnesses))

try:
result = cardano.submit_tx(signed_tx.to_cbor())
print(f"Number of inputs: \t {len(signed_tx.transaction_body.inputs)}")
print(f"Number of outputs: \t {len(signed_tx.transaction_body.outputs)}")
print(f"Fee: \t\t\t {signed_tx.transaction_body.fee/1000000} ADA")
print(f"Transaction submitted! ID: {result}")
except Exception as e:
if "BadInputsUTxO" in str(e):
print("Trying to spend an input that doesn't exist (or no longer exist).")
elif "ValueNotConservedUTxO" in str(e):
print(
"Transaction not correctly balanced. Inputs and outputs (+fee) don't match."
)
else:
print(e)
Loading
Loading