Hi Guest

More contents, please log on!

Bitmere.com 区块链技术 Content
01 导语
上一期我们介绍了合约升级 API,讲述了如何销毁和迁移智能合约。本期我们讨论如何跨合约静态调用。API 只有一个,用法如下:

下面我们具体讲述一下这个 API 的使用方法。在这之前,小伙伴们可以在本体智能合约开发工具 SmartX 中新建一个合约,跟着我们进行操作。同样,在文章中我们将给出这次讲解的所有源代码以及视频讲解。

02 RegisterAppCall 使用方法
使用 RegisterAppCall 函数前同样需要引入,可以通过下面的语句实现:
from ontology.interop.System.App import RegisterAppCall
RegisterAppCall API 有三个参数。分别对应目标合约、目标方法和方法需要的参数。我们准备两个智能合约——合约 A 与合约 B。接下来我们通过合约 A 来静态调用合约 B 的功能函数。
合约 A 的代码如下:
  1. from ontology.interop.System.App import RegisterAppCall
  2. from ontology.interop.System.Runtime import Notify
  3. HelloWorld = RegisterAppCall('028de32923bcc21e8a5485e4b0e81eff2d9ba08e', 'operation', 'args') # 定位被调用的合约,执行静态调用
  4. def Main(operation, args):
  5.     if operation == "CallHello":
  6.         opt = args[0]
  7.         msg = args[1]
  8.         return CallHello(opt, msg)
  9.     return False
  10. def CallHello(opt, msg):
  11.     return HelloWorld(opt, [msg])
Copy the Code

合约 B 是最简单的 Hello World 合约,合约 A 将调用合约 B 中的 Hello 函数。
特别注意:需要先部署合约 B,获取合约 B 的合约哈希,并当作合约 A 中RegisterAppCall 函数的参数写入。
  1. def Main(operation, args):
  2.     if operation == 'Hello':
  3.         msg = args[0]
  4.         return Hello(msg)
  5.     return False
  6. def Hello(msg):
  7.     return msg
Copy the Code

03 SmartX 示例
部署合约 B,得到其合约哈希为028de32923bcc21e8a5485e4b0e81eff2d9ba08e;
将合约哈希写入合约 A 中的 RegisterAppCall 参数中;
部署合约 A;
运行 CallHello 函数
点击「运行预执行」,返回68656c6c6f20776f726c64(Hello World 十六进制字符串),表示调用成功。

04 总结
本次技术视点中我们介绍了如何跨合约静态调用,开发者可以准备两个智能合约——合约 A 与合约 B,通过合约 A 来静态调用合约 B 的功能函数。
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

蓝天天使2017 初中生
  • Follow

    0

  • Following

    0

  • Articles

    10

Promoted