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