@leofcoin/chain 1.4.21 → 1.4.23

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 (92) hide show
  1. package/LICENSE +88 -88
  2. package/README.md +4 -4
  3. package/exports/chain.js +1071 -0
  4. package/exports/node.js +23 -0
  5. package/exports/typings/chain.d.ts +83 -0
  6. package/exports/typings/config/config.d.ts +1 -0
  7. package/exports/typings/config/main.d.ts +5 -0
  8. package/exports/typings/config/protocol.d.ts +6 -0
  9. package/exports/typings/contract.d.ts +29 -0
  10. package/exports/typings/fee/config.d.ts +4 -0
  11. package/exports/typings/machine.d.ts +26 -0
  12. package/exports/typings/node.d.ts +9 -0
  13. package/exports/typings/protocol.d.ts +4 -0
  14. package/exports/typings/state.d.ts +5 -0
  15. package/exports/typings/transaction.d.ts +47 -0
  16. package/exports/typings/typer.d.ts +6 -0
  17. package/package.json +77 -75
  18. package/CHANGELOG.md +0 -14
  19. package/block-worker.js +0 -1
  20. package/demo/865.browser.js +0 -10
  21. package/demo/chain.browser.js +0 -66842
  22. package/demo/generate-account.browser.js +0 -50
  23. package/demo/index.html +0 -25
  24. package/demo/messages.browser.js +0 -328
  25. package/demo/multi-wallet.browser.js +0 -15
  26. package/demo/node.browser.js +0 -9858
  27. package/demo/pako.browser.js +0 -6900
  28. package/demo/peernet-swarm.browser.js +0 -839
  29. package/demo/storage.browser.js +0 -3724
  30. package/demo/workers/865.js +0 -10
  31. package/demo/workers/block-worker.js +0 -13175
  32. package/demo/workers/machine-worker.js +0 -13385
  33. package/demo/workers/pool-worker.js +0 -8503
  34. package/demo/workers/transaction-worker.js +0 -8495
  35. package/demo/wrtc.browser.js +0 -28
  36. package/dist/browser/workers/865.js +0 -10
  37. package/dist/browser/workers/block-worker.js +0 -9460
  38. package/dist/browser/workers/machine-worker.js +0 -9670
  39. package/dist/browser/workers/pool-worker.js +0 -4608
  40. package/dist/browser/workers/transaction-worker.js +0 -4600
  41. package/dist/chain.js +0 -10128
  42. package/dist/client-80bc8156.js +0 -491
  43. package/dist/commonjs-7fe3c381.js +0 -270
  44. package/dist/contracts/factory.js +0 -1
  45. package/dist/contracts/name-service.js +0 -1
  46. package/dist/contracts/native-token.js +0 -1
  47. package/dist/contracts/validators.js +0 -1
  48. package/dist/generate-account-445db122.js +0 -46
  49. package/dist/index-57f93805.js +0 -718
  50. package/dist/messages-bce1b91d-81af3b00.js +0 -315
  51. package/dist/module/chain.js +0 -10091
  52. package/dist/module/client-8031ec88.js +0 -489
  53. package/dist/module/commonjs-9005d5c0.js +0 -268
  54. package/dist/module/generate-account-489552b6.js +0 -44
  55. package/dist/module/index-ac2285c4.js +0 -688
  56. package/dist/module/messages-bce1b91d-eaf75d83.js +0 -302
  57. package/dist/module/node.js +0 -7049
  58. package/dist/module/workers/block-worker.js +0 -94
  59. package/dist/module/workers/machine-worker.js +0 -304
  60. package/dist/module/workers/pool-worker.js +0 -55
  61. package/dist/module/workers/transaction-worker.js +0 -47
  62. package/dist/node.js +0 -7061
  63. package/dist/standards/token.js +0 -1
  64. package/dist/workers/machine-worker.js +0 -1
  65. package/dist/workers/pool-worker.js +0 -1
  66. package/dist/workers/transaction-worker.js +0 -1
  67. package/examples/contracts/token.js +0 -7
  68. package/plugins/bundle.js +0 -18
  69. package/rollup.config.js +0 -15
  70. package/src/chain.ts +0 -710
  71. package/src/config/config.js +0 -14
  72. package/src/config/main.js +0 -4
  73. package/src/config/protocol.js +0 -5
  74. package/src/contract.js +0 -52
  75. package/src/fee/config.js +0 -3
  76. package/src/machine.js +0 -215
  77. package/src/node.ts +0 -24
  78. package/src/protocol.js +0 -4
  79. package/src/state.js +0 -31
  80. package/src/transaction.ts +0 -182
  81. package/src/type.index.d.ts +0 -21
  82. package/src/typer.js +0 -19
  83. package/test/chain.js +0 -150
  84. package/test/contracts/token.js +0 -40
  85. package/test/create-genesis.js +0 -66
  86. package/test/index.js +0 -1
  87. package/tsconfig.json +0 -17
  88. package/workers/block-worker.js +0 -40
  89. package/workers/machine-worker.js +0 -219
  90. package/workers/pool-worker.js +0 -28
  91. package/workers/transaction-worker.js +0 -20
  92. package/workers/workers.js +0 -9
package/src/chain.ts DELETED
@@ -1,710 +0,0 @@
1
- import { BigNumber, formatUnits, parseUnits, formatBytes } from '@leofcoin/utils'
2
- import Machine from './machine.js'
3
- import { ContractMessage, TransactionMessage, BlockMessage, BWMessage, BWRequestMessage } from '@leofcoin/messages'
4
- import addresses, { nativeToken } from '@leofcoin/addresses'
5
- import { signTransaction } from '@leofcoin/lib'
6
- import { contractFactoryMessage, nativeTokenMessage, validatorsMessage, nameServiceMessage, calculateFee } from '@leofcoin/lib'
7
- import State from './state.js'
8
- import Contract from './contract.js'
9
- import { BigNumberish } from '@ethersproject/bignumber'
10
-
11
- globalThis.BigNumber = BigNumber
12
-
13
- // check if browser or local
14
- export default class Chain extends Contract {
15
- /** {Address[]} */
16
- #validators = []
17
- /** {Block[]} */
18
- #blocks = []
19
-
20
- #machine
21
- /** {Boolean} */
22
- #runningEpoch = false
23
-
24
- /** {Boolean} */
25
- #chainSyncing = false
26
-
27
- /** {Number} */
28
- #totalSize = 0
29
-
30
- /**
31
- * {Block} {index, hash, previousHash}
32
- */
33
- #lastBlock = {index: 0, hash: '0x0', previousHash: '0x0'}
34
-
35
- /**
36
- * amount the native token has been iteracted with
37
- */
38
- #nativeCalls = 0
39
-
40
- /**
41
- * amount the native token has been iteracted with
42
- */
43
- #nativeTransfers = 0
44
-
45
- /**
46
- * amount of native token burned
47
- * {Number}
48
- */
49
- #nativeBurns = 0
50
-
51
- /**
52
- * amount of native tokens minted
53
- * {Number}
54
- */
55
- #nativeMints = 0
56
-
57
- /**
58
- * total amount of transactions
59
- * {Number}
60
- */
61
- #totalTransactions = 0
62
-
63
- #participants = []
64
- #participating = false
65
- #jail = []
66
-
67
- constructor() {
68
- super()
69
- return this.#init()
70
- }
71
-
72
- get nativeMints() {
73
- return this.#nativeMints
74
- }
75
-
76
- get nativeBurns() {
77
- return this.#nativeBurns
78
- }
79
-
80
- get nativeTransfers() {
81
- return this.#nativeTransfers
82
- }
83
-
84
- get totalTransactions() {
85
- return this.#totalTransactions
86
- }
87
-
88
- get nativeCalls() {
89
- return this.#nativeCalls
90
- }
91
-
92
- get totalSize() {
93
- return this.#totalSize
94
- }
95
-
96
- get lib() {
97
- return lib
98
- }
99
-
100
- get lastBlock() {
101
- return this.#lastBlock
102
- }
103
-
104
- get nativeToken() {
105
- return addresses.nativeToken
106
- }
107
-
108
- get validators() {
109
- return [...this.#validators]
110
- }
111
-
112
- get blocks() {
113
- return [...this.#blocks]
114
- }
115
-
116
- async hasTransactionToHandle() {
117
- const size = await transactionPoolStore.size()
118
- if (size > 0) return true
119
- return false
120
- }
121
-
122
- async #runEpoch() {
123
- this.#runningEpoch = true
124
- console.log('epoch');
125
- const validators = await this.staticCall(addresses.validators, 'validators')
126
- console.log({validators});
127
- if (!validators[globalThis.peernet.selectedAccount]?.active) return
128
- const start = Date.now()
129
- try {
130
- await this.#createBlock()
131
- } catch (error) {
132
- console.error(error);
133
- }
134
-
135
- const end = Date.now()
136
- console.log(((end - start) / 1000) + ' s');
137
-
138
- if (await this.hasTransactionToHandle()) return this.#runEpoch()
139
- this.#runningEpoch = false
140
- // if (await this.hasTransactionToHandle() && !this.#runningEpoch) return this.#runEpoch()
141
- }
142
-
143
- async #setup() {
144
-
145
- const contracts = [{
146
- address: addresses.contractFactory,
147
- message: contractFactoryMessage
148
- }, {
149
- address: addresses.nativeToken,
150
- message: nativeTokenMessage
151
- }, {
152
- address: addresses.validators,
153
- message: validatorsMessage
154
- }, {
155
- address: addresses.nameService,
156
- message: nameServiceMessage
157
- }]
158
-
159
- await Promise.all(contracts.map(async ({address, message}) => {
160
- // console.log({message});
161
- message = await new ContractMessage(Uint8Array.from(message.split(',').map(string => Number(string))))
162
- await contractStore.put(address, message.encoded)
163
- }))
164
- console.log('handle native contracts');
165
- // handle native contracts
166
- }
167
-
168
- promiseRequests(promises) {
169
- return new Promise(async (resolve, reject) => {
170
- const timeout = setTimeout(() => {
171
- resolve([{index: 0, hash: '0x0'}])
172
- debug('sync timed out')
173
- }, 10_000)
174
-
175
- promises = await Promise.allSettled(promises);
176
- promises = promises.filter(({status}) => status === 'fulfilled')
177
- clearTimeout(timeout)
178
-
179
- promises = promises.map(({value}) => new peernet.protos['peernet-response'](value))
180
- promises = await Promise.all(promises)
181
- promises = promises.map(node => node.decoded.response)
182
- resolve(promises)
183
- })
184
-
185
- }
186
-
187
- getLatestBlock() {
188
- return this.#getLatestBlock()
189
- }
190
-
191
- async #getLatestBlock() {
192
- let promises = [];
193
-
194
- let data = await new peernet.protos['peernet-request']({request: 'lastBlock'});
195
- const node = await peernet.prepareMessage(data);
196
-
197
- for (const peer of peernet.connections) {
198
- if (peer.connected && peer.readyState === 'open' && peer.peerId !== this.id) {
199
- promises.push(peer.request(node.encoded));
200
- } else if (!peer.connected || peer.readyState !== 'open') {
201
- // todo: remove peer
202
- // reinitiate channel?
203
- }
204
- }
205
- promises = await this.promiseRequests(promises)
206
- let latest = {index: 0, hash: '0x0'}
207
-
208
- for (const value of promises) {
209
- if (value.index > latest.index) {
210
- latest.index = value.index;
211
- latest.hash = await value.hash();
212
- }
213
- }
214
-
215
- if (latest.hash && latest.hash !== '0x0') {
216
- latest = await peernet.get(latest.hash, block)
217
- latest = await new BlockMessage(latest)
218
- }
219
-
220
- return latest
221
- }
222
-
223
- async #init() {
224
- // this.node = await new Node()
225
- this.#participants = []
226
- this.#participating = false
227
- const initialized = await contractStore.has(addresses.contractFactory)
228
- if (!initialized) await this.#setup()
229
-
230
-
231
- this.utils = { BigNumber, formatUnits, parseUnits }
232
-
233
- this.state = new State()
234
-
235
- try {
236
- let localBlock
237
- try {
238
- localBlock = await chainStore.get('lastBlock')
239
- } catch{
240
- await chainStore.put('lastBlock', '0x0')
241
- localBlock = await chainStore.get('lastBlock')
242
- }
243
- localBlock = new TextDecoder().decode(localBlock)
244
- if (localBlock && localBlock !== '0x0') {
245
- localBlock = await peernet.get(localBlock, 'block')
246
- localBlock = await new BlockMessage(localBlock)
247
- this.#lastBlock = {...localBlock.decoded, hash: await localBlock.hash()}
248
- } else {
249
- const latestBlock = await this.#getLatestBlock()
250
- await this.#syncChain(latestBlock)
251
- }
252
- } catch (error) {
253
- console.log({e: error});
254
- }
255
-
256
- await peernet.addRequestHandler('bw-request-message', () => {
257
-
258
- return new BWMessage(peernet.client.bw) || { up: 0, down: 0 }
259
- })
260
-
261
- await peernet.addRequestHandler('lastBlock', this.#lastBlockHandler.bind(this))
262
-
263
- peernet.subscribe('add-block', this.#addBlock.bind(this))
264
-
265
- peernet.subscribe('add-transaction', this.#addTransaction.bind(this))
266
-
267
- peernet.subscribe('validator:timeout', this.#validatorTimeout.bind(this))
268
-
269
- pubsub.subscribe('peer:connected', this.#peerConnected.bind(this))
270
-
271
-
272
- // load local blocks
273
- await this.resolveBlocks()
274
- this.#machine = await new Machine(this.#blocks)
275
- await this.#loadBlocks(this.#blocks)
276
- return this
277
- }
278
-
279
- async #validatorTimeout(validatorInfo) {
280
- setTimeout(() => {
281
- this.#jail.splice(this.jail.indexOf(validatorInfo.address), 1)
282
- }, validatorInfo.timeout)
283
- this.#jail.push(validatorInfo.address)
284
- }
285
-
286
- async #syncChain(lastBlock) {
287
- if (this.#chainSyncing || !lastBlock || !lastBlock.hash || !lastBlock.hash) return
288
-
289
- if (!this.lastBlock || Number(this.lastBlock.index) < Number(lastBlock.index)) {
290
- this.#chainSyncing = true
291
- // TODO: check if valid
292
- const localIndex = this.lastBlock ? this.lastBlock.index : 0
293
- const index = lastBlock.index
294
- await this.resolveBlock(lastBlock.hash)
295
- let blocksSynced = localIndex > 0 ? (localIndex > index ? localIndex - index : index - localIndex) : index
296
- debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`)
297
-
298
- const end = this.#blocks.length
299
- const start = (this.#blocks.length - blocksSynced) - 1
300
- await this.#loadBlocks(this.blocks.slice(start))
301
- await this.#updateState(new BlockMessage(this.#blocks[this.#blocks.length - 1]))
302
- this.#chainSyncing = false
303
- }
304
- }
305
-
306
- async #peerConnected(peer) {
307
- let node = await new peernet.protos['peernet-request']({request: 'lastBlock'})
308
- node = await peernet.prepareMessage(node)
309
- let response = await peer.request(node.encoded)
310
- response = await new globalThis.peernet.protos['peernet-response'](response)
311
- let lastBlock = response.decoded.response
312
- this.#syncChain(lastBlock)
313
- }
314
-
315
- #epochTimeout
316
-
317
-
318
- async #lastBlockHandler() {
319
- return new peernet.protos['peernet-response']({response: { hash: this.#lastBlock?.hash, index: this.#lastBlock?.index }})
320
- }
321
-
322
- async resolveBlock(hash) {
323
- if (!hash) throw new Error(`expected hash, got: ${hash}`)
324
- let block = await peernet.get(hash, 'block')
325
- block = await new BlockMessage(block)
326
- if (!await peernet.has(hash, 'block')) await peernet.put(hash, block.encoded, 'block')
327
- const size = block.encoded.length > 0 ? block.encoded.length : block.encoded.byteLength
328
- this.#totalSize += size
329
- block = {...block.decoded, hash}
330
- if (this.#blocks[block.index] && this.#blocks[block.index].hash !== block.hash) throw `invalid block ${hash} @${block.index}`
331
- this.#blocks[block.index] = block
332
- console.log(`resolved block: ${hash} @${block.index} ${formatBytes(size)}`);
333
- if (block.previousHash !== '0x0') {
334
- return this.resolveBlock(block.previousHash)
335
- }
336
- }
337
-
338
- async resolveBlocks() {
339
- try {
340
- const localBlock = await chainStore.get('lastBlock')
341
- const hash = new TextDecoder().decode(localBlock)
342
-
343
- if (hash && hash !== '0x0')
344
- await this.resolveBlock(hash)
345
- this.#lastBlock = this.#blocks[this.#blocks.length - 1]
346
-
347
- } catch {
348
- await chainStore.put('lastBlock', new TextEncoder().encode('0x0'))
349
- return this.resolveBlocks()
350
- // console.log(e);
351
- }
352
- }
353
-
354
- /**
355
- *
356
- * @param {Block[]} blocks
357
- */
358
- async #loadBlocks(blocks) {
359
- for (const block of blocks) {
360
- if (block && !block.loaded) {
361
- for (const transaction of block.transactions) {
362
- try {
363
- await this.#machine.execute(transaction.to, transaction.method, transaction.params)
364
- if (transaction.to === nativeToken) {
365
- this.#nativeCalls += 1
366
- if (transaction.method === 'burn') this.#nativeBurns += 1
367
- if (transaction.method === 'mint') this.#nativeMints += 1
368
- if (transaction.method === 'transfer') this.#nativeTransfers += 1
369
- }
370
- this.#totalTransactions += 1
371
- } catch (error) {
372
- console.log(error);
373
- }
374
- }
375
- this.#blocks[block.index].loaded = true
376
- debug(`loaded block: ${block.hash} @${block.index}`);
377
- }
378
- }
379
- }
380
-
381
- async #executeTransaction({hash, from, to, method, params, nonce}) {
382
- try {
383
- let result = await this.#machine.execute(to, method, params, from, nonce)
384
- // if (!result) result = this.#machine.state
385
- pubsub.publish(`transaction.completed.${hash}`, {status: 'fulfilled', hash})
386
- return result || 'no state change'
387
- } catch (error) {
388
- console.log(error);
389
- pubsub.publish(`transaction.completed.${hash}`, {status: 'fail', hash, error: error})
390
- throw error
391
- }
392
- }
393
-
394
- async #addBlock(block) {
395
- // console.log(block);
396
- const blockMessage = await new BlockMessage(block)
397
- await Promise.all(blockMessage.decoded.transactions
398
- .map(async transaction => transactionPoolStore.delete(transaction.hash)))
399
- const hash = await blockMessage.hash()
400
-
401
- await blockStore.put(hash, blockMessage.encoded)
402
-
403
- if (this.lastBlock.index < blockMessage.decoded.index) await this.#updateState(blockMessage)
404
- debug(`added block: ${hash}`)
405
- let promises = []
406
- let contracts = []
407
- for (let transaction of blockMessage.decoded.transactions) {
408
- // await transactionStore.put(transaction.hash, transaction.encoded)
409
- const index = contracts.indexOf(transaction.to)
410
- if (index === -1) contracts.push(transaction.to)
411
- // Todo: go trough all accounts
412
- promises.push(this.#executeTransaction(transaction))
413
-
414
- }
415
- try {
416
- promises = await Promise.allSettled(promises)
417
- for (let transaction of blockMessage.decoded.transactions) {
418
- pubsub.publish('transaction-processed', transaction)
419
- if (transaction.to === peernet.selectedAccount) pubsub.publish('account-transaction-processed', transaction)
420
- await accountsStore.put(transaction.from, String(transaction.nonce))
421
- }
422
-
423
- // todo finish state
424
- // for (const contract of contracts) {
425
- // const state = await this.#machine.get(contract, 'state')
426
- // // await stateStore.put(contract, state)
427
- // console.log(state);
428
- // }
429
-
430
-
431
- pubsub.publish('block-processed', blockMessage.decoded)
432
-
433
- } catch (error) {
434
- console.log({e: error});
435
- }
436
-
437
- }
438
-
439
- async #updateState(message) {
440
- const hash = await message.hash()
441
- this.#lastBlock = { hash, ...message.decoded }
442
- await this.state.updateState(message)
443
- await chainStore.put('lastBlock', hash)
444
- }
445
-
446
-
447
-
448
- async participate(address) {
449
- // TODO: validate participant
450
- // hold min amount of 50k ART for 7 days
451
- // lock the 50k
452
- // introduce peer-reputation
453
- // peerReputation(peerId)
454
- // {bandwith: {up, down}, uptime}
455
- this.#participating = true
456
- if (!await this.staticCall(addresses.validators, 'has', [address])) {
457
- const rawTransaction = {
458
- from: address,
459
- to: addresses.validators,
460
- method: 'addValidator',
461
- params: [address],
462
- nonce: (await this.getNonce(address)) + 1,
463
- timestamp: Date.now()
464
- }
465
-
466
- const transaction = await signTransaction(rawTransaction, peernet.identity)
467
- await this.sendTransaction(transaction)
468
- }
469
- if (await this.hasTransactionToHandle() && !this.#runningEpoch) await this.#runEpoch()
470
- }
471
-
472
- // todo filter tx that need to wait on prev nonce
473
- async #createBlock(limit = 1800) {
474
- // vote for transactions
475
- if (await transactionPoolStore.size() === 0) return;
476
-
477
- let transactions = await transactionPoolStore.values(this.transactionLimit)
478
- if (Object.keys(transactions)?.length === 0 ) return
479
-
480
- let block = {
481
- transactions: [],
482
- validators: [],
483
- fees: BigNumber.from(0)
484
- }
485
-
486
- // exclude failing tx
487
- transactions = await this.promiseTransactions(transactions)
488
- transactions = transactions.sort((a, b) => a.nonce - b.nonce)
489
- for (let transaction of transactions) {
490
- const hash = await transaction.hash()
491
- try {
492
- await this.#executeTransaction({...transaction.decoded, hash})
493
- block.transactions.push({hash, ...transaction.decoded})
494
- block.fees += Number(calculateFee(transaction.decoded))
495
- await accountsStore.put(transaction.decoded.from, new TextEncoder().encode(String(transaction.decoded.nonce)))
496
- } catch (e) {
497
- await transactionPoolStore.delete(hash)
498
- }
499
- }
500
- // don't add empty block
501
- if (block.transactions.length === 0) return
502
- const validators = await this.staticCall(addresses.validators, 'validators')
503
- console.log({validators});
504
- // block.validators = Object.keys(block.validators).reduce((set, key) => {
505
- // if (block.validators[key].active) {
506
- // push({
507
- // address: key
508
- // })
509
- // }
510
- // }, [])
511
- const peers = {}
512
- for (const entry of peernet.peerEntries) {
513
- peers[entry[0]] = entry[1]
514
- }
515
- for (const validator of Object.keys(validators)) {
516
- if (validators[validator].active) {
517
- const peer = peers[validator]
518
- if (peer && peer.connected) {
519
- let data = await new BWRequestMessage()
520
- const node = await peernet.prepareMessage(validator, data.encoded)
521
- try {
522
- const bw = await peer.request(node.encoded)
523
- console.log({bw});
524
- block.validators.push({
525
- address: validator,
526
- bw: bw.up + bw.down
527
- })
528
- } catch{}
529
-
530
- } else if (peernet.selectedAccount === validator) {
531
- block.validators.push({
532
- address: peernet.selectedAccount,
533
- bw: peernet.bw.up + peernet.bw.down
534
- })
535
-
536
- }
537
- }
538
-
539
- }
540
-
541
- console.log({validators: block.validators});
542
-
543
- block.reward = 150
544
- block.validators = block.validators.map(validator => {
545
- validator.reward = String(Number(block.fees) + block.reward / block.validators.length)
546
- delete validator.bw
547
- return validator
548
- })
549
- // block.validators = calculateValidatorReward(block.validators, block.fees)
550
-
551
- block.index = this.lastBlock?.index
552
- if (block.index === undefined) block.index = 0
553
- else block.index += 1
554
-
555
- block.previousHash = this.lastBlock?.hash || '0x0'
556
- block.timestamp = Date.now()
557
-
558
- const parts = String(block.fees).split('.')
559
- let decimals = 0
560
- if (parts[1]) {
561
- const potentional = parts[1].split('e')
562
- if (potentional[0] === parts[1]) {
563
- decimals = parts[1].length
564
- } else {
565
- parts[1] = potentional[0]
566
- decimals = Number(potentional[1]?.replace(/[+-]/g, '')) + Number(potentional[0].length)
567
- }
568
-
569
- }
570
- block.fees = Number.parseFloat(String(block.fees)).toFixed(decimals)
571
-
572
- try {
573
- await Promise.all(block.transactions
574
- .map(async transaction => transactionPoolStore.delete(transaction.hash)))
575
-
576
-
577
- let blockMessage = await new BlockMessage(block)
578
- const hash = await blockMessage.hash()
579
-
580
-
581
- await peernet.put(hash, blockMessage.encoded, 'block')
582
- await this.#updateState(blockMessage)
583
- debug(`created block: ${hash}`)
584
-
585
- peernet.publish('add-block', blockMessage.encoded)
586
- pubsub.publish('add-block', blockMessage.decoded)
587
- } catch (error) {
588
- throw new Error(`invalid block ${block}`)
589
- }
590
- // data = await this.#machine.execute(to, method, params)
591
- // transactionStore.put(message.hash, message.encoded)
592
- }
593
-
594
-
595
-
596
- async #addTransaction(transaction) {
597
- try {
598
- transaction = await new TransactionMessage(transaction)
599
- const hash = await transaction.hash()
600
- const has = await transactionPoolStore.has(hash)
601
- if (!has) await transactionPoolStore.put(hash, transaction.encoded)
602
- if (this.#participating && !this.#runningEpoch) this.#runEpoch()
603
- } catch (e) {
604
- console.log(e);
605
- throw new Error('invalid transaction')
606
- }
607
- }
608
- /**
609
- * every tx done is trough contracts so no need for amount
610
- * data is undefined when nothing is returned
611
- * error is thrown on error so undefined data doesn't mean there is an error...
612
- **/
613
- async sendTransaction(transaction) {
614
- const event = await super.sendTransaction(transaction)
615
- this.#addTransaction(event.message.encoded)
616
- return event
617
- }
618
-
619
- /**
620
- *
621
- * @param {Address} sender
622
- * @returns {globalMessage}
623
- */
624
- #createMessage(sender = peernet.selectedAccount) {
625
- return {
626
- sender,
627
- call: this.call,
628
- staticCall: this.staticCall,
629
- delegate: this.delegate,
630
- staticDelegate: this.staticDelegate
631
- }
632
- }
633
-
634
- /**
635
- *
636
- * @param {Address} sender
637
- * @param {Address} contract
638
- * @param {String} method
639
- * @param {Array} parameters
640
- * @returns
641
- */
642
- internalCall(sender, contract, method, parameters) {
643
- globalThis.msg = this.#createMessage(sender)
644
-
645
- return this.#machine.execute(contract, method, parameters)
646
- }
647
-
648
- /**
649
- *
650
- * @param {Address} contract
651
- * @param {String} method
652
- * @param {Array} parameters
653
- * @returns
654
- */
655
- call(contract, method, parameters) {
656
- globalThis.msg = this.#createMessage()
657
-
658
- return this.#machine.execute(contract, method, parameters)
659
- }
660
-
661
- staticCall(contract, method, parameters?) {
662
- globalThis.msg = this.#createMessage()
663
- return this.#machine.get(contract, method, parameters)
664
- }
665
-
666
- delegate(contract, method, parameters) {
667
- globalThis.msg = this.#createMessage()
668
-
669
- return this.#machine.execute(contract, method, parameters)
670
- }
671
-
672
- staticDelegate(contract: Address, method: string, parameters: []): any {
673
- globalThis.msg = this.#createMessage()
674
-
675
- return this.#machine.get(contract, method, parameters)
676
- }
677
-
678
- mint(to: string, amount: BigNumberish) {
679
- return this.call(addresses.nativeToken, 'mint', [to, amount])
680
- }
681
-
682
- transfer(from: string, to: string, amount: BigNumberish) {
683
- return this.call(addresses.nativeToken, 'transfer', [from, to, amount])
684
- }
685
-
686
- get balances(): {address: BigNumberish} {
687
- return this.staticCall(addresses.nativeToken, 'balances')
688
- }
689
-
690
- get contracts() {
691
- return this.staticCall(addresses.contractFactory, 'contracts')
692
- }
693
-
694
- deleteAll() {
695
- return this.#machine.deleteAll()
696
- }
697
-
698
- /**
699
- * lookup an address for a registered name using the builtin nameService
700
- * @check nameService
701
- *
702
- * @param {String} - contractName
703
- * @returns {String} - address
704
- *
705
- * @example chain.lookup('myCoolContractName') // qmqsfddfdgfg...
706
- */
707
- lookup(name): {owner: string, address: string} {
708
- return this.call(addresses.nameService, 'lookup', [name])
709
- }
710
- }