@leofcoin/workers 1.5.2 → 1.5.3

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.
package/package.json CHANGED
@@ -1,21 +1,28 @@
1
1
  {
2
2
  "name": "@leofcoin/workers",
3
- "version": "1.5.2",
3
+ "version": "1.5.3",
4
4
  "description": "Workers used in @leofcoin/chain",
5
5
  "type": "module",
6
6
  "private": false,
7
7
  "exports": {
8
- ".": "./src/workers.js",
9
- "./machine-worker": "./src/machine-worker.js",
10
- "./block-worker": "./src/block-worker.js",
8
+ "./machine-worker": {
9
+ "import": "./exports/machine-worker.js",
10
+ "types": "./exports/machine-worker.d.ts"
11
+ },
12
+ "./block-worker": "./exports/block-worker.js",
11
13
  "./transaction-worker": "./src/transaction-worker.js",
12
14
  "./pool-worker": "./src/pool-worker.js"
13
15
  },
16
+ "files": [
17
+ "exports",
18
+ "src/**/*.js"
19
+ ],
14
20
  "scripts": {
15
21
  "prettier": "prettier src --config ./../../.prettierrc --write",
16
22
  "test": "echo \"Error: no test specified\" && exit 1",
17
23
  "npm-check-updates": "npx npm-check-updates -i",
18
- "check-dependencies": "npx depcheck"
24
+ "check-dependencies": "npx depcheck",
25
+ "build": "rollup -c --silent error --cache true"
19
26
  },
20
27
  "keywords": [],
21
28
  "author": "",
@@ -23,7 +30,7 @@
23
30
  "dependencies": {
24
31
  "@leofcoin/addresses": "^1.0.23",
25
32
  "@leofcoin/lib": "^1.2.43",
26
- "@leofcoin/messages": "^1.4.13",
33
+ "@leofcoin/messages": "^1.4.15",
27
34
  "@leofcoin/storage": "^3.5.28",
28
35
  "@leofcoin/utils": "^1.1.18",
29
36
  "@vandeurenglenn/easy-worker": "^1.0.2"
package/CHANGELOG.md DELETED
@@ -1,80 +0,0 @@
1
- # @leofcoin/workers
2
-
3
- ## 1.5.0
4
-
5
- ### Minor Changes
6
-
7
- - Update chain & machine-worker to support LIP1
8
-
9
- ## 1.4.19
10
-
11
- ### Patch Changes
12
-
13
- - 78299bf: bump
14
- - Updated dependencies [78299bf]
15
- - @leofcoin/addresses@1.0.23
16
- - @leofcoin/lib@1.2.43
17
- - @leofcoin/messages@1.4.13
18
- - @leofcoin/utils@1.1.18
19
-
20
- ## 1.4.18
21
-
22
- ### Patch Changes
23
-
24
- - Fix browser build
25
-
26
- ## 1.4.17
27
-
28
- ### Patch Changes
29
-
30
- - Upgrade dependencies
31
- - Updated dependencies
32
- - @leofcoin/addresses@1.0.22
33
- - @leofcoin/lib@1.2.42
34
- - @leofcoin/messages@1.4.12
35
- - @leofcoin/utils@1.1.17
36
-
37
- ## 1.4.16
38
-
39
- ### Patch Changes
40
-
41
- - Upgrade dependencies
42
- - Updated dependencies
43
- - @leofcoin/addresses@1.0.21
44
- - @leofcoin/messages@1.4.11
45
- - @leofcoin/utils@1.1.16
46
- - @leofcoin/lib@1.2.41
47
-
48
- ## 1.4.15
49
-
50
- ### Patch Changes
51
-
52
- - fb4e9c7: Bump
53
- - Updated dependencies [fb4e9c7]
54
- - Updated dependencies [1da023a]
55
- - @leofcoin/addresses@1.0.20
56
- - @leofcoin/messages@1.4.10
57
- - @leofcoin/utils@1.1.15
58
- - @leofcoin/lib@1.2.40
59
-
60
- ## 1.4.14
61
-
62
- ### Patch Changes
63
-
64
- - d239d6b: Bump
65
- - d239d6b: set to public
66
- - Updated dependencies [d239d6b]
67
- - Updated dependencies [d239d6b]
68
- - @leofcoin/addresses@1.0.19
69
- - @leofcoin/lib@1.2.39
70
- - @leofcoin/messages@1.4.9
71
- - @leofcoin/utils@1.1.14
72
-
73
- ## 1.4.13
74
-
75
- ### Patch Changes
76
-
77
- - c24054d: State it
78
- - Updated dependencies [c24054d]
79
- - @leofcoin/addresses@1.0.18
80
- - @leofcoin/lib@1.2.38
@@ -1,42 +0,0 @@
1
- import { BlockMessage } from '@leofcoin/messages'
2
- import { formatBytes, BigNumber } from '@leofcoin/utils'
3
-
4
- import EasyWorker from '@vandeurenglenn/easy-worker'
5
-
6
- declare type messageType = 'put' | 'get'
7
-
8
- declare type message = {
9
- type: messageType
10
- input: string
11
- }
12
-
13
- declare type messageReturn = {
14
- type: messageType
15
- result?: string
16
- message?: string
17
- error?: Error
18
- }
19
-
20
- const _addBlock = (block) => {
21
- blocks[block.index - 1] = block
22
- }
23
-
24
- const _getBlocks = (index = 0) => {
25
- worker.postMessage({ type: 'getBlock', result: blocks.slice(index - 1, blocks.length - 1) })
26
- }
27
-
28
- const _getBlock = (index) => {
29
- worker.postMessage({ type: 'getBlock', result: blocks[index - 1] })
30
- }
31
-
32
- const _init = (_blocks) => {
33
- blocks = _blocks
34
- try {
35
- } catch (error) {}
36
- worker.postMessage({ type: 'init', result: 'ready' })
37
- }
38
-
39
- worker.onmessage((message: message) => {
40
- if (!message.type) message.type = 'init'
41
- _[message.type](message.input)
42
- })
package/src/log-worker.ts DELETED
@@ -1,50 +0,0 @@
1
- import { BlockMessage } from '@leofcoin/messages'
2
- import { formatBytes, BigNumber } from '@leofcoin/utils'
3
-
4
- import EasyWorker from '@vandeurenglenn/easy-worker'
5
- import Storage from '@leofcoin/storage'
6
- const worker = new EasyWorker()
7
- const logStore = new Storage('log')
8
- await logStore.init()
9
-
10
- declare type messageType = 'put' | 'get'
11
-
12
- declare type message = {
13
- type: messageType
14
- input: string
15
- }
16
-
17
- declare type messageReturn = {
18
- type: messageType
19
- result?: string
20
- message?: string
21
- error?: Error
22
- }
23
-
24
- const handlePut = async (message) => {
25
- try {
26
- await fetch(`http://localhost:8844/log/put`, {
27
- method: 'put',
28
- body: message
29
- })
30
- } catch (error) {
31
- worker.postMessage({ type: 'logError', message, error })
32
- }
33
- }
34
-
35
- const handleGet = async (message) => {
36
- try {
37
- await fetch(`http://localhost:8844/log/get?`, {
38
- method: 'put',
39
- body: message
40
- })
41
- } catch (error) {
42
- worker.postMessage({ type: 'logError', message, error })
43
- }
44
- }
45
-
46
- worker.onmessage((message: message) => {
47
- if (!message.type) message.type = 'put'
48
- if (message.type === 'put') handlePut(message.input)
49
- else handleGet(message.input)
50
- })
@@ -1,418 +0,0 @@
1
- import { BlockMessage, ContractMessage, TransactionMessage } from '@leofcoin/messages'
2
- import { formatBytes, BigNumber } from '@leofcoin/utils'
3
- import addresses from '@leofcoin/addresses'
4
- import bytecodes from '@leofcoin/lib/bytecodes' assert { type: 'json' }
5
- import EasyWorker from '@vandeurenglenn/easy-worker'
6
- import { nativeToken } from '@leofcoin/addresses'
7
- import LittlePubSub from '@vandeurenglenn/little-pubsub'
8
- const pubsub = new LittlePubSub()
9
- const worker = new EasyWorker()
10
-
11
- const contractFactoryMessage = bytecodes.contractFactory
12
- const nativeTokenMessage = bytecodes.nativeToken
13
- const nameServiceMessage = bytecodes.nameService
14
- const validatorsMessage = bytecodes.validators
15
-
16
- const latestTransactions = []
17
- let nativeCalls = 0
18
- let nativeBurns = 0
19
- let nativeMints = 0
20
- let nativeTransfers = 0
21
- let totalTransactions = 0
22
-
23
- let totalBurnAmount = 0
24
- let totalMintAmount = 0
25
- let totalTransferAmount = 0
26
-
27
- let blocks = []
28
- let contracts = {}
29
- const _ = {}
30
-
31
- globalThis.BigNumber = BigNumber
32
-
33
- let lastBlock = { index: -1, hash: '0x0', previousHash: '0x0' }
34
-
35
- const debug = (message) => {
36
- worker.postMessage({
37
- type: 'debug',
38
- message
39
- })
40
- }
41
-
42
- const unique = (arr) =>
43
- arr.filter((el, pos, arr) => {
44
- return arr.indexOf(el) == pos
45
- })
46
-
47
- const has = (address) => {
48
- return contracts[address] ? true : false
49
- }
50
-
51
- const get = ({ contract, method, params }) => {
52
- let result
53
- if (params?.length > 0) {
54
- result = contracts[contract][method](...params)
55
- } else {
56
- result = contracts[contract][method]
57
- }
58
- return result
59
- }
60
-
61
- const respond = (id, value) => {
62
- worker.postMessage({
63
- type: 'response',
64
- value,
65
- id
66
- })
67
- }
68
-
69
- _.runContract = async ({ decoded, hash, encoded }, state) => {
70
- const params = decoded.constructorParameters
71
- try {
72
- const func = new Function(new TextDecoder().decode(decoded.contract))
73
- const Contract = func()
74
-
75
- if (state) params.push(state)
76
-
77
- globalThis.msg = createMessage(decoded.creator, hash)
78
- contracts[hash] = await new Contract(...params)
79
-
80
- debug(`loaded contract: ${hash} size: ${formatBytes(encoded.length)}`)
81
- } catch (e) {
82
- console.log(e)
83
- worker.postMessage({
84
- type: 'contractError',
85
- message: e.message,
86
- hash
87
- })
88
- }
89
- }
90
-
91
- _.execute = async ({ contract, method, params }) => {
92
- try {
93
- let result
94
-
95
- // don't execute the method on a proxy
96
- if (contracts[contract].fallback) {
97
- result = await contracts[contract].fallback(method, params)
98
- } else {
99
- result = await contracts[contract][method](...params)
100
- }
101
- // state.put(result)
102
- return result
103
- } catch (e) {
104
- console.log({ e })
105
- throw new Error(
106
- `error: ${e.message}
107
- contract: ${contract}
108
- method: ${method}
109
- params: ${JSON.stringify(params, null, '\t')}
110
- `
111
- )
112
- }
113
- }
114
-
115
- const createMessage = (sender = globalThis.peerid, contract) => {
116
- return {
117
- contract,
118
- sender,
119
- call: _.execute,
120
- staticCall: get
121
- }
122
- }
123
-
124
- const _executeTransaction = async (transaction) => {
125
- const hash = await new TransactionMessage(transaction).hash()
126
- if (latestTransactions.includes(hash)) {
127
- throw new Error(`double transaction found: ${hash} in block ${block.index}`)
128
- } else {
129
- latestTransactions.push(hash)
130
- const { from, to, method, params, nonce } = transaction
131
- globalThis.msg = createMessage(from)
132
-
133
- await _.execute({ contract: to, method, params })
134
- if (to === nativeToken) {
135
- nativeCalls += 1
136
- if (method === 'burn') {
137
- nativeBurns += 1
138
- totalBurnAmount += params[0]
139
- }
140
- if (method === 'mint') {
141
- nativeMints += 1
142
- totalMintAmount += params[0]
143
- }
144
- if (method === 'transfer') {
145
- nativeTransfers += 1
146
- totalTransferAmount += params[0]
147
- }
148
- }
149
- totalTransactions += 1
150
-
151
- worker.postMessage({
152
- type: 'transactionLoaded',
153
- result: {
154
- hash,
155
- from,
156
- nonce: String(nonce)
157
- }
158
- })
159
- }
160
- }
161
-
162
- const addToWantList = (hash) => {
163
- worker.postMessage({
164
- type: 'addToWantList',
165
- hash
166
- })
167
- }
168
-
169
- _.init = async (message) => {
170
- let { peerid, fromState, state, info } = message
171
- globalThis.peerid = peerid
172
- console.log({ fromState })
173
- if (fromState) {
174
- nativeCalls = info.nativeCalls
175
- nativeBurns = info.nativeBurns
176
- nativeMints = info.nativeMints
177
- nativeTransfers = info.nativeTransfers
178
- totalTransactions = info.totalTransactions
179
- totalBurnAmount = info.totalBurnAmount
180
- totalMintAmount = info.totalMintAmount
181
- totalTransferAmount = info.totalTransferAmount
182
-
183
- lastBlock = message.lastBlock
184
- const setState = async (address, state) => {
185
- const contractBytes = await resolveContract(address)
186
- if (contractBytes === address) {
187
- addToWantList(address)
188
- return
189
- }
190
- const contract = await new ContractMessage(contractBytes)
191
-
192
- await _.runContract({ hash: address, decoded: contract.decoded, encoded: contract.encoded }, state)
193
- }
194
-
195
- const entries = Object.entries(state)
196
- if (entries.length > 0) {
197
- const promises = []
198
- for (const [address, value] of entries) {
199
- promises.push(setState(address, value))
200
- }
201
- await Promise.all(promises)
202
- }
203
-
204
- const promises = []
205
- if (!contracts[addresses.contractFactory]) promises.push(setState(addresses.contractFactory))
206
- if (!contracts[addresses.nameService]) promises.push(setState(addresses.nameService))
207
- if (!contracts[addresses.validators]) promises.push(setState(addresses.validators))
208
- if (!contracts[addresses.nativeToken]) promises.push(setState(addresses.nativeToken))
209
- // contracts = await Promise.all(
210
- // contracts.map(async (contract) => {
211
- // contract = await new ContractMessage(new Uint8Array(contract.split(',')))
212
- // await _.runContract({ decoded: contract.decoded, encoded: contract.encoded, hash: await contract.hash() })
213
- // return contract
214
- // })
215
- // )
216
- await Promise.all(promises)
217
- } else {
218
- await Promise.all(
219
- [contractFactoryMessage, nativeTokenMessage, nameServiceMessage, validatorsMessage].map(async (contract) => {
220
- contract = await new ContractMessage(new Uint8Array(contract.split(',')))
221
- return _.runContract({ decoded: contract.decoded, encoded: contract.encoded, hash: await contract.hash() })
222
- })
223
- )
224
- console.log({ blocks: message.blocks })
225
- if (message.blocks?.length > 0) {
226
- // let pre
227
-
228
- // try {
229
- // const importee = await import('url')
230
- // const url = importee.default
231
- // if (url) pre = url.fileURLToPath(new URL('.', import.meta.url))
232
- // } catch {
233
- // // browser env
234
- // pre = './'
235
- // }
236
-
237
- // let _worker = await new EasyWorker(pre + '@leofcoin/workers/block-worker.js', {
238
- // serialization: 'advanced',
239
- // type: 'module'
240
- // })
241
- // blocks = await _worker.once(message.blocks)
242
- // _worker = null
243
- // blocks = unique(globalThis.blocks ? globalThis : [], blocks)
244
- // for (let i = 0; i < blocks.length; i++) {
245
-
246
- // }
247
- blocks = message.blocks
248
- for (const block of blocks) {
249
- // we only revalidate the latest 24 blocks
250
- // every 24 blocks a snapshot is taken and stored in state
251
- // this means contracts will be restored from this state
252
- // this also means devs NEED to make sure the state can be restored
253
- // on contract deploy an error will be thrown if state wasn't recoverable
254
- if (block.index >= blocks.length - 24) {
255
- const transactionCount = blocks[block.index].transactions.length
256
- latestTransactions.splice(-transactionCount, latestTransactions.length)
257
- }
258
- if (!block.loaded && !fromState) {
259
- try {
260
- const transactions = await Promise.all(
261
- block.transactions.map(async (transaction) => {
262
- const message = new TransactionMessage(await resolveTransaction(transaction)).decode()
263
- if (message === transaction) {
264
- throw new Error(`nothing found for ${transaction}`)
265
- }
266
- return message
267
- })
268
- )
269
- const priority = transactions
270
- .filter((transaction) => transaction.priority)
271
- ?.sort((a, b) => a.nonce - b.nonce)
272
- if (priority.length > 0)
273
- for (const transaction of priority) {
274
- await _executeTransaction(transaction)
275
- }
276
-
277
- await Promise.all(
278
- transactions
279
- .filter((transaction) => !transaction.priority)
280
- .map(async (transaction) => _executeTransaction(transaction))
281
- )
282
- block.loaded = true
283
- worker.postMessage({
284
- type: 'debug',
285
- message: `loaded transactions for block: ${block.hash} @${block.index}`
286
- })
287
- } catch (error) {
288
- // just tell chain it's ready so we can get this node sync
289
- // when a node connects this node will try to resolve the wantList
290
- // this should result in the node beeing sync
291
- if (error.message.includes('nothing found for')) worker.postMessage({ type: 'machine-ready', lastBlock })
292
- else console.error(error)
293
- }
294
- }
295
- }
296
- if (blocks.length > 0) {
297
- lastBlock = blocks[blocks.length - 1]
298
- }
299
- globalThis.blocks = blocks
300
- }
301
- }
302
-
303
- worker.postMessage({ type: 'machine-ready', lastBlock })
304
- }
305
-
306
- _.addLoadedBlock = (block) => {
307
- blocks[block.index - 1] = block
308
- lastBlock = blocks[blocks.length - 1]
309
- return true
310
- }
311
-
312
- _.loadBlock = (block) => {
313
- // todo validate here and deprecate addLoadedBlock
314
- }
315
-
316
- const askFor = (question, input) =>
317
- new Promise((resolve) => {
318
- const id = globalThis.crypto.randomUUID()
319
- pubsub.subscribe(id, resolve)
320
- worker.postMessage({
321
- type: 'ask',
322
- question,
323
- input,
324
- id
325
- })
326
- })
327
-
328
- const resolveContract = (hash) => askFor('contract', hash)
329
-
330
- const resolveTransaction = (hash) => askFor('transaction', hash)
331
-
332
- const runTask = async (id, taskName, input) => {
333
- try {
334
- const result = await _[taskName](input)
335
- respond(id, result)
336
- } catch (e) {
337
- worker.postMessage({
338
- type: `${taskName}Error`,
339
- message: e.message,
340
- id
341
- })
342
- }
343
- }
344
-
345
- worker.onmessage(({ id, type, input }) => {
346
- if (pubsub.hasSubscribers(id)) {
347
- pubsub.publish(id, input)
348
- return
349
- }
350
- switch (type) {
351
- case 'init':
352
- runTask(id, 'init', input)
353
- break
354
- case 'run':
355
- runTask(id, 'runContract', input)
356
- break
357
- case 'execute':
358
- runTask(id, 'execute', input)
359
- break
360
- case 'addLoadedBlock':
361
- runTask(id, 'addLoadedBlock', input)
362
- break
363
- case 'nativeCalls':
364
- respond(id, nativeCalls)
365
- break
366
- case 'contracts':
367
- respond(id, contracts)
368
- break
369
- case 'nativeMints':
370
- respond(id, nativeMints)
371
- break
372
- case 'nativeBurns':
373
- respond(id, nativeBurns)
374
- break
375
- case 'nativeTransfers':
376
- respond(id, nativeTransfers)
377
- break
378
- case 'totalBurnAmount':
379
- respond(id, totalBurnAmount)
380
- break
381
- case 'totalMintAmount':
382
- respond(id, totalMintAmount)
383
- break
384
- case 'totalTransferAmount':
385
- respond(id, totalTransferAmount)
386
- break
387
- case 'totalTransfers':
388
- respond(id, totalTransfers)
389
- break
390
- case 'totalBlocks':
391
- respond(id, blocks.length)
392
- break
393
- case 'blocks':
394
- respond(id, input ? blocks.slice(input.from, input.to) : blocks)
395
- break
396
- case 'block':
397
- respond(id, blocks[input - 1])
398
- break
399
- case 'lastBlock':
400
- respond(id, lastBlock)
401
- break
402
- case 'latestTransactions':
403
- respond(id, latestTransactions)
404
- break
405
- case 'totalTransactions':
406
- respond(id, totalTransactions)
407
- break
408
- case 'has':
409
- respond(id, has(input.address))
410
- break
411
- case 'get':
412
- respond(id, get(input))
413
- break
414
- default:
415
- console.log(`machine-worker: unsupported taskType: ${type}`)
416
- break
417
- }
418
- })
package/tsconfig.json DELETED
@@ -1,18 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "module": "NodeNext",
4
- "target": "ES2022",
5
- "outDir": "./exports",
6
- "moduleResolution": "NodeNext",
7
- "declaration": true,
8
- "emitDeclarationOnly": true,
9
- "declarationDir": "./exports",
10
- "allowSyntheticDefaultImports": true,
11
- "resolveJsonModule": true,
12
- "allowJs": true,
13
- "useDefineForClassFields": false,
14
- "types": ["node"]
15
- },
16
- "include": ["./src/**/*"],
17
- "exclude": ["node_modules"]
18
- }