mm_contract 1.0.1 → 1.0.3

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/README.md CHANGED
@@ -1,2 +1,11 @@
1
- # mm_contract
2
- 这是超级美眉智能合约调用辅助模块,用于快速发布合约和调用区块链ABI方法,适用于eth链及其衍生链
1
+ # mm_contract
2
+ 这是超级美眉智能合约调用辅助模块,用于快速发布合约和调用区块链ABI方法,适用于eth链及其衍生链
3
+
4
+ ## 工具契约(LLM 可调用)
5
+
6
+ 本模块 `tool/` 下登记以下工具契约,实现位于 `lib/tools/<name>/`,`tool/<name>/index.js` 仅为薄适配层。
7
+ 其它模块可直接 `require('<pkg>').tools.<name>` 复用实现,无需经过工具注册面。
8
+
9
+ | 工具名 | 标题 | 说明 |
10
+ | --- | --- | --- |
11
+ | `contract` | 链上合约账户与调用 | 默认账户、余额、签名、只读调用 |
package/index.js CHANGED
@@ -1,22 +1,5 @@
1
- var Web3 = require('web3');
2
- var mm_eth = require('./mm_eth.js');
3
- var mm_tron = require('./mm_tron.js');
4
-
5
- /**
6
- * 方法
7
- */
8
- class mm_contract {
9
- /**
10
- * 构造函数
11
- * @param {Object} config 配置参数
12
- */
13
- constructor(config, type) {
14
- if (type == "tron") {
15
- return new mm_tron(config);
16
- } else {
17
- return new mm_eth(config);
18
- }
19
- }
20
- }
21
-
22
- module.exports = mm_contract;
1
+ const Contract = require('./lib/contract.js');
2
+
3
+ module.exports = {
4
+ Contract
5
+ };
package/lib/admin.js ADDED
@@ -0,0 +1,17 @@
1
+ const { reg } = require('mm_admin');
2
+ const Contract = require('../contract.js');
3
+
4
+ let admin = reg('contract');
5
+ admin.setClass(Contract);
6
+
7
+ /**
8
+ * 合约管理员
9
+ */
10
+ function contractAdmin(scope, config) {
11
+ return admin.get(scope || 'os', config);
12
+ }
13
+
14
+ module.exports = {
15
+ admin,
16
+ contractAdmin
17
+ };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+ let Eth = require('../eth.js');
3
+ let Tron = require('../tron.js');
4
+
5
+ /**
6
+ * 合约分发类,按链类型返回对应实现实例。
7
+ */
8
+ class Contract {
9
+ /**
10
+ * 按链类型创建合约实例
11
+ * @param {Object} config 配置参数
12
+ * @param {string} [type] 链类型,取 tron 时返回 tron 实现
13
+ * @returns {Object} 对应链的合约实例
14
+ */
15
+ constructor(config, type) {
16
+ if (type == "tron") {
17
+ return new Tron(config);
18
+ } else {
19
+ return new Eth(config);
20
+ }
21
+ }
22
+ }
23
+
24
+ module.exports = Contract;
package/lib/eth.js ADDED
@@ -0,0 +1,436 @@
1
+ const Web3 = require("web3");
2
+ const BigNumber = require("bignumber.js");
3
+
4
+ class 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 {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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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 = Eth;
436
+ require("./lib/eth_ext.js");