@leofcoin/chain 1.3.3 → 1.3.4

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 (45) hide show
  1. package/dist/browser/workers/machine-worker.js +0 -13
  2. package/dist/chain.js +136 -125
  3. package/dist/contracts/factory.js +1 -1
  4. package/dist/contracts/{nameService.js → name-service.js} +1 -1
  5. package/dist/contracts/native-token.js +1 -0
  6. package/dist/contracts/validators.js +1 -1
  7. package/dist/module/chain.js +133 -122
  8. package/dist/module/workers/machine-worker.js +0 -6
  9. package/dist/standards/token.js +1 -1
  10. package/dist/workers/machine-worker.js +1 -1
  11. package/package.json +20 -2
  12. package/rollup.config.js +4 -4
  13. package/src/chain.js +103 -97
  14. package/src/contracts/factory.js +58 -15
  15. package/src/contracts/{nameService.js → name-service.js} +3 -5
  16. package/src/contracts/{nativeToken.js → native-token.js} +2 -2
  17. package/src/contracts/{powerToken.js → power-token.js} +1 -1
  18. package/src/contracts/proxies/{factoryProxy.js → factory-proxy.js} +1 -1
  19. package/src/contracts/proxies/{nameServiceProxy.js → name-service-proxy.js} +1 -1
  20. package/src/contracts/proxies/{nativeTokenProxy.js → native-token-proxy.js} +1 -1
  21. package/src/contracts/proxies/{validatorsProxy.js → validators-proxy.js} +1 -1
  22. package/src/contracts/proxies/{votingProxy.js → voting-proxy.js} +1 -1
  23. package/src/contracts/{proxyManager.js → proxy-manager.js} +1 -1
  24. package/src/contracts/validators.js +35 -25
  25. package/src/fee/config.js +1 -1
  26. package/src/machine.js +30 -25
  27. package/src/standards/{proxyManager.js → proxy-manager.js} +0 -0
  28. package/src/standards/{Proxy.js → proxy.js} +4 -8
  29. package/src/standards/roles.js +7 -5
  30. package/src/standards/voting.js +1 -0
  31. package/src/transactions/transaction.js +1 -3
  32. package/src/transactions/validator.js +1 -1
  33. package/src/typer.js +1 -1
  34. package/dist/865.browser.js +0 -10
  35. package/dist/chain.browser.js +0 -59745
  36. package/dist/contracts/nativeToken.js +0 -1
  37. package/dist/generate-account.browser.js +0 -50
  38. package/dist/messages.browser.js +0 -328
  39. package/dist/multi-wallet.browser.js +0 -15
  40. package/dist/node.browser.js +0 -9858
  41. package/dist/pako.browser.js +0 -6900
  42. package/dist/peernet-swarm.browser.js +0 -839
  43. package/dist/storage.browser.js +0 -3724
  44. package/dist/wrtc.browser.js +0 -28
  45. package/src/standards/Voting.js +0 -3
@@ -3,8 +3,8 @@ import _BN from 'bn.js';
3
3
  import '@ethersproject/bytes';
4
4
  import { Logger } from '@ethersproject/logger';
5
5
  import '@ethersproject/bignumber';
6
- import { randomBytes } from 'crypto';
7
- import { join } from 'path';
6
+ import { randomBytes } from 'node:crypto';
7
+ import { join } from 'node:path';
8
8
  import EasyWorker from '@vandeurenglenn/easy-worker';
9
9
  import { FormatInterface } from '@leofcoin/codec-format-interface';
10
10
  import MultiWallet from '@leofcoin/multi-wallet';
@@ -69,26 +69,31 @@ class Machine {
69
69
 
70
70
  async #onmessage(data) {
71
71
  switch (data.type) {
72
- case 'contractError':
72
+ case 'contractError': {
73
73
  console.warn(`removing contract ${await data.hash}`);
74
74
  await contractStore.delete(await data.hash);
75
- break
75
+ break
76
+ }
76
77
 
77
- case 'executionError':
78
+ case 'executionError': {
78
79
  // console.warn(`error executing transaction ${data.message}`);
79
80
  pubsub.publish(data.id, {error: data.message});
80
- break
81
+ break
82
+ }
81
83
 
82
- case 'debug':
83
- data.messages.forEach(message => debug(message));
84
- break
85
- case 'machine-ready':
84
+ case 'debug': {
85
+ for (const message of data.messages) debug(message);
86
+ break
87
+ }
88
+ case 'machine-ready': {
86
89
  this.lastBlock = data.lastBlock;
87
90
  pubsub.publish('machine.ready', true);
88
- break
89
- case 'response':
91
+ break
92
+ }
93
+ case 'response': {
90
94
  pubsub.publish(data.id, data.value);
91
- break
95
+ break
96
+ }
92
97
  }
93
98
 
94
99
  }
@@ -124,19 +129,19 @@ class Machine {
124
129
  }
125
130
 
126
131
  async #runContract(contractMessage) {
127
- const params = contractMessage.decoded.constructorParameters;
132
+ const parameters = contractMessage.decoded.constructorParameters;
128
133
  try {
129
134
 
130
- const func = new Function(contractMessage.decoded.contract);
131
- const Contract = func();
135
+ const function_ = new Function(contractMessage.decoded.contract);
136
+ const Contract = function_();
132
137
 
133
138
  globalThis.msg = this.#createMessage(contractMessage.decoded.creator);
134
139
  // globalThis.msg = {sender: contractMessage.decoded.creator}
135
- this.#contracts[await contractMessage.hash] = await new Contract(...params);
140
+ this.#contracts[await contractMessage.hash] = await new Contract(...parameters);
136
141
  debug(`loaded contract: ${await contractMessage.hash}`);
137
142
  debug(`size: ${formatBytes(contractMessage.encoded.length)}`);
138
- } catch (e) {
139
- console.log(e);
143
+ } catch (error) {
144
+ console.log(error);
140
145
  console.warn(`removing contract ${await contractMessage.hash}`);
141
146
  await contractStore.delete(await contractMessage.hash, contractMessage.encoded);
142
147
  }
@@ -153,7 +158,7 @@ class Machine {
153
158
  throw new Error('duplicate contract')
154
159
  }
155
160
 
156
- async execute(contract, method, params) {
161
+ async execute(contract, method, parameters) {
157
162
  return new Promise((resolve, reject) => {
158
163
  const id = randomBytes(20).toString('hex');
159
164
  const message = message => {
@@ -167,22 +172,22 @@ class Machine {
167
172
  input: {
168
173
  contract,
169
174
  method,
170
- params
175
+ params: parameters
171
176
  }
172
177
  });
173
178
  })
174
179
 
175
180
  }
176
181
 
177
- addJob(contract, method, params, from, nonce) {
182
+ addJob(contract, method, parameters, from, nonce) {
178
183
  if (!this.#nonces[from]) this.#nonces[from] = nonce;
179
- if (nonce === this.#nonces[from] + 1) return this.#contracts[contract][method](...params)
184
+ if (nonce === this.#nonces[from] + 1) return this.#contracts[contract][method](...parameters)
180
185
  // return setTimeout(() => {
181
186
  // return this.addJob(contract, method, params, from, nonce)
182
187
  // }, 50)
183
188
  }
184
189
 
185
- get(contract, method, params) {
190
+ get(contract, method, parameters) {
186
191
  return new Promise((resolve, reject) => {
187
192
  const id = randomBytes(20).toString();
188
193
  const message = message => {
@@ -195,7 +200,7 @@ class Machine {
195
200
  input: {
196
201
  contract,
197
202
  method,
198
- params
203
+ params: parameters
199
204
  }
200
205
  });
201
206
  })
@@ -404,8 +409,10 @@ class Chain {
404
409
  #blocks = []
405
410
  #machine
406
411
  #runningEpoch = false
412
+ #chainSyncing = false
407
413
  #lastBlock = {index: 0, hash: '0x0', previousHash: '0x0'}
408
-
414
+ #participants = []
415
+ #participating = false
409
416
  #jail = []
410
417
 
411
418
  constructor() {
@@ -445,14 +452,14 @@ class Chain {
445
452
  console.log(validators);
446
453
  if (!validators[peernet.selectedAccount]?.active) return
447
454
 
448
- const start = new Date().getTime();
455
+ const start = Date.now();
449
456
  try {
450
457
  await this.#createBlock();
451
- } catch (e) {
452
- console.error(e);
458
+ } catch (error) {
459
+ console.error(error);
453
460
  }
454
461
 
455
- const end = new Date().getTime();
462
+ const end = Date.now();
456
463
  console.log(((end - start) / 1000) + ' s');
457
464
 
458
465
  if (await this.hasTransactionToHandle()) return this.#runEpoch()
@@ -489,7 +496,7 @@ class Chain {
489
496
  const timeout = setTimeout(() => {
490
497
  resolve([{index: 0, hash: '0x0'}]);
491
498
  debug('sync timed out');
492
- }, 10000);
499
+ }, 10_000);
493
500
 
494
501
  promises = await Promise.allSettled(promises);
495
502
  promises = promises.filter(({status}) => status === 'fulfilled');
@@ -503,11 +510,11 @@ class Chain {
503
510
 
504
511
  }
505
512
 
506
- sync() {
507
- return this.#sync()
513
+ getLatestBlock() {
514
+ return this.#getLatestBlock()
508
515
  }
509
516
 
510
- async #sync() {
517
+ async #getLatestBlock() {
511
518
  let promises = [];
512
519
 
513
520
  let data = await new peernet.protos['peernet-request']({request: 'lastBlock'});
@@ -519,26 +526,27 @@ class Chain {
519
526
  } else if (!peer.connected || peer.readyState !== 'open') ;
520
527
  }
521
528
  promises = await this.promiseRequests(promises);
522
- promises = promises.reduce((set, value) => {
523
-
524
- if (value.index > set.index) {
525
- set.index = value.index;
526
- set.hash = value.hash;
527
- }
528
- return set
529
- }, {index: 0, hash: '0x0'});
530
- // get lastblock
531
- if (promises.hash && promises.hash !== '0x0') {
532
- await peernet.get(promises.hash);
529
+ let latest = {index: 0, hash: '0x0'};
530
+
531
+ for (const value of promises) {
532
+ if (value.index > latest.index) {
533
+ latest.index = value.index;
534
+ latest.hash = value.hash;
533
535
  }
534
-
535
-
536
+ }
537
+
538
+ if (latest.hash && latest.hash !== '0x0') {
539
+ let latestBlock = await peernet.get(latest.hash, block);
540
+ latestBlock = await new BlockMessage(latestBlock);
541
+ }
542
+
543
+ return latestBlock
536
544
  }
537
545
 
538
546
  async #init() {
539
547
  // this.node = await new Node()
540
- this.participants = [];
541
- this.participating = false;
548
+ this.#participants = [];
549
+ this.#participating = false;
542
550
  const initialized = await contractStore.has(addresses.contractFactory);
543
551
  if (!initialized) await this.#setup();
544
552
 
@@ -549,7 +557,7 @@ class Chain {
549
557
  let localBlock;
550
558
  try {
551
559
  localBlock = await chainStore.get('lastBlock');
552
- } catch(e) {
560
+ } catch{
553
561
  await chainStore.put('lastBlock', '0x0');
554
562
  localBlock = await chainStore.get('lastBlock');
555
563
  }
@@ -559,13 +567,11 @@ class Chain {
559
567
  localBlock = await new BlockMessage(localBlock);
560
568
  this.#lastBlock = {...localBlock.decoded, hash: await localBlock.hash};
561
569
  } else {
562
- await this.#sync();
570
+ const latestBlock = await this.#getLatestBlock();
571
+ await this.#syncChain(latestBlock);
563
572
  }
564
- } catch (e) {
565
- console.log({e});
566
-
567
-
568
- // this.#setup()
573
+ } catch (error) {
574
+ console.log({e: error});
569
575
  }
570
576
 
571
577
  await peernet.addRequestHandler('bw-request-message', () => {
@@ -587,9 +593,6 @@ class Chain {
587
593
  // load local blocks
588
594
  await this.resolveBlocks();
589
595
  this.#machine = await new Machine(this.#blocks);
590
- // for (const block of this.#blocks) {
591
- // block.loaded = true
592
- // }
593
596
  await this.#loadBlocks(this.#blocks);
594
597
  return this
595
598
  }
@@ -601,29 +604,33 @@ class Chain {
601
604
  this.#jail.push(validatorInfo.address);
602
605
  }
603
606
 
604
- async #peerConnected(peer) {
605
- let node = await new peernet.protos['peernet-request']({request: 'lastBlock'});
606
- node = await peernet.prepareMessage(node);
607
- let response = await peer.request(node.encoded);
608
- response = await new globalThis.peernet.protos['peernet-response'](response);
609
- let lastBlock = response.decoded.response;
607
+ async #syncChain(lastBlock) {
608
+ if (this.#chainSyncing) return
610
609
 
611
610
  if (!this.lastBlock || Number(this.lastBlock.index) < Number(lastBlock.index)) {
612
- // TODO: check if valid
611
+ this.#chainSyncing = true;
612
+ // TODO: check if valid
613
613
  const localIndex = this.lastBlock ? this.lastBlock.index : 0;
614
614
  const index = lastBlock.index;
615
615
  await this.resolveBlock(lastBlock.hash);
616
- let blocksSynced = localIndex > 0 ? localIndex > index ? localIndex - index : index - localIndex : index;
616
+ let blocksSynced = localIndex > 0 ? (localIndex > index ? localIndex - index : index - localIndex) : index;
617
617
  debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`);
618
618
 
619
619
  this.#blocks.length;
620
- const start = (this.#blocks.length) - blocksSynced;
620
+ const start = this.#blocks.length - blocksSynced;
621
621
  await this.#loadBlocks(this.blocks.slice(start));
622
- this.#lastBlock = this.#blocks[this.#blocks.length - 1];
623
- const message = await new BlockMessage(this.lastBlock);
624
- await blockStore.put(await message.hash, message.encoded);
625
- await chainStore.put('lastBlock', this.lastBlock.hash);
622
+ await this.#updateState(this.#blocks[this.#blocks.length - 1]);
623
+ this.#chainSyncing = false;
626
624
  }
625
+ }
626
+
627
+ async #peerConnected(peer) {
628
+ let node = await new peernet.protos['peernet-request']({request: 'lastBlock'});
629
+ node = await peernet.prepareMessage(node);
630
+ let response = await peer.request(node.encoded);
631
+ response = await new globalThis.peernet.protos['peernet-response'](response);
632
+ let lastBlock = response.decoded.response;
633
+ this.#syncChain(lastBlock);
627
634
  }
628
635
 
629
636
  #epochTimeout
@@ -633,9 +640,9 @@ class Chain {
633
640
  transaction = await new TransactionMessage(transaction);
634
641
  const has = await transactionPoolStore.has(await transaction.hash);
635
642
  if (!has) await transactionPoolStore.put(await transaction.hash, transaction.encoded);
636
- if (this.participating && !this.#runningEpoch) this.#runEpoch();
637
- } catch (e) {
638
- throw Error('invalid transaction')
643
+ if (this.#participating && !this.#runningEpoch) this.#runEpoch();
644
+ } catch {
645
+ throw new Error('invalid transaction')
639
646
  }
640
647
  }
641
648
 
@@ -648,7 +655,7 @@ async resolveBlock(hash) {
648
655
  let block = await peernet.get(hash, 'block');
649
656
  block = await new BlockMessage(block);
650
657
  if (!await peernet.has(hash, 'block')) await peernet.put(hash, block.encoded, 'block');
651
- const size = block.encoded.length || block.encoded.byteLength;
658
+ const size = block.encoded.length > 0 ? block.encoded.length : block.encoded.byteLength;
652
659
  block = {...block.decoded, hash};
653
660
  if (this.#blocks[block.index] && this.#blocks[block.index].hash !== block.hash) throw `invalid block ${hash} @${block.index}`
654
661
  this.#blocks[block.index] = block;
@@ -667,7 +674,7 @@ async resolveBlock(hash) {
667
674
  await this.resolveBlock(hash);
668
675
  this.#lastBlock = this.#blocks[this.#blocks.length - 1];
669
676
 
670
- } catch (e) {
677
+ } catch {
671
678
  await chainStore.put('lastBlock', new TextEncoder().encode('0x0'));
672
679
  return this.resolveBlocks()
673
680
  // console.log(e);
@@ -681,8 +688,8 @@ async resolveBlock(hash) {
681
688
  try {
682
689
  await this.#machine.execute(transaction.to, transaction.method, transaction.params);
683
690
 
684
- } catch (e) {
685
- console.log(e);
691
+ } catch (error) {
692
+ console.log(error);
686
693
  }
687
694
  }
688
695
  this.#blocks[block.index].loaded = true;
@@ -714,10 +721,10 @@ async resolveBlock(hash) {
714
721
  let result = await this.#machine.execute(to, method, params, from, nonce);
715
722
  // if (!result) result = this.#machine.state
716
723
  pubsub.publish(`transaction.completed.${hash}`, {status: 'fulfilled', hash});
717
- return result ? result : 'no state change'
718
- } catch (e) {
719
- pubsub.publish(`transaction.completed.${hash}`, {status: 'fail', hash, error: e});
720
- throw e
724
+ return result || 'no state change'
725
+ } catch (error) {
726
+ pubsub.publish(`transaction.completed.${hash}`, {status: 'fail', hash, error: error});
727
+ throw error
721
728
  }
722
729
  }
723
730
 
@@ -754,11 +761,15 @@ async resolveBlock(hash) {
754
761
  // await transactionStore.put(transaction.hash, transaction.encoded)
755
762
  const index = contracts.indexOf(transaction.to);
756
763
  if (index === -1) contracts.push(transaction.to);
764
+ // Todo: go trough all accounts
757
765
  promises.push(this.#executeTransaction(transaction));
766
+
758
767
  }
759
768
  try {
760
769
  promises = await Promise.allSettled(promises);
761
770
  for (let transaction of blockMessage.decoded.transactions) {
771
+ pubsub.publish('transaction-processed', transaction);
772
+ if (transaction.to === peernet.selectedAccount) pubsub.publish('account-transaction-processed', transaction);
762
773
  await accountsStore.put(transaction.from, String(transaction.nonce));
763
774
  }
764
775
 
@@ -771,8 +782,9 @@ async resolveBlock(hash) {
771
782
 
772
783
 
773
784
  pubsub.publish('block-processed', blockMessage.decoded);
774
- } catch (e) {
775
- console.log({e});
785
+
786
+ } catch (error) {
787
+ console.log({e: error});
776
788
  }
777
789
 
778
790
  }
@@ -792,7 +804,7 @@ async resolveBlock(hash) {
792
804
  // introduce peer-reputation
793
805
  // peerReputation(peerId)
794
806
  // {bandwith: {up, down}, uptime}
795
- this.participating = true;
807
+ this.#participating = true;
796
808
  if (!await this.staticCall(addresses.validators, 'has', [address])) await this.createTransactionFrom(address, addresses.validators, 'addValidator', [address]);
797
809
  if (await this.hasTransactionToHandle() && !this.#runningEpoch) await this.#runEpoch();
798
810
 
@@ -854,7 +866,7 @@ async resolveBlock(hash) {
854
866
  block.transactions.push(transaction);
855
867
  block.fees += Number(calculateFee(transaction));
856
868
  await accountsStore.put(transaction.from, new TextEncoder().encode(String(transaction.nonce)));
857
- } catch (e) {
869
+ } catch {
858
870
  transaction = await new TransactionMessage(transaction);
859
871
  await transactionPoolStore.delete(await transaction.hash);
860
872
  }
@@ -887,9 +899,7 @@ async resolveBlock(hash) {
887
899
  address: validator,
888
900
  bw: bw.up + bw.down
889
901
  });
890
- } catch(e) {
891
-
892
- }
902
+ } catch{}
893
903
 
894
904
  } else if (peernet.selectedAccount === validator) {
895
905
  block.validators.push({
@@ -917,17 +927,17 @@ async resolveBlock(hash) {
917
927
  else block.index += 1;
918
928
 
919
929
  block.previousHash = this.lastBlock?.hash || '0x0';
920
- block.timestamp = new Date().getTime();
930
+ block.timestamp = Date.now();
921
931
 
922
932
  const parts = String(block.fees).split('.');
923
933
  let decimals = 0;
924
934
  if (parts[1]) {
925
935
  const potentional = parts[1].split('e');
926
- if (potentional[0] !== parts[1]) {
927
- parts[1] = potentional[0];
928
- decimals = Number(potentional[1]?.replace(/\-|\+/g, '')) + Number(potentional[0].length);
929
- } else {
936
+ if (potentional[0] === parts[1]) {
930
937
  decimals = parts[1].length;
938
+ } else {
939
+ parts[1] = potentional[0];
940
+ decimals = Number(potentional[1]?.replace(/[+-]/g, '')) + Number(potentional[0].length);
931
941
  }
932
942
 
933
943
  }
@@ -947,9 +957,10 @@ async resolveBlock(hash) {
947
957
  debug(`created block: ${hash}`);
948
958
 
949
959
  peernet.publish('add-block', blockMessage.encoded);
950
- } catch (e) {
951
- console.log(e);
952
- throw Error(`invalid block ${block}`)
960
+ pubsub.publish('add-block', blockMessage.decoded);
961
+ } catch (error) {
962
+ console.log(error);
963
+ throw new Error(`invalid block ${block}`)
953
964
  }
954
965
  // data = await this.#machine.execute(to, method, params)
955
966
  // transactionStore.put(message.hash, message.encoded)
@@ -1018,8 +1029,8 @@ async resolveBlock(hash) {
1018
1029
  * @param {Array} params - array of paramters to apply to the contract method
1019
1030
  * @param {Number} nonce - total transaction count [optional]
1020
1031
  */
1021
- async createTransaction(to, method, params, nonce, signature) {
1022
- return this.createTransactionFrom(peernet.selectedAccount, to, method, params, nonce)
1032
+ async createTransaction(to, method, parameters, nonce, signature) {
1033
+ return this.createTransactionFrom(peernet.selectedAccount, to, method, parameters, nonce)
1023
1034
  }
1024
1035
 
1025
1036
 
@@ -1079,8 +1090,8 @@ async #signTransaction (transaction, wallet) {
1079
1090
  } else {
1080
1091
  let nonce = await accountsStore.get(transaction.from);
1081
1092
  nonce = new TextDecoder().decode(nonce);
1082
- if (transaction.nonce < nonce) throw Error(`a transaction with a higher nonce already exists`)
1083
- if (transaction.nonce === nonce) throw Error(`a transaction with the same nonce already exists`)
1093
+ if (transaction.nonce < nonce) throw new Error(`a transaction with a higher nonce already exists`)
1094
+ if (transaction.nonce === nonce) throw new Error(`a transaction with the same nonce already exists`)
1084
1095
  }
1085
1096
  return transaction
1086
1097
  }
@@ -1095,10 +1106,10 @@ async #signTransaction (transaction, wallet) {
1095
1106
  * @param {Array} params - array of paramters to apply to the contract method
1096
1107
  * @param {Number} nonce - total transaction count [optional]
1097
1108
  */
1098
- async createTransactionFrom(from, to, method, params, nonce) {
1109
+ async createTransactionFrom(from, to, method, parameters, nonce) {
1099
1110
  try {
1100
1111
 
1101
- const rawTransaction = await this.createRawTransaction({from, to, nonce, method, params});
1112
+ const rawTransaction = await this.createRawTransaction({from, to, nonce, method, params: parameters});
1102
1113
  const transaction = await this.signTransaction(rawTransaction, from);
1103
1114
  const message = await new TransactionMessage(transaction);
1104
1115
 
@@ -1114,7 +1125,7 @@ async #signTransaction (transaction, wallet) {
1114
1125
 
1115
1126
  setTimeout(async () => {
1116
1127
  pubsub.unsubscribe(`transaction.completed.${await message.hash}`, completed);
1117
- }, 10000);
1128
+ }, 10_000);
1118
1129
  };
1119
1130
  pubsub.subscribe(`transaction.completed.${await message.hash}`, completed);
1120
1131
  }
@@ -1126,9 +1137,9 @@ async #signTransaction (transaction, wallet) {
1126
1137
  peernet.publish('add-transaction', message.encoded);
1127
1138
  this.#addTransaction(message.encoded);
1128
1139
  return {hash: await message.hash, data, fee: await calculateFee(message.decoded), wait}
1129
- } catch (e) {
1130
- console.log(e);
1131
- throw e
1140
+ } catch (error) {
1141
+ console.log(error);
1142
+ throw error
1132
1143
  }
1133
1144
 
1134
1145
  }
@@ -1146,15 +1157,15 @@ async #signTransaction (transaction, wallet) {
1146
1157
  *
1147
1158
  * @param {String} contract - a contract string (see plugins/deployContract)
1148
1159
  */
1149
- async deployContract(contract, params = []) {
1160
+ async deployContract(contract, parameters = []) {
1150
1161
  globalThis.msg = {sender: peernet.selectedAccount, call: this.call};
1151
1162
 
1152
- const hash = await this.createContractAddress(creator, contract, params);
1163
+ const hash = await this.createContractAddress(creator, contract, parameters);
1153
1164
  console.log(hash);
1154
1165
  try {
1155
1166
  const tx = await this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'deployContract', [hash, creator, contract, constructorParameters]);
1156
- } catch (e) {
1157
- throw e
1167
+ } catch (error) {
1168
+ throw error
1158
1169
  }
1159
1170
  return this.#machine.addContract(message)
1160
1171
  }
@@ -1169,33 +1180,33 @@ console.log(hash);
1169
1180
  }
1170
1181
  }
1171
1182
 
1172
- internalCall(sender, contract, method, params) {
1183
+ internalCall(sender, contract, method, parameters) {
1173
1184
  globalThis.msg = this.#createMessage(sender);
1174
1185
 
1175
- return this.#machine.execute(contract, method, params)
1186
+ return this.#machine.execute(contract, method, parameters)
1176
1187
  }
1177
1188
 
1178
- call(contract, method, params) {
1189
+ call(contract, method, parameters) {
1179
1190
  globalThis.msg = this.#createMessage();
1180
1191
 
1181
- return this.#machine.execute(contract, method, params)
1192
+ return this.#machine.execute(contract, method, parameters)
1182
1193
  }
1183
1194
 
1184
- staticCall(contract, method, params) {
1195
+ staticCall(contract, method, parameters) {
1185
1196
  globalThis.msg = this.#createMessage();
1186
- return this.#machine.get(contract, method, params)
1197
+ return this.#machine.get(contract, method, parameters)
1187
1198
  }
1188
1199
 
1189
- delegate(contract, method, params) {
1200
+ delegate(contract, method, parameters) {
1190
1201
  globalThis.msg = this.#createMessage();
1191
1202
 
1192
- return this.#machine.execute(contract, method, params)
1203
+ return this.#machine.execute(contract, method, parameters)
1193
1204
  }
1194
1205
 
1195
- staticDelegate(contract, method, params) {
1206
+ staticDelegate(contract, method, parameters) {
1196
1207
  globalThis.msg = this.#createMessage();
1197
1208
 
1198
- return this.#machine.get(contract, method, params)
1209
+ return this.#machine.get(contract, method, parameters)
1199
1210
  }
1200
1211
 
1201
1212
  mint(to, amount) {
@@ -388,10 +388,6 @@ globalThis.BigNumber = BigNumber;
388
388
  globalThis.peernet = globalThis.peernet || {};
389
389
  globalThis.contracts = {};
390
390
 
391
- const unique = arr => arr.filter((el, pos, arr) => {
392
- return arr.indexOf(el) == pos;
393
- });
394
-
395
391
  const get = (contract, method, params) => {
396
392
  let result;
397
393
  if (params?.length > 0) {
@@ -576,5 +572,3 @@ const tasks = async (e) => {
576
572
  };
577
573
 
578
574
  worker.onmessage(data => tasks(data));
579
-
580
- export { unique };
@@ -1 +1 @@
1
- class Token extends class Roles{#roles={OWNER:[],MINT:[],BURN:[]};constructor(roles){if(roles){if(!(roles instanceof Object))throw new Error("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]&&-1!==this.#roles[role].indexOf(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)}}{#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(to,amount){if(!this.hasRole(msg.sender,"BURN"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.sub(amount),this.#decreaseBalance(to,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)}}export{Token as default};
1
+ class Roles{#roles={IMPLEMENTATION_MANAGER:[],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"),this.#grantRole(msg.sender,"IMPLEMENTATION_MANAGER")}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(to,amount){if(!this.hasRole(msg.sender,"BURN"))throw new Error("not allowed");this.#totalSupply=this.#totalSupply.sub(amount),this.#decreaseBalance(to,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)}}export{Token as default};