Hi Guest

More contents, please log on!

Bitmere.com 区块链技术 Content

Python智能合约教程之合约升级

zmhg799417
15 0 0
01 导语
在上一期的技术视点中,我们介绍了合约原生 API,讲述了如何利用智能合约进行ONT / ONG 转账。本期我们将讨论如何通过 Upgrade API 来进行合约升级。合约升级共有2个 API,分别为 Destroy 和 Migrate。其用法如下:

下面我们具体讲述一下这两个 API 的使用方法。在这之前,小伙伴们可以在本体智能合约开发工具 SmartX 中新建一个合约,跟着我们进行操作。跟以前的 API 讲解一样,在文章最后我们将给出这次讲解的视频示例。
02 Upgrade API 使用方法
使用这两个函数前需要引入。下面两条语句分别引入了 Migrate 和 Destroy 这两个函数。
from ontology.interop.Ontology.Contract import Migrate
from ontology.interop.System.Contract import Destroy
2.1 Destroy API
Destroy API 用于销毁合约,旧合约将会在链上被删除。下面是使用该 API 的示例代码。
from ontology.interop.System.Runtime import Notify
def Main(operation, args):
    if operation == "destroy_contract":
        return destroy_contract()
    return False
def destroy_contract():
    Destroy() # 调用destroy 销毁此合约
    Notify(["The contract has been destoryed"])
    return True
在 SmartX 上可以看到该示例代码的运行结果:
将以上代码粘贴至 SmartX 编译并部署;
再次点击部署会弹出「合约部署失败,该合约已经部署过」,因为链上已经存在相同合约;

运行 destroy_contract 函数销毁合约;

再次点击部署合约,会发现合约可以再次部署,不会再弹出「合约部署失败,该合约已经部署过」。这可以证明原先合约已经在链上被销毁。
2.2  Migrate API
Migrate API 用于迁移合约, 旧合约将会被新合约取代,旧合约中的数据也将自动迁移到新合约。迁移数据量越大,迁移费用越高。迁移成功后,旧合约会被删除。
特别注意:合约中的资产不会被自动迁移,需要提前转走。否则该合约中的资产将无法取回,相当于被转入黑洞地址。
Migrate 函数的传入参数列表如下:

同样,我们给出使用 Migrate 函数的合约示例代码:
from ontology.interop.System.Runtime import Notify
from ontology.libont import AddressFromVmCode
def Main(operation, args):
    if operation == "migrate_contract":
        if len(args) != 7:
            return False
        avm_code = args[0]
        need_storage = args[1]
        name = args[2]
        version = args[3]
        author = args[4]
        email = args[5]
        description = args[6]
        return migrate_contract(avm_code, need_storage, name, version, author, email, description)
    return False
def migrate_contract(avm_code, need_storage, name, version, author, email, description):
    res = Migrate(avm_code, need_storage, name, version, author, email, description) # 调用Migrate 迁移此合约
    if res:
        Notify(
["Migrate successfully"])
        new_contract_hash=AddressFromVmCode(avm_code) # 计算新合约地址
        Notify(new_contract_hash) # 打印出新合约地址
        return True
    else:
        return False
在 SmartX 上可以看到该示例代码的运行结果:
将以上代码粘贴至 SmartX 编译,填入参数。参数填入时需要特别注意以下两点:
a. 要确认 avm_code 在链上不存在,不然会报错;
b. Migrate 需要较高的 gas limit,所以运行函数时要调整 gas limit。

部署成功后,可以从控制台拿到新的合约哈希。该示例中,be4606c4663081b70f745ed9fc64d4c3b0d9c183 即为新的合约哈希。

03 结论
本次技术视点中我们介绍了本体区块链的 Upgrade API,开发者可以用来进行合约升级。合约升级共有2个 API,其中 Destroy API 用于销毁合约,Migrate API 用于迁移合约。希望教程会对大家有帮助。下一期我们将介绍本体 Python 智能合约语法的 Static & Dynamic Call API,讲述如何在 Python 智能合约中进行静态调用和动态调用。
BitMere.com is Information release platform,just provides information storage space services.
The opinions expressed are solely those of the author,Does not constitute advice, please treat with caution.
You have to log in before you can reply Login | 立即注册

Points Rules

Write the first review

zmhg799417 初中生
  • Follow

    0

  • Following

    0

  • Articles

    16

Promoted