@argonprotocol/mainchain 1.3.4 → 1.3.6

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.
@@ -261,10 +261,10 @@ var TxResult = (_class = class {
261
261
  var _bignumberjs = require('bignumber.js'); var BN = _interopRequireWildcard(_bignumberjs); var BN2 = _interopRequireWildcard(_bignumberjs);
262
262
  var { ROUND_FLOOR } = BN;
263
263
  var MICROGONS_PER_ARGON = 1e6;
264
- function formatArgons(x) {
265
- if (x === void 0 || x === null) return "na";
266
- const isNegative = x < 0;
267
- let format = BN.default.call(void 0, x.toString()).abs().div(MICROGONS_PER_ARGON).toFormat(2, ROUND_FLOOR);
264
+ function formatArgons(microgons) {
265
+ if (microgons === void 0 || microgons === null) return "na";
266
+ const isNegative = microgons < 0;
267
+ let format = BN.default.call(void 0, microgons.toString()).abs().div(MICROGONS_PER_ARGON).toFormat(2, ROUND_FLOOR);
268
268
  if (format.endsWith(".00")) {
269
269
  format = format.slice(0, -3);
270
270
  }
@@ -637,9 +637,13 @@ BLOCK #${header.number}, ${header.hash.toHuman()}`);
637
637
  }, _class4);
638
638
 
639
639
  // src/FrameCalculator.ts
640
- var FrameCalculator = class {
640
+ var FrameCalculator = class _FrameCalculator {
641
641
 
642
642
 
643
+
644
+ async load(client) {
645
+ return await this.getConfig(client);
646
+ }
643
647
  async getForTick(client, tick) {
644
648
  const { ticksBetweenFrames, biddingStartTick } = await this.getConfig(client);
645
649
  const ticksSinceMiningStart = tick - biddingStartTick;
@@ -647,9 +651,10 @@ var FrameCalculator = class {
647
651
  }
648
652
  async getTickRangeForFrame(client, frameId) {
649
653
  const { ticksBetweenFrames, biddingStartTick } = await this.getConfig(client);
650
- const startingTick = biddingStartTick + Math.floor(frameId * ticksBetweenFrames);
651
- const endingTick = startingTick + ticksBetweenFrames - 1;
652
- return [startingTick, endingTick];
654
+ return _FrameCalculator.calculateTickRangeForFrame(frameId, {
655
+ ticksBetweenFrames,
656
+ biddingStartTick
657
+ });
653
658
  }
654
659
  async getForHeader(client, header) {
655
660
  if (header.number.toNumber() === 0) return 0;
@@ -657,18 +662,30 @@ var FrameCalculator = class {
657
662
  if (tick === void 0) return void 0;
658
663
  return this.getForTick(client, tick);
659
664
  }
665
+ static frameToDateRange(frameId, config2) {
666
+ const [start, end] = _FrameCalculator.calculateTickRangeForFrame(frameId, config2);
667
+ return [new Date(start * config2.tickMillis), new Date(end * config2.tickMillis)];
668
+ }
669
+ static calculateTickRangeForFrame(frameId, config2) {
670
+ const { ticksBetweenFrames, biddingStartTick } = config2;
671
+ const startingTick = biddingStartTick + Math.floor(frameId * ticksBetweenFrames);
672
+ const endingTick = startingTick + ticksBetweenFrames - 1;
673
+ return [startingTick, endingTick];
674
+ }
660
675
  async getConfig(client) {
661
676
  this.miningConfig ??= await client.query.miningSlot.miningConfig().then((x) => ({
662
677
  ticksBetweenSlots: x.ticksBetweenSlots.toNumber(),
663
678
  slotBiddingStartAfterTicks: x.slotBiddingStartAfterTicks.toNumber()
664
679
  }));
665
680
  this.genesisTick ??= await client.query.ticks.genesisTick().then((x) => x.toNumber());
681
+ this.tickMillis ??= await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
666
682
  const config2 = this.miningConfig;
667
683
  const genesisTick = this.genesisTick;
668
684
  return {
669
685
  ticksBetweenFrames: config2.ticksBetweenSlots,
670
686
  slotBiddingStartAfterTicks: config2.slotBiddingStartAfterTicks,
671
687
  genesisTick,
688
+ tickMillis: this.tickMillis,
672
689
  biddingStartTick: genesisTick + config2.slotBiddingStartAfterTicks
673
690
  };
674
691
  }
@@ -1656,31 +1673,37 @@ var VaultMonitor = (_class8 = class {
1656
1673
 
1657
1674
  // src/CohortBidder.ts
1658
1675
  var CohortBidder = (_class9 = class {
1659
- constructor(accountset, cohortStartingFrameId, subaccounts, options) {;_class9.prototype.__init18.call(this);_class9.prototype.__init19.call(this);_class9.prototype.__init20.call(this);_class9.prototype.__init21.call(this);_class9.prototype.__init22.call(this);_class9.prototype.__init23.call(this);_class9.prototype.__init24.call(this);_class9.prototype.__init25.call(this);
1676
+ constructor(accountset, cohortStartingFrameId, subaccounts, options, callbacks) {;_class9.prototype.__init18.call(this);_class9.prototype.__init19.call(this);_class9.prototype.__init20.call(this);_class9.prototype.__init21.call(this);_class9.prototype.__init22.call(this);_class9.prototype.__init23.call(this);_class9.prototype.__init24.call(this);_class9.prototype.__init25.call(this);
1660
1677
  this.accountset = accountset;
1661
1678
  this.cohortStartingFrameId = cohortStartingFrameId;
1662
1679
  this.subaccounts = subaccounts;
1663
1680
  this.options = options;
1681
+ this.callbacks = callbacks;
1664
1682
  this.subaccounts.forEach((x) => {
1665
1683
  this.myAddresses.add(x.address);
1666
1684
  });
1667
1685
  }
1668
- get client() {
1686
+ get clientPromise() {
1669
1687
  return this.accountset.client;
1670
1688
  }
1671
1689
  __init18() {this.txFees = 0n}
1672
- __init19() {this.winningBids = []}
1690
+ __init19() {this.bidsAttempted = 0}
1691
+ __init20() {this.winningBids = []}
1692
+ __init21() {this.myAddresses = /* @__PURE__ */ new Set()}
1693
+ __init22() {this.currentBids = {
1694
+ bids: [],
1695
+ mostRecentBidTick: 0,
1696
+ atTick: 0,
1697
+ atBlockNumber: 0
1698
+ }}
1673
1699
 
1674
1700
 
1701
+ __init23() {this.isStopped = false}
1675
1702
 
1676
- __init20() {this.isStopped = false}
1677
- __init21() {this.needsRebid = false}
1678
- __init22() {this.lastBidTime = 0}
1703
+ __init24() {this.minIncrement = 10000n}
1679
1704
 
1680
- __init23() {this.minIncrement = 10000n}
1705
+ __init25() {this.lastBidTick = 0}
1681
1706
 
1682
- __init24() {this.lastBidBlockNumber = 0}
1683
- __init25() {this.myAddresses = /* @__PURE__ */ new Set()}
1684
1707
  async start() {
1685
1708
  console.log(`Starting cohort ${this.cohortStartingFrameId} bidder`, {
1686
1709
  maxBid: formatArgons(this.options.maxBid),
@@ -1690,7 +1713,7 @@ var CohortBidder = (_class9 = class {
1690
1713
  bidDelay: this.options.bidDelay,
1691
1714
  subaccounts: this.subaccounts
1692
1715
  });
1693
- const client = await this.client;
1716
+ const client = await this.clientPromise;
1694
1717
  this.minIncrement = client.consts.miningSlot.bidIncrements.toBigInt();
1695
1718
  this.nextCohortSize = await client.query.miningSlot.nextCohortSize().then((x) => x.toNumber());
1696
1719
  if (this.subaccounts.length > this.nextCohortSize) {
@@ -1700,14 +1723,22 @@ var CohortBidder = (_class9 = class {
1700
1723
  this.subaccounts.length = this.nextCohortSize;
1701
1724
  }
1702
1725
  this.millisPerTick = await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1726
+ let didStart = false;
1703
1727
  this.unsubscribe = await client.queryMulti(
1704
1728
  [
1705
1729
  client.query.miningSlot.bidsForNextSlotCohort,
1706
- client.query.miningSlot.nextFrameId
1730
+ client.query.miningSlot.nextFrameId,
1731
+ client.query.ticks.currentTick,
1732
+ client.query.system.number
1707
1733
  ],
1708
- async ([bids, nextFrameId]) => {
1734
+ async ([rawBids, nextFrameId, currentTick, blockNumber]) => {
1709
1735
  if (nextFrameId.toNumber() === this.cohortStartingFrameId) {
1710
- await this.checkWinningBids(bids);
1736
+ this.updateBidList(rawBids, blockNumber.toNumber(), currentTick.toNumber());
1737
+ if (!didStart) {
1738
+ didStart = true;
1739
+ this.scheduleEvaluation();
1740
+ void this.checkWinningBids();
1741
+ }
1711
1742
  }
1712
1743
  }
1713
1744
  );
@@ -1715,12 +1746,12 @@ var CohortBidder = (_class9 = class {
1715
1746
  async stop() {
1716
1747
  if (this.isStopped) return this.winningBids;
1717
1748
  this.isStopped = true;
1749
+ clearInterval(this.evaluateInterval);
1718
1750
  console.log("Stopping bidder for cohort", this.cohortStartingFrameId);
1719
- clearTimeout(this.retryTimeout);
1720
1751
  if (this.unsubscribe) {
1721
1752
  this.unsubscribe();
1722
1753
  }
1723
- const client = await this.client;
1754
+ const client = await this.clientPromise;
1724
1755
  const [nextFrameId, isBiddingOpen] = await client.queryMulti([
1725
1756
  client.query.miningSlot.nextFrameId,
1726
1757
  client.query.miningSlot.isNextSlotBiddingOpen
@@ -1737,58 +1768,63 @@ var CohortBidder = (_class9 = class {
1737
1768
  });
1738
1769
  }
1739
1770
  void await this.pendingRequest;
1740
- let header = await client.rpc.chain.getHeader();
1741
- let api = await client.at(header.hash);
1742
- while (true) {
1743
- const cohortStartingFrameId = await api.query.miningSlot.nextFrameId();
1744
- if (cohortStartingFrameId.toNumber() === this.cohortStartingFrameId) {
1745
- break;
1746
- }
1747
- header = await client.rpc.chain.getHeader(header.parentHash);
1748
- api = await client.at(header.hash);
1771
+ const currentFrameId = await client.query.miningSlot.nextFrameId();
1772
+ let blockNumber;
1773
+ if (currentFrameId.toNumber() > this.cohortStartingFrameId) {
1774
+ blockNumber = await client.query.miningSlot.frameStartBlockNumbers().then((x) => _optionalChain([x, 'access', _56 => _56[0], 'optionalAccess', _57 => _57.toNumber, 'call', _58 => _58()])) - 1;
1775
+ } else {
1776
+ blockNumber = await client.query.system.number().then((x) => x.toNumber());
1749
1777
  }
1750
- const bids = await api.query.miningSlot.bidsForNextSlotCohort();
1751
- this.updateSeatsWon(bids);
1778
+ const blockHash = await client.query.system.blockHash(blockNumber);
1779
+ const api = await client.at(blockHash);
1780
+ const rawBids = await api.query.miningSlot.bidsForNextSlotCohort();
1781
+ const currentTick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1782
+ this.updateBidList(rawBids, blockNumber, currentTick);
1752
1783
  console.log("Bidder stopped", {
1753
1784
  cohortStartingFrameId: this.cohortStartingFrameId,
1754
- blockNumber: header.number.toNumber(),
1755
- bids: this.winningBids
1785
+ blockNumber,
1786
+ winningBids: this.winningBids
1756
1787
  });
1757
1788
  return this.winningBids;
1758
1789
  }
1759
- async checkWinningBids(bids) {
1790
+ async checkWinningBids() {
1760
1791
  if (this.isStopped) return;
1761
- clearTimeout(this.retryTimeout);
1762
- this.updateSeatsWon(bids);
1763
- const winningBids = this.winningBids.length;
1764
- this.needsRebid = winningBids < this.subaccounts.length;
1765
- const client = await this.client;
1766
- const bestBlock = await client.rpc.chain.getBlockHash();
1767
- const api = await client.at(bestBlock);
1768
- const blockNumber = await api.query.system.number().then((x) => x.toNumber());
1769
- if (this.lastBidBlockNumber >= blockNumber) return;
1770
- if (this.pendingRequest) return;
1771
- const ticksSinceLastBid = Math.floor((Date.now() - this.lastBidTime) / this.millisPerTick);
1772
- if (ticksSinceLastBid < this.options.bidDelay && this.needsRebid) {
1773
- this.retryTimeout = setTimeout(() => void this.checkCurrentSeats(), this.millisPerTick);
1792
+ if (this.pendingRequest) {
1793
+ console.log("Current bid is still in progress, skipping this check");
1794
+ return;
1795
+ }
1796
+ if (this.currentBids.mostRecentBidTick < this.lastBidTick) {
1797
+ console.log(`Waiting for bids more recent than our last attempt.`, {
1798
+ ownAttemptedBidTick: this.lastBidTick,
1799
+ liveBidsTick: this.currentBids.mostRecentBidTick
1800
+ });
1801
+ return;
1802
+ }
1803
+ const bids = [...this.currentBids.bids];
1804
+ const bidsAtTick = this.currentBids.atTick;
1805
+ const blockNumber = this.currentBids.atBlockNumber;
1806
+ const winningBids = bids.filter((x) => this.myAddresses.has(x.address));
1807
+ if (winningBids.length >= this.subaccounts.length) {
1808
+ console.log(`No updates needed. Winning all remaining seats (${winningBids.length}).`);
1774
1809
  return;
1775
1810
  }
1776
- if (!this.needsRebid) return;
1777
1811
  console.log(
1778
- "Checking bids for cohort",
1779
- this.cohortStartingFrameId,
1780
- this.subaccounts.map((x) => x.index)
1812
+ `Checking bids for cohort ${this.cohortStartingFrameId}, Still trying for seats: ${this.subaccounts.length}`
1781
1813
  );
1782
- const winningAddresses = new Set(bids.map((x) => x.accountId.toHuman()));
1783
- let lowestBid = -this.options.bidIncrement;
1784
- if (bids.length) {
1785
- for (let i = bids.length - 1; i >= 0; i--) {
1786
- if (!this.myAddresses.has(bids[i].accountId.toHuman())) {
1787
- lowestBid = bids.at(i).bid.toBigInt();
1788
- break;
1814
+ const winningAddresses = new Set(winningBids.map((x) => x.address));
1815
+ let lowestBid;
1816
+ let myAllocatedBids = 0n;
1817
+ for (const bid of bids) {
1818
+ lowestBid ??= bid.bidMicrogons;
1819
+ if (this.myAddresses.has(bid.address)) {
1820
+ myAllocatedBids += bid.bidMicrogons;
1821
+ } else {
1822
+ if (bid.bidMicrogons < lowestBid) {
1823
+ lowestBid = bid.bidMicrogons;
1789
1824
  }
1790
1825
  }
1791
1826
  }
1827
+ lowestBid ??= -this.options.bidIncrement;
1792
1828
  let nextBid = lowestBid + this.options.bidIncrement;
1793
1829
  if (nextBid < this.options.minBid) {
1794
1830
  nextBid = this.options.minBid;
@@ -1800,39 +1836,59 @@ var CohortBidder = (_class9 = class {
1800
1836
  subaccounts: this.subaccounts,
1801
1837
  bidAmount: nextBid
1802
1838
  });
1803
- let availableBalanceForBids = await api.query.system.account(this.accountset.txSubmitterPair.address).then((x) => x.data.free.toBigInt());
1804
- for (const bid of bids) {
1805
- if (this.myAddresses.has(bid.accountId.toHuman())) {
1806
- availableBalanceForBids += bid.bid.toBigInt();
1807
- }
1808
- }
1839
+ let availableBalanceForBids = await this.accountset.submitterBalance();
1840
+ availableBalanceForBids += myAllocatedBids;
1809
1841
  const tip = _nullishCoalesce(this.options.tipPerTransaction, () => ( 0n));
1810
1842
  const feeEstimate = await fakeTx.feeEstimate(tip);
1811
- const feePlusTip = feeEstimate + tip;
1812
- let budgetForSeats = this.options.maxBudget - feePlusTip;
1843
+ const estimatedFeePlusTip = feeEstimate + tip;
1844
+ let budgetForSeats = this.options.maxBudget - estimatedFeePlusTip;
1813
1845
  if (budgetForSeats > availableBalanceForBids) {
1814
- budgetForSeats = availableBalanceForBids - feePlusTip;
1846
+ budgetForSeats = availableBalanceForBids - estimatedFeePlusTip;
1815
1847
  }
1816
1848
  if (nextBid < lowestBid) {
1817
1849
  console.log(
1818
- `Can't bid ${formatArgons(nextBid)}. Current lowest bid is ${formatArgons(lowestBid)}.`
1850
+ `Next bid within parameters is ${formatArgons(nextBid)}, but it's not enough. Current lowest bid is ${formatArgons(lowestBid)}.`
1819
1851
  );
1852
+ this.safeRecordParamsAdjusted({
1853
+ tick: bidsAtTick,
1854
+ blockNumber,
1855
+ maxSeats: 0,
1856
+ winningBidCount: winningBids.length,
1857
+ reason: "max-bid-too-low",
1858
+ availableBalanceForBids
1859
+ });
1820
1860
  return;
1821
1861
  }
1822
1862
  if (nextBid - lowestBid < Number(this.minIncrement)) {
1823
1863
  console.log(
1824
- `Can't make any more bids for ${this.cohortStartingFrameId} with given constraints.`,
1864
+ `Can't make any more bids for ${this.cohortStartingFrameId} with given constraints (next bid below min increment).`,
1825
1865
  {
1826
1866
  lowestCurrentBid: formatArgons(lowestBid),
1827
1867
  nextAttemptedBid: formatArgons(nextBid),
1828
1868
  maxBid: formatArgons(this.options.maxBid)
1829
1869
  }
1830
1870
  );
1871
+ this.safeRecordParamsAdjusted({
1872
+ tick: bidsAtTick,
1873
+ blockNumber,
1874
+ maxSeats: 0,
1875
+ winningBidCount: winningBids.length,
1876
+ reason: "max-bid-too-low",
1877
+ availableBalanceForBids
1878
+ });
1831
1879
  return;
1832
1880
  }
1833
1881
  const seatsInBudget = nextBid === 0n ? this.subaccounts.length : Number(budgetForSeats / nextBid);
1834
1882
  let accountsToUse = [...this.subaccounts];
1835
1883
  if (accountsToUse.length > seatsInBudget) {
1884
+ this.safeRecordParamsAdjusted({
1885
+ tick: bidsAtTick,
1886
+ blockNumber,
1887
+ maxSeats: this.subaccounts.length,
1888
+ winningBidCount: winningBids.length,
1889
+ reason: availableBalanceForBids - estimatedFeePlusTip < nextBid * BigInt(seatsInBudget) ? "insufficient-balance" : "max-budget-too-low",
1890
+ availableBalanceForBids
1891
+ });
1836
1892
  accountsToUse.sort((a, b) => {
1837
1893
  const isWinningA = winningAddresses.has(a.address);
1838
1894
  const isWinningB = winningAddresses.has(b.address);
@@ -1844,18 +1900,16 @@ var CohortBidder = (_class9 = class {
1844
1900
  });
1845
1901
  accountsToUse.length = seatsInBudget;
1846
1902
  }
1847
- if (accountsToUse.length > winningBids) {
1848
- this.pendingRequest = this.bid(nextBid, accountsToUse);
1903
+ if (accountsToUse.length > winningBids.length) {
1904
+ this.pendingRequest = this.submitBids(nextBid, accountsToUse);
1849
1905
  }
1850
- this.needsRebid = false;
1851
1906
  }
1852
- async bid(bidPerSeat, subaccounts) {
1853
- const prevLastBidTime = this.lastBidTime;
1907
+ async submitBids(microgonsPerSeat, subaccounts) {
1854
1908
  try {
1855
- this.lastBidTime = Date.now();
1909
+ this.bidsAttempted += subaccounts.length;
1856
1910
  const submitter = await this.accountset.createMiningBidTx({
1857
1911
  subaccounts,
1858
- bidAmount: bidPerSeat
1912
+ bidAmount: microgonsPerSeat
1859
1913
  });
1860
1914
  const tip = _nullishCoalesce(this.options.tipPerTransaction, () => ( 0n));
1861
1915
  const txResult = await submitter.submit({
@@ -1863,50 +1917,108 @@ var CohortBidder = (_class9 = class {
1863
1917
  useLatestNonce: true
1864
1918
  });
1865
1919
  const bidError = await txResult.inBlockPromise.then(() => void 0).catch((x) => x);
1866
- let blockNumber;
1867
- if (txResult.includedInBlock) {
1868
- const client = await this.client;
1869
- const api = await client.at(txResult.includedInBlock);
1870
- blockNumber = await api.query.system.number().then((x) => x.toNumber());
1920
+ const client = await this.clientPromise;
1921
+ let api = txResult.includedInBlock ? await client.at(txResult.includedInBlock) : client;
1922
+ this.lastBidTick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1923
+ const blockNumber = await api.query.system.number().then((x) => x.toNumber());
1924
+ const bidAtTick = this.lastBidTick;
1925
+ try {
1926
+ _optionalChain([this, 'access', _59 => _59.callbacks, 'optionalAccess', _60 => _60.onBidsSubmitted, 'optionalCall', _61 => _61({
1927
+ tick: bidAtTick,
1928
+ blockNumber,
1929
+ microgonsPerSeat,
1930
+ txFeePlusTip: _nullishCoalesce(txResult.finalFee, () => ( 0n)),
1931
+ submittedCount: subaccounts.length
1932
+ })]);
1933
+ } catch (error) {
1934
+ console.error("Error in onBidsSubmitted callback:", error);
1871
1935
  }
1872
1936
  const successfulBids = _nullishCoalesce(txResult.batchInterruptedIndex, () => ( subaccounts.length));
1873
1937
  this.txFees += _nullishCoalesce(txResult.finalFee, () => ( 0n));
1874
- if (blockNumber !== void 0) {
1875
- this.lastBidBlockNumber = Math.max(blockNumber, this.lastBidBlockNumber);
1876
- }
1877
- console.log("Done creating bids for cohort", {
1938
+ console.log("Result of bids for cohort", {
1878
1939
  successfulBids,
1879
- bidPerSeat,
1880
- blockNumber
1940
+ bidsPlaced: subaccounts.length,
1941
+ bidPerSeat: formatArgons(microgonsPerSeat),
1942
+ bidAtTick
1881
1943
  });
1882
- if (bidError) throw bidError;
1944
+ if (bidError) {
1945
+ try {
1946
+ _optionalChain([this, 'access', _62 => _62.callbacks, 'optionalAccess', _63 => _63.onBidsRejected, 'optionalCall', _64 => _64({
1947
+ tick: bidAtTick,
1948
+ blockNumber,
1949
+ microgonsPerSeat,
1950
+ submittedCount: subaccounts.length,
1951
+ rejectedCount: subaccounts.length - successfulBids,
1952
+ bidError
1953
+ })]);
1954
+ } catch (error) {
1955
+ console.error("Error in onBidsRejected callback:", error);
1956
+ }
1957
+ throw bidError;
1958
+ }
1883
1959
  } catch (err) {
1884
- this.lastBidTime = prevLastBidTime;
1885
1960
  console.error(`Error bidding for cohort ${this.cohortStartingFrameId}:`, err);
1886
- clearTimeout(this.retryTimeout);
1887
- this.retryTimeout = setTimeout(() => void this.checkCurrentSeats(), 1e3);
1888
1961
  } finally {
1889
1962
  this.pendingRequest = void 0;
1890
- }
1891
- if (this.needsRebid) {
1892
- this.needsRebid = false;
1893
- await this.checkCurrentSeats();
1963
+ this.scheduleEvaluation();
1894
1964
  }
1895
1965
  }
1896
- updateSeatsWon(next) {
1897
- this.winningBids.length = 0;
1898
- for (const x of next) {
1899
- const bid = x.bid.toBigInt();
1900
- const address = x.accountId.toHuman();
1901
- if (this.myAddresses.has(address)) {
1902
- this.winningBids.push({ address, bid });
1966
+ scheduleEvaluation() {
1967
+ const millisPerTick = this.millisPerTick;
1968
+ const delayTicks = Math.max(this.options.bidDelay, 1);
1969
+ const delay = delayTicks * millisPerTick;
1970
+ if (this.evaluateInterval) clearInterval(this.evaluateInterval);
1971
+ console.log(`Scheduling next evaluation in ${delay}ms`);
1972
+ this.evaluateInterval = setInterval(() => this.checkWinningBids().catch(console.error), delay);
1973
+ }
1974
+ updateBidList(rawBids, blockNumber, tick) {
1975
+ try {
1976
+ let mostRecentBidTick = 0;
1977
+ let hasDiffs = this.currentBids.bids.length !== rawBids.length;
1978
+ const bids = [];
1979
+ for (let i = 0; i < rawBids.length; i += 1) {
1980
+ const rawBid = rawBids[i];
1981
+ const bidAtTick = rawBid.bidAtTick.toNumber();
1982
+ if (bidAtTick > mostRecentBidTick) {
1983
+ mostRecentBidTick = bidAtTick;
1984
+ }
1985
+ const address = rawBid.accountId.toHuman();
1986
+ const bidMicrogons = rawBid.bid.toBigInt();
1987
+ if (!hasDiffs) {
1988
+ const existing = this.currentBids.bids[i];
1989
+ hasDiffs = _optionalChain([existing, 'optionalAccess', _65 => _65.address]) !== address || _optionalChain([existing, 'optionalAccess', _66 => _66.bidMicrogons]) !== bidMicrogons;
1990
+ }
1991
+ bids.push({
1992
+ address,
1993
+ bidMicrogons,
1994
+ bidAtTick
1995
+ });
1996
+ }
1997
+ if (blockNumber > this.currentBids.atBlockNumber && hasDiffs) {
1998
+ this.currentBids.bids = bids;
1999
+ this.currentBids.mostRecentBidTick = mostRecentBidTick;
2000
+ this.currentBids.atTick = tick;
2001
+ this.currentBids.atBlockNumber = blockNumber;
2002
+ this.winningBids = bids.filter((x) => this.myAddresses.has(x.address));
2003
+ console.log("Now winning bids:", this.winningBids.length);
2004
+ if (_optionalChain([this, 'access', _67 => _67.callbacks, 'optionalAccess', _68 => _68.onBidsUpdated])) {
2005
+ this.callbacks.onBidsUpdated({
2006
+ bids: this.winningBids,
2007
+ atBlockNumber: blockNumber,
2008
+ tick: mostRecentBidTick
2009
+ });
2010
+ }
1903
2011
  }
2012
+ } catch (err) {
2013
+ console.error("Error processing updated bids list:", err);
1904
2014
  }
1905
2015
  }
1906
- async checkCurrentSeats() {
1907
- const client = await this.client;
1908
- const bids = await client.query.miningSlot.bidsForNextSlotCohort();
1909
- await this.checkWinningBids(bids);
2016
+ safeRecordParamsAdjusted(args) {
2017
+ try {
2018
+ _optionalChain([this, 'access', _69 => _69.callbacks, 'optionalAccess', _70 => _70.onBidParamsAdjusted, 'optionalCall', _71 => _71(args)]);
2019
+ } catch (err) {
2020
+ console.error("Error in onBidParamsAdjusted callback:", err);
2021
+ }
1910
2022
  }
1911
2023
  }, _class9);
1912
2024
 
@@ -2009,7 +2121,7 @@ var BidPool = (_class10 = class {
2009
2121
  const { frameId: rawFrameId } = event.data;
2010
2122
  this.lastDistributedFrameId = rawFrameId.toNumber();
2011
2123
  this.bidPoolAmount = await this.getBidPool();
2012
- _optionalChain([this, 'access', _56 => _56.FrameSubscriptions, 'access', _57 => _57[rawFrameId.toNumber()], 'optionalCall', _58 => _58()]);
2124
+ _optionalChain([this, 'access', _72 => _72.FrameSubscriptions, 'access', _73 => _73[rawFrameId.toNumber()], 'optionalCall', _74 => _74()]);
2013
2125
  const entrant = await api.query.liquidityPools.vaultPoolsByFrame(rawFrameId);
2014
2126
  this.loadFrameData(rawFrameId.toNumber(), entrant);
2015
2127
  this.printDebounce();
@@ -2055,7 +2167,7 @@ var BidPool = (_class10 = class {
2055
2167
  const tx = client.tx.liquidityPools.bondArgons(vaultId, amount);
2056
2168
  const txSubmitter = new TxSubmitter(client, tx, this.keypair);
2057
2169
  const affordability = await txSubmitter.canAfford({
2058
- tip: _optionalChain([options, 'optionalAccess', _59 => _59.tip]),
2170
+ tip: _optionalChain([options, 'optionalAccess', _75 => _75.tip]),
2059
2171
  unavailableBalance: amount
2060
2172
  });
2061
2173
  if (!affordability.canAfford) {
@@ -2066,7 +2178,7 @@ var BidPool = (_class10 = class {
2066
2178
  throw new Error("Insufficient balance to bond argons to liquidity pool");
2067
2179
  }
2068
2180
  const result = await txSubmitter.submit({
2069
- tip: _optionalChain([options, 'optionalAccess', _60 => _60.tip]),
2181
+ tip: _optionalChain([options, 'optionalAccess', _76 => _76.tip]),
2070
2182
  useLatestNonce: true
2071
2183
  });
2072
2184
  await result.inBlockPromise;
@@ -2195,7 +2307,7 @@ Raising Funds (Frame ${this.nextFrameId + 1}):`);
2195
2307
  this.poolVaultCapitalByFrame ??= {};
2196
2308
  this.poolVaultCapitalByFrame[frameId] ??= {};
2197
2309
  this.poolVaultCapitalByFrame[frameId][vaultId] ??= {
2198
- activatedCapital: _nullishCoalesce(_nullishCoalesce(data.activatedCapital, () => ( _optionalChain([data, 'access', _61 => _61.contributors, 'optionalAccess', _62 => _62.reduce, 'call', _63 => _63((a, b) => a + b.amount, 0n)]))), () => ( 0n))
2310
+ activatedCapital: _nullishCoalesce(_nullishCoalesce(data.activatedCapital, () => ( _optionalChain([data, 'access', _77 => _77.contributors, 'optionalAccess', _78 => _78.reduce, 'call', _79 => _79((a, b) => a + b.amount, 0n)]))), () => ( 0n))
2199
2311
  };
2200
2312
  Object.assign(this.poolVaultCapitalByFrame[frameId][vaultId], filterUndefined(data));
2201
2313
  }
@@ -2283,7 +2395,7 @@ var BitcoinLocks = class _BitcoinLocks {
2283
2395
  const client = await this.client;
2284
2396
  const bitcoinNetwork = await client.query.bitcoinUtxos.bitcoinNetwork();
2285
2397
  return {
2286
- releaseExpirationBlocks: client.consts.bitcoinLocks.lockReleaseCosignDeadlineBlocks.toNumber(),
2398
+ lockReleaseCosignDeadlineFrames: client.consts.bitcoinLocks.lockReleaseCosignDeadlineFrames.toNumber(),
2287
2399
  pendingConfirmationExpirationBlocks: client.consts.bitcoinUtxos.maxPendingConfirmationBlocks.toNumber(),
2288
2400
  tickDurationMillis: await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber()),
2289
2401
  bitcoinNetwork
@@ -2291,7 +2403,7 @@ var BitcoinLocks = class _BitcoinLocks {
2291
2403
  }
2292
2404
  async getBitcoinConfirmedBlockHeight() {
2293
2405
  const client = await this.client;
2294
- return await client.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => _nullishCoalesce(_optionalChain([x, 'access', _64 => _64.value, 'optionalAccess', _65 => _65.blockHeight, 'access', _66 => _66.toNumber, 'call', _67 => _67()]), () => ( 0)));
2406
+ return await client.query.bitcoinUtxos.confirmedBitcoinBlockTip().then((x) => _nullishCoalesce(_optionalChain([x, 'access', _80 => _80.value, 'optionalAccess', _81 => _81.blockHeight, 'access', _82 => _82.toNumber, 'call', _83 => _83()]), () => ( 0)));
2295
2407
  }
2296
2408
  /**
2297
2409
  * Gets the UTXO reference by ID.
@@ -2324,19 +2436,18 @@ var BitcoinLocks = class _BitcoinLocks {
2324
2436
  const blockHash = await client.rpc.chain.getBlockHash(atHeight);
2325
2437
  client = await client.at(blockHash);
2326
2438
  }
2327
- const locksPendingRelease = await client.query.bitcoinLocks.locksPendingReleaseByUtxoId();
2328
- for (const [id, request] of locksPendingRelease.entries()) {
2329
- if (id.toNumber() === utxoId) {
2330
- return {
2331
- toScriptPubkey: request.toScriptPubkey.toHex(),
2332
- bitcoinNetworkFee: request.bitcoinNetworkFee.toBigInt(),
2333
- dueBlockHeight: request.cosignDueBlock.toNumber(),
2334
- vaultId: request.vaultId.toNumber(),
2335
- redemptionPrice: request.redemptionPrice.toBigInt()
2336
- };
2337
- }
2439
+ const requestMaybe = await client.query.bitcoinLocks.lockReleaseRequestsByUtxoId(utxoId);
2440
+ if (!requestMaybe.isSome) {
2441
+ return void 0;
2338
2442
  }
2339
- return void 0;
2443
+ const request = requestMaybe.unwrap();
2444
+ return {
2445
+ toScriptPubkey: request.toScriptPubkey.toHex(),
2446
+ bitcoinNetworkFee: request.bitcoinNetworkFee.toBigInt(),
2447
+ dueFrame: request.cosignDueFrame.toNumber(),
2448
+ vaultId: request.vaultId.toNumber(),
2449
+ redemptionPrice: request.redemptionPrice.toBigInt()
2450
+ };
2340
2451
  }
2341
2452
  async submitVaultSignature(args) {
2342
2453
  const { utxoId, vaultSignature, argonKeyring, txProgressCallback } = args;
@@ -2425,7 +2536,7 @@ var BitcoinLocks = class _BitcoinLocks {
2425
2536
  const atHeight = header.number.toNumber();
2426
2537
  this.getVaultCosignSignature(utxoId, atHeight).then((signature) => {
2427
2538
  if (signature) {
2428
- _optionalChain([unsub, 'optionalCall', _68 => _68()]);
2539
+ _optionalChain([unsub, 'optionalCall', _84 => _84()]);
2429
2540
  clearTimeout(timeout);
2430
2541
  resolve({ signature, blockHeight: atHeight });
2431
2542
  }
@@ -2435,7 +2546,7 @@ var BitcoinLocks = class _BitcoinLocks {
2435
2546
  });
2436
2547
  if (waitForSignatureMillis !== -1) {
2437
2548
  timeout = setTimeout(() => {
2438
- _optionalChain([unsub, 'optionalCall', _69 => _69()]);
2549
+ _optionalChain([unsub, 'optionalCall', _85 => _85()]);
2439
2550
  reject(new Error(`Timeout waiting for cosign signature for UTXO ID ${utxoId}`));
2440
2551
  }, waitForSignatureMillis);
2441
2552
  }
@@ -2506,7 +2617,8 @@ var BitcoinLocks = class _BitcoinLocks {
2506
2617
  argonKeyring
2507
2618
  );
2508
2619
  const marketPrice = await this.getMarketRate(BigInt(satoshis));
2509
- const securityFee = vault.calculateBitcoinFee(marketPrice);
2620
+ const isVaultOwner = argonKeyring.address === vault.operatorAccountId;
2621
+ const securityFee = isVaultOwner ? 0n : vault.calculateBitcoinFee(marketPrice);
2510
2622
  const { canAfford, availableBalance, txFee } = await submitter.canAfford({
2511
2623
  tip,
2512
2624
  unavailableBalance: securityFee + (_nullishCoalesce(args.reducedBalanceBy, () => ( 0n))),
@@ -2519,17 +2631,8 @@ var BitcoinLocks = class _BitcoinLocks {
2519
2631
  }
2520
2632
  return { tx, securityFee, txFee };
2521
2633
  }
2522
- async initializeLock(args) {
2523
- const { argonKeyring, tip = 0n, txProgressCallback } = args;
2634
+ async getBitcoinLockFromTxResult(txResult) {
2524
2635
  const client = await this.client;
2525
- const { tx, securityFee } = await this.createInitializeLockTx(args);
2526
- const submitter = new TxSubmitter(client, tx, argonKeyring);
2527
- const txResult = await submitter.submit({
2528
- waitForBlock: true,
2529
- logResults: true,
2530
- tip,
2531
- txProgressCallback
2532
- });
2533
2636
  const blockHash = await txResult.inBlockPromise;
2534
2637
  const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
2535
2638
  const utxoId = await _asyncNullishCoalesce(await this.getUtxoIdFromEvents(txResult.events), async () => ( 0));
@@ -2540,7 +2643,26 @@ var BitcoinLocks = class _BitcoinLocks {
2540
2643
  if (!lock) {
2541
2644
  throw new Error(`Lock with ID ${utxoId} not found after initialization`);
2542
2645
  }
2543
- return { lock, createdAtHeight: blockHeight, txResult, securityFee };
2646
+ return { lock, createdAtHeight: blockHeight, txResult };
2647
+ }
2648
+ async initializeLock(args) {
2649
+ const { argonKeyring, tip = 0n, txProgressCallback } = args;
2650
+ const client = await this.client;
2651
+ const { tx, securityFee } = await this.createInitializeLockTx(args);
2652
+ const submitter = new TxSubmitter(client, tx, argonKeyring);
2653
+ const txResult = await submitter.submit({
2654
+ waitForBlock: true,
2655
+ logResults: true,
2656
+ tip,
2657
+ txProgressCallback
2658
+ });
2659
+ const { lock, createdAtHeight } = await this.getBitcoinLockFromTxResult(txResult);
2660
+ return {
2661
+ lock,
2662
+ createdAtHeight,
2663
+ txResult,
2664
+ securityFee
2665
+ };
2544
2666
  }
2545
2667
  async requiredSatoshisForArgonLiquidity(argonAmount) {
2546
2668
  const marketRatePerBitcoin = await this.getMarketRate(SATS_PER_BTC);
@@ -2845,4 +2967,4 @@ async function getClient(host) {
2845
2967
 
2846
2968
 
2847
2969
  exports.WageProtector = WageProtector; exports.setConfig = setConfig; exports.getConfig = getConfig; exports.TxSubmitter = TxSubmitter; exports.TxResult = TxResult; exports.MICROGONS_PER_ARGON = MICROGONS_PER_ARGON; exports.formatArgons = formatArgons; exports.formatPercent = formatPercent; exports.filterUndefined = filterUndefined; exports.gettersToObject = gettersToObject; exports.toFixedNumber = toFixedNumber; exports.convertNumberToFixedU128 = convertNumberToFixedU128; exports.convertFixedU128ToBigNumber = convertFixedU128ToBigNumber; exports.convertPermillToBigNumber = convertPermillToBigNumber; exports.convertNumberToPermill = convertNumberToPermill; exports.eventDataToJson = eventDataToJson; exports.dispatchErrorToString = dispatchErrorToString; exports.ExtrinsicError = ExtrinsicError2; exports.dispatchErrorToExtrinsicError = dispatchErrorToExtrinsicError; exports.checkForExtrinsicSuccess = checkForExtrinsicSuccess; exports.JsonExt = JsonExt; exports.createNanoEvents = createNanoEvents; exports.TypedEmitter = TypedEmitter; exports.AccountRegistry = AccountRegistry; exports.getTickFromHeader = getTickFromHeader; exports.getAuthorFromHeader = getAuthorFromHeader; exports.BlockWatch = BlockWatch; exports.FrameCalculator = FrameCalculator; exports.AccountMiners = AccountMiners; exports.Accountset = Accountset; exports.parseSubaccountRange = parseSubaccountRange; exports.MiningBids = MiningBids; exports.Vault = Vault; exports.VaultMonitor = VaultMonitor; exports.CohortBidder = CohortBidder; exports.BidPool = BidPool; exports.SATS_PER_BTC = SATS_PER_BTC; exports.BitcoinLocks = BitcoinLocks; exports.keyringFromSuri = keyringFromSuri; exports.createKeyringPair = createKeyringPair; exports.Keyring = _api.Keyring; exports.decodeAddress = _utilcrypto.decodeAddress; exports.mnemonicGenerate = _utilcrypto.mnemonicGenerate; exports.waitForLoad = waitForLoad; exports.getClient = getClient; exports.u8aToHex = _util.u8aToHex; exports.hexToU8a = _util.hexToU8a; exports.u8aEq = _util.u8aEq; exports.GenericEvent = _generic.GenericEvent; exports.GenericBlock = _generic.GenericBlock; exports.GenericAddress = _generic.GenericAddress; exports.BTreeMap = _typescodec.BTreeMap; exports.Bytes = _typescodec.Bytes; exports.Compact = _typescodec.Compact; exports.Enum = _typescodec.Enum; exports.Null = _typescodec.Null; exports.Option = _typescodec.Option; exports.Result = _typescodec.Result; exports.Bool = _typescodec.Bool; exports.Tuple = _typescodec.Tuple; exports.Range = _typescodec.Range; exports.Struct = _typescodec.Struct; exports.Text = _typescodec.Text; exports.U256 = _typescodec.U256; exports.U8aFixed = _typescodec.U8aFixed; exports.Vec = _typescodec.Vec; exports.bool = _typescodec.bool; exports.i128 = _typescodec.i128; exports.u128 = _typescodec.u128; exports.u16 = _typescodec.u16; exports.u32 = _typescodec.u32; exports.u64 = _typescodec.u64; exports.u8 = _typescodec.u8;
2848
- //# sourceMappingURL=chunk-W5SOPU7I.cjs.map
2970
+ //# sourceMappingURL=chunk-U6J3AWYW.cjs.map