mm_contract 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mm_eth.js CHANGED
@@ -1,695 +1,436 @@
1
- require("mm_logs");
2
- const Web3 = require("web3");
3
- const BigNumber = require("bignumber.js");
4
-
5
- var pdr;
6
-
7
- class MM_eth {
8
- constructor(config) {
9
- this.config = Object.assign({
10
- defaultAccount: '0xF4Df46425a6689e170E2D6306aa5389A42ae1062',
11
- chainId: 97,
12
- chainName: "BSC",
13
- symbol: "BNB",
14
- decimals: 18,
15
- gas: 0,
16
- gas_add: 100000,
17
- coin: {
18
- address: "0x226d4E1eA7f203d1908bae3D4D65CbAaa4f7aB94",
19
- name: "CDTC",
20
- symbol: "CDTC",
21
- image: null,
22
- decimals: 18
23
- },
24
- precision: Math.pow(10, 18),
25
- rpc: {
26
- // 以太坊 Ethereum 主网络
27
- "1": "https://mainnet.infura.io/v3/dff1613e70d445b8bf5dcd060ac9a9eb",
28
- // Ropsten 测试网络
29
- "3": "https://ropsten.infura.io/v3/dff1613e70d445b8bf5dcd060ac9a9eb",
30
- // Kovan 测试网络
31
- "42": "https://kovan.infura.io/v3/dff1613e70d445b8bf5dcd060ac9a9eb",
32
- // BSC币安智能链
33
- "38": "https://bsc-dataseed.binance.org/",
34
- // BSC币安智能链
35
- "56": "https://bsc-dataseed.binance.org/",
36
- // BSC币安智能链
37
- "97": "https://bsc.elins.cn/",
38
- // Heco链
39
- "128": "https://http-mainnet.hecochain.com",
40
- // 本地测试链
41
- "545": "http://localhost:8545"
42
- // ...
43
- }
44
- }, config);
45
-
46
- /**
47
- * 事件集合
48
- */
49
- this.list_event = {};
50
-
51
- this.list_count = 0;
52
-
53
- /**
54
- * 地址
55
- */
56
- this.address = "";
57
-
58
- /**
59
- * 当前账户余额
60
- */
61
- this.balance = 0;
62
- }
63
- }
64
-
65
- /**
66
- * 新建驱动
67
- */
68
- MM_eth.prototype.newProvider = function() {
69
- var host = this.config.rpc[this.config.chainId];
70
- // 使用web3来进行区块链接口的调用
71
- var web3 = new Web3();
72
- web3.setProvider(new Web3.providers.HttpProvider(host));
73
- web3.eth.defaultAccount = this.config.defaultAccount;
74
- return web3;
75
- };
76
-
77
- /**
78
- * 登录
79
- * @param {String} way 登录
80
- * @return {String} 地址
81
- */
82
- MM_eth.prototype.login = async function(way) {
83
- if (!pdr) {
84
- var provider = this.newProvider();
85
- pdr = provider;
86
- }
87
- this.web3 = pdr;
88
- if (!this.web3.toBigNumber) {
89
- this.web3.toBigNumber = function(val) {
90
- return new BigNumber(val);
91
- }
92
- }
93
-
94
- if (!this.address) {
95
- var accounts = await this.web3.eth.accounts;
96
- this.address = accounts[0] || this.config.defaultAccount;
97
- }
98
- return this.address;
99
- }
100
-
101
- /**
102
- * 构建连接
103
- * @param {Object} Type
104
- */
105
- MM_eth.prototype.link = async function(type) {
106
- var dict = this[type];
107
- var abi = this.config[type + "_abi"];
108
- for (var k in dict) {
109
- var o = dict[k];
110
- o.contract = new this.web3.eth.Contract(abi, o.address + "");
111
- }
112
- };
113
-
114
- /**
115
- * 初始化
116
- */
117
- MM_eth.prototype.initAbi = async function() {
118
- for (var k in this.config) {
119
- if (k.indexOf("_abi") !== -1) {
120
- await this.link(k.replace("_abi", ""));
121
- }
122
- }
123
- }
124
-
125
- /**
126
- * 初始化
127
- * @param {String} way 登录方式
128
- * @return {String} 返回地址
129
- */
130
- MM_eth.prototype.init = async function(way) {
131
- await this.login(way);
132
- await this.initAbi();
133
- return this.web3;
134
- };
135
-
136
- /**
137
- * 发送
138
- * @param {String} type 类型
139
- * @param {String} name 登录方式
140
- * @param {String} method ABI方法
141
- * @param {Number} value 数值
142
- * @param {Array} param 参数集合
143
- * @return {String} 返回地址
144
- */
145
- MM_eth.prototype.send = async function(type, name, method, value, ...param) {
146
- $.log.debug("send req", type, name, method, value, ...param);
147
- try {
148
- var res = await this[type][name].contract.methods[method](...param).send({
149
- from: this.address,
150
- gasLimit: this.config.gas,
151
- value: value
152
- });
153
- $.log.debug("send res", type, name, method, res);
154
- } catch (err) {
155
- $.log.error(method, err);
156
- }
157
- $.log.debug("send res", name, method, res);
158
- return res;
159
- };
160
-
161
- /**
162
- * 查询
163
- * @param {String} name 登录方式
164
- * @param {String} method ABI方法
165
- * @param {Number} value 数值
166
- * @param {Array} param 参数集合
167
- * @return {String} 返回地址
168
- */
169
- MM_eth.prototype.call = async function(type, name, method, value, ...param) {
170
- if (!this.address) {
171
- await this.init();
172
- }
173
- $.log.debug("call req", type, name, method, ...param);
174
- try {
175
- var res = await this[type][name].contract.methods[method](...param).call({
176
- from: this.address
177
- });
178
- } catch (err) {
179
- $.log.error(method, err);
180
- }
181
- // $.log.debug("call res", name, method, res);
182
- return res;
183
- };
184
-
185
-
186
- /**
187
- * 事件管理器
188
- * @param {String} name 事件名称
189
- * @param {String} accounts 账号组
190
- * @param {Number} chainId 区块链频道
191
- */
192
- MM_eth.prototype.eventAfter = function(name, accounts, chainId) {
193
- // $.log.debug(name);
194
- };
195
-
196
- /**
197
- * 事件管理器
198
- * @param {String} name 事件名称
199
- * @param {String} accounts 账号组
200
- * @param {Number} chainId 区块链频道
201
- */
202
- MM_eth.prototype.event = function(name, accounts, chainId) {
203
- $.log.debug("event:", name, accounts, chainId);
204
- if (accounts && accounts.length) {
205
- this.address = pdr.selectedAddress || accounts[0];
206
- }
207
- if (!chainId) {
208
- this.chainId = chainId;
209
- } else if (!this.chainId) {
210
- this.chainId = this.chainId || this.config.chainId;
211
- }
212
- switch (name) {
213
- case "session_update":
214
- case "connect":
215
- case "connected":
216
- case "accountsChanged":
217
- if (this.address && pdr.isConnected && pdr.isConnected()) {
218
- this.is_connected = pdr.isConnected();
219
- } else {
220
- this.is_connected = false;
221
- }
222
- break;
223
- case "disconnect":
224
- this.is_connected = false;
225
- this.address = "";
226
- this.balance = 0;
227
- break;
228
- case "chainChanged":
229
- if (this.address && pdr.isConnected && pdr.isConnected()) {
230
- this.is_connected = pdr.isConnected();
231
- } else {
232
- this.is_connected = false;
233
- }
234
- break;
235
- }
236
-
237
- var list = this.list_event;
238
- for (var k in list) {
239
- var o = list[k];
240
- try {
241
- o(name, this.address, this.chainId);
242
- } catch (e) {
243
- $.log.debug(e);
244
- }
245
- }
246
- this.eventAfter(name, accounts, this.chainId);
247
- };
248
-
249
- /**
250
- * 执行供应器
251
- * @param {Object} provider
252
- */
253
- MM_eth.prototype.subscribeEvent = function(provider) {
254
- if (!provider) {
255
- return;
256
- }
257
- // Subscribe to accounts change
258
- provider.on("accountsChanged", (accounts) => {
259
- this.event("accountsChanged", accounts)
260
- });
261
-
262
- // Subscribe to chainId change
263
- provider.on("chainChanged", (chainId) => {
264
- this.event("chainChanged", null, this.toChage10(chainId, 1))
265
- });
266
-
267
- /**
268
- * 发起交易的时候会触发这个事件
269
- */
270
- provider.on("session_update", async (error, payload) => {
271
- if (error) {
272
- throw error;
273
- }
274
- const {
275
- chainId,
276
- accounts
277
- } = payload.params[0];
278
- this.event("session_update", accounts, this.toChage10(chainId, 1));
279
- });
280
-
281
- /**
282
- * 连接时
283
- */
284
- provider.on("connect", (error, payload) => {
285
- if (error) {
286
- throw error;
287
- }
288
- const {
289
- chainId,
290
- accounts
291
- } = payload;
292
- $.log.debug("连接成功");
293
- $.log.debug(chainId, accounts);
294
- $.log.debug(Object.keys(payload));
295
- this.event('connect', accounts, this.toChage10(chainId, 1));
296
- });
297
-
298
- /**
299
- * 断开连接时
300
- */
301
- provider.on("disconnect", (error, payload) => {
302
- if (error) {
303
- throw error;
304
- }
305
- this.event('disconnect');
306
- });
307
- };
308
-
309
- /**
310
- * 转10进制
311
- * @param {String} num 数值
312
- * @param {Number} map 精度
313
- * @return {String} 转换结果
314
- */
315
- MM_eth.prototype.toChage10 = function(value, map) {
316
- if (value) {
317
- return parseInt(value.replace('0x', ''), 16) / (map || this.config.precision);
318
- } else {
319
- return 0;
320
- }
321
- };
322
-
323
- /**
324
- * 新建合约连接器
325
- * @param {String} name 名称
326
- * @param {String} address 合约地址
327
- * @param {Array} abi ABI方法集合
328
- * @return {Object} 返回连接后的对象
329
- */
330
- MM_eth.prototype.new = function(name, abi, address) {
331
- if (!this[name]) {
332
- this[name] = new this.web3.eth.Contract(abi, address);
333
- }
334
- return this[name];
335
- };
336
-
337
- /**
338
- * 转16进制
339
- * @param {String} num 数值
340
- * @param {Number} map 精度
341
- * @return {String} 转换结果
342
- */
343
- MM_eth.prototype.toChage16 = function(num, map) {
344
- if (typeof(num) === "string") {
345
- return num;
346
- }
347
- return '0x' + (num * (map || this.config.precision)).toString(16);
348
- };
349
-
350
- /**
351
- * 补零
352
- * @param {String} value 需要补零的字符串
353
- * @return {String} 补零后的字符串
354
- */
355
- MM_eth.prototype.fullZore = function(value) {
356
- var len = 64 - value.length;
357
- var val = "";
358
-
359
- for (var i = 0; i < len; i++) {
360
- val += "0";
361
- }
362
-
363
- return val + value;
364
- };
365
-
366
- /**
367
- * 转为参数
368
- * @param {String} name 请求方法名称
369
- * @param {Array} param 请求参数集合
370
- * @return {Object} 返回参数
371
- */
372
- MM_eth.prototype.toParam = function(name, ...param) {
373
- var code = this.methods[name];
374
- var data = code;
375
- for (var i = 0; i < param.length; i++) {
376
- var o = param[i];
377
- if (typeof(o) == 'string') {
378
- data += this.fullZore(o.replace('0x', ''));
379
- } else if (typeof(o) == 'number') {
380
- data += this.fullZore(this.toChage16(o, 1).replace('0x', ''));
381
- }
382
- }
383
-
384
- return {
385
- to: this.config.contract_address, // 必需,合同发布期间除外 Required except during contract publications.
386
- from: this.address, // 发送地址 must match user's active address.
387
- data: data, // '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', // 可选,但用于定义智能合约的创建和交互 Optional, but used for defining smart contract creation and interaction.
388
- // chainId: this.chainId || this.config.chainId, // 用于防止跨区块链的事务重用,由MetaMask自动填充 Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
389
- };
390
- };
391
-
392
- /**
393
- * 获取 nonce
394
- */
395
- MM_eth.prototype.getNonce = async function() {
396
- var nonce_online = await this.web3.eth.getTransactionCount(this.web3.eth.defaultAccount || this.address);
397
- var key = "wr_nonce";
398
- var nonce = this.nonce;
399
- if (nonce) {
400
- nonce++;
401
- if (nonce < nonce_online) {
402
- nonce = nonce_online;
403
- }
404
- } else {
405
- nonce = nonce_online;
406
- }
407
- this.nonce = nonce;
408
- return nonce;
409
- };
410
-
411
- /**
412
- * 转账
413
- * @param {String} type 类型
414
- * @param {String} name 名称
415
- * @param {String} method 合约方法
416
- * @param {Number} value 转账数量
417
- * @param {Array} 合约传参
418
- * @return {Object} 成功返回转账结果, 否则返回空
419
- */
420
- MM_eth.prototype.sendS = async function(type, name, method, value, ...param) {
421
- let address_my = this.web3.eth.defaultAccount || this.address;
422
-
423
- if (!this[type]) {
424
- $.log.error("合约类型不正确");
425
- return
426
- }
427
- if (!this[type][name]) {
428
- $.log.error("合约不正确");
429
- return
430
- }
431
- if (!this[type][name].contract.methods[method]) {
432
- $.log.error("函数不存在!");
433
- return
434
- }
435
-
436
- let data = await this[type][name].contract.methods[method](...param).encodeABI();
437
- var contract_address = this[type][name].address;
438
-
439
-
440
- var nonce = await this.getNonce();
441
-
442
- var rawTx = {
443
- // from: address_my,
444
- nonce,
445
- // eth用 0x14F46B0400, bsc用 0x12A05F200
446
- gasPrice: "0x12A05F200",
447
- gasLimit: '0x249F0',
448
- to: contract_address,
449
- // 调用receiveEth 给合约转入0.1eth ,如果调用合约方法不给合约转入eth,这个值是0
450
- value: value ? this.toChage16(value) : '0x0',
451
- // 这个数据需要自己拼接,在gitee/gkai/metamask里面有方法(通过encodeABI可以不用自己拼接了)
452
- data
453
- };
454
-
455
- // $.log.info("数据", rawTx);
456
- var sign_data = await this.web3.eth.accounts.signTransaction(rawTx, this.config.private_key);
457
- if (!sign_data) {
458
- $.log.error("签名失败", rawTx, err);
459
- return null;
460
- }
461
- // $.log.info("签名", sign_data);
462
- // $.sleep(1000);
463
- var tx = null;
464
- try {
465
- tx = await this.web3.eth.sendSignedTransaction(sign_data.rawTransaction);
466
- } catch (err) {
467
- $.log.error("链上交易超时", rawTx, err);
468
- }
469
- // $.log.info("广播", tx);
470
- if (tx) {
471
- if (!tx.status) {
472
- this.nonce = 0;
473
- return null;
474
- }
475
- } else {
476
- this.nonce -= 1
477
- }
478
-
479
- $.log.debug('send res', name, tx);
480
- return tx;
481
- };
482
-
483
-
484
-
485
- /** 追加 **/
486
- /**
487
- * call obj
488
- * @param {String} name Login Method
489
- * @param {String} method ABI method
490
- * @param {Array} keys object prop
491
- * @param {Array} param parameter set
492
- * @return {String} return address
493
- */
494
- MM_eth.prototype.callObj = async function(type, name, method, keys, ...param) {
495
- $.log.debug("call req", type, name, method, ...param);
496
- try {
497
- var res = await this[type][name].contract.methods[method](...param).call({
498
- from: this.address
499
- });
500
- } catch (err) {
501
- $.log.error(method, err)
502
- }
503
- var arr = res.split('_');
504
- var obj = {};
505
- for(var i = 0; i < keys.length; i++){
506
- obj[keys[i]] = arr.length > i ? arr[i] : 0;
507
- }
508
- $.log.debug("call res", name, method, obj);
509
- return obj;
510
- };
511
-
512
- /**
513
- * call list
514
- * @param {String} name Login Method
515
- * @param {String} method ABI method
516
- * @param {Array} keys object prop
517
- * @param {Array} param parameter set
518
- * @return {String} return address
519
- */
520
- MM_eth.prototype.callList = async function(type, name, method, keys, ...param) {
521
- $.log.debug("call req", type, name, method, ...param);
522
- try {
523
- var res = await this[type][name].contract.methods[method](...param).call({
524
- from: this.address
525
- });
526
- } catch (err) {
527
- $.log.error(method, err)
528
- }
529
- var list = res.map((o) => {
530
- var arr = o.split('_');
531
- var obj = {};
532
- for(var i = 0; i < keys.length; i++){
533
- obj[keys[i]] = arr.length > i ? arr[i] : 0;
534
- }
535
- return obj
536
- });
537
- $.log.debug("call res", name, method, list);
538
- return list;
539
- };
540
-
541
- /**
542
- * Add event
543
- * @param {Function} name event name
544
- * @param {Function} func event method
545
- * @returns {Funtion} this event function key
546
- */
547
- MM_eth.prototype.addEvent = function(func, name) {
548
- if (!name) {
549
- this.list_count++;
550
- name = this.list_count;
551
- }
552
- this.list_event[name] = func;
553
- return name;
554
- };
555
-
556
- /**
557
- * Delete event
558
- * @param {Function} name event name
559
- */
560
- MM_eth.prototype.delEvent = function(name) {
561
- delete this.list_event[name];
562
- };
563
-
564
- /**
565
- * execute provider
566
- * @param {Object} provider
567
- */
568
- MM_eth.prototype.subscribeEvent = function(provider) {
569
- if (!provider) {
570
- return;
571
- }
572
- // Subscribe to accounts change
573
- provider.on("accountsChanged", (accounts) => {
574
- this.event("accountsChanged", accounts)
575
- });
576
-
577
- // Subscribe to chainId change
578
- provider.on("chainChanged", (chainId) => {
579
- this.event("chainChanged", null, this.toChage10(chainId, 1))
580
- });
581
-
582
- /**
583
- * This event is fired when a transaction is initiated
584
- */
585
- provider.on("session_update", async (error, payload) => {
586
- if (error) {
587
- throw error;
588
- }
589
- const {
590
- chainId,
591
- accounts
592
- } = payload.params[0];
593
- this.event("session_update", accounts, this.toChage10(chainId, 1));
594
- });
595
-
596
- /**
597
- * when connected
598
- */
599
- provider.on("connect", (error, payload) => {
600
- if (error) {
601
- throw error;
602
- }
603
- if (!payload) {
604
- return;
605
- }
606
- const {
607
- chainId,
608
- accounts
609
- } = payload;
610
- this.event('connect', accounts, this.toChage10(chainId, 1));
611
- });
612
-
613
- /**
614
- * when disconnected
615
- */
616
- provider.on("disconnect", (error, payload) => {
617
- if (error) {
618
- throw error;
619
- }
620
- this.event('disconnect');
621
- });
622
- };
623
-
624
- /**
625
- * Web3 签名加密
626
- * @param {String} content 签名内容
627
- * @param {String} address 签名地址
628
- * @param {Function} func 回调函数(可选)
629
- */
630
- MM_eth.prototype.sign = async function(content, address, func) {
631
- var ret = null;
632
- if (func) {
633
- this.web3.eth.sign(content, address, func);
634
- } else {
635
- ret = await this.web3.eth.sign(content, address);
636
- }
637
- return ret;
638
- }
639
-
640
- MM_eth.prototype.getBalance = async function(address) {
641
- var {
642
- chain_accuracy
643
- } = this.config;
644
- var y = Math.pow(10, chain_accuracy);
645
-
646
- if (!this.default_address) {
647
- await this.getAccounts();
648
- }
649
-
650
- if (!address) {
651
- address = this.default_address;
652
- }
653
- // 查询余额
654
- var num_str = await this.web3.eth.getBalance(address);
655
- // 转为大数字类型
656
- var num_b = new BigNumber(num_str);
657
- // 除以小数位
658
- var balance = num_b.div(y).toNumber();
659
- // 保存余额
660
- this.balance = balance;
661
- return balance;
662
- };
663
-
664
- /**
665
- * 获取以太网上的账户
666
- * @return {Array} 账户数组
667
- */
668
- MM_eth.prototype.getAccount = async function() {
669
- this.default_address = this.web3.eth.defaultAccount;
670
- return this.default_address;
671
- };
672
-
673
- /**
674
- * 获取以太网上的账户
675
- * @return {Array} 账户数组
676
- */
677
- MM_eth.prototype.getAccounts = async function() {
678
- var accounts = await this.web3.eth.getAccounts();
679
- if (accounts.length) {
680
- this.web3.eth.defaultAccount = accounts[0];
681
- this.default_address = this.web3.eth.defaultAccount;
682
- }
683
- return accounts;
684
- };
685
-
686
- /**
687
- * 加载ABI
688
- * @param {String} path 地址
689
- * @return {String} 加载成功返回true
690
- */
691
- MM_eth.prototype.loadAbi = function(abi) {
692
-
693
- }
694
-
695
- module.exports = MM_eth;
1
+ const Web3 = require("web3");
2
+ const BigNumber = require("bignumber.js");
3
+
4
+ class MM_eth {
5
+ /**
6
+ * 创建以太坊合约实例
7
+ * @param {Object} config - 配置参数
8
+ */
9
+ constructor(config) {
10
+ this.config = Object.assign({
11
+ defaultAccount: '0xF4Df46425a6689e170E2D6306aa5389A42ae1062',
12
+ chainId: 97,
13
+ chainName: "BSC",
14
+ symbol: "BNB",
15
+ decimals: 18,
16
+ gas: 0,
17
+ gas_add: 100000,
18
+ coin: {
19
+ address: "0x226d4E1eA7f203d1908bae3D4D65CbAaa4f7aB94",
20
+ name: "CDTC",
21
+ symbol: "CDTC",
22
+ image: null,
23
+ decimals: 18
24
+ },
25
+ precision: Math.pow(10, 18),
26
+ rpc: {
27
+ // 以太坊 Ethereum 主网络
28
+ "1": "https://mainnet.infura.io/v3/dff1613e70d445b8bf5dcd060ac9a9eb",
29
+ // Ropsten 测试网络
30
+ "3": "https://ropsten.infura.io/v3/dff1613e70d445b8bf5dcd060ac9a9eb",
31
+ // Kovan 测试网络
32
+ "42": "https://kovan.infura.io/v3/dff1613e70d445b8bf5dcd060ac9a9eb",
33
+ // BSC币安智能链
34
+ "38": "https://bsc-dataseed.binance.org/",
35
+ // BSC币安智能链
36
+ "56": "https://bsc-dataseed.binance.org/",
37
+ // BSC币安智能链
38
+ "97": "https://bsc.elins.cn/",
39
+ // Heco链
40
+ "128": "https://http-mainnet.hecochain.com"
41
+ // 本地测试链等环境端点属部署事实,由调用方 config.rpc 提供
42
+ }
43
+ }, config);
44
+
45
+ /**
46
+ * 事件集合
47
+ */
48
+ this.list_event = {};
49
+
50
+ this.list_count = 0;
51
+
52
+ /**
53
+ * 地址
54
+ */
55
+ this.address = "";
56
+
57
+ /**
58
+ * 当前账户余额
59
+ */
60
+ this.balance = 0;
61
+
62
+ /**
63
+ * 日志记录器(可经 config.logger 注入,缺省使用 console)
64
+ * @type {Object}
65
+ */
66
+ this._logger = this.config.logger || console;
67
+ }
68
+
69
+ /**
70
+ * 设置日志记录器
71
+ * @param {Object} logger 日志记录器(需实现 debug/info/warn/error)
72
+ * @returns {MM_eth} 当前实例
73
+ */
74
+ setLogger(logger) {
75
+ if (logger) {
76
+ this._logger = logger;
77
+ }
78
+ return this;
79
+ }
80
+
81
+ /**
82
+ * 获取日志记录器
83
+ * @returns {Object} 日志记录器
84
+ */
85
+ getLogger() {
86
+ return this._logger;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 新建驱动
92
+ */
93
+ MM_eth.prototype.newProvider = function() {
94
+ let host = this.config.rpc[this.config.chainId];
95
+ // 使用web3来进行区块链接口的调用
96
+ let web3 = new Web3();
97
+ web3.setProvider(new Web3.providers.HttpProvider(host));
98
+ web3.eth.defaultAccount = this.config.defaultAccount;
99
+ return web3;
100
+ };
101
+
102
+ /**
103
+ * 登录
104
+ * @param {String} way 登录
105
+ * @return {String} 地址
106
+ */
107
+ MM_eth.prototype.login = async function(way) {
108
+ if (!this._provider) {
109
+ this._provider = this.newProvider();
110
+ }
111
+ this.web3 = this._provider;
112
+ if (!this.web3.toBigNumber) {
113
+ this.web3.toBigNumber = function(val) {
114
+ return new BigNumber(val);
115
+ }
116
+ }
117
+
118
+ if (!this.address) {
119
+ let accounts = await this.web3.eth.accounts;
120
+ this.address = accounts[0] || this.config.defaultAccount;
121
+ }
122
+ return this.address;
123
+ }
124
+
125
+ /**
126
+ * 构建连接
127
+ * @param {Object} Type
128
+ */
129
+ MM_eth.prototype.link = async function(type) {
130
+ let dict = this[type];
131
+ let abi = this.config[type + "_abi"];
132
+ for (let k in dict) {
133
+ let o = dict[k];
134
+ o.contract = new this.web3.eth.Contract(abi, o.address + "");
135
+ }
136
+ };
137
+
138
+ /**
139
+ * 初始化
140
+ */
141
+ MM_eth.prototype.initAbi = async function() {
142
+ for (let k in this.config) {
143
+ if (k.indexOf("_abi") !== -1) {
144
+ await this.link(k.replace("_abi", ""));
145
+ }
146
+ }
147
+ }
148
+
149
+ /**
150
+ * 初始化
151
+ * @param {String} way 登录方式
152
+ * @return {String} 返回地址
153
+ */
154
+ MM_eth.prototype.init = async function(way) {
155
+ await this.login(way);
156
+ await this.initAbi();
157
+ return this.web3;
158
+ };
159
+
160
+ /**
161
+ * 发送
162
+ * @param {String} type 类型
163
+ * @param {String} name 登录方式
164
+ * @param {String} method ABI方法
165
+ * @param {Number} value 数值
166
+ * @param {Array} param 参数集合
167
+ * @return {String} 返回地址
168
+ */
169
+ MM_eth.prototype.send = async function(type, name, method, value, ...param) {
170
+ this._logger.debug("send req", type, name, method, value, ...param);
171
+ try {
172
+ let res = await this[type][name].contract.methods[method](...param).send({
173
+ from: this.address,
174
+ gasLimit: this.config.gas,
175
+ value: value
176
+ });
177
+ this._logger.debug("send res", type, name, method, res);
178
+ } catch (err) {
179
+ this._logger.error(method, err);
180
+ }
181
+ this._logger.debug("send res", name, method, res);
182
+ return res;
183
+ };
184
+
185
+ /**
186
+ * 查询
187
+ * @param {String} name 登录方式
188
+ * @param {String} method ABI方法
189
+ * @param {Number} value 数值
190
+ * @param {Array} param 参数集合
191
+ * @return {String} 返回地址
192
+ */
193
+ MM_eth.prototype.call = async function(type, name, method, value, ...param) {
194
+ if (!this.address) {
195
+ await this.init();
196
+ }
197
+ this._logger.debug("call req", type, name, method, ...param);
198
+ try {
199
+ let res = await this[type][name].contract.methods[method](...param).call({
200
+ from: this.address
201
+ });
202
+ } catch (err) {
203
+ this._logger.error(method, err);
204
+ }
205
+ // this._logger.debug("call res", name, method, res);
206
+ return res;
207
+ };
208
+
209
+
210
+ /**
211
+ * 事件管理器
212
+ * @param {String} name 事件名称
213
+ * @param {String} accounts 账号组
214
+ * @param {Number} chainId 区块链频道
215
+ */
216
+ MM_eth.prototype.eventAfter = function(name, accounts, chainId) {
217
+ // this._logger.debug(name);
218
+ };
219
+
220
+ /**
221
+ * 事件管理器
222
+ * @param {String} name 事件名称
223
+ * @param {String} accounts 账号组
224
+ * @param {Number} chainId 区块链频道
225
+ */
226
+ MM_eth.prototype.event = function(name, accounts, chainId) {
227
+ this._logger.debug("event:", name, accounts, chainId);
228
+ if (accounts && accounts.length) {
229
+ this.address = this._provider.selectedAddress || accounts[0];
230
+ }
231
+ if (!chainId) {
232
+ this.chainId = chainId;
233
+ } else if (!this.chainId) {
234
+ this.chainId = this.chainId || this.config.chainId;
235
+ }
236
+ switch (name) {
237
+ case "session_update":
238
+ case "connect":
239
+ case "connected":
240
+ case "accountsChanged":
241
+ if (this.address && this._provider.isConnected && this._provider.isConnected()) {
242
+ this.is_connected = this._provider.isConnected();
243
+ } else {
244
+ this.is_connected = false;
245
+ }
246
+ break;
247
+ case "disconnect":
248
+ this.is_connected = false;
249
+ this.address = "";
250
+ this.balance = 0;
251
+ break;
252
+ case "chainChanged":
253
+ if (this.address && this._provider.isConnected && this._provider.isConnected()) {
254
+ this.is_connected = this._provider.isConnected();
255
+ } else {
256
+ this.is_connected = false;
257
+ }
258
+ break;
259
+ }
260
+
261
+ let list = this.list_event;
262
+ for (let k in list) {
263
+ let o = list[k];
264
+ try {
265
+ o(name, this.address, this.chainId);
266
+ } catch (e) {
267
+ this._logger.debug(e);
268
+ }
269
+ }
270
+ this.eventAfter(name, accounts, this.chainId);
271
+ };
272
+
273
+ /**
274
+ * 执行供应器
275
+ * @param {Object} provider
276
+ */
277
+ MM_eth.prototype.subscribeEvent = function(provider) {
278
+ if (!provider) {
279
+ return;
280
+ }
281
+ // Subscribe to accounts change
282
+ provider.on("accountsChanged", (accounts) => {
283
+ this.event("accountsChanged", accounts)
284
+ });
285
+
286
+ // Subscribe to chainId change
287
+ provider.on("chainChanged", (chainId) => {
288
+ this.event("chainChanged", null, this.toChage10(chainId, 1))
289
+ });
290
+
291
+ /**
292
+ * 发起交易的时候会触发这个事件
293
+ */
294
+ provider.on("session_update", async (error, payload) => {
295
+ if (error) {
296
+ throw error;
297
+ }
298
+ let {
299
+ chainId,
300
+ accounts
301
+ } = payload.params[0];
302
+ this.event("session_update", accounts, this.toChage10(chainId, 1));
303
+ });
304
+
305
+ /**
306
+ * 连接时
307
+ */
308
+ provider.on("connect", (error, payload) => {
309
+ if (error) {
310
+ throw error;
311
+ }
312
+ let {
313
+ chainId,
314
+ accounts
315
+ } = payload;
316
+ this._logger.debug("连接成功");
317
+ this._logger.debug(chainId, accounts);
318
+ this._logger.debug(Object.keys(payload));
319
+ this.event('connect', accounts, this.toChage10(chainId, 1));
320
+ });
321
+
322
+ /**
323
+ * 断开连接时
324
+ */
325
+ provider.on("disconnect", (error, payload) => {
326
+ if (error) {
327
+ throw error;
328
+ }
329
+ this.event('disconnect');
330
+ });
331
+ };
332
+
333
+ /**
334
+ * 转10进制
335
+ * @param {String} num 数值
336
+ * @param {Number} map 精度
337
+ * @return {String} 转换结果
338
+ */
339
+ MM_eth.prototype.toChage10 = function(value, map) {
340
+ if (value) {
341
+ return parseInt(value.replace('0x', ''), 16) / (map || this.config.precision);
342
+ } else {
343
+ return 0;
344
+ }
345
+ };
346
+
347
+ /**
348
+ * 新建合约连接器
349
+ * @param {String} name 名称
350
+ * @param {String} address 合约地址
351
+ * @param {Array} abi ABI方法集合
352
+ * @return {Object} 返回连接后的对象
353
+ */
354
+ MM_eth.prototype.new = function(name, abi, address) {
355
+ if (!this[name]) {
356
+ this[name] = new this.web3.eth.Contract(abi, address);
357
+ }
358
+ return this[name];
359
+ };
360
+
361
+ /**
362
+ * 转16进制
363
+ * @param {String} num 数值
364
+ * @param {Number} map 精度
365
+ * @return {String} 转换结果
366
+ */
367
+ MM_eth.prototype.toChage16 = function(num, map) {
368
+ if (typeof(num) === "string") {
369
+ return num;
370
+ }
371
+ return '0x' + (num * (map || this.config.precision)).toString(16);
372
+ };
373
+
374
+ /**
375
+ * 补零
376
+ * @param {String} value 需要补零的字符串
377
+ * @return {String} 补零后的字符串
378
+ */
379
+ MM_eth.prototype.fullZore = function(value) {
380
+ let len = 64 - value.length;
381
+ let val = "";
382
+
383
+ for (let i = 0; i < len; i++) {
384
+ val += "0";
385
+ }
386
+
387
+ return val + value;
388
+ };
389
+
390
+ /**
391
+ * 转为参数
392
+ * @param {String} name 请求方法名称
393
+ * @param {Array} param 请求参数集合
394
+ * @return {Object} 返回参数
395
+ */
396
+ MM_eth.prototype.toParam = function(name, ...param) {
397
+ let code = this.methods[name];
398
+ let data = code;
399
+ for (let i = 0; i < param.length; i++) {
400
+ let o = param[i];
401
+ if (typeof(o) == 'string') {
402
+ data += this.fullZore(o.replace('0x', ''));
403
+ } else if (typeof(o) == 'number') {
404
+ data += this.fullZore(this.toChage16(o, 1).replace('0x', ''));
405
+ }
406
+ }
407
+
408
+ return {
409
+ to: this.config.contract_address, // 必需,合同发布期间除外 Required except during contract publications.
410
+ from: this.address, // 发送地址 must match user's active address.
411
+ data: data, // '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', // 可选,但用于定义智能合约的创建和交互 Optional, but used for defining smart contract creation and interaction.
412
+ // chainId: this.chainId || this.config.chainId, // 用于防止跨区块链的事务重用,由MetaMask自动填充 Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
413
+ };
414
+ };
415
+
416
+ /**
417
+ * 获取 nonce
418
+ */
419
+ MM_eth.prototype.getNonce = async function() {
420
+ let nonce_online = await this.web3.eth.getTransactionCount(this.web3.eth.defaultAccount || this.address);
421
+ let key = "wr_nonce";
422
+ let nonce = this.nonce;
423
+ if (nonce) {
424
+ nonce++;
425
+ if (nonce < nonce_online) {
426
+ nonce = nonce_online;
427
+ }
428
+ } else {
429
+ nonce = nonce_online;
430
+ }
431
+ this.nonce = nonce;
432
+ return nonce;
433
+ };
434
+
435
+ module.exports = MM_eth;
436
+ require("./lib/mm_eth_ext.js");