@leofcoin/chain 1.5.25 → 1.5.26

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/exports/chain.js CHANGED
@@ -41,11 +41,11 @@ class Transaction extends Protocol {
41
41
  return new Promise(async (resolve, reject) => {
42
42
  let size = 0;
43
43
  const _transactions = [];
44
- await Promise.all(transactions
45
- .map(async (tx) => {
44
+ await Promise.all(transactions.map(async (tx) => {
46
45
  tx = await new TransactionMessage(tx);
47
46
  size += tx.encoded.length;
48
- if (!formatBytes(size).includes('MB') || formatBytes(size).includes('MB') && Number(formatBytes(size).split(' MB')[0]) <= 0.75)
47
+ if (!formatBytes(size).includes('MB') ||
48
+ (formatBytes(size).includes('MB') && Number(formatBytes(size).split(' MB')[0]) <= 0.75))
49
49
  _transactions.push({ ...tx.decoded, hash: await tx.hash() });
50
50
  else
51
51
  resolve(_transactions);
@@ -59,7 +59,7 @@ class Transaction extends Protocol {
59
59
  * @returns {TransactionMessage}
60
60
  */
61
61
  async promiseTransactions(transactions) {
62
- transactions = await Promise.all(transactions.map(tx => new TransactionMessage(tx.encoded || tx)));
62
+ transactions = await Promise.all(transactions.map((tx) => new TransactionMessage(tx.encoded || tx)));
63
63
  return transactions;
64
64
  }
65
65
  /**
@@ -68,7 +68,7 @@ class Transaction extends Protocol {
68
68
  * @returns {Object} {transaction.decoded, transaction.hash}
69
69
  */
70
70
  async promiseTransactionsContent(transactions) {
71
- transactions = await Promise.all(transactions.map(tx => new Promise(async (resolve, reject) => {
71
+ transactions = await Promise.all(transactions.map((tx) => new Promise(async (resolve, reject) => {
72
72
  resolve({ ...tx.decoded, hash: await tx.hash() });
73
73
  })));
74
74
  return transactions;
@@ -81,7 +81,7 @@ class Transaction extends Protocol {
81
81
  async #getNonceFallback(address) {
82
82
  let transactions = await globalThis.transactionPoolStore.values();
83
83
  transactions = await this.promiseTransactions(transactions);
84
- transactions = transactions.filter(tx => tx.decoded.from === address);
84
+ transactions = transactions.filter((tx) => tx.decoded.from === address);
85
85
  transactions = await this.promiseTransactionsContent(transactions);
86
86
  // @ts-ignore
87
87
  if (this.lastBlock?.hash && transactions.length === 0 && this.lastBlock.hash !== '0x0') {
@@ -92,11 +92,11 @@ class Transaction extends Protocol {
92
92
  // tx = await peernet.get(tx, 'transaction')
93
93
  // transactions.push(new TransactionMessage(tx))
94
94
  // }
95
- transactions = transactions.filter(tx => tx.from === address);
95
+ transactions = transactions.filter((tx) => tx.from === address);
96
96
  while (transactions.length === 0 && block.decoded.index !== 0 && block.decoded.previousHash !== '0x0') {
97
97
  block = await globalThis.blockStore.get(block.decoded.previousHash);
98
98
  block = await new BlockMessage(block);
99
- transactions = block.decoded.transactions.filter(tx => tx.from === address);
99
+ transactions = block.decoded.transactions.filter((tx) => tx.from === address);
100
100
  }
101
101
  }
102
102
  if (transactions.length === 0)
@@ -110,7 +110,7 @@ class Transaction extends Protocol {
110
110
  * @returns {Number} nonce
111
111
  */
112
112
  async getNonce(address) {
113
- if (!await globalThis.accountsStore.has(address)) {
113
+ if (!(await globalThis.accountsStore.has(address))) {
114
114
  const nonce = await this.#getNonceFallback(address);
115
115
  await globalThis.accountsStore.put(address, new TextEncoder().encode(String(nonce)));
116
116
  }
@@ -119,7 +119,7 @@ class Transaction extends Protocol {
119
119
  nonce = new TextDecoder().decode(nonce);
120
120
  let transactions = await globalThis.transactionPoolStore.values();
121
121
  transactions = await this.promiseTransactions(transactions);
122
- transactions = transactions.filter(tx => tx.decoded.from === address);
122
+ transactions = transactions.filter((tx) => tx.decoded.from === address);
123
123
  transactions = await this.promiseTransactionsContent(transactions);
124
124
  for (const transaction of transactions) {
125
125
  if (transaction.nonce > nonce)
@@ -136,7 +136,7 @@ class Transaction extends Protocol {
136
136
  throw new Error(`a transaction with the same nonce already exists`);
137
137
  let transactions = await globalThis.transactionPoolStore.values();
138
138
  transactions = await this.promiseTransactions(transactions);
139
- transactions = transactions.filter(tx => tx.decoded.from === address);
139
+ transactions = transactions.filter((tx) => tx.decoded.from === address);
140
140
  for (const transaction of transactions) {
141
141
  if (transaction.decoded.nonce > nonce)
142
142
  throw new Error(`a transaction with a higher nonce already exists`);
@@ -215,8 +215,7 @@ class Contract extends Transaction {
215
215
  constructor() {
216
216
  super();
217
217
  }
218
- async init() {
219
- }
218
+ async init() { }
220
219
  /**
221
220
  *
222
221
  * @param {Address} creator
@@ -335,7 +334,10 @@ class Machine {
335
334
  // browser env
336
335
  pre = './';
337
336
  }
338
- this.worker = await new EasyWorker(pre + 'workers/machine-worker.js', { serialization: 'advanced', type: 'module' });
337
+ this.worker = await new EasyWorker(pre + 'workers/machine-worker.js', {
338
+ serialization: 'advanced',
339
+ type: 'module'
340
+ });
339
341
  this.worker.onmessage(this.#onmessage.bind(this));
340
342
  // const blocks = await blockStore.values()
341
343
  const contracts = await Promise.all([
@@ -361,7 +363,7 @@ class Machine {
361
363
  return new Promise((resolve, reject) => {
362
364
  // @ts-ignore
363
365
  const id = randombytes(20).toString('hex');
364
- const onmessage = message => {
366
+ const onmessage = (message) => {
365
367
  pubsub.unsubscribe(id, onmessage);
366
368
  if (message?.error)
367
369
  reject(message.error);
@@ -393,7 +395,7 @@ class Machine {
393
395
  if (await this.has(parameters[0]))
394
396
  throw new Error(`duplicate contract @${parameters[0]}`);
395
397
  let message;
396
- if (!await globalThis.contractStore.has(parameters[0])) {
398
+ if (!(await globalThis.contractStore.has(parameters[0]))) {
397
399
  message = await peernet.get(parameters[0], 'contract');
398
400
  message = await new ContractMessage(message);
399
401
  await globalThis.contractStore.put(await message.hash(), message.encoded);
@@ -402,7 +404,7 @@ class Machine {
402
404
  message = await globalThis.contractStore.get(parameters[0]);
403
405
  message = await new ContractMessage(message);
404
406
  }
405
- if (!await this.has(await message.hash()))
407
+ if (!(await this.has(await message.hash())))
406
408
  await this.#runContract(message);
407
409
  }
408
410
  }
@@ -412,7 +414,7 @@ class Machine {
412
414
  return new Promise((resolve, reject) => {
413
415
  // @ts-ignore
414
416
  const id = randombytes(20).toString('hex');
415
- const onmessage = message => {
417
+ const onmessage = (message) => {
416
418
  pubsub.unsubscribe(id, onmessage);
417
419
  if (message?.error)
418
420
  reject(new ExecutionError(message.error));
@@ -434,7 +436,7 @@ class Machine {
434
436
  get(contract, method, parameters) {
435
437
  return new Promise((resolve, reject) => {
436
438
  const id = randombytes(20).toString();
437
- const onmessage = message => {
439
+ const onmessage = (message) => {
438
440
  pubsub.unsubscribe(id, onmessage);
439
441
  resolve(message);
440
442
  };
@@ -454,7 +456,7 @@ class Machine {
454
456
  return new Promise((resolve, reject) => {
455
457
  // @ts-ignore
456
458
  const id = randombytes(20).toString('hex');
457
- const onmessage = message => {
459
+ const onmessage = (message) => {
458
460
  pubsub.unsubscribe(id, onmessage);
459
461
  if (message?.error)
460
462
  reject(message.error);
@@ -480,7 +482,7 @@ class Machine {
480
482
  */
481
483
  async deleteAll() {
482
484
  let hashes = await globalThis.contractStore.keys();
483
- hashes = Object.keys(hashes).map(hash => this.delete(hash));
485
+ hashes = Object.keys(hashes).map((hash) => this.delete(hash));
484
486
  return Promise.all(hashes);
485
487
  }
486
488
  }
@@ -635,20 +637,27 @@ class State extends Contract {
635
637
  */
636
638
  this.#totalTransactions = 0;
637
639
  this.#chainStateHandler = () => {
638
- return new globalThis.peernet.protos['peernet-response']({ response: this.#chainState });
640
+ return new globalThis.peernet.protos['peernet-response']({
641
+ response: this.#chainState
642
+ });
639
643
  };
640
644
  this.#lastBlockHandler = async () => {
641
- return new globalThis.peernet.protos['peernet-response']({ response: { hash: this.#lastBlock?.hash, index: this.#lastBlock?.index } });
645
+ return new globalThis.peernet.protos['peernet-response']({
646
+ response: { hash: this.#lastBlock?.hash, index: this.#lastBlock?.index }
647
+ });
642
648
  };
643
649
  this.#knownBlocksHandler = async () => {
644
- return new globalThis.peernet.protos['peernet-response']({ response: { blocks: this.#blocks.map((block) => block.hash) } });
650
+ return new globalThis.peernet.protos['peernet-response']({
651
+ response: { blocks: this.#blocks.map((block) => block.hash) }
652
+ });
645
653
  };
646
654
  this.#loadBlockTransactions = (transactions) => Promise.all(transactions.map((transaction) => new TransactionMessage(transaction)));
647
655
  this.#getLastTransactions = async () => {
648
- let lastTransactions = (await Promise.all(this.#blocks.filter(block => block.loaded).slice(-128)
649
- .map(block => this.#loadBlockTransactions(block.transactions))))
650
- .reduce((all, transactions) => [...all, ...transactions], []);
651
- return Promise.all(lastTransactions.map(transaction => transaction.hash()));
656
+ let lastTransactions = (await Promise.all(this.#blocks
657
+ .filter((block) => block.loaded)
658
+ .slice(-128)
659
+ .map((block) => this.#loadBlockTransactions(block.transactions)))).reduce((all, transactions) => [...all, ...transactions], []);
660
+ return Promise.all(lastTransactions.map((transaction) => transaction.hash()));
652
661
  };
653
662
  }
654
663
  async clearPool() {
@@ -686,7 +695,10 @@ class State extends Contract {
686
695
  if (localBlock && localBlock !== '0x0') {
687
696
  localBlock = await globalThis.peernet.get(localBlock, 'block');
688
697
  localBlock = await new BlockMessage(localBlock);
689
- this.#lastBlock = { ...localBlock.decoded, hash: await localBlock.hash() };
698
+ this.#lastBlock = {
699
+ ...localBlock.decoded,
700
+ hash: await localBlock.hash()
701
+ };
690
702
  }
691
703
  else {
692
704
  if (globalThis.peernet?.connections.length > 0) {
@@ -739,7 +751,7 @@ class State extends Contract {
739
751
  const { index } = block.decoded;
740
752
  if (this.#blocks[index - 1] && this.#blocks[index - 1].hash !== block.hash)
741
753
  throw `invalid block ${hash} @${index}`;
742
- if (!await globalThis.peernet.has(hash))
754
+ if (!(await globalThis.peernet.has(hash)))
743
755
  await globalThis.peernet.put(hash, block.encoded, 'block');
744
756
  }
745
757
  return block;
@@ -841,8 +853,7 @@ class State extends Contract {
841
853
  // console.log(e);
842
854
  }
843
855
  }
844
- destroyResolveJob() {
845
- }
856
+ destroyResolveJob() { }
846
857
  async syncChain(lastBlock) {
847
858
  if (!this.shouldSync)
848
859
  return;
@@ -901,7 +912,7 @@ class State extends Contract {
901
912
  console.log('ok');
902
913
  let blocksSynced = localIndex > 0 ? (localIndex > index ? localIndex - index : index + -localIndex) : index;
903
914
  globalThis.debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`);
904
- const start = (this.#blocks.length - blocksSynced);
915
+ const start = this.#blocks.length - blocksSynced;
905
916
  if (this.#machine)
906
917
  await this.#loadBlocks(this.blocks.slice(start));
907
918
  await this.updateState(new BlockMessage(this.#blocks[this.#blocks.length - 1]));
@@ -914,7 +925,9 @@ class State extends Contract {
914
925
  }
915
926
  async #getLatestBlock() {
916
927
  let promises = [];
917
- let data = await new globalThis.peernet.protos['peernet-request']({ request: 'lastBlock' });
928
+ let data = await new globalThis.peernet.protos['peernet-request']({
929
+ request: 'lastBlock'
930
+ });
918
931
  let node = await globalThis.peernet.prepareMessage(data);
919
932
  for (const peer of globalThis.peernet?.connections) {
920
933
  // @ts-ignore
@@ -946,7 +959,9 @@ class State extends Contract {
946
959
  latest = { ...message.decoded, hash };
947
960
  const peer = promises[0].peer;
948
961
  if (peer.connected && peer.version === this.version) {
949
- let data = await new globalThis.peernet.protos['peernet-request']({ request: 'knownBlocks' });
962
+ let data = await new globalThis.peernet.protos['peernet-request']({
963
+ request: 'knownBlocks'
964
+ });
950
965
  let node = await globalThis.peernet.prepareMessage(data);
951
966
  let message = await peer.request(node);
952
967
  message = await new globalThis.peernet.protos['peernet-response'](message);
@@ -1051,7 +1066,7 @@ class State extends Contract {
1051
1066
  if (this.#resolveErrored ||
1052
1067
  this.#syncState === 'errored' ||
1053
1068
  this.#syncState === 'connectionless' ||
1054
- !this.canSync && this.#lastResolvedTime + this.resolveTimeout > Date.now())
1069
+ (!this.canSync && this.#lastResolvedTime + this.resolveTimeout > Date.now()))
1055
1070
  return true;
1056
1071
  return false;
1057
1072
  }
@@ -1071,7 +1086,7 @@ class VersionControl extends State {
1071
1086
  super();
1072
1087
  }
1073
1088
  async init() {
1074
- super.init && await super.init();
1089
+ super.init && (await super.init());
1075
1090
  console.log('init');
1076
1091
  try {
1077
1092
  const version = await globalThis.chainStore.get('version');
@@ -1153,29 +1168,34 @@ class Chain extends VersionControl {
1153
1168
  console.error(error);
1154
1169
  }
1155
1170
  const end = Date.now();
1156
- console.log(((end - start) / 1000) + ' s');
1171
+ console.log((end - start) / 1000 + ' s');
1157
1172
  if (await this.hasTransactionToHandle())
1158
1173
  return this.#runEpoch();
1159
1174
  this.#runningEpoch = false;
1160
1175
  // if (await this.hasTransactionToHandle() && !this.#runningEpoch) return this.#runEpoch()
1161
1176
  }
1162
1177
  async #setup() {
1163
- const contracts = [{
1178
+ const contracts = [
1179
+ {
1164
1180
  address: addresses.contractFactory,
1165
1181
  message: contractFactoryMessage
1166
- }, {
1182
+ },
1183
+ {
1167
1184
  address: addresses.nativeToken,
1168
1185
  message: nativeTokenMessage
1169
- }, {
1186
+ },
1187
+ {
1170
1188
  address: addresses.validators,
1171
1189
  message: validatorsMessage
1172
- }, {
1190
+ },
1191
+ {
1173
1192
  address: addresses.nameService,
1174
1193
  message: nameServiceMessage
1175
- }];
1194
+ }
1195
+ ];
1176
1196
  await Promise.all(contracts.map(async ({ address, message }) => {
1177
1197
  // @ts-ignore
1178
- message = await new ContractMessage(Uint8Array.from(message.split(',').map(string => Number(string))));
1198
+ message = await new ContractMessage(Uint8Array.from(message.split(',').map((string) => Number(string))));
1179
1199
  // @ts-ignore
1180
1200
  await globalThis.contractStore.put(address, message.encoded);
1181
1201
  }));
@@ -1197,7 +1217,7 @@ class Chain extends VersionControl {
1197
1217
  return new BWMessage(globalThis.peernet.client.bw) || { up: 0, down: 0 };
1198
1218
  });
1199
1219
  // await globalThis.peernet.addRequestHandler('peerId', () => {
1200
- // let node =
1220
+ // let node =
1201
1221
  // globalThis.peernet.protos['peernet-response']({response: node.encoded})
1202
1222
  // })
1203
1223
  await globalThis.peernet.addRequestHandler('transactionPool', this.#transactionPoolHandler.bind(this));
@@ -1253,7 +1273,7 @@ class Chain extends VersionControl {
1253
1273
  return;
1254
1274
  const lastBlock = await this.#makeRequest(peer, 'lastBlock');
1255
1275
  const higherThenCurrentLocal = lastBlock.index > this.lastBlock?.index;
1256
- const peerTransactionPool = higherThenCurrentLocal && await this.getPeerTransactionPool(peer) || [];
1276
+ const peerTransactionPool = (higherThenCurrentLocal && (await this.getPeerTransactionPool(peer))) || [];
1257
1277
  if (Object.keys(lastBlock).length > 0) {
1258
1278
  if (!this.lastBlock || higherThenCurrentLocal) {
1259
1279
  this.knownBlocks = await this.#makeRequest(peer, 'knownBlocks');
@@ -1342,7 +1362,7 @@ class Chain extends VersionControl {
1342
1362
  // peerReputation(peerId)
1343
1363
  // {bandwith: {up, down}, uptime}
1344
1364
  this.#participating = true;
1345
- if (!await this.staticCall(addresses.validators, 'has', [address])) {
1365
+ if (!(await this.staticCall(addresses.validators, 'has', [address]))) {
1346
1366
  const rawTransaction = {
1347
1367
  from: address,
1348
1368
  to: addresses.validators,
@@ -1354,13 +1374,13 @@ class Chain extends VersionControl {
1354
1374
  const transaction = await signTransaction(rawTransaction, globalThis.peernet.identity);
1355
1375
  await this.sendTransaction(transaction);
1356
1376
  }
1357
- if (await this.hasTransactionToHandle() && !this.#runningEpoch && this.#participating)
1377
+ if ((await this.hasTransactionToHandle()) && !this.#runningEpoch && this.#participating)
1358
1378
  await this.#runEpoch();
1359
1379
  }
1360
1380
  // todo filter tx that need to wait on prev nonce
1361
1381
  async #createBlock(limit = this.transactionLimit) {
1362
1382
  // vote for transactions
1363
- if (await globalThis.transactionPoolStore.size() === 0)
1383
+ if ((await globalThis.transactionPoolStore.size()) === 0)
1364
1384
  return;
1365
1385
  let transactions = await globalThis.transactionPoolStore.values(this.transactionLimit);
1366
1386
  for (const hash of await globalThis.transactionPoolStore.keys()) {
@@ -1453,7 +1473,7 @@ class Chain extends VersionControl {
1453
1473
  }
1454
1474
  }
1455
1475
  }
1456
- block.validators = block.validators.map(validator => {
1476
+ block.validators = block.validators.map((validator) => {
1457
1477
  validator.reward = block.fees;
1458
1478
  validator.reward = validator.reward.add(block.reward);
1459
1479
  validator.reward = validator.reward.div(block.validators.length);
@@ -1471,8 +1491,7 @@ class Chain extends VersionControl {
1471
1491
  // block.reward = block.reward.toString()
1472
1492
  // block.fees = block.fees.toString()
1473
1493
  try {
1474
- block.transactions = await Promise.all(block.transactions
1475
- .map(async (transaction) => {
1494
+ block.transactions = await Promise.all(block.transactions.map(async (transaction) => {
1476
1495
  await globalThis.transactionPoolStore.delete(await transaction.hash());
1477
1496
  return transaction.decoded;
1478
1497
  }));
@@ -1,4 +1,4 @@
1
- import Transaction from "./transaction.js";
1
+ import Transaction from './transaction.js';
2
2
  import type MultiWallet from '@leofcoin/multi-wallet';
3
3
  /**
4
4
  * @extends {Transaction}
package/exports/node.js CHANGED
@@ -16,7 +16,9 @@ class Node {
16
16
  stars: networks.leofcoin.peach.stars,
17
17
  autoStart: false
18
18
  }, password) {
19
- this.#node = globalThis.Peernet ? await new globalThis.Peernet(config, password) : await new Peernet(config, password);
19
+ this.#node = globalThis.Peernet
20
+ ? await new globalThis.Peernet(config, password)
21
+ : await new Peernet(config, password);
20
22
  await nodeConfig(config);
21
23
  globalThis.pubsub.subscribe('chain:ready', async () => {
22
24
  // when autostart is false the node will only be started after the chain is ready (this is here so we can just use node for communication)
@@ -1,5 +1,5 @@
1
- import Protocol from "./protocol.js";
2
- import { TransactionMessage } from "@leofcoin/messages";
1
+ import Protocol from './protocol.js';
2
+ import { TransactionMessage } from '@leofcoin/messages';
3
3
  export default class Transaction extends Protocol {
4
4
  #private;
5
5
  constructor();
@@ -1,4 +1,4 @@
1
- import State from "./state.js";
1
+ import State from './state.js';
2
2
  export declare class VersionControl extends State {
3
3
  constructor();
4
4
  init(): Promise<void>;
@@ -1,29 +1,33 @@
1
- import { E as EasyWorker, B as BigNumber, a as BlockMessage, f as formatBytes } from './worker-0f66935f.js';
1
+ import { E as EasyWorker, B as BigNumber, a as BlockMessage, f as formatBytes } from './worker-5b02efbe.js';
2
2
 
3
- const worker = new EasyWorker();
4
-
5
- globalThis.BigNumber = BigNumber;
6
- globalThis.contracts = {};
7
-
8
- const run = async (blocks) => {
9
- blocks = await Promise.all(blocks.map(block => new BlockMessage(block)));
10
- blocks = blocks.sort((a, b) => a.decoded.timestamp - b.decoded.timestamp);
11
-
12
- blocks = await Promise.all(blocks.map(block => new Promise(async (resolve, reject) => {
13
- // todo: tx worker or nah?
14
- await block.encode();
15
- const size = block.encoded.length || block.encoded.byteLength;
16
- console.log(`loaded block: ${await block.hash()} @${block.decoded.index} ${formatBytes(size)}`);
17
- // todo we don't want this, need shared state
18
- resolve(block.decoded);
19
- })));
20
- return blocks
21
- };
22
-
23
- const tasks = async blocks => {
24
- blocks = await run(blocks);
25
- worker.postMessage(blocks);
26
- };
27
-
28
-
29
- worker.onmessage(data => tasks(data));
3
+ const worker = new EasyWorker();
4
+
5
+ globalThis.BigNumber = BigNumber;
6
+ globalThis.contracts = {};
7
+
8
+ const run = async (blocks) => {
9
+ blocks = await Promise.all(blocks.map((block) => new BlockMessage(block)));
10
+ blocks = blocks.sort((a, b) => a.decoded.timestamp - b.decoded.timestamp);
11
+
12
+ blocks = await Promise.all(
13
+ blocks.map(
14
+ (block) =>
15
+ new Promise(async (resolve, reject) => {
16
+ // todo: tx worker or nah?
17
+ await block.encode();
18
+ const size = block.encoded.length || block.encoded.byteLength;
19
+ console.log(`loaded block: ${await block.hash()} @${block.decoded.index} ${formatBytes(size)}`);
20
+ // todo we don't want this, need shared state
21
+ resolve(block.decoded);
22
+ })
23
+ )
24
+ );
25
+ return blocks
26
+ };
27
+
28
+ const tasks = async (blocks) => {
29
+ blocks = await run(blocks);
30
+ worker.postMessage(blocks);
31
+ };
32
+
33
+ worker.onmessage((data) => tasks(data));