AssemblyScript API
注意:如果您在
graph cli
或
graph ts
版本
0.22.0
之前创建了子图,那么您使用的是较旧版本的AssemblyScript,我们建议您查看
迁移指南
。
此页面记录了编写子图映射时可以使用的内置 API。有两种开箱即用的 API:
graph-ts
)
graph codegen
从子图文件生成的代码。
也可以添加其他库作为依赖项,只要它们与 AssemblyScript 兼容。 由于这是汇编语言映射,因此可以参考 AssemblyScript wiki 了解相应的语言和标准库功能。
使用
graph init
创建的子图带有预配置的依赖项。 安装这些依赖项只需运行以下命令之一:
yarn install # Yarnnpm install # NPM
如果子图是从头开始创建的,则以下两个命令之一将安装 Graph TypeScript 库作为依赖项:
yarn add --dev @graphprotocol/graph-ts # Yarnnpm install --save-dev @graphprotocol/graph-ts # NPM
@graphprotocol/graph-ts
库提供以下 API:
以太坊
API。
存储
API。
log
API。
ipfs
API。
json
API。
crypto
API。
子图清单中的
apiVersion
指定了由 Graph 节点为给定子图运行的映射 API 版本。 当前的映射 API 版本是 0.0.6。
版本 | Release 说明 |
---|---|
0.0.7 |
在以太坊类型中添加了
TransactionReceipt
和
Log
类
添加了
收据
字段到以太坊事件对象
|
0.0.6 |
向以太坊交易对象添加了
nonce
字段 向 Etherum 区块对象
添加
baseFeePerGas
|
0.0.5 |
AssemblyScript 升级到版本 0.19.10(这包括重大更改,参阅
迁移指南
)
ethereum.transaction.gasUsed
重命名为
ethereum.transaction.gasLimit
|
0.0.4 |
向以太坊智能合约唤起对象添加了
功能
签名字段
|
0.0.3 |
从
字段添加到以太坊唤起对象
Etherem.call. 地址
重命名为
ethereum.call.to
|
0.0.2 |
添加了以太坊交易对象的
输入
字段
|
可以在 AssemblyScript wiki 中找到有关 AssemblyScript 中内置的基本类型的文档。
@graphprotocol/graph-ts
提供了以下附加类型。
从'@graphprotocol/graph-ts'导入{ ByteArray }
ByteArray
表示
u8
的数组。
From I32(x: i32): ByteArray
-将
x
分解为字节。
From HexString (hex: string): ByteArray
-输入长度必须是偶数。前缀为
0x
是可选的。
toHexString (): string
-转换为前缀为
0x
的十六进制字符串。
toString (): string
-将字节解释为 UTF-8的字符串。
toBase58(): string
-将字节编码为 base58字符串。
toU32(): u32
-将字节解释为 little-endian
u32
。在溢出情况下抛出。
toI32(): i32
-将字节数组解释为little-endian
i32
。在溢出情况下抛出。
等于(y: 字节数组): bool
-可以写成
x = = y
。
Concat (其他: 字节数组) : ByteArray
-返回一个新的
ByteArray
,其中包含
这个
函数,然后是
other
。
ConcatI32(other: i32) : ByteArray
-返回一个新的
ByteArray
,该 ByteArray 由
this
直接组成,其后是
other
的字节表示形式。
从“@Graphprotocol/graph-ts”导入{ BigDecimal }
BigDecimal
用于表示任意精度的小数。
注意:
内部
BigDecimal
以
IEEE-754 decimal128浮点格式
存储,该格式支持34位有效小数位。这使得
BigDecimal
不适合表示跨度大于34位的定点类型,例如 Solidty
ufixed256x18
或等效的定点类型。
构造函数(bigInt: BigInt)
-从
BigInt
创建一个
BigDecimal
。
static from String (s: string): BigDecimal
-从十进制字符串解析。
toString (): string
- 打印为十进制字符串。
加(y: BigDecimal): BigDecimal
–可以写成
x + y
.
减(y: BigDecimal): BigDecimal
– 可以写成
x - y
.
乘(y: BigDecimal): BigDecimal
– 可以写成
x * y
.
除(y: BigDecimal): BigDecimal
– 可以写成
x / y
.
等于(y: BigDecimal): bool
– 可以写成
x == y
.
不等于(y: BigDecimal): bool
– 可以写成
x != y
.
小于(y: BigDecimal): bool
– 可以写成
x < y
.
小于等于(y: BigDecimal): bool
– 可以写成
x <= y
.
大于(y: BigDecimal): bool
– 可以写成
x > y
.
大于等于(y: BigDecimal): bool
– 可以写成
x >= y
.
负(): BigDecimal
- 可以写成
-x
.
从'@graphprotocol/graph-ts'导入{ BigInt }
BigInt
用于表示大整数。 这包括
uint32
到
uint256
和
int64
到
int256
类型的以太坊值。
uint32
下的所有内容,例如
int32
、
uint24
或
int8
都表示为
i32
。
BigInt
类具有以下 API:
BigInt.fromI32(x: i32): BigInt
-从
i32
创建一个
BigInt
。
BigInt.fromString(s: string): BigInt
– 从字符串中解析
BigInt
。
BigInt.fromUnsignedBytes(x: Bytes): BigInt
– 将
字节
解释为一个无符号的little-endian整数。如果您输入的是 big-endian,请首先调用
转换()
。
BigInt.fromSignedBytes(x: Bytes): BigInt
–将
字节
解释为有符号的little-endian整数。如果您输入的是 big-endian,请首先调用
转换()
。
x.toHex(): string
–将
BigInt
转换为十六进制字符串。
x.toString(): string
– 将
BigInt
转换为十进制数字字符串。
x.toI32(): i32
– 将
BigInt
作为
i32
返回; 如果值不适合
i32
,则失败。最好先检查
x.isI32()
。
x.toBigDecimal(): BigDecimal
- 转换为没有小数部分的小数
x.plus(y: BigInt): BigInt
– 可以写成
x + y
.
x.minus(y: BigInt): BigInt
– 可以写成
x - y
.
x.times(y: BigInt): BigInt
– 可以写成
x * y
.
x.div(y: BigInt): BigInt
– 可以写成
x / y
.
x.mod(y: BigInt): BigInt
– 可以写成
x % y
.
x.equals(y: BigInt): bool
– 可以写成
x == y
.
x.notEqual(y: BigInt): bool
– 可以写成
x != y
.
x.lt(y: BigInt): bool
– 可以写成
x < y
.
x.le(y: BigInt): bool
– 可以写成
x <= y
.
x.gt(y: BigInt): bool
– 可以写成
x > y
.
x.ge(y: BigInt): bool
– 可以写成
x >= y
.
x.neg(): BigInt
– 可以写成
-x
.
x.divDecimal(y: BigDecimal): BigDecimal
– 除以十进制,得到十进制结果。
x.isZero(): bool
– 方便检查数字是否为零。
x.isI32(): bool
– 检查数字是否适合
i32
。
x.abs(): BigInt
– 绝对值。
x.pow(exp: u8): BigInt
– 指数。
bitOr(x: BigInt, y: BigInt): BigInt
– 可以写成
x | y
.
bitAnd(x: BigInt, y: BigInt): BigInt
– 可以写成
x & y
.
leftShift(x: BigInt, bits: u8): BigInt
– 可以写成
x << y
.
rightShift(x: BigInt, bits: u8): BigInt
– 可以写成
x >> y
.
从'@graphprotocol/graph-ts'导入{ TypedMap }
类型化映射
可用于存储密钥值对。请参见
此示例
。
TypedMap
类具有以下 API:
new TypedMap<K, V>()
– 创建一个空映射,密钥为
K
,值为
T
map.set(key: K, value: V): void
– 将
密钥
的值设置为
value
map.getEntry(key: K): TypedMapEntry<K, V> | null
– 返回某个
密钥
的密钥值对,如果该
密钥
在映射中不存在,则返回
无效
map.get(key: K): V | null
– 返回一个
密钥
的值,或者如果该
密钥
在映射中不存在,则返回
无效
map.isSet(key: K): bool
–如果
密钥
存在于映射中,返回
真
; 如果不存在,返回
假
从 '@graphprotocol/graph-ts'导入{ Bytes }
字节
用于表示任意长度的字节数组,包括
字节
类型的以太坊值、
bytes32
等。
字节
类扩展了 AssemblyScript 的
Uint8Array
,它支持所有
Uint8Array
功能,以及以下新方法:
From HexString (hex: string) : Bytes
-将必须包含偶数个
十六进制
数字的字符串十六进制转换为
ByteArray
。字符串
十六进制
可以选择以
0x
开始
fromI32(i: i32) : Bytes
-将
i
转换为字节数组
b.toHex()
–返回表示数组中字节的十六进制字符串
b.toString()
– 将数组中的字节转换为 Unicode 字符串
b.toBase58()
– 将以太坊值转换为 base58编码(用于 IPFS hashes)
b.Concat (其他: 字节) : Byte
-返回新的
字节
,其中包含
这个
字节,然后是
其他
。
b.ConcatI32(other: i32) : ByteArray
-返回新的
字节数组
,该字节数组由
这个
直接组成,其后是
其他
的字节表示形式。
从 '@graphprotocol/graph-ts'导入{ Address }
地址
扩展了
字节
以表示以太坊
地址
值。
它在
字节
API 之上添加了以下方法:
Address.fromString(s: string): Address
–从十六进制字符串创建一个
地址
Address.fromBytes(b: Bytes): Address
-从
b
中创建一个必须正好是20个字节长的
地址
。传入字节数较少或较多的值将导致错误
从 '@graphprotocol/graph-ts'导入 { store }
存储
API 允许从图形节点存储中加载、保存和删除实体。
写入存储的实体与子图的 GraphQL 模式中定义的
@entity
类型一一对应。 为了方便使用这些实体,
Graph CLI
提供的
graph codegen
命令可以用来生成实体类。这些实体类是内置
Entity
类型的子类,具有模式中字段的属性获取和设置方法,以及加载和保存这些实体的方法。
以下是从以太坊事件创建实体的常见模式。
/ Import the Transfer event class generated from the ERC20 ABIimport { Transfer as TransferEvent } from '../generated/ERC20/ERC20'// Import the Transfer entity type generated from the GraphQL schemaimport { Transfer } from '../generated/schema'// Transfer event handlerexport function handleTransfer(event: TransferEvent): void {// Create a Transfer entity, using the transaction hash as the entity IDlet id = event.transaction.hashlet transfer = new Transfer(id)// Set properties on the entity, using the event parameterstransfer.from = event.params.fromtransfer.to = event.params.totransfer.amount = event.params.amount// Save the entity to the storetransfer.save()}
如果在处理链时遇到
Transfer
事件,它会使用生成的
Transfer
类型(别名为
TransferEvent
以避免与实体类型的命名冲突) 传递给
handleTransfer
事件处理器。 此类型允许访问事件的母交易及其参数等数据。
每个实体都必须有一个唯一的 ID 以避免与其他实体发生冲突。 事件参数包含可以使用的唯一标识符是相当常见的。 注意:使用交易hash作为 ID 时, 假定同一交易中没有其他事件创建以该hash作为 ID 的实体。
如果实体已经存在,则可以使用以下内容从存储中加载它:
let id = event.transaction.hash // or however the ID is constructedlet transfer = Transfer.load( id)if (transfer == null) {transfer = new Transfer(id)}// Use the Transfer entity as before
由于实体可能尚不存在于存储中,因此
load
方法返回一个
Transfer | null
。 因此,在使用该值之前,需要检查值为
null
情况。
注意: 仅当映射中所做的更改依赖于实体的先前数据时,才需要加载实体。 有关更新现有实体的两种方法,请参阅下一节。
graph-节点
v0.31.0、
@graphprotocol/graph-ts
v0.30.0和
@graphproto协议/graph cli
v0.49.0起,
loadInBlock
方法可用于所有实体类型。
存储API有助于检索在当前区块中创建或更新的实体。这方面的一种典型情况是,一个处理程序从某个链上事件创建一个,之交易后的处理程序希望访问该交易(如果存在)。在交易不存在的情况下,子图必须去数据库才能发现实体不存在;如果子图作者已经知道实体必须是在同一个区块中创建的,那么使用loadInBlock可以避免这种数据库往返。对于某些子图,这些遗漏的查找可能会显著增加索引时间。
let id = event.transaction.hash // or however the ID is constructedlet transfer = Transfer.loadInBlock(id)if (transfer == null) {transfer = new Transfer(id)}// Use the Transfer entity as before
注意:如果在给定的区块中没有创建实体,则
loadInBlock
将返回
null
,即使存储中有具有给定ID的实体。
graph-节点
v0.31.0、
@graphprotocol/graph-ts
v0.31.0和
@graphproto协议/graph cli
v0.51.0起,
loadInBlock
方法可用于所有实体类型。
这允许从事件处理程序中加载派生实体字段。例如,给定以下模式:
type Token @entity {id: ID!holder: Holder!color: String}type Holder @entity {id: ID!tokens: [Token!]! @derivedFrom (field: "holder")}
以下代码将加载
Holder
实体来源的
Token
实体:
let holder = Holder.load('test-id')// Load the Token entity that the Holder entity was derived fromlet token = holder.tokens.load()
有两种方法可以更新现有实体:
Transfer.load(id)
加载实体,在实体上设置属性,然后调用
.save()
将其返回到存储。
new Transfer(id)
创建实体,在实体上设置属性,然后调用
.save()
将其保存到存储。 如果实体已经存在,则将更改合并到其中。
由于生成的属性设置器,在大多数情况下更改属性是直截了当的:
let transfer = new Transfer(id)transfer.from = ...transfer.to = ...transfer.amount = ...
也可以使用以下两条指令之一取消设置属性:
transfer.from.unset()transfer.from = null
这仅适用于可选属性,即在 GraphQL 中没有
!
声明的属性。 两个例子是
owner: Bytes
或
amount: BigInt
。
更新数组属性有点复杂,因为从实体获取数组会创建该数组的副本。 这意味着必须在更改数组后必须再次显式设置数组属性。 以下代码假设
entity
有
numbers: [BigInt!]!
字段。
// This won't workentity.numbers.push(BigInt.fromI32(1))entity.save()// This will worklet numbers = entity.numbersnumbers.push(BigInt.fromI32(1))entity.numbers = numbersentity.save()
目前无法通过生成的类型删除实体。 相反,删除实体需要将实体类型的名称和实体 ID 传递给
store.remove
:
import { store } from '@graphprotocol/graph-ts'...let id = event.transaction.hashstore.remove('Transfer', id)
以太坊 API 提供对智能合约、公共状态变量、合约函数、事件、交易、区块和编码/解码以太坊数据的访问。
与实体一样,
graph codegen
为子图中使用的所有智能合约和事件生成类。 为此,合约 ABI 需要成为子图清单中数据源的一部分。 通常,ABI 文件存储在
abis/
文件夹中。
通过生成的类,以太坊类型和 内置类型 之间的转换发生在幕后,因此子图开发者不必担心。
以下示例说明了这一点。 给定一个子图模式,如
type Transfer @entity {from: Bytes!to: Bytes!amount: BigInt!}
和以太坊上的
Transfer(address,address,uint256)
事件签名,
from
、
to
和
amount
值
address
类型,
address
和
uint256
被转换为
Address
和
BigInt
,允许它们被传递给
Transfer
实体的
Bytes!
和
BigInt!
属性:
let id = event.transaction.hash.toHex()let transfer = new Transfer(id)transfer.from = event.params.fromtransfer.to = event.params.totransfer.amount = event.params.amounttransfer.save()
传递给事件处理程序的以太坊事件,例如前面示例中的
Transfer
事件,不仅提供对事件参数的访问,还提供对它们的父事务和它们所属的块的访问。以下数据可以从
event
实例中获取(这些类是
graph-ts
中
ethereum
模块的一部分):
class Event {address: AddresslogIndex: BigInttransactionLogIndex: BigIntlogType: string | nullblock: Blocktransaction: Transactionparameters: Array<EventParam>receipt: TransactionReceipt | null}class Block {hash: BytesparentHash: BytesunclesHash: Bytesauthor: AddressstateRoot: BytestransactionsRoot: BytesreceiptsRoot: Bytesnumber: BigIntgasUsed: BigIntgasLimit: BigInttimestamp: BigIntdifficulty: BigInttotalDifficulty: BigIntsize: BigInt | nullbaseFeePerGas: BigInt | null}class Transaction {hash: Bytesindex: BigIntfrom: Addressto: Address | nullvalue: BigIntgasLimit: BigIntgasPrice: BigIntinput: Bytesnonce: BigInt}class TransactionReceipt {transactionHash: BytestransactionIndex: BigIntblockHash: BytesblockNumber: BigIntcumulativeGasUsed: BigIntgasUsed: BigIntcontractAddress: Addresslogs: Array<Log>status: BigIntroot: ByteslogsBloom: Bytes}class Log {address: Addresstopics: Array<Bytes>data: BytesblockHash: BytesblockNumber: BytestransactionHash: BytestransactionIndex: BigIntlogIndex: BigInttransactionLogIndex: BigIntlogType: stringremoved: bool | null}
graph codegen
生成的代码还包括子图中使用的智能合约的相关类。 这些可用于访问公共状态变量,并在当前区块调用合约的函数。
一种常见的模式是访问事件起源的合约。 这是通过以下代码实现的:
// Import the generated contract class and generated Transfer event classimport { ERC20Contract, Transfer as TransferEvent } from '../generated/ERC20Contract/ERC20Contract'// Import the generated entity classimport { Transfer } from '../generated/schema'export function handleTransfer(event: TransferEvent) {// Bind the contract to the address that emitted the eventlet contract = ERC20Contract.bind(event.address)// Access state variables and functions by calling themlet erc20Symbol = contract.symbol()}
此处
Transfer
别名为
TransferEvent
,以避免与实体类型发生命名冲突。
只要以太坊上的
ERC20Contract
有一个名为
symbol
的公共只读函数,就可以用
.symbol()
进行调用。 对于公共状态变量,会自动创建一个具有相同名称的方法。
作为子图一部分的任何其他合约都可以从生成的代码中导入,并且可以绑定到一个有效地址。
如果您合约的只读方法可能会重复使用,那么您应该通过调用生成的以
try_
为前缀的合约方法来处理它。 例如,Gravity 合约公开了
gravatarToOwner
方法。 此代码将能够处理该方法中的重复使用:
let gravity = Gravity.bind(event.address)let callResult = gravity.try_gravatarToOwner(gravatar)if (callResult.reverted) {log.info('getGravatar reverted', [])} else {let owner = callResult.value}
请注意,连接到 Geth 或 Infura 客户端的 Graph 节点可能无法检测到所有重复使用,如果您依赖于此,我们建议使用连接到 Parity 客户端的 Graph 节点。
使用
ethereum
模块中的
encode
和
decode
函数,可以根据以太坊的 ABI 编码格式对数据进行编码和解码。
import { Address, BigInt, ethereum } from '@graphprotocol/graph-ts'let tupleArray: Array<ethereum.Value> = [ethereum.Value.fromAddress(Address.fromString('0x0000000000000000000000000000000000000420')),ethereum.Value.fromUnsignedBigInt(BigInt.fromI32(62)),]let tuple = tupleArray as ethereum.Tuplelet encoded = ethereum.encode(ethereum.Value.fromTuple(tuple))!let decoded = ethereum.decode ('(address,uint256)', encoded)
查询更多的信息:
从 '@graphprotocol/graph-ts'导入 { log }
log
API 允许子图将信息记录到 Graph 节点标准输出以及 Graph 浏览器。 可以使用不同的日志级别记录消息。有一个基本格式字符串语法可以用来编写带参数的日志消息。
log
API 包括以下函数:
log.debug(fmt: string, args:Array<string>): void
- 记录调试消息。
log.info(fmt: string, args:Array<string>): void
- 记录信息性消息。
log.warning(fmt: string, args: <string>): void
- 记录警告。
log.error(fmt: string, args: <string>): void
- 记录一条错误消息。
log.critical(fmt: string, args: <string>): void
– 记录一条关键消息
并
终止子图。
log
API 采用格式字符串和字符串值数组,然后用数组中的字符串值替换占位符。 第一个
{}
占位符被数组中的第一个值替换,第二个
{}
占位符被第二个值替换,依此类推。
log.info('Message to be displayed: {}, {}, {}', [value.toString(), anotherValue.toString(), 'already a string'])
在下面的示例中,字符串值“A”在被记录之前被传递到一个数组中成为
['A']
:
let myValue = 'A'export function handleSomeEvent(event: SomeEvent): void {// Displays : "My value is: A"log.info('My value is: {}', [myValue])}
在下面的示例中,尽管参数数组包含三个值,只有该数组的第一个值被记录了。
let myArray = ['A', 'B', 'C']export function handleSomeEvent(event: SomeEvent): void {// Displays : "My value is: A" (Even though three values are passed to `log.info`)log.info('My value is: {}', myArray)}
参数数组中的每个条目都需要在日志消息字符串中有自己的占位符
{}
。 下面的示例在日志消息中包含三个占位符
{}
。 因此,
myArray
中的所有三个值都会被记录。
let myArray = ['A', 'B', 'C']export function handleSomeEvent(event: SomeEvent): void {// Displays : "My first value is: A, second value is: B, third value is: C"log.info('My first value is: {}, second value is: {}, third value is: {}', myArray)}
要在数组中显示特定值,必须提供它的索引值。
export function handleSomeEvent(event: SomeEvent): void {// Displays : "My third value is C"log.info('My third value is: {}', [myArray[2]])}
下面的例子记录了一个事件的区块号、区块hash和交易hash:
import { log } from '@graphprotocol/graph-ts'export function handleSomeEvent(event: SomeEvent): void {log.debug('Block number: {}, block hash: {}, transaction hash: {}', [event.block.number.toString(), // "47596000"event.block.hash.toHexString(), // "0x..."event.transaction.hash.toHexString(), // "0x..."])}
从 '@graphprotocol/graph-ts'导入{ ipfs }
智能合约偶尔会在链上锚定 IPFS 文件。 这允许映射从合约中获取 IPFS hash并从 IPFS 读取相应的文件。 文件数据将以
Bytes
形式返回,这通常需要进一步处理,例如使用本页后面记录的
json
API 进行处理。
给定一个 IPFS hash或路径,从 IPFS 读取文件的过程如下:
// Put this inside an event handler in the mappinglet hash = 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D'let data = ipfs.cat(hash)// Paths like `QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile`// that include files in directories are also supportedlet path = 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D/Makefile'let data = ipfs.cat(path)
**注意: **
ipfs.cat
目前不是确定性的。如果在请求超时之前无法通过 IPFS 网络检索该文件,它将返回
null
。因此,总是值得检查结果是否为
null
。
还可以使用
ipfs.map
以流方式处理较大的文件。 该函数需要 IPFS 文件的hash或路径、回调的名称以及修改其行为的标志:
import { JSONValue, Value } from '@graphprotocol/graph-ts'export function processItem(value: JSONValue, userData: Value): void {// See the JSONValue documentation for details on dealing// with JSON valueslet obj = value.toObject()let id = obj.get('id')let title = obj.get('title')if (!id || !title) {return}// Callbacks can also created entitieslet newItem = new Item(id)newItem.title = title.toString()newitem.parent = userData.toString() // Set parent to "parentId"newitem.save()}// Put this inside an event handler in the mappingipfs.map('Qm...', 'processItem', Value.fromString('parentId'), ['json'])// Alternatively, use `ipfs.mapJSON`ipfs.mapJSON('Qm...', 'processItem', Value.fromString('parentId'))
当前支持的唯一标志是
json
,它必须传递给
ipfs.map
。 使用
json
标志,IPFS 文件必须包含一系列 JSON 值,每行一个值。 对
ipfs.map
的调用将读取文件中的每一行,将其反序列化为
JSONValue
并为每一行调用回调函数。 回调函数可以使用实体操作存储来自
JSONValue
的数据。 实体更改仅在调用
ipfs.map
的处理程序成功完成时存储; 同时,它们被保存在内存中,因此
ipfs.map
可以处理的文件的大小是有限的。
成功时,
ipfs.map
返回
void
。 如果回调函数的任何调用导致错误,则调用
ipfs.map
的处理程序将被中止,并且子图被标记为失败。
从'@graphprotocol/graph-ts'导入{ crypto }
crypto
API 使加密函数可用于映射。 目前,只有一个函数:
crypto.keccak256(input: ByteArray): ByteArray
从'@graphprotocol/graph-ts'导入{ json, JSONValueKind }
JSON 数据可以使用
json
API 进行解析:
json.fromBytes(data: Bytes): JSONValue
– 解析来自
Bytes
数组的 JSON 数据,解释为有效的 UTF-8 序列
json.try_fromBytes(data: Bytes): Result<JSONValue, boolean>
–
json.fromBytes
的安全版本, 如果解析失败则返回错误变体
json.fromString(data: string): JSONValue
– 从有效的 UTF-8
String
解析 JSON 数据
json.try_fromString(data: Bytes): Result<JSONValue, boolean>
–
json.fromString
的安全版本, 如果解析失败则返回错误变体
JSONValue
类提供了一种从任意 JSON 文档中提取值的方法。 由于 JSON 值可以是布尔值、数字、数组等,因此
JSONValue
带有一个
kind
属性来检查值的类型:
let value = json.fromBytes(...)if (value.kind == JSONValueKind.BOOL) {...}
此外,还有一个方法可以检查该值是否为
空
:
value.isNull(): boolean
当值的类型确定时,可以使用以下方法之一将其转换为 内置类型 :
value.toBool(): boolean
value.toI64(): i64
value.toF64(): f64
value.toBigInt(): BigInt
value.toString(): string
value.toArray(): Array<JSONValue>
- (然后使用上述 5 种方法之一转换
JSONValue
)
源 | 目标 | 转换函数 |
---|---|---|
地址 | 字节 | none |
地址 | 字符串 | s.toHexString() |
BigDecimal | 字符串 | s.toString() |
BigInt | BigDecimal | s.toBigDecimal() |
BigInt | String (hexadecimal) | s.toHexString() 或 s.toHex() |
BigInt | 字符串 (unicode) | s.toString() |
BigInt | i32 | s.toI32() |
Boolean | Boolean | none |
字节 (签字) | BigInt | BigInt.fromSignedBytes(s) |
字节(未签字) | BigInt | BigInt.fromUnsignedBytes(s) |
字节 | 字串(十六进制) | s.toHexString() 或 s.toHex() |
字节 | 字符串 (unicode) | s.toString() |
字节 | 字符串 (base58) | s.toBase58() |
字节 | i32 | s.toI32() |
字节 | u32 | s.toU32() |
字节 | JSON | json.fromBytes(s) |
int8 | i32 | none |
int32 | i32 | none |
int32 | BigInt | Bigint.fromI32(s) |
uint24 | i32 | none |
int64 - int256 | BigInt | none |
uint32 - uint256 | BigInt | none |
JSON | boolean | s.toBool() |
JSON | i64 | s.toI64() |
JSON | u64 | s.toU64() |
JSON | f64 | s.toF64() |
JSON | BigInt | s.toBigInt() |
JSON | 字符串 | s.toString() |
JSON | 数组 | s.toArray() |
JSON | 对象 | s.toObject() |
字符串 | 地址 | Address.fromString(s) |
字节 | 地址 | Address.fromString(s) |
字符串 | BigInt | BigDecimal.fromString(s) |
字符串 | BigDecimal | BigDecimal.fromString(s) |
字串(十六进制) | 字节 | 字节数组.fromHexString(s) |
字符串 (UTF-8) | 字节 | 字节数组.fromUTF8(s) |
您可以通过
dataSource
命名空间检查调用处理程序数据源的合约地址、网络和内容:
dataSource.address(): Address
dataSource.network(): string
dataSource.context(): DataSourceContext
基本的
Entity
类和
DataSourceContext
子类可以帮助动态设置和获取字段:
setString(key: string, value: string): void
setI32(key: string, value: i32): void
setBigInt(key: string, value: BigInt): void
setBytes(key: string, value: Bytes): void
setBoolean(key: string, value: bool): void
setBigDecimal(key, value: BigDecimal): void
getString(key: string): string
getI32(key: string): i32
getBigInt(key: string): BigInt
getBytes(key: string): Bytes
getBoolean(key: string): boolean
getBigDecimal(key: string): BigDecimal