听说Python的广告刷爆了你的朋友圈
zmhg799417
发表于 2023-1-10 00:02:09
171
0
0
使用 DynamicAppCall 函数前需要将其引入。这可以通过下面的语句实现: y5 N2 w" G" E/ i2 \2 ~
from ontology.interop.System.App import DynamicAppCall! p" D7 V- k6 E; h ]
2.1 DynamicAppCall API( ~! V" B d( U' Y
DynamicAppCall API 有三个参数,分别对应被调用合约的哈希反序,被调用合约方法和被调用方法所需要的参数。我们准备两个智能合约,合约 A 与合约 B。接下来我们通过合约 A 来动态调用合约 B 的功能函数。( e7 W0 ~( s# F5 }; }1 Z
合约 A 的代码如下:2 y" X+ h8 }) T
特别注意:获取合约 B 的合约哈希后,需要将其反序后再作为调用合约 A 时的参数传入。7 j! @' G* }( e! ]4 A, e0 b: \
from ontology.interop.System.App import DynamicAppCall/ K* d7 k! T( `
from ontology.interop.System.Runtime import Notify8 g, d2 |; x; o8 h I a+ Q* J
def Main(operation, args):1 h7 `, r2 Q# m) q0 C. r- ~
if operation == "DynamicCallContract":
if len(args) != 3:
return False9 M) j5 }0 _+ k1 n# w5 g9 I
revesedContractAddress = args[0]4 e: ^8 B. `* S. m5 G2 O
opt = args[1]& c) W% @8 D4 g
params = args[2]
return DynamicCallContract(revesedContractAddress, opt, params)- t- j: _8 M5 F9 s" h' D9 w
return False$ v& f+ U; O% @
def DynamicCallContract(revesedContractAddress, operation, params):
res = DynamicAppCall(revesedContractAddress, operation, [params])
Notify(["the result of the DynamicCall is: ", res])
return res
/ x) _- H n3 Y. n) }& Y4 r
合约 B。也是最简单的 Hello World 合约。合约 A 将调用合约 B 中的 Hello 函数。
特别注意:需要先部署合约 B,获取合约 B 的合约哈希。
from ontology.interop.System.Runtime import Notify
def Main(operation, args):
if operation == 'Hello':0 Y7 { j2 c1 ]+ e9 f
msg = args[0]$ v4 @3 @8 M+ h! R5 A. l6 w
return Hello(msg)
return False. Y% M1 W6 P/ `1 i: m
def Hello(msg):( T8 d( {' L1 H( i2 |
return msg: c$ p& a. U% o" C
此外,我们推荐在合约 A 中预留接口,对 B 合约哈希的反序进行存储 (注意存储时,value 的类型应为 bytearray)。当我们通过合约 A 调用合约 B 时,可将被存储的 B 合约哈希取出填充到 DynamicAppCall() 中的第一个参数位置。. J: b8 b6 s+ l6 |) S/ S7 r
这样做的好处有:7 a% z( W4 Q! M' M
% U# e. k. F# D. [* _) r' M
不用每次调用方法时,传入 B 合约的哈希反序;
: o$ z* z+ z+ p9 I2 d- _
对于函数调用者而言,合约 B 的哈希是隐形的,可以预先在合约 A 中方便地进行设置,进而保留了动态调用的灵活性,同时也包含了 RegisterAppCall 接口传参的简洁性。
B* W3 z7 i# B' e1 i3 a6 m8 s; U
03 SmartX 示例( `' _: i6 Y& Q' N- ?$ s
部署合约 B,得到其合约哈希为028de32923bcc21e8a5485e4b0e81eff2d9ba08e;点击工具栏使用Hex String (Big-endian/Little-endian),将合约哈希反序得到8ea09b2dff1ee8b0e485548a1ec2bc2329e38d02;部署合约 A;在 SmartX 上选中合约 A 中的 DynamicCallContract 方法,并设置参数:1 ^- y& S1 l8 k5 o$ @4 P
点击「运行预执行」,返回68656c6c6f20776f726c64 (Hello World 十六进制字符串), 调用成功。- v( \6 I" N* I% _9 v0 y
04 总结
这两期我们分别介绍了静态合约调用与动态合约调用。可以总结,二者的主要区别在于:1 p2 p+ H' Q4 O4 _. }0 t
静态合约调用需要写死合约地址(作为参数写入 RegisterAppCall),也就是说静态调用只能调用某个特定合约。而动态合约调用可以将合约地址作为参数传入,意味着可以没有限制地调用任意非 Native 合约。
静态合约调用合约地址无需反序,而动态调用合约地址需要反序。
成为第一个吐槽的人