这是关于在本体区块链网络上使用 Python 创建智能合约的系列教育文章的第三部分。 在之前的文章中我们认识了
现在您已经了解了在本体网络上使用Python开发智能合约时如何调用合适的持久存储API,让我们继续学习如何使用 运行时 API (合约执行API)。 Runtime API 有 8 个相关 API,为合约执行提供通用接口,帮助开发人员检索、转换和验证数据。
下面简单介绍一下8个API数据:
下面我们详细看看8个API数据如何使用。 在此之前,您可以在本体智能合约开发工具中创建新合约
如何使用运行时 API
有两种导入方式 运行时API:ontology.interop.System.Runtime и 本体.互操作.本体.运行时。 Ontology路径包含新添加的API。 下面的行导入 API 数据。
from ontology.interop.System.Runtime import GetTime, CheckWitness, Log, Notify, Serialize, Deserialize
from ontology.interop.Ontology.Runtime import Base58ToAddress, AddressToBase58, GetCurrentBlockHash
通知API
通知功能在整个网络中广播该事件。 在下面的示例中,Notify 函数将返回十六进制字符串“hello word”并在整个网络中广播它。
from ontology.interop.System.Runtime import Notify
def demo():
Notify("hello world")
您可以在日志中看到这一点:
获取时间API
GetTime 函数返回当前时间戳,即返回调用该函数的 Unix 时间。 计量单位是秒。
from ontology.interop.System.Runtime import GetTime
def demo():
time=GetTime()
return time # return a uint num
获取当前区块哈希 API
GetCurrentBlockHash 函数返回当前块的哈希值。
from ontology.interop.Ontology.Runtime import GetCurrentBlockHash
def demo():
block_hash = GetCurrentBlockHash()
return block_hash
序列化和反序列化
这是一对序列化和反序列化函数。 Serialize 函数将对象转换为 bytearray 对象,Deserialize 函数将 bytearray 转换为原始对象。 下面的代码示例转换传入的参数并将它们存储在合约的持久存储中。 它还从合约的持久存储中检索数据并将其转换为原始对象。
from ontology.interop.System.Runtime import GetTime, CheckWitness, Log, Notify, Serialize, Deserialize
from ontology.interop.System.Storage import Put, Get, GetContext
def Main(operation, args):
if operation == 'serialize_to_bytearray':
data = args[0]
return serialize_to_bytearray(data)
if operation == 'deserialize_from_bytearray':
key = args[0]
return deserialize_from_bytearray(key)
return False
def serialize_to_bytearray(data):
sc = GetContext()
key = "1"
byte_data = Serialize(data)
Put(sc, key, byte_data)
def deserialize_from_bytearray(key):
sc = GetContext()
byte_data = Get(sc, key)
data = Deserialize(byte_data)
return data
Base58ToAddress 和 AddressToBase58
这对地址转换函数。 Base58ToAddress函数将base58编码的地址转换为bytearray地址,AddressToBase58将bytearray地址转换为base58编码的地址。
from ontology.interop.Ontology.Runtime import Base58ToAddress, AddressToBase58
def demo():
base58_addr="AV1GLfVzw28vtK3d1kVGxv5xuWU59P6Sgn"
addr=Base58ToAddress(base58_addr)
Log(addr)
base58_addr=AddressToBase58(addr)
Log(base58_addr)
检查证人
CheckWitness(fromAcct) 函数有两个功能:
- 验证当前函数的调用者是否为 fromAcct。 如果是(即签名验证通过),函数返回。
- 检查调用当前函数的对象是否是合约。 如果是合约,并且函数是从合约中执行的,那么验证就通过了。 即验证fromAcct是否是GetCallingScriptHash()的返回值。 GetCallingScriptHash()函数可以获取当前智能合约的合约哈希值。
GetCallingScriptHash():
更多关于
from ontology.interop.System.Runtime import CheckWitness
from ontology.interop.Ontology.Runtime import Base58ToAddress
def demo():
addr=Base58ToAddress("AW8hN1KhHE3fLDoPAwrhtjD1P7vfad3v8z")
res=CheckWitness(addr)
return res
更多信息可以在
文章由编辑翻译
算力&份额 特别是对于OntologyRussia。
你是开发者吗? 加入我们的技术社区
本体论
来源: habr.com