|
| 1 | +"""An example that demonstrates low-level construction of a transaction.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import pathlib |
| 5 | +import tempfile |
| 6 | +import time |
| 7 | + |
| 8 | +import websocket |
| 9 | +from retry import retry |
| 10 | + |
| 11 | +from pycardano import * |
| 12 | + |
| 13 | + |
| 14 | +class TestMintNFT: |
| 15 | + # Define chain context |
| 16 | + NETWORK = Network.TESTNET |
| 17 | + |
| 18 | + OGMIOS_WS = "ws://localhost:1337" |
| 19 | + |
| 20 | + chain_context = OgmiosChainContext(OGMIOS_WS, Network.TESTNET) |
| 21 | + |
| 22 | + @retry(tries=5, delay=2) |
| 23 | + def check_ogmios(self): |
| 24 | + print(f"Current chain tip: {self.chain_context.last_block_slot}") |
| 25 | + |
| 26 | + def test_mint(self): |
| 27 | + self.check_ogmios() |
| 28 | + chain_context = OgmiosChainContext(self.OGMIOS_WS, Network.TESTNET) |
| 29 | + |
| 30 | + payment_key_path = os.environ.get("PAYMENT_KEY") |
| 31 | + if not payment_key_path: |
| 32 | + raise Exception( |
| 33 | + "Cannot find payment key. Please specify environment variable PAYMENT_KEY" |
| 34 | + ) |
| 35 | + payment_skey = PaymentSigningKey.load(payment_key_path) |
| 36 | + payment_vkey = PaymentVerificationKey.from_signing_key(payment_skey) |
| 37 | + address = Address(payment_vkey.hash(), network=self.NETWORK) |
| 38 | + |
| 39 | + # Load payment keys or create them if they don't exist |
| 40 | + def load_or_create_key_pair(base_dir, base_name): |
| 41 | + skey_path = base_dir / f"{base_name}.skey" |
| 42 | + vkey_path = base_dir / f"{base_name}.vkey" |
| 43 | + |
| 44 | + if skey_path.exists(): |
| 45 | + skey = PaymentSigningKey.load(str(skey_path)) |
| 46 | + vkey = PaymentVerificationKey.from_signing_key(skey) |
| 47 | + else: |
| 48 | + key_pair = PaymentKeyPair.generate() |
| 49 | + key_pair.signing_key.save(str(skey_path)) |
| 50 | + key_pair.verification_key.save(str(vkey_path)) |
| 51 | + skey = key_pair.signing_key |
| 52 | + vkey = key_pair.verification_key |
| 53 | + return skey, vkey |
| 54 | + |
| 55 | + tempdir = tempfile.TemporaryDirectory() |
| 56 | + PROJECT_ROOT = tempdir.name |
| 57 | + |
| 58 | + root = pathlib.Path(PROJECT_ROOT) |
| 59 | + # Create the directory if it doesn't exist |
| 60 | + root.mkdir(parents=True, exist_ok=True) |
| 61 | + """Generate keys""" |
| 62 | + key_dir = root / "keys" |
| 63 | + key_dir.mkdir(exist_ok=True) |
| 64 | + |
| 65 | + # Generate policy keys, which will be used when minting NFT |
| 66 | + policy_skey, policy_vkey = load_or_create_key_pair(key_dir, "policy") |
| 67 | + |
| 68 | + """Create policy""" |
| 69 | + # A policy that requires a signature from the policy key we generated above |
| 70 | + pub_key_policy = ScriptPubkey(policy_vkey.hash()) |
| 71 | + |
| 72 | + # A time policy that disallows token minting after 10000 seconds from last block |
| 73 | + must_before_slot = InvalidHereAfter(chain_context.last_block_slot + 10000) |
| 74 | + |
| 75 | + # Combine two policies using ScriptAll policy |
| 76 | + policy = ScriptAll([pub_key_policy, must_before_slot]) |
| 77 | + |
| 78 | + # Calculate policy ID, which is the hash of the policy |
| 79 | + policy_id = policy.hash() |
| 80 | + |
| 81 | + """Define NFT""" |
| 82 | + my_nft = MultiAsset.from_primitive( |
| 83 | + { |
| 84 | + policy_id.payload: { |
| 85 | + b"MY_NFT_1": 1, # Name of our NFT1 # Quantity of this NFT |
| 86 | + b"MY_NFT_2": 1, # Name of our NFT2 # Quantity of this NFT |
| 87 | + } |
| 88 | + } |
| 89 | + ) |
| 90 | + |
| 91 | + native_scripts = [policy] |
| 92 | + |
| 93 | + """Create metadata""" |
| 94 | + # We need to create a metadata for our NFTs, so they could be displayed correctly by blockchain explorer |
| 95 | + metadata = { |
| 96 | + 721: { # 721 refers to the metadata label registered for NFT standard here: |
| 97 | + # https://github.com/cardano-foundation/CIPs/blob/master/CIP-0010/registry.json#L14-L17 |
| 98 | + policy_id.payload.hex(): { |
| 99 | + "MY_NFT_1": { |
| 100 | + "description": "This is my first NFT thanks to PyCardano", |
| 101 | + "name": "PyCardano NFT example token 1", |
| 102 | + "id": 1, |
| 103 | + "image": "ipfs://QmRhTTbUrPYEw3mJGGhQqQST9k86v1DPBiTTWJGKDJsVFw", |
| 104 | + }, |
| 105 | + "MY_NFT_2": { |
| 106 | + "description": "This is my second NFT thanks to PyCardano", |
| 107 | + "name": "PyCardano NFT example token 2", |
| 108 | + "id": 2, |
| 109 | + "image": "ipfs://QmRhTTbUrPYEw3mJGGhQqQST9k86v1DPBiTTWJGKDJsVFw", |
| 110 | + }, |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + # Place metadata in AuxiliaryData, the format acceptable by a transaction. |
| 116 | + auxiliary_data = AuxiliaryData(AlonzoMetadata(metadata=Metadata(metadata))) |
| 117 | + |
| 118 | + """Build transaction""" |
| 119 | + |
| 120 | + # Create a transaction builder |
| 121 | + builder = TransactionBuilder(chain_context) |
| 122 | + |
| 123 | + # Add our own address as the input address |
| 124 | + builder.add_input_address(address) |
| 125 | + |
| 126 | + # Since an InvalidHereAfter rule is included in the policy, we must specify time to live (ttl) for this transaction |
| 127 | + builder.ttl = must_before_slot.after |
| 128 | + |
| 129 | + # Set nft we want to mint |
| 130 | + builder.mint = my_nft |
| 131 | + |
| 132 | + # Set native script |
| 133 | + builder.native_scripts = native_scripts |
| 134 | + |
| 135 | + # Set transaction metadata |
| 136 | + builder.auxiliary_data = auxiliary_data |
| 137 | + |
| 138 | + # Calculate the minimum amount of lovelace that need to hold the NFT we are going to mint |
| 139 | + min_val = min_lovelace(Value(0, my_nft), chain_context) |
| 140 | + |
| 141 | + # Send the NFT to our own address |
| 142 | + nft_output = TransactionOutput(address, Value(min_val, my_nft)) |
| 143 | + builder.add_output(nft_output) |
| 144 | + |
| 145 | + # Build a finalized transaction body with the change returning to our own address |
| 146 | + tx_body = builder.build(change_address=address) |
| 147 | + |
| 148 | + """Sign transaction and add witnesses""" |
| 149 | + # Sign the transaction body hash using the payment signing key |
| 150 | + payment_signature = payment_skey.sign(tx_body.hash()) |
| 151 | + |
| 152 | + # Sign the transaction body hash using the policy signing key because we are minting new tokens |
| 153 | + policy_signature = policy_skey.sign(tx_body.hash()) |
| 154 | + |
| 155 | + # Add verification keys and their signatures to the witness set |
| 156 | + vk_witnesses = [ |
| 157 | + VerificationKeyWitness(payment_vkey, payment_signature), |
| 158 | + VerificationKeyWitness(policy_vkey, policy_signature), |
| 159 | + ] |
| 160 | + |
| 161 | + # Create final signed transaction |
| 162 | + signed_tx = Transaction( |
| 163 | + tx_body, |
| 164 | + # Beside vk witnesses, We also need to add the policy script to witness set when we are minting new tokens. |
| 165 | + TransactionWitnessSet( |
| 166 | + vkey_witnesses=vk_witnesses, native_scripts=native_scripts |
| 167 | + ), |
| 168 | + auxiliary_data=auxiliary_data, |
| 169 | + ) |
| 170 | + |
| 171 | + print("############### Transaction created ###############") |
| 172 | + print(signed_tx) |
| 173 | + print(signed_tx.to_cbor()) |
| 174 | + |
| 175 | + # Submit signed transaction to the network |
| 176 | + print("############### Submitting transaction ###############") |
| 177 | + chain_context.submit_tx(signed_tx.to_cbor()) |
| 178 | + |
| 179 | + time.sleep(3) |
| 180 | + |
| 181 | + utxos = chain_context.utxos(str(address)) |
| 182 | + found_nft = False |
| 183 | + |
| 184 | + for utxo in utxos: |
| 185 | + output = utxo.output |
| 186 | + if output == nft_output: |
| 187 | + found_nft = True |
| 188 | + |
| 189 | + assert found_nft, f"Cannot find target NFT in address: {address}" |
0 commit comments