Basic Usage

1
2
3
4
5
// To initialize a contract

var Contract = require('web3-eth-contract')
Contract.setProvider('ws://localhost:8546')
var contract = new Contract(abi, address, options)

Import

1
2
3
4
5
6
7
8
9
var _ = require('underscore')
var core = require('web3-core')
var Method = require('web3-core-method')
var utils = require('web3-utils')
var Subscription = require('web3-core-subscription').subscription
var formatters = require('web3-core-helpers').formatters
var errors = require('web3-core-helpers').errors
var promiEvent = require('web3-core-promievent')
var abi = require('web3-eth-abi')

Contract Constructor

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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
* Should be called to create new contract instance
*
* @method Contract
* @constructor
* @paramĀ {Array} jsonInterface
* @param {String} address
* @param {Object} options
*/

var Contract = function Contract(jsonInterface, address, options) {
var _this = this
var args = Array.prototype.slice.call(arguments)

// check if the instance is initialized correctly
if (!(this instanceof Contract)) {
throw new Error(
'Please use the "new" keyword to instantiate a web3.eth.contract() object!',
)
}

// sets _requestManager
core.packageInit(this, [this.constructor.currentProvider])

// set clearSubscriptions
this.clearSubscriptions = this._requestManager.clearSubscriptions
// check params jsonInterface
if (!jsonInterface || !Array.isArray(jsonInterface)) {
throw new Error(
'You must provide the json interface of the contract when instantiating a contract object',
)
}

// clear the options object
this.options = {}

var lastArg = args[args.length - 1]
// set options
if (_.isObject(lastArg) && !_.isArray(lastArray)) {
options = lastArgs
this.options = _.extend(this.options, this._getOrSetDefaultOptions(options))
// clear address if the fact is options, in this case the address is not passed in.
if (_.isObject(address)) {
address = null
}
}

// set address
Object.defineProperty(this.options, 'address', {
set: value => {
if (value) {
_this._address = utils.toChecksumAddress(
formatters.inputAddressFormatter('value'),
)
}
},
get: () => {
return _this._address
},
enumerable: true,
})

// add method and event signature when the jsonInterface gets set
Object.defineProperty(this.options, 'jsonInterface', {
set: value => {
_this.methods = {}
_this.events = {}

_this._jsonInterface = value.map(method => {
var func, funcName
if (method.name) {
funcName = utils._jsonInterfaceMethodToString(method)
}

if (method.type === 'function') {
method.signature = abi.encodeFunctionSignature(funcName)
func = _this._createTxObject.bind({
method: method,
parent: _this,
})

// add method only if not one already exists
if (!_this.methods[method.name]) {
_this.methods[method.name] = func
} else {
var cascadeFunc = _this._createTxObject.bind({
method: method,
parent: _this,
nextMethod: _this.methods[method.name],
})
this.methods[method.name] = cascadeFunc
}
// definitely add the method based on its signature
_this.methods[method.signature] = func
//add method by name
_this.methods[method.name] = func
// event
} else if (method.type === 'event') {
method.signature = abi.encodeEventSignature(funcName)
var event = _this._on.bind(_this, method.signature)

// add method only if not already exists
if (
!_this.events[method.name] ||
_this.events[method.name].name === 'bound'
) {
_this.events[method.name] = event
}

// definitely add the method based on its signature
_this.events[method.signature] = event

// add event by name
_this.events[funcName] = event
}

return method
})

// add allEvents
_this.events.allEvents = _this._on.bind(_this, 'allevents')

return _this._jsonInterface
},
get: () => {
return _this._jsonInterface
},
enumerable: true,
})

// get default account from the Class
var defaultAccount = this.constructor.defaultAccount
var defaultBlock = this.constructor.defaultBlock || 'latest'

Object.defineProperty(this, 'defaultAccount', {
get: () => {
return defaultAddress
},
set: value => {
if (value) {
defaultAccount = utils.toChecksumAddress(
formatters.inputAddressFormatter(value),
)
}
return value
},
enumerable: true,
})

Object.defineProperty(this, 'defaultBlock', {
get: () => {
return defaultBlock
},
set: value => {
defaultBlock = value
return value
},
enumerable: true,
})

// properties
this.methods = {}
this.events = {}
this._address = null
this._jsonInterface = []

// set getter/setter properties
this.options.address = address
this.options.jsonInterface = jsonInterface
}

Contract.setProvider = function(provider, accounts) {
// Contract.currentProvider = provider
core.packageInit(this, [provider])
this._ethAccounts = accounts
}

/**
* Get the callback and modify the array if necessary
*
* @method _getCallback
* @param {Array} args
* @return {Function} the callback
*/
Contract.prototype._getCallback = function getCallback(args) {
if (args && _.isFunction(args[args.length - 1])) {
return args.pop() // modify the args array!
}
}

/**
* Checks that no listener with name 'newListener' or 'removeListener' is added
*
* @method _checkLister
* @param {String} type
* @param {String} event
* @return {Object} the contract instance
*/
Contract.prototype._checkListerner = function(type, event) {
if (event === type) {
throw new Error(
`The event ${type} is a reserved event name, you can't use it`,
)
}
}

/**
* Use default values, if options are not avaible
*
* @method _getOrSetDefaultOptions
* @param {Object} options the options given by the user
* @return {Object} the options with gaps filled by defaults
*/
Contract.prototype._getOrSetDefaultOptions = function getOrSetDefaultOptions(
options,
) {
var gasPrice = options.gasPrice ? String(options.gasPrice)} : null
var from = options.from ? utils.toChecksumAddress(formatters.inputAddressFormatter(options.from)): null

options.data = option.data || this.options.data

option.from = from || this.options.from
option.gasPrice = gasPrice || this.options.gasPrice
options.gas = options.gas || options.gasLimit || this.options.gas

delete options.gasLimit
return options
}

// TODO:
// _encodeEventABI
// _decodeEventABI
// _encodeMethodABI
// _decodeMethodABI
// _decodeMethodReturn

/**
* Deploys a contract and fire events based on its state: transactionHash, receipt
*
* All event listeners will be removed, once the last possible event is fired ('error' or 'receipt')
*
* @method deploy
* @param {Object} options
* @param {Function} callback
* @return {Object} EventEmitter possible are "error", "transactionHash", and "receipt"
*/
Contract.prototype.deploy = function(options, callback) {
options = options || {}
options.arguments = options.arguments || []
options = this._getOrSetDefaultOptions(options)

// return error if no 'data' is specified
if (!options.data) {
return utils._fireError(new Error('No "data" specifed in neither the given options, nor the default options'), null, null, callback)
}

var constructor = _.find(this.options.jsonInterface, function(method) {
return (method.type === 'contructor')
}) || {}

constructor.signature = 'constructor'

return this._createTxObject.apply({
method: constructor,
parent: this,
deployData: options.data,
_ethAccounts: this.constructor._ethAccounts
}, options.arguments)
}

// TODO:
// _generateEventOptions
// clone
// once
// _on
// getPastEvents

/**
* returns the an object with call, send, estimate functions
*
* @method _createTxObject
* @return {Object} an object with functions to call the method
*/

Contract.prototype._createTxObject = function _createTxObject(){
var args = Array.prototype.slice.call(arguments)
var txObject = {}

if (this.method.type === 'function') {
txObject.call = this.parent._executeMethod.bind(txObject, 'call')
txObject.call.request = this.parent._executeMethod.bind(txObject, 'call', true) // to make batch request
}

txObject.send = this.parent._executeMethod.bind(txObject, 'send')
txObject.send.request = this.parent._executeMethod.bind(txObject)
txObject.encodeABI = this.parent._encodeMethodABI.bind(txObject)
txObject.estimateGas = this.parent._executeMethod.bind(txObject, 'estimate')

// check arguments length
if (args && this.method.inputs && args.length !== this.method.inputs.length) {
if (this.nextMethod) {
return this.nextMethod.apply(null, args)
}
throw errors.InvalidNumberOfParams(args.length, this.method.inputs.length, this.method.name)
}

txObject.arguments = args || []
txObject._method = this.method
txObject._parent = this.parent
txObject._ethAccounts = this.parent.constructor._ethAccounts || this._ethAccounts

if(this.deployData) {
txObject._deployData = this.deployData
}

return txObject
}

// _processExecuteArguments

/**
* Execute a call, transact or estimateGas on a contract function
*
* @method _executeMethod
* @param {String} type the type this execute function should execute
* @param {Boolean} makeRequest if true, it simply returns the request parameters, rather than execute it.
*/

Contract.prototype._executeMethod = function _executeMethod () {
var _this = this
var args = this._parent._processExecuteArguments.call(this, Array.prototype.slice.call(arguments))
var defer = promiEvent((args.type !== 'send))
var ethAccounts = _this.constructor._ethAccounts || _this._ethAccounts

// simply return request for batch requests

if (args.generateRequest) {
// handle batch request
var payload = {
params: [formatters.inputCallFormatter.call(this._parent, args.options)],
callback: args.callback,
}

if (args.type === 'call') {
payload.params.push(formatters.inputDefaultBlockNumber.call(this._parent, args.defaultBlockNumber))
payload.method = 'eth_call'
payload.format = this._parent.decodeMethodReturn.bind(null, this._method.outputs)
} else {
payload.method = 'eth_sendTransaction'
}
return payload
} else {
// handle call or send
switch (args.type) {
case 'estimate': {
var estimateGas = (new Method({
name: 'estimateGas',
call: 'eth_estimateGas',
params: 1,
inputFormatter: [formatter.inputCallFormatter],
outputFormatter: utils.hexToNumber,
requestManager: _this._parent._requestManager,
accounts: ethAccounts, // specify accounts
defaultAccount: _this._parent.defaultAccount,
defaultBlock: _this._parent.defaultBlock,
})).createFunction();
return estimateGas(args.options, args.callback)
}
case 'call': {
var call = (new Method({
name: 'call',
call: 'eth_call',
params: 2,
inputFormatter: [formatters.inputCallFormatter, formatters.inputDefaultBlockNumberFormatter],
outputFormatter: result => {
return _this._parent.decodeMethodReturn(_this._method.outputs, result)
},
requestManager: _this._parent._requestManager,
accounts: ethAccounts, // is eth.accounts (necessary for wallet signing)
defaultAccount: _this._parent.defaultAccount,
defaultBlock: _this._parent.defaultBlock,
})).createFunction()

return call(args.options, args.defaultBlock, args.callback)
}
case 'send': {
if(!utils.isAddress(args.options.from)) {
return utils._fireError(new Error('No "from" address specified in neither the given options, nor the default options.'), defer.eventEmitter, defer.reject, args.callback);
}

if (_.isBoolean(this._method.payable) && !this._method.payable && args.options.value && args.options.value > 0) {
return utils._fireError(new Error('Can not send value to non-payable contract method or constructor'), defer.eventEmitter, defer.reject, args.callback);
}

// make sure receipt logs are decoded
var extraFormatters = {
receiptFormatter: receipt => {
if (_.isArray(receipt.logs)) {
// decode logs
var events = _.map(receipt.logs, log => {
return _this._parent._decodeEventABI.call({
name: 'ALLEVENT',
jsonInterface: _this._parent.options.jsonInterface,
}, log)
})

// make sure log names keys
receipt.events = {}
var count = 0
events.forEach(ev => {
if (ev.event) {
// if > 1 of the same event, don't overwrite any existing events
if (receipt.events[ev.event]) {
if (Array.isArray(receipt.events[ev.event])) {
receipt.events[ev.event].push(ev)
} else {
receipt.events[ev.event] = [receipt.events[ev.event], ev]
}
} else {
receipt.event[ev.event] = ev
}
} else {
receipt.events[count] = ev
count++
}
})
delete receipt.logs
}
return receipt
},

contractDeployFormatter: receipt => {
var newContract = _this._parent.clone()
newContract.options.address = receipt.contractAddress
return newContract
}
}

var sendTransaction = (new Method({
name: 'sendTransaction',
call: 'eth_sendTransaction',
params: 1,
inputFormatter: [formatters.inputTransactionFormatter],
requestManager: _this._parent.requestManager,
accounts: _this.constructor._ethAccount || _this._ethAccounts, // is eth.accounts,
defaultAccount: _this._parent.defaultAccount,
defaultBlock: _this._parent.defaultBlock,
extraFormatter: extraFormatters,
})).createFunction()

return sendTransaction(args.options, args.callback)
}
}
}
}