forked from EOSIO/eosjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstructs.js
570 lines (496 loc) · 16.2 KB
/
structs.js
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
const {Signature, PublicKey} = require('eosjs-ecc')
const Fcbuffer = require('fcbuffer')
const ByteBuffer = require('bytebuffer')
const assert = require('assert')
const json = {schema: require('./schema')}
const {
isName, encodeName, decodeName,
DecimalPad, DecimalImply, DecimalUnimply,
printAsset, parseAsset
} = require('./format')
/** Configures Fcbuffer for EOS specific structs and types. */
module.exports = (config = {}, extendedSchema) => {
const structLookup = (lookupName, account) => {
const cachedCode = new Set(['eosio', 'eosio.token', 'eosio.null'])
if(cachedCode.has(account)) {
return structs[lookupName]
}
const abi = config.abiCache.abi(account)
const struct = abi.structs[lookupName]
if(struct != null) {
return struct
}
// TODO: move up (before `const struct = abi.structs[lookupName]`)
for(const action of abi.abi.actions) {
const {name, type} = action
if(name === lookupName) {
const struct = abi.structs[type]
if(struct != null) {
return struct
}
}
}
throw new Error(`Missing ABI struct or action: ${lookupName}`)
}
// If nodeos does not have an ABI setup for a certain action.type, it will throw
// an error: `Invalid cast from object_type to string` .. forceActionDataHex
// may be used to until native ABI is added or fixed.
const forceActionDataHex = config.forceActionDataHex != null ?
config.forceActionDataHex : true
const override = Object.assign({},
authorityOverride,
abiOverride(structLookup),
wasmCodeOverride(config),
actionDataOverride(structLookup, forceActionDataHex),
config.override
)
const eosTypes = {
name: ()=> [Name],
public_key: () => [variant(PublicKeyEcc)],
symbol: () => [Symbol],
extended_symbol: () => [ExtendedSymbol],
asset: () => [Asset], // After Symbol: amount, precision, symbol, contract
extended_asset: () => [ExtendedAsset], // After Asset: amount, precision, symbol, contract
signature: () => [variant(SignatureType)]
}
const customTypes = Object.assign({}, eosTypes, config.customTypes)
config = Object.assign({override}, {customTypes}, config)
// Do not sort transaction actions
config.sort = Object.assign({}, config.sort)
config.sort['action.authorization'] = true
config.sort['signed_transaction.signature'] = true
config.sort['authority.accounts'] = true
config.sort['authority.keys'] = true
const schema = Object.assign({}, json.schema, extendedSchema)
const {structs, types, errors, fromBuffer, toBuffer} = Fcbuffer(schema, config)
if(errors.length !== 0) {
throw new Error(JSON.stringify(errors, null, 4))
}
return {structs, types, fromBuffer, toBuffer}
}
/**
Name eos::types native.hpp
*/
const Name = (validation) => {
return {
fromByteBuffer (b) {
const n = decodeName(b.readUint64(), false) // b is already in littleEndian
// if(validation.debug) {
// console.error(`${n}`, '(Name.fromByteBuffer)')
// }
return n
},
appendByteBuffer (b, value) {
// if(validation.debug) {
// console.error(`${value}`, (Name.appendByteBuffer))
// }
b.writeUint64(encodeName(value, false)) // b is already in littleEndian
},
fromObject (value) {
return value
},
toObject (value) {
if (validation.defaults && value == null) {
return ''
}
return value
}
}
}
/**
A variant is like having a version of an object. A varint comes
first and identifies which type of object this is.
@arg {Array} variantArray array of types
*/
const variant = (...variantArray) => (validation, baseTypes, customTypes) => {
const variants = variantArray.map(Type => Type(validation, baseTypes, customTypes))
const staticVariant = baseTypes.static_variant(variants)
return {
fromByteBuffer (b) {
return staticVariant.fromByteBuffer(b)
},
appendByteBuffer (b, value) {
if(!Array.isArray(value)) {
value = [0, value]
}
staticVariant.appendByteBuffer(b, value)
},
fromObject (value) {
if(!Array.isArray(value)) {
value = [0, value]
}
return staticVariant.fromObject(value)[1]
},
toObject (value) {
if(!Array.isArray(value)) {
value = [0, value]
}
return staticVariant.toObject(value)[1]
}
}
}
const PublicKeyEcc = (validation) => {
return {
fromByteBuffer (b) {
const bcopy = b.copy(b.offset, b.offset + 33)
b.skip(33)
const pubbuf = Buffer.from(bcopy.toBinary(), 'binary')
return PublicKey.fromBuffer(pubbuf).toString()
},
appendByteBuffer (b, value) {
// if(validation.debug) {
// console.error(`${value}`, 'PublicKeyType.appendByteBuffer')
// }
const buf = PublicKey.fromStringOrThrow(value).toBuffer()
b.append(buf.toString('binary'), 'binary')
},
fromObject (value) {
return value
},
toObject (value) {
if (validation.defaults && value == null) {
return 'EOS6MRy..'
}
return value
}
}
}
/**
Internal: precision, symbol
External: symbol
@example 'SYS'
*/
const Symbol = validation => {
return {
fromByteBuffer (b) {
const bcopy = b.copy(b.offset, b.offset + 8)
b.skip(8)
const precision = bcopy.readUint8()
const bin = bcopy.toBinary()
let symbol = ''
for(const code of bin) {
if(code == '\0') {
break
}
symbol += code
}
return `${precision},${symbol}`
},
appendByteBuffer (b, value) {
const {symbol, precision} = parseAsset(value)
assert(precision != null, `Precision unknown for symbol: ${value}`)
const pad = '\0'.repeat(7 - symbol.length)
b.append(String.fromCharCode(precision) + symbol + pad)
},
fromObject (value) {
assert(value != null, `Symbol is required: ` + value)
const {symbol, precision} = parseAsset(value)
if(precision == null) {
return symbol
} else {
// Internal object, this can have the precision prefix
return `${precision},${symbol}`
}
},
toObject (value) {
if (validation.defaults && value == null) {
return 'SYS'
}
// symbol only (without precision prefix)
return parseAsset(value).symbol
}
}
}
/**
Internal: precision, symbol, contract
External: symbol, contract
@example 'SYS@contract'
*/
const ExtendedSymbol = (validation, baseTypes, customTypes) => {
const symbolType = customTypes.symbol(validation)
const contractName = customTypes.name(validation)
return {
fromByteBuffer (b) {
const symbol = symbolType.fromByteBuffer(b)
const contract = contractName.fromByteBuffer(b)
return `${symbol}@${contract}`
},
appendByteBuffer (b, value) {
assert.equal(typeof value, 'string', 'Invalid extended symbol: ' + value)
const [symbol, contract] = value.split('@')
assert(contract != null, 'Missing @contract suffix in extended symbol: ' + value)
symbolType.appendByteBuffer(b, symbol)
contractName.appendByteBuffer(b, contract)
},
fromObject (value) {
return value
},
toObject (value) {
if (validation.defaults && value == null) {
return 'SYS@contract'
}
return value
}
}
}
/**
Internal: amount, precision, symbol, contract
@example '1.0000 SYS'
*/
const Asset = (validation, baseTypes, customTypes) => {
const amountType = baseTypes.int64(validation)
const symbolType = customTypes.symbol(validation)
return {
fromByteBuffer (b) {
const amount = amountType.fromByteBuffer(b)
assert(amount != null, 'amount')
const sym = symbolType.fromByteBuffer(b)
const {precision, symbol} = parseAsset(`${sym}`)
assert(precision != null, 'precision')
assert(symbol != null, 'symbol')
return `${DecimalUnimply(amount, precision)} ${symbol}`
},
appendByteBuffer (b, value) {
const {amount, precision, symbol} = parseAsset(value)
assert(amount != null, 'amount')
assert(precision != null, 'precision')
assert(symbol != null, 'symbol')
amountType.appendByteBuffer(b, DecimalImply(amount, precision))
symbolType.appendByteBuffer(b, `${precision},${symbol}`)
},
fromObject (value) {
const {amount, precision, symbol} = parseAsset(value)
assert(amount != null, 'amount')
assert(precision != null, 'precision')
assert(symbol != null, 'symbol')
return `${DecimalPad(amount, precision)} ${symbol}`
},
toObject (value) {
if (validation.defaults && value == null) {
return '0.0001 SYS'
}
const {amount, precision, symbol} = parseAsset(value)
assert(amount != null, 'amount')
assert(precision != null, 'precision')
assert(symbol != null, 'symbol')
return `${DecimalPad(amount, precision)} ${symbol}`
}
}
}
/**
@example '1.0000 SYS@contract'
*/
const ExtendedAsset = (validation, baseTypes, customTypes) => {
const assetType = customTypes.asset(validation)
const contractName = customTypes.name(validation)
return {
fromByteBuffer (b) {
const asset = assetType.fromByteBuffer(b)
const contract = contractName.fromByteBuffer(b)
return parseAsset(`${asset}@${contract}`)
},
appendByteBuffer (b, value) {
assert.equal(typeof value, 'object', 'expecting extended_asset object, got ' + typeof value)
const asset = printAsset(value)
const [, contract] = asset.split('@')
assert.equal(typeof contract, 'string', 'Invalid extended asset: ' + value)
// asset includes contract (assetType needs this)
assetType.appendByteBuffer(b, asset)
contractName.appendByteBuffer(b, contract)
},
fromObject (value) {
// like: 1.0000 SYS@contract or 1 SYS@contract
const asset = {}
if(typeof value === 'string') {
Object.assign(asset, parseAsset(value))
} else if (typeof value === 'object') {
Object.assign(asset, value)
} else {
assert(false, 'expecting extended_asset<object|string>, got: ' + typeof value)
}
const {amount, precision, symbol, contract} = asset
assert(amount != null, 'missing amount')
assert(precision != null, 'missing precision')
assert(symbol != null, 'missing symbol')
assert(contract != null, 'missing contract')
return {amount, precision, symbol, contract}
},
toObject (value) {
if (validation.defaults && value == null) {
return {
amount: '1.0000',
precision: 4,
symbol: 'SYS',
contract: 'eosio.token'
}
}
assert.equal(typeof value, 'object', 'expecting extended_asset object')
const {amount, precision, symbol, contract} = value
return {
amount: DecimalPad(amount, precision),
precision,
symbol,
contract
}
}
}
}
const SignatureType = (validation, baseTypes) => {
const signatureType = baseTypes.fixed_bytes65(validation)
return {
fromByteBuffer (b) {
const signatureBuffer = signatureType.fromByteBuffer(b)
const signature = Signature.from(signatureBuffer)
return signature.toString()
},
appendByteBuffer (b, value) {
const signature = Signature.from(value)
signatureType.appendByteBuffer(b, signature.toBuffer())
},
fromObject (value) {
const signature = Signature.from(value)
return signature.toString()
},
toObject (value) {
if (validation.defaults && value == null) {
return 'SIG_K1_bas58signature..'
}
const signature = Signature.from(value)
return signature.toString()
}
}
}
const authorityOverride = ({
/** shorthand `EOS6MRyAj..` */
'authority.fromObject': (value) => {
if(PublicKey.fromString(value)) {
return {
threshold: 1,
keys: [{key: value, weight: 1}]
}
}
if(typeof value === 'string') {
const [account, permission = 'active'] = value.split('@')
return {
threshold: 1,
accounts: [{
permission: {
actor: account,
permission
},
weight: 1
}]
}
}
}
})
const abiOverride = structLookup => ({
'abi.fromObject': (value) => {
if(typeof value === 'string') {
return JSON.parse(value)
}
if(Buffer.isBuffer(value)) {
return JSON.parse(value.toString())
}
},
'setabi.abi.appendByteBuffer': ({fields, object, b}) => {
const ser = structLookup('abi_def', 'eosio')
const b2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)
ser.appendByteBuffer(b2, object.abi)
b.writeVarint32(b2.offset) // length prefix
b.append(b2.copy(0, b2.offset), 'binary')
}
})
const wasmCodeOverride = config => ({
'setcode.code.fromObject': ({object, result}) => {
try {
const code = object.code.toString()
if(/^\s*\(module/.test(code)) {
const {binaryen} = config
assert(binaryen != null, 'required: config.binaryen = require("binaryen")')
if(config.debug) {
console.log('Assembling WASM..')
}
const wasm = Buffer.from(binaryen.parseText(code).emitBinary())
result.code = wasm
} else {
result.code = object.code
}
} catch(error) {
console.error(error, object.code)
throw error
}
}
})
/**
Nested serialized structure. Nested struct may be in HEX or object format.
*/
const actionDataOverride = (structLookup, forceActionDataHex) => ({
'action.data.fromByteBuffer': ({fields, object, b, config}) => {
const ser = (object.name || '') == '' ? fields.data : structLookup(object.name, object.account)
if(ser) {
b.readVarint32() // length prefix (usefull if object.name is unknown)
object.data = ser.fromByteBuffer(b, config)
} else {
// console.log(`Unknown Action.name ${object.name}`)
const lenPrefix = b.readVarint32()
const bCopy = b.copy(b.offset, b.offset + lenPrefix)
b.skip(lenPrefix)
object.data = Buffer.from(bCopy.toBinary(), 'binary')
}
},
'action.data.appendByteBuffer': ({fields, object, b}) => {
const ser = (object.name || '') == '' ? fields.data : structLookup(object.name, object.account)
if(ser) {
const b2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)
ser.appendByteBuffer(b2, object.data)
b.writeVarint32(b2.offset)
b.append(b2.copy(0, b2.offset), 'binary')
} else {
// console.log(`Unknown Action.name ${object.name}`)
const data = typeof object.data === 'string' ? new Buffer(object.data, 'hex') : object.data
if(!Buffer.isBuffer(data)) {
throw new TypeError(`Unknown struct '${object.name}' for contract '${object.account}', locate this struct or provide serialized action.data`)
}
b.writeVarint32(data.length)
b.append(data.toString('binary'), 'binary')
}
},
'action.data.fromObject': ({fields, object, result}) => {
const {data, name} = object
const ser = (name || '') == '' ? fields.data : structLookup(name, object.account)
if(ser) {
if(typeof data === 'object') {
result.data = ser.fromObject(data) // resolve shorthand
} else if(typeof data === 'string') {
const buf = new Buffer(data, 'hex')
result.data = Fcbuffer.fromBuffer(ser, buf)
} else {
throw new TypeError('Expecting hex string or object in action.data')
}
} else {
// console.log(`Unknown Action.name ${object.name}`)
result.data = data
}
},
'action.data.toObject': ({fields, object, result, config}) => {
const {data, name} = object || {}
const ser = (name || '') == '' ? fields.data : structLookup(name, object.account)
if(!ser) {
// Types without an ABI will accept hex
result.data = Buffer.isBuffer(data) ? data.toString('hex') : data
return
}
if(forceActionDataHex) {
const b2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN)
if(data) {
ser.appendByteBuffer(b2, data)
}
result.data = b2.copy(0, b2.offset).toString('hex')
// console.log('result.data', result.data)
return
}
// Serializable JSON
result.data = ser.toObject(data, config)
}
})