bdcontract-doc/markdown_trans/markdown/YJSAPI.md

1385 lines
32 KiB
Markdown
Raw Permalink Normal View History

2022-08-05 10:29:30 +00:00
# YJS SDK
## YJS Build-in API
### Built-in object Global
### The built-in object Requester
The built-in object will have a value in the Export Function only if the contract callsignatureis verified.
### Execute the contract as executeContract
Parameters:
``` bash
action:executeContract;
contractID:合约的id或名称均可
operation:调用合约的方法名;
arg: 参数格式为JSON字符串有action与arg两个字段。
```
Optional parameters:
```bash
requestID:字符串类型自行生成用于查询hash
```
Example:
```javascript
function testExecutorContract(arg){
var ret = JSON.parse(executeContract("ElemeProvider","queryDB",arg));
if (ret.status == "Success"){
return JSON.parse(ret.result);
}else return null;
}
```
### Subscribe to the event subject Subscribe
parameter
``` bash
contractID字符串类型 合约id或名称均可。
event字符串类型
handler方法名该方法必须接受Event内含字段topic和content类型的唯一变量为参数可以不是export方法
```
Example:
```javascript
export function init(arg) {
YancloudUtil.subscribe("topic", handler);
print("Handler: " + handler);
}
function handler(e) {
print("topic: " + e.topic);
print("content: " + e.content);
}
```
### Publish the event pubEvent
parameter
``` bash
topic字符串类型发布的事件主题
content字符串类型发布的事件内容
```
Example:
```javascript
export function pub1(arg) {
YancloudUtil.pubEvent("topic", arg);
return "done";
}
```
You can also declare an event at the beginning of the contract, so the event name is the event subject, and you can publish the event directly using the event as the method name
```javascript
event topic;
export function pub2(arg) {
topic(arg);
return "done";
}
```
This is equivalent to `pub1` above.
### Publish pubEventConstraint with semantic event
parameter
``` bash
topic字符串类型发布的事件主题
content字符串类型发布的事件内容
semantics枚举类型作为字符串输入事件语义
```
Event semantic parameters
+ AT_LEAST_ONCE: at least once. Default semantics
+ AT_MOST_ONCE: at most once
+ ONLY_ONCE: only once
Example:
```javascript
export function pub1(arg) {
YancloudUtil.pubEventConstraint("topic", arg, "AT_MOST_ONCE");
return "done";
}
```
You can also declare the event at the beginning of the contract, and the event name is the event subject. In this case, you can simply use the event as the method name to publish the event according to the declared semantics
```javascript
event AT_MOST_ONCE topic;
export function pub2(arg) {
topic(arg);
return "done";
}
```
This is equivalent to `pub1` above.
Pre-declared events can be called with the suffix S as a method name regardless of semantics, publishing events of any semantics:
```javascript
event topic;
export function pub3(arg) {
topics(arg, "AT_MOST_ONCE");
return "done";
}
```
This is equivalent to `pub1, pub2` above.
* When an event is declared without event semantics, the semantics defaults to at least once (AT_LEAST_ONCE). *
### Accessing Resource Files
Run the global. Resources command to load the YPK internal resource file.
#### loadAsInputStream
Parameters:
```bash
path字符串类型 需要加载文件的地址
```
Example:
```javascript
var file = Global.Resources.loadAsInputStream("/deleteit.txt");
```
#### loadAsScanner
Parameters:
```bash
path字符串类型 需要加载文件的地址
```
Example:
```javascript
var scanner = Global.Resources.loadAsScanner("/local.txt");
```
### YancloudUtil
Some built-in tool methods are provided.
#### getKeyPair
Parameters:
```
```
Example:
```
var keyPair = YancloudUtil.getKeyPair();
//该类型为SM2KeyPair类型
print(keyPair.getPublicKeyStr());
print(keyPair.getPrivateKeyStr());
print(keyPair.toJson());
```
## YJS Build-in Annotation
### @Access
To set whether a contract call requires a signature, there are two types: signed and unsigned. Verified indicates that a signature is required. Others indicate that no signature is required.
```
@Access("verified")
export function easy(arg){
return "true";
}
```
### @LogType
The LogType annotation declares the logging type of a contract or function as an argument.
Arg indicates the contract execution parameter recorded in logs. Result indicates the return Result of recording the execution of the contract. Branch Indicates the Branch where contracts are executed.
For example, declare a function with the following LogType annotation
```
@LogType("Arg","Result","Branch")
export function easy(arg){
Global.a = "a";
Global.b = "b";
if(arg > 0)
return Global.a;
else
return Global.b;
}
```
### @LogLocation
This annotation can modify `contract` or `function`. Set the log storage location. Parameter“Dataware” is stored in the ledger and locally, if not, only locally. For example, use the following LogLocation to set the storage location.
In the BaaS platform, you can specify the name of the ledger. The default value of the BaaS platform is default, and `@LogLocation("bdledger:default")` is used. To save to a custom ledger, for example, the“ABC” ledger, use `@LogLocation("bdledger:abc")`
```
@LogLocation("dataware")
export function easy(arg){
Global.a = "a";
}
```
### @Permission
This annotation can only modify the permission of tool classes called in the `contract` setting contract, including File, Http, MySQL, MongoDB, RocksDB and other tool classes. If the above utility classes are used in the contract, corresponding authorization fields need to be added in the annotations. By default, only YancloudUtil is provided by YJS. An“Unauthorized utility class” exception is thrown if none is added. The six utility classes are described in detail later in this section.
```
@Permission("Http","File")
contract HttpPermission {
export function main(args){
var http=HttpUtil.httpGet(args);
var dir="adf/adfas/";
var file=FileUtil.getDir(dir);
return YancloudUtil.currentTimeMillis();
}
}
```
### @Description
This annotation can modify `contract` or `function`. Exported a description of the contract and function can be used to generate an introduction of the exported function in the exported document.
```
@Description("返回数据条目,无需参数")
export function count(args){
var sql = "select count(*) from data;";
var conn = getConn();
var statement = conn.createStatement();
var resultSet = statement.executeQuery(sql);
var c = {};
resultSet.next();
c.count = resultSet.getLong(1);
return JSON.stringify(c);
}
```
### @Param
This annotation can modify `function`. Provides examples of parameters to call the function, as well as default parameters to return results in the generation specification document.
```
@Param({"offset":0,"count":100})
export function get(args){
var offset = args.offset;
var count = args.count;
...
}
```
### @MockTemplate
This annotation can modify `function`. Provides a return mock data template for a function that describes the format of the return value. When invoked in debug mode with this annotation, returns simulated data generated in this format.
#### Specifies the supported field types
```
@integer 整数
@string 字符串
@boolean 布尔值
@date @time @datatime
@word 单词 @cword 中文单词
@first @last 英文姓,名
@cfirst @clast @cname 中文姓,名,全名
@url @domin @ip @email
@region @province @city @county 地区,省,市,县
……
详细格式可以参考http://mockjs.com/examples.html
```
#### Note that the template format is { result : template}
```json
//返回一个对象包含如下字段
@MockTemplate({'result':{'id':'@integer','email':'@email','password':'@string','name':'@name'}})
//返回
{"password":"3ZLc","name":"William Young","id":36097783842688,"email":"d.fuunwe@gqnr.to"}"
//返回元素个数为1-5个之间的一个数组数组的每个元素都是上述格式的一个对象
{'result|1-5':[{'id':'@integer','email':'@email','password':'@string','name':'@name'}]}
//返回
[
{"password":"dO]wW","name":"Jeffrey Lopez","id":1783453207480410,"email":"a.ckokgxrga@hgiesugi.bb"},
{"password":"BQYRL","name":"Brian Moore","id":4310212972071102,"email":"k.lbpxocydrh@msgnjtox.na"},
{"password":"Gw1","name":"Susan Jackson","id":7766580783668916,"email":"h.zjgusl@htce.cr"}
]
```
```
@MockTemplate({'result':{'id':'@integer','email':'@email','password':'@string','name':'@name'}})
export function count(args){
var sql = "select count(*) from data;";
var conn = getConn();
var statement = conn.createStatement();
var resultSet = statement.executeQuery(sql);
var c = {};
resultSet.next();
c.count = resultSet.getLong(1);
return JSON.stringify(c);
}
```
### @Result
This annotation can modify `function`. Provides an example of the return result of a function that, with this annotation, will be returned directly when the documentation is generated instead of calling the function with the default arguments.
```
@Result(666)
export function count(args){
var sql = "select count(*) from data;";
var conn = getConn();
var statement = conn.createStatement();
var resultSet = statement.executeQuery(sql);
var c = {};
resultSet.next();
c.count = resultSet.getLong(1);
return JSON.stringify(c);
}
```
### @Cost
This annotation can modify `function`. Provides the CPU metering function for functions.
```
@Cost({"countGas":true})
export function ....
```
## IO tools
### An overview of
|Name of the IO tool class|说明|
|---|---|
|[FileUtil](./YJSAPI.html#fileutil)| 文件操作相关的类 |
|[LedgerUtil](./YJSAPI.html#ledgerutil)| 账本操作相关的类 |
|[HttpUtil](./YJSAPI.html#httputil)| Http接口相关的类 |
|[DOIPUtil](./YJSAPI.html#doiputil)| DoIP相关的类 |
|[MySQLUtil](./YJSAPI.html#mysqlutil)| 连接mysql数据库 |
|[MongoDBUtil](./YJSAPI.html#mongodbutil)| MongoDB连接相关的类 |
|[RocksDBUtil](./YJSAPI.html#rocksdbutil)| RocksDB基于本地文件的k-v数据库 |
|[BDWareTimeSeriesDBUtil](./YJSAPI.html#BDWareTimeSeriesDBUtil)| 基于本地文件的时间序列数据库 |
### FileUtil
A FileUtil object can be introduced using @permission (“File”).
```
@Permission("File")
contract FileSample {
...
}
```
This object supports the following methods:
#### copyTo
You can copy files and directories. The first parameter is source and the second parameter is destination.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | src |Type String|
| 2 | dest |Type String|
##### Use the sample
```javascript
var ret = FileUtil.copyTo("./source.txt","./dest.txt");
```
#### getContent
If the file does not exist, ```undefined``` is returned.
##### parameter
|The serial number| parameter | 说明 |
| --- | --- | --- |
| 1 | path |Type String|
##### Use the sample
```javascript
var ret = FileUtil.getContent("./source.txt");
```
#### getDir
Get the name of the folder where the file resides. Enter a string as a parameter.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | path |Type String|
##### Use the sample
```javascript
var ret = FileUtil.getDir("./parent/src.txt");
// ret 为 "./parent/";
```
#### getFileName
Get the file name. The input parameter is a string.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | path |Type String|
##### Use the sample
```javascript
var ret = FileUtil.getFileName("./parent/src.txt");
// ret 为 "src.txt"
```
#### openFileAsPrinter
Open the file as PrintStream. The result is of type ```java.io.PrintStream```.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | path |File name. The type is String|
| 2 | isAppend|The type is Boolean, indicating whether to add to the end of the file|
##### Use the sample
```javascript
var ret = FileUtil.openFileAsPrinter("./parent/src.txt",true);
ret.println("hello");
ret.close();
```
### LedgerUtil
You can use @permission (“Ledger”) to import LedgerUtil objects.
```
@Permission("Ledger")
contract LedgerExample{
...
}
```
#### getClient
Gets a connection client, one parameter, of the object type. The returned result is of the LedgerClient type, which is used for subsequent operations such as querying ledbooks.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | address |Contains two fields: IP and port|
##### Use the sample
```javascript
var address = {};
address.ip = "127.0.0.1";
address.port = 18091;
var ledgerClient = LedgerUtil.getClient(address);
```
#### queryByHash
Queries transactions based on Hash. The returned result is an object containing from, to, type, and data, all of which are Strings. Where data is the byte array parsed according to UTF-8 encoding. If the encoding is not UTF8 when storing the certificate, garbled characters may be returned.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | client |Object obtained through the getClient method|
| 2 | info |Object type. Two fields, ledger and hash, are strings|
##### Use the sample
```javascript
// ... ledgerClient = LedgerUtil.getClient(...);
var info = {};
info.ledger = "bdcontract";
info.hash = "4d3b75750835092a50085127702669615b602e53";
var ret = LedgerUtil.queryByHash(ledgerClient,info);
print(ret.from);
print(ret.to);
print(ret.type);
print(ret.data);
```
#### sendTransaction
Deposit data.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | client |Object obtained through the getClient method|
| 2 | info |Object type, with from\to\data three fields, all String type|
##### Use the sample
```javascript
// ... ledgerClient = LedgerUtil.getClient(...);
var info = {};
info.ledger = "bdcontract";
info.from = "b60e8dd61c5d32be8058bb8eb970870f07233155";
info.to = "b60e8dd61c5d32be8058bb8eb970870f07233155";
info.data = "hello world";
var ret = LedgerUtil.sendTransaction(ledgerClient,info);
//ret为存证的哈希值
print(ret);
```
### HttpUtil
We can use @permission (“Http”) to import HttpUtil objects.
```
@Permission("Http")
contract HttpExample{
...
}
```
#### createAPIGate
It can be used with the mobile phones Yuan state. When the mobile phone is installed with Yuan State and the API interface is installed, it can become the data source.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | ip |The value is a string of IP. The default port number is 6161|
##### Use the sample
```javascript
var ret = HttpUtil.createAPIGate("192.168.4.4");
ret.get("com.tencent.mm","sendMsg","msg");
print(ret);
```
#### createAPIGate
It can be used with the mobile phones Yuan state. When the mobile phone is installed with Yuan State and the API interface is installed, it can become the data source.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | ip |The value is a string of type IP|
| 2 | port |It is a string of type, port|
##### Use the sample
```javascript
var ret = HttpUtil.createAPIGate("192.168.4.4", "6161");
ret.get("com.tencent.mm","sendMsg","msg");
print(ret);
```
#### get
Initiate an Http GET request. The result is of object type and contains the Response and responseCode fields.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | url |A character string, indicating the URL type|
##### Use the sample
```javascript
var ret = HttpUtil.get("https://www.baidu.com");
print(ret.responseCode);
print(ret.response);
```
#### post
Make an Http POST request. The result is of object type and contains the Response and responseCode fields.
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | args |Object type with URL, headers, and data fields. Args. headers is the object type.|
##### Use the sample
```javascript
var req = {};
req.url = "https://www.baidu.com";
req.data = "hello";
req.header = {};
req.header.Accept = "application/json";
req.header["Content-Type"] = "application/json";
var ret = HttpUtil.post(req);
print(ret.resposeCode);
print(ret.response);
```
### DOIPUtil
The DOIPUtil object can be introduced using @permission (“DOIP”).
```
@Permission("DOIP")
contract DOIPExample{
...
}
```
#### call
Call a DO
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 |arg0|The string type identifies the target DO|
| 2 |arg1|The input parameter is a string|
##### Use the sample
```javascript
var ret = DOIPUtil.call("86.5000.470/do.hello","inputString");
```
#### create
Create a string of type DO to a Repository
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | arg0 |A string that identifies the target Repo|
| 2 |arg1|Object type, including doID,doBody field|
##### Use the sample
```javascript
var digitalObject = JSON.parse("{\"doID\":\"86.5000.470/do.hello\",\"doBody\":\"hello world\"}");
var ret = DOIPUtil.create("86.5000.470/repo.localTcpRepo",digitalObject);
```
#### delete
Remove DO from a Repository
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | arg0 |The string type target DO identifier|
| 2 |arg1|String type target Repo identity|
##### Use the sample
```javascript
var ret = DOIPUtil.delete("86.5000.470/do.hello","86.5000.470/repo.localTcpRepo");
```
#### hello
Gets the DOIP service information of the target Repository
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | arg0 |String type target Repo identity|
##### Use the sample
```javascript
var ret = DOIPUtil.hello("86.5000.470/repo.localTcpRepo");
```
#### listOperation
Gets the DOIP operations supported by the target DO
##### parameter
|The serial number| parameter | 说明 |
|---|---|---|
| 1 | arg0 |The string type target DO identifier|
##### Use the sample
```javascript
var ret = DOIPUtil.listOperation("86.5000.470/do.hello");
```
#### register
Register a DO with the LHS and return the assigned identity
##### parameter
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |Repo identifier of the string type DO|
| 2 | arg1 |String type DO Format description string|
##### Use the sample
```javascript
var ret = DOIPUtil.register("86.5000.470/repo.localTcpRepo","String");
```
#### reregister
Example Modify the registration information of the DO on the LHS
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |The string type target DO identifier|
| 2 | arg1 |Repo identifier of the string type DO|
| 3 |arg2|String type DO Format description string|
##### Use the sample
```javascript
var ret = DOIPUtil.reregister("86.5000.470/do.hello","86.5000.470/repo.localTcpRepo","String");
```
#### retrieve
Get a DO
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |The string type target DO identifier|
##### Use the sample
```javascript
var ret = DOIPUtil.retrieve("86.5000.470/do.hello");
```
### test
Tests whether DOIPUtils is available
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |String Type Any string|
##### Use the sample
```javascript
var ret = DOIPUtil.test("hello");
```
#### update
Update target DO
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |JS object, including doID,doBody field|
##### Use the sample
```javascript
var digitalObject = JSON.parse("{\"doID\":\"86.5000.470/do.hello\",\"doBody\":\"hello world\"}");
var ret = DOIPUtil.update(digitalObject);
```
### SQLUtil
You can use @permission (“SQL”) to import SQLUtil objects. To support MySQL/PostgreSQL/Oracle/GuassDB200 SQL database. The corresponding JDBC JAR needs to be uploaded to the project. For example, to use mysql, upload mysql-connector-java-8.0.24.jar
```
@Permission("SQL")
oracle MySQLExample{
...
}
```
#### initDriver
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 |driverClass| 字符串类型 |
##### Use the sample
```javascript
//使用mysql
SQLUtil.initDriver("com.mysql.cj.jdbc.Driver");
//使用postgresql
SQLUtil.initDriver("org.postgresql.Driver");
//使用oracle
SQLUtil.initDriver("oracle.jdbc.OracleDriver");
```
#### getConnection
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | URL |String type, JDBC connection|
| 2 | usrName |The value is a string of user names|
| 3 | pwd |The value is a string of characters and a password|
##### Use the sample
```javascript
var url = "jdbc:mysql://xx.xx.xx:port/tableName";
var usrName = "xxx";
var pwd = "xxx";
//配置好用户名和密码url格式为ip或域名+端口,中间以”:”隔开。
var conn = SQLUtil.getConnection(url,usrName,pwd);
//获取数据库连接
var sql = "select * from newele.data";
//创建查询语句
var statement = conn.createStatement();
var resultSet = statement.executeQuery(sql);
var waimailist = [];
//解析查询结果
var meta = resultSet.getMetaData();
for (;resultSet.next();){
var line = {};
for (var j=1;j<=meta.getColumnCount();j++){
line[meta.getColumnName(j)] = resultSet.getString(j);
}
waimailist.push(line);
}
```
In this case, the object returned by the getConnection method is bound to a java.util.Connection object in Java through the reflection mechanism. Therefore, you can view:
<https://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html>
To learn how to operate the Mysql database.
### MongoDBUtil
The MongoDBUtil object can be introduced using @permission (“MongoDB”).
```
@Permission("MongoDB")
contract MongoDBExample{
...
}
```
#### getConnection
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | URL |The URL of a database of string type|
| 2 | port |Port number of an integer type|
| 3 | dbName |The name of the database of string type|
| 4 | usrName |The user name of a string database|
| 5 | pwd |Password of a string database|
##### Use the sample
** Note: port is an integer and other parameters are strings **
```javascript
var client = MongoDBUtil.getConnection(url,port,dbName,usrName,pwd);
//获取数据库对象
var db = client.getDatabase("yancloud");
var collection = db.getCollection("containers");
var iter = collection.find().iterator();
var ret ="";
for (;iter.hasNext();){
ret+=iter.next().toJson();
ret+="\n";
}
```
Here, getMongoDBClient object is bound to a com.mongodb.MongoClient object in Java via reflection mechanism. Therefore, you can view:
<https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/MongoClient.html>
To learn more about how this object works and how it can be used.
### RocksDBUtil
Use @permission (“RocksDB”) to import the RocksDBUtil object.
```
@Permission("RocksDB")
contract RocksDBSample {
...
}
```
#### loadDB
Load a RocksDB database with loadDB. After the load is loaded, you can perform operations such as GET, delete, and PUT.
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | path |The path where the string database is deployed|
| 2 | readOnly |The Boolean database is read-only|
##### Use the sample
```
@Permission("RocksDB")
@Description("这是个使用RocksDB的参考代码")
contract RocksDBSample{
function onCreate(){
Global.rocksdb = RocksDBUtil.loadDB("./dbdir/","false");
}
@Description("示例参数: {\"key\":\"abc\",\"value\":\"def\"}")
export function put(arg){
arg = JSON.parse(arg);
Global.rocksdb.put(arg.key,arg.value);
return "success";
}
@Description("示例参数: \"abc\"}")
export function get(arg){
return Global.rocksdb.get(arg);
return "failed";
}
@Description("示例参数: \"abc\"")
export function deleteKey(arg){
return Global.rocksdb.delete(arg);
}
@Description("遍历KV库无需参数")
export function iter(arg){
var iter = Global.rocksdb.newIterator();
var obj = undefined;
var ret = {
};
for (iter.seekToFirst();(obj=Global.rocksdb.getNext(iter))!=undefined;){
ret[obj.key]=obj.value;
}
return JSON.stringify(ret)
}
}
```
### BDWareTimeSeriesDBUtil
Use the sample
```
@Permission("BDWareTimeSeriesDB")
contract BDWareTimeDBExample{
function onCreate(arg){
Global.dbutil = BDWareTimeSeriesDBUtil.getConnection();
}
export function put(arg){
//第一个参数为表名第二个参数为要放的value时间戳自动打。
Global.dbutil.put("defaultTable",arg);
return "success";
}
@Param
export function getCount(arg){
return Global.dbutil.getCount("defaultTable");
}
@Param(1617254937373)
export function queryByStartTime(arg){
var startDate = java.lang.Long.valueOf(arg);
//查询从开始时刻startDate到最新的数据
var list = Global.dbutil.query("defaultTable",startDate);
var ret=[];
print("DBUtil"+Global.dbutil+" list:"+list+" list.size"+list.size());
var i=0;
for (i=0;i<list.size();i++){
print(i+"-->"+list.get(i));
ret.push(list.get(i));
}
return ret;
}
@Description("示例参数: {\"offset\":1,\"len\":1}")
@Param({"offset":1,"len":1})
export function queryByOffset(arg){
var offsetLen = JSON.parse(arg);
//可配合getCount使用查询第offset至offset+len条数据
var list = Global.dbutil.queryByOffset("defaultTable",offsetLen.offset,offsetLen.len);
var ret=[];
print("DBUtil"+Global.dbutil+" list:"+list+" list.size"+list.size());
var i=0;
for (i=0;i<list.size();i++){
print(i+"-->"+list.get(i));
ret.push(list.get(i));
}
return ret;
}
}
```
## Encryption and decryption tools
### SM2
The SM2Util object can be imported using @permission (“SM2”).
```
@Permission("SM2")
contract SM2Sample {
...
}
```
#### generateKeyPair
Generate public and private keys.
##### 参数
No parameters.
##### Use the sample
```javascript
var ret = SM2Util.generateKeyPair();
print(ret.publicKey);
print(ret.privateKey);
return JSON.stringify(ret);
```
#### sign
The signature.
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | content |The value is a string of characters to be signed|
| 2 |keyPair| sm2 |
##### Use the sample
```
var keypair = SM2Util.generateKeyPair();
var ret = SM2Util.sign("Hello",keypair);
print(ret.status);
//如果status是success
print(ret.signature);
//如果status是failed
print(ret.message);
```
#### verify
Attestation.
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | content |The value is a string of characters to be verified|
| 2 | signature | 字符串类型 签名 |
| 3 |publicKey| 字符串类型 公钥 |
##### Use the sample
```javascript
var ret = SM2Util.verify("Hello","....签名","...公钥");
// 验证通过时result为truestatus为success
// 失败时result为failedstatus为failed
print(ret.status);
print(ret.result);
```
#### encrypt
Sm2 encryption.
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | content |The value is a string of characters to be verified|
| 3 |publicKey| 字符串类型 公钥 |
##### Use the sample
```javascript
var ret = SM2Util.encrypt("Hello","...公钥");
print(ret);
```
#### decrypt
Sm2 decryption.
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | content |The value is a string of characters to be verified|
| 3 |privateKey| 字符串类型 公钥 |
##### Use the sample
```javascript
var ret = SM2Util.decrypt("Hello","...私钥");
print(ret);
```
## Multithreading Tool class
### AsyncUtil
An AsyncUtil object can be introduced using @permission (“Async”).
```
@Permission("Async")
contract AsyncExample{
export function longTimeTask(arg){
var a = {
};
a.count = 100;
AsyncUtil.postFunction(taskFun,a);
}
function taskFun(arg){
Global.progress = 0;
for (var i=0;i<arg.count;i++){
AsyncUtil.sleep(100);
Global.progress++;
}
}
export function getProgress(arg){
return Global.progress;
}
}
```
#### postFunction
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |ScriptFunction|
| 2 | arg1 | 对象 |
##### Use the sample
```javascript
var ret = AsyncUtil.postFunction(a,{"a":"b"});
```
#### setInterval
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |ScriptFunction|
| 2 | arg1 | long |
| 3 | arg2 | long |
| 4 |arg3| 对象 |
##### Use the sample
```javascript
var ret = AsyncUtil.setInterval(a,100,1000,"abc");
```
#### setTimeOut
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 |ScriptFunction|
| 2 | arg1 | long |
| 3 | arg2 |Object|
##### Use the sample
```javascript
var ret = AsyncUtil.setTimeOut(a,100,"abc");
```
#### sleep
##### 参数
|The serial number| 参数 | 说明 |
|---|---|---|
| 1 | arg0 | long |
##### Use the sample
```javascript
var ret = AsyncUtil.sleep();
```
## ECMA5 Build-in Objects
YJS supports some of ECMAScript6s built-in objects:
* String <https://www.w3schools.com/js/js_strings.asp>
* Number <https://www.w3schools.com/js/js_numbers.asp>
* Math <https://www.w3schools.com/js/js_math.asp>
* Date <https://www.w3schools.com/js/js_dates.asp>
* RegExp <https://www.w3schools.com/js/js_regexp.asp>
* Error <https://www.w3schools.com/js/js_errors.asp>
* JSON <https://www.w3schools.com/js/js_json.asp>
## YJS application framework
### Ypk project composition
As described earlier, YPK can store static resource files (HTML/CSS /js). Declaring the loadResource method in the smart contract can return static resource files. Based on loadResource, this project provides a YJS application framework. The framework can load and display YPKs (HTML/CSS /js) files through executeContract.
### Function agreed
| 序号 |Contract function name| 说明 |
|---|---|---|
| 1 | needRender |Will not be called, there is this function to indicate the need to render the front end|
| 2 | getMainFrame |If no parameter is specified, String is returned, indicating the HTML file path of the home page|
| 3 | loadResource |The value is String and returns the static resource file in the relative path in text format|
### Loading process
Arguments loaded in the front end are resolved to global.urlparam. The following parameters are included:
```
//global.urlparam对象示例
{
"contract":"TrustedStorage0899", //表示合约ID或是合约的名称
"keys":{ //表示当前登录者的密钥对
"privateKey":"ff38dd04710...",
"publicKey":"04fc228..."
},
"nodeAddr":"022.node.internetapi.cn:21030" //节点的ip+端口
}
```
A WebSocket connection to nodeAddr is established before loading. Once the connection is established, the loading process is divided into two steps: the first step is to log in with the current Publickey-privatekey. For details about the login process, see `合约节点WebSocket接口` After login, the contract information will be obtained. And stored in the global.CurrentContract object.
The second step is to see if there is a needRender method in the global.CurrentContract object, and if there is, it will start loading the front-end code. Execute executeCurrentContract(“getMainFrame”) to obtain the HTML of the page. After append to mainDIV, all the `<script>`, `<link>` tags will be resolved. 2. The executeCurrentContract(“loadResources”) method is called with the `fromContract` attribute in the tag. A typical YJS loadResources method is as follows. 3. All scripts obtained will be eval, and link will be loaded as CSS.
```
//在某个yjs文件中声明。
export function loadResource(arg){
return Global.Resources.loadAsString(arg);
}
```
![前端加载流程图](./_static/imgs/clientLoadProcess.png)
### Front-end framework preset function description
The front-end javascript has loaded jquery in HTML (using $.) And vue2. To avoid conflicts, this version does not support reloading the vue2/ vuE3 script. Front end through executeContract/executeCurrentContract interact with the backend.
#### executeContract
Call a function on a contract. The current global.sm2key is automatically used for signature. Parameter Description and Example:
```javascript
executeContract(contracID,operation,arg,callback);
//其中contractID为string类型为被调用的合约名称/合约ID。
//operation为string类型合约函数
//arg为string类型表示参数
//callback为函数类型接受返回结果的回调函数。
```
#### executeCurrentContract
Executes a function of the current contract. The current global.sm2key is automatically used for signature. Parameter Description and Example:
```javascript
executeContract(operation,arg,callback);
//operation为string类型合约函数
//arg为string类型表示参数
//callback为函数类型接受返回结果的回调函数。
```