@leofcoin/chain 1.4.50 → 1.4.52

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.
@@ -1,4 +1,4 @@
1
- import { B as BigNumber, L as Logger, v as version$1, h as hexZeroPad, i as isBigNumberish, a as arrayify, b as isBytes, C as ContractMessage, T as TransactionMessage, c as CodecHash, d as BlockMessage, e as BWMessage, f as BWRequestMessage } from './contract-f76383c3.js';
1
+ import { B as BigNumber, L as Logger, v as version$1, h as hexZeroPad, i as isBigNumberish, a as arrayify, b as isBytes, C as ContractMessage, T as TransactionMessage, R as RawTransactionMessage, c as BlockMessage, d as BWMessage, e as BWRequestMessage } from './index-640d9f36.js';
2
2
 
3
3
  const logger$1 = new Logger(version$1);
4
4
  const _constructorGuard = {};
@@ -729,7 +729,16 @@ const calculateFee = async (transaction, format = false) => {
729
729
  // fee = fee.div(1000000)
730
730
  return format ? formatUnits(fee.toString()) : fee;
731
731
  };
732
- const createTransactionHash = async (transaction) => (await new CodecHash(transaction, { name: 'transaction-message' })).digest;
732
+ const createTransactionHash = async (transaction) => {
733
+ const isRawTransactionMessage = transaction instanceof RawTransactionMessage;
734
+ if (!isRawTransactionMessage) {
735
+ if (transaction.decoded && transaction instanceof TransactionMessage)
736
+ transaction = await new RawTransactionMessage(transaction.decoded);
737
+ else
738
+ transaction = await new RawTransactionMessage(transaction);
739
+ }
740
+ return (await transaction.peernetHash).digest;
741
+ };
733
742
  const signTransaction = async (transaction, wallet) => {
734
743
  const signature = await wallet.sign(await createTransactionHash(transaction));
735
744
  const signedTransaction = { ...transaction, signature };
@@ -7637,9 +7646,23 @@ class State {
7637
7646
  }
7638
7647
  }
7639
7648
 
7649
+ const limit = 1800;
7650
+ const transactionLimit = 1800;
7651
+ const requestTimeout = 30_000;
7652
+ const syncTimeout = 30_000;
7640
7653
  class Protocol {
7641
- limit = 1800;
7642
- transactionLimit = 1800;
7654
+ get limit() {
7655
+ return limit;
7656
+ }
7657
+ get transactionLimit() {
7658
+ return transactionLimit;
7659
+ }
7660
+ get requestTimeout() {
7661
+ return requestTimeout;
7662
+ }
7663
+ get syncTimeout() {
7664
+ return syncTimeout;
7665
+ }
7643
7666
  }
7644
7667
 
7645
7668
  class Transaction extends Protocol {
@@ -7801,7 +7824,7 @@ class Transaction extends Protocol {
7801
7824
  await globalThis.transactionPoolStore.put(hash, message.encoded);
7802
7825
  // debug(`Added ${hash} to the transaction pool`)
7803
7826
  peernet.publish('add-transaction', message.encoded);
7804
- return { hash: hash, data, fee: await calculateFee(message.decoded), wait, message };
7827
+ return { hash, data, fee: await calculateFee(message.decoded), wait, message };
7805
7828
  }
7806
7829
  catch (error) {
7807
7830
  throw error;
@@ -8000,7 +8023,7 @@ class Chain extends Contract {
8000
8023
  const timeout = setTimeout(() => {
8001
8024
  resolve([{ index: 0, hash: '0x0' }]);
8002
8025
  globalThis.debug('sync timed out');
8003
- }, 10_000);
8026
+ }, this.requestTimeout);
8004
8027
  promises = await Promise.allSettled(promises);
8005
8028
  promises = promises.filter(({ status }) => status === 'fulfilled');
8006
8029
  clearTimeout(timeout);
@@ -8048,11 +8071,11 @@ class Chain extends Contract {
8048
8071
  const hash = await message.hash();
8049
8072
  if (hash !== latest.hash)
8050
8073
  throw new Error('invalid block @getLatestBlock');
8051
- let data = await new globalThis.peernet.protos['peernet-request']({ request: 'knownBlocks' });
8052
- let node = await globalThis.peernet.prepareMessage(data);
8053
- const peer = promises[0].peer;
8054
8074
  latest = { ...message.decoded, hash };
8075
+ const peer = promises[0].peer;
8055
8076
  if (peer.connected && peer.version === this.version) {
8077
+ let data = await new globalThis.peernet.protos['peernet-request']({ request: 'knownBlocks' });
8078
+ let node = await globalThis.peernet.prepareMessage(data);
8056
8079
  let message = await peer.request(node);
8057
8080
  message = await new globalThis.peernet.protos['peernet-response'](message);
8058
8081
  this.#knownBlocks = message.decoded.response;
@@ -8067,7 +8090,7 @@ class Chain extends Contract {
8067
8090
  try {
8068
8091
  const version = await globalThis.chainStore.get('version');
8069
8092
  this.version = new TextDecoder().decode(version);
8070
- if (version !== '1.0.0') {
8093
+ if (this.version !== '1.0.0') {
8071
8094
  this.version = '1.0.0';
8072
8095
  await globalThis.chainStore.clear();
8073
8096
  await globalThis.blockStore.clear();
@@ -8076,14 +8099,14 @@ class Chain extends Contract {
8076
8099
  }
8077
8100
  // if (version)
8078
8101
  }
8079
- catch {
8102
+ catch (e) {
8103
+ console.log(e);
8080
8104
  this.version = '1.0.0';
8081
8105
  await globalThis.chainStore.clear();
8082
8106
  await globalThis.blockStore.clear();
8083
8107
  await globalThis.transactionPoolStore.clear();
8084
- await globalThis.chainStore.put('version', this.version);
8108
+ await globalThis.chainStore.put('version', new TextEncoder().encode(this.version));
8085
8109
  }
8086
- await this.#clearPool();
8087
8110
  // this.node = await new Node()
8088
8111
  this.#participants = [];
8089
8112
  this.#participating = false;
@@ -8105,7 +8128,7 @@ class Chain extends Contract {
8105
8128
  await globalThis.peernet.addRequestHandler('knownBlocks', this.#knownBlocksHandler.bind(this));
8106
8129
  globalThis.peernet.subscribe('add-block', this.#addBlock.bind(this));
8107
8130
  globalThis.peernet.subscribe('invalid-transaction', this.#invalidTransaction.bind(this));
8108
- globalThis.peernet.subscribe('add-transaction', this.#addTransaction.bind(this));
8131
+ globalThis.peernet.subscribe('send-transaction', this.#sendTransaction.bind(this));
8109
8132
  globalThis.peernet.subscribe('validator:timeout', this.#validatorTimeout.bind(this));
8110
8133
  globalThis.pubsub.subscribe('peer:connected', this.#peerConnected.bind(this));
8111
8134
  // todo some functions rely on state
@@ -8162,7 +8185,7 @@ class Chain extends Contract {
8162
8185
  let current;
8163
8186
  const timeout = () => current = setTimeout(() => {
8164
8187
  if (this.#chainSyncing) {
8165
- if (this.#lastResolved + 10000 > Date.now())
8188
+ if (this.#lastResolved + this.syncTimeout > Date.now())
8166
8189
  timeout();
8167
8190
  else {
8168
8191
  this.#chainSyncing = false;
@@ -8170,7 +8193,7 @@ class Chain extends Contract {
8170
8193
  this.#syncChain(lastBlock);
8171
8194
  }
8172
8195
  }
8173
- }, 10000);
8196
+ }, this.syncTimeout);
8174
8197
  timeout();
8175
8198
  if (this.#chainSyncing || !lastBlock || !lastBlock.hash || !lastBlock.hash)
8176
8199
  return;
@@ -8213,23 +8236,38 @@ class Chain extends Contract {
8213
8236
  if (!peer.version || peer.version !== this.version)
8214
8237
  return;
8215
8238
  const lastBlock = await this.#makeRequest(peer, 'lastBlock');
8216
- this.#knownBlocks = await this.#makeRequest(peer, 'knownBlocks');
8217
- let pool = await this.#makeRequest(peer, 'transactionPool');
8218
- pool = await Promise.all(pool.map(async (hash) => {
8219
- const has = await globalThis.peernet.has(hash);
8220
- return { has, hash };
8221
- }));
8222
- pool = pool.filter(item => !item.has);
8223
- await Promise.all(pool.map(async ({ hash }) => {
8224
- const result = await globalThis.peernet.get(hash);
8225
- const node = await new TransactionMessage(result);
8226
- await globalThis.transactionPoolStore.put(await node.hash(), node.encoded);
8227
- }));
8228
- if (pool.length > 0)
8229
- this.#runEpoch();
8230
- console.log(pool);
8231
- if (lastBlock)
8232
- this.#syncChain(lastBlock);
8239
+ if (lastBlock.index > this.#lastBlock?.index) {
8240
+ // this.#knownBlocks = await this.#makeRequest(peer, 'knownBlocks')
8241
+ try {
8242
+ console.log('getting pool');
8243
+ let pool = await this.#makeRequest(peer, 'transactionPool');
8244
+ console.log('got pool');
8245
+ pool = await Promise.all(pool.map(async (hash) => {
8246
+ const has = await globalThis.peernet.has(hash);
8247
+ return { has, hash };
8248
+ }));
8249
+ pool = pool.filter(item => !item.has);
8250
+ await Promise.all(pool.map(async ({ hash }) => {
8251
+ const result = await globalThis.peernet.get(hash);
8252
+ // result could be undefined cause invalid/double transactions could be deleted already
8253
+ if (!result)
8254
+ console.log(result);
8255
+ if (result) {
8256
+ const node = await new TransactionMessage(result);
8257
+ await globalThis.transactionPoolStore.put(await node.hash(), node.encoded);
8258
+ }
8259
+ }));
8260
+ }
8261
+ catch (error) {
8262
+ console.log(error);
8263
+ console.log('error fetching transactionPool');
8264
+ }
8265
+ console.log(lastBlock);
8266
+ if (lastBlock)
8267
+ await this.#syncChain(lastBlock);
8268
+ if (await this.hasTransactionToHandle())
8269
+ this.#runEpoch();
8270
+ }
8233
8271
  }
8234
8272
  #epochTimeout;
8235
8273
  async #transactionPoolHandler() {
@@ -8246,13 +8284,16 @@ class Chain extends Contract {
8246
8284
  return new globalThis.peernet.protos['peernet-response']({ response: { blocks: this.#blocks.map((block) => block.hash) } });
8247
8285
  }
8248
8286
  async getAndPutBlock(hash) {
8287
+ // todo peernet resolves undefined blocks....
8249
8288
  let block = await globalThis.peernet.get(hash, 'block');
8250
- block = await new BlockMessage(block);
8251
- const { index } = block.decoded;
8252
- if (this.#blocks[index] && this.#blocks[index].hash !== block.hash)
8253
- throw `invalid block ${hash} @${index}`;
8254
- if (!await globalThis.peernet.has(hash, 'block'))
8255
- await globalThis.peernet.put(hash, block.encoded, 'block');
8289
+ if (block !== undefined) {
8290
+ block = await new BlockMessage(block);
8291
+ const { index } = block.decoded;
8292
+ if (this.#blocks[index] && this.#blocks[index].hash !== block.hash)
8293
+ throw `invalid block ${hash} @${index}`;
8294
+ if (!await globalThis.peernet.has(hash, 'block'))
8295
+ await globalThis.peernet.put(hash, block.encoded, 'block');
8296
+ }
8256
8297
  return block;
8257
8298
  }
8258
8299
  async resolveBlock(hash) {
@@ -8326,12 +8367,14 @@ class Chain extends Contract {
8326
8367
  }
8327
8368
  catch (error) {
8328
8369
  console.log(error);
8370
+ return false;
8329
8371
  }
8330
8372
  }
8331
8373
  this.#blocks[block.index].loaded = true;
8332
8374
  globalThis.debug(`loaded block: ${block.hash} @${block.index}`);
8333
8375
  }
8334
8376
  }
8377
+ return true;
8335
8378
  }
8336
8379
  async #executeTransaction({ hash, from, to, method, params, nonce }) {
8337
8380
  try {
@@ -8423,7 +8466,6 @@ class Chain extends Contract {
8423
8466
  let transactions = await globalThis.transactionPoolStore.values(this.transactionLimit);
8424
8467
  if (Object.keys(transactions)?.length === 0)
8425
8468
  return;
8426
- const keys = await globalThis.transactionPoolStore.keys();
8427
8469
  const timestamp = Date.now();
8428
8470
  let block = {
8429
8471
  transactions: [],
@@ -8447,35 +8489,30 @@ class Chain extends Contract {
8447
8489
  }
8448
8490
  }
8449
8491
  }
8450
- console.log();
8451
8492
  if (doubleTransactions.length > 0) {
8452
8493
  await globalThis.transactionPoolStore.delete(hash);
8453
8494
  await globalThis.peernet.publish('invalid-transaction', hash);
8454
8495
  }
8455
8496
  else {
8456
- if (timestamp + this.#slotTime > Date.now()) {
8457
- try {
8458
- const result = await this.#executeTransaction({ ...transaction.decoded, hash });
8459
- console.log({ result });
8460
- block.transactions.push({ hash, ...transaction.decoded });
8461
- block.fees = block.fees.add(await calculateFee(transaction.decoded));
8462
- await globalThis.accountsStore.put(transaction.decoded.from, new TextEncoder().encode(String(transaction.decoded.nonce)));
8463
- }
8464
- catch (e) {
8465
- console.log(keys.includes(hash));
8466
- console.log({ e });
8467
- console.log(hash);
8468
- await globalThis.transactionPoolStore.delete(hash);
8469
- }
8497
+ // if (timestamp + this.#slotTime > Date.now()) {
8498
+ try {
8499
+ const result = await this.#executeTransaction({ ...transaction.decoded, hash });
8500
+ block.transactions.push(transaction);
8501
+ block.fees = block.fees.add(await calculateFee(transaction.decoded));
8502
+ await globalThis.accountsStore.put(transaction.decoded.from, new TextEncoder().encode(String(transaction.decoded.nonce)));
8470
8503
  }
8504
+ catch (e) {
8505
+ console.log({ e });
8506
+ console.log(hash);
8507
+ await globalThis.transactionPoolStore.delete(hash);
8508
+ }
8509
+ // }
8471
8510
  }
8472
8511
  }
8473
- console.log(block.transactions);
8474
8512
  // don't add empty block
8475
8513
  if (block.transactions.length === 0)
8476
8514
  return;
8477
8515
  const validators = await this.staticCall(addresses.validators, 'validators');
8478
- console.log({ validators });
8479
8516
  // block.validators = Object.keys(block.validators).reduce((set, key) => {
8480
8517
  // if (block.validators[key].active) {
8481
8518
  // push({
@@ -8495,7 +8532,6 @@ class Chain extends Contract {
8495
8532
  const node = await globalThis.peernet.prepareMessage(validator, data.encoded);
8496
8533
  try {
8497
8534
  const bw = await peer.request(node.encoded);
8498
- console.log({ bw });
8499
8535
  block.validators.push({
8500
8536
  address: validator,
8501
8537
  bw: bw.up + bw.down
@@ -8511,16 +8547,13 @@ class Chain extends Contract {
8511
8547
  }
8512
8548
  }
8513
8549
  }
8514
- console.log({ validators: block.validators });
8515
8550
  block.validators = block.validators.map(validator => {
8516
8551
  validator.reward = block.fees;
8517
8552
  validator.reward = validator.reward.add(block.reward);
8518
8553
  validator.reward = validator.reward.div(block.validators.length);
8519
- validator.reward = validator.reward.toString();
8520
8554
  delete validator.bw;
8521
8555
  return validator;
8522
8556
  });
8523
- console.log({ validators: block.validators });
8524
8557
  // block.validators = calculateValidatorReward(block.validators, block.fees)
8525
8558
  block.index = this.lastBlock?.index;
8526
8559
  if (block.index === undefined)
@@ -8528,12 +8561,15 @@ class Chain extends Contract {
8528
8561
  else
8529
8562
  block.index += 1;
8530
8563
  block.previousHash = this.lastBlock?.hash || '0x0';
8531
- block.timestamp = Date.now();
8532
- block.reward = block.reward.toString();
8533
- block.fees = block.fees.toString();
8564
+ // block.timestamp = Date.now()
8565
+ // block.reward = block.reward.toString()
8566
+ // block.fees = block.fees.toString()
8534
8567
  try {
8535
- await Promise.all(block.transactions
8536
- .map(async (transaction) => globalThis.transactionPoolStore.delete(transaction.hash)));
8568
+ block.transactions = await Promise.all(block.transactions
8569
+ .map(async (transaction) => {
8570
+ await globalThis.transactionPoolStore.delete(await transaction.hash());
8571
+ return transaction.decoded;
8572
+ }));
8537
8573
  let blockMessage = await new BlockMessage(block);
8538
8574
  const hash = await blockMessage.hash();
8539
8575
  await globalThis.peernet.put(hash, blockMessage.encoded, 'block');
@@ -8543,23 +8579,22 @@ class Chain extends Contract {
8543
8579
  globalThis.pubsub.publish('add-block', blockMessage.decoded);
8544
8580
  }
8545
8581
  catch (error) {
8582
+ console.log(error);
8546
8583
  throw new Error(`invalid block ${block}`);
8547
8584
  }
8548
8585
  // data = await this.#machine.execute(to, method, params)
8549
8586
  // transactionStore.put(message.hash, message.encoded)
8550
8587
  }
8551
- async #addTransaction(transaction) {
8552
- transaction = await new TransactionMessage(transaction);
8588
+ async #sendTransaction(transaction) {
8589
+ transaction = await new TransactionMessage(transaction.encoded);
8553
8590
  const hash = await transaction.hash();
8554
8591
  try {
8555
8592
  const has = await globalThis.transactionPoolStore.has(hash);
8556
8593
  if (!has) {
8557
8594
  await globalThis.transactionPoolStore.put(hash, transaction.encoded);
8558
- if (this.#participating && !this.#runningEpoch)
8559
- this.#runEpoch();
8560
8595
  }
8561
- else
8562
- globalThis.peernet.publish('invalid-transaction', hash);
8596
+ if (this.#participating && !this.#runningEpoch)
8597
+ this.#runEpoch();
8563
8598
  }
8564
8599
  catch (e) {
8565
8600
  console.log(e);
@@ -8574,7 +8609,8 @@ class Chain extends Contract {
8574
8609
  **/
8575
8610
  async sendTransaction(transaction) {
8576
8611
  const event = await super.sendTransaction(transaction);
8577
- this.#addTransaction(event.message.encoded);
8612
+ this.#sendTransaction(await new TransactionMessage(event.message.encoded));
8613
+ globalThis.peernet.publish('send-transaction', event.message.encoded);
8578
8614
  return event;
8579
8615
  }
8580
8616
  async addContract(transaction, contractMessage) {
@@ -1,5 +1,5 @@
1
- import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './node-browser-8791470c.js';
2
- import './contract-f76383c3.js';
1
+ import { c as commonjsGlobal, g as getDefaultExportFromCjs } from './node-browser-63d44d8e.js';
2
+ import './index-640d9f36.js';
3
3
 
4
4
  function commonjsRequire(path) {
5
5
  throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
@@ -1,5 +1,5 @@
1
- import { M as MultiWallet, e as encrypt, b as base58$1 } from './node-browser-8791470c.js';
2
- import './contract-f76383c3.js';
1
+ import { M as MultiWallet, e as encrypt, b as base58$1 } from './node-browser-63d44d8e.js';
2
+ import './index-640d9f36.js';
3
3
 
4
4
  /**
5
5
  * @params {String} network