@quantovainc/qcore 0.1.31 → 0.1.32

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.
package/shared.js CHANGED
@@ -51,6 +51,53 @@ function accountNonce(nonce) {
51
51
  return n;
52
52
  }
53
53
 
54
+ const VALIDITY_BLOCKS = 300n;
55
+ const MAX_PLAUSIBLE_HEAD = 1n << 40n;
56
+ const HEAD_BLOCKS_PER_SEC = 4n;
57
+ const HEAD_SLACK_SECS = 60n;
58
+ const TRANSFER_METER = 1210n;
59
+
60
+ function meterLimitOf(meterLimit) {
61
+ if (typeof meterLimit === 'number' && !Number.isSafeInteger(meterLimit)) {
62
+ throw new Error('the meter limit must be a whole number in the safe integer range');
63
+ }
64
+ let meter;
65
+ try {
66
+ meter = BigInt(meterLimit);
67
+ } catch {
68
+ throw new Error('the meter limit must be a whole number');
69
+ }
70
+ if (meter < 0n || meter > 0xffffffffffffffffn) {
71
+ throw new Error('the meter limit must fit in an unsigned 64 bit integer');
72
+ }
73
+ return meter;
74
+ }
75
+
76
+ function vmCallFee(transferFee, meterLimit) {
77
+ const meter = meterLimitOf(meterLimit);
78
+ let units = (meter + TRANSFER_METER - 1n) / TRANSFER_METER;
79
+ if (units < 1n) units = 1n;
80
+ return BigInt(transferFee) * units;
81
+ }
82
+
83
+ function validUntil(info) {
84
+ const head = info && info.head_height;
85
+ if (head == null) throw new Error('the gateway did not report a head height to bound the transaction to');
86
+ if (typeof head === 'number' && !Number.isSafeInteger(head)) {
87
+ throw new Error('the gateway reported a head height outside the safe integer range');
88
+ }
89
+ let h;
90
+ try {
91
+ h = BigInt(head);
92
+ } catch {
93
+ throw new Error('the gateway reported a head height that is not a whole number');
94
+ }
95
+ if (h < 0n || h > MAX_PLAUSIBLE_HEAD) {
96
+ throw new Error('the gateway reported a head height past any height this chain can have reached');
97
+ }
98
+ return h + VALIDITY_BLOCKS;
99
+ }
100
+
54
101
  function gatewayFee(fee) {
55
102
  if (typeof fee === 'number' && !Number.isSafeInteger(fee)) {
56
103
  throw new Error('the gateway reported a fee outside the safe integer range, a number that large silently rounds and would sign a different fee');
@@ -83,7 +130,7 @@ async function readBounded(res) {
83
130
  if (done) break;
84
131
  total += value.byteLength;
85
132
  if (total > MAX_RESPONSE) {
86
- try { await reader.cancel(); } catch { /* already closing */ }
133
+ try { await reader.cancel(); } catch {}
87
134
  throw new Error('the response is too large');
88
135
  }
89
136
  chunks.push(value);
@@ -198,12 +245,6 @@ function makeClient(core) {
198
245
  this.network = opts.network instanceof Network ? opts.network : Network.forUrl(base);
199
246
  }
200
247
  this.base = requireSafeTransport(base).replace(/\/$/, '');
201
- // The chain name the gateway reports is hashed into the signature preimage of
202
- // every signing path, so whoever names it decides which network a signature is
203
- // valid on. `Network.forUrl` leaves chainId null, which is the default for
204
- // `new Client(url)`, and the configured check is skipped when it is null, so by
205
- // default the endpoint chose. Bind it with expectedChainId, or rely on the pin,
206
- // which at least refuses a gateway that changes its mind mid session.
207
248
  this.expectedChainId =
208
249
  typeof opts.expectedChainId === 'string' && opts.expectedChainId.length > 0
209
250
  ? opts.expectedChainId
@@ -231,12 +272,6 @@ function makeClient(core) {
231
272
  if (!this.acknowledgeMainnet && this._isMainnetId(id)) {
232
273
  throw new Error(`the gateway reports the mainnet chain ${name}; refusing to sign a mainnet transaction without acknowledgeMainnet`);
233
274
  }
234
- // Pin on first ACCEPTED use, after every refusal above. With nothing configured
235
- // the endpoint names the chain, and the least this can do is refuse one that
236
- // answers differently later in the same session, which is how a signature ends
237
- // up bound to a network the caller never chose while every earlier call looked
238
- // entirely normal. Pinning a name we refused to sign for would be wrong: it was
239
- // never a chain this client accepted.
240
275
  if (this._pinnedChainName === null) {
241
276
  this._pinnedChainName = name;
242
277
  } else if (this._pinnedChainName !== name) {
@@ -277,19 +312,42 @@ function makeClient(core) {
277
312
  head() { return this._call('head', '{}'); }
278
313
  async account(address) {
279
314
  const acct = await this._call('get_account', core.account_body(address));
280
- if (acct && acct.address != null && acct.address !== address) {
315
+ if (!acct || typeof acct.address !== 'string') {
316
+ throw new Error(`the gateway answered about ${address} without naming the account, refusing to trust it`);
317
+ }
318
+ if (acct.address !== address) {
281
319
  throw new Error(`the gateway answered for ${acct.address} when asked about ${address}, refusing to trust it`);
282
320
  }
283
321
  return acct;
284
322
  }
285
- _checkedNonce(reported, expected) {
323
+ _checkedNonce(reported, expected, key) {
286
324
  const n = accountNonce(reported);
287
- if (expected != null) {
288
- const e = BigInt(expected);
289
- if (n < e) throw new Error(`the gateway reported nonce ${n} below the expected ${e}; refusing so a replayed lower nonce cannot force a second payment`);
290
- if (n > e + 16n) throw new Error(`the gateway reported nonce ${n} far above the expected ${e}; refusing`);
325
+ if (!this._nextNonces) this._nextNonces = new Map();
326
+ const local = key != null ? this._nextNonces.get(key) : undefined;
327
+ const e = expected != null ? BigInt(expected) : local;
328
+ if (e == null) return n;
329
+ if (n > e) throw new Error(`the gateway reported nonce ${n} above the expected ${e}; refusing so a signature cannot be banked for a nonce the account has not reached`);
330
+ return expected != null ? e : n;
331
+ }
332
+
333
+ _remember(key, used, outcome) {
334
+ if (!this._nextNonces) this._nextNonces = new Map();
335
+ if (outcome && outcome.verdict === 'accepted') this._nextNonces.set(key, BigInt(used) + 1n);
336
+ }
337
+
338
+ _validity(info) {
339
+ const until = validUntil(info);
340
+ const head = until - VALIDITY_BLOCKS;
341
+ const now = BigInt(Math.floor(Date.now() / 1000));
342
+ if (this._headFloor) {
343
+ const { height, at } = this._headFloor;
344
+ if (head < height) throw new Error(`the gateway reports head ${head} below the ${height} it reported earlier, refusing to sign`);
345
+ const allowed = (now - at + HEAD_SLACK_SECS) * HEAD_BLOCKS_PER_SEC;
346
+ if (head > height + allowed) throw new Error(`the gateway head leapt from ${height} to ${head} faster than blocks are made, refusing to sign`);
347
+ } else {
348
+ this._headFloor = { height: head, at: now };
291
349
  }
292
- return n;
350
+ return until;
293
351
  }
294
352
  transaction(txId) { return this._call('get_transaction', core.transaction_body(txId)); }
295
353
  block(height) { return this._call('get_block', core.block_by_height_body(BigInt(height))); }
@@ -315,15 +373,16 @@ function makeClient(core) {
315
373
  const from = core.address(seedHex, accountIndex(index));
316
374
  const acct = await this.account(from);
317
375
  if (!acct || acct.nonce == null) throw new Error('the gateway did not report a nonce');
318
- const nonce = this._checkedNonce(acct.nonce, expectedNonce);
376
+ const nonce = this._checkedNonce(acct.nonce, expectedNonce, from);
319
377
  const signed = JSON.parse(
320
- core.sign_transfer(seedHex, accountIndex(index), to, String(amount), nonce, String(fee), chainId)
378
+ core.sign_transfer(seedHex, accountIndex(index), to, String(amount), nonce, String(fee), chainId, this._validity(info))
321
379
  );
322
380
  const outcome = await this.submit(signed.tx_hex);
381
+ this._remember(from, nonce, outcome);
323
382
  return { signed, outcome };
324
383
  }
325
384
 
326
- async register(seedHex, index, maxFeeQuon) {
385
+ async register(seedHex, index, maxFeeQuon, expectedNonce) {
327
386
  const ceiling = feeCeiling(maxFeeQuon);
328
387
  const info = await this.nodeInfo();
329
388
  this._guardMainnet();
@@ -336,33 +395,38 @@ function makeClient(core) {
336
395
  const from = core.address(seedHex, accountIndex(index));
337
396
  const acct = await this.account(from);
338
397
  if (!acct || acct.nonce == null) throw new Error('the gateway did not report a nonce');
339
- const signed = JSON.parse(core.signRegister(seedHex, accountIndex(index), accountNonce(acct.nonce), String(fee), chainId));
398
+ const nonce = this._checkedNonce(acct.nonce, expectedNonce, from);
399
+ const signed = JSON.parse(core.signRegister(seedHex, accountIndex(index), nonce, String(fee), chainId, this._validity(info)));
340
400
  const outcome = await this.submit(signed.tx_hex);
401
+ this._remember(from, nonce, outcome);
341
402
  return { signed, outcome };
342
403
  }
343
404
 
344
- async call(seedHex, index, target, argsHex, meterLimit, maxFeeQuon) {
405
+ async call(seedHex, index, target, argsHex, meterLimit, maxFeeQuon, expectedNonce) {
345
406
  if (!core.valid_address(target)) throw new Error('the target is not a q1 address');
346
407
  const ceiling = feeCeiling(maxFeeQuon);
347
408
  const info = await this.nodeInfo();
348
409
  this._guardMainnet();
349
410
  const chainId = this._signingChainId(info);
350
- const fee = info && info.fee && info.fee.transfer_quon;
351
- if (fee == null) throw new Error('the gateway did not report a transfer fee');
352
- if (gatewayFee(fee) > ceiling) {
353
- throw new Error(`the gateway fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
411
+ const reported = info && info.fee && info.fee.transfer_quon;
412
+ if (reported == null) throw new Error('the gateway did not report a transfer fee');
413
+ const fee = vmCallFee(gatewayFee(reported), meterLimit);
414
+ if (fee > ceiling) {
415
+ throw new Error(`the fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
354
416
  }
355
417
  const from = core.address(seedHex, accountIndex(index));
356
418
  const acct = await this.account(from);
357
419
  if (!acct || acct.nonce == null) throw new Error('the gateway did not report a nonce');
420
+ const nonce = this._checkedNonce(acct.nonce, expectedNonce, from);
358
421
  const signed = JSON.parse(
359
- core.sign_call(seedHex, accountIndex(index), target, argsHex, accountNonce(acct.nonce), BigInt(meterLimit), String(fee), chainId)
422
+ core.sign_call(seedHex, accountIndex(index), target, argsHex, nonce, meterLimitOf(meterLimit), String(fee), chainId, this._validity(info))
360
423
  );
361
424
  const outcome = await this.submit(signed.tx_hex);
425
+ this._remember(from, nonce, outcome);
362
426
  return { signed, outcome };
363
427
  }
364
428
 
365
- async assetCall(seedHex, index, target, argsHex, assetIssuer, amount, meterLimit, maxFeeQuon) {
429
+ async assetCall(seedHex, index, target, argsHex, assetIssuer, amount, meterLimit, maxFeeQuon, expectedNonce) {
366
430
  if (!core.valid_address(target)) throw new Error('the target is not a q1 address');
367
431
  if (!core.valid_address(assetIssuer)) throw new Error('the asset issuer is not a q1 address');
368
432
  checkAmount(amount);
@@ -370,77 +434,83 @@ function makeClient(core) {
370
434
  const info = await this.nodeInfo();
371
435
  this._guardMainnet();
372
436
  const chainId = this._signingChainId(info);
373
- const fee = info && info.fee && info.fee.transfer_quon;
374
- if (fee == null) throw new Error('the gateway did not report a transfer fee');
375
- if (gatewayFee(fee) > ceiling) {
376
- throw new Error(`the gateway fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
437
+ const reported = info && info.fee && info.fee.transfer_quon;
438
+ if (reported == null) throw new Error('the gateway did not report a transfer fee');
439
+ const fee = vmCallFee(gatewayFee(reported), meterLimit);
440
+ if (fee > ceiling) {
441
+ throw new Error(`the fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
377
442
  }
378
443
  const from = core.address(seedHex, accountIndex(index));
379
444
  const acct = await this.account(from);
380
445
  if (!acct || acct.nonce == null) throw new Error('the gateway did not report a nonce');
446
+ const nonce = this._checkedNonce(acct.nonce, expectedNonce, from);
381
447
  const signed = JSON.parse(
382
- core.signAssetCall(seedHex, accountIndex(index), target, argsHex, assetIssuer, String(amount), accountNonce(acct.nonce), BigInt(meterLimit), String(fee), chainId)
448
+ core.signAssetCall(seedHex, accountIndex(index), target, argsHex, assetIssuer, String(amount), nonce, meterLimitOf(meterLimit), String(fee), chainId, this._validity(info))
383
449
  );
384
450
  const outcome = await this.submit(signed.tx_hex);
451
+ this._remember(from, nonce, outcome);
385
452
  return { signed, outcome };
386
453
  }
387
454
 
388
- async payableCall(seedHex, index, target, argsHex, value, meterLimit, maxFeeQuon) {
455
+ async payableCall(seedHex, index, target, argsHex, value, meterLimit, maxFeeQuon, expectedNonce) {
389
456
  if (!core.valid_address(target)) throw new Error('the target is not a q1 address');
390
457
  checkAmount(value);
391
458
  const ceiling = feeCeiling(maxFeeQuon);
392
459
  const info = await this.nodeInfo();
393
460
  this._guardMainnet();
394
461
  const chainId = this._signingChainId(info);
395
- const fee = info && info.fee && info.fee.transfer_quon;
396
- if (fee == null) throw new Error('the gateway did not report a transfer fee');
397
- if (gatewayFee(fee) > ceiling) {
398
- throw new Error(`the gateway fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
462
+ const reported = info && info.fee && info.fee.transfer_quon;
463
+ if (reported == null) throw new Error('the gateway did not report a transfer fee');
464
+ const fee = vmCallFee(gatewayFee(reported), meterLimit);
465
+ if (fee > ceiling) {
466
+ throw new Error(`the fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
399
467
  }
400
468
  const from = core.address(seedHex, accountIndex(index));
401
469
  const acct = await this.account(from);
402
470
  if (!acct || acct.nonce == null) throw new Error('the gateway did not report a nonce');
471
+ const nonce = this._checkedNonce(acct.nonce, expectedNonce, from);
403
472
  const signed = JSON.parse(
404
- core.signPayableCall(seedHex, accountIndex(index), target, argsHex, accountNonce(acct.nonce), BigInt(meterLimit), String(fee), String(value), chainId)
473
+ core.signPayableCall(seedHex, accountIndex(index), target, argsHex, nonce, meterLimitOf(meterLimit), String(fee), String(value), chainId, this._validity(info))
405
474
  );
406
475
  const outcome = await this.submit(signed.tx_hex);
476
+ this._remember(from, nonce, outcome);
407
477
  return { signed, outcome };
408
478
  }
409
479
 
480
+ async _slotValue(contract, key) {
481
+ const resp = await this._call('get_storage_at', JSON.stringify({ address: contract, keys: [key] }));
482
+ return BigInt(core.storageValue(JSON.stringify(resp), key));
483
+ }
484
+
410
485
  async contractNonce(contract, signerHex) {
411
- const resp = await this._call('get_storage', core.storageBody(contract));
412
- return BigInt(core.storageValue(JSON.stringify(resp), core.nonceSlotKey(signerHex)));
486
+ return this._slotValue(contract, core.nonceSlotKey(signerHex));
413
487
  }
414
488
 
415
489
  async contractScalar(contract, slot) {
416
- const resp = await this._call('get_storage', core.storageBody(contract));
417
- return BigInt(core.storageValue(JSON.stringify(resp), core.scalarSlotKey(BigInt(slot))));
490
+ return this._slotValue(contract, core.scalarSlotKey(BigInt(slot)));
418
491
  }
419
492
 
420
- async callSignedOrder(callerSeedHex, callerIndex, contract, selectorHex, orderSpec, ownerSeedHex, ownerIndex, meterLimit, maxFeeQuon, expectedOrderNonce) {
493
+ async callSignedOrder(callerSeedHex, callerIndex, contract, selectorHex, orderSpec, ownerSeedHex, ownerIndex, meterLimit, maxFeeQuon, expectedOrderNonce, expectedNonce) {
421
494
  if (!core.valid_address(contract)) throw new Error('the contract is not a q1 address');
422
495
  const ceiling = feeCeiling(maxFeeQuon);
423
496
  const info = await this.nodeInfo();
424
497
  this._guardMainnet();
425
498
  const chainId = this._signingChainId(info);
426
- const fee = info && info.fee && info.fee.transfer_quon;
427
- if (fee == null) throw new Error('the gateway did not report a transfer fee');
428
- if (gatewayFee(fee) > ceiling) {
429
- throw new Error(`the gateway fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
499
+ const reported = info && info.fee && info.fee.transfer_quon;
500
+ if (reported == null) throw new Error('the gateway did not report a transfer fee');
501
+ const fee = vmCallFee(gatewayFee(reported), meterLimit);
502
+ if (fee > ceiling) {
503
+ throw new Error(`the fee ${fee} is above the maximum you allowed ${maxFeeQuon}, refusing to sign`);
430
504
  }
431
505
  const signer = core.orderSigner(ownerSeedHex, accountIndex(ownerIndex));
432
- // The owner authorisation carries no deadline, so this nonce is the only thing
433
- // that stops it being replayed. Reading it from the gateway hands the party the
434
- // signature protects against the one term that expires it: answer with a future
435
- // nonce and the reply is a valid order banked until the contract counter reaches
436
- // it. Pass expectedOrderNonce to bind what you meant to sign; without it you are
437
- // trusting the endpoint with the owner key.
438
- const nonce = await this.contractNonce(contract, signer);
439
- if (expectedOrderNonce != null && BigInt(expectedOrderNonce) !== nonce) {
506
+ const orderKey = contract + '/' + signer;
507
+ const reportedOrder = await this.contractNonce(contract, signer);
508
+ if (expectedOrderNonce != null && BigInt(expectedOrderNonce) !== reportedOrder) {
440
509
  throw new Error(
441
- `the gateway reported order nonce ${nonce} but you expected ${expectedOrderNonce}, refusing to sign`
510
+ `the gateway reported order nonce ${reportedOrder} but you expected ${expectedOrderNonce}, refusing to sign`
442
511
  );
443
512
  }
513
+ const nonce = this._checkedNonce(reportedOrder, expectedOrderNonce, orderKey);
444
514
  const order = JSON.parse(core.buildTypedOrderCall(
445
515
  chainId,
446
516
  contract,
@@ -448,7 +518,12 @@ function makeClient(core) {
448
518
  BigInt(orderSpec.schemeOff),
449
519
  BigInt(orderSpec.ptrOff),
450
520
  BigInt(orderSpec.regionOff || 0),
451
- JSON.stringify(orderSpec.fields || []),
521
+ JSON.stringify(orderSpec.fields || [], (k, v) => {
522
+ if (typeof v !== 'bigint') return v;
523
+ if (k === 'value') return v.toString();
524
+ if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`the order field ${k} ${v} is too large to carry`);
525
+ return Number(v);
526
+ }),
452
527
  ownerSeedHex,
453
528
  accountIndex(ownerIndex),
454
529
  nonce,
@@ -456,13 +531,16 @@ function makeClient(core) {
456
531
  const from = core.address(callerSeedHex, accountIndex(callerIndex));
457
532
  const acct = await this.account(from);
458
533
  if (!acct || acct.nonce == null) throw new Error('the gateway did not report a nonce');
534
+ const accountNonceUsed = this._checkedNonce(acct.nonce, expectedNonce, from);
459
535
  const signed = JSON.parse(
460
- core.sign_call(callerSeedHex, accountIndex(callerIndex), contract, order.call_args, accountNonce(acct.nonce), BigInt(meterLimit), String(fee), chainId)
536
+ core.sign_call(callerSeedHex, accountIndex(callerIndex), contract, order.call_args, accountNonceUsed, meterLimitOf(meterLimit), String(fee), chainId, this._validity(info))
461
537
  );
462
538
  const outcome = await this.submit(signed.tx_hex);
539
+ this._remember(from, accountNonceUsed, outcome);
540
+ this._remember(orderKey, nonce, outcome);
463
541
  return { order, signed, outcome, orderNonce: nonce };
464
542
  }
465
543
  };
466
544
  }
467
545
 
468
- module.exports = { makeClient, feeCeiling, checkAmount, generateSeed, readBounded, requireSafeTransport, Network };
546
+ module.exports = { makeClient, feeCeiling, checkAmount, generateSeed, readBounded, requireSafeTransport, validUntil, vmCallFee, VALIDITY_BLOCKS, Network };