前端调用API操作内置函数

详细讲解一个标准的智能合约客户端该有的样子

文件包.png

Node_modules存放react框架下所有类库文件

星云链API的库文件命令:

进入项目目录

1
npm i nebulas

下列命令展示该项目所有依赖包:

1
npm -l package.json

启动项目命令:

1
npm start

启动5.png

解析源码

目录: / src/ index.js

该文件是索引文件

1
2
3
4
5
6
7
8
9
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app'
// 导入包
// 代码入口
ReactDOM.render(
<App />,
document.getElementById('root')
);

这里是所有程序的入口.

打开node.json包文件下的nebulas包, 进入index.js文件

看到如下结构

1
2
3
4
5
6
7
8
9
module.exports = {
HttpRequest: HttpRequest,
Neb: Neb,
Account: Account,
Transaction: Transaction,
Utils: Utils,
CryptoUtils: CryptoUtils,
Unit: Unit
};

这就是返回的结构,一个map

检查是否能调用nebulas包测试

执行/src/下新建文件testAPI.js

1
2
3
4
5
6
"use strict";

//引入包文件,可以使用里面提供的方法
var Nebulas = require('nebulas');

console.log(Nebulas)

执行如下命令

1
node nebulasTest.js

输出结果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
rick@Rick:~/Desktop/新云/0509/demoapp-0011/src$ node testAPI.js
{ HttpRequest: [Function: HttpRequest],
Neb: [Function: Neb],
Account:
{ [Function: Account]
NewAccount: [Function],
isValidAddress: [Function],
fromAddress: [Function],
getNormalType: [Function],
getContractType: [Function] },
Transaction: [Function: Transaction],
Utils:
{ isNull: [Function: isNull],
isBrowser: [Function: isBrowser],
isBigNumber: [Function: isBigNumber],
isString: [Function: isString],
isObject: [Function: isObject],
isFunction: [Function: isFunction],
isNumber: [Function: isNumber],
toBigNumber: [Function: toBigNumber],
toString: [Function: toString],
argumentsToObject: [Function: argumentsToObject],
zipArraysToObject: [Function: zipArraysToObject] },
CryptoUtils:
{ secp256k1:
{ privateKeyVerify: [Function],
privateKeyExport: [Function],
privateKeyImport: [Function],
privateKeyNegate: [Function],
privateKeyModInverse: [Function],
privateKeyTweakAdd: [Function],
privateKeyTweakMul: [Function],
publicKeyCreate: [Function],
publicKeyConvert: [Function],
publicKeyVerify: [Function],
publicKeyTweakAdd: [Function],
publicKeyTweakMul: [Function],
publicKeyCombine: [Function],
signatureNormalize: [Function],
signatureExport: [Function],
signatureImport: [Function],
signatureImportLax: [Function],
sign: [Function],
verify: [Function],
recover: [Function],
ecdh: [Function],
ecdhUnsafe: [Function],
path: '/home/rick/Desktop/新云/0509/demoapp-0011/node_modules/secp256k1/build/Release/secp256k1.node' },
keccak: [Function: keccak],
sha3: [Function: sha3],
ripemd160: [Function: ripemd160],
crypto:
{ _toBuf: [Function: toBuf],
createCipher: [Function: createCipher],
createCipheriv: [Function: createCipheriv],
createDecipher: [Function: createDecipher],
createDecipheriv: [Function: createDecipheriv],
createDiffieHellman: [Function: createDiffieHellman],
createDiffieHellmanGroup: [Function: createDiffieHellmanGroup],
createECDH: [Function: createECDH],
createHash: [Function: createHash],
createHmac: [Function: createHmac],
createSign: [Function: createSign],
createVerify: [Function: createVerify],
getCiphers: [Function],
getCurves: [Function],
getDiffieHellman: [Function: createDiffieHellmanGroup],
getHashes: [Function],
pbkdf2: [Function: pbkdf2],
pbkdf2Sync: [Function: pbkdf2Sync],
privateDecrypt: [Function],
privateEncrypt: [Function],
prng: [Function: randomBytes],
pseudoRandomBytes: [Function: randomBytes],
publicDecrypt: [Function],
publicEncrypt: [Function],
randomBytes: [Function: randomBytes],
randomFill: [Function: randomFill],
randomFillSync: [Function: randomFillSync],
rng: [Function: randomBytes],
setEngine: [Function: setEngine],
timingSafeEqual: [Function: timingSafeEqual],
getFips: [Function: getFipsDisabled],
setFips: [Function: setFipsDisabled],
Certificate: [Function],
Cipher: [Function],
Cipheriv: [Function],
Decipher: [Function],
Decipheriv: [Function],
DiffieHellman: [Function: DiffieHellman],
DiffieHellmanGroup: [Function: DiffieHellmanGroup],
ECDH: [Function],
Hash: [Function],
Hmac: [Function],
Sign: [Function],
Verify: [Function],
DEFAULT_ENCODING: [Getter/Setter],
constants: [Object],
createCredentials: [Getter],
Credentials: [Getter] },
scrypt: [Function: scrypt],
uuid: { [Function: v4] v1: [Function: v1], v4: [Circular] },
zeros: [Function: zeros],
isHexPrefixed: [Function: isHexPrefixed],
padToBigEndian: [Function: padToBigEndian],
toBuffer: [Function: toBuffer],
bufferToHex: [Function: bufferToHex],
privateToPublic: [Function: privateToPublic],
isValidPublic: [Function: isValidPublic],
sign: [Function: sign],
verify: [Function: verify],
recover: [Function: recover] },
Unit:
{ toBasic: [Function: toBasic],
fromBasic: [Function: fromBasic],
nasToBasic: [Function: nasToBasic] } }
rick@Rick:~/Desktop/新云/0509/demoapp-0011/src$

可调用的包全部暴露出来.

API注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use strict";
//导包
var Nebulas = require('nebulas');

//控制台输出结果显示nebulas自带的方法
console.log(Nebulas)

//通过nebulas获取不同方法的对象
var Neb = Nebulas.Neb;

//测试链,参数可换成localhost:8685,获取本地链对象
var neb = new Neb(new Nebulas.HttpRequest("https://testnet.nebulas.io"));

//账户
var Account = Nebulas.Account;

console.log("\n\n")
console.log(neb)

//链上提供的各种API方法,如果不清楚,可以去https://nebulasio.github.io/neb.js/API.html查看
var api = neb.api;


// 当前区块链状态
api.getNebState().then(function(state) {
// 异步 什么是异步:相当于多线程执行程序,不会因为某个方法未结束而阻塞
console.log("\n\n")
console.log(state)
});


// 当前链上最新的区块信息
api.latestIrreversibleBlock().then(function(blockData) {
console.log("\n\n")
console.log(blockData)
});

//查询钱包状态 参数是钱包地址
api.getAccountState({address: "n1YLc2ndCuzS5hKthxvpBDtv1c1YPa6Pacw"}).then(function(state) {
console.log("\n\n")
console.log(state)
});


//查询合约状态 参数是合约地址
api.getAccountState({address: "n1qGHtVR16SDtuzM9KSGvxtpT9PpUfr8QaR"}).then(function(state) {
console.log("\n\n")
console.log(state)
});


//查询区块链上的信息
//新生成的钱包地址,因为查询是谁都能查
var from = Account.NewAccount().getAddressString();
console.log("\n\n\n")
console.log(from)
console.log("\n\n\n")
//合约地址:制定从哪个合约上查询
var dappAddress = "n1qGHtVR16SDtuzM9KSGvxtpT9PpUfr8QaR"
var value = "0";
var nonce = "0"
var gas_price = "1000000"
var gas_limit = "2000000"
//调用的方法,get获取
var callFunction = "get";
//需要查询的内容,字符串表示//
var callArgs = "[\"" + "test" + "\"]";
var contract = {
"function": callFunction,
"args": callArgs
}
//调用查询方法,上面写的一堆参数
neb.api.call(from,dappAddress,value,nonce,gas_price,gas_limit,contract).then(function (resp) {
console.log(resp)
}).catch(function (err) {
//cbSearch(err)
console.log("error:" + err.message)
})

实现在区块链上调用API查询内容代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

import React,{ Component } from 'react';

var Nebulas = require('nebulas')
var Neb = Nebulas.Neb; // Neb
var neb = new Neb(new Nebulas.HttpRequest("https://testnet.nebulas.io"));
var Account = Nebulas.Account;
var api = neb.api;

class App extends Component {
//结构提
constructor(props){
super(props)
}

//页面渲染
render() {
return (

<div style={{backgroundColor: "rgb(52,83,136)",flex: 1
,display: "flex",flexDirection: 'column',alignItems: 'center'}}>
<img src="imag/logo.png" style={{marginTop: 20}}></img>
<div style={{width: "100%",height: 100,marginTop: 100,display: "flex",justifyContent: 'center'}}>
<input
ref="inputRef"
style={{borderWidth: 3,borderColor: "gray",fontSize: 50,flex: 1,marginLeft: 100}}/>
//按钮标签,绑定onclick 点击时间
<button onClick = {() => {
console.log("搜索")
console.log(this.refs.inputRef.value)

//以下是调用neb自带的查询方法,用来实现从区块链上查询内容
var from = Account.NewAccount().getAddressString();
var dappAddress = "n1NPapTqKduzc9vFVsP1uqm1FqFEQWxj3Mp"
var value = "0";
var nonce = "0"
var gas_price = "1000000"
var gas_limit = "2000000"
var callFunction = "get";
//获取input标签输入的内容
var callArgs = "[\"" + this.refs.inputRef.value + "\"]";
var contract = {
"function": callFunction,
"args": callArgs
}

neb.api.call(from,dappAddress,value,nonce,gas_price,gas_limit,contract).then(function (resp) {
console.log("over\n")
console.log(resp)
}).catch(function (err) {

console.log("error:" + err.message)
})

}}
//设置按钮样式
style={{width: 200,marginLeft: 40,fontSize: 50,marginRight: 100}} >SEARCH</button>
</div>
</div>

)
}
}


export default App;