26 KiB
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:
action:executeContract;
contractID:合约的id或名称均可;
operation:调用合约的方法名;
arg: 参数;格式为JSON字符串,有action与arg两个字段。
Optional parameters:
requestID:字符串类型,自行生成,用于查询hash
Example:
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
contractID:字符串类型 合约id或名称均可。
event:字符串类型
handler:方法名,该方法必须接受Event(内含字段topic和content)类型的唯一变量为参数;可以不是export方法
Example:
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
topic:字符串类型,发布的事件主题
content:字符串类型,发布的事件内容
Example:
export function pub1(arg) {
YancloudUtil.pubEvent("topic", arg);
return "done";
}
You can also define an event at the beginning of the contract, so that the event name is the event subject, and you can publish the event directly using the event as the method name
event topic;
export function pub2(arg) {
topic(arg);
return "done";
}
This is equivalent to pub1
above.
Accessing Resource Files
Run the global. Resources command to load the YPK internal resource file.
loadAsInputStream
Parameters:
path:字符串类型 需要加载文件的地址
Example:
var file = Global.Resources.loadAsInputStream("/deleteit.txt");
loadAsScanner
Parameters:
path:字符串类型 需要加载文件的地址
Example:
var scanner = Global.Resources.loadAsScanner("/local.txt");
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 account book. The default account book 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
/[a-z][A-Z][0-9]/ (正则表达式)
……
详细格式可以参考http://mockjs.com/examples.html
Note that the template format is {′ result ’: template}
//返回一个1-100之间的整数
@MockTemplate({'result|1-100':1})
//返回
{'result':76}
//返回一个1-5个数的数组
@MockTemplate({'result|1-5':[{'value|1-100':1}]})
//返回
{"result":[{"value":34},{"value":8},{"value":48},{"value":50},{"value":43}]}
//返回一个对象包含如下字段
@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
. If there is no simulated data template, the content of this annotation provides an example of the result returned by the function when the data is simulated. If this annotation is added, the result is returned directly when the documentation is generated without calling the function with the default parameters.
@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);
}
IO tools
An overview of
Name of the IO tool class | 说明 |
---|---|
FileUtil | 文件操作相关的类 |
LedgerUtil | 账本操作相关的类 |
HttpUtil | Http接口相关的类 |
DOIPUtil | DoIP相关的类 |
MySQLUtil | 连接mysql数据库 |
MongoDBUtil | MongoDB连接相关的类 |
RocksDBUtil | RocksDB(基于本地文件的k-v数据库) |
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
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
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
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
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
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
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
// ... 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
// ... 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 phone’s 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
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 phone’s 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
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
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
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
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
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
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
var ret = DOIPUtil.hello("86.5000.470/repo.localTcpRepo");
listOperation
Gets the DOIP operations supported by the target DO
参数
The serial number | 参数 | 说明 |
---|---|---|
1 | arg0 | The string type target DO identifier |
Use the sample
var ret = DOIPUtil.listOperation("86.5000.470/do.hello");
register
Register a DO with the LHS and return the assigned identity
参数
The serial number | 参数 | 说明 |
---|---|---|
1 | arg0 | Repo identifier of the string type DO |
2 | arg1 | String type DO Format description string |
Use the sample
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
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
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
var ret = DOIPUtil.test("hello");
update
Update target DO
参数
The serial number | 参数 | 说明 |
---|---|---|
1 | arg0 | JS object, including doID,doBody field |
Use the sample
var digitalObject = JSON.parse("{\"doID\":\"86.5000.470/do.hello\",\"doBody\":\"hello world\"}");
var ret = DOIPUtil.update(digitalObject);
MySQLUtil
You can use @permission (“MySQL”) to import the MySQLUtil object.
@Permission("MySQL")
contract MySQLExample{
...
}
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
var url = "jdbc:mysql://xx.xx.xx:port/tableName";
var usrName = "xxx";
var pwd = "xxx";
//配置好用户名和密码,url格式为ip或域名+端口,中间以”:”隔开。
var conn = MySQLUtil.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 **
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
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
var ret = SM2Util.verify("Hello","....签名","...公钥");
// 验证通过时,result为true,status为success
// 失败时,result为failed,status为failed
print(ret.status);
print(ret.result);
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
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
var ret = AsyncUtil.setInterval(a,100,1000,"abc");
setTimeOut
参数
The serial number | 参数 | 说明 |
---|---|---|
1 | arg0 | ScriptFunction |
2 | arg1 | long |
3 | arg2 | Object |
Use the sample
var ret = AsyncUtil.setTimeOut(a,100,"abc");
sleep
参数
The serial number | 参数 | 说明 |
---|---|---|
1 | arg0 | long |
Use the sample
var ret = AsyncUtil.sleep();
ECMA5 Build-in Objects
YJS supports some of ECMAScript6’s built-in objects: