Lição 4

FIFO合约创建

在本课中,我们将深入探讨SmartPy合约的一个更复杂的案例:先进先出(FIFO)队列。FIFO是一种组织和操作数据缓冲区的方法,首先处理队列中最早的(第一个)指令,又称“头(head)”。

理论

在FIFO的数据结构中,第一个加入队列的元素也将是第一个被移除的元素。也就是说,一旦添加了新元素,必须先移除之前添加的所有元素,才能移除新元素。

来源:Investopedia

在智能合约中,实现FIFO队列可以用于许多场景,例如公平的排队系统,每个人都按照他们到达的顺序得到服务(或处理)。

实操

我们直接开始编写一个FIFO合约。合约的两个主要运算将是push(用于向队列添加元素)和pop(用于从队列中移除元素)。

合约将队列存储在其存储空间中的列表中,每次push运算都会将一个元素追加到列表的末尾,而每次pop运算都会从列表的开头移除一个元素。

合约代码如下:

Python
import smartpy as sp


@sp.module
def main():
    # The Fifo class defines a simple contract that handles push and pop instructions
    # on a first-in first-out basis.

    class SimpleFifo(sp.Contract):
        def __init__(self):
            self.data.first = 0
            self.data.last = -1
            self.data.saved = {}

        @sp.entrypoint
        def pop(self):
            assert self.data.first < self.data.last
            del self.data.saved[self.data.first]
            self.data.first += 1

        @sp.entrypoint
        def push(self, element):
            self.data.last += 1
            self.data.saved[self.data.last] = element

        @sp.onchain_view
        def head(self):
            return self.data.saved[self.data.first]


if "templates" not in __name__:

    @sp.add_test(name="Fifo")
    def test():
        scenario = sp.test_scenario(main)
        scenario.h1("Simple Fifo Contract")
        c1 = main.SimpleFifo()
        scenario += c1
        c1.push(4)
        c1.push(5)
        c1.push(6)
        c1.push(7)
        c1.pop()
        scenario.verify(sp.View(c1, "head")() == 5)

测试FIFO合约:

第一步:复制合约代码并粘贴至SmartPy IDE中。

第二步:点击右上角的Run按钮来编译和模拟合约。

第三步:查看IDE右侧的模拟结果。你将看到每次运算后合同存储的状态。

第四步:尝试更改运算的顺序或添加新运算。

现在,你已经学会了如何在Tezos区块链上创建FIFO合约!在下一课中,我们将进一步介绍SmartPy的一个强大功能——递归,可以让合约调用自身。祝大家编程愉快!

Isenção de responsabilidade
* O investimento em criptomoedas envolve grandes riscos. Prossiga com cautela. O curso não se destina a servir de orientação para investimentos.
* O curso foi criado pelo autor que entrou para o Gate Learn. As opiniões compartilhadas pelo autor não representam o Gate Learn.
Catálogo
Lição 4

FIFO合约创建

在本课中,我们将深入探讨SmartPy合约的一个更复杂的案例:先进先出(FIFO)队列。FIFO是一种组织和操作数据缓冲区的方法,首先处理队列中最早的(第一个)指令,又称“头(head)”。

理论

在FIFO的数据结构中,第一个加入队列的元素也将是第一个被移除的元素。也就是说,一旦添加了新元素,必须先移除之前添加的所有元素,才能移除新元素。

来源:Investopedia

在智能合约中,实现FIFO队列可以用于许多场景,例如公平的排队系统,每个人都按照他们到达的顺序得到服务(或处理)。

实操

我们直接开始编写一个FIFO合约。合约的两个主要运算将是push(用于向队列添加元素)和pop(用于从队列中移除元素)。

合约将队列存储在其存储空间中的列表中,每次push运算都会将一个元素追加到列表的末尾,而每次pop运算都会从列表的开头移除一个元素。

合约代码如下:

Python
import smartpy as sp


@sp.module
def main():
    # The Fifo class defines a simple contract that handles push and pop instructions
    # on a first-in first-out basis.

    class SimpleFifo(sp.Contract):
        def __init__(self):
            self.data.first = 0
            self.data.last = -1
            self.data.saved = {}

        @sp.entrypoint
        def pop(self):
            assert self.data.first < self.data.last
            del self.data.saved[self.data.first]
            self.data.first += 1

        @sp.entrypoint
        def push(self, element):
            self.data.last += 1
            self.data.saved[self.data.last] = element

        @sp.onchain_view
        def head(self):
            return self.data.saved[self.data.first]


if "templates" not in __name__:

    @sp.add_test(name="Fifo")
    def test():
        scenario = sp.test_scenario(main)
        scenario.h1("Simple Fifo Contract")
        c1 = main.SimpleFifo()
        scenario += c1
        c1.push(4)
        c1.push(5)
        c1.push(6)
        c1.push(7)
        c1.pop()
        scenario.verify(sp.View(c1, "head")() == 5)

测试FIFO合约:

第一步:复制合约代码并粘贴至SmartPy IDE中。

第二步:点击右上角的Run按钮来编译和模拟合约。

第三步:查看IDE右侧的模拟结果。你将看到每次运算后合同存储的状态。

第四步:尝试更改运算的顺序或添加新运算。

现在,你已经学会了如何在Tezos区块链上创建FIFO合约!在下一课中,我们将进一步介绍SmartPy的一个强大功能——递归,可以让合约调用自身。祝大家编程愉快!

Isenção de responsabilidade
* O investimento em criptomoedas envolve grandes riscos. Prossiga com cautela. O curso não se destina a servir de orientação para investimentos.
* O curso foi criado pelo autor que entrou para o Gate Learn. As opiniões compartilhadas pelo autor não representam o Gate Learn.
It seems that you are attempting to access our services from a Restricted Location where Gate.io is unable to provide services. We apologize for any inconvenience this may cause. Currently, the Restricted Locations include but not limited to: the United States of America, Canada, Cambodia, Thailand, Cuba, Iran, North Korea and so on. For more information regarding the Restricted Locations, please refer to the User Agreement. Should you have any other questions, please contact our Customer Support Team.