@leofcoin/workers 1.5.1 → 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.1",
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,417 +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
- })
267
- )
268
- const priority = transactions
269
- .filter((transaction) => transaction.priority)
270
- ?.sort((a, b) => a.nonce - b.nonce)
271
- if (priority.length > 0)
272
- for (const transaction of priority) {
273
- await _executeTransaction(transaction)
274
- }
275
-
276
- await Promise.all(
277
- transactions
278
- .filter((transaction) => !transaction.priority)
279
- .map(async (transaction) => _executeTransaction(transaction))
280
- )
281
- block.loaded = true
282
- worker.postMessage({
283
- type: 'debug',
284
- message: `loaded transactions for block: ${block.hash} @${block.index}`
285
- })
286
- } catch (error) {
287
- // just tell chain it's ready so we can get this node sync
288
- // when a node connects this node will try to resolve the wantList
289
- // this should result in the node beeing sync
290
- if (error.message.includes('nothing found for')) worker.postMessage({ type: 'machine-ready', lastBlock })
291
- else console.error(error)
292
- }
293
- }
294
- }
295
- if (blocks.length > 0) {
296
- lastBlock = blocks[blocks.length - 1]
297
- }
298
- globalThis.blocks = blocks
299
- }
300
- }
301
-
302
- worker.postMessage({ type: 'machine-ready', lastBlock })
303
- }
304
-
305
- _.addLoadedBlock = (block) => {
306
- blocks[block.index - 1] = block
307
- lastBlock = blocks[blocks.length - 1]
308
- return true
309
- }
310
-
311
- _.loadBlock = (block) => {
312
- // todo validate here and deprecate addLoadedBlock
313
- }
314
-
315
- const askFor = (question, input) =>
316
- new Promise((resolve) => {
317
- const id = globalThis.crypto.randomUUID()
318
- pubsub.subscribe(id, resolve)
319
- worker.postMessage({
320
- type: 'ask',
321
- question,
322
- input,
323
- id
324
- })
325
- })
326
-
327
- const resolveContract = (hash) => askFor('contract', hash)
328
-
329
- const resolveTransaction = (hash) => askFor('transaction', hash)
330
-
331
- const runTask = async (id, taskName, input) => {
332
- try {
333
- const result = await _[taskName](input)
334
- respond(id, result)
335
- } catch (e) {
336
- worker.postMessage({
337
- type: `${taskName}Error`,
338
- message: e.message,
339
- id
340
- })
341
- }
342
- }
343
-
344
- worker.onmessage(({ id, type, input }) => {
345
- if (pubsub.hasSubscribers(id)) {
346
- pubsub.publish(id, input)
347
- return
348
- }
349
- switch (type) {
350
- case 'init':
351
- runTask(id, 'init', input)
352
- break
353
- case 'run':
354
- runTask(id, 'runContract', input)
355
- break
356
- case 'execute':
357
- runTask(id, 'execute', input)
358
- break
359
- case 'addLoadedBlock':
360
- runTask(id, 'addLoadedBlock', input)
361
- break
362
- case 'nativeCalls':
363
- respond(id, nativeCalls)
364
- break
365
- case 'contracts':
366
- respond(id, contracts)
367
- break
368
- case 'nativeMints':
369
- respond(id, nativeMints)
370
- break
371
- case 'nativeBurns':
372
- respond(id, nativeBurns)
373
- break
374
- case 'nativeTransfers':
375
- respond(id, nativeTransfers)
376
- break
377
- case 'totalBurnAmount':
378
- respond(id, totalBurnAmount)
379
- break
380
- case 'totalMintAmount':
381
- respond(id, totalMintAmount)
382
- break
383
- case 'totalTransferAmount':
384
- respond(id, totalTransferAmount)
385
- break
386
- case 'totalTransfers':
387
- respond(id, totalTransfers)
388
- break
389
- case 'totalBlocks':
390
- respond(id, blocks.length)
391
- break
392
- case 'blocks':
393
- respond(id, input ? blocks.slice(input.from, input.to) : blocks)
394
- break
395
- case 'block':
396
- respond(id, blocks[input - 1])
397
- break
398
- case 'lastBlock':
399
- respond(id, lastBlock)
400
- break
401
- case 'latestTransactions':
402
- respond(id, latestTransactions)
403
- break
404
- case 'totalTransactions':
405
- respond(id, totalTransactions)
406
- break
407
- case 'has':
408
- respond(id, has(input.address))
409
- break
410
- case 'get':
411
- respond(id, get(input))
412
- break
413
- default:
414
- console.log(`machine-worker: unsupported taskType: ${type}`)
415
- break
416
- }
417
- })
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
- }