lampamazaza-new-internal-utils 0.24.3

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 (216) hide show
  1. package/LICENSE +21 -0
  2. package/dist/_virtual/rolldown_runtime.cjs +43 -0
  3. package/dist/_virtual/rolldown_runtime.js +18 -0
  4. package/dist/config.cjs +82 -0
  5. package/dist/config.d.cts +42 -0
  6. package/dist/config.d.ts +42 -0
  7. package/dist/config.js +72 -0
  8. package/dist/errors/assert.cjs +11 -0
  9. package/dist/errors/assert.d.cts +11 -0
  10. package/dist/errors/assert.d.ts +11 -0
  11. package/dist/errors/assert.js +11 -0
  12. package/dist/errors/base.cjs +34 -0
  13. package/dist/errors/base.d.cts +21 -0
  14. package/dist/errors/base.d.ts +21 -0
  15. package/dist/errors/base.js +33 -0
  16. package/dist/errors/index.cjs +23 -0
  17. package/dist/errors/index.d.cts +11 -0
  18. package/dist/errors/index.d.ts +11 -0
  19. package/dist/errors/index.js +18 -0
  20. package/dist/errors/request.cjs +48 -0
  21. package/dist/errors/request.d.cts +61 -0
  22. package/dist/errors/request.d.ts +61 -0
  23. package/dist/errors/request.js +46 -0
  24. package/dist/errors/utils/isNetworkError.cjs +23 -0
  25. package/dist/errors/utils/isNetworkError.js +22 -0
  26. package/dist/errors/utils/toError.cjs +8 -0
  27. package/dist/errors/utils/toError.d.cts +4 -0
  28. package/dist/errors/utils/toError.d.ts +4 -0
  29. package/dist/errors/utils/toError.js +7 -0
  30. package/dist/index.cjs +125 -0
  31. package/dist/index.d.cts +30 -0
  32. package/dist/index.d.ts +30 -0
  33. package/dist/index.js +30 -0
  34. package/dist/logger.d.cts +11 -0
  35. package/dist/logger.d.ts +11 -0
  36. package/dist/nearClient.cjs +18 -0
  37. package/dist/nearClient.d.cts +8 -0
  38. package/dist/nearClient.d.ts +8 -0
  39. package/dist/nearClient.js +18 -0
  40. package/dist/poaBridge/constants/blockchains.cjs +57 -0
  41. package/dist/poaBridge/constants/blockchains.d.cts +86 -0
  42. package/dist/poaBridge/constants/blockchains.d.ts +86 -0
  43. package/dist/poaBridge/constants/blockchains.js +54 -0
  44. package/dist/poaBridge/errors/withdrawal.cjs +52 -0
  45. package/dist/poaBridge/errors/withdrawal.d.cts +34 -0
  46. package/dist/poaBridge/errors/withdrawal.d.ts +34 -0
  47. package/dist/poaBridge/errors/withdrawal.js +50 -0
  48. package/dist/poaBridge/getPendingDeposits.cjs +9 -0
  49. package/dist/poaBridge/getPendingDeposits.d.cts +12 -0
  50. package/dist/poaBridge/getPendingDeposits.d.ts +13 -0
  51. package/dist/poaBridge/getPendingDeposits.js +9 -0
  52. package/dist/poaBridge/index.cjs +23 -0
  53. package/dist/poaBridge/index.d.cts +11 -0
  54. package/dist/poaBridge/index.d.ts +11 -0
  55. package/dist/poaBridge/index.js +18 -0
  56. package/dist/poaBridge/poaBridgeHttpClient/apis.cjs +38 -0
  57. package/dist/poaBridge/poaBridgeHttpClient/apis.d.cts +12 -0
  58. package/dist/poaBridge/poaBridgeHttpClient/apis.d.ts +12 -0
  59. package/dist/poaBridge/poaBridgeHttpClient/apis.js +32 -0
  60. package/dist/poaBridge/poaBridgeHttpClient/index.cjs +21 -0
  61. package/dist/poaBridge/poaBridgeHttpClient/index.d.cts +9 -0
  62. package/dist/poaBridge/poaBridgeHttpClient/index.d.ts +9 -0
  63. package/dist/poaBridge/poaBridgeHttpClient/index.js +16 -0
  64. package/dist/poaBridge/poaBridgeHttpClient/runtime.cjs +49 -0
  65. package/dist/poaBridge/poaBridgeHttpClient/runtime.js +47 -0
  66. package/dist/poaBridge/poaBridgeHttpClient/types.d.cts +161 -0
  67. package/dist/poaBridge/poaBridgeHttpClient/types.d.ts +161 -0
  68. package/dist/poaBridge/waitForWithdrawalCompletion.cjs +57 -0
  69. package/dist/poaBridge/waitForWithdrawalCompletion.d.cts +31 -0
  70. package/dist/poaBridge/waitForWithdrawalCompletion.d.ts +31 -0
  71. package/dist/poaBridge/waitForWithdrawalCompletion.js +56 -0
  72. package/dist/services/blockchainBalanceService.cjs +40 -0
  73. package/dist/services/blockchainBalanceService.d.cts +21 -0
  74. package/dist/services/blockchainBalanceService.d.ts +21 -0
  75. package/dist/services/blockchainBalanceService.js +37 -0
  76. package/dist/solverRelay/errors/intentSettlement.cjs +20 -0
  77. package/dist/solverRelay/errors/intentSettlement.d.cts +13 -0
  78. package/dist/solverRelay/errors/intentSettlement.d.ts +13 -0
  79. package/dist/solverRelay/errors/intentSettlement.js +20 -0
  80. package/dist/solverRelay/errors/quote.cjs +18 -0
  81. package/dist/solverRelay/errors/quote.d.cts +21 -0
  82. package/dist/solverRelay/errors/quote.d.ts +22 -0
  83. package/dist/solverRelay/errors/quote.js +18 -0
  84. package/dist/solverRelay/getQuote.cjs +49 -0
  85. package/dist/solverRelay/getQuote.d.cts +14 -0
  86. package/dist/solverRelay/getQuote.d.ts +14 -0
  87. package/dist/solverRelay/getQuote.js +49 -0
  88. package/dist/solverRelay/getStatus.cjs +26 -0
  89. package/dist/solverRelay/getStatus.d.cts +17 -0
  90. package/dist/solverRelay/getStatus.d.ts +18 -0
  91. package/dist/solverRelay/getStatus.js +26 -0
  92. package/dist/solverRelay/index.cjs +27 -0
  93. package/dist/solverRelay/index.d.cts +16 -0
  94. package/dist/solverRelay/index.d.ts +16 -0
  95. package/dist/solverRelay/index.js +22 -0
  96. package/dist/solverRelay/publishIntent.cjs +20 -0
  97. package/dist/solverRelay/publishIntent.d.cts +15 -0
  98. package/dist/solverRelay/publishIntent.d.ts +16 -0
  99. package/dist/solverRelay/publishIntent.js +20 -0
  100. package/dist/solverRelay/publishIntents.cjs +43 -0
  101. package/dist/solverRelay/publishIntents.d.cts +10 -0
  102. package/dist/solverRelay/publishIntents.d.ts +11 -0
  103. package/dist/solverRelay/publishIntents.js +42 -0
  104. package/dist/solverRelay/solverRelayHttpClient/apis.cjs +21 -0
  105. package/dist/solverRelay/solverRelayHttpClient/apis.d.cts +9 -0
  106. package/dist/solverRelay/solverRelayHttpClient/apis.d.ts +9 -0
  107. package/dist/solverRelay/solverRelayHttpClient/apis.js +18 -0
  108. package/dist/solverRelay/solverRelayHttpClient/index.cjs +18 -0
  109. package/dist/solverRelay/solverRelayHttpClient/index.d.cts +9 -0
  110. package/dist/solverRelay/solverRelayHttpClient/index.d.ts +9 -0
  111. package/dist/solverRelay/solverRelayHttpClient/index.js +13 -0
  112. package/dist/solverRelay/solverRelayHttpClient/runtime.cjs +60 -0
  113. package/dist/solverRelay/solverRelayHttpClient/runtime.js +58 -0
  114. package/dist/solverRelay/solverRelayHttpClient/types.d.cts +109 -0
  115. package/dist/solverRelay/solverRelayHttpClient/types.d.ts +109 -0
  116. package/dist/solverRelay/utils/parseFailedPublishError.cjs +40 -0
  117. package/dist/solverRelay/utils/parseFailedPublishError.d.cts +25 -0
  118. package/dist/solverRelay/utils/parseFailedPublishError.d.ts +26 -0
  119. package/dist/solverRelay/utils/parseFailedPublishError.js +39 -0
  120. package/dist/solverRelay/utils/quoteWithLog.cjs +21 -0
  121. package/dist/solverRelay/utils/quoteWithLog.d.cts +12 -0
  122. package/dist/solverRelay/utils/quoteWithLog.d.ts +14 -0
  123. package/dist/solverRelay/utils/quoteWithLog.js +21 -0
  124. package/dist/solverRelay/waitForIntentSettlement.cjs +52 -0
  125. package/dist/solverRelay/waitForIntentSettlement.d.cts +30 -0
  126. package/dist/solverRelay/waitForIntentSettlement.d.ts +30 -0
  127. package/dist/solverRelay/waitForIntentSettlement.js +52 -0
  128. package/dist/types/authHandle.cjs +22 -0
  129. package/dist/types/authHandle.d.cts +25 -0
  130. package/dist/types/authHandle.d.ts +25 -0
  131. package/dist/types/authHandle.js +16 -0
  132. package/dist/types/base.d.cts +45 -0
  133. package/dist/types/base.d.ts +45 -0
  134. package/dist/types/intentsUserId.d.cts +10 -0
  135. package/dist/types/intentsUserId.d.ts +10 -0
  136. package/dist/types/walletMessage.cjs +11 -0
  137. package/dist/types/walletMessage.d.cts +106 -0
  138. package/dist/types/walletMessage.d.ts +106 -0
  139. package/dist/types/walletMessage.js +5 -0
  140. package/dist/utils/abortSignal.cjs +19 -0
  141. package/dist/utils/abortSignal.js +18 -0
  142. package/dist/utils/appFee.cjs +20 -0
  143. package/dist/utils/appFee.d.cts +9 -0
  144. package/dist/utils/appFee.d.ts +9 -0
  145. package/dist/utils/appFee.js +15 -0
  146. package/dist/utils/assert.cjs +9 -0
  147. package/dist/utils/assert.d.cts +7 -0
  148. package/dist/utils/assert.d.ts +7 -0
  149. package/dist/utils/assert.js +9 -0
  150. package/dist/utils/authIdentity.cjs +56 -0
  151. package/dist/utils/authIdentity.d.cts +34 -0
  152. package/dist/utils/authIdentity.d.ts +34 -0
  153. package/dist/utils/authIdentity.js +50 -0
  154. package/dist/utils/failover.cjs +22 -0
  155. package/dist/utils/failover.d.cts +16 -0
  156. package/dist/utils/failover.d.ts +16 -0
  157. package/dist/utils/failover.js +20 -0
  158. package/dist/utils/handleRPCResponse.cjs +30 -0
  159. package/dist/utils/handleRPCResponse.js +28 -0
  160. package/dist/utils/index.cjs +55 -0
  161. package/dist/utils/index.d.cts +13 -0
  162. package/dist/utils/index.d.ts +13 -0
  163. package/dist/utils/index.js +50 -0
  164. package/dist/utils/messageFactory.cjs +137 -0
  165. package/dist/utils/messageFactory.d.cts +70 -0
  166. package/dist/utils/messageFactory.d.ts +70 -0
  167. package/dist/utils/messageFactory.js +132 -0
  168. package/dist/utils/multiPayload/webauthn.cjs +27 -0
  169. package/dist/utils/multiPayload/webauthn.js +26 -0
  170. package/dist/utils/near.cjs +58 -0
  171. package/dist/utils/near.d.cts +35 -0
  172. package/dist/utils/near.d.ts +35 -0
  173. package/dist/utils/near.js +53 -0
  174. package/dist/utils/poll.cjs +87 -0
  175. package/dist/utils/poll.d.cts +54 -0
  176. package/dist/utils/poll.d.ts +54 -0
  177. package/dist/utils/poll.js +85 -0
  178. package/dist/utils/prepareBroadcastRequest.cjs +98 -0
  179. package/dist/utils/prepareBroadcastRequest.d.cts +16 -0
  180. package/dist/utils/prepareBroadcastRequest.d.ts +16 -0
  181. package/dist/utils/prepareBroadcastRequest.js +90 -0
  182. package/dist/utils/promise/withTimeout.cjs +34 -0
  183. package/dist/utils/promise/withTimeout.d.cts +16 -0
  184. package/dist/utils/promise/withTimeout.d.ts +16 -0
  185. package/dist/utils/promise/withTimeout.js +34 -0
  186. package/dist/utils/request.cjs +100 -0
  187. package/dist/utils/request.d.cts +27 -0
  188. package/dist/utils/request.d.ts +27 -0
  189. package/dist/utils/request.js +99 -0
  190. package/dist/utils/requestShouldRetry.cjs +20 -0
  191. package/dist/utils/requestShouldRetry.js +20 -0
  192. package/dist/utils/retry.cjs +66 -0
  193. package/dist/utils/retry.d.cts +56 -0
  194. package/dist/utils/retry.d.ts +56 -0
  195. package/dist/utils/retry.js +64 -0
  196. package/dist/utils/serialize.cjs +82 -0
  197. package/dist/utils/serialize.d.cts +17 -0
  198. package/dist/utils/serialize.d.ts +17 -0
  199. package/dist/utils/serialize.js +81 -0
  200. package/dist/utils/stellarAddressToBytes.cjs +295 -0
  201. package/dist/utils/stellarAddressToBytes.js +294 -0
  202. package/dist/utils/token.cjs +8 -0
  203. package/dist/utils/token.js +7 -0
  204. package/dist/utils/tokenUtils.cjs +263 -0
  205. package/dist/utils/tokenUtils.d.cts +88 -0
  206. package/dist/utils/tokenUtils.d.ts +88 -0
  207. package/dist/utils/tokenUtils.js +238 -0
  208. package/dist/utils/tronAddressToHex.cjs +18 -0
  209. package/dist/utils/tronAddressToHex.js +17 -0
  210. package/dist/utils/uint8Array.cjs +15 -0
  211. package/dist/utils/uint8Array.d.cts +4 -0
  212. package/dist/utils/uint8Array.d.ts +4 -0
  213. package/dist/utils/uint8Array.js +14 -0
  214. package/dist/utils/webAuthn.cjs +91 -0
  215. package/dist/utils/webAuthn.js +89 -0
  216. package/package.json +56 -0
@@ -0,0 +1,54 @@
1
+ import { BaseError } from "../errors/base.js";
2
+
3
+ //#region src/utils/poll.d.ts
4
+
5
+ /**
6
+ * Sentinel value to signal that polling should continue.
7
+ * Return this from the poll function to indicate "not done yet".
8
+ */
9
+ declare const POLL_PENDING: unique symbol;
10
+ type PollTimeoutErrorType = PollTimeoutError & {
11
+ name: "PollTimeoutError";
12
+ };
13
+ declare class PollTimeoutError extends BaseError {
14
+ elapsedMs: number;
15
+ timeoutMs: number;
16
+ name: "PollTimeoutError";
17
+ constructor(elapsedMs: number, timeoutMs: number);
18
+ }
19
+ interface CompletionStats {
20
+ /** 50th percentile (median completion time in ms) */
21
+ p50: number;
22
+ /** 90th percentile (in ms) */
23
+ p90: number;
24
+ /** 99th percentile - hard timeout (in ms) */
25
+ p99: number;
26
+ }
27
+ interface PollOptions {
28
+ stats: CompletionStats;
29
+ signal?: AbortSignal;
30
+ /** Minimum interval floor (default: 300ms) */
31
+ minInterval?: number;
32
+ /** Maximum interval ceiling (default: 30000ms) */
33
+ maxInterval?: number;
34
+ }
35
+ /**
36
+ * Polls a function using latency-optimized intervals.
37
+ *
38
+ * Polls aggressively early (when completion is most likely), backs off later
39
+ * for outliers. Optimized for latency-sensitive operations like swaps.
40
+ *
41
+ * Interval strategy:
42
+ * - 0 → p50: HOT (300ms) - most completions happen here (~50%)
43
+ * - p50 → p90: COOLING (3s) - moderate polling (~40%)
44
+ * - p90 → p99: COLD (10s) - back off for outliers (~9%)
45
+ *
46
+ * @param fn - Function to poll. Return POLL_PENDING to continue, any other value to complete.
47
+ * @param options - Polling configuration with completion stats
48
+ * @returns The resolved value from fn
49
+ * @throws PollTimeoutError when p99 is exceeded
50
+ * @throws AbortError when signal is aborted
51
+ */
52
+ declare function poll<T>(fn: () => Promise<T | typeof POLL_PENDING>, options: PollOptions): Promise<T>;
53
+ //#endregion
54
+ export { CompletionStats, POLL_PENDING, PollOptions, PollTimeoutError, PollTimeoutErrorType, poll };
@@ -0,0 +1,85 @@
1
+ import { BaseError } from "../errors/base.js";
2
+
3
+ //#region src/utils/poll.ts
4
+ const PHASE = {
5
+ HOT: "HOT",
6
+ COOLING: "COOLING",
7
+ COLD: "COLD"
8
+ };
9
+ const DEFAULT_INTERVALS = {
10
+ [PHASE.HOT]: 300,
11
+ [PHASE.COOLING]: 3e3,
12
+ [PHASE.COLD]: 1e4
13
+ };
14
+ /**
15
+ * Sentinel value to signal that polling should continue.
16
+ * Return this from the poll function to indicate "not done yet".
17
+ */
18
+ const POLL_PENDING = Symbol("poll.pending");
19
+ var PollTimeoutError = class extends BaseError {
20
+ constructor(elapsedMs, timeoutMs) {
21
+ super("Polling timed out", { details: `Operation did not complete within ${timeoutMs}ms (elapsed: ${elapsedMs}ms)` });
22
+ this.elapsedMs = elapsedMs;
23
+ this.timeoutMs = timeoutMs;
24
+ this.name = "PollTimeoutError";
25
+ }
26
+ };
27
+ /**
28
+ * Polls a function using latency-optimized intervals.
29
+ *
30
+ * Polls aggressively early (when completion is most likely), backs off later
31
+ * for outliers. Optimized for latency-sensitive operations like swaps.
32
+ *
33
+ * Interval strategy:
34
+ * - 0 → p50: HOT (300ms) - most completions happen here (~50%)
35
+ * - p50 → p90: COOLING (3s) - moderate polling (~40%)
36
+ * - p90 → p99: COLD (10s) - back off for outliers (~9%)
37
+ *
38
+ * @param fn - Function to poll. Return POLL_PENDING to continue, any other value to complete.
39
+ * @param options - Polling configuration with completion stats
40
+ * @returns The resolved value from fn
41
+ * @throws PollTimeoutError when p99 is exceeded
42
+ * @throws AbortError when signal is aborted
43
+ */
44
+ async function poll(fn, options) {
45
+ const { stats, signal, minInterval = 300, maxInterval = 3e4 } = options;
46
+ const { p50, p90, p99 } = stats;
47
+ const startTime = performance.now();
48
+ while (true) {
49
+ signal?.throwIfAborted();
50
+ const elapsed = performance.now() - startTime;
51
+ if (elapsed >= p99) throw new PollTimeoutError(elapsed, p99);
52
+ const result = await fn();
53
+ if (result !== POLL_PENDING) return result;
54
+ const rawInterval = DEFAULT_INTERVALS[getPhase(elapsed, p50, p90)];
55
+ await sleep(clamp(rawInterval, minInterval, maxInterval), signal);
56
+ }
57
+ }
58
+ function getPhase(elapsed, p50, p90) {
59
+ if (elapsed < p50) return PHASE.HOT;
60
+ if (elapsed < p90) return PHASE.COOLING;
61
+ return PHASE.COLD;
62
+ }
63
+ function clamp(value, min, max) {
64
+ return Math.max(min, Math.min(max, value));
65
+ }
66
+ function sleep(ms, signal) {
67
+ return new Promise((resolve, reject) => {
68
+ if (signal?.aborted) {
69
+ reject(signal.reason);
70
+ return;
71
+ }
72
+ const abortHandler = () => {
73
+ clearTimeout(timeoutId);
74
+ reject(signal?.reason);
75
+ };
76
+ const timeoutId = setTimeout(() => {
77
+ signal?.removeEventListener("abort", abortHandler);
78
+ resolve();
79
+ }, ms);
80
+ signal?.addEventListener("abort", abortHandler);
81
+ });
82
+ }
83
+
84
+ //#endregion
85
+ export { POLL_PENDING, PollTimeoutError, poll };
@@ -0,0 +1,98 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_assert = require('./assert.cjs');
3
+ const require_stellarAddressToBytes = require('./stellarAddressToBytes.cjs');
4
+ const require_webauthn = require('./multiPayload/webauthn.cjs');
5
+ let _scure_base = require("@scure/base");
6
+
7
+ //#region src/utils/prepareBroadcastRequest.ts
8
+ var prepareBroadcastRequest_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
9
+ normalizeERC191Signature: () => normalizeERC191Signature,
10
+ prepareSwapSignedData: () => prepareSwapSignedData,
11
+ transformERC191Signature: () => transformERC191Signature
12
+ });
13
+ function prepareSwapSignedData(signature, userInfo) {
14
+ switch (signature.type) {
15
+ case "NEP413": return {
16
+ standard: "nep413",
17
+ payload: {
18
+ message: signature.signedData.message,
19
+ nonce: _scure_base.base64.encode(signature.signedData.nonce),
20
+ recipient: signature.signedData.recipient,
21
+ callbackUrl: signature.signedData.callbackUrl
22
+ },
23
+ public_key: signature.signatureData.publicKey,
24
+ signature: transformNEP141Signature(signature.signatureData.signature)
25
+ };
26
+ case "ERC191": return {
27
+ standard: "erc191",
28
+ payload: signature.signedData.message,
29
+ signature: transformERC191Signature(signature.signatureData)
30
+ };
31
+ case "SOLANA":
32
+ require_assert.assert(userInfo.userChainType === "solana", "User chain and signature chain must match");
33
+ return {
34
+ standard: "raw_ed25519",
35
+ payload: new TextDecoder().decode(signature.signedData.message),
36
+ public_key: `ed25519:${userInfo.userAddress}`,
37
+ signature: transformED25519Signature(signature.signatureData)
38
+ };
39
+ case "WEBAUTHN": return require_webauthn.makeWebAuthnMultiPayload(userInfo, signature);
40
+ case "TON_CONNECT": return {
41
+ standard: "ton_connect",
42
+ address: signature.signatureData.address,
43
+ domain: signature.signatureData.domain,
44
+ timestamp: signature.signatureData.timestamp,
45
+ payload: signature.signatureData.payload,
46
+ public_key: `ed25519:${_scure_base.base58.encode(_scure_base.hex.decode(userInfo.userAddress))}`,
47
+ signature: `ed25519:${_scure_base.base58.encode(_scure_base.base64.decode(signature.signatureData.signature))}`
48
+ };
49
+ case "STELLAR_SEP53":
50
+ require_assert.assert(userInfo.userChainType === "stellar", "User chain and signature chain must match");
51
+ return {
52
+ standard: "sep53",
53
+ payload: signature.signedData.message,
54
+ public_key: `ed25519:${_scure_base.base58.encode(require_stellarAddressToBytes.stellarAddressToBytes(userInfo.userAddress))}`,
55
+ signature: transformED25519Signature(signature.signatureData)
56
+ };
57
+ case "TRON": return {
58
+ standard: "tip191",
59
+ payload: signature.signedData.message,
60
+ signature: transformERC191Signature(signature.signatureData)
61
+ };
62
+ default: throw new Error("exhaustive check failed");
63
+ }
64
+ }
65
+ function transformNEP141Signature(signature) {
66
+ return `ed25519:${_scure_base.base58.encode(_scure_base.base64.decode(signature))}`;
67
+ }
68
+ function transformERC191Signature(signature) {
69
+ const normalizedSignature = normalizeERC191Signature(signature);
70
+ const bytes = _scure_base.hex.decode(normalizedSignature.startsWith("0x") ? normalizedSignature.slice(2) : normalizedSignature);
71
+ return `secp256k1:${_scure_base.base58.encode(bytes)}`;
72
+ }
73
+ function normalizeERC191Signature(signature) {
74
+ let v = Number.parseInt(signature.slice(-2), 16);
75
+ v = toRecoveryBit(v);
76
+ const vHex = v.toString(16).padStart(2, "0");
77
+ return signature.slice(0, -2) + vHex;
78
+ }
79
+ function toRecoveryBit(yParityOrV) {
80
+ if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV;
81
+ if (yParityOrV === 27) return 0;
82
+ if (yParityOrV === 28) return 1;
83
+ throw new Error("Invalid yParityOrV value");
84
+ }
85
+ function transformED25519Signature(signature) {
86
+ return `ed25519:${_scure_base.base58.encode(signature)}`;
87
+ }
88
+
89
+ //#endregion
90
+ exports.normalizeERC191Signature = normalizeERC191Signature;
91
+ Object.defineProperty(exports, 'prepareBroadcastRequest_exports', {
92
+ enumerable: true,
93
+ get: function () {
94
+ return prepareBroadcastRequest_exports;
95
+ }
96
+ });
97
+ exports.prepareSwapSignedData = prepareSwapSignedData;
98
+ exports.transformERC191Signature = transformERC191Signature;
@@ -0,0 +1,16 @@
1
+ import { Params, PublishIntentRequest } from "../solverRelay/solverRelayHttpClient/types.cjs";
2
+ import { AuthMethod } from "../types/authHandle.cjs";
3
+ import { WalletSignatureResult } from "../types/walletMessage.cjs";
4
+
5
+ //#region src/utils/prepareBroadcastRequest.d.ts
6
+ declare namespace prepareBroadcastRequest_d_exports {
7
+ export { normalizeERC191Signature, prepareSwapSignedData, transformERC191Signature };
8
+ }
9
+ declare function prepareSwapSignedData(signature: WalletSignatureResult, userInfo: {
10
+ userAddress: string;
11
+ userChainType: AuthMethod;
12
+ }): Params<PublishIntentRequest>["signed_data"];
13
+ declare function transformERC191Signature(signature: string): string;
14
+ declare function normalizeERC191Signature(signature: string): string;
15
+ //#endregion
16
+ export { normalizeERC191Signature, prepareBroadcastRequest_d_exports, prepareSwapSignedData, transformERC191Signature };
@@ -0,0 +1,16 @@
1
+ import { Params, PublishIntentRequest } from "../solverRelay/solverRelayHttpClient/types.js";
2
+ import { AuthMethod } from "../types/authHandle.js";
3
+ import { WalletSignatureResult } from "../types/walletMessage.js";
4
+
5
+ //#region src/utils/prepareBroadcastRequest.d.ts
6
+ declare namespace prepareBroadcastRequest_d_exports {
7
+ export { normalizeERC191Signature, prepareSwapSignedData, transformERC191Signature };
8
+ }
9
+ declare function prepareSwapSignedData(signature: WalletSignatureResult, userInfo: {
10
+ userAddress: string;
11
+ userChainType: AuthMethod;
12
+ }): Params<PublishIntentRequest>["signed_data"];
13
+ declare function transformERC191Signature(signature: string): string;
14
+ declare function normalizeERC191Signature(signature: string): string;
15
+ //#endregion
16
+ export { normalizeERC191Signature, prepareBroadcastRequest_d_exports, prepareSwapSignedData, transformERC191Signature };
@@ -0,0 +1,90 @@
1
+ import { __exportAll } from "../_virtual/rolldown_runtime.js";
2
+ import { assert } from "./assert.js";
3
+ import { stellarAddressToBytes } from "./stellarAddressToBytes.js";
4
+ import { makeWebAuthnMultiPayload } from "./multiPayload/webauthn.js";
5
+ import { base58, base64, hex } from "@scure/base";
6
+
7
+ //#region src/utils/prepareBroadcastRequest.ts
8
+ var prepareBroadcastRequest_exports = /* @__PURE__ */ __exportAll({
9
+ normalizeERC191Signature: () => normalizeERC191Signature,
10
+ prepareSwapSignedData: () => prepareSwapSignedData,
11
+ transformERC191Signature: () => transformERC191Signature
12
+ });
13
+ function prepareSwapSignedData(signature, userInfo) {
14
+ switch (signature.type) {
15
+ case "NEP413": return {
16
+ standard: "nep413",
17
+ payload: {
18
+ message: signature.signedData.message,
19
+ nonce: base64.encode(signature.signedData.nonce),
20
+ recipient: signature.signedData.recipient,
21
+ callbackUrl: signature.signedData.callbackUrl
22
+ },
23
+ public_key: signature.signatureData.publicKey,
24
+ signature: transformNEP141Signature(signature.signatureData.signature)
25
+ };
26
+ case "ERC191": return {
27
+ standard: "erc191",
28
+ payload: signature.signedData.message,
29
+ signature: transformERC191Signature(signature.signatureData)
30
+ };
31
+ case "SOLANA":
32
+ assert(userInfo.userChainType === "solana", "User chain and signature chain must match");
33
+ return {
34
+ standard: "raw_ed25519",
35
+ payload: new TextDecoder().decode(signature.signedData.message),
36
+ public_key: `ed25519:${userInfo.userAddress}`,
37
+ signature: transformED25519Signature(signature.signatureData)
38
+ };
39
+ case "WEBAUTHN": return makeWebAuthnMultiPayload(userInfo, signature);
40
+ case "TON_CONNECT": return {
41
+ standard: "ton_connect",
42
+ address: signature.signatureData.address,
43
+ domain: signature.signatureData.domain,
44
+ timestamp: signature.signatureData.timestamp,
45
+ payload: signature.signatureData.payload,
46
+ public_key: `ed25519:${base58.encode(hex.decode(userInfo.userAddress))}`,
47
+ signature: `ed25519:${base58.encode(base64.decode(signature.signatureData.signature))}`
48
+ };
49
+ case "STELLAR_SEP53":
50
+ assert(userInfo.userChainType === "stellar", "User chain and signature chain must match");
51
+ return {
52
+ standard: "sep53",
53
+ payload: signature.signedData.message,
54
+ public_key: `ed25519:${base58.encode(stellarAddressToBytes(userInfo.userAddress))}`,
55
+ signature: transformED25519Signature(signature.signatureData)
56
+ };
57
+ case "TRON": return {
58
+ standard: "tip191",
59
+ payload: signature.signedData.message,
60
+ signature: transformERC191Signature(signature.signatureData)
61
+ };
62
+ default: throw new Error("exhaustive check failed");
63
+ }
64
+ }
65
+ function transformNEP141Signature(signature) {
66
+ return `ed25519:${base58.encode(base64.decode(signature))}`;
67
+ }
68
+ function transformERC191Signature(signature) {
69
+ const normalizedSignature = normalizeERC191Signature(signature);
70
+ const bytes = hex.decode(normalizedSignature.startsWith("0x") ? normalizedSignature.slice(2) : normalizedSignature);
71
+ return `secp256k1:${base58.encode(bytes)}`;
72
+ }
73
+ function normalizeERC191Signature(signature) {
74
+ let v = Number.parseInt(signature.slice(-2), 16);
75
+ v = toRecoveryBit(v);
76
+ const vHex = v.toString(16).padStart(2, "0");
77
+ return signature.slice(0, -2) + vHex;
78
+ }
79
+ function toRecoveryBit(yParityOrV) {
80
+ if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV;
81
+ if (yParityOrV === 27) return 0;
82
+ if (yParityOrV === 28) return 1;
83
+ throw new Error("Invalid yParityOrV value");
84
+ }
85
+ function transformED25519Signature(signature) {
86
+ return `ed25519:${base58.encode(signature)}`;
87
+ }
88
+
89
+ //#endregion
90
+ export { normalizeERC191Signature, prepareBroadcastRequest_exports, prepareSwapSignedData, transformERC191Signature };
@@ -0,0 +1,34 @@
1
+ const require_base = require('../../errors/base.cjs');
2
+
3
+ //#region src/utils/promise/withTimeout.ts
4
+ function withTimeout(fn, { errorInstance = /* @__PURE__ */ new Error("timed out"), timeout, signal }) {
5
+ return new Promise((resolve, reject) => {
6
+ (async () => {
7
+ let timeoutId;
8
+ try {
9
+ const controller = new AbortController();
10
+ if (timeout > 0) timeoutId = setTimeout(() => {
11
+ if (signal) controller.abort(new SpecialInternalTimeoutError());
12
+ else reject(errorInstance);
13
+ }, timeout);
14
+ resolve(await fn({ signal: signal ? controller.signal : null }));
15
+ } catch (err) {
16
+ if (err instanceof SpecialInternalTimeoutError) reject(errorInstance);
17
+ reject(err);
18
+ } finally {
19
+ clearTimeout(timeoutId);
20
+ }
21
+ })();
22
+ });
23
+ }
24
+ var SpecialInternalTimeoutError = class extends require_base.BaseError {
25
+ constructor() {
26
+ super("Special internal timeout error.", {
27
+ name: "SpecialInternalTimeoutError",
28
+ details: "This error should be never be caught since another error instance is rethrown."
29
+ });
30
+ }
31
+ };
32
+
33
+ //#endregion
34
+ exports.withTimeout = withTimeout;
@@ -0,0 +1,16 @@
1
+ //#region src/utils/promise/withTimeout.d.ts
2
+ declare function withTimeout<data>(fn: ({
3
+ signal
4
+ }: {
5
+ signal: AbortController["signal"] | null;
6
+ }) => Promise<data>, {
7
+ errorInstance,
8
+ timeout,
9
+ signal
10
+ }: {
11
+ errorInstance?: Error | undefined;
12
+ timeout: number;
13
+ signal?: boolean | undefined;
14
+ }): Promise<data>;
15
+ //#endregion
16
+ export { withTimeout };
@@ -0,0 +1,16 @@
1
+ //#region src/utils/promise/withTimeout.d.ts
2
+ declare function withTimeout<data>(fn: ({
3
+ signal
4
+ }: {
5
+ signal: AbortController["signal"] | null;
6
+ }) => Promise<data>, {
7
+ errorInstance,
8
+ timeout,
9
+ signal
10
+ }: {
11
+ errorInstance?: Error | undefined;
12
+ timeout: number;
13
+ signal?: boolean | undefined;
14
+ }): Promise<data>;
15
+ //#endregion
16
+ export { withTimeout };
@@ -0,0 +1,34 @@
1
+ import { BaseError } from "../../errors/base.js";
2
+
3
+ //#region src/utils/promise/withTimeout.ts
4
+ function withTimeout(fn, { errorInstance = /* @__PURE__ */ new Error("timed out"), timeout, signal }) {
5
+ return new Promise((resolve, reject) => {
6
+ (async () => {
7
+ let timeoutId;
8
+ try {
9
+ const controller = new AbortController();
10
+ if (timeout > 0) timeoutId = setTimeout(() => {
11
+ if (signal) controller.abort(new SpecialInternalTimeoutError());
12
+ else reject(errorInstance);
13
+ }, timeout);
14
+ resolve(await fn({ signal: signal ? controller.signal : null }));
15
+ } catch (err) {
16
+ if (err instanceof SpecialInternalTimeoutError) reject(errorInstance);
17
+ reject(err);
18
+ } finally {
19
+ clearTimeout(timeoutId);
20
+ }
21
+ })();
22
+ });
23
+ }
24
+ var SpecialInternalTimeoutError = class extends BaseError {
25
+ constructor() {
26
+ super("Special internal timeout error.", {
27
+ name: "SpecialInternalTimeoutError",
28
+ details: "This error should be never be caught since another error instance is rethrown."
29
+ });
30
+ }
31
+ };
32
+
33
+ //#endregion
34
+ export { withTimeout };
@@ -0,0 +1,100 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_request = require('../errors/request.cjs');
3
+ const require_isNetworkError = require('../errors/utils/isNetworkError.cjs');
4
+ const require_toError = require('../errors/utils/toError.cjs');
5
+ const require_abortSignal = require('./abortSignal.cjs');
6
+ const require_withTimeout = require('./promise/withTimeout.cjs');
7
+ const require_requestShouldRetry = require('./requestShouldRetry.cjs');
8
+ let _lifeomic_attempt = require("@lifeomic/attempt");
9
+
10
+ //#region src/utils/request.ts
11
+ async function request({ retryOptions = { maxAttempts: 1 }, logger, ...params }) {
12
+ const overallStartTime = performance.now();
13
+ let totalNetworkTime = 0;
14
+ let attemptCount = 0;
15
+ const response = await (0, _lifeomic_attempt.retry)(async (ctx) => {
16
+ attemptCount = ctx.attemptNum + 1;
17
+ const attemptStartTime = performance.now();
18
+ logger?.debug("Sending HTTP request", {
19
+ url: params.url.toString(),
20
+ method: params.fetchOptions?.method || "GET",
21
+ body: JSON.stringify(params.body),
22
+ attempt: ctx.attemptNum
23
+ });
24
+ const response$1 = await request_(params);
25
+ const attemptDuration = performance.now() - attemptStartTime;
26
+ totalNetworkTime += attemptDuration;
27
+ logger?.debug("HTTP request attempt completed", {
28
+ attempt: ctx.attemptNum,
29
+ attemptDuration: Math.floor(attemptDuration),
30
+ statusCode: response$1.status,
31
+ success: response$1.ok,
32
+ responseSize: response$1.headers.get("content-length")
33
+ });
34
+ return response$1;
35
+ }, {
36
+ ...retryOptions,
37
+ handleError: (err, context) => {
38
+ logger?.error("HTTP request attempt failed", {
39
+ attempt: context.attemptNum,
40
+ errorMessage: require_toError.toError(err).message
41
+ });
42
+ if (!require_requestShouldRetry.requestShouldRetry(err) || params.fetchOptions?.signal?.reason === err) context.abort();
43
+ }
44
+ });
45
+ const overallDuration = performance.now() - overallStartTime;
46
+ const retryOverhead = overallDuration - totalNetworkTime;
47
+ logger?.[attemptCount > 1 ? "info" : "debug"]("HTTP request completed", {
48
+ statusCode: response.status,
49
+ success: response.ok,
50
+ totalDuration: Math.floor(overallDuration),
51
+ networkTime: Math.floor(totalNetworkTime),
52
+ retryOverhead: Math.floor(retryOverhead),
53
+ attempts: attemptCount,
54
+ responseSize: response.headers.get("content-length")
55
+ });
56
+ return response;
57
+ }
58
+ async function request_({ url, body, timeout = 1e4, fetchOptions }) {
59
+ const { headers: customHeaders, method, signal: signal_ } = fetchOptions ?? {};
60
+ try {
61
+ const headers = new Headers(customHeaders);
62
+ headers.set("Content-Type", "application/json");
63
+ const response = await require_withTimeout.withTimeout(({ signal }) => {
64
+ return fetch(url, {
65
+ ...fetchOptions,
66
+ method,
67
+ headers,
68
+ body: JSON.stringify(body),
69
+ signal: require_abortSignal.mergeAbortSignals([signal_, timeout > 0 ? signal : null].filter(Boolean))
70
+ });
71
+ }, {
72
+ errorInstance: new require_request.TimeoutError({
73
+ body,
74
+ url: url.toString()
75
+ }),
76
+ timeout,
77
+ signal: true
78
+ });
79
+ if (!response.ok) throw new require_request.HttpRequestError({
80
+ body,
81
+ details: response.statusText,
82
+ headers: response.headers,
83
+ status: response.status,
84
+ url: url.toString()
85
+ });
86
+ return response;
87
+ } catch (err) {
88
+ if (err instanceof require_request.HttpRequestError) throw err;
89
+ if (err instanceof require_request.TimeoutError) throw err;
90
+ if (require_isNetworkError.isNetworkError(err)) throw new require_request.HttpRequestError({
91
+ body,
92
+ cause: err,
93
+ url: url.toString()
94
+ });
95
+ throw err;
96
+ }
97
+ }
98
+
99
+ //#endregion
100
+ exports.request = request;
@@ -0,0 +1,27 @@
1
+ import { HttpRequestError, TimeoutError } from "../errors/request.cjs";
2
+ import { ILogger } from "../logger.cjs";
3
+ import { RetryOptions } from "./retry.cjs";
4
+
5
+ //#region src/utils/request.d.ts
6
+ type RequestErrorType = HttpRequestError | TimeoutError;
7
+ declare function request({
8
+ retryOptions,
9
+ logger,
10
+ ...params
11
+ }: Parameters<typeof request_>[0] & {
12
+ retryOptions?: RetryOptions;
13
+ logger?: ILogger;
14
+ }): Promise<Response>;
15
+ declare function request_({
16
+ url,
17
+ body,
18
+ timeout,
19
+ fetchOptions
20
+ }: {
21
+ url: string | URL;
22
+ body?: unknown | undefined;
23
+ timeout?: number | undefined;
24
+ fetchOptions?: Omit<RequestInit, "body"> | undefined;
25
+ }): Promise<Response>;
26
+ //#endregion
27
+ export { RequestErrorType, request };
@@ -0,0 +1,27 @@
1
+ import { HttpRequestError, TimeoutError } from "../errors/request.js";
2
+ import { ILogger } from "../logger.js";
3
+ import { RetryOptions } from "./retry.js";
4
+
5
+ //#region src/utils/request.d.ts
6
+ type RequestErrorType = HttpRequestError | TimeoutError;
7
+ declare function request({
8
+ retryOptions,
9
+ logger,
10
+ ...params
11
+ }: Parameters<typeof request_>[0] & {
12
+ retryOptions?: RetryOptions;
13
+ logger?: ILogger;
14
+ }): Promise<Response>;
15
+ declare function request_({
16
+ url,
17
+ body,
18
+ timeout,
19
+ fetchOptions
20
+ }: {
21
+ url: string | URL;
22
+ body?: unknown | undefined;
23
+ timeout?: number | undefined;
24
+ fetchOptions?: Omit<RequestInit, "body"> | undefined;
25
+ }): Promise<Response>;
26
+ //#endregion
27
+ export { RequestErrorType, request };