@leofcoin/chain 1.4.21 → 1.4.22

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +14 -14
  2. package/LICENSE +88 -88
  3. package/README.md +4 -4
  4. package/demo/index.html +25 -25
  5. package/examples/contracts/token.js +7 -7
  6. package/package.json +71 -75
  7. package/plugins/bundle.js +18 -18
  8. package/src/{chain.ts → chain.js} +716 -710
  9. package/src/config/config.js +14 -14
  10. package/src/config/main.js +4 -4
  11. package/src/config/protocol.js +5 -5
  12. package/src/contract.js +51 -51
  13. package/src/fee/config.js +3 -3
  14. package/src/machine.js +215 -215
  15. package/src/{node.ts → node.js} +24 -24
  16. package/src/protocol.js +3 -3
  17. package/src/state.js +31 -31
  18. package/src/{transaction.ts → transaction.js} +233 -181
  19. package/src/type.index.d.ts +20 -20
  20. package/src/typer.js +19 -19
  21. package/test/chain.js +120 -150
  22. package/test/contracts/token.js +40 -40
  23. package/test/create-genesis.js +66 -66
  24. package/tsconfig.js +15 -0
  25. package/workers/block-worker.js +40 -40
  26. package/workers/machine-worker.js +218 -218
  27. package/workers/pool-worker.js +28 -28
  28. package/workers/transaction-worker.js +19 -19
  29. package/workers/workers.js +8 -8
  30. package/block-worker.js +0 -1
  31. package/demo/865.browser.js +0 -10
  32. package/demo/chain.browser.js +0 -66842
  33. package/demo/generate-account.browser.js +0 -50
  34. package/demo/messages.browser.js +0 -328
  35. package/demo/multi-wallet.browser.js +0 -15
  36. package/demo/node.browser.js +0 -9858
  37. package/demo/pako.browser.js +0 -6900
  38. package/demo/peernet-swarm.browser.js +0 -839
  39. package/demo/storage.browser.js +0 -3724
  40. package/demo/workers/865.js +0 -10
  41. package/demo/workers/block-worker.js +0 -13175
  42. package/demo/workers/machine-worker.js +0 -13385
  43. package/demo/workers/pool-worker.js +0 -8503
  44. package/demo/workers/transaction-worker.js +0 -8495
  45. package/demo/wrtc.browser.js +0 -28
  46. package/dist/browser/workers/865.js +0 -10
  47. package/dist/browser/workers/block-worker.js +0 -9460
  48. package/dist/browser/workers/machine-worker.js +0 -9670
  49. package/dist/browser/workers/pool-worker.js +0 -4608
  50. package/dist/browser/workers/transaction-worker.js +0 -4600
  51. package/dist/chain.js +0 -10128
  52. package/dist/client-80bc8156.js +0 -491
  53. package/dist/commonjs-7fe3c381.js +0 -270
  54. package/dist/contracts/factory.js +0 -1
  55. package/dist/contracts/name-service.js +0 -1
  56. package/dist/contracts/native-token.js +0 -1
  57. package/dist/contracts/validators.js +0 -1
  58. package/dist/generate-account-445db122.js +0 -46
  59. package/dist/index-57f93805.js +0 -718
  60. package/dist/messages-bce1b91d-81af3b00.js +0 -315
  61. package/dist/module/chain.js +0 -10091
  62. package/dist/module/client-8031ec88.js +0 -489
  63. package/dist/module/commonjs-9005d5c0.js +0 -268
  64. package/dist/module/generate-account-489552b6.js +0 -44
  65. package/dist/module/index-ac2285c4.js +0 -688
  66. package/dist/module/messages-bce1b91d-eaf75d83.js +0 -302
  67. package/dist/module/node.js +0 -7049
  68. package/dist/module/workers/block-worker.js +0 -94
  69. package/dist/module/workers/machine-worker.js +0 -304
  70. package/dist/module/workers/pool-worker.js +0 -55
  71. package/dist/module/workers/transaction-worker.js +0 -47
  72. package/dist/node.js +0 -7061
  73. package/dist/standards/token.js +0 -1
  74. package/dist/workers/machine-worker.js +0 -1
  75. package/dist/workers/pool-worker.js +0 -1
  76. package/dist/workers/transaction-worker.js +0 -1
  77. package/rollup.config.js +0 -15
  78. package/tsconfig.json +0 -17
@@ -1,270 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('path');
4
- var os = require('os');
5
- var fs = require('fs');
6
- var child_process = require('child_process');
7
- var classicLevel = require('classic-level');
8
-
9
- // import base32 from '@vandeurenglenn/base32'
10
- // import base58 from '@vandeurenglenn/base58'
11
-
12
- // export const encodings = {
13
- // base58,
14
- // base32
15
- // }
16
-
17
- const encode = (string, encoding = 'utf-8') => {
18
- if (typeof string === 'string') {
19
- let encoded;
20
-
21
- // if (encodings[encoding]) encoded = encodings[encoding].encode(encoded)
22
- encoded = new TextEncoder().encode(string);
23
- return encoded
24
- }
25
- throw Error(`expected typeof String instead got ${string}`)
26
- };
27
-
28
- const decode = (uint8Array, encoding) => {
29
- if (uint8Array instanceof Uint8Array) {
30
- let decoded;
31
- // if (encodings[encoding]) decoded = encodings[encoding].decode(decoded)
32
- decoded = new TextDecoder().decode(uint8Array);
33
-
34
- return decoded
35
- }
36
- throw Error(`expected typeof uint8Array instead got ${uint8Array}`)
37
- };
38
-
39
- const pathSepS = '/';
40
- class KeyPath {
41
-
42
- /**
43
- * @param {string | Uint8Array} input
44
- */
45
- constructor(input) {
46
- if (typeof input === 'string') {
47
- this.uint8Array = encode(input);
48
- } else if (input instanceof Uint8Array) {
49
- this.uint8Array = input;
50
- } else if (input instanceof KeyPath) {
51
- this.uint8Array = input.uint8Array;
52
- } else {
53
- throw new Error('Invalid keyPath, should be a String, Uint8Array or KeyPath')
54
- }
55
- }
56
-
57
- /**
58
- * Convert to the string representation
59
- *
60
- * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
61
- * @returns {string}
62
- */
63
- toString (encoding = 'hex') {
64
- return decode(this.uint8Array)
65
- }
66
-
67
- /**
68
- * Returns the `list` representation of this path.
69
- *
70
- * @returns {Array<string>}
71
- *
72
- * @example
73
- * ```js
74
- * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()
75
- * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']
76
- * ```
77
- */
78
- list() {
79
- return this.toString().split(pathSepS).slice(1)
80
- }
81
-
82
- }
83
-
84
- class KeyValue {
85
-
86
- /**
87
- * @param {string | Uint8Array} input
88
- */
89
- constructor(input) {
90
- if (typeof input === 'string') {
91
- this.uint8Array = encode(input);
92
- } else if (input instanceof Uint8Array) {
93
- this.uint8Array = input;
94
- } else if (input instanceof KeyValue) {
95
- this.uint8Array = input.uint8Array;
96
- } else {
97
- throw new Error('Invalid KeyValue, should be a String, Uint8Array or KeyValue')
98
- }
99
- }
100
-
101
- /**
102
- * Convert to the string representation
103
- *
104
- * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.
105
- * @returns {string}
106
- */
107
- toString(encoding = 'utf8') {
108
- return decode(this.uint8Array)
109
- }
110
-
111
- }
112
-
113
- const mkdirp = path => child_process.execSync(`mkdir "${path.replace(/\//g, '\\')}"`);
114
-
115
- const init = (root, home = true) => {
116
- let _root;
117
- if (home) _root = path.join(os.homedir(), root);
118
- if (fs.readdirSync) try {
119
- fs.readdirSync(_root);
120
- } catch (e) {
121
- mkdirp(_root);
122
- }
123
-
124
- return _root
125
- };
126
-
127
- class Store {
128
- constructor(name = 'storage', root, version = 'v1.0.0') {
129
- this.name = name;
130
- this.root = init(root);
131
- this.version = version;
132
-
133
- this.db = new classicLevel.ClassicLevel(path.join(this.root, this.name), { valueEncoding: 'view'});
134
- }
135
-
136
- toKeyPath(key) {
137
- return key ? key.toString('base32') : key
138
- }
139
-
140
- toKeyValue(value) {
141
- return value.uint8Array
142
- }
143
-
144
- async get(key) {
145
- return this.db.get(this.toKeyPath(key))
146
- }
147
-
148
- async put(key, value) {
149
- return this.db.put(this.toKeyPath(key), this.toKeyValue(value))
150
- }
151
-
152
- async delete(key) {
153
- return this.db.del(this.toKeyPath(key))
154
- }
155
-
156
- async clear() {
157
- return this.db.clear()
158
- }
159
-
160
- async values(limit = -1) {
161
- const values = [];
162
- for await (const value of this.db.values({limit})) {
163
- values.push(value);
164
- }
165
- return values
166
- }
167
-
168
- async keys(limit = -1) {
169
- const keys = [];
170
- for await (const key of this.db.keys({limit})) {
171
- keys.push(key);
172
- }
173
- return keys
174
- }
175
-
176
- }
177
-
178
- class LeofcoinStorage {
179
-
180
- constructor(name = 'storage', root = '.leofcoin') {
181
- this.name = name;
182
- this.db = new Store(name, root);
183
- }
184
-
185
- async get(key) {
186
- if (!key) return this.query()
187
- if (typeof key === 'object') return this.many('get', key);
188
- return this.db.get(new KeyPath(key))
189
- }
190
-
191
- /**
192
- *
193
- * @param {*} key
194
- * @param {*} value
195
- * @returns Promise
196
- */
197
- put(key, value) {
198
- if (typeof key === 'object') return this.many('put', key);
199
- return this.db.put(new KeyPath(key), new KeyValue(value));
200
- }
201
-
202
- async has(key) {
203
- if (typeof key === 'object') return this.many('has', key);
204
-
205
- try {
206
- const has = await this.db.get(new KeyPath(key));
207
-
208
- return Boolean(has);
209
- } catch (e) {
210
- return false
211
- }
212
- }
213
-
214
- async delete(key) {
215
- return this.db.delete(new KeyPath(key))
216
- }
217
-
218
- keys(limit = -1) {
219
- return this.db.keys({limit})
220
- }
221
-
222
- async #queryJob(key) {
223
- const value = await this.db.get(key);
224
- return { key, value }
225
- }
226
-
227
- async query() {
228
- const keys = await this.keys();
229
- let promises = [];
230
- for (const key of keys) {
231
- promises.push(this.#queryJob(key));
232
- }
233
- return Promise.all(promises)
234
- }
235
-
236
- async values(limit = -1) {
237
- return this.db.values({limit})
238
- }
239
-
240
- async many(type, _value) {
241
- const jobs = [];
242
-
243
- for (const key of Object.keys(_value)) {
244
- jobs.push(this[type](key, _value[key]));
245
- }
246
-
247
- return Promise.all(jobs)
248
- }
249
-
250
- async length() {
251
- const keys = await this.keys();
252
- return keys.length
253
- }
254
-
255
- async size() {
256
- let size = 0;
257
- const query = await this.query();
258
- for (const item of query) {
259
- size += item.value.length;
260
- }
261
- return size
262
- }
263
-
264
- async clear() {
265
- return this.db.clear()
266
- }
267
-
268
- }
269
-
270
- module.exports = LeofcoinStorage;
@@ -1 +0,0 @@
1
- class Factory{#name="ArtOnlineContractFactory";#totalContracts=0;#contracts=[];constructor(state){state&&(this.#contracts=state.contracts,this.#totalContracts=state.totalContracts)}get state(){return{totalContracts:this.#totalContracts,contracts:this.#contracts}}get name(){return this.#name}get contracts(){return[...this.#contracts]}get totalContracts(){return this.#totalContracts}async registerContract(address){if(await msg.staticCall(address,"hasRole",[msg.sender,"OWNER"]),this.#contracts.includes(address))throw new Error("already registered");this.#totalContracts+=1,this.#contracts.push(address)}}export{Factory as default};
@@ -1 +0,0 @@
1
- class NameService{#name="ArtOnlineNameService";#owner;#price=0;#registry={};#currency;get name(){return this.#name}get registry(){return{...this.#registry}}get state(){}constructor(factoryAddress,currency,validatorAddress,price,state){state?(this.#owner=state.owner,this.#registry=state.registry,this.#currency=state.currency,this.#price=state.price):(this.#owner=msg.sender,this.#price=price,this.#registry.ArtOnlineContractFactory={owner:msg.sender,address:factoryAddress},this.#registry.ArtOnlineToken={owner:msg.sender,address:currency},this.#registry.ArtOnlineValidators={owner:msg.sender,address:validatorAddress},this.#currency=currency)}changeOwner(owner){if(msg.sender!==this.#owner)throw new Error("no owner");this.#owner=owner}changePrice(price){if(msg.sender!==this.#owner)throw new Error("no owner");this.#price=price}changeCurrency(currency){if(msg.sender!==this.#owner)throw new Error("no owner");this.#currency=currency}async purchaseName(name,address){if(await msg.call(this.#currency,"balanceOf",[msg.sender])<this.#price)throw new Error("price exceeds balance");try{await msg.call(this.#currency,"transfer",[msg.sender,this.#owner,this.#price])}catch(error){throw error}this.#registry[name]={owner:msg.sender,address}}lookup(name){return this.#registry[name]}transferOwnership(name,to){if(msg.sender!==this.#registry.owner)throw new Error("not a owner");this.#registry[name].owner=to}changeAddress(name,address){if(msg.sender!==this.#registry.owner)throw new Error("not a owner");this.#registry[name].address=address}}export{NameService as default};
@@ -1 +0,0 @@
1
- class Roles{#roles={OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Token extends Roles{#name;#symbol;#holders=0;#balances={};#approvals={};#decimals=18;#totalSupply=BigNumber.from(0);constructor(name,symbol,decimals=18,state){if(!name)throw new Error("name undefined");if(!symbol)throw new Error("symbol undefined");super(state?.roles),this.#name=name,this.#symbol=symbol,this.#decimals=decimals}get state(){return{...super.state,holders:this.holders,balances:this.balances,approvals:{...this.#approvals},totalSupply:this.totalSupply}}get totalSupply(){return this.#totalSupply}get name(){return this.#name}get symbol(){return this.#symbol}get holders(){return this.#holders}get balances(){return{...this.#balances}}mint(to,amount){if(!this.hasRole(msg.sender,"MINT"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.add(amount),this.#increaseBalance(to,amount)}burn(from,amount){if(!this.hasRole(msg.sender,"BURN"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.sub(amount),this.#decreaseBalance(from,amount)}#beforeTransfer(from,to,amount){if(!this.#balances[from]||this.#balances[from]<amount)throw new Error("amount exceeds balance")}#updateHolders(address,previousBalance){"0x00"===this.#balances[address].toHexString()?this.#holders-=1:"0x00"!==this.#balances[address].toHexString()&&"0x00"===previousBalance.toHexString()&&(this.#holders+=1)}#increaseBalance(address,amount){this.#balances[address]||(this.#balances[address]=BigNumber.from(0));const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].add(amount),this.#updateHolders(address,previousBalance)}#decreaseBalance(address,amount){const previousBalance=this.#balances[address];this.#balances[address]=this.#balances[address].sub(amount),this.#updateHolders(address,previousBalance)}balanceOf(address){return this.#balances[address]}setApproval(operator,amount){const owner=globalThis.msg.sender;this.#approvals[owner]||(this.#approvals[owner]={}),this.#approvals[owner][operator]=amount}approved(owner,operator,amount){return this.#approvals[owner][operator]===amount}transfer(from,to,amount){amount=BigNumber.from(amount),this.#beforeTransfer(from,to,amount),this.#decreaseBalance(from,amount),this.#increaseBalance(to,amount)}}class ArtOnline extends Token{constructor(state){super("ArtOnline","ART",18,state)}}export{ArtOnline as default};
@@ -1 +0,0 @@
1
- class Roles{#roles={OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new TypeError("expected roles to be an object");this.#roles={...roles,...this.#roles}}else this.#grantRole(msg.sender,"OWNER")}get state(){return{roles:this.roles}}get roles(){return{...this.#roles}}hasRole(address,role){return!!this.#roles[role]&&this.#roles[role].includes(address)}#grantRole(address,role){if(this.hasRole(address,role))throw new Error(`${role} role already granted for ${address}`);this.#roles[role].push(address)}#revokeRole(address,role){if(!this.hasRole(address,role))throw new Error(`${role} role already revoked for ${address}`);if("OWNER"===role&&1===this.#roles[role].length)throw new Error("atleast one owner is needed!");this.#roles[role].splice(this.#roles[role].indexOf(address))}grantRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#grantRole(address,role)}revokeRole(address,role){if(!this.hasRole(address,"OWNER"))throw new Error("Not allowed");this.#revokeRole(address,role)}}class Validators extends Roles{#name="ArtOnlineValidators";#totalValidators=0;#activeValidators=0;#validators={};#currency;#minimumBalance;get state(){return{...super.state,minimumBalance:this.#minimumBalance,currency:this.#currency,totalValidators:this.#totalValidators,activeValidators:this.#activeValidators,validators:this.#validators}}constructor(tokenAddress,state){super(state?.roles),state?(this.#minimumBalance=state.minimumBalance,this.#currency=state.currency,this.#totalValidators=state.totalValidators,this.#activeValidators=state.activeValidators,this.#validators=state.validators):(this.#minimumBalance=5e4,this.#currency=tokenAddress,this.#totalValidators+=1,this.#activeValidators+=1,this.#validators[msg.sender]={firstSeen:Date.now(),lastSeen:Date.now(),active:!0})}get name(){return this.#name}get currency(){return this.#currency}get validators(){return{...this.#validators}}get totalValidators(){return this.#totalValidators}get minimumBalance(){return this.#minimumBalance}changeCurrency(currency){if(!this.hasRole(msg.sender,"OWNER"))throw new Error("not an owner");this.#currency=currency}has(validator){return Boolean(void 0!==this.#validators[validator])}#isAllowed(address){if(msg.sender!==address&&!this.hasRole(msg.sender,"OWNER"))throw new Error("sender is not the validator or owner");return!0}async addValidator(validator){if(this.#isAllowed(validator),this.has(validator))throw new Error("already a validator");const balance=await msg.staticCall(this.currency,"balanceOf",[validator]);if(balance<this.minimumBalance)throw new Error(`balance to low! got: ${balance} need: ${this.#minimumBalance}`);this.#totalValidators+=1,this.#activeValidators+=1,this.#validators[validator]={firstSeen:Date.now(),lastSeen:Date.now(),active:!0}}removeValidator(validator){if(this.#isAllowed(validator),!this.has(validator))throw new Error("validator not found");this.#totalValidators-=1,this.#validators[validator].active&&(this.#activeValidators-=1),delete this.#validators[validator]}async updateValidator(validator,active){if(this.#isAllowed(validator),!this.has(validator))throw new Error("validator not found");const balance=await msg.staticCall(this.currency,"balanceOf",[validator]);if(balance<this.minimumBalance&&active)throw new Error(`balance to low! got: ${balance} need: ${this.#minimumBalance}`);if(this.#validators[validator].active===active)throw new Error("already "+(active?"activated":"deactivated"));active?this.#activeValidators+=1:this.#activeValidators-=1,this.#validators[validator].active=active}}export{Validators as default};
@@ -1,46 +0,0 @@
1
- 'use strict';
2
-
3
- var MultiWallet = require('@leofcoin/multi-wallet');
4
-
5
- function _interopDefaultLegacy$1 (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
6
-
7
- var MultiWallet__default = /*#__PURE__*/_interopDefaultLegacy$1(MultiWallet);
8
-
9
- /**
10
- * @params {String} network
11
- * @return {object} { identity, accounts, config }
12
- */
13
- var generateAccount = async network => {
14
- let wallet = new MultiWallet__default["default"](network);
15
- /**
16
- * @type {string}
17
- */
18
- const mnemonic = await wallet.generate();
19
-
20
- wallet = new MultiWallet__default["default"](network);
21
- await wallet.recover(mnemonic, network);
22
- /**
23
- * @type {object}
24
- */
25
- const account = wallet.account(0);
26
- /**
27
- * @type {object}
28
- */
29
- const external = account.external(0);
30
- const internal = account.internal(0);
31
-
32
- return {
33
- identity: {
34
- mnemonic,
35
- // multiWIF: wallet.export(),
36
- publicKey: external.publicKey,
37
- privateKey: external.privateKey,
38
- walletId: external.id
39
- },
40
- accounts: [['main account', external.address, internal.address]]
41
- // config: {
42
- // }
43
- }
44
- };
45
-
46
- module.exports = generateAccount;