UNPKG

1.75 kBJavaScriptView Raw
1const callable = require('../util/callable');
2const FunctionCoder = require('./FunctionCoder');
3const Transaction = require('../Transaction');
4
5/**
6 * @memberOf ContractMethod
7 */
8class MethodTransaction extends Transaction {
9 constructor(options, method) {
10 super(options);
11 Reflect.defineProperty(this, 'method', { value: method }); // avoid for JSON.stringify
12 }
13
14 options(options) {
15 return new this.constructor({ to: this.to, data: this.data, ...options }, this.method);
16 }
17
18 async then(resolve, reject) {
19 try {
20 const hex = await this.method.conflux.call(this);
21 const result = this.method.decodeOutputs(hex);
22 return resolve(result);
23 } catch (e) {
24 return reject(e);
25 }
26 }
27
28 async catch(callback) {
29 return this.then(v => v, callback);
30 }
31
32 async finally(callback) {
33 try {
34 return await this;
35 } finally {
36 await callback();
37 }
38 }
39}
40
41class ContractMethod extends FunctionCoder {
42 constructor(fragment, contract, conflux) {
43 super(fragment);
44 this.contract = contract;
45 this.conflux = conflux;
46
47 return callable(this, this.call.bind(this));
48 }
49
50 call(...args) {
51 const to = this.contract.address; // dynamic get `contract.address`
52 const data = this.encodeData(args);
53 return new MethodTransaction({ to, data }, this);
54 }
55
56 decodeData(hex) {
57 const namedTuple = super.decodeData(hex);
58 return {
59 name: this.name,
60 fullName: this.fullName,
61 type: this.type,
62 signature: this.signature,
63 array: [...namedTuple],
64 object: namedTuple.toObject(),
65 };
66 }
67}
68
69module.exports = ContractMethod;
70module.exports.MethodTransaction = MethodTransaction;