@leofcoin/chain 1.3.3 → 1.3.5

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 (46) hide show
  1. package/dist/browser/workers/machine-worker.js +0 -13
  2. package/dist/chain.js +155 -133
  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 +152 -130
  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 +122 -104
  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 -26
  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/token.js +2 -2
  31. package/src/standards/voting.js +1 -0
  32. package/src/transactions/transaction.js +1 -3
  33. package/src/transactions/validator.js +1 -1
  34. package/src/typer.js +1 -1
  35. package/dist/865.browser.js +0 -10
  36. package/dist/chain.browser.js +0 -59745
  37. package/dist/contracts/nativeToken.js +0 -1
  38. package/dist/generate-account.browser.js +0 -50
  39. package/dist/messages.browser.js +0 -328
  40. package/dist/multi-wallet.browser.js +0 -15
  41. package/dist/node.browser.js +0 -9858
  42. package/dist/pako.browser.js +0 -6900
  43. package/dist/peernet-swarm.browser.js +0 -839
  44. package/dist/storage.browser.js +0 -3724
  45. package/dist/wrtc.browser.js +0 -28
  46. package/src/standards/Voting.js +0 -3
@@ -11723,11 +11723,6 @@ var __webpack_exports__ = {};
11723
11723
  // This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
11724
11724
  !function() {
11725
11725
 
11726
- // EXPORTS
11727
- __webpack_require__.d(__webpack_exports__, {
11728
- "T": function() { return /* binding */ unique; }
11729
- });
11730
-
11731
11726
  ;// CONCATENATED MODULE: ./node_modules/@vandeurenglenn/base-x/src/base-x.js
11732
11727
  // base-x encoding / decoding
11733
11728
  // Copyright (c) 2018 base-x contributors
@@ -13727,10 +13722,6 @@ globalThis.BigNumber = BigNumber;
13727
13722
  globalThis.peernet = globalThis.peernet || {};
13728
13723
  globalThis.contracts = {};
13729
13724
 
13730
- const unique = arr => arr.filter((el, pos, arr) => {
13731
- return arr.indexOf(el) == pos;
13732
- });
13733
-
13734
13725
  const get = (contract, method, params) => {
13735
13726
  let result;
13736
13727
  if (params?.length > 0) {
@@ -13916,8 +13907,4 @@ const tasks = async (e) => {
13916
13907
 
13917
13908
  worker.onmessage(data => tasks(data));
13918
13909
 
13919
-
13920
-
13921
13910
  }();
13922
- var __webpack_exports__unique = __webpack_exports__.T;
13923
- export { __webpack_exports__unique as unique };
package/dist/chain.js CHANGED
@@ -5,8 +5,8 @@ var _BN = require('bn.js');
5
5
  require('@ethersproject/bytes');
6
6
  var logger = require('@ethersproject/logger');
7
7
  require('@ethersproject/bignumber');
8
- var crypto = require('crypto');
9
- var path = require('path');
8
+ var node_crypto = require('node:crypto');
9
+ var node_path = require('node:path');
10
10
  var EasyWorker = require('@vandeurenglenn/easy-worker');
11
11
  var codecFormatInterface = require('@leofcoin/codec-format-interface');
12
12
  var MultiWallet = require('@leofcoin/multi-wallet');
@@ -78,26 +78,31 @@ class Machine {
78
78
 
79
79
  async #onmessage(data) {
80
80
  switch (data.type) {
81
- case 'contractError':
81
+ case 'contractError': {
82
82
  console.warn(`removing contract ${await data.hash}`);
83
83
  await contractStore.delete(await data.hash);
84
84
  break
85
+ }
85
86
 
86
- case 'executionError':
87
+ case 'executionError': {
87
88
  // console.warn(`error executing transaction ${data.message}`);
88
89
  pubsub.publish(data.id, {error: data.message});
89
90
  break
91
+ }
90
92
 
91
- case 'debug':
92
- data.messages.forEach(message => debug(message));
93
+ case 'debug': {
94
+ for (const message of data.messages) debug(message);
93
95
  break
94
- case 'machine-ready':
96
+ }
97
+ case 'machine-ready': {
95
98
  this.lastBlock = data.lastBlock;
96
99
  pubsub.publish('machine.ready', true);
97
100
  break
98
- case 'response':
101
+ }
102
+ case 'response': {
99
103
  pubsub.publish(data.id, data.value);
100
104
  break
105
+ }
101
106
  }
102
107
 
103
108
  }
@@ -108,7 +113,7 @@ class Machine {
108
113
  resolve(this);
109
114
  });
110
115
 
111
- this.worker = await new EasyWorker__default["default"](path.join(__dirname, './workers/machine-worker.js'), {serialization: 'advanced', type:'module'});
116
+ this.worker = await new EasyWorker__default["default"](node_path.join(__dirname, './workers/machine-worker.js'), {serialization: 'advanced', type:'module'});
112
117
  this.worker.onmessage(this.#onmessage.bind(this));
113
118
 
114
119
  // const blocks = await blockStore.values()
@@ -133,19 +138,19 @@ class Machine {
133
138
  }
134
139
 
135
140
  async #runContract(contractMessage) {
136
- const params = contractMessage.decoded.constructorParameters;
141
+ const parameters = contractMessage.decoded.constructorParameters;
137
142
  try {
138
143
 
139
- const func = new Function(contractMessage.decoded.contract);
140
- const Contract = func();
144
+ const function_ = new Function(contractMessage.decoded.contract);
145
+ const Contract = function_();
141
146
 
142
147
  globalThis.msg = this.#createMessage(contractMessage.decoded.creator);
143
148
  // globalThis.msg = {sender: contractMessage.decoded.creator}
144
- this.#contracts[await contractMessage.hash] = await new Contract(...params);
149
+ this.#contracts[await contractMessage.hash] = await new Contract(...parameters);
145
150
  debug(`loaded contract: ${await contractMessage.hash}`);
146
151
  debug(`size: ${formatBytes(contractMessage.encoded.length)}`);
147
- } catch (e) {
148
- console.log(e);
152
+ } catch (error) {
153
+ console.log(error);
149
154
  console.warn(`removing contract ${await contractMessage.hash}`);
150
155
  await contractStore.delete(await contractMessage.hash, contractMessage.encoded);
151
156
  }
@@ -154,17 +159,16 @@ class Machine {
154
159
  * @params {ContractMessage} - contractMessage
155
160
  */
156
161
  async addContract(contractMessage) {
157
- if (!await contractStore.has(contractMessage.hash)) {
158
- await contractStore.put(contractMessage.hash, contractMessage.encoded);
159
- await this.#runContract(contractMessage);
160
- return contractMessage.hash
161
- }
162
- throw new Error('duplicate contract')
162
+ if (await contractStore.has(await contractMessage.hash)) throw new Error('duplicate contract')
163
+
164
+ await contractStore.put(await contractMessage.hash, contractMessage.encoded);
165
+ await this.#runContract(contractMessage);
166
+ return contractMessage.hash
163
167
  }
164
168
 
165
- async execute(contract, method, params) {
169
+ async execute(contract, method, parameters) {
166
170
  return new Promise((resolve, reject) => {
167
- const id = crypto.randomBytes(20).toString('hex');
171
+ const id = node_crypto.randomBytes(20).toString('hex');
168
172
  const message = message => {
169
173
  if (message?.error) reject(message.error);
170
174
  else resolve(message);
@@ -176,24 +180,24 @@ class Machine {
176
180
  input: {
177
181
  contract,
178
182
  method,
179
- params
183
+ params: parameters
180
184
  }
181
185
  });
182
186
  })
183
187
 
184
188
  }
185
189
 
186
- addJob(contract, method, params, from, nonce) {
190
+ addJob(contract, method, parameters, from, nonce) {
187
191
  if (!this.#nonces[from]) this.#nonces[from] = nonce;
188
- if (nonce === this.#nonces[from] + 1) return this.#contracts[contract][method](...params)
192
+ if (nonce === this.#nonces[from] + 1) return this.#contracts[contract][method](...parameters)
189
193
  // return setTimeout(() => {
190
194
  // return this.addJob(contract, method, params, from, nonce)
191
195
  // }, 50)
192
196
  }
193
197
 
194
- get(contract, method, params) {
198
+ get(contract, method, parameters) {
195
199
  return new Promise((resolve, reject) => {
196
- const id = crypto.randomBytes(20).toString();
200
+ const id = node_crypto.randomBytes(20).toString();
197
201
  const message = message => {
198
202
  resolve(message);
199
203
  };
@@ -204,7 +208,7 @@ class Machine {
204
208
  input: {
205
209
  contract,
206
210
  method,
207
- params
211
+ params: parameters
208
212
  }
209
213
  });
210
214
  })
@@ -413,8 +417,10 @@ class Chain {
413
417
  #blocks = []
414
418
  #machine
415
419
  #runningEpoch = false
420
+ #chainSyncing = false
416
421
  #lastBlock = {index: 0, hash: '0x0', previousHash: '0x0'}
417
-
422
+ #participants = []
423
+ #participating = false
418
424
  #jail = []
419
425
 
420
426
  constructor() {
@@ -454,14 +460,14 @@ class Chain {
454
460
  console.log(validators);
455
461
  if (!validators[peernet.selectedAccount]?.active) return
456
462
 
457
- const start = new Date().getTime();
463
+ const start = Date.now();
458
464
  try {
459
465
  await this.#createBlock();
460
- } catch (e) {
461
- console.error(e);
466
+ } catch (error) {
467
+ console.error(error);
462
468
  }
463
469
 
464
- const end = new Date().getTime();
470
+ const end = Date.now();
465
471
  console.log(((end - start) / 1000) + ' s');
466
472
 
467
473
  if (await this.hasTransactionToHandle()) return this.#runEpoch()
@@ -498,7 +504,7 @@ class Chain {
498
504
  const timeout = setTimeout(() => {
499
505
  resolve([{index: 0, hash: '0x0'}]);
500
506
  debug('sync timed out');
501
- }, 10000);
507
+ }, 10_000);
502
508
 
503
509
  promises = await Promise.allSettled(promises);
504
510
  promises = promises.filter(({status}) => status === 'fulfilled');
@@ -512,11 +518,11 @@ class Chain {
512
518
 
513
519
  }
514
520
 
515
- sync() {
516
- return this.#sync()
521
+ getLatestBlock() {
522
+ return this.#getLatestBlock()
517
523
  }
518
524
 
519
- async #sync() {
525
+ async #getLatestBlock() {
520
526
  let promises = [];
521
527
 
522
528
  let data = await new peernet.protos['peernet-request']({request: 'lastBlock'});
@@ -528,26 +534,27 @@ class Chain {
528
534
  } else if (!peer.connected || peer.readyState !== 'open') ;
529
535
  }
530
536
  promises = await this.promiseRequests(promises);
531
- promises = promises.reduce((set, value) => {
532
-
533
- if (value.index > set.index) {
534
- set.index = value.index;
535
- set.hash = value.hash;
536
- }
537
- return set
538
- }, {index: 0, hash: '0x0'});
539
- // get lastblock
540
- if (promises.hash && promises.hash !== '0x0') {
541
- await peernet.get(promises.hash);
537
+ let latest = {index: 0, hash: '0x0'};
538
+
539
+ for (const value of promises) {
540
+ if (value.index > latest.index) {
541
+ latest.index = value.index;
542
+ latest.hash = value.hash;
542
543
  }
543
-
544
-
544
+ }
545
+
546
+ if (latest.hash && latest.hash !== '0x0') {
547
+ let latestBlock = await peernet.get(latest.hash, block);
548
+ latestBlock = await new BlockMessage(latestBlock);
549
+ }
550
+
551
+ return latestBlock
545
552
  }
546
553
 
547
554
  async #init() {
548
555
  // this.node = await new Node()
549
- this.participants = [];
550
- this.participating = false;
556
+ this.#participants = [];
557
+ this.#participating = false;
551
558
  const initialized = await contractStore.has(addresses.contractFactory);
552
559
  if (!initialized) await this.#setup();
553
560
 
@@ -558,7 +565,7 @@ class Chain {
558
565
  let localBlock;
559
566
  try {
560
567
  localBlock = await chainStore.get('lastBlock');
561
- } catch(e) {
568
+ } catch{
562
569
  await chainStore.put('lastBlock', '0x0');
563
570
  localBlock = await chainStore.get('lastBlock');
564
571
  }
@@ -568,13 +575,11 @@ class Chain {
568
575
  localBlock = await new BlockMessage(localBlock);
569
576
  this.#lastBlock = {...localBlock.decoded, hash: await localBlock.hash};
570
577
  } else {
571
- await this.#sync();
578
+ const latestBlock = await this.#getLatestBlock();
579
+ await this.#syncChain(latestBlock);
572
580
  }
573
- } catch (e) {
574
- console.log({e});
575
-
576
-
577
- // this.#setup()
581
+ } catch (error) {
582
+ console.log({e: error});
578
583
  }
579
584
 
580
585
  await peernet.addRequestHandler('bw-request-message', () => {
@@ -596,9 +601,6 @@ class Chain {
596
601
  // load local blocks
597
602
  await this.resolveBlocks();
598
603
  this.#machine = await new Machine(this.#blocks);
599
- // for (const block of this.#blocks) {
600
- // block.loaded = true
601
- // }
602
604
  await this.#loadBlocks(this.#blocks);
603
605
  return this
604
606
  }
@@ -610,29 +612,33 @@ class Chain {
610
612
  this.#jail.push(validatorInfo.address);
611
613
  }
612
614
 
613
- async #peerConnected(peer) {
614
- let node = await new peernet.protos['peernet-request']({request: 'lastBlock'});
615
- node = await peernet.prepareMessage(node);
616
- let response = await peer.request(node.encoded);
617
- response = await new globalThis.peernet.protos['peernet-response'](response);
618
- let lastBlock = response.decoded.response;
615
+ async #syncChain(lastBlock) {
616
+ if (this.#chainSyncing) return
619
617
 
620
618
  if (!this.lastBlock || Number(this.lastBlock.index) < Number(lastBlock.index)) {
621
- // TODO: check if valid
619
+ this.#chainSyncing = true;
620
+ // TODO: check if valid
622
621
  const localIndex = this.lastBlock ? this.lastBlock.index : 0;
623
622
  const index = lastBlock.index;
624
623
  await this.resolveBlock(lastBlock.hash);
625
- let blocksSynced = localIndex > 0 ? localIndex > index ? localIndex - index : index - localIndex : index;
624
+ let blocksSynced = localIndex > 0 ? (localIndex > index ? localIndex - index : index - localIndex) : index;
626
625
  debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`);
627
626
 
628
627
  this.#blocks.length;
629
- const start = (this.#blocks.length) - blocksSynced;
628
+ const start = this.#blocks.length - blocksSynced;
630
629
  await this.#loadBlocks(this.blocks.slice(start));
631
- this.#lastBlock = this.#blocks[this.#blocks.length - 1];
632
- const message = await new BlockMessage(this.lastBlock);
633
- await blockStore.put(await message.hash, message.encoded);
634
- await chainStore.put('lastBlock', this.lastBlock.hash);
630
+ await this.#updateState(this.#blocks[this.#blocks.length - 1]);
631
+ this.#chainSyncing = false;
635
632
  }
633
+ }
634
+
635
+ async #peerConnected(peer) {
636
+ let node = await new peernet.protos['peernet-request']({request: 'lastBlock'});
637
+ node = await peernet.prepareMessage(node);
638
+ let response = await peer.request(node.encoded);
639
+ response = await new globalThis.peernet.protos['peernet-response'](response);
640
+ let lastBlock = response.decoded.response;
641
+ this.#syncChain(lastBlock);
636
642
  }
637
643
 
638
644
  #epochTimeout
@@ -642,9 +648,9 @@ class Chain {
642
648
  transaction = await new TransactionMessage(transaction);
643
649
  const has = await transactionPoolStore.has(await transaction.hash);
644
650
  if (!has) await transactionPoolStore.put(await transaction.hash, transaction.encoded);
645
- if (this.participating && !this.#runningEpoch) this.#runEpoch();
646
- } catch (e) {
647
- throw Error('invalid transaction')
651
+ if (this.#participating && !this.#runningEpoch) this.#runEpoch();
652
+ } catch {
653
+ throw new Error('invalid transaction')
648
654
  }
649
655
  }
650
656
 
@@ -657,7 +663,7 @@ async resolveBlock(hash) {
657
663
  let block = await peernet.get(hash, 'block');
658
664
  block = await new BlockMessage(block);
659
665
  if (!await peernet.has(hash, 'block')) await peernet.put(hash, block.encoded, 'block');
660
- const size = block.encoded.length || block.encoded.byteLength;
666
+ const size = block.encoded.length > 0 ? block.encoded.length : block.encoded.byteLength;
661
667
  block = {...block.decoded, hash};
662
668
  if (this.#blocks[block.index] && this.#blocks[block.index].hash !== block.hash) throw `invalid block ${hash} @${block.index}`
663
669
  this.#blocks[block.index] = block;
@@ -676,7 +682,7 @@ async resolveBlock(hash) {
676
682
  await this.resolveBlock(hash);
677
683
  this.#lastBlock = this.#blocks[this.#blocks.length - 1];
678
684
 
679
- } catch (e) {
685
+ } catch {
680
686
  await chainStore.put('lastBlock', new TextEncoder().encode('0x0'));
681
687
  return this.resolveBlocks()
682
688
  // console.log(e);
@@ -690,8 +696,8 @@ async resolveBlock(hash) {
690
696
  try {
691
697
  await this.#machine.execute(transaction.to, transaction.method, transaction.params);
692
698
 
693
- } catch (e) {
694
- console.log(e);
699
+ } catch (error) {
700
+ console.log(error);
695
701
  }
696
702
  }
697
703
  this.#blocks[block.index].loaded = true;
@@ -723,10 +729,10 @@ async resolveBlock(hash) {
723
729
  let result = await this.#machine.execute(to, method, params, from, nonce);
724
730
  // if (!result) result = this.#machine.state
725
731
  pubsub.publish(`transaction.completed.${hash}`, {status: 'fulfilled', hash});
726
- return result ? result : 'no state change'
727
- } catch (e) {
728
- pubsub.publish(`transaction.completed.${hash}`, {status: 'fail', hash, error: e});
729
- throw e
732
+ return result || 'no state change'
733
+ } catch (error) {
734
+ pubsub.publish(`transaction.completed.${hash}`, {status: 'fail', hash, error: error});
735
+ throw error
730
736
  }
731
737
  }
732
738
 
@@ -763,11 +769,15 @@ async resolveBlock(hash) {
763
769
  // await transactionStore.put(transaction.hash, transaction.encoded)
764
770
  const index = contracts.indexOf(transaction.to);
765
771
  if (index === -1) contracts.push(transaction.to);
772
+ // Todo: go trough all accounts
766
773
  promises.push(this.#executeTransaction(transaction));
774
+
767
775
  }
768
776
  try {
769
777
  promises = await Promise.allSettled(promises);
770
778
  for (let transaction of blockMessage.decoded.transactions) {
779
+ pubsub.publish('transaction-processed', transaction);
780
+ if (transaction.to === peernet.selectedAccount) pubsub.publish('account-transaction-processed', transaction);
771
781
  await accountsStore.put(transaction.from, String(transaction.nonce));
772
782
  }
773
783
 
@@ -780,8 +790,9 @@ async resolveBlock(hash) {
780
790
 
781
791
 
782
792
  pubsub.publish('block-processed', blockMessage.decoded);
783
- } catch (e) {
784
- console.log({e});
793
+
794
+ } catch (error) {
795
+ console.log({e: error});
785
796
  }
786
797
 
787
798
  }
@@ -801,7 +812,7 @@ async resolveBlock(hash) {
801
812
  // introduce peer-reputation
802
813
  // peerReputation(peerId)
803
814
  // {bandwith: {up, down}, uptime}
804
- this.participating = true;
815
+ this.#participating = true;
805
816
  if (!await this.staticCall(addresses.validators, 'has', [address])) await this.createTransactionFrom(address, addresses.validators, 'addValidator', [address]);
806
817
  if (await this.hasTransactionToHandle() && !this.#runningEpoch) await this.#runEpoch();
807
818
 
@@ -863,7 +874,7 @@ async resolveBlock(hash) {
863
874
  block.transactions.push(transaction);
864
875
  block.fees += Number(calculateFee(transaction));
865
876
  await accountsStore.put(transaction.from, new TextEncoder().encode(String(transaction.nonce)));
866
- } catch (e) {
877
+ } catch {
867
878
  transaction = await new TransactionMessage(transaction);
868
879
  await transactionPoolStore.delete(await transaction.hash);
869
880
  }
@@ -896,9 +907,7 @@ async resolveBlock(hash) {
896
907
  address: validator,
897
908
  bw: bw.up + bw.down
898
909
  });
899
- } catch(e) {
900
-
901
- }
910
+ } catch{}
902
911
 
903
912
  } else if (peernet.selectedAccount === validator) {
904
913
  block.validators.push({
@@ -926,17 +935,17 @@ async resolveBlock(hash) {
926
935
  else block.index += 1;
927
936
 
928
937
  block.previousHash = this.lastBlock?.hash || '0x0';
929
- block.timestamp = new Date().getTime();
938
+ block.timestamp = Date.now();
930
939
 
931
940
  const parts = String(block.fees).split('.');
932
941
  let decimals = 0;
933
942
  if (parts[1]) {
934
943
  const potentional = parts[1].split('e');
935
- if (potentional[0] !== parts[1]) {
936
- parts[1] = potentional[0];
937
- decimals = Number(potentional[1]?.replace(/\-|\+/g, '')) + Number(potentional[0].length);
938
- } else {
944
+ if (potentional[0] === parts[1]) {
939
945
  decimals = parts[1].length;
946
+ } else {
947
+ parts[1] = potentional[0];
948
+ decimals = Number(potentional[1]?.replace(/[+-]/g, '')) + Number(potentional[0].length);
940
949
  }
941
950
 
942
951
  }
@@ -956,9 +965,10 @@ async resolveBlock(hash) {
956
965
  debug(`created block: ${hash}`);
957
966
 
958
967
  peernet.publish('add-block', blockMessage.encoded);
959
- } catch (e) {
960
- console.log(e);
961
- throw Error(`invalid block ${block}`)
968
+ pubsub.publish('add-block', blockMessage.decoded);
969
+ } catch (error) {
970
+ console.log(error);
971
+ throw new Error(`invalid block ${block}`)
962
972
  }
963
973
  // data = await this.#machine.execute(to, method, params)
964
974
  // transactionStore.put(message.hash, message.encoded)
@@ -1027,8 +1037,8 @@ async resolveBlock(hash) {
1027
1037
  * @param {Array} params - array of paramters to apply to the contract method
1028
1038
  * @param {Number} nonce - total transaction count [optional]
1029
1039
  */
1030
- async createTransaction(to, method, params, nonce, signature) {
1031
- return this.createTransactionFrom(peernet.selectedAccount, to, method, params, nonce)
1040
+ async createTransaction(to, method, parameters, nonce, signature) {
1041
+ return this.createTransactionFrom(peernet.selectedAccount, to, method, parameters, nonce)
1032
1042
  }
1033
1043
 
1034
1044
 
@@ -1088,8 +1098,8 @@ async #signTransaction (transaction, wallet) {
1088
1098
  } else {
1089
1099
  let nonce = await accountsStore.get(transaction.from);
1090
1100
  nonce = new TextDecoder().decode(nonce);
1091
- if (transaction.nonce < nonce) throw Error(`a transaction with a higher nonce already exists`)
1092
- if (transaction.nonce === nonce) throw Error(`a transaction with the same nonce already exists`)
1101
+ if (transaction.nonce < nonce) throw new Error(`a transaction with a higher nonce already exists`)
1102
+ if (transaction.nonce === nonce) throw new Error(`a transaction with the same nonce already exists`)
1093
1103
  }
1094
1104
  return transaction
1095
1105
  }
@@ -1104,10 +1114,10 @@ async #signTransaction (transaction, wallet) {
1104
1114
  * @param {Array} params - array of paramters to apply to the contract method
1105
1115
  * @param {Number} nonce - total transaction count [optional]
1106
1116
  */
1107
- async createTransactionFrom(from, to, method, params, nonce) {
1117
+ async createTransactionFrom(from, to, method, parameters, nonce) {
1108
1118
  try {
1109
1119
 
1110
- const rawTransaction = await this.createRawTransaction({from, to, nonce, method, params});
1120
+ const rawTransaction = await this.createRawTransaction({from, to, nonce, method, params: parameters});
1111
1121
  const transaction = await this.signTransaction(rawTransaction, from);
1112
1122
  const message = await new TransactionMessage(transaction);
1113
1123
 
@@ -1123,7 +1133,7 @@ async #signTransaction (transaction, wallet) {
1123
1133
 
1124
1134
  setTimeout(async () => {
1125
1135
  pubsub.unsubscribe(`transaction.completed.${await message.hash}`, completed);
1126
- }, 10000);
1136
+ }, 10_000);
1127
1137
  };
1128
1138
  pubsub.subscribe(`transaction.completed.${await message.hash}`, completed);
1129
1139
  }
@@ -1135,9 +1145,9 @@ async #signTransaction (transaction, wallet) {
1135
1145
  peernet.publish('add-transaction', message.encoded);
1136
1146
  this.#addTransaction(message.encoded);
1137
1147
  return {hash: await message.hash, data, fee: await calculateFee(message.decoded), wait}
1138
- } catch (e) {
1139
- console.log(e);
1140
- throw e
1148
+ } catch (error) {
1149
+ console.log(error);
1150
+ throw error
1141
1151
  }
1142
1152
 
1143
1153
  }
@@ -1152,20 +1162,19 @@ async #signTransaction (transaction, wallet) {
1152
1162
  }
1153
1163
 
1154
1164
  /**
1155
- *
1156
- * @param {String} contract - a contract string (see plugins/deployContract)
1165
+ *
1166
+ * @param {String} contract
1167
+ * @param {Array} parameters
1168
+ * @returns
1157
1169
  */
1158
- async deployContract(contract, params = []) {
1159
- globalThis.msg = {sender: peernet.selectedAccount, call: this.call};
1160
-
1161
- const hash = await this.createContractAddress(creator, contract, params);
1162
- console.log(hash);
1170
+ async deployContract(contract, parameters = []) {
1171
+ const message = await createContractMessage(peernet.selectedAccount, contract, parameters);
1163
1172
  try {
1164
- const tx = await this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'deployContract', [hash, creator, contract, constructorParameters]);
1165
- } catch (e) {
1166
- throw e
1173
+ await this.#machine.addContract(message);
1174
+ } catch (error) {
1175
+ throw error
1167
1176
  }
1168
- return this.#machine.addContract(message)
1177
+ return this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'registerContract', [await message.hash])
1169
1178
  }
1170
1179
 
1171
1180
  #createMessage(sender = peernet.selectedAccount) {
@@ -1178,33 +1187,33 @@ console.log(hash);
1178
1187
  }
1179
1188
  }
1180
1189
 
1181
- internalCall(sender, contract, method, params) {
1190
+ internalCall(sender, contract, method, parameters) {
1182
1191
  globalThis.msg = this.#createMessage(sender);
1183
1192
 
1184
- return this.#machine.execute(contract, method, params)
1193
+ return this.#machine.execute(contract, method, parameters)
1185
1194
  }
1186
1195
 
1187
- call(contract, method, params) {
1196
+ call(contract, method, parameters) {
1188
1197
  globalThis.msg = this.#createMessage();
1189
1198
 
1190
- return this.#machine.execute(contract, method, params)
1199
+ return this.#machine.execute(contract, method, parameters)
1191
1200
  }
1192
1201
 
1193
- staticCall(contract, method, params) {
1202
+ staticCall(contract, method, parameters) {
1194
1203
  globalThis.msg = this.#createMessage();
1195
- return this.#machine.get(contract, method, params)
1204
+ return this.#machine.get(contract, method, parameters)
1196
1205
  }
1197
1206
 
1198
- delegate(contract, method, params) {
1207
+ delegate(contract, method, parameters) {
1199
1208
  globalThis.msg = this.#createMessage();
1200
1209
 
1201
- return this.#machine.execute(contract, method, params)
1210
+ return this.#machine.execute(contract, method, parameters)
1202
1211
  }
1203
1212
 
1204
- staticDelegate(contract, method, params) {
1213
+ staticDelegate(contract, method, parameters) {
1205
1214
  globalThis.msg = this.#createMessage();
1206
1215
 
1207
- return this.#machine.get(contract, method, params)
1216
+ return this.#machine.get(contract, method, parameters)
1208
1217
  }
1209
1218
 
1210
1219
  mint(to, amount) {
@@ -1219,6 +1228,19 @@ console.log(hash);
1219
1228
  return this.staticCall(addresses.nativeToken, 'balances')
1220
1229
  }
1221
1230
 
1231
+ get contracts() {
1232
+ return this.staticCall(addresses.contractFactory, 'contracts')
1233
+ }
1234
+ /**
1235
+ *
1236
+ * @param {Address} address old contract address
1237
+ * @param {Address} newAddress new contract address
1238
+ * @returns
1239
+ */
1240
+ async updateImplementation(address, newAddress) {
1241
+ return this.call(addresses.contractFactory, 'updateImplementation', [address, newAddress])
1242
+ }
1243
+
1222
1244
  deleteAll() {
1223
1245
  return this.#machine.deleteAll()
1224
1246
  }
@@ -1 +1 @@
1
- class Factory{#name="ArtOnlineContractFactory";#totalContracts=0;#contracts=[];constructor(state){state&&(this.#contracts=state.contracts,this.#totalContracts=state.totalContracts)}get state(){return{totalContracts:this.#totalContracts,contracts:this.#contracts}}get name(){return this.#name}get contracts(){return[...this.#contracts]}get totalContracts(){return this.#totalContracts}isvalid(hash,creator,contract,constructorParameters=[]){const message=new ContractMessage({creator,contract,constructorParameters});return Boolean(message.hash===hash)}async deployContract(contractHash,creator,contract,constructorParameters=[]){if(contract.creator!==msg.sender)throw new Error("only a contract creator can deploy a contract");if(await contractStore.has(hash))throw new Error("duplicate contract");if(!this.isValid(contractHash,creator,contract,constructorParameters))throw new Error("invalid contract");await contractStore.put(hash,encoded),this.#totalContracts+=1,this.#contracts.push(hash)}}export{Factory as default};
1
+ class Factory{#name="ArtOnlineContractFactory";#totalContracts=0;#contracts=[];#implementations={};constructor(state){state&&(this.#contracts=state.contracts,this.#totalContracts=state.totalContracts,this.#implementations=state.implementations)}get state(){return{totalContracts:this.#totalContracts,contracts:this.#contracts,implementations:this.#implementations}}get name(){return this.#name}get contracts(){return[...this.#contracts]}get totalContracts(){return this.#totalContracts}get implementations(){return{...this.#implementations}}async registerContract(address){let isAllowed=!1;if(isAllowed=await msg.staticCall(address,"hasRole",[msg.sender,"IMPLEMENTATION_MANAGER"]),!isAllowed)throw new Error("only the implementation manager can update");if(this.#implementations[address])throw new Error("already registered");this.#totalContracts+=1,this.#implementations[address]=[],this.#implementations[address].push(address),this.#contracts.push(address)}async updateImplementation(address,newAddress){let isAllowed=!1;if(isAllowed=await msg.staticCall(address,"hasRole",[msg.sender,"IMPLEMENTATION_MANAGER"]),!isAllowed)throw new Error("only the implementation manager can update");if(!this.#implementations[address])throw new Error(`register ${address} before updating to ${newAddress}`);this.#implementations[address].push(newAddress)}getImplementations(address){return this.#implementations[address]}getImplementation(address,index){return index=index||this.#implementations[address].length-1,this.#implementations[address][index]}}export{Factory as default};
@@ -1 +1 @@
1
- class NameService{#name="ArtOnlineNameService";#owner;#price=0;#registry={};#currency;get name(){return this.#name}get registry(){return{...this.#registry}}get state(){}constructor(factoryAddress,currency,validatorAddress,price,state){state?(this.#owner=state.owner,this.#registry=state.registry,this.#currency=state.currency,this.#price=state.price):(this.#owner=msg.sender,this.#price=price,this.#registry.ArtOnlineContractFactory={owner:msg.sender,address:factoryAddress},this.#registry.ArtOnlineToken={owner:msg.sender,address:currency},this.#registry.ArtOnlineValidators={owner:msg.sender,address:validatorAddress},this.#currency=currency)}changeOwner(owner){if(msg.sender!==this.#owner)throw new Error("no owner");this.#owner=owner}changePrice(price){if(msg.sender!==this.#owner)throw new Error("no owner");this.#price=price}changeCurrency(currency){if(msg.sender!==this.#owner)throw new Error("no owner");this.#currency=currency}async purchaseName(name,address){if(await msg.call(this.#currency,"balanceOf",[msg.sender])<this.#price)throw new Error("price exceeds balance");try{await msg.call(this.#currency,"transfer",[msg.sender,this.#owner,this.#price])}catch(e){throw e}this.#registry[name]={owner:msg.sender,address}}lookup(name){return this.#registry[name]}transferOwnership(name,to){if(msg.sender!==this.#registry.owner)throw new Error("not a owner");this.#registry[name].owner=to}changeAddress(name,address){if(msg.sender!==this.#registry.owner)throw new Error("not a owner");this.#registry[name].address=address}}export{NameService as default};
1
+ class NameService{#name="ArtOnlineNameService";#owner;#price=0;#registry={};#currency;get name(){return this.#name}get registry(){return{...this.#registry}}get state(){}constructor(factoryAddress,currency,validatorAddress,price,state){state?(this.#owner=state.owner,this.#registry=state.registry,this.#currency=state.currency,this.#price=state.price):(this.#owner=msg.sender,this.#price=price,this.#registry.ArtOnlineContractFactory={owner:msg.sender,address:factoryAddress},this.#registry.ArtOnlineToken={owner:msg.sender,address:currency},this.#registry.ArtOnlineValidators={owner:msg.sender,address:validatorAddress},this.#currency=currency)}changeOwner(owner){if(msg.sender!==this.#owner)throw new Error("no owner");this.#owner=owner}changePrice(price){if(msg.sender!==this.#owner)throw new Error("no owner");this.#price=price}changeCurrency(currency){if(msg.sender!==this.#owner)throw new Error("no owner");this.#currency=currency}async purchaseName(name,address){if(await msg.call(this.#currency,"balanceOf",[msg.sender])<this.#price)throw new Error("price exceeds balance");try{await msg.call(this.#currency,"transfer",[msg.sender,this.#owner,this.#price])}catch(error){throw error}this.#registry[name]={owner:msg.sender,address}}lookup(name){return this.#registry[name]}transferOwnership(name,to){if(msg.sender!==this.#registry.owner)throw new Error("not a owner");this.#registry[name].owner=to}changeAddress(name,address){if(msg.sender!==this.#registry.owner)throw new Error("not a owner");this.#registry[name].address=address}}export{NameService as default};