Skip to content

Commit

Permalink
Feat: nft collection example for python (#739)
Browse files Browse the repository at this point in the history
* python examples

* Fix examples

* added counter

---------

Co-authored-by: Thoralf Müller <[email protected]>
  • Loading branch information
Brord van Wierst and Thoralf-M authored Jul 10, 2023
1 parent 77c0ecc commit 74537b7
Show file tree
Hide file tree
Showing 14 changed files with 139 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ async function run() {
i + NUM_NFTS_MINTED_PER_TRANSACTION,
);

console.log(`Minting ${chunk.length} NFTs...`);
console.log(
`Minting ${chunk.length} NFTs... (${
i + chunk.length
}/${NFT_COLLECTION_SIZE})`,
);
const prepared = await account.prepareMintNfts(chunk);
const transaction = await prepared.send();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@
)

transaction = account.send_outputs([basic_output])
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

block_id = account.retry_transaction_until_included(transaction["transactionId"])
block_id = account.retry_transaction_until_included(transaction.transactionId)

print(
f'Block sent: {os.environ["EXPLORER_URL"]}/block/{block_id}')
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
}]

transaction = account.send(params, {"allowMicroAmount": True})
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

block_id = account.retry_transaction_until_included(transaction["transactionId"])
block_id = account.retry_transaction_until_included(transaction.transactionId)

print(
f'Block sent: {os.environ["EXPLORER_URL"]}/block/{block_id}')
2 changes: 1 addition & 1 deletion bindings/python/examples/how_tos/native_tokens/burn.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

# Send transaction.
transaction = account.prepare_burn_native_token(token["tokenId"], burn_amount).send()
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction['transactionId'])
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/examples/how_tos/native_tokens/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
if not balance["aliases"]:
# If we don't have an alias, we need to create one
transaction = account.prepare_create_alias_output(None, None).send()
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction.transactionId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

# Send transaction.
transaction = account.prepare_destroy_foundry(foundry_id).send()
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction.transactionId)
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/examples/how_tos/native_tokens/melt.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

# Send transaction.
transaction = account.prepare_melt_native_token(token_id, melt_amount).send()
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction['transactionId'])
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/examples/how_tos/native_tokens/mint.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

# Prepare and send transaction.
transaction = account.prepare_mint_native_token(token_id, mint_amount).send()
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction['transactionId'])
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/examples/how_tos/native_tokens/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
}]

transaction = account.prepare_send_native_tokens(outputs, None).send()
print(f'Transaction sent: {transaction["transactionId"]}')
print(f'Transaction sent: {transaction.transactionId}')

# Wait for transaction to get included
blockId = account.retry_transaction_until_included(transaction['transactionId'])
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from iota_sdk import Wallet, Utils, utf8_to_hex
from dotenv import load_dotenv
import os

load_dotenv()

# In this example we will mint the issuer NFT for the NFT collection.

wallet = Wallet(os.environ['WALLET_DB_PATH'])

if 'STRONGHOLD_PASSWORD' not in os.environ:
raise Exception(".env STRONGHOLD_PASSWORD is undefined, see .env.example")

wallet.set_stronghold_password(os.environ["STRONGHOLD_PASSWORD"])

account = wallet.get_account('Alice')

# Sync account with the node
account.sync()

# Issue the minting transaction and wait for its inclusion
print('Sending NFT minting transaction...')
params = {
"immutableMetadata": utf8_to_hex("This NFT will be the issuer from the awesome NFT collection"),
}

prepared = account.prepare_mint_nfts([params])
transaction = prepared.send()

# Wait for transaction to get included
block_id = account.retry_transaction_until_included(transaction.transactionId)

print(
f'Block sent: {os.environ["EXPLORER_URL"]}/block/{block_id}')

essence = transaction.payload["essence"]

for outputIndex, output in enumerate(essence["outputs"]):
# New minted NFT id is empty in the output
if output["type"] == 6 and output["nftId"] == '0x0000000000000000000000000000000000000000000000000000000000000000':
outputId = Utils.compute_output_id(transaction.transactionId, outputIndex)
nftId = Utils.compute_nft_id(outputId)
print(f'New minted NFT id: {nftId}')
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
from iota_sdk import Wallet, Utils, utf8_to_hex
from dotenv import load_dotenv
import os
import sys
import json

load_dotenv()

# The NFT collection size
NFT_COLLECTION_SIZE = 150
# Mint NFTs in chunks since the transaction size is limited
NUM_NFTS_MINTED_PER_TRANSACTION = 50

# In this example we will mint some collection NFTs with issuer feature.

if len(sys.argv) < 2:
raise Exception("missing example argument: ISSUER_NFT_ID")

issuer_nft_id = sys.argv[1]

wallet = Wallet(os.environ['WALLET_DB_PATH'])

if 'STRONGHOLD_PASSWORD' not in os.environ:
raise Exception(".env STRONGHOLD_PASSWORD is undefined, see .env.example")

wallet.set_stronghold_password(os.environ["STRONGHOLD_PASSWORD"])

account = wallet.get_account('Alice')

# Sync account with the node
account.sync()

bech32_hrp = wallet.get_client().get_bech32_hrp()
issuer = Utils.nft_id_to_bech32(issuer_nft_id, bech32_hrp)

def get_immutable_metadata(index: int, issuer_nft_id: str) -> str:
data = {
"standard": "IRC27",
"version": "v1.0",
"type": "video/mp4",
"uri": "ipfs://wrongcVm9fx47YXNTkhpMEYSxCD3Bqh7PJYr7eo5Ywrong",
"name": "Shimmer OG NFT #" + str(index),
"description": "The Shimmer OG NFT was handed out 1337 times by the IOTA Foundation to celebrate the official launch of the Shimmer Network.",
"issuerName": "IOTA Foundation",
"collectionId": issuer_nft_id,
"collectionName": "Shimmer OG"
}
return json.dumps(data, separators=(',', ':'))

# Create the metadata with another index for each
nft_mint_params = list(map(lambda index: {
"immutableMetadata": utf8_to_hex(get_immutable_metadata(index, issuer_nft_id)),
"issuer": issuer
}, range(NFT_COLLECTION_SIZE)))

while nft_mint_params:
chunk, nft_mint_params = nft_mint_params[:NUM_NFTS_MINTED_PER_TRANSACTION], nft_mint_params[NUM_NFTS_MINTED_PER_TRANSACTION:]
print(f'Minting {len(chunk)} NFTs... ({NFT_COLLECTION_SIZE-len(nft_mint_params)}/{NFT_COLLECTION_SIZE})')
prepared = account.prepare_mint_nfts(chunk)
transaction = prepared.send()

# Wait for transaction to get included
block_id = account.retry_transaction_until_included(transaction.transactionId)

print(
f'Block sent: {os.environ["EXPLORER_URL"]}/block/{block_id}')

# Sync so the new outputs are available again for new transactions
account.sync()
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@
"amount": "1000000",
}]

transaction = account.send(outputs)
transaction = account.send(params)
print(f'Block sent: {os.environ["EXPLORER_URL"]}/block/{transaction.blockId}')
7 changes: 4 additions & 3 deletions bindings/python/iota_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,23 +120,24 @@ def compute_storage_deposit(output, rent) -> HexStr:
"""Computes the required storage deposit of an output.
"""
return _call_method('computeStorageDeposit', {
'inputs': inputs
'output': output,
'rent': rent
})

@staticmethod
def compute_nft_id(output_id: OutputId) -> HexStr:
"""Computes the NFT id for the given NFT output id.
"""
return _call_method('computeNftId', {
'outputId': output_id
'outputId': repr(output_id)
})

@staticmethod
def compute_output_id(transaction_id: HexStr, index: int) -> OutputId:
"""Computes the output id from transaction id and output index.
"""
return OutputId.from_string(_call_method('computeOutputId', {
'transactionId': transaction_id,
'id': transaction_id,
'index': index,
}))

Expand Down
9 changes: 7 additions & 2 deletions sdk/examples/how_tos/nft_collection/01_mint_collection_nft.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,13 @@ async fn main() -> Result<()> {
})
.collect::<Vec<_>>();

for nft_mint_params in nft_mint_params.chunks(NUM_NFTS_MINTED_PER_TRANSACTION) {
println!("Minting {} NFTs...", nft_mint_params.len());
for (index, nft_mint_params) in nft_mint_params.chunks(NUM_NFTS_MINTED_PER_TRANSACTION).enumerate() {
println!(
"Minting {} NFTs... ({}/{})",
nft_mint_params.len(),
index * NUM_NFTS_MINTED_PER_TRANSACTION + nft_mint_params.len(),
NFT_COLLECTION_SIZE
);
let transaction = account.mint_nfts(nft_mint_params.to_vec(), None).await?;
wait_for_inclusion(&transaction.transaction_id, &account).await?;

Expand Down

0 comments on commit 74537b7

Please sign in to comment.