@leofcoin/chain 1.4.36 → 1.4.38

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 (30) hide show
  1. package/exports/browser/chain.js +135 -4326
  2. package/exports/browser/client-de444350-a666f9b6.js +41075 -0
  3. package/exports/browser/contract-32687834.js +6071 -0
  4. package/exports/browser/{index-1ce30988-44319c80.js → index-712688fc-ad40bdec.js} +2 -2
  5. package/exports/browser/{messages-e025829d-a0354268.js → messages-3f370680-fb7e5b5b.js} +2 -2
  6. package/exports/browser/{node-browser-13cbe71a.js → node-browser-bd6a5de3.js} +4290 -187
  7. package/exports/browser/node-browser.js +2 -2
  8. package/exports/browser/workers/block-worker.js +6069 -0
  9. package/exports/browser/workers/machine-worker.js +6279 -0
  10. package/exports/chain.js +117 -96
  11. package/exports/node.js +2 -1
  12. package/exports/typings/chain.d.ts +5 -2
  13. package/exports/typings/contract.d.ts +1 -0
  14. package/exports/typings/node.d.ts +1 -0
  15. package/exports/typings/transaction.d.ts +1 -1
  16. package/package.json +4 -2
  17. package/exports/browser/browser-10ffabe1-10ffabe1.js +0 -56
  18. package/exports/browser/browser-e1cd4e67-e1cd4e67.js +0 -198
  19. package/exports/browser/client-111c93a3-b0dcdc19.js +0 -612
  20. package/exports/browser/client-1d0234a7-df40059a.js +0 -624
  21. package/exports/browser/client-21cee984-77440b6b.js +0 -624
  22. package/exports/browser/contract-163f031f.js +0 -1859
  23. package/exports/browser/index-3d3f56ca-064d16ce.js +0 -37
  24. package/exports/browser/index-543bc6a3-be806e11.js +0 -37
  25. package/exports/browser/messages-48deb2c3-73e8ace1.js +0 -205
  26. package/exports/browser/messages-af41e873-479a93a8.js +0 -205
  27. package/exports/browser/node-browser-63c7cb33.js +0 -16877
  28. package/exports/browser/node-browser-64b82fc8.js +0 -16877
  29. package/exports/browser/pako.esm-aa674ebf-aa674ebf.js +0 -6876
  30. package/exports/browser/simple-peer-743c19fe-03a0830e.js +0 -7856
package/exports/chain.js CHANGED
@@ -448,11 +448,16 @@ class Contract extends Transaction {
448
448
  }
449
449
  return this.createTransactionFrom(peernet.selectedAccount, addresses.contractFactory, 'registerContract', [await message.hash()]);
450
450
  }
451
+ async deployContractMessage(message) {
452
+ }
451
453
  }
452
454
 
453
455
  globalThis.BigNumber = BigNumber;
454
456
  // check if browser or local
455
457
  class Chain extends Contract {
458
+ #state;
459
+ id;
460
+ utils;
456
461
  /** {Address[]} */
457
462
  #validators = [];
458
463
  /** {Block[]} */
@@ -534,7 +539,7 @@ class Chain extends Contract {
534
539
  return [...this.#blocks];
535
540
  }
536
541
  async hasTransactionToHandle() {
537
- const size = await transactionPoolStore.size();
542
+ const size = await globalThis.transactionPoolStore.size();
538
543
  if (size > 0)
539
544
  return true;
540
545
  return false;
@@ -544,7 +549,7 @@ class Chain extends Contract {
544
549
  console.log('epoch');
545
550
  const validators = await this.staticCall(addresses.validators, 'validators');
546
551
  console.log({ validators });
547
- if (!validators[globalThis.peernet.selectedAccount]?.active)
552
+ if (!validators[globalThis.globalThis.peernet.selectedAccount]?.active)
548
553
  return;
549
554
  const start = Date.now();
550
555
  try {
@@ -577,7 +582,7 @@ class Chain extends Contract {
577
582
  await Promise.all(contracts.map(async ({ address, message }) => {
578
583
  // console.log({message});
579
584
  message = await new ContractMessage(Uint8Array.from(message.split(',').map(string => Number(string))));
580
- await contractStore.put(address, message.encoded);
585
+ await globalThis.contractStore.put(address, message.encoded);
581
586
  }));
582
587
  console.log('handle native contracts');
583
588
  // handle native contracts
@@ -586,14 +591,14 @@ class Chain extends Contract {
586
591
  return new Promise(async (resolve, reject) => {
587
592
  const timeout = setTimeout(() => {
588
593
  resolve([{ index: 0, hash: '0x0' }]);
589
- debug('sync timed out');
594
+ globalThis.debug('sync timed out');
590
595
  }, 10_000);
591
596
  promises = await Promise.allSettled(promises);
592
597
  promises = promises.filter(({ status }) => status === 'fulfilled');
593
598
  clearTimeout(timeout);
594
599
  if (promises.length > 0) {
595
600
  promises = promises.map(async ({ value }) => {
596
- const node = await new peernet.protos['peernet-response'](value.result);
601
+ const node = await new globalThis.peernet.protos['peernet-response'](value.result);
597
602
  return { value: node.decoded.response, peer: value.peer };
598
603
  });
599
604
  promises = await Promise.all(promises);
@@ -609,10 +614,10 @@ class Chain extends Contract {
609
614
  }
610
615
  async #getLatestBlock() {
611
616
  let promises = [];
612
- let data = await new peernet.protos['peernet-request']({ request: 'lastBlock' });
613
- let node = await peernet.prepareMessage(data);
614
- for (const peer of peernet?.connections) {
615
- if (peer.connected && peer.readyState === 'open' && peer.peerId !== this.id) {
617
+ let data = await new globalThis.peernet.protos['peernet-request']({ request: 'lastBlock' });
618
+ let node = await globalThis.peernet.prepareMessage(data);
619
+ for (const peer of globalThis.peernet?.connections) {
620
+ if (peer.connected) {
616
621
  promises.push(async () => {
617
622
  try {
618
623
  const result = await peer.request(node.encoded);
@@ -623,7 +628,11 @@ class Chain extends Contract {
623
628
  }
624
629
  });
625
630
  }
626
- else if (!peer.connected || peer.readyState !== 'open') ;
631
+ else if (!peer.connected) {
632
+ globalThis.peernet.removePeer(peer);
633
+ // todo: remove peer
634
+ // reinitiate channel?
635
+ }
627
636
  }
628
637
  promises = await this.promiseRequests(promises);
629
638
  let latest = { index: 0, hash: '0x0', previousHash: '0x0' };
@@ -631,18 +640,18 @@ class Chain extends Contract {
631
640
  if (promises.length > 0)
632
641
  latest = promises[0].value;
633
642
  if (latest.hash && latest.hash !== '0x0') {
634
- let message = await peernet.get(latest.hash, 'block');
643
+ let message = await globalThis.peernet.get(latest.hash, 'block');
635
644
  message = await new BlockMessage(message);
636
645
  const hash = await message.hash();
637
646
  if (hash !== latest.hash)
638
647
  throw new Error('invalid block @getLatestBlock');
639
- let data = await new peernet.protos['peernet-request']({ request: 'knownBlocks' });
640
- let node = await peernet.prepareMessage(data);
648
+ let data = await new globalThis.peernet.protos['peernet-request']({ request: 'knownBlocks' });
649
+ let node = await globalThis.peernet.prepareMessage(data);
641
650
  const peer = promises[0].peer;
642
651
  latest = { ...message.decoded, hash };
643
652
  if (peer.connected && peer.readyState === 'open' && peer.peerId !== this.id) {
644
653
  let message = await peer.request(node);
645
- message = await new peernet.protos['peernet-response'](message);
654
+ message = await new globalThis.peernet.protos['peernet-response'](message);
646
655
  this.#knownBlocks = message.decoded.response;
647
656
  }
648
657
  }
@@ -652,33 +661,37 @@ class Chain extends Contract {
652
661
  // this.node = await new Node()
653
662
  this.#participants = [];
654
663
  this.#participating = false;
655
- const initialized = await contractStore.has(addresses.contractFactory);
664
+ const initialized = await globalThis.contractStore.has(addresses.contractFactory);
656
665
  if (!initialized)
657
666
  await this.#setup();
658
667
  this.utils = { BigNumber, formatUnits, parseUnits };
659
- this.state = new State();
660
- await peernet.addRequestHandler('bw-request-message', () => {
661
- return new BWMessage(peernet.client.bw) || { up: 0, down: 0 };
668
+ this.#state = new State();
669
+ await globalThis.peernet.addRequestHandler('bw-request-message', () => {
670
+ return new BWMessage(globalThis.peernet.client.bw) || { up: 0, down: 0 };
662
671
  });
663
- await peernet.addRequestHandler('lastBlock', this.#lastBlockHandler.bind(this));
664
- await peernet.addRequestHandler('knownBlocks', this.#knownBlocksHandler.bind(this));
665
- peernet.subscribe('add-block', this.#addBlock.bind(this));
666
- peernet.subscribe('add-transaction', this.#addTransaction.bind(this));
667
- peernet.subscribe('validator:timeout', this.#validatorTimeout.bind(this));
668
- pubsub.subscribe('peer:connected', this.#peerConnected.bind(this));
672
+ // await globalThis.peernet.addRequestHandler('peerId', () => {
673
+ // let node =
674
+ // globalThis.peernet.protos['peernet-response']({response: node.encoded})
675
+ // })
676
+ await globalThis.peernet.addRequestHandler('lastBlock', this.#lastBlockHandler.bind(this));
677
+ await globalThis.peernet.addRequestHandler('knownBlocks', this.#knownBlocksHandler.bind(this));
678
+ globalThis.peernet.subscribe('add-block', this.#addBlock.bind(this));
679
+ globalThis.peernet.subscribe('add-transaction', this.#addTransaction.bind(this));
680
+ globalThis.peernet.subscribe('validator:timeout', this.#validatorTimeout.bind(this));
681
+ globalThis.pubsub.subscribe('peer:connected', this.#peerConnected.bind(this));
669
682
  // todo some functions rely on state
670
683
  try {
671
684
  let localBlock;
672
685
  try {
673
- localBlock = await chainStore.get('lastBlock');
686
+ localBlock = await globalThis.chainStore.get('lastBlock');
674
687
  }
675
688
  catch {
676
- await chainStore.put('lastBlock', '0x0');
677
- localBlock = await chainStore.get('lastBlock');
689
+ await globalThis.chainStore.put('lastBlock', '0x0');
690
+ localBlock = await globalThis.chainStore.get('lastBlock');
678
691
  }
679
692
  localBlock = new TextDecoder().decode(localBlock);
680
693
  if (localBlock && localBlock !== '0x0') {
681
- localBlock = await peernet.get(localBlock, 'block');
694
+ localBlock = await globalThis.peernet.get(localBlock, 'block');
682
695
  localBlock = await new BlockMessage(localBlock);
683
696
  this.#lastBlock = { ...localBlock.decoded, hash: await localBlock.hash() };
684
697
  }
@@ -696,15 +709,22 @@ class Chain extends Contract {
696
709
  await this.resolveBlocks();
697
710
  this.#machine = await new Machine(this.#blocks);
698
711
  await this.#loadBlocks(this.#blocks);
699
- globalThis.pubsub.publish('chain:ready', true);
712
+ globalThis.globalThis.pubsub.publish('chain:ready', true);
700
713
  return this;
701
714
  }
702
715
  async #validatorTimeout(validatorInfo) {
703
716
  setTimeout(() => {
704
- this.#jail.splice(this.jail.indexOf(validatorInfo.address), 1);
717
+ this.#jail.splice(this.#jail.indexOf(validatorInfo.address), 1);
705
718
  }, validatorInfo.timeout);
706
719
  this.#jail.push(validatorInfo.address);
707
720
  }
721
+ async triggerSync() {
722
+ if (this.#chainSyncing)
723
+ return 'already syncing';
724
+ const latest = await this.#getLatestBlock();
725
+ await this.#syncChain(latest);
726
+ return 'synced';
727
+ }
708
728
  async #syncChain(lastBlock) {
709
729
  if (this.#chainSyncing || !lastBlock || !lastBlock.hash || !lastBlock.hash)
710
730
  return;
@@ -712,7 +732,7 @@ class Chain extends Contract {
712
732
  if (this.#knownBlocks?.length === Number(lastBlock.index) + 1) {
713
733
  let promises = [];
714
734
  promises = await Promise.allSettled(this.#knownBlocks.map(async (address) => {
715
- const has = await peernet.has(address, 'block');
735
+ const has = await globalThis.peernet.has(address, 'block');
716
736
  return { has, address };
717
737
  }));
718
738
  promises = promises.filter(({ status, value }) => status === 'fulfilled' && !value.has);
@@ -724,53 +744,58 @@ class Chain extends Contract {
724
744
  const index = lastBlock.index;
725
745
  await this.resolveBlock(lastBlock.hash);
726
746
  let blocksSynced = localIndex > 0 ? (localIndex > index ? localIndex - index : index - localIndex) : index;
727
- debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`);
747
+ globalThis.debug(`synced ${blocksSynced} ${blocksSynced > 1 ? 'blocks' : 'block'}`);
728
748
  const start = (this.#blocks.length - blocksSynced) - 1;
729
- await this.#loadBlocks(this.blocks.slice(start));
749
+ if (this.#machine)
750
+ await this.#loadBlocks(this.blocks.slice(start));
730
751
  await this.#updateState(new BlockMessage(this.#blocks[this.#blocks.length - 1]));
731
752
  }
732
753
  this.#chainSyncing = false;
733
754
  }
734
755
  async #peerConnected(peer) {
735
- let node = await new peernet.protos['peernet-request']({ request: 'lastBlock' });
736
- node = await peernet.prepareMessage(node);
756
+ let node = await new globalThis.peernet.protos['peernet-request']({ request: 'lastBlock' });
757
+ node = await globalThis.peernet.prepareMessage(node);
737
758
  let response = await peer.request(node.encoded);
738
- response = await new globalThis.peernet.protos['peernet-response'](response);
759
+ response = await new globalThis.globalThis.peernet.protos['peernet-response'](new Uint8Array(Object.values(response)));
739
760
  let lastBlock = response.decoded.response;
740
761
  // try catch known blocks
741
- node = await new peernet.protos['peernet-request']({ request: 'knownBlocks' });
742
- node = await peernet.prepareMessage(node);
762
+ node = await new globalThis.peernet.protos['peernet-request']({ request: 'knownBlocks' });
763
+ node = await globalThis.peernet.prepareMessage(node);
743
764
  response = await peer.request(node.encoded);
744
- response = await new globalThis.peernet.protos['peernet-response'](response);
765
+ response = await new globalThis.globalThis.peernet.protos['peernet-response'](new Uint8Array(Object.values(response)));
745
766
  this.#knownBlocks = response.decoded.response;
746
767
  this.#syncChain(lastBlock);
747
768
  }
748
769
  #epochTimeout;
749
770
  async #lastBlockHandler() {
750
- return new peernet.protos['peernet-response']({ response: { hash: this.#lastBlock?.hash, index: this.#lastBlock?.index } });
771
+ return new globalThis.peernet.protos['peernet-response']({ response: { hash: this.#lastBlock?.hash, index: this.#lastBlock?.index } });
751
772
  }
752
773
  async #knownBlocksHandler() {
753
- return new peernet.protos['peernet-response']({ response: { blocks: this.#blocks.map((block) => block.hash) } });
774
+ return new globalThis.peernet.protos['peernet-response']({ response: { blocks: this.#blocks.map((block) => block.hash) } });
754
775
  }
755
776
  async getAndPutBlock(hash) {
756
- let block = await peernet.get(hash, 'block');
777
+ let block = await globalThis.peernet.get(hash, 'block');
757
778
  block = await new BlockMessage(block);
758
779
  const { index } = block.decoded;
759
780
  if (this.#blocks[index] && this.#blocks[index].hash !== block.hash)
760
781
  throw `invalid block ${hash} @${index}`;
761
- if (!await peernet.has(hash, 'block'))
762
- await peernet.put(hash, block.encoded, 'block');
782
+ if (!await globalThis.peernet.has(hash, 'block'))
783
+ await globalThis.peernet.put(hash, block.encoded, 'block');
763
784
  return block;
764
785
  }
765
786
  async resolveBlock(hash) {
766
787
  if (!hash)
767
788
  throw new Error(`expected hash, got: ${hash}`);
789
+ if (hash === '0x0')
790
+ return;
768
791
  const index = this.#blockHashMap.get(hash);
769
792
  if (this.#blocks[index]) {
770
793
  if (this.#blocks[index].previousHash !== '0x0') {
771
- return this.resolveBlock(this.#blocks[index]);
794
+ return this.resolveBlock(this.#blocks[index].previousHash);
795
+ }
796
+ else {
797
+ return;
772
798
  }
773
- return;
774
799
  }
775
800
  try {
776
801
  const block = await this.getAndPutBlock(hash);
@@ -790,14 +815,14 @@ class Chain extends Contract {
790
815
  }
791
816
  async resolveBlocks() {
792
817
  try {
793
- const localBlock = await chainStore.get('lastBlock');
818
+ const localBlock = await globalThis.chainStore.get('lastBlock');
794
819
  const hash = new TextDecoder().decode(localBlock);
795
820
  if (hash && hash !== '0x0')
796
821
  await this.resolveBlock(hash);
797
822
  this.#lastBlock = this.#blocks[this.#blocks.length - 1];
798
823
  }
799
824
  catch {
800
- await chainStore.put('lastBlock', new TextEncoder().encode('0x0'));
825
+ await globalThis.chainStore.put('lastBlock', new TextEncoder().encode('0x0'));
801
826
  return this.resolveBlocks();
802
827
  // console.log(e);
803
828
  }
@@ -828,7 +853,7 @@ class Chain extends Contract {
828
853
  }
829
854
  }
830
855
  this.#blocks[block.index].loaded = true;
831
- debug(`loaded block: ${block.hash} @${block.index}`);
856
+ globalThis.debug(`loaded block: ${block.hash} @${block.index}`);
832
857
  }
833
858
  }
834
859
  }
@@ -836,25 +861,24 @@ class Chain extends Contract {
836
861
  try {
837
862
  let result = await this.#machine.execute(to, method, params, from, nonce);
838
863
  // if (!result) result = this.#machine.state
839
- pubsub.publish(`transaction.completed.${hash}`, { status: 'fulfilled', hash });
864
+ globalThis.pubsub.publish(`transaction.completed.${hash}`, { status: 'fulfilled', hash });
840
865
  return result || 'no state change';
841
866
  }
842
867
  catch (error) {
843
868
  console.log(error);
844
- pubsub.publish(`transaction.completed.${hash}`, { status: 'fail', hash, error: error });
869
+ globalThis.pubsub.publish(`transaction.completed.${hash}`, { status: 'fail', hash, error: error });
845
870
  throw error;
846
871
  }
847
872
  }
848
873
  async #addBlock(block) {
849
- // console.log(block);
850
874
  const blockMessage = await new BlockMessage(block);
851
875
  await Promise.all(blockMessage.decoded.transactions
852
- .map(async (transaction) => transactionPoolStore.delete(transaction.hash)));
876
+ .map(async (transaction) => globalThis.transactionPoolStore.delete(transaction.hash)));
853
877
  const hash = await blockMessage.hash();
854
- await blockStore.put(hash, blockMessage.encoded);
878
+ await globalThis.blockStore.put(hash, blockMessage.encoded);
855
879
  if (this.lastBlock.index < blockMessage.decoded.index)
856
880
  await this.#updateState(blockMessage);
857
- debug(`added block: ${hash}`);
881
+ globalThis.debug(`added block: ${hash}`);
858
882
  let promises = [];
859
883
  let contracts = [];
860
884
  for (let transaction of blockMessage.decoded.transactions) {
@@ -868,10 +892,10 @@ class Chain extends Contract {
868
892
  try {
869
893
  promises = await Promise.allSettled(promises);
870
894
  for (let transaction of blockMessage.decoded.transactions) {
871
- pubsub.publish('transaction-processed', transaction);
872
- if (transaction.to === peernet.selectedAccount)
873
- pubsub.publish('account-transaction-processed', transaction);
874
- await accountsStore.put(transaction.from, String(transaction.nonce));
895
+ globalThis.pubsub.publish('transaction-processed', transaction);
896
+ if (transaction.to === globalThis.peernet.selectedAccount)
897
+ globalThis.pubsub.publish('account-transaction-processed', transaction);
898
+ await globalThis.accountsStore.put(transaction.from, String(transaction.nonce));
875
899
  }
876
900
  // todo finish state
877
901
  // for (const contract of contracts) {
@@ -879,7 +903,7 @@ class Chain extends Contract {
879
903
  // // await stateStore.put(contract, state)
880
904
  // console.log(state);
881
905
  // }
882
- pubsub.publish('block-processed', blockMessage.decoded);
906
+ globalThis.pubsub.publish('block-processed', blockMessage.decoded);
883
907
  }
884
908
  catch (error) {
885
909
  console.log({ e: error });
@@ -889,7 +913,7 @@ class Chain extends Contract {
889
913
  const hash = await message.hash();
890
914
  this.#lastBlock = { hash, ...message.decoded };
891
915
  // await this.state.updateState(message)
892
- await chainStore.put('lastBlock', hash);
916
+ await globalThis.chainStore.put('lastBlock', hash);
893
917
  }
894
918
  async participate(address) {
895
919
  // TODO: validate participant
@@ -908,7 +932,7 @@ class Chain extends Contract {
908
932
  nonce: (await this.getNonce(address)) + 1,
909
933
  timestamp: Date.now()
910
934
  };
911
- const transaction = await signTransaction(rawTransaction, peernet.identity);
935
+ const transaction = await signTransaction(rawTransaction, globalThis.peernet.identity);
912
936
  await this.sendTransaction(transaction);
913
937
  }
914
938
  if (await this.hasTransactionToHandle() && !this.#runningEpoch)
@@ -917,15 +941,19 @@ class Chain extends Contract {
917
941
  // todo filter tx that need to wait on prev nonce
918
942
  async #createBlock(limit = 1800) {
919
943
  // vote for transactions
920
- if (await transactionPoolStore.size() === 0)
944
+ if (await globalThis.transactionPoolStore.size() === 0)
921
945
  return;
922
- let transactions = await transactionPoolStore.values(this.transactionLimit);
946
+ let transactions = await globalThis.transactionPoolStore.values(this.transactionLimit);
923
947
  if (Object.keys(transactions)?.length === 0)
924
948
  return;
925
949
  let block = {
926
950
  transactions: [],
927
951
  validators: [],
928
- fees: BigNumber.from(0)
952
+ fees: BigNumber.from(0),
953
+ timestamp: Date.now(),
954
+ previousHash: '',
955
+ reward: parseUnits('150'),
956
+ index: 0
929
957
  };
930
958
  // exclude failing tx
931
959
  transactions = await this.promiseTransactions(transactions);
@@ -935,11 +963,11 @@ class Chain extends Contract {
935
963
  try {
936
964
  await this.#executeTransaction({ ...transaction.decoded, hash });
937
965
  block.transactions.push({ hash, ...transaction.decoded });
938
- block.fees += Number(calculateFee(transaction.decoded));
939
- await accountsStore.put(transaction.decoded.from, new TextEncoder().encode(String(transaction.decoded.nonce)));
966
+ block.fees = block.fees.add(await calculateFee(transaction.decoded));
967
+ await globalThis.accountsStore.put(transaction.decoded.from, new TextEncoder().encode(String(transaction.decoded.nonce)));
940
968
  }
941
969
  catch (e) {
942
- await transactionPoolStore.delete(hash);
970
+ await globalThis.transactionPoolStore.delete(hash);
943
971
  }
944
972
  }
945
973
  // don't add empty block
@@ -955,7 +983,7 @@ class Chain extends Contract {
955
983
  // }
956
984
  // }, [])
957
985
  const peers = {};
958
- for (const entry of peernet.peerEntries) {
986
+ for (const entry of globalThis.peernet.peerEntries) {
959
987
  peers[entry[0]] = entry[1];
960
988
  }
961
989
  for (const validator of Object.keys(validators)) {
@@ -963,7 +991,7 @@ class Chain extends Contract {
963
991
  const peer = peers[validator];
964
992
  if (peer && peer.connected) {
965
993
  let data = await new BWRequestMessage();
966
- const node = await peernet.prepareMessage(validator, data.encoded);
994
+ const node = await globalThis.peernet.prepareMessage(validator, data.encoded);
967
995
  try {
968
996
  const bw = await peer.request(node.encoded);
969
997
  console.log({ bw });
@@ -974,21 +1002,24 @@ class Chain extends Contract {
974
1002
  }
975
1003
  catch { }
976
1004
  }
977
- else if (peernet.selectedAccount === validator) {
1005
+ else if (globalThis.peernet.selectedAccount === validator) {
978
1006
  block.validators.push({
979
- address: peernet.selectedAccount,
980
- bw: peernet.bw.up + peernet.bw.down
1007
+ address: globalThis.peernet.selectedAccount,
1008
+ bw: globalThis.peernet.bw.up + globalThis.peernet.bw.down
981
1009
  });
982
1010
  }
983
1011
  }
984
1012
  }
985
1013
  console.log({ validators: block.validators });
986
- block.reward = 150;
987
1014
  block.validators = block.validators.map(validator => {
988
- validator.reward = String(Number(block.fees) + block.reward / block.validators.length);
1015
+ validator.reward = block.fees;
1016
+ validator.reward = validator.reward.add(block.reward);
1017
+ validator.reward = validator.reward.div(block.validators.length);
1018
+ validator.reward = validator.reward.toString();
989
1019
  delete validator.bw;
990
1020
  return validator;
991
1021
  });
1022
+ console.log({ validators: block.validators });
992
1023
  // block.validators = calculateValidatorReward(block.validators, block.fees)
993
1024
  block.index = this.lastBlock?.index;
994
1025
  if (block.index === undefined)
@@ -997,29 +1028,19 @@ class Chain extends Contract {
997
1028
  block.index += 1;
998
1029
  block.previousHash = this.lastBlock?.hash || '0x0';
999
1030
  block.timestamp = Date.now();
1000
- const parts = String(block.fees).split('.');
1001
- let decimals = 0;
1002
- if (parts[1]) {
1003
- const potentional = parts[1].split('e');
1004
- if (potentional[0] === parts[1]) {
1005
- decimals = parts[1].length;
1006
- }
1007
- else {
1008
- parts[1] = potentional[0];
1009
- decimals = Number(potentional[1]?.replace(/[+-]/g, '')) + Number(potentional[0].length);
1010
- }
1011
- }
1012
- block.fees = Number.parseFloat(String(block.fees)).toFixed(decimals);
1031
+ block.reward = block.reward.toString();
1032
+ block.fees = block.fees.toString();
1013
1033
  try {
1014
1034
  await Promise.all(block.transactions
1015
- .map(async (transaction) => transactionPoolStore.delete(transaction.hash)));
1035
+ .map(async (transaction) => globalThis.transactionPoolStore.delete(transaction.hash)));
1016
1036
  let blockMessage = await new BlockMessage(block);
1037
+ blockMessage = await new BlockMessage(blockMessage.encoded);
1017
1038
  const hash = await blockMessage.hash();
1018
- await peernet.put(hash, blockMessage.encoded, 'block');
1039
+ await globalThis.peernet.put(hash, blockMessage.encoded, 'block');
1019
1040
  await this.#updateState(blockMessage);
1020
- debug(`created block: ${hash}`);
1021
- peernet.publish('add-block', blockMessage.encoded);
1022
- pubsub.publish('add-block', blockMessage.decoded);
1041
+ globalThis.debug(`created block: ${hash}`);
1042
+ globalThis.peernet.publish('add-block', blockMessage.encoded);
1043
+ globalThis.pubsub.publish('add-block', blockMessage.decoded);
1023
1044
  }
1024
1045
  catch (error) {
1025
1046
  throw new Error(`invalid block ${block}`);
@@ -1031,9 +1052,9 @@ class Chain extends Contract {
1031
1052
  try {
1032
1053
  transaction = await new TransactionMessage(transaction);
1033
1054
  const hash = await transaction.hash();
1034
- const has = await transactionPoolStore.has(hash);
1055
+ const has = await globalThis.transactionPoolStore.has(hash);
1035
1056
  if (!has)
1036
- await transactionPoolStore.put(hash, transaction.encoded);
1057
+ await globalThis.transactionPoolStore.put(hash, transaction.encoded);
1037
1058
  if (this.#participating && !this.#runningEpoch)
1038
1059
  this.#runEpoch();
1039
1060
  }
@@ -1066,7 +1087,7 @@ class Chain extends Contract {
1066
1087
  * @param {Address} sender
1067
1088
  * @returns {globalMessage}
1068
1089
  */
1069
- #createMessage(sender = globalThis.peernet.selectedAccount) {
1090
+ #createMessage(sender = globalThis.globalThis.peernet.selectedAccount) {
1070
1091
  return {
1071
1092
  sender,
1072
1093
  call: this.call,
package/exports/node.js CHANGED
@@ -12,7 +12,8 @@ class Node {
12
12
  network: 'leofcoin:peach',
13
13
  networkName: 'leofcoin:peach',
14
14
  networkVersion: 'peach',
15
- stars: networks.leofcoin.peach.stars
15
+ stars: networks.leofcoin.peach.stars,
16
+ autoStart: false
16
17
  }, password) {
17
18
  this.#node = globalThis.Peernet ? await new globalThis.Peernet(config, password) : await new Peernet(config, password);
18
19
  await nodeConfig(config);
@@ -3,6 +3,8 @@ import Contract from './contract.js';
3
3
  import { BigNumberish } from '@ethersproject/bignumber';
4
4
  export default class Chain extends Contract {
5
5
  #private;
6
+ id: string;
7
+ utils: {};
6
8
  constructor();
7
9
  get nativeMints(): number;
8
10
  get nativeBurns(): number;
@@ -26,6 +28,7 @@ export default class Chain extends Contract {
26
28
  hash: string;
27
29
  previousHash: string;
28
30
  }>;
31
+ triggerSync(): Promise<"already syncing" | "synced">;
29
32
  getAndPutBlock(hash: string): BlockMessage;
30
33
  resolveBlock(hash: any): any;
31
34
  resolveBlocks(): any;
@@ -38,14 +41,14 @@ export default class Chain extends Contract {
38
41
  sendTransaction(transaction: any): Promise<{
39
42
  hash: any;
40
43
  data: any;
41
- fee: string | 0;
44
+ fee: any;
42
45
  wait: Promise<unknown>;
43
46
  message: any;
44
47
  }>;
45
48
  addContract(transaction: any, contractMessage: any): Promise<{
46
49
  hash: any;
47
50
  data: any;
48
- fee: string | 0;
51
+ fee: any;
49
52
  wait: Promise<unknown>;
50
53
  message: any;
51
54
  }>;
@@ -25,5 +25,6 @@ export default class Contract extends Transaction {
25
25
  * @returns
26
26
  */
27
27
  deployContract(contract: string, constructorParameters?: any[]): Promise<any>;
28
+ deployContractMessage(message: any): Promise<void>;
28
29
  }
29
30
  import Transaction from "./transaction.js";
@@ -6,5 +6,6 @@ export default class Node {
6
6
  networkName: string;
7
7
  networkVersion: string;
8
8
  stars: any;
9
+ autoStart: boolean;
9
10
  }, password: string): Promise<this>;
10
11
  }
@@ -40,7 +40,7 @@ export default class Transaction extends Protocol {
40
40
  sendTransaction(message: any): Promise<{
41
41
  hash: any;
42
42
  data: any;
43
- fee: string | 0;
43
+ fee: any;
44
44
  wait: Promise<unknown>;
45
45
  message: any;
46
46
  }>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leofcoin/chain",
3
- "version": "1.4.36",
3
+ "version": "1.4.38",
4
4
  "description": "Official javascript implementation",
5
5
  "exports": {
6
6
  "./node": "./exports/node.js",
@@ -45,7 +45,9 @@
45
45
  "eslint": "^8.28.0",
46
46
  "eslint-plugin-unicorn": "^45.0.0",
47
47
  "open": "^8.4.0",
48
+ "rimraf": "^4.4.0",
48
49
  "rollup": "^3.12.0",
50
+ "rollup-plugin-modify": "^3.0.0",
49
51
  "tape": "^5.5.2",
50
52
  "tslib": "^2.4.1"
51
53
  },
@@ -56,7 +58,7 @@
56
58
  "@leofcoin/messages": "^1.2.0",
57
59
  "@leofcoin/multi-wallet": "^2.1.1",
58
60
  "@leofcoin/networks": "^1.0.0",
59
- "@leofcoin/peernet": "^1.1.2",
61
+ "@leofcoin/peernet": "^1.1.12",
60
62
  "@leofcoin/peernet-swarm": "^1.0.0",
61
63
  "@leofcoin/storage": "^3.0.6",
62
64
  "@leofcoin/utils": "^1.1.4",
@@ -1,56 +0,0 @@
1
- function _mergeNamespaces(n, m) {
2
- m.forEach(function (e) {
3
- e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) {
4
- if (k !== 'default' && !(k in n)) {
5
- var d = Object.getOwnPropertyDescriptor(e, k);
6
- Object.defineProperty(n, k, d.get ? d : {
7
- enumerable: true,
8
- get: function () { return e[k]; }
9
- });
10
- }
11
- });
12
- });
13
- return Object.freeze(n);
14
- }
15
-
16
- var browser$1 = {};
17
-
18
- var MediaStream = browser$1.MediaStream = window.MediaStream;
19
- var MediaStreamTrack = browser$1.MediaStreamTrack = window.MediaStreamTrack;
20
- var RTCDataChannel = browser$1.RTCDataChannel = window.RTCDataChannel;
21
- var RTCDataChannelEvent = browser$1.RTCDataChannelEvent = window.RTCDataChannelEvent;
22
- var RTCDtlsTransport = browser$1.RTCDtlsTransport = window.RTCDtlsTransport;
23
- var RTCIceCandidate = browser$1.RTCIceCandidate = window.RTCIceCandidate;
24
- var RTCIceTransport = browser$1.RTCIceTransport = window.RTCIceTransport;
25
- var RTCPeerConnection = browser$1.RTCPeerConnection = window.RTCPeerConnection;
26
- var RTCPeerConnectionIceEvent = browser$1.RTCPeerConnectionIceEvent = window.RTCPeerConnectionIceEvent;
27
- var RTCRtpReceiver = browser$1.RTCRtpReceiver = window.RTCRtpReceiver;
28
- var RTCRtpSender = browser$1.RTCRtpSender = window.RTCRtpSender;
29
- var RTCRtpTransceiver = browser$1.RTCRtpTransceiver = window.RTCRtpTransceiver;
30
- var RTCSctpTransport = browser$1.RTCSctpTransport = window.RTCSctpTransport;
31
- var RTCSessionDescription = browser$1.RTCSessionDescription = window.RTCSessionDescription;
32
- var getUserMedia = browser$1.getUserMedia = window.getUserMedia;
33
- var mediaDevices = browser$1.mediaDevices = navigator.mediaDevices;
34
-
35
- var browser = /*#__PURE__*/_mergeNamespaces({
36
- __proto__: null,
37
- MediaStream: MediaStream,
38
- MediaStreamTrack: MediaStreamTrack,
39
- RTCDataChannel: RTCDataChannel,
40
- RTCDataChannelEvent: RTCDataChannelEvent,
41
- RTCDtlsTransport: RTCDtlsTransport,
42
- RTCIceCandidate: RTCIceCandidate,
43
- RTCIceTransport: RTCIceTransport,
44
- RTCPeerConnection: RTCPeerConnection,
45
- RTCPeerConnectionIceEvent: RTCPeerConnectionIceEvent,
46
- RTCRtpReceiver: RTCRtpReceiver,
47
- RTCRtpSender: RTCRtpSender,
48
- RTCRtpTransceiver: RTCRtpTransceiver,
49
- RTCSctpTransport: RTCSctpTransport,
50
- RTCSessionDescription: RTCSessionDescription,
51
- default: browser$1,
52
- getUserMedia: getUserMedia,
53
- mediaDevices: mediaDevices
54
- }, [browser$1]);
55
-
56
- export { browser as b };