Skip to content
On this page

Code inlining โ€‹

Inlining allows for replacing a function call at a given location with the function's body being called. This approach enables the user to reduce code duplication.

For more extensive functions, sp.TLambda should be used instead because inline expansion will produce bigger contracts.

Example โ€‹

In SmartPy all non annotated functions get inlined when called inside entrypoint or lambda methods, as shown below.

python
import smartpy as sp

admin1 = sp.address('tz1aTgF2c3vyrk2Mko1yzkJQGAnqUeDapxxm')
admin2 = sp.address('tz1Ke2h7sDdakHJQh8WX4Z372du1KChsksyU')

class InlineExample(sp.Contract):
    def __init__(self):
        self.init(admins = sp.set([admin1]))

    def isAdmin(self, address):
        return self.data.admins.contains(address)

    def onlyAdmin(self):
        sp.verify(self.isAdmin(sp.sender), 'onlyAdmin')

    @sp.entrypoint
    def changeAdmins(self, remove, add):
        self.onlyAdmin()
        sp.if remove.is_some():
            sp.for admin in remove.open_some().elements():
                self.data.admins.remove(admin)
        sp.if add.is_some():
            sp.for admin in add.open_some().elements():
                self.data.admins.add(admin)

@sp.add_test(name = "InlineExample")
def test():
    scenario = sp.test_scenario()
    c1 = InlineExample()
    scenario += c1
    scenario.verify(c1.data.admins.contains(admin1))

    scenario.h2('Remove and add admins')
    c1.changeAdmins(
        remove = sp.some(sp.set([admin1])),
        add = sp.some(sp.set([admin2]))
    ).run( sender = admin1 )
    scenario.verify_equal(c1.data.admins, sp.set([admin2]))