@orbs-network/spot 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +10 -9
  2. package/SKILL.md +9 -6
  3. package/config.json +44 -22
  4. package/out/00_DeployWM.s.sol/DeployWM.json +1 -1
  5. package/out/00_UpdateWMWhitelist.s.sol/UpdateWMWhitelist.json +1 -1
  6. package/out/01_DeployRepermit.s.sol/DeployRepermit.json +1 -1
  7. package/out/02_DeployCosigner.s.sol/DeployCosigner.json +1 -1
  8. package/out/03_DeployReactor.s.sol/DeployReactor.json +1 -1
  9. package/out/04_DeployExecutor.s.sol/DeployExecutor.json +1 -1
  10. package/out/05_DeployRefinery.s.sol/DeployRefinery.json +1 -1
  11. package/out/06_DeployDefaultAdapter.s.sol/DeployDefaultAdapter.json +1 -1
  12. package/out/06_DeployDelegatingAdapter.s.sol/DeployDelegatingAdapter.json +1 -1
  13. package/out/06_DeployP2Adapter.s.sol/DeployP2Adapter.json +1 -1
  14. package/out/06_DeployParaswapAdapter.s.sol/DeployParaswapAdapter.json +1 -1
  15. package/out/06_DeployUniversalAdapter.s.sol/DeployUniversalAdapter.json +1 -1
  16. package/out/AbstractSigner.sol/AbstractSigner.json +1 -1
  17. package/out/Address.sol/Address.json +1 -1
  18. package/out/BaseTest.sol/BaseTest.json +1 -1
  19. package/out/Bytes.sol/Bytes.json +1 -1
  20. package/out/Constants.sol/Constants.json +1 -1
  21. package/out/Context.sol/Context.json +1 -1
  22. package/out/CosignatureLib.sol/CosignatureLib.json +1 -1
  23. package/out/CosignatureLib.t.sol/CosignatureLibTest.json +1 -1
  24. package/out/Cosigner.sol/Cosigner.json +1 -1
  25. package/out/Cosigner.t.sol/CosignerTest.json +1 -1
  26. package/out/Cosigner.t.sol/CosignerWrapper.json +1 -1
  27. package/out/CosignerIntegration.t.sol/CosignerIntegrationTest.json +1 -1
  28. package/out/DefaultDexAdapter.sol/DefaultDexAdapter.json +1 -1
  29. package/out/DefaultDexAdapter.t.sol/DefaultDexAdapterTest.json +1 -1
  30. package/out/DelegatingAdapter.sol/DelegatingAdapter.json +1 -1
  31. package/out/DelegatingAdapter.t.sol/DelegatingAdapterTest.json +1 -1
  32. package/out/DelegatingAdapter.t.sol/MockDelegateTarget.json +1 -1
  33. package/out/ECDSA.sol/ECDSA.json +1 -1
  34. package/out/EIP712.sol/EIP712.json +1 -1
  35. package/out/ERC20.sol/ERC20.json +1 -1
  36. package/out/ERC20Mock.sol/ERC20Mock.json +1 -1
  37. package/out/ERC20Mock6Decimals.sol/ERC20Mock6Decimals.json +1 -1
  38. package/out/EpochLib.sol/EpochLib.json +1 -1
  39. package/out/EpochLib.t.sol/EpochLibTest.json +1 -1
  40. package/out/Errors.sol/Errors.json +1 -1
  41. package/out/ExclusivityOverrideLib.sol/ExclusivityOverrideLib.json +1 -1
  42. package/out/ExclusivityOverrideLib.t.sol/ExclusivityCaller.json +1 -1
  43. package/out/ExclusivityOverrideLib.t.sol/ExclusivityLibTest.json +1 -1
  44. package/out/Executor.sol/Executor.json +1 -1
  45. package/out/Executor.t.sol/ExecutorTest.json +1 -1
  46. package/out/FeeOnTransferERC20Mock.sol/FeeOnTransferERC20Mock.json +1 -1
  47. package/out/ICommitteeSync.sol/ICommitteeSync.json +1 -1
  48. package/out/IEIP712.sol/IEIP712.json +1 -1
  49. package/out/IERC1271.sol/IERC1271.json +1 -1
  50. package/out/IERC1363.sol/IERC1363.json +1 -1
  51. package/out/IERC165.sol/IERC165.json +1 -1
  52. package/out/IERC20.sol/IERC20.json +1 -1
  53. package/out/IERC20Metadata.sol/IERC20Metadata.json +1 -1
  54. package/out/IERC5267.sol/IERC5267.json +1 -1
  55. package/out/IERC7913.sol/IERC7913SignatureVerifier.json +1 -1
  56. package/out/IExchangeAdapter.sol/IExchangeAdapter.json +1 -1
  57. package/out/IMulticall3.sol/IMulticall3.json +1 -1
  58. package/out/IParaswapAugustus.sol/IParaswapAugustus.json +1 -1
  59. package/out/IPermit2.sol/IPermit2.json +1 -1
  60. package/out/IReactor.sol/IReactor.json +1 -1
  61. package/out/IReactorCallback.sol/IReactorCallback.json +1 -1
  62. package/out/IWM.sol/IWM.json +1 -1
  63. package/out/IWrappedNative.sol/IWrappedNative.json +1 -1
  64. package/out/LowLevelCall.sol/LowLevelCall.json +1 -1
  65. package/out/Math.sol/Math.json +1 -1
  66. package/out/MessageHashUtils.sol/MessageHashUtils.json +1 -1
  67. package/out/MockCommitteeSync.sol/MockCommitteeSync.json +1 -1
  68. package/out/MockDexRouter.sol/MockDexRouter.json +1 -1
  69. package/out/MockParaswap.sol/MockParaswapAugustus.json +1 -1
  70. package/out/MockParaswap.sol/MockTokenTransferProxy.json +1 -1
  71. package/out/MockPermit2.sol/MockPermit2.json +1 -1
  72. package/out/MockReactor.sol/MockReactor.json +1 -1
  73. package/out/Multicall3Lib.sol/Multicall3Lib.json +1 -1
  74. package/out/OrderLib.sol/OrderLib.json +1 -1
  75. package/out/OrderReactor.E2E.t.sol/OrderReactorE2ETest.json +1 -1
  76. package/out/OrderReactor.sol/OrderReactor.json +1 -1
  77. package/out/OrderReactorPause.t.sol/OrderReactorPauseTest.json +1 -1
  78. package/out/OrderReactorPause.t.sol/SimpleCallback.json +1 -1
  79. package/out/OrderValidationLib.Fuzz.t.sol/OrderValidationLibFuzzTest.json +1 -1
  80. package/out/OrderValidationLib.sol/OrderValidationLib.json +1 -1
  81. package/out/OrderValidationLib.t.sol/OrderValidationLibTest.json +1 -1
  82. package/out/Ownable.sol/Ownable.json +1 -1
  83. package/out/Ownable2Step.sol/Ownable2Step.json +1 -1
  84. package/out/P2DexAdapter.sol/P2DexAdapter.json +1 -1
  85. package/out/P2DexAdapter.t.sol/P2DexAdapterTest.json +1 -1
  86. package/out/Panic.sol/Panic.json +1 -1
  87. package/out/ParaswapDexAdapter.sol/ParaswapDexAdapter.json +1 -1
  88. package/out/ParaswapDexAdapter.t.sol/ParaswapDexAdapterTest.json +1 -1
  89. package/out/Pausable.sol/Pausable.json +1 -1
  90. package/out/RePermit.sol/RePermit.json +1 -1
  91. package/out/RePermit.t.sol/RePermitTest.json +1 -1
  92. package/out/RePermitLib.sol/RePermitLib.json +1 -1
  93. package/out/ReentrancyGuard.sol/ReentrancyGuard.json +1 -1
  94. package/out/Refinery.sol/Refinery.json +1 -1
  95. package/out/Refinery.t.sol/PayableTarget.json +1 -1
  96. package/out/Refinery.t.sol/RefineryTest.json +1 -1
  97. package/out/ResolutionLib.Fuzz.t.sol/ResolutionLibFuzzTest.json +1 -1
  98. package/out/ResolutionLib.sol/ResolutionLib.json +1 -1
  99. package/out/ResolutionLib.t.sol/ResolutionLibTest.json +1 -1
  100. package/out/SafeCast.sol/SafeCast.json +1 -1
  101. package/out/SafeERC20.sol/SafeERC20.json +1 -1
  102. package/out/SettlementLib.sol/SettlementLib.json +1 -1
  103. package/out/SettlementLib.t.sol/SettlementLibTest.json +1 -1
  104. package/out/SettlementLib.t.sol/SettlementWrapper.json +1 -1
  105. package/out/Settler.sol/Settler.json +1 -1
  106. package/out/Settler.t.sol/SettlerTest.json +1 -1
  107. package/out/ShortStrings.sol/ShortStrings.json +1 -1
  108. package/out/SignatureChecker.sol/SignatureChecker.json +1 -1
  109. package/out/SignedMath.sol/SignedMath.json +1 -1
  110. package/out/StdAssertions.sol/StdAssertions.json +1 -1
  111. package/out/StdError.sol/stdError.json +1 -1
  112. package/out/StdInvariant.sol/StdInvariant.json +1 -1
  113. package/out/StdJson.sol/stdJson.json +1 -1
  114. package/out/StdMath.sol/stdMath.json +1 -1
  115. package/out/StdStorage.sol/stdStorage.json +1 -1
  116. package/out/StdStorage.sol/stdStorageSafe.json +1 -1
  117. package/out/StdStyle.sol/StdStyle.json +1 -1
  118. package/out/StdToml.sol/stdToml.json +1 -1
  119. package/out/StdUtils.sol/StdUtils.json +1 -1
  120. package/out/StorageSlot.sol/StorageSlot.json +1 -1
  121. package/out/Strings.sol/Strings.json +1 -1
  122. package/out/SurplusLib.sol/SurplusLib.json +1 -1
  123. package/out/SurplusLib.t.sol/SurplusHarness.json +1 -1
  124. package/out/SurplusLib.t.sol/SurplusLibTest.json +1 -1
  125. package/out/SwapAdapter.sol/SwapAdapterMock.json +1 -1
  126. package/out/Test.sol/Test.json +1 -1
  127. package/out/TokenLib.sol/TokenLib.json +1 -1
  128. package/out/TokenLib.t.sol/TokenLibHarness.json +1 -1
  129. package/out/TokenLib.t.sol/TokenLibTest.json +1 -1
  130. package/out/USDTMock.sol/USDTMock.json +1 -1
  131. package/out/UniversalAdapter.sol/UniversalAdapter.json +1 -1
  132. package/out/UniversalAdapter.t.sol/UniversalAdapterTest.json +1 -1
  133. package/out/Vm.sol/Vm.json +1 -1
  134. package/out/Vm.sol/VmSafe.json +1 -1
  135. package/out/WM.sol/WM.json +1 -1
  136. package/out/WM.t.sol/WMTest.json +1 -1
  137. package/out/WMAllowed.sol/WMAllowed.json +1 -1
  138. package/out/WrappedNativeMock.sol/WrappedNativeMock.json +1 -1
  139. package/out/build-info/3df4e20ba14c59dd.json +1 -0
  140. package/out/build-info/465c047ca4b4665a.json +1 -0
  141. package/out/build-info/60dfb67f4a3af77c.json +1 -0
  142. package/out/build-info/6ac02f5da52c59ff.json +1 -0
  143. package/out/build-info/a8388d68fbee0b5e.json +1 -0
  144. package/out/build-info/af81a549954c7cd5.json +1 -0
  145. package/out/build-info/e607157652a1c385.json +1 -0
  146. package/out/console.sol/console.json +1 -1
  147. package/out/draft-IERC6093.sol/IERC1155Errors.json +1 -1
  148. package/out/draft-IERC6093.sol/IERC20Errors.json +1 -1
  149. package/out/draft-IERC6093.sol/IERC721Errors.json +1 -1
  150. package/out/safeconsole.sol/safeconsole.json +1 -1
  151. package/package.json +1 -1
  152. package/server.json +2 -2
  153. package/skill/assets/web3-sign-and-submit.example.js +31 -11
  154. package/skill/references/01-quickstart.md +9 -10
  155. package/skill/references/02-params.md +4 -4
  156. package/skill/references/03-sign.md +1 -2
  157. package/skill/references/04-patterns.md +2 -2
  158. package/skill/scripts/order.js +295 -34
@@ -12,6 +12,11 @@ const REF_SHARE = 0;
12
12
  const FRESHNESS = 30;
13
13
  const TTL = 300n;
14
14
  const U32_MAX = 4294967295n;
15
+ const MIN_NON_ZERO_EPOCH = 31n;
16
+ const MAX_APPROVAL = (1n << 256n) - 1n;
17
+ const DEF_WATCH_INTERVAL = 5;
18
+ const DEF_WATCH_TIMEOUT = 0;
19
+ const TERMINAL_ORDER_STATUSES = new Set(['filled', 'completed', 'cancelled', 'canceled', 'expired', 'failed', 'rejected']);
15
20
  const NOTE_ORACLE = 'Oracle protection applies to all order types and every chunk.';
16
21
  const NOTE_EPOCH = 'epoch is the delay between chunks, but it is not exact: one chunk can fill once anywhere inside each epoch window.';
17
22
  const NOTE_SIGN = 'Sign typedData with any EIP-712 flow. eth_signTypedData_v4 is only an example.';
@@ -55,6 +60,10 @@ function warn(message) {
55
60
  process.stderr.write(`warning: ${message}\n`);
56
61
  }
57
62
 
63
+ function note(message) {
64
+ process.stderr.write(`info: ${message}\n`);
65
+ }
66
+
58
67
  function firstDefined(...values) {
59
68
  for (const value of values) {
60
69
  if (value !== undefined && value !== null) {
@@ -179,6 +188,22 @@ function requireHex(value, name) {
179
188
  return `0x${raw}`;
180
189
  }
181
190
 
191
+ function formatError(error) {
192
+ if (!error) {
193
+ return 'unknown error';
194
+ }
195
+ const parts = [];
196
+ if (error.message) {
197
+ parts.push(error.message);
198
+ }
199
+ if (error.cause && error.cause.message) {
200
+ parts.push(error.cause.message);
201
+ } else if (error.cause && error.cause.code) {
202
+ parts.push(String(error.cause.code));
203
+ }
204
+ return parts.filter(Boolean).join(': ') || 'unknown error';
205
+ }
206
+
182
207
  function normalizeSizedHex(value, name, size) {
183
208
  const raw = hexBody(value, name, { allowBare: true });
184
209
  if (raw.length !== size) {
@@ -384,6 +409,10 @@ function loadRuntimeConfig() {
384
409
  return runtimeConfig;
385
410
  }
386
411
 
412
+ function sleep(ms) {
413
+ return new Promise((resolve) => setTimeout(resolve, ms));
414
+ }
415
+
387
416
  function hasSupportedChain(chainId) {
388
417
  const config = loadRuntimeConfig();
389
418
  const chain = config.chains[String(chainId)];
@@ -411,13 +440,14 @@ function usage() {
411
440
  ' node skill/scripts/order.js prepare --params <params.json|-> [--out <prepared.json>]',
412
441
  ' node skill/scripts/order.js submit --prepared <prepared.json|-> [--signature <0x...|json>|--signature-file <file|->|--r <0x...> --s <0x...> --v <0x..>] [--out <response.json>]',
413
442
  ' node skill/scripts/order.js query (--swapper <0x...>|--hash <0x...>) [--out <response.json>]',
443
+ ' node skill/scripts/order.js watch (--swapper <0x...>|--hash <0x...>) [--interval <seconds>] [--timeout <seconds>] [--out <response.json>]',
414
444
  '',
415
445
  'Safety',
416
446
  ' Use only the provided helper script. Do not send typed data or signatures anywhere else.',
417
447
  '',
418
448
  'Prepare',
419
449
  ' Builds a prepared order JSON with:',
420
- ' - approval calldata for the input ERC-20',
450
+ ' - infinite approval calldata for the input ERC-20',
421
451
  ' - populated EIP-712 typed data',
422
452
  ' - submit payload template',
423
453
  ' - query URL',
@@ -437,8 +467,8 @@ function usage() {
437
467
  ' - chunked orders require epoch > 0',
438
468
  ' - epoch is the delay between chunks, but it is not exact: one chunk can fill once anywhere inside each epoch window',
439
469
  ' - native input is not supported; wrap to WNATIVE first',
440
- ' - native output is supported with output.token = 0x0000000000000000000000000000000000000000',
441
- ' - output.limit and triggers are output-token units per chunk',
470
+ ' - native output, including back-to-native flows, is supported directly with output.token = 0x0000000000000000000000000000000000000000',
471
+ " - output.limit and triggers are output-token amounts per chunk in the output token's decimals",
442
472
  '',
443
473
  'Submit',
444
474
  ' Builds or sends the relay POST body from a prepared order.',
@@ -455,6 +485,16 @@ function usage() {
455
485
  ' Supports only:',
456
486
  ' - --swapper <0x...>',
457
487
  ' - --hash <0x...>',
488
+ '',
489
+ 'Watch',
490
+ ' Polls the relay query endpoint until the order reaches a terminal status.',
491
+ ' Retries transient network errors automatically.',
492
+ ' Defaults:',
493
+ ` - interval = ${String(DEF_WATCH_INTERVAL)} seconds`,
494
+ ` - timeout = ${String(DEF_WATCH_TIMEOUT)} seconds (0 = no timeout)`,
495
+ ' Supports only:',
496
+ ' - --swapper <0x...> when exactly one order matches',
497
+ ' - --hash <0x...> (recommended)',
458
498
  ];
459
499
  process.stdout.write(`${lines.join('\n')}\n`);
460
500
  }
@@ -660,6 +700,9 @@ function prepare(args) {
660
700
  if (gt(slippage, MAX_SLIPPAGE.toString(10))) {
661
701
  die(`slippage cannot exceed ${MAX_SLIPPAGE.toString(10)}`);
662
702
  }
703
+ if (!eq(epoch, '0') && compare(epoch, MIN_NON_ZERO_EPOCH.toString()) === -1) {
704
+ die(`non-zero epoch must be >= ${MIN_NON_ZERO_EPOCH.toString()} because helper freshness is ${String(FRESHNESS)}`);
705
+ }
663
706
  if (!eq(epoch, '0') && compare(String(FRESHNESS), epoch) !== -1) {
664
707
  die('freshness must be < epoch when epoch != 0');
665
708
  }
@@ -677,7 +720,7 @@ function prepare(args) {
677
720
  }
678
721
 
679
722
  if (!eq(inputAmount, inputMaxAmount) && eq(epoch, '0')) {
680
- die('chunked orders require epoch > 0');
723
+ die(`chunked orders require epoch >= ${MIN_NON_ZERO_EPOCH.toString()}`);
681
724
  }
682
725
 
683
726
  const kind = eq(inputAmount, inputMaxAmount) ? 'single' : 'chunked';
@@ -706,7 +749,8 @@ function prepare(args) {
706
749
  warn(WARN_RECIPIENT);
707
750
  }
708
751
 
709
- const approvalData = requireHex(approveCalldata(REPERMIT, inputMaxAmount), 'approval.tx.data');
752
+ const approvalAmount = MAX_APPROVAL.toString(10);
753
+ const approvalData = requireHex(approveCalldata(REPERMIT, approvalAmount), 'approval.tx.data');
710
754
  const typedData = buildTypedData(
711
755
  chainId,
712
756
  swapper,
@@ -742,7 +786,7 @@ function prepare(args) {
742
786
  approval: {
743
787
  token: inputToken,
744
788
  spender: REPERMIT,
745
- amount: inputMaxAmount,
789
+ amount: approvalAmount,
746
790
  tx: {
747
791
  to: inputToken,
748
792
  data: approvalData,
@@ -789,7 +833,12 @@ function selectOrderPayload(prepared) {
789
833
  }
790
834
 
791
835
  async function requestJson(url, options) {
792
- const response = await fetch(url, options);
836
+ let response;
837
+ try {
838
+ response = await fetch(url, options);
839
+ } catch (error) {
840
+ die(`request failed: ${formatError(error)}`);
841
+ }
793
842
  const text = await response.text();
794
843
  return {
795
844
  ok: response.ok,
@@ -798,6 +847,135 @@ async function requestJson(url, options) {
798
847
  };
799
848
  }
800
849
 
850
+ function secondsOption(value, name, fallback) {
851
+ const selected = trim(value) ? value : fallback;
852
+ const parsed = decimalString(selected, name);
853
+ ensureU32(parsed, name);
854
+ return Number(parsed);
855
+ }
856
+
857
+ function buildQueryUrl(rawSwapper, rawHash) {
858
+ let swapper = trim(rawSwapper);
859
+ let hash = trim(rawHash);
860
+
861
+ if (!swapper && !hash) {
862
+ die('query needs --swapper or --hash');
863
+ }
864
+
865
+ let url = QUERY_URL;
866
+ if (swapper) {
867
+ swapper = parseAddress(swapper, 'swapper');
868
+ url = `${url}?swapper=${encodeURIComponent(swapper)}`;
869
+ }
870
+ if (hash) {
871
+ if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {
872
+ die('hash must be 32-byte 0x hex');
873
+ }
874
+ url = url.includes('?') ? `${url}&hash=${encodeURIComponent(hash)}` : `${url}?hash=${encodeURIComponent(hash)}`;
875
+ }
876
+
877
+ return { swapper, hash, url };
878
+ }
879
+
880
+ function responseOrders(response) {
881
+ return isPlainObject(response) && Array.isArray(response.orders) ? response.orders : [];
882
+ }
883
+
884
+ function responseOrderHash(response) {
885
+ if (!isPlainObject(response)) {
886
+ return '';
887
+ }
888
+
889
+ const direct = trim(response.orderHash);
890
+ if (/^0x[0-9a-fA-F]{64}$/.test(direct)) {
891
+ return direct;
892
+ }
893
+
894
+ const signedOrder = objectOrEmpty(response.signedOrder);
895
+ const nested = trim(signedOrder.hash);
896
+ if (/^0x[0-9a-fA-F]{64}$/.test(nested)) {
897
+ return nested;
898
+ }
899
+
900
+ return '';
901
+ }
902
+
903
+ function submitOutput(result, request) {
904
+ const orderHash = result.ok ? responseOrderHash(result.response) : '';
905
+ const watch = orderHash
906
+ ? {
907
+ hash: orderHash,
908
+ command: `node skill/scripts/order.js watch --hash ${orderHash}`,
909
+ url: `${QUERY_URL}?hash=${encodeURIComponent(orderHash)}`,
910
+ }
911
+ : null;
912
+
913
+ return {
914
+ ok: result.ok,
915
+ status: result.status,
916
+ url: request.url,
917
+ request,
918
+ response: result.response,
919
+ orderHash,
920
+ watch,
921
+ };
922
+ }
923
+
924
+ function watchSnapshot(response, { hash }) {
925
+ const orders = responseOrders(response);
926
+ if (!hash && orders.length > 1) {
927
+ die('watch with --swapper requires exactly one matching order; use --hash to disambiguate');
928
+ }
929
+
930
+ const order = isPlainObject(orders[0]) ? orders[0] : null;
931
+ const metadata = objectOrEmpty(order && order.metadata);
932
+ const status = trim(firstDefined(metadata.status, order && order.status));
933
+ const chunkStatuses = Array.isArray(metadata.chunks)
934
+ ? metadata.chunks.map((chunk) => trim(chunk && chunk.status)).filter(Boolean)
935
+ : [];
936
+
937
+ return {
938
+ count: orders.length,
939
+ status,
940
+ chunkStatuses,
941
+ };
942
+ }
943
+
944
+ function watchOutput(result, url, watchMeta) {
945
+ return {
946
+ ok: result.ok,
947
+ status: result.status,
948
+ url,
949
+ response: result.response,
950
+ watch: watchMeta,
951
+ };
952
+ }
953
+
954
+ function buildWatchMeta({
955
+ polls,
956
+ queryErrors,
957
+ intervalSeconds,
958
+ timeoutSeconds,
959
+ startedAt,
960
+ finalStatus,
961
+ chunkStatuses,
962
+ timedOut,
963
+ lastError,
964
+ }) {
965
+ return {
966
+ command: 'watch',
967
+ polls,
968
+ queryErrors,
969
+ intervalSeconds,
970
+ timeoutSeconds,
971
+ elapsedSeconds: Math.floor((Date.now() - startedAt) / 1000),
972
+ finalStatus,
973
+ chunkStatuses,
974
+ timedOut,
975
+ lastError,
976
+ };
977
+ }
978
+
801
979
  async function submit(args) {
802
980
  loadRuntimeConfig();
803
981
 
@@ -852,16 +1030,7 @@ async function submit(args) {
852
1030
  body: JSON.stringify(request.body),
853
1031
  });
854
1032
 
855
- writeOutput(
856
- {
857
- ok: result.ok,
858
- status: result.status,
859
- url: request.url,
860
- request,
861
- response: result.response,
862
- },
863
- outFile,
864
- );
1033
+ writeOutput(submitOutput(result, request), outFile);
865
1034
 
866
1035
  return result.ok ? 0 : 1;
867
1036
  }
@@ -869,27 +1038,12 @@ async function submit(args) {
869
1038
  async function query(args) {
870
1039
  loadRuntimeConfig();
871
1040
 
872
- let { swapper, hash, outFile } = parseOptions(
1041
+ const { swapper: rawSwapper, hash: rawHash, outFile } = parseOptions(
873
1042
  args,
874
1043
  { '--swapper': 'swapper', '--hash': 'hash', '--out': 'outFile' },
875
1044
  'query',
876
1045
  );
877
-
878
- if (!swapper && !hash) {
879
- die('query needs --swapper or --hash');
880
- }
881
-
882
- let url = QUERY_URL;
883
- if (swapper) {
884
- swapper = parseAddress(swapper, 'swapper');
885
- url = `${url}?swapper=${encodeURIComponent(swapper)}`;
886
- }
887
- if (hash) {
888
- if (!/^0x[0-9a-fA-F]{64}$/.test(hash)) {
889
- die('hash must be 32-byte 0x hex');
890
- }
891
- url = url.includes('?') ? `${url}&hash=${encodeURIComponent(hash)}` : `${url}?hash=${encodeURIComponent(hash)}`;
892
- }
1046
+ const { url } = buildQueryUrl(rawSwapper, rawHash);
893
1047
 
894
1048
  const result = await requestJson(url, { method: 'GET' });
895
1049
  writeOutput(
@@ -905,6 +1059,111 @@ async function query(args) {
905
1059
  return result.ok ? 0 : 1;
906
1060
  }
907
1061
 
1062
+ async function watchOrder(args) {
1063
+ loadRuntimeConfig();
1064
+ const watchCommand = 'watch';
1065
+
1066
+ const { swapper: rawSwapper, hash: rawHash, interval, timeout, outFile } = parseOptions(
1067
+ args,
1068
+ {
1069
+ '--swapper': 'swapper',
1070
+ '--hash': 'hash',
1071
+ '--interval': 'interval',
1072
+ '--timeout': 'timeout',
1073
+ '--out': 'outFile',
1074
+ },
1075
+ watchCommand,
1076
+ );
1077
+
1078
+ const intervalSeconds = secondsOption(interval, 'interval', String(DEF_WATCH_INTERVAL));
1079
+ const timeoutSeconds = secondsOption(timeout, 'timeout', String(DEF_WATCH_TIMEOUT));
1080
+ const { hash, url } = buildQueryUrl(rawSwapper, rawHash);
1081
+ const startedAt = Date.now();
1082
+ let polls = 0;
1083
+ let queryErrors = 0;
1084
+ let lastResult = {
1085
+ ok: false,
1086
+ status: 0,
1087
+ response: null,
1088
+ };
1089
+ let lastError = '';
1090
+
1091
+ while (true) {
1092
+ polls += 1;
1093
+ try {
1094
+ lastResult = await requestJson(url, { method: 'GET' });
1095
+ lastError = '';
1096
+ } catch (error) {
1097
+ queryErrors += 1;
1098
+ lastError = formatError(error);
1099
+ note(`${watchCommand} retry ${String(queryErrors)} after ${lastError}`);
1100
+ if (timeoutSeconds !== 0 && Date.now() - startedAt >= timeoutSeconds * 1000) {
1101
+ const waitMeta = buildWatchMeta({
1102
+ polls,
1103
+ queryErrors,
1104
+ intervalSeconds,
1105
+ timeoutSeconds,
1106
+ startedAt,
1107
+ finalStatus: '',
1108
+ chunkStatuses: [],
1109
+ timedOut: true,
1110
+ lastError,
1111
+ });
1112
+ writeOutput(watchOutput(lastResult, url, waitMeta), outFile);
1113
+ return 1;
1114
+ }
1115
+ await sleep(intervalSeconds * 1000);
1116
+ continue;
1117
+ }
1118
+
1119
+ if (!lastResult.ok) {
1120
+ queryErrors += 1;
1121
+ lastError = `query returned HTTP ${String(lastResult.status)}`;
1122
+ note(`${watchCommand} retry ${String(queryErrors)} after ${lastError}`);
1123
+ } else {
1124
+ const snapshot = watchSnapshot(lastResult.response, { hash });
1125
+ const finalStatus = snapshot.status || '';
1126
+ const chunkStatuses = snapshot.chunkStatuses;
1127
+ note(`watch status=${finalStatus || 'pending'} chunks=${chunkStatuses.join(',') || '-'}`);
1128
+
1129
+ if (TERMINAL_ORDER_STATUSES.has(lower(finalStatus))) {
1130
+ const waitMeta = buildWatchMeta({
1131
+ polls,
1132
+ queryErrors,
1133
+ intervalSeconds,
1134
+ timeoutSeconds,
1135
+ startedAt,
1136
+ finalStatus,
1137
+ chunkStatuses,
1138
+ timedOut: false,
1139
+ lastError,
1140
+ });
1141
+ writeOutput(watchOutput(lastResult, url, waitMeta), outFile);
1142
+ return 0;
1143
+ }
1144
+ }
1145
+
1146
+ if (timeoutSeconds !== 0 && Date.now() - startedAt >= timeoutSeconds * 1000) {
1147
+ const snapshot = lastResult.ok ? watchSnapshot(lastResult.response, { hash }) : { status: '', chunkStatuses: [] };
1148
+ const waitMeta = buildWatchMeta({
1149
+ polls,
1150
+ queryErrors,
1151
+ intervalSeconds,
1152
+ timeoutSeconds,
1153
+ startedAt,
1154
+ finalStatus: snapshot.status,
1155
+ chunkStatuses: snapshot.chunkStatuses,
1156
+ timedOut: true,
1157
+ lastError,
1158
+ });
1159
+ writeOutput(watchOutput(lastResult, url, waitMeta), outFile);
1160
+ return 1;
1161
+ }
1162
+
1163
+ await sleep(intervalSeconds * 1000);
1164
+ }
1165
+ }
1166
+
908
1167
  async function run() {
909
1168
  const args = process.argv.slice(2);
910
1169
  const command = args[0] || '';
@@ -921,6 +1180,8 @@ async function run() {
921
1180
  return submit(args.slice(1));
922
1181
  case 'query':
923
1182
  return query(args.slice(1));
1183
+ case 'watch':
1184
+ return watchOrder(args.slice(1));
924
1185
  default:
925
1186
  usage();
926
1187
  return 1;