### Download and Run SmartPy Tezos Example (Shell) Source: https://smartpy.tezos.com/manual/introduction/installation Downloads a SmartPy Tezos example script ('welcome.py') using wget and then executes it using the Python interpreter. This verifies the installation by running a basic contract example. ```shell wget https://smartpy.io/templates/welcome.py python welcome.py ``` -------------------------------- ### Install SmartPy Tezos (Pip) Source: https://smartpy.tezos.com/manual/introduction/installation Installs the SmartPy Tezos package using pip. This command should be run after activating the virtual environment. It fetches and installs the latest stable version. ```shell pip install smartpy-tezos ``` -------------------------------- ### Create and Activate Virtual Environment (Shell) Source: https://smartpy.tezos.com/manual/introduction/installation Creates a Python virtual environment named 'smartpy-env' and activates it. This isolates project dependencies. The activation command differs slightly between Linux/macOS and Windows. ```shell python -m venv smartpy-env source smartpy-env/bin/activate ``` -------------------------------- ### Install Specific SmartPy Tezos Version (Pip) Source: https://smartpy.tezos.com/manual/introduction/installation Installs a specific version of the SmartPy Tezos package using pip. This is useful for alpha releases or when a particular version is required. Replace '' with the desired version number. ```shell pip install smartpy-tezos== ``` -------------------------------- ### SmartPy: Full Example of Contract Origination Source: https://smartpy.tezos.com/manual/data-types/operations Provides a complete example demonstrating contract origination. It includes the definition of the contract to be originated (`MyContract`) and the contract that performs the origination (`Originator`), showcasing how storage and private data are set. ```python class MyContract(sp.Contract): def __init__(self): self.private.px = 10 self.private.py = 0 self.data.a = sp.int(0) self.data.b = sp.nat(0) @sp.entrypoint def ep(self, params): self.data.a += params.x + self.private.px self.data.b += params.y + self.private.py class Originator(sp.Contract): @sp.entrypoint def ep(self): sp.create_contract( MyContract, None, sp.tez(0), sp.record(a=1, b=2), private_=sp.record(px=10, py=20), ) ``` -------------------------------- ### SmartPy List Push Operation Example Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Provides a concise example of using the `push()` method to add an element to the beginning of a SmartPy list. This method modifies the list in-place. The example shows the list before and after the `push` operation. ```python s = [1, 2, 3] s.push(4) # evaluates to `[4, 1, 2, 3]` ``` -------------------------------- ### Inlined SmartPy Module Definition and Import Source: https://smartpy.tezos.com/manual/syntax/modules Demonstrates defining two inlined SmartPy modules. The first module 'example' contains a simple function 'foo'. The second module 'my_module' imports and uses the 'foo' function from the 'example' module, showcasing inter-module dependency management in SmartPy. ```python import smartpy as sp # an inlined SmartPy module @sp.module def example(): def foo(): pass # another inlined SmartPy module that uses the previous module @sp.module def my_module(): # Since v0.20.0: to use the `example` module you must import it import example def bar(): example.foo() ``` -------------------------------- ### Originate Nft Contract with Pre-minted Tokens using SmartPy Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/base_classes Demonstrates originating an Nft contract with pre-minted tokens using SmartPy. This example includes defining token metadata and populating the ledger with initial token ownership. ```python import smartpy as sp from smartpy.templates import fa2_lib as fa2 @sp.add_test() def test(): sc = sp.test_scenario("Nft", fa2.main) sc.h2("With pre-minted tokens") alice = sp.test_account("alice") bob = sp.test_account("bob") tok0_md = fa2.make_metadata(name="Token Zero", decimals=1, symbol="Tok0") tok1_md = fa2.make_metadata(name="Token One", decimals=1, symbol="Tok1") tok2_md = fa2.make_metadata(name="Token Two", decimals=1, symbol="Tok2") c1 = fa2.main.Nft( metadata = sp.big_map(), ledger = { 0: alice.address, 1: bob.address, 2: alice.address, }, token_metadata = [tok0_md, tok1_md, tok2_md] ) sc += c1 ``` -------------------------------- ### Originate Empty Fungible Contract with SmartPy Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/base_classes Shows how to originate an empty Fungible token contract using SmartPy's fa2_lib. This example initializes the metadata, ledger, and token_metadata parameters as empty. ```python import smartpy as sp from smartpy.templates import fa2_lib as fa2 @sp.add_test() def test(): sc = sp.test_scenario("Fungible", fa2.main) sc.h2("Without pre-minted tokens") c1 = fa2.main.Fungible(sp.big_map(), {}, []) sc += c1 ``` -------------------------------- ### SmartPy Range Generation Examples Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Shows various ways to generate lists of numbers using the `sp.range()` function. It covers generating sequences with a specified end, a start and end, and with a custom step. Examples include both `sp.nat` and `sp.int` types. ```python sp.range(3) # evaluates to `[0, 1, 2]` sp.range(3, 7) # evaluates to `[3, 4, 5, 6]` sp.range(3, 7, 2) # evaluates to `[3, 5]` ``` -------------------------------- ### SmartPy Value Creation Source: https://smartpy.tezos.com/manual/introduction/local_development Shows how to create values, with examples of type inference and explicit type definition using `sp.nat()` or `sp.cast()`. ```python a = 1 # inferred as sp.int b = sp.nat(1) # explicitly sp.nat c = sp.cast(1, sp.nat) # explicitly sp.nat using sp.cast ``` -------------------------------- ### SmartPy FA2 Transfer Entrypoint Example Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/entrypoints Demonstrates how to perform multiple token transfers in a single call to the `transfer` entrypoint. It requires a list of batches, where each batch specifies the sender, recipient, token ID, and amount. Dependencies include the SmartPy library (`sp`). ```python contract.transfer( [ sp.record( from_=alice.address, txs=[ sp.record(to_=bob.address, amount=10, token_id=0), sp.record(to_=bob.address, amount=10, token_id=1), ], ), sp.record( from_=bob.address, txs=[sp.record(to_=alice.address, amount=11, token_id=0)] ), ], _sender=charlie, ) ``` -------------------------------- ### SmartPy: FA2 Allowance System Implementation Example Source: https://smartpy.tezos.com/manual/introduction/faq Demonstrates how to implement an allowance system using the FA2 standard in SmartPy. This involves setting up operators and managing allowances for token transfers, with specific notes on safe allowance changes to prevent reentrancy attacks. ```python This example focuses on the conceptual flow and would require a full SmartPy contract implementation to be executable. 1. User calls `update_operators` to grant an operator. 2. User calls `update_allowance` to set a token allowance for the operator. 3. Operator calls the contract's `transfer` entrypoint. 4. Contract logic verifies operator and allowance before executing the transfer. ``` -------------------------------- ### Originate Empty Nft Contract with SmartPy Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/base_classes Demonstrates the origination of an empty Nft contract using SmartPy's fa2_lib. It takes metadata, ledger, and token_metadata as parameters. The ledger and token_metadata are initialized as empty in this example. ```python import smartpy as sp from smartpy.templates import fa2_lib as fa2 @sp.add_test() def test(): sc = sp.test_scenario("Nft", fa2.main) sc.h2("Without pre-minted tokens") c1 = fa2.main.Nft(sp.big_map(), {}, []) sc += c1 ``` -------------------------------- ### Install SmartPy in Jupyter Notebook Source: https://smartpy.tezos.com/manual/introduction/web_ide This command installs the SmartPy library within a Jupyter Notebook environment using the pip magic command. It's a prerequisite for using SmartPy features in the notebook. ```python %pip install smartpy_tezos ``` -------------------------------- ### Originate SingleAsset Contract with Pre-minted Tokens using SmartPy Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/base_classes Illustrates originating a SingleAsset token contract with pre-minted tokens using SmartPy. This example defines token metadata and sets the initial ledger with token amounts for an address. ```python import smartpy as sp from smartpy.templates import fa2_lib as fa2 @sp.add_test() def test(): sc = sp.test_scenario("SingleAsset", fa2.main) sc.h2("With pre-minted tokens") alice = sp.test_account("alice") tok0_md = fa2.make_metadata(name="Token Zero", decimals=1, symbol="Tok0") c1 = fa2.main.SingleAsset( metadata=sp.big_map(), token_metadata=tok0_md, ledger={alice.address: 42} ) sc += c1 ``` -------------------------------- ### Calling SmartPy Entrypoints with Records Source: https://smartpy.tezos.com/manual/scenarios/testing_contracts This example illustrates how to invoke a SmartPy entrypoint that accepts multiple parameters. Parameters can be passed either as an implied record by naming the arguments or as an explicit `sp.record` object. ```smartpy @sp.add_test() def test(): scenario = sp.test_scenario(main, "A Test") contract = main.MyContract() scenario += contract # Implied record contract.exampleEntrypoint(a=5, b=6) # Explicit record contract.exampleEntrypoint(sp.record(a=5, b=6)) ``` -------------------------------- ### SmartPy FA2 Update Operators Entrypoint Example Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/entrypoints Illustrates how to modify operator permissions for token transfers. This example shows removing one operator and adding another for a specific token ID. It requires a list of operations, each specifying the action, owner, operator, and token ID. Dependencies include the SmartPy library (`sp`). ```python contract.update_operators( [ sp.variant( "remove_operator", sp.record(owner=alice.address, operator=op1.address, token_id=0), ), sp.variant( "add_operator", sp.record(owner=alice.address, operator=op2.address, token_id=0), ), ], _sender=alice, ) ``` -------------------------------- ### SmartPy: Transferring Tez and Calling Contracts Source: https://smartpy.tezos.com/manual/data-types/operations Demonstrates how to transfer a specified amount of tez to a destination address or call a contract's entrypoint with arguments and a tez transfer. Includes examples for basic transfers and transfers to specific entrypoints. ```python sp.transfer(100, sp.mutez(0), c) sp.transfer(42, sp.mutez(0), sp.self_entrypoint("abc")) ``` -------------------------------- ### SmartPy List Creation and Manipulation Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Demonstrates how to create, initialize, and add elements to a SmartPy list using the `push()` method. It also includes a test scenario to verify the sum of elements in the list. This example showcases basic list operations within a SmartPy contract. ```python import smartpy as sp @sp.module def main(): class ListTest(sp.Contract): def __init__(self): self.data.myList = [] sp.cast(self.data.myList, sp.list[sp.int]) @sp.entrypoint def add(self, newValue): self.data.myList.push(newValue) @sp.add_test() def test(): scenario = sp.test_scenario("ListTest", main) contract = main.ListTest() scenario += contract contract.add(4) contract.add(6) scenario.verify(sp.sum(contract.data.myList) == 10) ``` -------------------------------- ### Python: Initialize NFT Contract with Mint Mixin Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/mixins Demonstrates how to initialize an NFT contract by inheriting from FA2.Admin, FA2.MintNft, and FA2.Fa2Nft mixins. This setup requires an administrator address and specific contract configurations. ```python class NftWithMint(FA2.Admin, FA2.MintNft, FA2.Fa2Nft): def __init__(self, admin, **kwargs): Fa2Nft.__init__(self, **kwargs) Admin.__init__(self, admin) ``` -------------------------------- ### SmartPy List Iteration Example Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Demonstrates how to iterate over the elements of a SmartPy list using a standard `for` loop. The example shows accumulating the sum of elements in a list within a contract's data field. ```python for x in [1, 2, 3]: self.data.result += x ``` -------------------------------- ### SmartPy Entrypoint with Multiple Parameters (Record) Source: https://smartpy.tezos.com/manual/syntax/contracts Shows a SmartPy contract with an entrypoint that accepts multiple named parameters ('a' and 'b'). To call this entrypoint, parameters must be passed as a record. The example includes a test case that verifies the multiplication result. ```python @sp.module def main(): class Calculator(sp.Contract): def __init__(self): self.data.value = 0 @sp.entrypoint def multiply(self, a, b): self.data.value = a * b @sp.add_test() def test(): scenario = sp.test_scenario("Calculator", main) contract = main.Calculator() scenario += contract # There are multiple parameters, so pass a record contract.multiply(a=5, b=6) scenario.verify(contract.data.value == 30) ``` -------------------------------- ### Initialize Test Scenario (Python) Source: https://smartpy.tezos.com/manual/scenarios/test_scenarios This example shows the basic structure for defining a test function using the `@sp.add_test()` decorator and creating a test scenario with `sp.test_scenario()`. It sets up the simulated environment before contract interactions. ```python @sp.module def main(): class MyContract(sp.Contract): pass # ...etc @sp.add_test() def test(): # Create a test scenario scenario = sp.test_scenario("A Test") ``` -------------------------------- ### Contract Initialization with Constructor Parameters Source: https://smartpy.tezos.com/manual/syntax/contracts Shows how to define a SmartPy contract 'A' whose constructor (__init__) accepts parameters to initialize its storage fields. The example includes a test case to verify that the storage values are correctly set upon contract instantiation. ```python @sp.module def main(): class A(sp.Contract): def __init__(self, int_value: sp.int, string_value: sp.string): self.data.int_value = int_value self.data.string_value = string_value @sp.add_test() def test(): scenario = sp.test_scenario("A", main) contract = main.A(12, "Hello!") scenario += contract scenario.verify(contract.data.int_value == 12) scenario.verify(contract.data.string_value == "Hello!") ``` -------------------------------- ### Example Shell Output for SmartPy Tracing Source: https://smartpy.tezos.com/manual/syntax/debugging This is an example of the standard error output generated when running the SmartPy Python script containing the `sp.trace` statements. Each line represents a value passed to the `fibonacci` view during its execution, illustrating the recursive calls and their order. This output is crucial for debugging the contract's logic during local development. ```shell $ python fibonacci_view.py 5 4 3 2 1 0 1 2 1 0 3 2 1 0 1 ``` -------------------------------- ### SmartPy Big Map Operations: Create and Populate Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Shows how to create and work with a SmartPy 'sp.big_map', which is optimized for large amounts of data. This example demonstrates adding and accessing elements in a big map. ```python m = sp.big_map() m["a"] = 65 m["b"] = 66 assert m["a"] == 65 m["c"] = 67 assert m["c"] == 67 ``` -------------------------------- ### Create and Add Fixed-Point Numbers in SmartPy Source: https://smartpy.tezos.com/manual/stdlib/library Provides an example of creating fixed-point decimal numbers using `fp.mk` and then adding them together using the `fp.add` function. The fixed-point representation includes a value and an exponent. ```smartpy import smartpy.fixed_point as fp v1 = fp.mk((123, 2)) v2 = fp.mk((245, 2)) assert fp.add((v1, v2)) == sp.record(value=sp.int(368), exponent=2) ``` -------------------------------- ### Set Flags with Parameters for Compiler (Python) Source: https://smartpy.tezos.com/manual/scenarios/test_scenarios This example shows how to set flags that require parameters, such as the compiler output directory or the simulation protocol, using `scenario.add_flag`. These flags allow customization of the compilation and testing environment. ```python # Compile for Rio protocol scenario.add_flag("protocol", "rio") ``` -------------------------------- ### SmartPy Map Operations: Get Keys Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Demonstrates retrieving all keys from a SmartPy map as a list. This is useful when you only need to work with the keys of a map. ```python m = {'a': 97, 'b': 98} keys = m.keys() # keys will be ['a', 'b'] ``` -------------------------------- ### Create FA2 Compliant Tokens with SmartPy (Python) Source: https://smartpy.tezos.com/manual/introduction/faq This example outlines the creation of tokens adhering to the Tezos FA2 standard using the SmartPy FA2 library. It involves defining a smart contract that manages a ledger to track token ownership and associated metadata. ```python import smartpy as sp # Example of defining an FA2 token contract using SmartPy's library # This is a simplified illustration. # Define metadata for the token metadata = { "name": "My Awesome Token", "symbol": "MAT", "decimals": 6, "icon": "https://example.com/icon.png" } class MyTokenContract(sp.Contract): def __init__(self, initial_supply=1000000, owner=sp.address("tz1...")): self.fa2 = sp.FA2([sp.FA2.TokenMetadata(token_id=0, token_info=metadata)]) self.init(owner=owner, balances={owner: initial_supply}, total_supply=initial_supply) @sp.entry_point def transfer(self, from_address, to_address, amount): # Basic transfer logic, requires more robust implementation for FA2 sp.verify(from_address != to_address) sp.verify(self.data.balances.get(from_address, 0) >= amount) self.data.balances[from_address] = sp.as_nat(self.data.balances.get(from_address, 0) - amount) self.data.balances[to_address] = sp.as_nat(self.data.balances.get(to_address, 0) + amount) # To deploy and test, you would typically use: # sp.add_compilation_target("my_token_contract", MyTokenContract()) # scenario = sp.test_scenario(MyTokenContract()) # scenario.run(transfer_from=..., transfer_to=..., amount=...) ``` -------------------------------- ### Configure Octez Client for Ghostnet Testnet Source: https://smartpy.tezos.com/manual/compilation/deploying This command configures the Octez client to connect to a Ghostnet testnet node. It requires the URL of a Ghostnet node, which can be found on teztats.com. Ensure you have the Octez client installed and configured for the target network. ```bash octez-client --endpoint https://rpc.ghostnet.teztnets.com config update ``` -------------------------------- ### SmartPy Type Compatibility and Inference (SmartPy) Source: https://smartpy.tezos.com/manual/data-types/types Illustrates SmartPy's strict type system, showing how function signatures enforce type expectations. It provides an example of type inference for function arguments and explains limitations with incompatible types. Conversion functions are also mentioned. ```smartpy def f(x: sp.nat): pass f(5) # 5 is inferred as sp.nat due to the function signature # `f(-5)` would fails because -5 cannot be a nat ``` -------------------------------- ### Inheriting from a Contract in Another Inlined Module Source: https://smartpy.tezos.com/manual/syntax/modules Illustrates how to create a new SmartPy module 'main' that imports and extends a contract 'Calculator' from the 'calc' module. This example shows inheritance and adding a new entrypoint 'add' to the extended contract, demonstrating modularity and code reuse. ```python @sp.module def main(): import calc class NewCalculator(calc.Calculator): def __init__(self): calc.Calculator.__init__(self) @sp.entrypoint def add(self, x, y): self.data.result = x + y ``` -------------------------------- ### Get List Element at Index (SmartPy) Source: https://smartpy.tezos.com/manual/stdlib/library Retrieves the element from a list at a specific index. It takes a pair of (list, index) as input and returns the integer element at that position. Indexing starts from 0. ```python import smartpy.stdlib.list_utils as list_utils list_utils.element_at(([1, 2, 3], 0)) == 1 list_utils.element_at(([1, 2, 3], 1)) == 2 list_utils.element_at(([1, 2, 3], 2)) == 3 ``` -------------------------------- ### SmartPy Contract Testing with Entrypoint Calls Source: https://smartpy.tezos.com/manual/scenarios/testing_contracts This snippet demonstrates a complete SmartPy test scenario. It includes defining a simple contract with an entrypoint, creating a contract instance, adding it to a scenario, calling the entrypoint, and verifying the contract's storage state before and after the call. ```smartpy @sp.module def main(): class MyCounter(sp.Contract): def __init__(self, initialValue: sp.nat): self.data.value = initialValue @sp.entrypoint def increment(self, update): self.data.value += update @sp.add_test() def test(): # Create a test scenario # Specify the output folder and a module or list of modules to import scenario = sp.test_scenario("Test for my smart contract", main) # Create an instance of a contract # Automatically calls the __init__() method of the contract's class contract = main.MyCounter(5) # Add the contract to the scenario scenario += contract # Check the expected value in the contract storage scenario.verify(contract.data.value == 5) # Call an entrypoint contract.increment(3) # Check the expected value in the contract storage scenario.verify(contract.data.value == 8) ``` -------------------------------- ### Add Non-Standard Mint Entrypoint using Mixins Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/entrypoints Illustrates how to incorporate non-standard FA2 entrypoints, such as `mint`, using the mixin mechanism provided by the SmartPy library. This allows for functionalities not mandated by the FA2 standard, like token creation. ```smartpy class MyFA2Contract(main.Fungible, mintable.Mintable): # ... contract implementation ... pass ``` -------------------------------- ### Extract Sub-list (SmartPy) Source: https://smartpy.tezos.com/manual/stdlib/library Computes and returns a portion of a list, specified by a start index and an end index (exclusive). It takes a tuple containing the list, the starting index, and the ending index. The elements from the start index up to (but not including) the end index are returned. ```python import smartpy.stdlib.list_utils as list_utils sp.pack(list_utils.sub_list(([1, 2, 3, 4, 5], 1, 3))) == sp.pack([2, 3]) sp.pack(list_utils.sub_list(([1, 2, 3, 4, 5], 1, 4))) == sp.pack([2, 3, 4]) ``` -------------------------------- ### SmartPy Set Add Operation Example Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Provides an example of adding an element to a SmartPy set using the `add()` method and verifying its presence with `contains()`. Sets store unique elements, and `add()` will not duplicate existing elements. The example shows the state after adding an element. ```python s = {1, 2, 3} s.add(4) assert s.contains(4) ``` -------------------------------- ### SmartPy Module Auxiliary Function Source: https://smartpy.tezos.com/manual/syntax/contracts Presents an example of a SmartPy module containing an auxiliary function named 'multiply'. This function is then used within a contract's entrypoint to perform a multiplication. The example demonstrates how auxiliary functions can be integrated into contract logic and tested. ```python @sp.module def main(): def multiply(a, b): return a * b class C(sp.Contract): @sp.entrypoint def ep(self): assert multiply(sp.record(a=4, b=5)) == 20 ``` -------------------------------- ### SmartPy List Reversal Example Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Illustrates the `reversed()` function for SmartPy lists, which returns a new list with the elements in reverse order. The original list remains unchanged. The example shows the input list and the resulting reversed list. ```python reversed([1, 2, 3]) # evaluates to `[3, 2, 1]` ``` -------------------------------- ### Query Token Balances with balance_of Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/entrypoints The `balance_of` entrypoint queries the balances of specified account/token pairs and sends the results to a callback contract. It requires a list of requests and callback information. The response format is defined by `t.balance_of_response`. ```smartpy contract.balance_of( callback=sp.contract( sp.list(fa2.t.balance_of_response), contract2.address, entry_point="receive_balances", ).unwrap_some(), requests=[sp.record(owner=alice.address, token_id=0)], _sender=alice, ) ``` -------------------------------- ### SmartPy Map Operations: Get with Default or Error Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Illustrates retrieving values from a SmartPy map using the 'get' method, which allows specifying a default value if the key is not found or raising an error. This provides flexible data retrieval and error handling. ```python # Example with default m = {"a": 65} value = m.get('b', default=0) # Example with error (if 'b' is not in m, an error will be raised) # value = m.get('b', error='Key not found') ``` -------------------------------- ### Define Smart Contract and Create Test Scenario (Python) Source: https://smartpy.tezos.com/manual/scenarios/test_scenarios This snippet demonstrates defining a simple SmartPy contract and then setting up a test scenario to interact with it. It includes contract instantiation, calling an entrypoint, expecting a failed call, and verifying contract storage. ```python @sp.module def main(): class MyCounter(sp.Contract): def __init__(self, initialValue: sp.nat): self.data.value = initialValue @sp.entrypoint def increment(self, update): assert update < 6, "Increment by less than 6" self.data.value += update @sp.add_test() def test(): # Create a test scenario # Specify the output folder scenario = sp.test_scenario("MyCounter tests") # Create an instance of a contract # Automatically calls the __init__() method of the contract's class contract = main.MyCounter(5) # Add the contract to the scenario scenario += contract # Call an entrypoint contract.increment(3) # Call an entrypoint and expect it to fail contract.increment(12, _valid=False) # Check the expected value in the contract storage scenario.verify(contract.data.value == 8) ``` -------------------------------- ### SmartPy List Cons Operation Example Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Demonstrates the `sp.cons()` function, which creates a new list with an element added to the front of an existing list. This is an immutable operation, returning a new list without modifying the original. The example shows the input and the resulting list. ```python sp.cons(1, [2, 3]) # evaluates to `[1, 2, 3]` ``` -------------------------------- ### SmartPy NFT Token Contract with Mixins Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/mixins This example demonstrates how to create an NFT token contract by inheriting multiple mixins from the SmartPy FA2 library. It includes functionalities for administration, metadata changes, withdrawal, minting, burning, and on-chain/off-chain views. The `__init__` method shows the correct order for calling superclass initializers. ```python class ExampleFa2Nft( main.Admin, main.Nft, main.ChangeMetadata, main.WithdrawMutez, main.MintNft, main.BurnNft, main.OffchainviewTokenMetadata, main.OnchainviewBalanceOf, ): def __init__(self, administrator, metadata, ledger, token_metadata): main.OnchainviewBalanceOf.__init__(self) main.OffchainviewTokenMetadata.__init__(self) main.BurnNft.__init__(self) main.MintNft.__init__(self) main.WithdrawMutez.__init__(self) main.ChangeMetadata.__init__(self) main.Nft.__init__(self, metadata, ledger, token_metadata) main.Admin.__init__(self, administrator) ``` -------------------------------- ### SmartPy Map Operations: Get Values Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Shows how to retrieve all values from a SmartPy map as a list. This is useful when you only need to work with the values stored in a map. ```python m = {'a': 97, 'b': 98} values = m.values() # values will be [97, 98] ``` -------------------------------- ### SmartPy Syntax Equivalents Source: https://smartpy.tezos.com/manual/introduction/local_development Lists direct replacements for specific SmartPy syntax elements with their native Python or Tezos equivalents. ```plaintext sp.unit → () sp.pair(x, y) → (x, y) ``` -------------------------------- ### SmartPy Map Operations: Get Items Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Illustrates retrieving all key-value pairs from a SmartPy map as a list of records. This is useful for iterating over all entries in a map. ```python m = {'a': 97, 'b': 98} items = m.items() # items will be [sp.record(key='a', value=97), sp.record(key='b', value=98)] ``` -------------------------------- ### Call a Lambda Function Source: https://smartpy.tezos.com/manual/data-types/lambdas Shows how to invoke a previously defined lambda function by passing its argument in parentheses. This example asserts that calling the lambda `f` with the argument `1` results in `2`. ```python assert f(1) == 2 ``` -------------------------------- ### SmartPy: Sending Tez to Accounts or Contracts Source: https://smartpy.tezos.com/manual/data-types/operations Explains how to send a specified amount of tez to a destination, which can be an implicit account or a contract with a 'default' entrypoint. Provides an equivalent transfer example. ```python sp.send(dest, sp.tez(42)) # equivalent to sp.transfer((), sp.tez(42), sp.contract(sp.unit, dest).unwrap_some()) ``` -------------------------------- ### Mint Token with Metadata (SmartPy) Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/token_metadata This snippet shows how to pass a metadata object to the `mint` entrypoint of an FA2 contract. It assumes `example_md` is a pre-defined metadata object and `account` and `admin` are valid addresses or parameters within the contract context. ```smartpy contract.mint( [ sp.record(metadata=example_md, to_=account.address), ], _sender=admin, ) ``` -------------------------------- ### SmartPy Map Operations: Get Length Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Shows how to obtain the number of entries in a SmartPy map using the 'sp.len()' function. This is useful for knowing the current size of the map. ```python m = {"a": 65, "b": 66} length = sp.len(m) assert length == 2 ``` -------------------------------- ### Originate SmartPy Contract with Octez Client Source: https://smartpy.tezos.com/manual/compilation/deploying This command deploys a compiled SmartPy contract and its initial storage to the Tezos network using the Octez client. It specifies the contract file, the storage file, the originating account, and a burn cap. The response will include the deployed contract's address (KT1). ```bash octez-client originate contract welcome transferring 0 from my_account \ running Welcome/step_002_cont_0_contract.tz \ --init "`cat Welcome/step_002_cont_0_storage.tz`" --burn-cap 1 ``` -------------------------------- ### Check Transaction Amount in SmartPy Entrypoint Source: https://smartpy.tezos.com/manual/syntax/contracts Demonstrates how to access and check transaction variables within a SmartPy entrypoint. This example specifically checks if the incoming transaction amount (`sp.amount`) matches an expected value. ```smartpy def ep_receive(self): assert sp.amount == 5 # ... ``` -------------------------------- ### SmartPy: Originating New Contracts with Storage and Delegate Source: https://smartpy.tezos.com/manual/data-types/operations Shows how to originate new smart contracts using `sp.create_contract`. This includes specifying the contract type, initial storage, optional private data, delegate, and initial tez transfer amount. ```python sp.create_contract(MyContract, None, sp.tez(0), ()) sp.create_contract( MyContract, sp.Some(key_hash), sp.tez(10), sp.record(x=42, y="abc"), private_=sp.record(a=1, b="xyz"), ) ``` -------------------------------- ### Import SmartPy FA2 Library Components Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/overview Imports the necessary SmartPy library and its FA2 template components for developing Tezos token contracts. This is a foundational step for using the FA2 library's functionalities. ```python import smartpy as sp from smartpy.templates import fa2_lib as fa2 ``` -------------------------------- ### SmartPy: Setting Delegate Operation Source: https://smartpy.tezos.com/manual/data-types/operations This SmartPy example demonstrates how to create an operation to set a delegate for the current contract using `sp.set_delegate_operation`. The generated operation is then added to the `sp.operations` list to be executed. ```python op = sp.set_delegate_operation(sp.Some(d)) sp.operations.push(op) ``` -------------------------------- ### Convert Fixed Point to String (SmartPy) Source: https://smartpy.tezos.com/manual/stdlib/library Converts a fixed-point number, represented by a record containing its value and exponent, into its decimal string representation. For example, a value of 123 with an exponent of 2 becomes '1.23'. ```python import smartpy.stdlib.string_utils as string_utils # Assuming 'fp' is defined elsewhere, e.g., from smartpy.contract.fixed_point # from smartpy.contract import fixed_point as fp # string_utils.from_fixed_point(fp.mk((123, 2))) == "1.23" ``` -------------------------------- ### SmartPy Map Operations: Create, Access, and Update Source: https://smartpy.tezos.com/manual/data-types/lists-sets-and-maps Demonstrates basic map operations in SmartPy, including initializing a map, accessing elements by key, and adding new entries. This is useful for managing small, in-memory collections of data. ```python m = {"a": 65, "b": 66} assert m["a"] == 65 m["c"] = 67 assert m["c"] == 67 ``` -------------------------------- ### Python Pattern Matching with SmartPy Variants Source: https://smartpy.tezos.com/manual/introduction/local_development Demonstrates using Python's native `match` and `case` syntax with SmartPy variants like `sp.variant.Circle` and `sp.Some` for conditional logic within SmartPy contracts. ```python @sp.module def main(): class C(sp.Contract): @sp.entrypoint def ep(self): v = sp.variant.Circle(2) match v: case Circle(radius): assert radius == 2 case Rectangle(dimensions): # Do something with dimensions pass ``` ```python @sp.module def main(): class C(sp.Contract): @sp.entrypoint def ep(self): o = sp.Some(5) match o: case Some(value): assert value == 5 case None: pass ``` -------------------------------- ### Originate Empty SingleAsset Contract with SmartPy Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/base_classes Illustrates the origination of an empty SingleAsset token contract with SmartPy's fa2_lib. The contract is initialized with empty metadata, ledger, and token_metadata. ```python import smartpy as sp from smartpy.templates import fa2_lib as fa2 @sp.add_test() def test(): sc = sp.test_scenario("SingleAsset", fa2.main) sc.h2("Without pre-minted tokens") c1 = fa2.main.SingleAsset(sp.big_map(), {}, {}) sc += c1 ``` -------------------------------- ### SmartPy Entrypoint with Single Parameter Source: https://smartpy.tezos.com/manual/syntax/contracts Illustrates a SmartPy contract with an entrypoint that accepts a single numerical parameter. The entrypoint calculates the square of the input parameter and updates the contract's storage. The accompanying test scenario demonstrates how to call this entrypoint with a literal value. ```python @sp.module def main(): class Calculator(sp.Contract): def __init__(self): self.data.value = 0 @sp.entrypoint def setSquare(self, a): self.data.value = a * a @sp.add_test() def test(): scenario = sp.test_scenario("Calculator", main) contract = main.Calculator() scenario += contract # There is one parameter, so pass a single value contract.square(4) scenario.verify(contract.data.value == 16) ``` -------------------------------- ### Import SmartPy Library in Jupyter Notebook Source: https://smartpy.tezos.com/manual/introduction/web_ide This line of code imports the SmartPy library, aliasing it as 'sp' for easier use in subsequent cells. This import statement is necessary after installing the library. ```python import smartpy as sp ``` -------------------------------- ### Call Contract from Entrypoint with sp.contract and sp.transfer (Python) Source: https://smartpy.tezos.com/manual/data-types/contracts Demonstrates how to represent a target contract using `sp.contract` and then invoke it using `sp.transfer`. It handles potential contract non-existence by using pattern matching on the optional contract reference. Dependencies include the `sp` module. Input is an integer and mutez, output is a contract call. ```python address = sp.address("KT1R2LTg3mQoLvHtUjo2xSi7RMBUJ1sJkDiD") contract_opt = sp.contract(sp.int, address, entrypoint="increment") match contract_opt: case Some(contract): sp.transfer(sp.int(5), sp.mutez(0), contract) case None: sp.trace("Failed to find contract") ``` -------------------------------- ### Originate Fungible Contract with Pre-minted Tokens using SmartPy Source: https://smartpy.tezos.com/manual/libraries/FA2-lib/base_classes Shows how to originate a Fungible token contract with pre-minted tokens using SmartPy. This involves defining token metadata and setting up the initial ledger with token amounts for addresses. ```python import smartpy as sp from smartpy.templates import fa2_lib as fa2 @sp.add_test() def test(): sc = sp.test_scenario("Fungible", fa2.main) sc.h2("With pre-minted tokens") alice = sp.test_account("alice") tok0_md = fa2.make_metadata(name="Token Zero", decimals=1, symbol="Tok0") tok1_md = fa2.make_metadata(name="Token One", decimals=1, symbol="Tok1") tok2_md = fa2.make_metadata(name="Token Two", decimals=1, symbol="Tok2") c1 = fa2.main.Fungible( metadata = sp.big_map(), ledger = { (alice.address, 0): 42, (alice.address, 1): 42, (alice.address, 2): 42, }, token_metadata = [tok0_md, tok1_md, tok2_md] ) sc += c1 ``` -------------------------------- ### Type Inference from Variable Assignment Source: https://smartpy.tezos.com/manual/data-types/casting Provides examples where SmartPy automatically infers the type of a variable based on the value assigned to it, eliminating the need for explicit casting. This applies to simple types and collections like lists. ```python smartpy``` # No casting required my_string = "hello" # Inferred to be sp.string my_list = [my_string] # Inferred to be sp.list[string] ``` -------------------------------- ### Check if String Starts With Pattern (SmartPy) Source: https://smartpy.tezos.com/manual/stdlib/library Verifies if a given string begins with a specified pattern. It takes a pair of strings as input, where the first string is the text to check and the second is the pattern. Returns a boolean value. ```python import smartpy.stdlib.string_utils as string_utils string_utils.starts_with(("abc", "abc")) == True string_utils.starts_with(("abc", "abcd")) == True string_utils.starts_with(("abc", "abcdefg")) == True ``` -------------------------------- ### Add Inline Module to Test Scenario (Python) Source: https://smartpy.tezos.com/manual/scenarios/test_scenarios This example demonstrates adding an inlined module (defined within the same file) to a test scenario. This makes the module's contents available for use within the test function. ```python @sp.module def main(): class MyContract(sp.Contract): pass # ...etc @sp.add_test() def test(): scenario = sp.test_scenario("A Test") scenario.add_module(main) ``` -------------------------------- ### Initializing Empty Collections in SmartPy Source: https://smartpy.tezos.com/manual/data-types/types Provides an example of initializing an empty map in SmartPy. `sp.cast` is used here to explicitly declare the type of the empty map as `sp.map[sp.string, sp.nat]`, as the type cannot be inferred from an empty literal. ```smartpy empty_map = sp.cast({}, sp.map[sp.string, sp.nat]) ``` -------------------------------- ### SmartPy Contract with Test Account Simulation Source: https://smartpy.tezos.com/manual/scenarios/test_accounts Demonstrates a SmartPy contract with an admin setting functionality and a test scenario simulating contract interactions. It shows how to create test accounts, deploy the contract, and verify admin changes using different sender addresses. This is useful for testing access control mechanisms. ```python smartpy``` @sp.module def main(): class MyContract(sp.Contract): def __init__(self, admin): self.data.adminAccount = admin @sp.entrypoint def setAdmin(self, newAdmin): assert sp.sender == self.data.adminAccount, "Must be admin" self.data.adminAccount = newAdmin @sp.add_test() def test(): # Create test accounts alice = sp.test_account("Alice") bob = sp.address("tz1QCVQinE8iVj1H2fckqx6oiM85CNJSK9Sx") scenario = sp.test_scenario("Admin test", main) contract = main.MyContract(alice.address) scenario += contract # Verify that non-admin account can't change the admin contract.setAdmin(bob, _sender=bob, _valid=False) # Verify that the admin can change the admin contract.setAdmin( bob, _sender=alice, ) scenario.verify(contract.data.adminAccount == bob) ``` ```