Files: aafe96ace826878428496f61ad0f8a93f9fccd2e / systemObjects.js
2064 bytesRaw
1 | const cbor = require('borc') |
2 | |
3 | const TAGS = { |
4 | id: 41, |
5 | link: 42, |
6 | func: 43, |
7 | mod: 44 |
8 | } |
9 | |
10 | const DEFAULTS = { |
11 | elem: [], |
12 | data: Buffer.from([]), |
13 | id: new cbor.Tagged(TAGS.id, 0), |
14 | mod: new cbor.Tagged(TAGS.mod, [{}, new cbor.Tagged(TAGS.id, 0)]), |
15 | link: {'/': null}, |
16 | func: new cbor.Tagged(TAGS.func, 0) |
17 | } |
18 | |
19 | const decoder = new cbor.Decoder({ |
20 | tags: { |
21 | [TAGS.id]: val => new ID(val), |
22 | [TAGS.func]: val => new FunctionRef(...val), |
23 | [TAGS.mod]: val => new ModuleRef(...val) |
24 | } |
25 | }) |
26 | |
27 | class Serializable { |
28 | serialize () { |
29 | const encoder = new cbor.Encoder() |
30 | this.encodeCBOR(encoder) |
31 | return encoder.finalize() |
32 | } |
33 | |
34 | static deserialize (serialized) { |
35 | return decoder.decodeFirst(serialized) |
36 | } |
37 | } |
38 | |
39 | class FunctionRef extends Serializable { |
40 | constructor (opts) { |
41 | super() |
42 | this.identifier = opts.identifier |
43 | if (!(opts.id instanceof ID)) { |
44 | opts.id = new ID(opts.id) |
45 | } |
46 | this.destId = opts.id |
47 | this.params = opts.params |
48 | this.gas = opts.gas |
49 | } |
50 | |
51 | encodeCBOR (gen) { |
52 | return gen.write(new cbor.Tagged(TAGS.func, [ |
53 | this.identifier, |
54 | this.params, |
55 | this.destId |
56 | ])) |
57 | } |
58 | |
59 | set container (container) { |
60 | this._container = container |
61 | } |
62 | } |
63 | |
64 | class ModuleRef extends Serializable { |
65 | constructor (ex, id) { |
66 | super() |
67 | this.exports = ex |
68 | this.id = id |
69 | } |
70 | |
71 | getFuncRef (name) { |
72 | return new FunctionRef({ |
73 | identifier: [false, name], |
74 | params: this.exports[name], |
75 | id: this.id |
76 | }) |
77 | } |
78 | |
79 | encodeCBOR (gen) { |
80 | return gen.write(new cbor.Tagged(TAGS.mod, [this.exports, this.id])) |
81 | } |
82 | |
83 | static fromMetaJSON (json, id) { |
84 | const exports = {} |
85 | for (const ex in json.exports) { |
86 | const type = json.types[json.indexes[json.exports[ex].toString()]].params |
87 | exports[ex] = type |
88 | } |
89 | return new ModuleRef(exports, id) |
90 | } |
91 | } |
92 | |
93 | class ID extends Serializable { |
94 | constructor (id) { |
95 | super() |
96 | this.id = id |
97 | } |
98 | |
99 | encodeCBOR (gen) { |
100 | return gen.write(new cbor.Tagged(TAGS.id, this.id)) |
101 | } |
102 | } |
103 | |
104 | module.exports = { |
105 | ID, |
106 | FunctionRef, |
107 | ModuleRef, |
108 | DEFAULTS |
109 | } |
110 |
Built with git-ssb-web