@argonprotocol/mainchain 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -56,7 +56,7 @@ var WageProtector = class _WageProtector {
56
56
  new _WageProtector({
57
57
  argonUsdTargetPrice: cpi.value.argonUsdTargetPrice.toBigInt(),
58
58
  argonUsdPrice: cpi.value.argonUsdPrice.toBigInt(),
59
- finalizedBlock: Buffer.from(finalizedBlock),
59
+ finalizedBlock: new Uint8Array(finalizedBlock),
60
60
  tick: cpi.value.tick.toBigInt()
61
61
  })
62
62
  );
@@ -81,9 +81,29 @@ var WageProtector = class _WageProtector {
81
81
  }
82
82
  };
83
83
 
84
+ // src/config.ts
85
+ var config = {};
86
+ function getEnvVar(key) {
87
+ if (typeof process !== "undefined" && process.env) {
88
+ return process.env[key];
89
+ }
90
+ return void 0;
91
+ }
92
+ function setConfig(newConfig) {
93
+ config = { ...config, ...newConfig };
94
+ }
95
+ function getConfig() {
96
+ return {
97
+ debug: config.debug ?? getEnvVar("DEBUG") === "true",
98
+ keysVersion: config.keysVersion ?? (getEnvVar("KEYS_VERSION") ? parseInt(getEnvVar("KEYS_VERSION")) : void 0),
99
+ keysMnemonic: config.keysMnemonic ?? getEnvVar("KEYS_MNEMONIC"),
100
+ subaccountRange: config.subaccountRange ?? getEnvVar("SUBACCOUNT_RANGE") ?? "0-9"
101
+ };
102
+ }
103
+
84
104
  // src/TxSubmitter.ts
85
105
  function logExtrinsicResult(result) {
86
- if (process.env.DEBUG) {
106
+ if (getConfig().debug) {
87
107
  const json = result.status.toJSON();
88
108
  const status = Object.keys(json)[0];
89
109
  console.debug('Transaction update: "%s"', status, json[status]);
@@ -103,18 +123,21 @@ var TxSubmitter = class {
103
123
  const { tip, unavailableBalance } = options;
104
124
  const account = await this.client.query.system.account(this.pair.address);
105
125
  let availableBalance = account.data.free.toBigInt();
126
+ const userBalance = availableBalance;
106
127
  if (unavailableBalance) {
107
128
  availableBalance -= unavailableBalance;
108
129
  }
109
130
  const existentialDeposit = options.includeExistentialDeposit ? this.client.consts.balances.existentialDeposit.toBigInt() : 0n;
110
131
  const fees = await this.feeEstimate(tip);
111
132
  const totalCharge = fees + (tip ?? 0n);
112
- const canAfford = availableBalance > totalCharge + existentialDeposit;
113
- return { canAfford, availableBalance, txFee: fees };
133
+ const canAfford = availableBalance >= totalCharge + existentialDeposit;
134
+ return { canAfford, availableBalance: userBalance, txFee: fees };
114
135
  }
115
136
  async submit(options = {}) {
116
- const { logResults } = options;
137
+ const { logResults, waitForBlock, useLatestNonce, ...apiOptions } = options;
138
+ await waitForLoad();
117
139
  const result = new TxResult(this.client, logResults);
140
+ result.txProgressCallback = options.txProgressCallback;
118
141
  let toHuman = this.tx.toHuman().method;
119
142
  let txString = [];
120
143
  let api = formatCall(toHuman);
@@ -132,12 +155,12 @@ var TxSubmitter = class {
132
155
  args.push(toHuman.args);
133
156
  }
134
157
  args.unshift(txString.join("->"));
135
- if (options.useLatestNonce && !options.nonce) {
136
- options.nonce = await this.client.rpc.system.accountNextIndex(this.pair.address);
158
+ if (useLatestNonce && !apiOptions.nonce) {
159
+ apiOptions.nonce = await this.client.rpc.system.accountNextIndex(this.pair.address);
137
160
  }
138
- console.log("Submitting transaction:", ...args);
139
- await this.tx.signAndSend(this.pair, options, result.onResult.bind(result));
140
- if (options.waitForBlock) {
161
+ console.log("Submitting transaction from %s:", this.pair.address, ...args);
162
+ await this.tx.signAndSend(this.pair, apiOptions, result.onResult.bind(result));
163
+ if (waitForBlock) {
141
164
  await result.inBlockPromise;
142
165
  }
143
166
  return result;
@@ -180,6 +203,7 @@ var TxResult = class {
180
203
  * The fee tip paid for the transaction.
181
204
  */
182
205
  finalFeeTip;
206
+ txProgressCallback;
183
207
  inBlockResolve;
184
208
  inBlockReject;
185
209
  finalizedResolve;
@@ -191,7 +215,7 @@ var TxResult = class {
191
215
  }
192
216
  const { events, status, dispatchError, isFinalized } = result;
193
217
  if (status.isInBlock) {
194
- this.includedInBlock = Buffer.from(status.asInBlock);
218
+ this.includedInBlock = new Uint8Array(status.asInBlock);
195
219
  let encounteredError = dispatchError;
196
220
  let batchErrorIndex;
197
221
  for (const event of events) {
@@ -211,12 +235,21 @@ var TxResult = class {
211
235
  const error = dispatchErrorToExtrinsicError(this.client, encounteredError, batchErrorIndex);
212
236
  this.reject(error);
213
237
  } else {
214
- this.inBlockResolve(Buffer.from(status.asInBlock));
238
+ this.inBlockResolve(new Uint8Array(status.asInBlock));
215
239
  }
216
240
  }
217
241
  if (isFinalized) {
218
242
  this.finalizedResolve(status.asFinalized);
219
243
  }
244
+ if (this.txProgressCallback) {
245
+ let percent = 0;
246
+ if (result.status.isBroadcast) {
247
+ percent = 50;
248
+ } else if (result.status.isInBlock) {
249
+ percent = 100;
250
+ }
251
+ this.txProgressCallback(percent, this);
252
+ }
220
253
  }
221
254
  reject(error) {
222
255
  this.inBlockReject(error);
@@ -271,10 +304,11 @@ async function gettersToObject(obj) {
271
304
  }
272
305
  return result;
273
306
  }
274
- function toFixedNumber(value, base) {
275
- const decimalFactor = new BigNumber(10).pow(base);
276
- const rawValue = new BigNumber(value.toString());
277
- return BigInt(rawValue.times(decimalFactor).toFixed(0, ROUND_FLOOR));
307
+ function toFixedNumber(value, decimals) {
308
+ const factor = new BigNumber(10).pow(decimals);
309
+ const bn = new BigNumber(value);
310
+ const int = bn.times(factor).integerValue(BigNumber.ROUND_DOWN);
311
+ return BigInt(int.toFixed(0));
278
312
  }
279
313
  function convertNumberToFixedU128(value) {
280
314
  return toFixedNumber(value, 18);
@@ -356,8 +390,12 @@ var JsonExt = class {
356
390
  if (typeof v === "bigint") {
357
391
  return `${v}n`;
358
392
  }
359
- if (Buffer.isBuffer(v)) {
360
- return Buffer.from(v).toJSON();
393
+ if (v instanceof Uint8Array) {
394
+ return {
395
+ type: "Buffer",
396
+ data: Array.from(v)
397
+ // Convert Uint8Array to an array of numbers
398
+ };
361
399
  }
362
400
  return v;
363
401
  },
@@ -370,7 +408,7 @@ var JsonExt = class {
370
408
  return BigInt(v.slice(0, -1));
371
409
  }
372
410
  if (typeof v === "object" && v !== null && v.type === "Buffer" && Array.isArray(v.data)) {
373
- return Buffer.from(v.data);
411
+ return Uint8Array.from(v.data);
374
412
  }
375
413
  return v;
376
414
  });
@@ -412,9 +450,6 @@ var AccountRegistry = class _AccountRegistry {
412
450
  static factory = (name) => new _AccountRegistry(name);
413
451
  };
414
452
 
415
- // src/Accountset.ts
416
- import * as process2 from "node:process";
417
-
418
453
  // src/BlockWatch.ts
419
454
  function getTickFromHeader(client, header) {
420
455
  for (const x of header.digest.logs) {
@@ -628,13 +663,13 @@ var FrameCalculator = class {
628
663
  slotBiddingStartAfterTicks: x.slotBiddingStartAfterTicks.toNumber()
629
664
  }));
630
665
  this.genesisTick ??= await client.query.ticks.genesisTick().then((x) => x.toNumber());
631
- const config = this.miningConfig;
666
+ const config2 = this.miningConfig;
632
667
  const genesisTick = this.genesisTick;
633
668
  return {
634
- ticksBetweenFrames: config.ticksBetweenSlots,
635
- slotBiddingStartAfterTicks: config.slotBiddingStartAfterTicks,
669
+ ticksBetweenFrames: config2.ticksBetweenSlots,
670
+ slotBiddingStartAfterTicks: config2.slotBiddingStartAfterTicks,
636
671
  genesisTick,
637
- biddingStartTick: genesisTick + config.slotBiddingStartAfterTicks
672
+ biddingStartTick: genesisTick + config2.slotBiddingStartAfterTicks
638
673
  };
639
674
  }
640
675
  };
@@ -645,10 +680,10 @@ var AccountMiners = class _AccountMiners {
645
680
  this.accountset = accountset;
646
681
  this.options = options;
647
682
  this.frameCalculator = new FrameCalculator();
648
- for (const seat of registeredMiners) {
649
- this.trackedAccountsByAddress[seat.address] = {
650
- startingFrameId: seat.startingFrameId,
651
- subaccountIndex: seat.subaccountIndex
683
+ for (const miner of registeredMiners) {
684
+ this.trackedAccountsByAddress[miner.address] = {
685
+ startingFrameId: miner.seat.startingFrameId,
686
+ subaccountIndex: miner.subaccountIndex
652
687
  };
653
688
  }
654
689
  }
@@ -760,6 +795,7 @@ var AccountMiners = class _AccountMiners {
760
795
  };
761
796
 
762
797
  // src/Accountset.ts
798
+ import { u8aToHex } from "@polkadot/util";
763
799
  var Accountset = class {
764
800
  txSubmitterPair;
765
801
  isProxy = false;
@@ -882,7 +918,7 @@ var Accountset = class {
882
918
  const index = indexRaw.toNumber();
883
919
  const bidAmount = bidAmountsByFrame[frameId]?.[index];
884
920
  addressToMiningIndex[address] = {
885
- frameId,
921
+ startingFrameId: frameId,
886
922
  index,
887
923
  bidAmount: bidAmount ?? 0n
888
924
  };
@@ -892,7 +928,7 @@ var Accountset = class {
892
928
  const cohort = addressToMiningIndex[address];
893
929
  let isLastDay = false;
894
930
  if (cohort !== void 0) {
895
- isLastDay = nextFrameId.toNumber() - cohort.frameId === 10;
931
+ isLastDay = nextFrameId.toNumber() - cohort.startingFrameId === 10;
896
932
  }
897
933
  return {
898
934
  address,
@@ -1021,11 +1057,9 @@ var Accountset = class {
1021
1057
  await client.disconnect();
1022
1058
  }
1023
1059
  keys(keysVersion) {
1024
- let version = keysVersion ?? 0;
1025
- if (process2.env.KEYS_VERSION) {
1026
- version = parseInt(process2.env.KEYS_VERSION) ?? 0;
1027
- }
1028
- const seedMnemonic = this.sessionKeyMnemonic ?? process2.env.KEYS_MNEMONIC;
1060
+ const config2 = getConfig();
1061
+ let version = keysVersion ?? config2.keysVersion ?? 0;
1062
+ const seedMnemonic = this.sessionKeyMnemonic ?? config2.keysMnemonic;
1029
1063
  if (!seedMnemonic) {
1030
1064
  throw new Error("KEYS_MNEMONIC environment variable not set. Cannot derive keys.");
1031
1065
  }
@@ -1040,12 +1074,12 @@ var Accountset = class {
1040
1074
  return {
1041
1075
  seal: {
1042
1076
  privateKey: blockSealKey,
1043
- publicKey: `0x${Buffer.from(blockSealAccount.publicKey).toString("hex")}`,
1077
+ publicKey: u8aToHex(blockSealAccount.publicKey),
1044
1078
  rawPublicKey: blockSealAccount.publicKey
1045
1079
  },
1046
1080
  gran: {
1047
1081
  privateKey: granKey,
1048
- publicKey: `0x${Buffer.from(grandpaAccount.publicKey).toString("hex")}`,
1082
+ publicKey: u8aToHex(grandpaAccount.publicKey),
1049
1083
  rawPublicKey: grandpaAccount.publicKey
1050
1084
  }
1051
1085
  };
@@ -1148,10 +1182,11 @@ var Accountset = class {
1148
1182
  };
1149
1183
  function getDefaultSubaccountRange() {
1150
1184
  try {
1151
- return parseSubaccountRange(process2.env.SUBACCOUNT_RANGE ?? "0-9");
1185
+ const config2 = getConfig();
1186
+ return parseSubaccountRange(config2.subaccountRange ?? "0-9");
1152
1187
  } catch {
1153
1188
  console.error(
1154
- "Failed to parse SUBACCOUNT_RANGE environment variable. Defaulting to 0-9. Please check the format of the SUBACCOUNT_RANGE variable."
1189
+ "Failed to parse SUBACCOUNT_RANGE configuration. Defaulting to 0-9. Please check the format of the subaccountRange config value."
1155
1190
  );
1156
1191
  return Array.from({ length: 10 }, (_, i) => i);
1157
1192
  }
@@ -1190,7 +1225,7 @@ var MiningBids = class {
1190
1225
  nextCohort = [];
1191
1226
  async maxCohortSize() {
1192
1227
  const client = await this.client;
1193
- return client.consts.miningSlot.maxCohortSize.toNumber();
1228
+ return client.query.miningSlot.nextCohortSize().then((x) => x.toNumber());
1194
1229
  }
1195
1230
  async onCohortChange(options) {
1196
1231
  const { onBiddingStart, onBiddingEnd } = options;
@@ -1265,12 +1300,35 @@ var MiningBids = class {
1265
1300
  // src/Vault.ts
1266
1301
  import BigNumber2, * as BN2 from "bignumber.js";
1267
1302
  import bs58check from "bs58check";
1303
+ import { hexToU8a } from "@polkadot/util";
1268
1304
  var { ROUND_FLOOR: ROUND_FLOOR2 } = BN2;
1269
1305
  var Vault = class _Vault {
1270
1306
  constructor(id, vault, tickDuration) {
1271
1307
  this.tickDuration = tickDuration;
1308
+ this.vaultId = id;
1309
+ this.openedTick = vault.openedTick.toNumber();
1310
+ this.openedDate = new Date(this.openedTick * this.tickDuration);
1311
+ this.argonsScheduledForRelease = /* @__PURE__ */ new Map();
1312
+ this.load(vault);
1313
+ }
1314
+ securitization;
1315
+ argonsLocked;
1316
+ argonsPendingActivation;
1317
+ argonsScheduledForRelease;
1318
+ terms;
1319
+ operatorAccountId;
1320
+ isClosed;
1321
+ vaultId;
1322
+ pendingTerms;
1323
+ pendingTermsChangeTick;
1324
+ openedDate;
1325
+ openedTick;
1326
+ securitizationRatio;
1327
+ load(vault) {
1272
1328
  this.securitization = vault.securitization.toBigInt();
1273
- this.securitizationRatio = convertFixedU128ToBigNumber(vault.securitizationRatio.toBigInt());
1329
+ this.securitizationRatio = convertFixedU128ToBigNumber(
1330
+ vault.securitizationRatio.toBigInt()
1331
+ ).toNumber();
1274
1332
  this.argonsLocked = vault.argonsLocked.toBigInt();
1275
1333
  this.argonsPendingActivation = vault.argonsPendingActivation.toBigInt();
1276
1334
  if (vault.argonsScheduledForRelease.size > 0) {
@@ -1290,7 +1348,6 @@ var Vault = class _Vault {
1290
1348
  };
1291
1349
  this.operatorAccountId = vault.operatorAccountId.toString();
1292
1350
  this.isClosed = vault.isClosed.valueOf();
1293
- this.vaultId = id;
1294
1351
  if (vault.pendingTerms.isSome) {
1295
1352
  const [tickApply, terms] = vault.pendingTerms.value;
1296
1353
  this.pendingTermsChangeTick = tickApply.toNumber();
@@ -1304,22 +1361,7 @@ var Vault = class _Vault {
1304
1361
  )
1305
1362
  };
1306
1363
  }
1307
- this.openedTick = vault.openedTick.toNumber();
1308
- this.openedDate = new Date(this.openedTick * tickDuration);
1309
1364
  }
1310
- securitization;
1311
- securitizationRatio;
1312
- argonsLocked;
1313
- argonsPendingActivation;
1314
- argonsScheduledForRelease = /* @__PURE__ */ new Map();
1315
- terms;
1316
- operatorAccountId;
1317
- isClosed;
1318
- vaultId;
1319
- pendingTerms;
1320
- pendingTermsChangeTick;
1321
- openedDate;
1322
- openedTick;
1323
1365
  availableBitcoinSpace() {
1324
1366
  const recoverySecuritization = this.recoverySecuritization();
1325
1367
  const reLockable = this.getRelockCapacity();
@@ -1328,21 +1370,21 @@ var Vault = class _Vault {
1328
1370
  getRelockCapacity() {
1329
1371
  return [...this.argonsScheduledForRelease.values()].reduce((acc, val) => acc + val, 0n);
1330
1372
  }
1373
+ securitizationRatioBN() {
1374
+ return new BigNumber2(this.securitizationRatio);
1375
+ }
1331
1376
  recoverySecuritization() {
1332
- const reserved = new BigNumber2(1).div(this.securitizationRatio);
1377
+ const reserved = new BigNumber2(1).div(this.securitizationRatioBN());
1333
1378
  return this.securitization - BigInt(reserved.multipliedBy(this.securitization.toString()).toFixed(0, ROUND_FLOOR2));
1334
1379
  }
1335
1380
  minimumSecuritization() {
1336
1381
  return BigInt(
1337
- this.securitizationRatio.multipliedBy(this.argonsLocked.toString()).decimalPlaces(0, BigNumber2.ROUND_CEIL).toString()
1382
+ this.securitizationRatioBN().multipliedBy(this.argonsLocked.toString()).decimalPlaces(0, BigNumber2.ROUND_CEIL).toString()
1338
1383
  );
1339
1384
  }
1340
1385
  activatedSecuritization() {
1341
1386
  const activated = this.argonsLocked - this.argonsPendingActivation;
1342
- let maxRatio = this.securitizationRatio;
1343
- if (this.securitizationRatio.toNumber() > 2) {
1344
- maxRatio = BigNumber2(2);
1345
- }
1387
+ const maxRatio = BigNumber2(Math.min(this.securitizationRatio, 2));
1346
1388
  return BigInt(maxRatio.multipliedBy(activated.toString()).toFixed(0, ROUND_FLOOR2));
1347
1389
  }
1348
1390
  /**
@@ -1356,48 +1398,69 @@ var Vault = class _Vault {
1356
1398
  const fee = this.terms.bitcoinAnnualPercentRate.multipliedBy(Number(amount)).integerValue(BigNumber2.ROUND_CEIL);
1357
1399
  return BigInt(fee.toString()) + this.terms.bitcoinBaseFee;
1358
1400
  }
1359
- static async get(client, vaultId) {
1401
+ static async get(client, vaultId, tickDurationMillis) {
1360
1402
  const rawVault = await client.query.vaults.vaultsById(vaultId);
1361
1403
  if (rawVault.isNone) {
1362
1404
  throw new Error(`Vault with id ${vaultId} not found`);
1363
1405
  }
1364
- const tickDuration = await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1406
+ const tickDuration = tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1365
1407
  return new _Vault(vaultId, rawVault.unwrap(), tickDuration);
1366
1408
  }
1367
- static async create(client, keypair, args, config = {}) {
1368
- const { securitization, securitizationRatio, annualPercentRate, baseFee, bitcoinXpub, tip } = args;
1369
- let xpubBytes = Buffer.from(bitcoinXpub, "hex");
1409
+ static async create(client, keypair, args, config2 = {}) {
1410
+ const {
1411
+ securitization,
1412
+ securitizationRatio,
1413
+ annualPercentRate,
1414
+ baseFee,
1415
+ bitcoinXpub,
1416
+ tip,
1417
+ doNotExceedBalance,
1418
+ txProgressCallback
1419
+ } = args;
1420
+ let xpubBytes = hexToU8a(bitcoinXpub);
1370
1421
  if (xpubBytes.length !== 78) {
1371
1422
  if (bitcoinXpub.startsWith("xpub") || bitcoinXpub.startsWith("tpub") || bitcoinXpub.startsWith("zpub")) {
1372
1423
  const bytes = bs58check.decode(bitcoinXpub);
1373
1424
  if (bytes.length !== 78) {
1374
1425
  throw new Error("Invalid Bitcoin xpub key length, must be 78 bytes");
1375
1426
  }
1376
- xpubBytes = Buffer.from(bytes);
1427
+ xpubBytes = bytes;
1428
+ }
1429
+ }
1430
+ let vaultParams = {
1431
+ terms: {
1432
+ // convert to fixed u128
1433
+ bitcoinAnnualPercentRate: toFixedNumber(annualPercentRate, 18),
1434
+ bitcoinBaseFee: BigInt(baseFee),
1435
+ liquidityPoolProfitSharing: toFixedNumber(args.liquidityPoolProfitSharing, 6)
1436
+ },
1437
+ securitizationRatio: toFixedNumber(securitizationRatio, 18),
1438
+ securitization: BigInt(securitization),
1439
+ bitcoinXpubkey: xpubBytes
1440
+ };
1441
+ let tx = new TxSubmitter(client, client.tx.vaults.create(vaultParams), keypair);
1442
+ if (doNotExceedBalance) {
1443
+ const finalTip = tip ?? 0n;
1444
+ let txFee = await tx.feeEstimate(finalTip);
1445
+ while (txFee + finalTip + vaultParams.securitization > doNotExceedBalance) {
1446
+ vaultParams.securitization = doNotExceedBalance - txFee - finalTip;
1447
+ tx.tx = client.tx.vaults.create(vaultParams);
1448
+ txFee = await tx.feeEstimate(finalTip);
1377
1449
  }
1378
1450
  }
1379
- const tx = new TxSubmitter(
1380
- client,
1381
- client.tx.vaults.create({
1382
- terms: {
1383
- // convert to fixed u128
1384
- bitcoinAnnualPercentRate: toFixedNumber(annualPercentRate, 18),
1385
- bitcoinBaseFee: BigInt(baseFee),
1386
- liquidityPoolProfitSharing: toFixedNumber(args.liquidityPoolProfitSharing, 6)
1387
- },
1388
- securitizationRatio: toFixedNumber(securitizationRatio, 18),
1389
- securitization: BigInt(securitization),
1390
- bitcoinXpubkey: xpubBytes
1391
- }),
1392
- keypair
1393
- );
1394
1451
  const canAfford = await tx.canAfford({ tip, unavailableBalance: BigInt(securitization) });
1395
1452
  if (!canAfford.canAfford) {
1396
1453
  throw new Error(
1397
1454
  `Insufficient balance to create vault. Required: ${formatArgons(securitization)}, Available: ${formatArgons(canAfford.availableBalance)}`
1398
1455
  );
1399
1456
  }
1400
- const result = await tx.submit({ waitForBlock: true, tip });
1457
+ const result = await tx.submit({
1458
+ tip,
1459
+ useLatestNonce: true,
1460
+ waitForBlock: true,
1461
+ txProgressCallback
1462
+ });
1463
+ await result.inBlockPromise;
1401
1464
  let vaultId;
1402
1465
  for (const event of result.events) {
1403
1466
  if (client.events.vaults.VaultCreated.is(event)) {
@@ -1412,8 +1475,9 @@ var Vault = class _Vault {
1412
1475
  if (rawVault.isNone) {
1413
1476
  throw new Error("Vault creation failed, vault not found");
1414
1477
  }
1415
- const tickDuration = config.tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1416
- return new _Vault(vaultId, rawVault.unwrap(), tickDuration);
1478
+ const tickDuration = config2.tickDurationMillis ?? await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1479
+ const vault = new _Vault(vaultId, rawVault.unwrap(), tickDuration);
1480
+ return { vault, txResult: result };
1417
1481
  }
1418
1482
  };
1419
1483
 
@@ -1465,7 +1529,7 @@ var VaultMonitor = class {
1465
1529
  const client = await this.mainchain;
1466
1530
  this.tickDuration = (await client.query.ticks.genesisTicker()).tickDurationMillis.toNumber();
1467
1531
  const blockHeader = await client.rpc.chain.getHeader();
1468
- const blockHash = Buffer.from(blockHeader.hash);
1532
+ const blockHash = new Uint8Array(blockHeader.hash);
1469
1533
  console.log(
1470
1534
  `${justPrint ? "Run" : "Started"} at block ${blockHeader.number} - ${blockHeader.hash.toHuman()}`
1471
1535
  );
@@ -1501,7 +1565,7 @@ var VaultMonitor = class {
1501
1565
  id: vaultId,
1502
1566
  btcSpace: `${formatArgons(vault.availableBitcoinSpace())} (${formatArgons(vault.argonsPendingActivation)} pending)`,
1503
1567
  btcDeal: `${formatArgons(vault.terms.bitcoinBaseFee)} + ${formatPercent(vault.terms.bitcoinAnnualPercentRate)}`,
1504
- securitization: `${formatArgons(vault.securitization)} at ${vault.securitizationRatio.toFormat(1)}x`,
1568
+ securitization: `${formatArgons(vault.securitization)} at ${vault.securitizationRatio}x`,
1505
1569
  securActivated: `${formatArgons(vault.activatedSecuritizationPerSlot())}/slot`,
1506
1570
  liquidPoolDeal: `${formatPercent(vault.terms.liquidityPoolProfitSharing)} sharing`,
1507
1571
  operator: `${this.accountset.namedAccounts.has(vault.operatorAccountId) ? ` (${this.accountset.namedAccounts.get(vault.operatorAccountId)})` : vault.operatorAccountId}`,
@@ -1590,143 +1654,6 @@ var VaultMonitor = class {
1590
1654
  }
1591
1655
  };
1592
1656
 
1593
- // src/CohortBidderHistory.ts
1594
- var CohortBidderHistory = class _CohortBidderHistory {
1595
- constructor(cohortStartingFrameId, subaccounts) {
1596
- this.cohortStartingFrameId = cohortStartingFrameId;
1597
- this.subaccounts = subaccounts;
1598
- this.maxSeatsInPlay = this.subaccounts.length;
1599
- this.subaccounts.forEach((x) => {
1600
- this.myAddresses.add(x.address);
1601
- });
1602
- }
1603
- bidHistory = [];
1604
- stats = {
1605
- // number of seats won
1606
- seatsWon: 0,
1607
- // sum of argons bid in successful bids
1608
- totalArgonsBid: 0n,
1609
- // total number of bids placed (includes 1 per seat)
1610
- bidsAttempted: 0,
1611
- // fees including the tip
1612
- fees: 0n,
1613
- // Max bid per seat
1614
- maxBidPerSeat: 0n,
1615
- // The cost in argonots of each seat
1616
- argonotsPerSeat: 0n,
1617
- // The argonot price in USD for cost basis
1618
- argonotUsdPrice: 0,
1619
- // The cohort expected argons per block
1620
- cohortArgonsPerBlock: 0n,
1621
- // The last block that bids are synced to
1622
- lastBlockNumber: 0
1623
- };
1624
- lastBids = [];
1625
- myAddresses = /* @__PURE__ */ new Set();
1626
- maxSeatsInPlay = 0;
1627
- async init(client) {
1628
- if (!this.stats.argonotsPerSeat) {
1629
- const startingStats = await _CohortBidderHistory.getStartingData(client);
1630
- Object.assign(this.stats, startingStats);
1631
- }
1632
- }
1633
- maybeReducingSeats(maxSeats, reason, historyEntry) {
1634
- if (this.maxSeatsInPlay > maxSeats) {
1635
- historyEntry.maxSeatsReductionReason = reason;
1636
- }
1637
- this.maxSeatsInPlay = maxSeats;
1638
- historyEntry.maxSeatsInPlay = maxSeats;
1639
- }
1640
- trackChange(next, blockNumber, tick, isLastEntry = false) {
1641
- let winningBids = 0;
1642
- let totalArgonsBid = 0n;
1643
- const nextEntrants = [];
1644
- for (const x of next) {
1645
- const bid = x.bid.toBigInt();
1646
- const address = x.accountId.toHuman();
1647
- nextEntrants.push({ address, bid });
1648
- if (this.myAddresses.has(address)) {
1649
- winningBids++;
1650
- totalArgonsBid += bid;
1651
- }
1652
- }
1653
- this.stats.seatsWon = winningBids;
1654
- this.stats.totalArgonsBid = totalArgonsBid;
1655
- this.stats.lastBlockNumber = Math.max(blockNumber, this.stats.lastBlockNumber);
1656
- const historyEntry = {
1657
- cohortStartingFrameId: this.cohortStartingFrameId,
1658
- blockNumber,
1659
- tick,
1660
- bidChanges: [],
1661
- winningSeats: winningBids,
1662
- maxSeatsInPlay: this.maxSeatsInPlay
1663
- };
1664
- const hasDiffs = JsonExt.stringify(nextEntrants) !== JsonExt.stringify(this.lastBids);
1665
- if (!isLastEntry || hasDiffs) {
1666
- this.bidHistory.unshift(historyEntry);
1667
- }
1668
- if (hasDiffs) {
1669
- nextEntrants.forEach(({ address, bid }, i) => {
1670
- const prevBidIndex = this.lastBids.findIndex((y) => y.address === address);
1671
- const entry = {
1672
- address,
1673
- bidAmount: bid,
1674
- bidPosition: i,
1675
- prevPosition: prevBidIndex === -1 ? null : prevBidIndex
1676
- };
1677
- if (prevBidIndex !== -1) {
1678
- const prevBidAmount = this.lastBids[prevBidIndex].bid;
1679
- if (prevBidAmount !== bid) {
1680
- entry.prevBidAmount = prevBidAmount;
1681
- }
1682
- }
1683
- historyEntry.bidChanges.push(entry);
1684
- });
1685
- this.lastBids.forEach(({ address, bid }, i) => {
1686
- const nextBid = nextEntrants.some((y) => y.address === address);
1687
- if (!nextBid) {
1688
- historyEntry.bidChanges.push({
1689
- address,
1690
- bidAmount: bid,
1691
- bidPosition: null,
1692
- prevPosition: i
1693
- });
1694
- }
1695
- });
1696
- this.lastBids = nextEntrants;
1697
- }
1698
- return historyEntry;
1699
- }
1700
- onBidResult(historyEntry, param) {
1701
- const { txFeePlusTip, bidPerSeat, bidsAttempted, successfulBids, blockNumber, bidError } = param;
1702
- this.stats.fees += txFeePlusTip;
1703
- this.stats.bidsAttempted += bidsAttempted;
1704
- if (bidPerSeat > this.stats.maxBidPerSeat) {
1705
- this.stats.maxBidPerSeat = bidPerSeat;
1706
- }
1707
- if (blockNumber !== void 0) {
1708
- this.stats.lastBlockNumber = Math.max(blockNumber, this.stats.lastBlockNumber);
1709
- }
1710
- if (historyEntry.myBidsPlaced) {
1711
- historyEntry.myBidsPlaced.failureReason = bidError;
1712
- historyEntry.myBidsPlaced.successfulBids = successfulBids;
1713
- historyEntry.myBidsPlaced.txFeePlusTip = txFeePlusTip;
1714
- }
1715
- }
1716
- static async getStartingData(api) {
1717
- const argonotPrice = await api.query.priceIndex.current();
1718
- let argonotUsdPrice = 0;
1719
- if (argonotPrice.isSome) {
1720
- argonotUsdPrice = convertFixedU128ToBigNumber(
1721
- argonotPrice.unwrap().argonotUsdPrice.toBigInt()
1722
- ).toNumber();
1723
- }
1724
- const argonotsPerSeat = await api.query.miningSlot.argonotsPerMiningSeat().then((x) => x.toBigInt());
1725
- const cohortArgonsPerBlock = await api.query.blockRewards.argonsPerBlock().then((x) => x.toBigInt());
1726
- return { argonotsPerSeat, argonotUsdPrice, cohortArgonsPerBlock };
1727
- }
1728
- };
1729
-
1730
1657
  // src/CohortBidder.ts
1731
1658
  var CohortBidder = class {
1732
1659
  constructor(accountset, cohortStartingFrameId, subaccounts, options) {
@@ -1734,7 +1661,6 @@ var CohortBidder = class {
1734
1661
  this.cohortStartingFrameId = cohortStartingFrameId;
1735
1662
  this.subaccounts = subaccounts;
1736
1663
  this.options = options;
1737
- this.history = new CohortBidderHistory(cohortStartingFrameId, subaccounts);
1738
1664
  this.subaccounts.forEach((x) => {
1739
1665
  this.myAddresses.add(x.address);
1740
1666
  });
@@ -1742,23 +1668,52 @@ var CohortBidder = class {
1742
1668
  get client() {
1743
1669
  return this.accountset.client;
1744
1670
  }
1745
- get stats() {
1746
- return this.history.stats;
1747
- }
1748
- get bidHistory() {
1749
- return this.history.bidHistory;
1750
- }
1671
+ txFees = 0n;
1672
+ winningBids = [];
1751
1673
  unsubscribe;
1752
1674
  pendingRequest;
1753
1675
  retryTimeout;
1754
1676
  isStopped = false;
1755
1677
  needsRebid = false;
1756
1678
  lastBidTime = 0;
1757
- history;
1758
1679
  millisPerTick;
1680
+ minIncrement = 10000n;
1681
+ nextCohortSize;
1682
+ lastBidBlockNumber = 0;
1759
1683
  myAddresses = /* @__PURE__ */ new Set();
1684
+ async start() {
1685
+ console.log(`Starting cohort ${this.cohortStartingFrameId} bidder`, {
1686
+ maxBid: formatArgons(this.options.maxBid),
1687
+ minBid: formatArgons(this.options.minBid),
1688
+ bidIncrement: formatArgons(this.options.bidIncrement),
1689
+ maxBudget: formatArgons(this.options.maxBudget),
1690
+ bidDelay: this.options.bidDelay,
1691
+ subaccounts: this.subaccounts
1692
+ });
1693
+ const client = await this.client;
1694
+ this.minIncrement = client.consts.miningSlot.bidIncrements.toBigInt();
1695
+ this.nextCohortSize = await client.query.miningSlot.nextCohortSize().then((x) => x.toNumber());
1696
+ if (this.subaccounts.length > this.nextCohortSize) {
1697
+ console.info(
1698
+ `Cohort size ${this.nextCohortSize} is less than provided subaccounts ${this.subaccounts.length}.`
1699
+ );
1700
+ this.subaccounts.length = this.nextCohortSize;
1701
+ }
1702
+ this.millisPerTick = await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1703
+ this.unsubscribe = await client.queryMulti(
1704
+ [
1705
+ client.query.miningSlot.bidsForNextSlotCohort,
1706
+ client.query.miningSlot.nextFrameId
1707
+ ],
1708
+ async ([bids, nextFrameId]) => {
1709
+ if (nextFrameId.toNumber() === this.cohortStartingFrameId) {
1710
+ await this.checkWinningBids(bids);
1711
+ }
1712
+ }
1713
+ );
1714
+ }
1760
1715
  async stop() {
1761
- if (this.isStopped) return this.stats;
1716
+ if (this.isStopped) return this.winningBids;
1762
1717
  this.isStopped = true;
1763
1718
  console.log("Stopping bidder for cohort", this.cohortStartingFrameId);
1764
1719
  clearTimeout(this.retryTimeout);
@@ -1783,79 +1738,47 @@ var CohortBidder = class {
1783
1738
  }
1784
1739
  void await this.pendingRequest;
1785
1740
  let header = await client.rpc.chain.getHeader();
1741
+ let api = await client.at(header.hash);
1786
1742
  while (true) {
1787
- const api2 = await client.at(header.hash);
1788
- const cohortStartingFrameId = await api2.query.miningSlot.nextFrameId();
1743
+ const cohortStartingFrameId = await api.query.miningSlot.nextFrameId();
1789
1744
  if (cohortStartingFrameId.toNumber() === this.cohortStartingFrameId) {
1790
1745
  break;
1791
1746
  }
1792
1747
  header = await client.rpc.chain.getHeader(header.parentHash);
1748
+ api = await client.at(header.hash);
1793
1749
  }
1794
- const api = await client.at(header.hash);
1795
- const tick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1796
1750
  const bids = await api.query.miningSlot.bidsForNextSlotCohort();
1797
- this.history.trackChange(bids, header.number.toNumber(), tick, true);
1751
+ this.updateSeatsWon(bids);
1798
1752
  console.log("Bidder stopped", {
1799
1753
  cohortStartingFrameId: this.cohortStartingFrameId,
1800
1754
  blockNumber: header.number.toNumber(),
1801
- tick,
1802
- bids: bids.map((x) => ({
1803
- address: x.accountId.toHuman(),
1804
- bid: x.bid.toBigInt()
1805
- }))
1755
+ bids: this.winningBids
1806
1756
  });
1807
- return this.stats;
1808
- }
1809
- async start() {
1810
- console.log(`Starting cohort ${this.cohortStartingFrameId} bidder`, {
1811
- maxBid: formatArgons(this.options.maxBid),
1812
- minBid: formatArgons(this.options.minBid),
1813
- bidIncrement: formatArgons(this.options.bidIncrement),
1814
- maxBudget: formatArgons(this.options.maxBudget),
1815
- bidDelay: this.options.bidDelay,
1816
- subaccounts: this.subaccounts
1817
- });
1818
- const client = await this.client;
1819
- await this.history.init(client);
1820
- this.millisPerTick ??= await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber());
1821
- this.unsubscribe = await client.queryMulti(
1822
- [
1823
- client.query.miningSlot.bidsForNextSlotCohort,
1824
- client.query.miningSlot.nextFrameId
1825
- ],
1826
- async ([bids, nextFrameId]) => {
1827
- if (nextFrameId.toNumber() === this.cohortStartingFrameId) {
1828
- await this.checkWinningBids(bids);
1829
- }
1830
- }
1831
- );
1757
+ return this.winningBids;
1832
1758
  }
1833
1759
  async checkWinningBids(bids) {
1834
1760
  if (this.isStopped) return;
1835
1761
  clearTimeout(this.retryTimeout);
1762
+ this.updateSeatsWon(bids);
1763
+ const winningBids = this.winningBids.length;
1764
+ this.needsRebid = winningBids < this.subaccounts.length;
1836
1765
  const client = await this.client;
1837
1766
  const bestBlock = await client.rpc.chain.getBlockHash();
1838
1767
  const api = await client.at(bestBlock);
1839
1768
  const blockNumber = await api.query.system.number().then((x) => x.toNumber());
1840
- if (this.bidHistory[0]?.blockNumber >= blockNumber) {
1841
- return;
1842
- }
1843
- const tick = await api.query.ticks.currentTick().then((x) => x.toNumber());
1844
- const historyEntry = this.history.trackChange(bids, blockNumber, tick);
1769
+ if (this.lastBidBlockNumber >= blockNumber) return;
1845
1770
  if (this.pendingRequest) return;
1846
1771
  const ticksSinceLastBid = Math.floor((Date.now() - this.lastBidTime) / this.millisPerTick);
1847
- if (ticksSinceLastBid < this.options.bidDelay) {
1772
+ if (ticksSinceLastBid < this.options.bidDelay && this.needsRebid) {
1848
1773
  this.retryTimeout = setTimeout(() => void this.checkCurrentSeats(), this.millisPerTick);
1849
1774
  return;
1850
1775
  }
1776
+ if (!this.needsRebid) return;
1851
1777
  console.log(
1852
1778
  "Checking bids for cohort",
1853
1779
  this.cohortStartingFrameId,
1854
1780
  this.subaccounts.map((x) => x.index)
1855
1781
  );
1856
- const winningBids = historyEntry.winningSeats;
1857
- this.needsRebid = winningBids < this.subaccounts.length;
1858
- if (!this.needsRebid) return;
1859
1782
  const winningAddresses = new Set(bids.map((x) => x.accountId.toHuman()));
1860
1783
  let lowestBid = -this.options.bidIncrement;
1861
1784
  if (bids.length) {
@@ -1866,7 +1789,6 @@ var CohortBidder = class {
1866
1789
  }
1867
1790
  }
1868
1791
  }
1869
- const MIN_INCREMENT = 10000n;
1870
1792
  let nextBid = lowestBid + this.options.bidIncrement;
1871
1793
  if (nextBid < this.options.minBid) {
1872
1794
  nextBid = this.options.minBid;
@@ -1895,10 +1817,9 @@ var CohortBidder = class {
1895
1817
  console.log(
1896
1818
  `Can't bid ${formatArgons(nextBid)}. Current lowest bid is ${formatArgons(lowestBid)}.`
1897
1819
  );
1898
- this.history.maybeReducingSeats(winningBids, "MaxBidTooLow" /* MaxBidTooLow */, historyEntry);
1899
1820
  return;
1900
1821
  }
1901
- if (nextBid - lowestBid < MIN_INCREMENT) {
1822
+ if (nextBid - lowestBid < Number(this.minIncrement)) {
1902
1823
  console.log(
1903
1824
  `Can't make any more bids for ${this.cohortStartingFrameId} with given constraints.`,
1904
1825
  {
@@ -1907,14 +1828,11 @@ var CohortBidder = class {
1907
1828
  maxBid: formatArgons(this.options.maxBid)
1908
1829
  }
1909
1830
  );
1910
- this.history.maybeReducingSeats(winningBids, "MaxBidTooLow" /* MaxBidTooLow */, historyEntry);
1911
1831
  return;
1912
1832
  }
1913
1833
  const seatsInBudget = nextBid === 0n ? this.subaccounts.length : Number(budgetForSeats / nextBid);
1914
1834
  let accountsToUse = [...this.subaccounts];
1915
1835
  if (accountsToUse.length > seatsInBudget) {
1916
- const reason = availableBalanceForBids - feePlusTip < nextBid * BigInt(seatsInBudget) ? "InsufficientFunds" /* InsufficientFunds */ : "MaxBudgetTooLow" /* MaxBudgetTooLow */;
1917
- this.history.maybeReducingSeats(seatsInBudget, reason, historyEntry);
1918
1836
  accountsToUse.sort((a, b) => {
1919
1837
  const isWinningA = winningAddresses.has(a.address);
1920
1838
  const isWinningB = winningAddresses.has(b.address);
@@ -1927,19 +1845,11 @@ var CohortBidder = class {
1927
1845
  accountsToUse.length = seatsInBudget;
1928
1846
  }
1929
1847
  if (accountsToUse.length > winningBids) {
1930
- historyEntry.myBidsPlaced = {
1931
- bids: accountsToUse.length,
1932
- bidPerSeat: nextBid,
1933
- txFeePlusTip: feePlusTip,
1934
- successfulBids: 0
1935
- };
1936
- this.pendingRequest = this.bid(nextBid, accountsToUse, historyEntry);
1937
- } else if (historyEntry.bidChanges.length === 0) {
1938
- this.history.bidHistory.shift();
1848
+ this.pendingRequest = this.bid(nextBid, accountsToUse);
1939
1849
  }
1940
1850
  this.needsRebid = false;
1941
1851
  }
1942
- async bid(bidPerSeat, subaccounts, historyEntry) {
1852
+ async bid(bidPerSeat, subaccounts) {
1943
1853
  const prevLastBidTime = this.lastBidTime;
1944
1854
  try {
1945
1855
  this.lastBidTime = Date.now();
@@ -1960,14 +1870,10 @@ var CohortBidder = class {
1960
1870
  blockNumber = await api.query.system.number().then((x) => x.toNumber());
1961
1871
  }
1962
1872
  const successfulBids = txResult.batchInterruptedIndex ?? subaccounts.length;
1963
- this.history.onBidResult(historyEntry, {
1964
- blockNumber,
1965
- successfulBids,
1966
- bidPerSeat,
1967
- txFeePlusTip: txResult.finalFee ?? 0n,
1968
- bidsAttempted: subaccounts.length,
1969
- bidError
1970
- });
1873
+ this.txFees += txResult.finalFee ?? 0n;
1874
+ if (blockNumber !== void 0) {
1875
+ this.lastBidBlockNumber = Math.max(blockNumber, this.lastBidBlockNumber);
1876
+ }
1971
1877
  console.log("Done creating bids for cohort", {
1972
1878
  successfulBids,
1973
1879
  bidPerSeat,
@@ -1987,6 +1893,16 @@ var CohortBidder = class {
1987
1893
  await this.checkCurrentSeats();
1988
1894
  }
1989
1895
  }
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 });
1903
+ }
1904
+ }
1905
+ }
1990
1906
  async checkCurrentSeats() {
1991
1907
  const client = await this.client;
1992
1908
  const bids = await client.query.miningSlot.bidsForNextSlotCohort();
@@ -2059,7 +1975,7 @@ var BidPool = class {
2059
1975
  }
2060
1976
  async loadAt(blockHash) {
2061
1977
  const client = await this.client;
2062
- blockHash ??= Buffer.from((await client.rpc.chain.getHeader()).hash);
1978
+ blockHash ??= new Uint8Array((await client.rpc.chain.getHeader()).hash);
2063
1979
  const api = await client.at(blockHash);
2064
1980
  const rawVaultIds = await api.query.vaults.vaultsById.keys();
2065
1981
  const vaultIds = rawVaultIds.map((x) => x.args[0].toNumber());
@@ -2328,6 +2244,7 @@ Raising Funds (Frame ${this.nextFrameId + 1}):`);
2328
2244
  };
2329
2245
 
2330
2246
  // src/BitcoinLocks.ts
2247
+ import { hexToU8a as hexToU8a2, u8aToHex as u8aToHex2 } from "@polkadot/util";
2331
2248
  var SATS_PER_BTC = 100000000n;
2332
2249
  var BitcoinLocks = class _BitcoinLocks {
2333
2250
  constructor(client) {
@@ -2367,6 +2284,7 @@ var BitcoinLocks = class _BitcoinLocks {
2367
2284
  const bitcoinNetwork = await client.query.bitcoinUtxos.bitcoinNetwork();
2368
2285
  return {
2369
2286
  releaseExpirationBlocks: client.consts.bitcoinLocks.lockReleaseCosignDeadlineBlocks.toNumber(),
2287
+ pendingConfirmationExpirationBlocks: client.consts.bitcoinUtxos.maxPendingConfirmationBlocks.toNumber(),
2370
2288
  tickDurationMillis: await client.query.ticks.genesisTicker().then((x) => x.tickDurationMillis.toNumber()),
2371
2289
  bitcoinNetwork
2372
2290
  };
@@ -2387,7 +2305,7 @@ var BitcoinLocks = class _BitcoinLocks {
2387
2305
  async getUtxoRef(utxoId, atHeight) {
2388
2306
  let client = await this.client;
2389
2307
  if (atHeight !== void 0) {
2390
- const blockHash = await client.query.system.blockHash(atHeight);
2308
+ const blockHash = await client.rpc.chain.getBlockHash(atHeight);
2391
2309
  client = await client.at(blockHash);
2392
2310
  }
2393
2311
  const refRaw = await client.query.bitcoinUtxos.utxoIdToRef(utxoId);
@@ -2395,15 +2313,15 @@ var BitcoinLocks = class _BitcoinLocks {
2395
2313
  return;
2396
2314
  }
2397
2315
  const ref = refRaw.unwrap();
2398
- const txid = Buffer.from(ref.txid).toString("hex");
2399
- const btcTxid = Buffer.from(ref.txid.reverse()).toString("hex");
2316
+ const txid = u8aToHex2(ref.txid);
2317
+ const bitcoinTxid = u8aToHex2(ref.txid.reverse());
2400
2318
  const vout = ref.outputIndex.toNumber();
2401
- return { txid: `0x${txid}`, vout, bitcoinTxid: `0x${btcTxid}` };
2319
+ return { txid, vout, bitcoinTxid };
2402
2320
  }
2403
2321
  async getReleaseRequest(utxoId, atHeight) {
2404
2322
  let client = await this.client;
2405
2323
  if (atHeight !== void 0) {
2406
- const blockHash = await client.query.system.blockHash(atHeight);
2324
+ const blockHash = await client.rpc.chain.getBlockHash(atHeight);
2407
2325
  client = await client.at(blockHash);
2408
2326
  }
2409
2327
  const locksPendingRelease = await client.query.bitcoinLocks.locksPendingReleaseByUtxoId();
@@ -2421,17 +2339,17 @@ var BitcoinLocks = class _BitcoinLocks {
2421
2339
  return void 0;
2422
2340
  }
2423
2341
  async submitVaultSignature(args) {
2424
- const { utxoId, vaultSignature, argonKeyring } = args;
2342
+ const { utxoId, vaultSignature, argonKeyring, txProgressCallback } = args;
2425
2343
  const client = await this.client;
2426
- if (!vaultSignature || vaultSignature.byteLength < 71 || vaultSignature.byteLength > 73) {
2344
+ if (!vaultSignature || vaultSignature.byteLength < 70 || vaultSignature.byteLength > 73) {
2427
2345
  throw new Error(
2428
- `Invalid vault signature length: ${vaultSignature.byteLength}. Must be 71-73 bytes.`
2346
+ `Invalid vault signature length: ${vaultSignature.byteLength}. Must be 70-73 bytes.`
2429
2347
  );
2430
2348
  }
2431
- const signature = `0x${vaultSignature.toString("hex")}`;
2349
+ const signature = u8aToHex2(vaultSignature);
2432
2350
  const tx = client.tx.bitcoinLocks.cosignRelease(utxoId, signature);
2433
2351
  const submitter = new TxSubmitter(client, tx, argonKeyring);
2434
- return await submitter.submit({ waitForBlock: true });
2352
+ return await submitter.submit({ txProgressCallback });
2435
2353
  }
2436
2354
  async getBitcoinLock(utxoId) {
2437
2355
  const client = await this.client;
@@ -2452,7 +2370,7 @@ var BitcoinLocks = class _BitcoinLocks {
2452
2370
  const ownerPubkey = utxo.ownerPubkey.toHex();
2453
2371
  const [fingerprint, cosign_hd_index, claim_hd_index] = utxo.vaultXpubSources;
2454
2372
  const vaultXpubSources = {
2455
- parentFingerprint: Buffer.from(fingerprint),
2373
+ parentFingerprint: new Uint8Array(fingerprint),
2456
2374
  cosignHdIndex: cosign_hd_index.toNumber(),
2457
2375
  claimHdIndex: claim_hd_index.toNumber()
2458
2376
  };
@@ -2534,7 +2452,7 @@ var BitcoinLocks = class _BitcoinLocks {
2534
2452
  await new Promise((resolve) => setTimeout(resolve, 1e3));
2535
2453
  continue;
2536
2454
  }
2537
- const hash = await client.query.system.blockHash(atHeight).then((x) => x.toHex());
2455
+ const hash = await client.rpc.chain.getBlockHash(atHeight).then((x) => x.toHex());
2538
2456
  if (hash === "0x0000000000000000000000000000000000000000000000000000000000000000") {
2539
2457
  console.warn(`Block hash not found for height ${atHeight}. Retrying...`);
2540
2458
  await new Promise((resolve) => setTimeout(resolve, 1e3));
@@ -2556,7 +2474,7 @@ var BitcoinLocks = class _BitcoinLocks {
2556
2474
  if (client.events.bitcoinLocks.BitcoinUtxoCosigned.is(event.event)) {
2557
2475
  const { utxoId: id, signature } = event.event.data;
2558
2476
  if (id.toNumber() === utxoId) {
2559
- return Buffer.from(signature);
2477
+ return new Uint8Array(signature);
2560
2478
  }
2561
2479
  }
2562
2480
  }
@@ -2602,11 +2520,16 @@ var BitcoinLocks = class _BitcoinLocks {
2602
2520
  return { tx, securityFee, txFee };
2603
2521
  }
2604
2522
  async initializeLock(args) {
2605
- const { argonKeyring, tip = 0n } = args;
2523
+ const { argonKeyring, tip = 0n, txProgressCallback } = args;
2606
2524
  const client = await this.client;
2607
2525
  const { tx, securityFee } = await this.createInitializeLockTx(args);
2608
2526
  const submitter = new TxSubmitter(client, tx, argonKeyring);
2609
- const txResult = await submitter.submit({ waitForBlock: true, logResults: true, tip });
2527
+ const txResult = await submitter.submit({
2528
+ waitForBlock: true,
2529
+ logResults: true,
2530
+ tip,
2531
+ txProgressCallback
2532
+ });
2610
2533
  const blockHash = await txResult.inBlockPromise;
2611
2534
  const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
2612
2535
  const utxoId = await this.getUtxoIdFromEvents(txResult.events) ?? 0;
@@ -2629,7 +2552,8 @@ var BitcoinLocks = class _BitcoinLocks {
2629
2552
  lock,
2630
2553
  releaseRequest: { bitcoinNetworkFee, toScriptPubkey },
2631
2554
  argonKeyring,
2632
- tip
2555
+ tip,
2556
+ txProgressCallback
2633
2557
  } = args;
2634
2558
  if (!toScriptPubkey.startsWith("0x")) {
2635
2559
  throw new Error("toScriptPubkey must be a hex string starting with 0x");
@@ -2652,7 +2576,12 @@ var BitcoinLocks = class _BitcoinLocks {
2652
2576
  `Insufficient funds to release lock. Available: ${formatArgons(canAfford.availableBalance)}, Required: ${formatArgons(redemptionPrice)}`
2653
2577
  );
2654
2578
  }
2655
- const txResult = await submitter.submit({ waitForBlock: true, logResults: true, tip });
2579
+ const txResult = await submitter.submit({
2580
+ waitForBlock: true,
2581
+ logResults: true,
2582
+ tip,
2583
+ txProgressCallback
2584
+ });
2656
2585
  const blockHash = await txResult.inBlockPromise;
2657
2586
  const blockHeight = await client.at(blockHash).then((x) => x.query.system.number()).then((x) => x.toNumber());
2658
2587
  return {
@@ -2691,7 +2620,7 @@ var BitcoinLocks = class _BitcoinLocks {
2691
2620
  };
2692
2621
  }
2693
2622
  async ratchet(args) {
2694
- const { lock, argonKeyring, tip = 0n, vault } = args;
2623
+ const { lock, argonKeyring, tip = 0n, vault, txProgressCallback } = args;
2695
2624
  const client = await this.client;
2696
2625
  const ratchetPrice = await this.getRatchetPrice(lock, vault);
2697
2626
  const txSubmitter = new TxSubmitter(
@@ -2712,7 +2641,8 @@ var BitcoinLocks = class _BitcoinLocks {
2712
2641
  }
2713
2642
  const submission = await txSubmitter.submit({
2714
2643
  waitForBlock: true,
2715
- tip
2644
+ tip,
2645
+ txProgressCallback
2716
2646
  });
2717
2647
  const ratchetEvent = submission.events.find(
2718
2648
  (x) => client.events.bitcoinLocks.BitcoinLockRatcheted.is(x)
@@ -2744,7 +2674,7 @@ var BitcoinLocks = class _BitcoinLocks {
2744
2674
  const vaults = new VaultMonitor(accountset, {
2745
2675
  bitcoinSpaceAvailable: argonAmount
2746
2676
  });
2747
- const bitcoinXpubBuffer = Buffer.from(bitcoinXpub.replace(/^0x(.+)/, "$1"), "hex");
2677
+ const bitcoinXpubBuffer = hexToU8a2(bitcoinXpub);
2748
2678
  return new Promise(async (resolve, reject) => {
2749
2679
  vaults.events.on("bitcoin-space-above", async (vaultId, amount) => {
2750
2680
  const vault = vaults.vaultsById[vaultId];
@@ -2801,9 +2731,32 @@ function createKeyringPair(opts) {
2801
2731
  }
2802
2732
 
2803
2733
  // src/index.ts
2804
- export * from "@polkadot/types";
2805
- export * from "@polkadot/types/interfaces";
2806
- export * from "@polkadot/types-codec/types";
2734
+ import { u8aToHex as u8aToHex3, hexToU8a as hexToU8a3, u8aEq } from "@polkadot/util";
2735
+ import { GenericEvent as GenericEvent2, GenericBlock, GenericAddress } from "@polkadot/types/generic";
2736
+ import {
2737
+ BTreeMap,
2738
+ Bytes,
2739
+ Compact,
2740
+ Enum,
2741
+ Null,
2742
+ Option as Option2,
2743
+ Result,
2744
+ Bool,
2745
+ Tuple,
2746
+ Range,
2747
+ Struct,
2748
+ Text,
2749
+ U256,
2750
+ U8aFixed,
2751
+ Vec,
2752
+ bool,
2753
+ i128,
2754
+ u128,
2755
+ u16,
2756
+ u32,
2757
+ u64,
2758
+ u8
2759
+ } from "@polkadot/types-codec";
2807
2760
  async function waitForLoad() {
2808
2761
  await cryptoWaitReady();
2809
2762
  }
@@ -2819,7 +2772,10 @@ async function getClient(host) {
2819
2772
 
2820
2773
  export {
2821
2774
  WageProtector,
2775
+ setConfig,
2776
+ getConfig,
2822
2777
  TxSubmitter,
2778
+ TxResult,
2823
2779
  MICROGONS_PER_ARGON,
2824
2780
  formatArgons,
2825
2781
  formatPercent,
@@ -2849,7 +2805,6 @@ export {
2849
2805
  MiningBids,
2850
2806
  Vault,
2851
2807
  VaultMonitor,
2852
- CohortBidderHistory,
2853
2808
  CohortBidder,
2854
2809
  BidPool,
2855
2810
  SATS_PER_BTC,
@@ -2860,6 +2815,34 @@ export {
2860
2815
  decodeAddress,
2861
2816
  mnemonicGenerate,
2862
2817
  waitForLoad,
2863
- getClient
2818
+ getClient,
2819
+ u8aToHex3 as u8aToHex,
2820
+ hexToU8a3 as hexToU8a,
2821
+ u8aEq,
2822
+ GenericEvent2 as GenericEvent,
2823
+ GenericBlock,
2824
+ GenericAddress,
2825
+ BTreeMap,
2826
+ Bytes,
2827
+ Compact,
2828
+ Enum,
2829
+ Null,
2830
+ Option2 as Option,
2831
+ Result,
2832
+ Bool,
2833
+ Tuple,
2834
+ Range,
2835
+ Struct,
2836
+ Text,
2837
+ U256,
2838
+ U8aFixed,
2839
+ Vec,
2840
+ bool,
2841
+ i128,
2842
+ u128,
2843
+ u16,
2844
+ u32,
2845
+ u64,
2846
+ u8
2864
2847
  };
2865
- //# sourceMappingURL=chunk-CGXT6XF7.js.map
2848
+ //# sourceMappingURL=chunk-P3OMJABP.js.map