@qntx/wallet-engine 0.12.0 → 0.14.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 (81) hide show
  1. package/README.md +1057 -20
  2. package/dist/apps-fiat24.d.mts +202 -0
  3. package/dist/apps-fiat24.mjs +1378 -0
  4. package/dist/apps-fiat24.mjs.map +1 -0
  5. package/dist/apps-hyperliquid.d.mts +549 -0
  6. package/dist/apps-hyperliquid.mjs +2742 -0
  7. package/dist/apps-hyperliquid.mjs.map +1 -0
  8. package/dist/apps-polymarket.d.mts +729 -0
  9. package/dist/apps-polymarket.mjs +3786 -0
  10. package/dist/apps-polymarket.mjs.map +1 -0
  11. package/dist/apps.d.mts +136 -0
  12. package/dist/apps.mjs +535 -0
  13. package/dist/apps.mjs.map +1 -0
  14. package/dist/connect-BY1C5ZRI.mjs +210 -0
  15. package/dist/connect-BY1C5ZRI.mjs.map +1 -0
  16. package/dist/connect.d.mts +17 -9
  17. package/dist/connect.mjs +3 -185
  18. package/dist/controller-DpNVHVsj.d.mts +2295 -0
  19. package/dist/controller-rMnaxKAH.mjs +46 -0
  20. package/dist/controller-rMnaxKAH.mjs.map +1 -0
  21. package/dist/decimal-COJ4g8qy.mjs +38 -0
  22. package/dist/decimal-COJ4g8qy.mjs.map +1 -0
  23. package/dist/eligibility-BfM9ybYZ.mjs +48 -0
  24. package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
  25. package/dist/engine-Dic_kkEr.d.mts +1829 -0
  26. package/dist/errors-B8W-hoYW.d.mts +7 -0
  27. package/dist/errors-horUy5k1.mjs +24 -0
  28. package/dist/errors-horUy5k1.mjs.map +1 -0
  29. package/dist/gateway-contract.d.mts +3 -362
  30. package/dist/gateway-contract.mjs +1531 -81
  31. package/dist/gateway-contract.mjs.map +1 -1
  32. package/dist/idb.d.mts +5 -0
  33. package/dist/idb.mjs +122 -46
  34. package/dist/idb.mjs.map +1 -1
  35. package/dist/index-vBgfOFIh.d.mts +2227 -0
  36. package/dist/index.d.mts +58 -515
  37. package/dist/index.mjs +22314 -4901
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/json-BDwV38cj.mjs +15 -0
  40. package/dist/json-BDwV38cj.mjs.map +1 -0
  41. package/dist/link-Ceq8Dggp.mjs +139 -0
  42. package/dist/link-Ceq8Dggp.mjs.map +1 -0
  43. package/dist/primitives-DbSHLZKq.mjs +31 -0
  44. package/dist/primitives-DbSHLZKq.mjs.map +1 -0
  45. package/dist/push-message-AQuzoNFY.d.mts +84 -0
  46. package/dist/push-message-kbnH1A5w.mjs +142 -0
  47. package/dist/push-message-kbnH1A5w.mjs.map +1 -0
  48. package/dist/push.d.mts +13 -0
  49. package/dist/push.mjs +70 -0
  50. package/dist/push.mjs.map +1 -0
  51. package/dist/qr.d.mts +292 -0
  52. package/dist/qr.mjs +1725 -0
  53. package/dist/qr.mjs.map +1 -0
  54. package/dist/registry-CbtwcxkX.mjs +374 -0
  55. package/dist/registry-CbtwcxkX.mjs.map +1 -0
  56. package/dist/risk-DyABgg4W.mjs +757 -0
  57. package/dist/risk-DyABgg4W.mjs.map +1 -0
  58. package/dist/session-CNJFLarP.mjs +18 -0
  59. package/dist/session-CNJFLarP.mjs.map +1 -0
  60. package/dist/socket-ChG9JRT_.mjs +110 -0
  61. package/dist/socket-ChG9JRT_.mjs.map +1 -0
  62. package/dist/spi-BrTw5s98.d.mts +3 -0
  63. package/dist/timer-Cdk5rGM2.mjs +43 -0
  64. package/dist/timer-Cdk5rGM2.mjs.map +1 -0
  65. package/dist/types-BpvioFGo.d.mts +258 -0
  66. package/dist/types-DbftVZ3I.mjs +90 -0
  67. package/dist/types-DbftVZ3I.mjs.map +1 -0
  68. package/dist/walletconnect.d.mts +86 -0
  69. package/dist/walletconnect.mjs +1507 -0
  70. package/dist/walletconnect.mjs.map +1 -0
  71. package/dist/webln-BgrtPXpG.mjs +2593 -0
  72. package/dist/webln-BgrtPXpG.mjs.map +1 -0
  73. package/dist/webln-Bllk_xJ2.d.mts +666 -0
  74. package/package.json +94 -19
  75. package/dist/connect.mjs.map +0 -1
  76. package/dist/errors-DpkJneDe.d.mts +0 -1696
  77. package/dist/registry-Deo5WQe1.d.mts +0 -25
  78. package/dist/registry-wYrcuFNc.mjs +0 -99
  79. package/dist/registry-wYrcuFNc.mjs.map +0 -1
  80. package/dist/webln-DzsI7jVb.mjs +0 -3629
  81. package/dist/webln-DzsI7jVb.mjs.map +0 -1
@@ -1,27 +1,12 @@
1
- import { i as networkById, n as NETWORKS, r as SOLANA_NETWORKS, t as BITCOIN_NETWORKS } from "./registry-wYrcuFNc.mjs";
1
+ import { a as eligibilityResponse, c as parseWith, i as eligibilityRequest, n as appAvailability, o as accepts, r as eligibility, s as endpoint, t as APP_ID } from "./eligibility-BfM9ybYZ.mjs";
2
+ import { a as caip2, i as PROVIDER_PIN_HEADER, n as GATEWAY_ERRORS, o as clientId, r as PROVIDERS_HEADER, s as gatewayError, t as CLIENT_ID_HEADER } from "./primitives-DbSHLZKq.mjs";
3
+ import { a as networkById, i as TRON_NETWORKS, n as NETWORKS, r as SOLANA_NETWORKS, t as BITCOIN_NETWORKS } from "./registry-CbtwcxkX.mjs";
4
+ import { a as PUSH_ID_DOMAIN, c as PUSH_VERSION, d as pushAad, f as pushEventInput, i as PUSH_EVENT_KINDS, l as parsePushMessage, n as PUSH_BLOB_MAX, o as PUSH_KEYS_MAX, p as serializePushPlaintext, r as PUSH_EVENT_DOMAIN, s as PUSH_PLAINTEXT_MAX, t as PUSH_AAD_PREFIX, u as parsePushPlaintext } from "./push-message-kbnH1A5w.mjs";
5
+ import * as z$1 from "zod/mini";
2
6
  import { utf8ToBytes } from "@noble/hashes/utils.js";
3
- import * as z from "zod/mini";
4
- import { base64 } from "@scure/base";
7
+ import { isTronAddress } from "@qntx/wallet-chains/tron";
5
8
  import { sha256 } from "@noble/hashes/sha2.js";
6
- // src/gateway/contract/endpoint.ts
7
- /** One gateway route: its verb, versioned path template, and request/response schemas. */
8
- function endpoint(method, path, request, response) {
9
- return {
10
- method,
11
- path,
12
- request,
13
- response
14
- };
15
- }
16
- /** `value` typed by `schema`, or `undefined` when it does not satisfy it. */
17
- function parseWith(schema, value) {
18
- const result = z.safeParse(schema, value);
19
- return result.success ? result.data : void 0;
20
- }
21
- /** Whether `value` satisfies `schema` — lets consumers validate without importing zod. */
22
- function accepts(schema, value) {
23
- return z.safeParse(schema, value).success;
24
- }
9
+ import { base64 } from "@scure/base";
25
10
  // src/gateway/contract/rpc.ts
26
11
  /** One JSON-RPC call plus nothing else: batches may carry at most this many entries. */
27
12
  const RPC_BATCH_MAX = 20;
@@ -42,6 +27,7 @@ const EVM_RPC_METHODS = [
42
27
  "eth_getBlockTransactionCountByHash",
43
28
  "eth_getBlockTransactionCountByNumber",
44
29
  "eth_getCode",
30
+ "eth_getLogs",
45
31
  "eth_getProof",
46
32
  "eth_getStorageAt",
47
33
  "eth_getTransactionByBlockHashAndIndex",
@@ -59,11 +45,11 @@ const EVM_RPC_METHODS = [
59
45
  const SOLANA_RPC_METHODS = [
60
46
  "getAccountInfo",
61
47
  "getBalance",
62
- "getBlock",
63
48
  "getBlockHeight",
64
49
  "getBlockTime",
65
50
  "getEpochInfo",
66
51
  "getFeeForMessage",
52
+ "getFirstAvailableBlock",
67
53
  "getGenesisHash",
68
54
  "getLatestBlockhash",
69
55
  "getMinimumBalanceForRentExemption",
@@ -72,71 +58,833 @@ const SOLANA_RPC_METHODS = [
72
58
  "getSignatureStatuses",
73
59
  "getSignaturesForAddress",
74
60
  "getSlot",
61
+ "getStakeMinimumDelegation",
75
62
  "getTokenAccountBalance",
76
63
  "getTokenAccountsByOwner",
77
64
  "getTokenSupply",
78
65
  "getTransaction",
79
66
  "getVersion",
67
+ "getVoteAccounts",
80
68
  "isBlockhashValid",
81
69
  "sendTransaction",
82
70
  "simulateTransaction"
83
71
  ];
84
- const jsonRpcId = z.union([
85
- z.string(),
86
- z.number(),
87
- z.null()
72
+ /** Methods that relay a signed transaction — retrying one can double-broadcast it. */
73
+ const RPC_BROADCAST_METHODS = ["eth_sendRawTransaction", "sendTransaction"];
74
+ /**
75
+ * A request id is an int or a short string the caller chose — never `null`. `null` only exists on
76
+ * responses, where it reports a request that could not be parsed at all ({@link jsonRpcId}).
77
+ */
78
+ const jsonRpcRequestId = z$1.union([z$1.int(), z$1.string().check(z$1.maxLength(64))]);
79
+ /** A response id echoes the request's; a parse-level error legitimately answers with `null`. */
80
+ const jsonRpcId = z$1.union([
81
+ z$1.string(),
82
+ z$1.number(),
83
+ z$1.null()
88
84
  ]);
89
- const jsonRpcParams = z.optional(z.union([z.array(z.unknown()), z.record(z.string(), z.unknown())]));
90
- const callSchema = (method) => z.object({
91
- jsonrpc: z.literal("2.0"),
92
- id: jsonRpcId,
85
+ const jsonRpcParams = z$1.optional(z$1.union([z$1.array(z$1.unknown()), z$1.record(z$1.string(), z$1.unknown())]));
86
+ const callSchema = (method, params) => z$1.object({
87
+ jsonrpc: z$1.literal("2.0"),
88
+ id: jsonRpcRequestId,
93
89
  method,
94
- params: jsonRpcParams
90
+ params
95
91
  });
96
- const bodySchema = (call) => z.union([call, z.array(call).check(z.minLength(1), z.maxLength(20))]);
92
+ const bodySchema = (call) => z$1.union([call, z$1.array(call).check(z$1.minLength(1), z$1.maxLength(20))]);
97
93
  /** Method-agnostic wire shape of a call or batch (the gateway narrows by family). */
98
- const rpcRequest = bodySchema(callSchema(z.string()));
99
- const evmRpcRequest = bodySchema(callSchema(z.enum(EVM_RPC_METHODS)));
100
- const solanaRpcRequest = bodySchema(callSchema(z.enum(SOLANA_RPC_METHODS)));
101
- const successResponse = z.object({
102
- jsonrpc: z.literal("2.0"),
94
+ const rpcRequest = bodySchema(callSchema(z$1.string(), jsonRpcParams));
95
+ /** `eth_getLogs` is the one read whose cost the caller chooses: these bound it. */
96
+ const LOGS_BLOCK_RANGE_MAX = 500;
97
+ const LOGS_ADDRESS_MAX = 20;
98
+ const LOGS_TOPIC_ALTERNATIVES_MAX = 20;
99
+ /** Eth_getProof storage keys: upstream time scales with them while the published price is flat. */
100
+ const RPC_PROOF_KEYS_MAX = 100;
101
+ /** Eth_simulateV1 blockStateCalls: upstream time scales with blocks while the price is flat. */
102
+ const RPC_SIMULATE_BLOCKS_MAX = 16;
103
+ /** Eth_simulateV1 calls across all blocks: upstream time scales with them, the price is flat. */
104
+ const RPC_SIMULATE_CALLS_MAX = 100;
105
+ /** Eth_feeHistory blockCount: upstream time scales with it while the published price is flat. */
106
+ const FEE_HISTORY_BLOCKS_MAX = 1024;
107
+ /** Eth_feeHistory rewardPercentiles: upstream time scales with them, the price is flat. */
108
+ const FEE_HISTORY_PERCENTILES_MAX = 100;
109
+ const quantity = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{1,64}$/));
110
+ const hash32$1 = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{64}$/));
111
+ const evmAddress$3 = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{40}$/));
112
+ /** Even-length hex calldata; `0x` alone is legal (an empty payload). */
113
+ const hexData = z$1.string().check(z$1.regex(/^0x([0-9a-fA-F]{2})*$/));
114
+ /** The tags that name a recent block; `earliest` would make a range unbounded. */
115
+ const recentBlock = z$1.enum([
116
+ "latest",
117
+ "safe",
118
+ "finalized",
119
+ "pending"
120
+ ]);
121
+ const blockTag = z$1.enum([
122
+ "latest",
123
+ "earliest",
124
+ "pending",
125
+ "safe",
126
+ "finalized"
127
+ ]);
128
+ const tagOrNumber = z$1.union([blockTag, quantity]);
129
+ /** A "default block" parameter: tag, quantity, or the EIP-1898 object form. */
130
+ const blockParam = z$1.union([
131
+ tagOrNumber,
132
+ z$1.strictObject({ blockNumber: quantity }),
133
+ z$1.strictObject({
134
+ blockHash: hash32$1,
135
+ requireCanonical: z$1.optional(z$1.boolean())
136
+ })
137
+ ]);
138
+ /** Params may be omitted or `[]` for the methods that take none. */
139
+ const noParams = z$1.optional(z$1.tuple([]));
140
+ const optional = (inner) => z$1.optional(inner);
141
+ /** A transaction call object; `from`/`to` are the only fields the gateway constrains. */
142
+ const callTx = z$1.looseObject({
143
+ from: z$1.optional(evmAddress$3),
144
+ to: z$1.optional(z$1.union([evmAddress$3, z$1.null()]))
145
+ });
146
+ const logsScope = {
147
+ address: z$1.optional(z$1.union([evmAddress$3, z$1.array(evmAddress$3).check(z$1.minLength(1), z$1.maxLength(20))])),
148
+ topics: z$1.optional(z$1.array(z$1.union([
149
+ z$1.null(),
150
+ hash32$1,
151
+ z$1.array(hash32$1).check(z$1.maxLength(20))
152
+ ])).check(z$1.maxLength(4)))
153
+ };
154
+ const logsFilter = z$1.union([z$1.strictObject({
155
+ ...logsScope,
156
+ blockHash: hash32$1
157
+ }), z$1.strictObject({
158
+ ...logsScope,
159
+ fromBlock: z$1.optional(z$1.union([recentBlock, quantity])),
160
+ toBlock: z$1.optional(z$1.union([recentBlock, quantity]))
161
+ })]);
162
+ const isNumbered = (block) => block?.startsWith("0x") === true;
163
+ /** The only tags that move with the head; `safe` and `finalized` can trail it by thousands. */
164
+ const HEAD_TAGS = /* @__PURE__ */ new Set(["latest", "pending"]);
165
+ /**
166
+ * Why an `eth_getLogs` call is refused, or `undefined` when its filter is bounded: one block by
167
+ * hash, a numbered range of at most {@link LOGS_BLOCK_RANGE_MAX} blocks, or tags that name the same
168
+ * block or the head. `safe`/`finalized` may not pair with the head: on Arbitrum that span is
169
+ * thousands of blocks.
170
+ */
171
+ function logsFilterViolation(params) {
172
+ const parsed = z$1.safeParse(z$1.tuple([logsFilter]), params);
173
+ if (!parsed.success) return `eth_getLogs takes one filter of at most 20 addresses and 20 alternatives per topic, by blockHash or by a bounded block range`;
174
+ const [filter] = parsed.data;
175
+ if ("blockHash" in filter) return;
176
+ const from = filter.fromBlock ?? "latest";
177
+ const to = filter.toBlock ?? "latest";
178
+ if (isNumbered(from) !== isNumbered(to)) return "eth_getLogs needs fromBlock and toBlock to be both block numbers or both block tags";
179
+ if (!isNumbered(from) || !isNumbered(to)) return from === to || HEAD_TAGS.has(from) && HEAD_TAGS.has(to) ? void 0 : "eth_getLogs block tags must match or both name the head (latest or pending)";
180
+ const span = BigInt(to) - BigInt(from);
181
+ return span < 0n || span >= BigInt(500) ? `eth_getLogs is limited to a range of 500 blocks` : void 0;
182
+ }
183
+ const simulateBlocks = z$1.array(z$1.looseObject({ calls: z$1.optional(z$1.array(z$1.unknown())) }));
184
+ /** The eth_simulateV1 payload: loose except the bounds its flat price cannot cover. */
185
+ const simulateInput = z$1.looseObject({}).check(z$1.refine((input) => {
186
+ const parsed = z$1.safeParse(z$1.looseObject({ blockStateCalls: simulateBlocks }), input);
187
+ if (!parsed.success) return !("blockStateCalls" in input);
188
+ const { blockStateCalls } = parsed.data;
189
+ return blockStateCalls.length <= 16 && blockStateCalls.reduce((sum, block) => sum + (block.calls?.length ?? 0), 0) <= 100;
190
+ }));
191
+ /** The params shape each allow-listed EVM method accepts — one entry per method, no wildcards. */
192
+ const EVM_PARAMS = {
193
+ eth_blobBaseFee: noParams,
194
+ eth_blockNumber: noParams,
195
+ eth_call: z$1.tuple([callTx, optional(blockParam)], z$1.unknown()),
196
+ eth_chainId: noParams,
197
+ eth_createAccessList: z$1.tuple([callTx, optional(blockParam)], z$1.unknown()),
198
+ eth_estimateGas: z$1.tuple([callTx, optional(blockParam)], z$1.unknown()),
199
+ eth_feeHistory: z$1.tuple([
200
+ z$1.union([quantity, z$1.int().check(z$1.nonnegative())]).check(z$1.refine((count) => {
201
+ try {
202
+ return BigInt(count) <= BigInt(FEE_HISTORY_BLOCKS_MAX);
203
+ } catch {
204
+ return true;
205
+ }
206
+ })),
207
+ tagOrNumber,
208
+ optional(z$1.union([z$1.array(z$1.number()).check(z$1.maxLength(100)), z$1.null()]))
209
+ ]),
210
+ eth_gasPrice: noParams,
211
+ eth_getBalance: z$1.tuple([evmAddress$3, optional(blockParam)]),
212
+ eth_getBlockByHash: z$1.tuple([hash32$1, z$1.boolean()]),
213
+ eth_getBlockByNumber: z$1.tuple([tagOrNumber, z$1.boolean()]),
214
+ eth_getBlockReceipts: z$1.tuple([blockParam]),
215
+ eth_getBlockTransactionCountByHash: z$1.tuple([hash32$1]),
216
+ eth_getBlockTransactionCountByNumber: z$1.tuple([tagOrNumber]),
217
+ eth_getCode: z$1.tuple([evmAddress$3, optional(blockParam)]),
218
+ eth_getLogs: z$1.array(z$1.unknown()).check(z$1.refine((params) => logsFilterViolation(params) === void 0)),
219
+ eth_getProof: z$1.tuple([
220
+ evmAddress$3,
221
+ z$1.array(z$1.union([hash32$1, quantity])).check(z$1.maxLength(100)),
222
+ blockParam
223
+ ]),
224
+ eth_getStorageAt: z$1.tuple([
225
+ evmAddress$3,
226
+ z$1.union([quantity, hash32$1]),
227
+ optional(blockParam)
228
+ ]),
229
+ eth_getTransactionByBlockHashAndIndex: z$1.tuple([hash32$1, quantity]),
230
+ eth_getTransactionByBlockNumberAndIndex: z$1.tuple([tagOrNumber, quantity]),
231
+ eth_getTransactionByHash: z$1.tuple([hash32$1]),
232
+ eth_getTransactionCount: z$1.tuple([evmAddress$3, optional(blockParam)]),
233
+ eth_getTransactionReceipt: z$1.tuple([hash32$1]),
234
+ eth_maxPriorityFeePerGas: noParams,
235
+ eth_sendRawTransaction: z$1.tuple([hexData]),
236
+ eth_simulateV1: z$1.tuple([simulateInput, optional(blockParam)]),
237
+ net_version: noParams,
238
+ web3_clientVersion: noParams
239
+ };
240
+ const solanaPubkey = z$1.string().check(z$1.regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/));
241
+ const solanaSignature = z$1.string().check(z$1.regex(/^[1-9A-HJ-NP-Za-km-z]{64,88}$/));
242
+ /** Trailing `{ encoding, commitment, … }` config object; its contents pass through. */
243
+ const solanaConfig = z$1.looseObject({});
244
+ /** Params `[pubkey]` or `[pubkey, config]`. */
245
+ const pubkeyCall = z$1.tuple([solanaPubkey, optional(solanaConfig)]);
246
+ /** Params omitted, `[]` or `[config]`. */
247
+ const configOnly = z$1.optional(z$1.tuple([z$1.optional(solanaConfig)]));
248
+ const SOLANA_PARAMS = {
249
+ getAccountInfo: pubkeyCall,
250
+ getBalance: pubkeyCall,
251
+ getBlockHeight: configOnly,
252
+ getBlockTime: z$1.tuple([z$1.int().check(z$1.nonnegative())]),
253
+ getEpochInfo: configOnly,
254
+ getFeeForMessage: z$1.tuple([z$1.string().check(z$1.minLength(1)), optional(solanaConfig)]),
255
+ getFirstAvailableBlock: noParams,
256
+ getGenesisHash: noParams,
257
+ getLatestBlockhash: configOnly,
258
+ getMinimumBalanceForRentExemption: z$1.tuple([z$1.int().check(z$1.nonnegative()), optional(solanaConfig)]),
259
+ getMultipleAccounts: z$1.tuple([z$1.array(solanaPubkey).check(z$1.minLength(1), z$1.maxLength(100)), optional(solanaConfig)]),
260
+ getRecentPrioritizationFees: z$1.optional(z$1.tuple([z$1.optional(z$1.array(solanaPubkey).check(z$1.maxLength(128)))])),
261
+ getSignatureStatuses: z$1.tuple([z$1.array(solanaSignature).check(z$1.minLength(1), z$1.maxLength(256)), optional(solanaConfig)]),
262
+ getSignaturesForAddress: pubkeyCall,
263
+ getSlot: configOnly,
264
+ getStakeMinimumDelegation: configOnly,
265
+ getTokenAccountBalance: pubkeyCall,
266
+ getTokenAccountsByOwner: z$1.tuple([
267
+ solanaPubkey,
268
+ z$1.union([z$1.strictObject({ mint: solanaPubkey }), z$1.strictObject({ programId: solanaPubkey })]),
269
+ optional(solanaConfig)
270
+ ]),
271
+ getTokenSupply: pubkeyCall,
272
+ getTransaction: z$1.tuple([solanaSignature, optional(solanaConfig)]),
273
+ getVersion: noParams,
274
+ getVoteAccounts: configOnly,
275
+ isBlockhashValid: pubkeyCall,
276
+ sendTransaction: z$1.tuple([z$1.string().check(z$1.minLength(1)), optional(solanaConfig)]),
277
+ simulateTransaction: z$1.tuple([z$1.string().check(z$1.minLength(1)), optional(solanaConfig)])
278
+ };
279
+ const evmRpcRequest = bodySchema(z$1.union(EVM_RPC_METHODS.map((method) => callSchema(z$1.literal(method), EVM_PARAMS[method]))));
280
+ const solanaRpcRequest = bodySchema(z$1.union(SOLANA_RPC_METHODS.map((method) => callSchema(z$1.literal(method), SOLANA_PARAMS[method]))));
281
+ const successResponse = z$1.object({
282
+ jsonrpc: z$1.literal("2.0"),
103
283
  id: jsonRpcId,
104
- result: z.unknown()
284
+ result: z$1.unknown()
105
285
  });
106
- const errorResponse = z.object({
107
- jsonrpc: z.literal("2.0"),
286
+ const errorResponse = z$1.object({
287
+ jsonrpc: z$1.literal("2.0"),
108
288
  id: jsonRpcId,
109
- error: z.object({
110
- code: z.int(),
111
- message: z.string(),
112
- data: z.optional(z.unknown())
289
+ error: z$1.object({
290
+ code: z$1.int(),
291
+ message: z$1.string(),
292
+ data: z$1.optional(z$1.unknown())
113
293
  })
114
294
  });
115
- const jsonRpcResponse = z.union([successResponse, errorResponse]);
116
- const rpcResponse = z.union([jsonRpcResponse, z.array(jsonRpcResponse)]);
295
+ const jsonRpcResponse = z$1.union([successResponse, errorResponse]);
296
+ const rpcResponse = z$1.union([jsonRpcResponse, z$1.array(jsonRpcResponse)]);
117
297
  const rpc = endpoint("POST", "/v1/rpc/:caip2", rpcRequest, rpcResponse);
118
298
  /** The JSON-RPC URL path for one network. */
119
299
  const rpcPath = (caip2) => rpc.path.replace(":caip2", caip2);
120
- // src/gateway/contract/primitives.ts
121
- const INSTALL_ID_HEADER = "x-install-id";
122
- const PROVIDERS_HEADER = "x-gateway-providers";
123
- /** 128 random bits as lowercase hex — generated once per install, unrelated to wallet secrets. */
124
- const installId = z.string().check(z.regex(/^[0-9a-f]{32}$/));
125
- /** CAIP-2 chain id: `namespace:reference`. */
126
- const caip2 = z.string().check(z.regex(/^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/));
127
- const GATEWAY_ERRORS = [
128
- "invalid-request",
129
- "unknown-network",
130
- "not-found",
131
- "rate-limited",
132
- "unavailable",
133
- "internal"
134
- ];
135
- const gatewayError = z.object({ error: z.enum(GATEWAY_ERRORS) });
300
+ const broadcastMethods = new Set(RPC_BROADCAST_METHODS);
301
+ /** Whether a validated call or batch relays a signed transaction. */
302
+ function containsBroadcast(body) {
303
+ return (Array.isArray(body) ? body : [body]).some((call) => broadcastMethods.has(call.method));
304
+ }
136
305
  // src/gateway/contract/health.ts
137
- const healthRequest = z.undefined();
138
- const healthResponse = z.object({ status: z.literal("ok") });
306
+ const healthRequest = z$1.undefined();
307
+ const healthResponse = z$1.object({ status: z$1.literal("ok") });
139
308
  const health = endpoint("GET", "/v1/health", healthRequest, healthResponse);
309
+ // src/gateway/contract/tron.ts
310
+ /**
311
+ * The TRON surface: the node's `/wallet` and `/walletsolidity` HTTP API plus the TronGrid
312
+ * `/v1/accounts` indexer paths (display-only history/discovery). Every path is a POST with a JSON
313
+ * body — the gateway translates the indexer calls to TronGrid's GET form. Paths not listed are
314
+ * rejected. Response schemas bound only what the engine reads; the node's `transaction` fields are
315
+ * never declared.
316
+ */
317
+ /** A base58 `T…` address (`visible: true` callers always send and receive it). */
318
+ const tronAddress = z$1.string().check(z$1.refine((value) => isTronAddress(value)));
319
+ /** Lowercase hex txid, no `0x`. */
320
+ const tronTxId = z$1.string().check(z$1.regex(/^[0-9a-f]{64}$/));
321
+ /** Contract calldata: even-length lowercase hex, 8 bytes to 10 kB. */
322
+ const callData = z$1.string().check(z$1.regex(/^([0-9a-f]{2}){4,10000}$/));
323
+ /** The node's hard cap on a relayed transaction is 500 KiB — 1,024,000 hex chars. */
324
+ const signedTransaction = z$1.string().check(z$1.regex(/^([0-9a-f]{2}){1,512000}$/));
325
+ const emptyRequest = z$1.strictObject({});
326
+ const accountRequest = z$1.strictObject({
327
+ address: tronAddress,
328
+ visible: z$1.literal(true)
329
+ });
330
+ const blockByNumRequest = z$1.strictObject({ num: z$1.int().check(z$1.nonnegative()) });
331
+ const transactionIdRequest = z$1.strictObject({ value: tronTxId });
332
+ const ownerRequest = z$1.strictObject({
333
+ owner_address: tronAddress,
334
+ visible: z$1.literal(true)
335
+ });
336
+ const canDelegateRequest = z$1.strictObject({
337
+ owner_address: tronAddress,
338
+ type: z$1.union([z$1.literal(0), z$1.literal(1)]),
339
+ visible: z$1.literal(true)
340
+ });
341
+ const delegatedResourceRequest = z$1.strictObject({
342
+ fromAddress: tronAddress,
343
+ toAddress: tronAddress,
344
+ visible: z$1.literal(true)
345
+ });
346
+ const triggerRequest = z$1.strictObject({
347
+ owner_address: tronAddress,
348
+ contract_address: tronAddress,
349
+ data: callData,
350
+ call_value: z$1.optional(z$1.int().check(z$1.nonnegative())),
351
+ visible: z$1.literal(true)
352
+ });
353
+ const broadcastRequest = z$1.strictObject({ transaction: signedTransaction });
354
+ const TRON_INDEXER_LIMIT_MAX = 50;
355
+ const indexerPageRequest = z$1.strictObject({
356
+ address: tronAddress,
357
+ fingerprint: z$1.optional(z$1.string().check(z$1.regex(/^[A-Za-z0-9]{0,1024}$/))),
358
+ limit: z$1.optional(z$1.int().check(z$1.minimum(1), z$1.maximum(50)))
359
+ });
360
+ const indexerAccountRequest = z$1.strictObject({ address: tronAddress });
361
+ const tronEmpty = z$1.strictObject({});
362
+ /** A block header: `getblockbynum` of a height past the head answers `{}`, never an error. */
363
+ const tronBlockResponse = z$1.looseObject({
364
+ blockID: tronTxId,
365
+ block_header: z$1.looseObject({ raw_data: z$1.looseObject({
366
+ number: z$1.int().check(z$1.nonnegative()),
367
+ timestamp: z$1.int().check(z$1.nonnegative())
368
+ }) })
369
+ });
370
+ const tronMaybeBlockResponse = z$1.union([tronBlockResponse, tronEmpty]);
371
+ const intField = z$1.number().check(z$1.int(), z$1.nonnegative());
372
+ /**
373
+ * Account-side int64 amounts (sun balances, TRC-10 totals) can exceed 2^53. `parseTronJson` emits a
374
+ * `bigint` for out-of-range integer literals and a safe `number` otherwise — both are exact.
375
+ */
376
+ const amountField = z$1.union([z$1.number().check(z$1.int(), z$1.nonnegative(), z$1.refine((v) => Number.isSafeInteger(v))), z$1.bigint().check(z$1.nonnegative())]);
377
+ /** `assetV2` rows carry the account's TRC-10 balances: `{key: "<asset id>", value: <amount>}`. */
378
+ const trc10Balance = z$1.looseObject({
379
+ key: z$1.string(),
380
+ value: amountField
381
+ });
382
+ /** One permission key — `address` follows the request's `visible` flag (base58 when true). */
383
+ const tronPermissionKey = z$1.looseObject({
384
+ address: z$1.optional(z$1.string()),
385
+ weight: z$1.optional(intField)
386
+ });
387
+ /** An account permission (owner / active / witness): who may sign, and how much weight counts. */
388
+ const tronPermission = z$1.looseObject({
389
+ type: z$1.optional(z$1.union([z$1.string(), z$1.number()])),
390
+ id: z$1.optional(z$1.number()),
391
+ permission_name: z$1.optional(z$1.string()),
392
+ threshold: z$1.optional(intField),
393
+ keys: z$1.optional(z$1.array(tronPermissionKey))
394
+ });
395
+ /** An account row: an absent account answers `{}`. `type === "Contract"` names a contract. */
396
+ const tronAccount = z$1.looseObject({
397
+ /** Present on every existing account — proto3 omits `balance`/`type` when they are zero. */
398
+ address: z$1.optional(z$1.string()),
399
+ balance: z$1.optional(amountField),
400
+ type: z$1.optional(z$1.string()),
401
+ assetV2: z$1.optional(z$1.array(trc10Balance)),
402
+ /** Stake V2 rows: `{type?: "ENERGY", amount}` — absent type means BANDWIDTH (proto3 enum 0). */
403
+ frozenV2: z$1.optional(z$1.array(z$1.looseObject({
404
+ type: z$1.optional(z$1.union([z$1.string(), z$1.number()])),
405
+ amount: z$1.optional(amountField)
406
+ }))),
407
+ /** Pending unfreeze rows: `{type?, unfreeze_amount, unfreeze_expire_time}`. */
408
+ unfrozenV2: z$1.optional(z$1.array(z$1.looseObject({
409
+ type: z$1.optional(z$1.union([z$1.string(), z$1.number()])),
410
+ unfreeze_amount: z$1.optional(amountField),
411
+ unfreeze_expire_time: z$1.optional(intField)
412
+ }))),
413
+ /** `vote_address` is the witness's 21-byte hex form. */
414
+ votes: z$1.optional(z$1.array(z$1.looseObject({
415
+ vote_address: z$1.optional(z$1.string()),
416
+ vote_count: intField
417
+ }))),
418
+ latest_withdraw_time: z$1.optional(intField),
419
+ /** Nested resource row: both ENERGY delegation totals live here (bandwidth is top-level). */
420
+ account_resource: z$1.optional(z$1.looseObject({
421
+ delegated_frozenV2_balance_for_energy: z$1.optional(amountField),
422
+ acquired_delegated_frozenV2_balance_for_energy: z$1.optional(amountField)
423
+ })),
424
+ delegated_frozenV2_balance_for_bandwidth: z$1.optional(amountField),
425
+ acquired_delegated_frozenV2_balance_for_bandwidth: z$1.optional(amountField),
426
+ /** Permissions: a key set with a threshold — any key that is not the owner is a grant. */
427
+ owner_permission: z$1.optional(tronPermission),
428
+ witness_permission: z$1.optional(tronPermission),
429
+ active_permission: z$1.optional(z$1.array(tronPermission))
430
+ });
431
+ const tronAccountResponse = z$1.union([tronAccount, tronEmpty]);
432
+ /** Account resources: proto3 omits zero fields, so every counter is optional. */
433
+ const tronAccountResource = z$1.looseObject({
434
+ freeNetLimit: z$1.optional(amountField),
435
+ freeNetUsed: z$1.optional(amountField),
436
+ NetLimit: z$1.optional(amountField),
437
+ NetUsed: z$1.optional(amountField),
438
+ EnergyLimit: z$1.optional(amountField),
439
+ EnergyUsed: z$1.optional(amountField),
440
+ /** Staked-for-votes power = frozen BANDWIDTH + frozen ENERGY in TRX units. */
441
+ tronPowerLimit: z$1.optional(amountField),
442
+ tronPowerUsed: z$1.optional(amountField)
443
+ });
444
+ const tronChainParameters = z$1.looseObject({ chainParameter: z$1.array(z$1.looseObject({
445
+ key: z$1.string(),
446
+ value: z$1.optional(z$1.union([z$1.number().check(z$1.int(), z$1.refine((v) => Number.isSafeInteger(v))), z$1.bigint()]))
447
+ })) });
448
+ /** An event log entry: hex contract address, hex topics, hex data (never `visible`-form). */
449
+ const tronLog = z$1.looseObject({
450
+ address: z$1.optional(z$1.string()),
451
+ topics: z$1.optional(z$1.array(z$1.string())),
452
+ data: z$1.optional(z$1.string())
453
+ });
454
+ /**
455
+ * `triggerconstantcontract`: a successful constant call (`result.result === true`) or a failure —
456
+ * REVERT and runtime errors answer `result: {code?, message?}` with `message` hex-encoded UTF-8.
457
+ */
458
+ const tronConstantCallResponse = z$1.union([z$1.looseObject({
459
+ result: z$1.looseObject({ result: z$1.literal(true) }),
460
+ energy_used: z$1.optional(intField),
461
+ energy_penalty: z$1.optional(intField),
462
+ constant_result: z$1.optional(z$1.array(z$1.string())),
463
+ logs: z$1.optional(z$1.array(tronLog))
464
+ }), z$1.looseObject({
465
+ result: z$1.looseObject({
466
+ code: z$1.optional(z$1.string()),
467
+ message: z$1.optional(z$1.string())
468
+ }),
469
+ energy_used: z$1.optional(intField),
470
+ energy_penalty: z$1.optional(intField)
471
+ })]);
472
+ /** `broadcasthex`: `code` is the `Return.response_code` name; `message` is plain UTF-8 here. */
473
+ const tronBroadcastResponse = z$1.looseObject({
474
+ result: z$1.boolean(),
475
+ code: z$1.optional(z$1.string()),
476
+ message: z$1.optional(z$1.string()),
477
+ txid: z$1.optional(z$1.string())
478
+ });
479
+ /**
480
+ * A transfer contract's `parameter.value` as the node renders it (`owner_address`/`to_address` are
481
+ * 41-prefixed hex, `asset_name` the TRC-10 id); a `TriggerSmartContract` adds `contract_address`
482
+ * plus the attached `call_value`/`call_token_value`/`token_id` movements. History cross-checks it
483
+ * against the indexer.
484
+ */
485
+ const tronContractValue = z$1.looseObject({
486
+ owner_address: z$1.optional(z$1.string()),
487
+ to_address: z$1.optional(z$1.string()),
488
+ amount: z$1.optional(amountField),
489
+ asset_name: z$1.optional(z$1.string()),
490
+ contract_address: z$1.optional(z$1.string()),
491
+ call_value: z$1.optional(amountField),
492
+ call_token_value: z$1.optional(amountField),
493
+ token_id: z$1.optional(intField)
494
+ });
495
+ /** `gettransactionbyid`: an unknown id answers `{}`. `raw_data_hex` lets history pin the body. */
496
+ const tronTransactionResponse = z$1.union([z$1.looseObject({
497
+ txID: tronTxId,
498
+ block_timestamp: z$1.optional(intField),
499
+ raw_data_hex: z$1.optional(z$1.string()),
500
+ raw_data: z$1.optional(z$1.looseObject({ contract: z$1.array(z$1.looseObject({
501
+ type: z$1.string(),
502
+ parameter: z$1.looseObject({ value: tronContractValue })
503
+ })) }))
504
+ }), tronEmpty]);
505
+ /** `gettransactioninfobyid` (full or solidified): an unknown id answers `{}`. */
506
+ const tronTransactionInfo = z$1.looseObject({
507
+ id: z$1.optional(tronTxId),
508
+ blockNumber: intField,
509
+ blockTimeStamp: intField,
510
+ fee: z$1.optional(intField),
511
+ receipt: z$1.optional(z$1.looseObject({
512
+ net_usage: z$1.optional(intField),
513
+ net_fee: z$1.optional(intField),
514
+ energy_usage_total: z$1.optional(intField),
515
+ energy_fee: z$1.optional(intField),
516
+ result: z$1.optional(z$1.string())
517
+ })),
518
+ result: z$1.optional(z$1.string()),
519
+ resMessage: z$1.optional(z$1.string()),
520
+ log: z$1.optional(z$1.array(tronLog))
521
+ });
522
+ const tronTransactionInfoResponse = z$1.union([tronTransactionInfo, tronEmpty]);
523
+ const tronIndexerPageResponse = z$1.looseObject({
524
+ success: z$1.literal(true),
525
+ data: z$1.array(z$1.unknown()).check(z$1.maxLength(50)),
526
+ meta: z$1.looseObject({ fingerprint: z$1.optional(z$1.string()) })
527
+ });
528
+ const indexerAccountResponse = z$1.looseObject({
529
+ success: z$1.literal(true),
530
+ data: z$1.array(z$1.unknown()).check(z$1.maxLength(1)),
531
+ meta: z$1.looseObject({ fingerprint: z$1.optional(z$1.string()) })
532
+ });
533
+ /**
534
+ * One `/v1/accounts/transactions` row — only the fields history reads. Rows that fail this schema
535
+ * are skipped by the stream, never thrown: the indexer is display-only and untrusted.
536
+ */
537
+ const tronIndexerTransaction = z$1.looseObject({
538
+ txID: tronTxId,
539
+ block_timestamp: intField,
540
+ blockNumber: z$1.optional(intField),
541
+ raw_data: z$1.looseObject({ contract: z$1.array(z$1.looseObject({
542
+ type: z$1.string(),
543
+ parameter: z$1.looseObject({ value: tronContractValue })
544
+ })) })
545
+ });
546
+ /** One `/v1/accounts/transactions/trc20` row — same skipped-not-thrown rule as the tx feed. */
547
+ const tronIndexerTrc20 = z$1.looseObject({
548
+ transaction_id: tronTxId,
549
+ block_timestamp: intField,
550
+ from: z$1.string(),
551
+ to: z$1.string(),
552
+ type: z$1.string(),
553
+ value: z$1.string(),
554
+ token_info: z$1.looseObject({
555
+ address: z$1.optional(z$1.string()),
556
+ symbol: z$1.optional(z$1.string()),
557
+ name: z$1.optional(z$1.string()),
558
+ decimals: z$1.optional(intField)
559
+ })
560
+ });
561
+ /** `getavailableunfreezecount` — `{count: n}`, or `{}` when none is available. */
562
+ const tronUnfreezeCountResponse = z$1.looseObject({ count: z$1.optional(intField) });
563
+ /** `getcandelegatedmaxsize` — `{max_size: n}` in sun; `{}` means the account can delegate 0. */
564
+ const tronCanDelegateMaxSizeResponse = z$1.looseObject({ max_size: z$1.optional(amountField) });
565
+ /** `getdelegatedresourcev2`: the row's lock expiry is per-resource, in ms. */
566
+ const tronDelegatedResourceResponse = z$1.looseObject({ delegatedResource: z$1.optional(z$1.array(z$1.looseObject({
567
+ from: z$1.optional(z$1.string()),
568
+ to: z$1.optional(z$1.string()),
569
+ frozen_balance_for_bandwidth: z$1.optional(amountField),
570
+ frozen_balance_for_energy: z$1.optional(amountField),
571
+ expire_time_for_bandwidth: z$1.optional(intField),
572
+ expire_time_for_energy: z$1.optional(intField)
573
+ }))) });
574
+ /** `getReward` — `{reward: sun}`, or `{}` when nothing is withdrawable. */
575
+ const tronRewardResponse = z$1.looseObject({ reward: z$1.optional(amountField) });
576
+ /** `listwitnesses`: `address` is the witness's base58 or `41…` hex form. */
577
+ /**
578
+ * `getassetissuebyid` — TRC-10 metadata. `name`/`abbr` are hex-encoded strings per the node;
579
+ * `precision` is the TRC-10 decimals.
580
+ */
581
+ const tronAssetIssueResponse = z$1.looseObject({
582
+ id: z$1.optional(z$1.string()),
583
+ name: z$1.optional(z$1.string()),
584
+ abbr: z$1.optional(z$1.string()),
585
+ precision: z$1.optional(intField)
586
+ });
587
+ const tronWitnessListResponse = z$1.looseObject({ witnesses: z$1.optional(z$1.array(z$1.looseObject({ address: z$1.optional(z$1.string()) }))) });
588
+ /** Node API paths forwarded to every provider: path → request schema, response schema. */
589
+ const TRON_NODE_PATHS = {
590
+ "/wallet/getnowblock": {
591
+ request: emptyRequest,
592
+ response: tronBlockResponse
593
+ },
594
+ "/walletsolidity/getnowblock": {
595
+ request: emptyRequest,
596
+ response: tronBlockResponse
597
+ },
598
+ "/wallet/getblockbynum": {
599
+ request: blockByNumRequest,
600
+ response: tronMaybeBlockResponse
601
+ },
602
+ "/walletsolidity/getblockbynum": {
603
+ request: blockByNumRequest,
604
+ response: tronMaybeBlockResponse
605
+ },
606
+ "/wallet/getaccount": {
607
+ request: accountRequest,
608
+ response: tronAccountResponse
609
+ },
610
+ "/wallet/getavailableunfreezecount": {
611
+ request: ownerRequest,
612
+ response: tronUnfreezeCountResponse
613
+ },
614
+ "/wallet/getcandelegatedmaxsize": {
615
+ request: canDelegateRequest,
616
+ response: tronCanDelegateMaxSizeResponse
617
+ },
618
+ "/wallet/getdelegatedresourcev2": {
619
+ request: delegatedResourceRequest,
620
+ response: tronDelegatedResourceResponse
621
+ },
622
+ "/wallet/getReward": {
623
+ request: accountRequest,
624
+ response: tronRewardResponse
625
+ },
626
+ "/wallet/getassetissuebyid": {
627
+ request: z$1.strictObject({ value: z$1.int().check(z$1.nonnegative()) }),
628
+ response: tronAssetIssueResponse
629
+ },
630
+ "/wallet/listwitnesses": {
631
+ request: emptyRequest,
632
+ response: tronWitnessListResponse
633
+ },
634
+ "/wallet/getaccountresource": {
635
+ request: accountRequest,
636
+ response: tronAccountResource
637
+ },
638
+ "/wallet/getchainparameters": {
639
+ request: emptyRequest,
640
+ response: tronChainParameters
641
+ },
642
+ "/wallet/triggerconstantcontract": {
643
+ request: triggerRequest,
644
+ response: tronConstantCallResponse
645
+ },
646
+ "/wallet/broadcasthex": {
647
+ request: broadcastRequest,
648
+ response: tronBroadcastResponse
649
+ },
650
+ "/wallet/gettransactionbyid": {
651
+ request: transactionIdRequest,
652
+ response: tronTransactionResponse
653
+ },
654
+ "/wallet/gettransactioninfobyid": {
655
+ request: transactionIdRequest,
656
+ response: tronTransactionInfoResponse
657
+ },
658
+ "/walletsolidity/gettransactioninfobyid": {
659
+ request: transactionIdRequest,
660
+ response: tronTransactionInfoResponse
661
+ }
662
+ };
663
+ /**
664
+ * Display-only indexer paths — the engine's own names; the gateway translates them to TronGrid GETs
665
+ * and only indexer providers serve them.
666
+ */
667
+ const TRON_INDEXER_PATHS = {
668
+ "/v1/accounts/transactions": {
669
+ request: indexerPageRequest,
670
+ response: tronIndexerPageResponse
671
+ },
672
+ "/v1/accounts/transactions/trc20": {
673
+ request: indexerPageRequest,
674
+ response: tronIndexerPageResponse
675
+ },
676
+ "/v1/accounts/account": {
677
+ request: indexerAccountRequest,
678
+ response: indexerAccountResponse
679
+ }
680
+ };
681
+ /** The path that relays a signed transaction — failover could double-broadcast it. */
682
+ const TRON_BROADCAST_PATH = "/wallet/broadcasthex";
683
+ /** The path entry, or `undefined` when `path` is not allow-listed. */
684
+ const tronPathEntry = (path) => TRON_NODE_PATHS[path] ?? TRON_INDEXER_PATHS[path];
685
+ const tronPathAllowed = (path) => tronPathEntry(path) !== void 0;
686
+ /** Whether `path` is an indexer path — routed only to the network's indexer providers. */
687
+ const isTronIndexerPath = (path) => TRON_INDEXER_PATHS[path] !== void 0;
688
+ const tron = endpoint("POST", "/v1/tron/:caip2/*", z$1.unknown(), z$1.unknown());
689
+ /** The TRON base path for one network; allow-listed node and indexer paths are appended to it. */
690
+ const tronBasePath = (caip2) => tron.path.replace(":caip2", caip2).replace(/\/\*$/, "");
691
+ // src/gateway/contract/tron-json.ts
692
+ /**
693
+ * Lossless JSON.parse: TRON's java-tron printer emits int64 fields as bare JSON numbers, so any
694
+ * value beyond ±(2^53−1) would lose precision under `JSON.parse`. This parser accepts exactly the
695
+ * JSON grammar — nothing `JSON.parse` would reject is accepted — and differs only in that an
696
+ * integer literal (no fraction, no exponent) outside the safe range becomes a `bigint` holding the
697
+ * literal's exact value. Everything else — strings, booleans, null, doubles, duplicate keys (last
698
+ * wins) — behaves identically to `JSON.parse`.
699
+ */
700
+ var TronJsonParseError = class extends Error {
701
+ /** Byte offset into the input where the grammar failed. */
702
+ offset;
703
+ constructor(message, offset) {
704
+ super(`${message} at offset ${offset}`);
705
+ this.name = "TronJsonParseError";
706
+ this.offset = offset;
707
+ }
708
+ };
709
+ /** Hostile nesting is rejected before the recursion can overflow the stack. */
710
+ const MAX_DEPTH = 512;
711
+ const QUOTE = 34;
712
+ const BACKSLASH = 92;
713
+ const COMMA = 44;
714
+ const COLON = 58;
715
+ const LBRACE = 123;
716
+ const RBRACE = 125;
717
+ const LBRACKET = 91;
718
+ const RBRACKET = 93;
719
+ const MINUS = 45;
720
+ const PLUS = 43;
721
+ const DOT = 46;
722
+ const ZERO = 48;
723
+ const NINE = 57;
724
+ const ESCAPES = /* @__PURE__ */ new Set([
725
+ QUOTE,
726
+ BACKSLASH,
727
+ 47,
728
+ 98,
729
+ 102,
730
+ 110,
731
+ 114,
732
+ 116
733
+ ]);
734
+ const isDigit = (c) => c >= ZERO && c <= NINE;
735
+ const isHexDigit = (c) => isDigit(c) || c >= 97 && c <= 102 || c >= 65 && c <= 70;
736
+ const parseTronJson = (text) => {
737
+ const n = text.length;
738
+ let i = 0;
739
+ /** Code point at `p`, `-1` past the end — every digit/structural test fails on it. */
740
+ const at = (p) => text.codePointAt(p) ?? -1;
741
+ const fail = (message) => {
742
+ throw new TronJsonParseError(message, i);
743
+ };
744
+ const skipWs = () => {
745
+ while (i < n) {
746
+ const c = at(i);
747
+ if (c !== 32 && c !== 9 && c !== 10 && c !== 13) return;
748
+ i += 1;
749
+ }
750
+ };
751
+ const literal = (word) => {
752
+ if (!text.startsWith(word, i)) fail(`expected ${word}`);
753
+ i += word.length;
754
+ };
755
+ const string = () => {
756
+ const start = i;
757
+ i += 1;
758
+ for (;;) {
759
+ if (i >= n) fail("unterminated string");
760
+ const c = at(i);
761
+ if (c === QUOTE) {
762
+ i += 1;
763
+ return String(JSON.parse(text.slice(start, i)));
764
+ }
765
+ if (c === BACKSLASH) {
766
+ const e = at(i + 1);
767
+ if (ESCAPES.has(e)) {
768
+ i += 2;
769
+ continue;
770
+ }
771
+ if (e === 117) {
772
+ for (let k = 2; k <= 5; k += 1) if (!isHexDigit(at(i + k))) fail("bad unicode escape");
773
+ i += 6;
774
+ continue;
775
+ }
776
+ fail("bad escape");
777
+ }
778
+ if (c < 32) fail("control character in string");
779
+ i += 1;
780
+ }
781
+ };
782
+ const number = () => {
783
+ const start = i;
784
+ if (at(i) === MINUS) i += 1;
785
+ const d0 = at(i);
786
+ if (d0 === ZERO) i += 1;
787
+ else if (d0 >= 49 && d0 <= NINE) while (isDigit(at(i))) i += 1;
788
+ else fail("bad number");
789
+ let integer = true;
790
+ if (at(i) === DOT) {
791
+ integer = false;
792
+ i += 1;
793
+ if (!isDigit(at(i))) fail("bad fraction");
794
+ while (isDigit(at(i))) i += 1;
795
+ }
796
+ const e = at(i);
797
+ if (e === 101 || e === 69) {
798
+ integer = false;
799
+ i += 1;
800
+ const sign = at(i);
801
+ if (sign === PLUS || sign === MINUS) i += 1;
802
+ if (!isDigit(at(i))) fail("bad exponent");
803
+ while (isDigit(at(i))) i += 1;
804
+ }
805
+ const token = text.slice(start, i);
806
+ if (!integer) return Number(token);
807
+ const value = Number(token);
808
+ return Number.isSafeInteger(value) ? value : BigInt(token);
809
+ };
810
+ const value = (depth) => {
811
+ if (depth > MAX_DEPTH) fail("nesting too deep");
812
+ skipWs();
813
+ if (i >= n) fail("unexpected end of input");
814
+ const c = at(i);
815
+ if (c === QUOTE) return string();
816
+ if (c === LBRACE) {
817
+ const out = {};
818
+ i += 1;
819
+ skipWs();
820
+ if (at(i) === RBRACE) {
821
+ i += 1;
822
+ return out;
823
+ }
824
+ for (;;) {
825
+ skipWs();
826
+ if (at(i) !== QUOTE) fail("expected object key");
827
+ const key = string();
828
+ skipWs();
829
+ if (at(i) !== COLON) fail("expected :");
830
+ i += 1;
831
+ const v = value(depth + 1);
832
+ Object.defineProperty(out, key, {
833
+ value: v,
834
+ writable: true,
835
+ enumerable: true,
836
+ configurable: true
837
+ });
838
+ skipWs();
839
+ const next = at(i);
840
+ if (next === RBRACE) {
841
+ i += 1;
842
+ return out;
843
+ }
844
+ if (next !== COMMA) fail("expected , or }");
845
+ i += 1;
846
+ }
847
+ }
848
+ if (c === LBRACKET) {
849
+ const out = [];
850
+ i += 1;
851
+ skipWs();
852
+ if (at(i) === RBRACKET) {
853
+ i += 1;
854
+ return out;
855
+ }
856
+ for (;;) {
857
+ out.push(value(depth + 1));
858
+ skipWs();
859
+ const next = at(i);
860
+ if (next === RBRACKET) {
861
+ i += 1;
862
+ return out;
863
+ }
864
+ if (next !== COMMA) fail("expected , or ]");
865
+ i += 1;
866
+ }
867
+ }
868
+ if (c === 116) {
869
+ literal("true");
870
+ return true;
871
+ }
872
+ if (c === 102) {
873
+ literal("false");
874
+ return false;
875
+ }
876
+ if (c === 110) {
877
+ literal("null");
878
+ return null;
879
+ }
880
+ if (c === MINUS || isDigit(c)) return number();
881
+ return fail("unexpected character");
882
+ };
883
+ const parsed = value(0);
884
+ skipWs();
885
+ if (i !== n) fail("trailing characters");
886
+ return parsed;
887
+ };
140
888
  // src/gateway/contract/esplora.ts
141
889
  const HEX64 = "[0-9a-f]{64}";
142
890
  /** The Esplora surface the engine uses; every other path is rejected. */
@@ -145,6 +893,10 @@ const ESPLORA_ROUTES = [
145
893
  method: "GET",
146
894
  pattern: /^\/block-height\/\d{1,10}$/
147
895
  },
896
+ {
897
+ method: "GET",
898
+ pattern: /^\/blocks\/tip\/height$/
899
+ },
148
900
  {
149
901
  method: "GET",
150
902
  pattern: /^\/fee-estimates$/
@@ -153,6 +905,10 @@ const ESPLORA_ROUTES = [
153
905
  method: "GET",
154
906
  pattern: new RegExp(`^/scripthash/${HEX64}/txs$`)
155
907
  },
908
+ {
909
+ method: "GET",
910
+ pattern: new RegExp(`^/scripthash/${HEX64}/txs/chain/${HEX64}$`)
911
+ },
156
912
  {
157
913
  method: "GET",
158
914
  pattern: new RegExp(`^/scripthash/${HEX64}/utxo$`)
@@ -172,14 +928,14 @@ const ESPLORA_ROUTES = [
172
928
  ];
173
929
  /** `path` is the Esplora path after `/v1/esplora/:caip2`, with a leading slash and no query. */
174
930
  const esploraPathAllowed = (method, path) => ESPLORA_ROUTES.some((route) => route.method === method && route.pattern.test(path));
175
- const esploraGet = endpoint("GET", "/v1/esplora/:caip2/*", z.undefined(), z.unknown());
931
+ const esploraGet = endpoint("GET", "/v1/esplora/:caip2/*", z$1.undefined(), z$1.unknown());
176
932
  /** The Esplora base path for one network; allow-listed paths are appended to it. */
177
933
  const esploraBasePath = (caip2) => esploraGet.path.replace(":caip2", caip2).replace(/\/\*$/, "");
178
- const esploraPost = endpoint("POST", "/v1/esplora/:caip2/tx", z.string(), z.string());
934
+ const esploraPost = endpoint("POST", "/v1/esplora/:caip2/tx", z$1.string(), z$1.string());
179
935
  // src/gateway/contract/served.ts
180
- const servedNetworksRequest = z.undefined();
936
+ const servedNetworksRequest = z$1.undefined();
181
937
  /** The networks the gateway actually serves, in its configured order. */
182
- const servedNetworksResponse = z.object({ networks: z.array(caip2) });
938
+ const servedNetworksResponse = z$1.object({ networks: z$1.array(caip2) });
183
939
  const servedNetworks = endpoint("GET", "/v1/networks", servedNetworksRequest, servedNetworksResponse);
184
940
  const networksPath = servedNetworks.path;
185
941
  // src/gateway/contract/risk.ts
@@ -240,28 +996,28 @@ function phishingCandidates(url) {
240
996
  for (let start = 0; labels.length - start >= MIN_HOST_LABELS; start += 1) candidates.push(labels.slice(start).join("."));
241
997
  return candidates;
242
998
  }
243
- const version = z.number().check(z.int(), z.nonnegative());
999
+ const version = z$1.number().check(z$1.int(), z$1.nonnegative());
244
1000
  /** Concatenated sorted 8-byte hashes, standard-alphabet base64; the empty string is an empty set. */
245
- const hashes = z.string().check(z.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/));
246
- const delta = z.object({
1001
+ const hashes = z$1.string().check(z$1.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/));
1002
+ const delta = z$1.object({
247
1003
  add: hashes,
248
1004
  remove: hashes
249
1005
  });
250
- const phishingListRequest = z.object({ since: z.optional(z.string().check(z.regex(/^\d{1,15}$/))) });
251
- const phishingListResponse = z.discriminatedUnion("kind", [
252
- z.object({
253
- kind: z.literal("current"),
1006
+ const phishingListRequest = z$1.object({ since: z$1.optional(z$1.string().check(z$1.regex(/^\d{1,15}$/))) });
1007
+ const phishingListResponse = z$1.discriminatedUnion("kind", [
1008
+ z$1.object({
1009
+ kind: z$1.literal("current"),
254
1010
  version
255
1011
  }),
256
- z.object({
257
- kind: z.literal("diff"),
1012
+ z$1.object({
1013
+ kind: z$1.literal("diff"),
258
1014
  from: version,
259
1015
  version,
260
1016
  deny: delta,
261
1017
  allow: delta
262
1018
  }),
263
- z.object({
264
- kind: z.literal("snapshot"),
1019
+ z$1.object({
1020
+ kind: z$1.literal("snapshot"),
265
1021
  version,
266
1022
  deny: hashes,
267
1023
  allow: hashes
@@ -389,6 +1145,700 @@ const union = (a, b) => merge(a, b, () => true);
389
1145
  const difference = (a, b) => merge(a, b, (inA, inB) => inA && !inB);
390
1146
  /** `(list − remove) ∪ add`. */
391
1147
  const applyDiff = (list, add, remove) => union(difference(list, remove), add);
392
- export { BITCOIN_NETWORKS, ESPLORA_ROUTES, EVM_RPC_METHODS, GATEWAY_ERRORS, INSTALL_ID_HEADER, NETWORKS, PHISHING_HASH_BYTES, PHISHING_MAX_PATH_SEGMENTS, PROVIDERS_HEADER, RPC_BATCH_MAX, SOLANA_NETWORKS, SOLANA_RPC_METHODS, accepts, applyDiff, caip2, contains, decodeHashList, difference, encodeHashList, endpoint, esploraBasePath, esploraGet, esploraPathAllowed, esploraPost, evmRpcRequest, gatewayError, hashCount, hashList, health, healthRequest, healthResponse, installId, jsonRpcId, jsonRpcResponse, networkById, networksPath, parseWith, phishingCandidates, phishingHash, phishingKey, phishingList, phishingListPath, phishingListRequest, phishingListResponse, rpc, rpcPath, rpcRequest, rpcResponse, servedNetworks, servedNetworksRequest, servedNetworksResponse, solanaRpcRequest, union };
1148
+ // src/gateway/contract/quotes.ts
1149
+ /** The native-token sentinel 0x uses for sell and buy tokens. */
1150
+ const ZEROX_NATIVE_TOKEN = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
1151
+ /** `0x` + 40 hex — an EVM address, the 0x native sentinel `0xEeee…` among them. */
1152
+ const evmAddress$2 = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{40}$/));
1153
+ /** A decimal string of a non-negative integer (`"0"` allowed for gas nulls). */
1154
+ const decimal$3 = z$1.string().check(z$1.regex(/^[0-9]+$/));
1155
+ const UINT256_MAX$1 = 2n ** 256n - 1n;
1156
+ const U64_MAX = 2n ** 64n - 1n;
1157
+ /**
1158
+ * An exact base-unit amount: a positive integer as decimal, at most `max` — the width of the
1159
+ * chain's amount type, so the upstream is never asked for an amount it must reject.
1160
+ */
1161
+ const positiveAmount = (max) => z$1.string().check(z$1.refine((value) => /^[1-9][0-9]*$/.test(value) && BigInt(value) <= max));
1162
+ /** The `swapQuote` request: which exact-in sell on which chain, for which taker, at what slippage. */
1163
+ const swapQuoteRequest = z$1.object({
1164
+ /** `eip155:<n>` — the only namespace a 0x swap supports. */
1165
+ network: caip2.check(z$1.regex(/^eip155:[0-9]+$/)),
1166
+ /** The token sold — an ERC-20 address, or `0xEeeee…` for native. */
1167
+ sellToken: evmAddress$2,
1168
+ /** The token bought — an ERC-20 address, or `0xEeeee…` for native. */
1169
+ buyToken: evmAddress$2,
1170
+ /** Exact base-unit sell amount, a positive uint256 as decimal. */
1171
+ sellAmount: positiveAmount(UINT256_MAX$1),
1172
+ /** The address the settlement contract pays out for. */
1173
+ taker: evmAddress$2,
1174
+ /** Worst-case slippage in basis points, 1–5000 (a query string, coerced). */
1175
+ slippageBps: z$1.coerce.number().check(z$1.int(), z$1.minimum(1), z$1.maximum(5e3))
1176
+ });
1177
+ const fee = z$1.object({
1178
+ /** The token the fee is charged in (sell or buy token). */
1179
+ token: evmAddress$2,
1180
+ /** The fee amount in base units. */
1181
+ amount: decimal$3
1182
+ });
1183
+ /** A quote with liquidity: the AllowanceHolder `exec` calldata to sign and the terms it must keep. */
1184
+ const quoteFilled = z$1.object({
1185
+ liquidity: z$1.literal(true),
1186
+ provider: z$1.literal("0x"),
1187
+ sellToken: evmAddress$2,
1188
+ buyToken: evmAddress$2,
1189
+ sellAmount: decimal$3,
1190
+ buyAmount: decimal$3,
1191
+ minBuyAmount: decimal$3,
1192
+ /** The spender `exec` approves — `null` for a native sell. */
1193
+ allowanceTarget: z$1.union([evmAddress$2, z$1.null()]),
1194
+ transaction: z$1.object({
1195
+ to: evmAddress$2,
1196
+ data: z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]*$/)),
1197
+ value: decimal$3,
1198
+ gas: z$1.union([decimal$3, z$1.null()])
1199
+ }),
1200
+ fees: z$1.object({
1201
+ integrator: z$1.union([fee, z$1.null()]),
1202
+ zeroEx: z$1.union([fee, z$1.null()])
1203
+ }),
1204
+ /** The block the quote was priced at — staleness is measured against this. */
1205
+ blockNumber: decimal$3
1206
+ });
1207
+ /** No route found: the response carries only the liquidity flag. */
1208
+ const quoteEmpty = z$1.object({ liquidity: z$1.literal(false) });
1209
+ const swapQuoteResponse = z$1.union([quoteFilled, quoteEmpty]);
1210
+ const swapQuote = endpoint("GET", "/v1/quotes/swap", swapQuoteRequest, swapQuoteResponse);
1211
+ /** Base58 public key — Solana mints, program ids, takers and accounts are all 32-byte keys. */
1212
+ const base58$1 = z$1.string().check(z$1.regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/));
1213
+ /** Jupiter is mainnet-only — every other Solana CAIP-2 id is a client error. */
1214
+ const SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
1215
+ /** The `swapQuoteSolana` request: an exact-in mint pair for a taker on Solana mainnet. */
1216
+ const swapQuoteSolanaRequest = z$1.object({
1217
+ network: z$1.literal(SOLANA_MAINNET),
1218
+ /** The mint sold — `So111…112` for wrapped SOL. */
1219
+ inputMint: base58$1,
1220
+ /** The mint bought — `So111…112` for wrapped SOL. */
1221
+ outputMint: base58$1,
1222
+ /** Exact base-unit sell amount, a positive u64 (an SPL amount) as decimal. */
1223
+ amount: positiveAmount(U64_MAX),
1224
+ /** The account the swap settles for. */
1225
+ taker: base58$1,
1226
+ /** Worst-case slippage in basis points, 1–5000 (a query string, coerced). */
1227
+ slippageBps: z$1.coerce.number().check(z$1.int(), z$1.minimum(1), z$1.maximum(5e3))
1228
+ });
1229
+ /** One Solana instruction as the wire carries it — base64 data, plain account flags. */
1230
+ const solanaInstruction = z$1.object({
1231
+ programId: base58$1,
1232
+ accounts: z$1.array(z$1.object({
1233
+ address: base58$1,
1234
+ signer: z$1.boolean(),
1235
+ writable: z$1.boolean()
1236
+ })),
1237
+ data: z$1.string().check(z$1.regex(/^[A-Za-z0-9+/]*={0,2}$/))
1238
+ });
1239
+ /**
1240
+ * A Jupiter `/build` relay: the instructions that assemble the versioned transaction — the engine
1241
+ * replaces the compute budget with its own and reads the named lookup tables from chain.
1242
+ */
1243
+ const solanaQuoteFilled = z$1.object({
1244
+ liquidity: z$1.literal(true),
1245
+ provider: z$1.literal("jupiter"),
1246
+ inputMint: base58$1,
1247
+ outputMint: base58$1,
1248
+ inAmount: decimal$3,
1249
+ outAmount: decimal$3,
1250
+ otherAmountThreshold: decimal$3,
1251
+ slippageBps: z$1.coerce.number().check(z$1.int(), z$1.minimum(0), z$1.maximum(1e4)),
1252
+ setup: z$1.array(solanaInstruction),
1253
+ swap: solanaInstruction,
1254
+ cleanup: z$1.union([solanaInstruction, z$1.null()]),
1255
+ /** The address lookup tables the message compresses against — contents never come over the wire. */
1256
+ lookupTables: z$1.array(base58$1)
1257
+ });
1258
+ const swapQuoteSolanaResponse = z$1.union([solanaQuoteFilled, quoteEmpty]);
1259
+ const swapQuoteSolana = endpoint("GET", "/v1/quotes/swap/solana", swapQuoteSolanaRequest, swapQuoteSolanaResponse);
1260
+ /** The `bridgeQuote` request: an exact-in token transfer from an origin chain to a destination. */
1261
+ const bridgeQuoteRequest = z$1.object({
1262
+ /** `eip155:<n>` — the origin chain. */
1263
+ network: caip2.check(z$1.regex(/^eip155:[0-9]+$/)),
1264
+ /** `eip155:<n>` — the destination chain. */
1265
+ destinationNetwork: caip2.check(z$1.regex(/^eip155:[0-9]+$/)),
1266
+ /** The token deposited on the origin chain — the chain's wrapped native for a native send. */
1267
+ inputToken: evmAddress$2,
1268
+ /** The token received on the destination chain. */
1269
+ outputToken: evmAddress$2,
1270
+ /** Exact base-unit input amount, a positive uint256 as decimal. */
1271
+ amount: positiveAmount(UINT256_MAX$1),
1272
+ /** The account the deposit settles for. */
1273
+ taker: evmAddress$2
1274
+ });
1275
+ /**
1276
+ * An Across `/suggested-fees` relay: the deposit terms the engine must verify on-chain — output and
1277
+ * deadline verbatim, the spoke pool address so a stale or spoofed build is refused.
1278
+ */
1279
+ const bridgeQuoteFilled = z$1.object({
1280
+ liquidity: z$1.literal(true),
1281
+ provider: z$1.literal("across"),
1282
+ inputToken: evmAddress$2,
1283
+ outputToken: evmAddress$2,
1284
+ inputAmount: decimal$3,
1285
+ outputAmount: decimal$3,
1286
+ destinationNetwork: caip2.check(z$1.regex(/^eip155:[0-9]+$/)),
1287
+ quoteTimestamp: z$1.coerce.number().check(z$1.int()),
1288
+ fillDeadline: z$1.coerce.number().check(z$1.int()),
1289
+ exclusiveRelayer: evmAddress$2,
1290
+ exclusivityParameter: z$1.coerce.number().check(z$1.int()),
1291
+ spokePool: evmAddress$2,
1292
+ limits: z$1.object({
1293
+ minDeposit: decimal$3,
1294
+ maxDeposit: decimal$3
1295
+ })
1296
+ });
1297
+ const bridgeQuoteResponse = z$1.union([bridgeQuoteFilled, quoteEmpty]);
1298
+ const bridgeQuote = endpoint("GET", "/v1/quotes/bridge", bridgeQuoteRequest, bridgeQuoteResponse);
1299
+ // src/gateway/contract/history.ts
1300
+ /** Entries the client may ask for per direction and page. */
1301
+ const HISTORY_PAGE_MAX = 50;
1302
+ /** Response cap: a drained block can legitimately exceed the requested limit. */
1303
+ const HISTORY_ITEMS_MAX = 500;
1304
+ /** Transfers kept per transaction. */
1305
+ const HISTORY_TRANSFERS_MAX = 100;
1306
+ const evmAddress$1 = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{40}$/));
1307
+ const hash32 = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{64}$/));
1308
+ const DECIMAL$1 = /^(0|[1-9][0-9]*)$/;
1309
+ /** A non-negative integer in decimal — no leading zeros, floats, signs or hex. */
1310
+ const decimal$2 = z$1.string().check(z$1.regex(DECIMAL$1));
1311
+ /**
1312
+ * The highest block bound the upstream verifiably accepts (int64 max): Alchemy rejects a `toBlock`
1313
+ * of 2^64 or more with a 400, so the contract refuses it before any upstream call.
1314
+ */
1315
+ const HISTORY_CURSOR_MAX = 2n ** 63n - 1n;
1316
+ /** An inclusive upper block bound, decimal, at most {@link HISTORY_CURSOR_MAX}. */
1317
+ const blockNumber = z$1.string().check(z$1.refine((value) => DECIMAL$1.test(value) && BigInt(value) <= HISTORY_CURSOR_MAX));
1318
+ const historyRequest = z$1.strictObject({
1319
+ address: evmAddress$1,
1320
+ cursor: z$1.optional(blockNumber),
1321
+ limit: z$1.optional(z$1.int().check(z$1.minimum(1), z$1.maximum(50)))
1322
+ });
1323
+ const historyTransfer = z$1.strictObject({
1324
+ kind: z$1.enum([
1325
+ "native",
1326
+ "internal",
1327
+ "erc20",
1328
+ "erc721",
1329
+ "erc1155"
1330
+ ]),
1331
+ from: evmAddress$1,
1332
+ to: z$1.union([evmAddress$1, z$1.null()]),
1333
+ /** Null for native/internal transfers. */
1334
+ contract: z$1.union([evmAddress$1, z$1.null()]),
1335
+ /** Erc721/erc1155 only. */
1336
+ tokenId: z$1.union([decimal$2, z$1.null()]),
1337
+ /** Base units; erc721 carries "1". */
1338
+ amount: decimal$2,
1339
+ decimals: z$1.union([z$1.int().check(z$1.minimum(0), z$1.maximum(255)), z$1.null()]),
1340
+ /** Display only, untrusted. */
1341
+ symbol: z$1.union([z$1.string().check(z$1.maxLength(32)), z$1.null()]),
1342
+ /** The receipt log that records the transfer; null for native/internal. */
1343
+ logIndex: z$1.union([z$1.int().check(z$1.minimum(0)), z$1.null()])
1344
+ });
1345
+ const historyItem = z$1.strictObject({
1346
+ hash: hash32,
1347
+ block: decimal$2,
1348
+ /** Milliseconds since the epoch. */
1349
+ timestamp: z$1.int().check(z$1.minimum(0)),
1350
+ transfers: z$1.array(historyTransfer).check(z$1.minLength(1), z$1.maxLength(100))
1351
+ });
1352
+ const historyResponse = z$1.strictObject({
1353
+ items: z$1.array(historyItem).check(z$1.maxLength(500)),
1354
+ /** Null: there is no older page. */
1355
+ cursor: z$1.union([decimal$2, z$1.null()]),
1356
+ /**
1357
+ * True when the gateway left out transfers in the range this page covers — a block or a
1358
+ * transaction with more transfers than one page can carry. The cursor still moves past them (they
1359
+ * cannot be paged), so the list has a gap there.
1360
+ */
1361
+ truncated: z$1.boolean()
1362
+ });
1363
+ const history = endpoint("POST", "/v1/history/:caip2", historyRequest, historyResponse);
1364
+ /** The history path for one network. */
1365
+ const historyPath = (caip2) => history.path.replace(":caip2", caip2);
1366
+ // src/gateway/contract/prices.ts
1367
+ /** Quote currencies the price route serves — ISO 4217 codes, lowercase as the providers spell them. */
1368
+ const FIAT_CURRENCIES = [
1369
+ "usd",
1370
+ "eur",
1371
+ "gbp",
1372
+ "jpy",
1373
+ "cny",
1374
+ "krw",
1375
+ "hkd",
1376
+ "sgd",
1377
+ "cad",
1378
+ "aud",
1379
+ "chf"
1380
+ ];
1381
+ const fiatCurrency = z$1.enum(FIAT_CURRENCIES);
1382
+ /** The most assets one `prices` request may name. */
1383
+ const MAX_PRICE_ASSETS = 100;
1384
+ /**
1385
+ * SLIP-44 coin type of the native asset on every mainnet the price route values (SLIP-0044
1386
+ * registry, satoshilabs/slips slip-0044.md @ 02e7b618; ETH-native L2s reuse 60). Testnets are
1387
+ * absent on purpose: their coins have no price.
1388
+ */
1389
+ const NATIVE_SLIP44 = {
1390
+ "eip155:1": 60,
1391
+ "eip155:8453": 60,
1392
+ "eip155:42161": 60,
1393
+ "eip155:10": 60,
1394
+ "eip155:137": 966,
1395
+ "eip155:56": 714,
1396
+ "eip155:999": 2457,
1397
+ "eip155:43114": 9e3,
1398
+ "eip155:4663": 60,
1399
+ "eip155:143": 268435779,
1400
+ "eip155:5042": 5042,
1401
+ "eip155:1672": 3172,
1402
+ "eip155:25": 394,
1403
+ "eip155:100": 700,
1404
+ "eip155:747474": 60,
1405
+ "eip155:80094": 8008,
1406
+ "eip155:480": 60,
1407
+ "eip155:130": 60,
1408
+ "eip155:1329": 19000118,
1409
+ "eip155:59144": 60,
1410
+ "eip155:42220": 52752,
1411
+ "eip155:146": 10007,
1412
+ "eip155:324": 60,
1413
+ "eip155:1868": 60,
1414
+ "eip155:4326": 60,
1415
+ "eip155:8217": 8217,
1416
+ "eip155:57073": 60,
1417
+ "eip155:534352": 60,
1418
+ "eip155:60808": 60,
1419
+ "eip155:204": 714,
1420
+ "eip155:42170": 60,
1421
+ "eip155:167000": 60,
1422
+ "eip155:7777777": 60,
1423
+ "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": 501,
1424
+ "tron:728126428": 195,
1425
+ "bip122:000000000019d6689c085ae165831e93": 0
1426
+ };
1427
+ /**
1428
+ * A priceable CAIP-19 asset id in its one canonical spelling: a native coin (`<caip2>/slip44:<n>`),
1429
+ * an ERC-20 with its address lowercase (`eip155:<n>/erc20:0x…`), or an SPL mint
1430
+ * (`solana:<ref>/token:<mint>`). A single spelling per asset keeps batches and cache keys free of
1431
+ * duplicates.
1432
+ */
1433
+ const priceAssetId = z$1.string().check(z$1.regex(/^(?:[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}\/slip44:(?:0|[1-9][0-9]{0,9})|eip155:[1-9][0-9]{0,9}\/erc20:0x[0-9a-f]{40}|solana:[1-9A-HJ-NP-Za-km-z]{32}\/token:[1-9A-HJ-NP-Za-km-z]{32,44}|tron:728126428\/trc20:T[1-9A-HJ-NP-Za-km-z]{33})$/));
1434
+ /** The asset id of `network`'s native coin, or `undefined` for a network without prices. */
1435
+ const nativeAssetId = (network) => {
1436
+ const slip44 = NATIVE_SLIP44[network];
1437
+ return slip44 === void 0 ? void 0 : `${network}/slip44:${String(slip44)}`;
1438
+ };
1439
+ /**
1440
+ * The asset id of a token on `network` (an ERC-20 address or an SPL mint), or `undefined` for a
1441
+ * network without prices or a token address the network does not spell that way.
1442
+ */
1443
+ const tokenAssetId = (network, address) => {
1444
+ if (NATIVE_SLIP44[network] === void 0) return;
1445
+ const id = network.startsWith("eip155:") ? `${network}/erc20:${address.toLowerCase()}` : network.startsWith("tron:") ? `${network}/trc20:${address}` : `${network}/token:${address}`;
1446
+ return z$1.safeParse(priceAssetId, id).success ? id : void 0;
1447
+ };
1448
+ /**
1449
+ * Fiat per whole unit of the asset as a canonical decimal string: positive, at most 12 integer
1450
+ * digits and 18 decimals, no trailing zeros — never a binary float on the wire.
1451
+ */
1452
+ const fiatPrice = z$1.string().check(z$1.regex(/^(?:[1-9][0-9]{0,11}(?:\.[0-9]{0,17}[1-9])?|0\.[0-9]{0,17}[1-9])$/));
1453
+ /** A 24 h change in percent as a canonical decimal string, at most 8 decimals, never below -100. */
1454
+ const percentChange = z$1.string().check(z$1.regex(/^-?(?:0|[1-9][0-9]{0,5})(?:\.[0-9]{0,7}[1-9])?$/), z$1.refine((value) => value !== "-0" && Number(value) >= -100));
1455
+ const priceQuote = z$1.object({
1456
+ asset: priceAssetId,
1457
+ price: fiatPrice,
1458
+ /** `null` when the provider has no 24 h change for the asset. */
1459
+ change24h: z$1.union([percentChange, z$1.null()]),
1460
+ /** When the provider last updated the price, Unix ms. */
1461
+ updatedAt: z$1.number().check(z$1.int(), z$1.positive())
1462
+ });
1463
+ /** The `prices` request: spot prices of up to {@link MAX_PRICE_ASSETS} distinct assets. */
1464
+ const pricesRequest = z$1.object({
1465
+ currency: fiatCurrency,
1466
+ assets: z$1.array(priceAssetId).check(z$1.minLength(1), z$1.maxLength(100), z$1.refine((assets) => new Set(assets).size === assets.length))
1467
+ });
1468
+ /**
1469
+ * Every requested asset is in exactly one of `prices` (priced), `missing` (the providers had no
1470
+ * price now — a later request may find one) or `unsupported` (the gateway has no price coverage for
1471
+ * it at all — do not retry).
1472
+ */
1473
+ const pricesResponse = z$1.object({
1474
+ currency: fiatCurrency,
1475
+ prices: z$1.array(priceQuote).check(z$1.maxLength(100)),
1476
+ missing: z$1.array(priceAssetId).check(z$1.maxLength(100)),
1477
+ unsupported: z$1.array(priceAssetId).check(z$1.maxLength(100))
1478
+ });
1479
+ /**
1480
+ * The gateway scopes a price request is partitioned by: one per chain family, each sent under that
1481
+ * family's own client id.
1482
+ */
1483
+ const PRICE_FAMILIES = [
1484
+ "evm",
1485
+ "solana",
1486
+ "bitcoin",
1487
+ "tron"
1488
+ ];
1489
+ const priceFamily = z$1.enum(PRICE_FAMILIES);
1490
+ /**
1491
+ * The family whose scope prices `asset`, by its CAIP-2 namespace (eip155, solana, bip122, tron);
1492
+ * `undefined` for any other.
1493
+ */
1494
+ const priceAssetFamily = (asset) => {
1495
+ switch (asset.slice(0, asset.indexOf(":"))) {
1496
+ case "eip155": return "evm";
1497
+ case "solana": return "solana";
1498
+ case "bip122": return "bitcoin";
1499
+ case "tron": return "tron";
1500
+ default: return;
1501
+ }
1502
+ };
1503
+ /**
1504
+ * `POST /v1/prices/:family` — no address is sent, but the asset set describes a portfolio, so it
1505
+ * travels in the body and per family scope: a request never names another family's assets, so the
1506
+ * portfolio links no scopes beyond what each scope's own traffic already shows.
1507
+ */
1508
+ const prices = endpoint("POST", "/v1/prices/:family", pricesRequest, pricesResponse);
1509
+ /** The prices path for one family scope. */
1510
+ const pricesPath = (family) => prices.path.replace(":family", family);
1511
+ // src/gateway/contract/tokens.ts
1512
+ /** Per-network caps the route enforces — bigger lists are never published. */
1513
+ const TOKEN_LIST_MAX_ENTRIES = {
1514
+ evm: 1500,
1515
+ solana: 5e3
1516
+ };
1517
+ const TOKEN_LIST_SOURCES = [
1518
+ "uniswap",
1519
+ "coingecko",
1520
+ "jupiter"
1521
+ ];
1522
+ const CONTROL = /\p{C}/u;
1523
+ /**
1524
+ * Display text a host renders verbatim: bounded in UTF-16 units, free of control, format,
1525
+ * unassigned and private-use characters, and without leading or trailing whitespace.
1526
+ */
1527
+ const displayText = (max) => z$1.string().check(z$1.minLength(1), z$1.maxLength(max), z$1.refine((value) => !CONTROL.test(value), { error: "control character" }), z$1.refine((value) => value === value.trim(), { error: "outer whitespace" }));
1528
+ const tokenSymbol = displayText(20);
1529
+ const tokenName = displayText(64);
1530
+ const tokenListEntry = z$1.object({
1531
+ address: z$1.string(),
1532
+ symbol: tokenSymbol,
1533
+ name: tokenName,
1534
+ decimals: z$1.int().check(z$1.gte(0), z$1.lte(255))
1535
+ });
1536
+ const EVM_ADDRESS$1 = /^0x[0-9a-f]{40}$/;
1537
+ const SOLANA_ADDRESS$1 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
1538
+ /**
1539
+ * The network pins the address shape and the entry cap; eip155 addresses are lowercase hex and
1540
+ * every list is sorted by plain `<` string order — unique and canonical, so one list has exactly
1541
+ * one serialization.
1542
+ */
1543
+ const validForNetwork = (doc) => {
1544
+ const [namespace] = doc.network.split(":");
1545
+ const rule = namespace === "eip155" ? {
1546
+ pattern: EVM_ADDRESS$1,
1547
+ max: TOKEN_LIST_MAX_ENTRIES.evm
1548
+ } : namespace === "solana" ? {
1549
+ pattern: SOLANA_ADDRESS$1,
1550
+ max: TOKEN_LIST_MAX_ENTRIES.solana
1551
+ } : void 0;
1552
+ if (rule === void 0 || doc.tokens.length > rule.max) return false;
1553
+ return doc.tokens.every((token, i) => rule.pattern.test(token.address) && (i === 0 || (doc.tokens[i - 1]?.address ?? "") < token.address));
1554
+ };
1555
+ const tokenListResponse = z$1.object({
1556
+ network: caip2,
1557
+ /** Monotonic per network — a smaller version than the stored one is a rollback. */
1558
+ version: z$1.int().check(z$1.nonnegative()),
1559
+ sources: z$1.array(z$1.enum(TOKEN_LIST_SOURCES)).check(z$1.minLength(1)),
1560
+ tokens: z$1.array(tokenListEntry).check(z$1.maxLength(TOKEN_LIST_MAX_ENTRIES.solana))
1561
+ }).check(z$1.refine(validForNetwork, { error: "entries do not fit the network" }));
1562
+ const tokenList = endpoint("GET", "/v1/tokens/:caip2", z$1.undefined(), tokenListResponse);
1563
+ /** The token list path for one network. */
1564
+ const tokenListPath = (caip2) => tokenList.path.replace(":caip2", caip2);
1565
+ // src/gateway/contract/approvals.ts
1566
+ /** The candidates one response may carry. */
1567
+ const APPROVAL_CANDIDATES_MAX = 500;
1568
+ const evmAddress = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{40}$/));
1569
+ /** A non-negative integer in decimal — no leading zeros, floats, signs or hex. */
1570
+ const decimal$1 = z$1.string().check(z$1.regex(/^(0|[1-9][0-9]*)$/));
1571
+ const approvalsRequest = z$1.strictObject({ address: evmAddress });
1572
+ /**
1573
+ * One approval-shaped event the discovery scan surfaced — keys only: which token, whose approval,
1574
+ * at which block. Never the current state (an amount, a live flag): the engine confirms every
1575
+ * candidate on chain itself.
1576
+ */
1577
+ const approvalCandidate = z$1.discriminatedUnion("kind", [
1578
+ z$1.strictObject({
1579
+ kind: z$1.literal("erc20"),
1580
+ /** The contract that emitted the Approval. */
1581
+ token: evmAddress,
1582
+ spender: evmAddress,
1583
+ block: decimal$1
1584
+ }),
1585
+ z$1.strictObject({
1586
+ kind: z$1.literal("erc721"),
1587
+ token: evmAddress,
1588
+ spender: evmAddress,
1589
+ tokenId: decimal$1,
1590
+ block: decimal$1
1591
+ }),
1592
+ z$1.strictObject({
1593
+ kind: z$1.literal("operator"),
1594
+ token: evmAddress,
1595
+ operator: evmAddress,
1596
+ block: decimal$1
1597
+ }),
1598
+ z$1.strictObject({
1599
+ kind: z$1.literal("permit2"),
1600
+ /** The token the Permit2 allowance names (an indexed topic, not the emitting contract). */
1601
+ token: evmAddress,
1602
+ spender: evmAddress,
1603
+ block: decimal$1
1604
+ })
1605
+ ]);
1606
+ const approvalsResponse = z$1.strictObject({
1607
+ /** The head the logs were read up to. */
1608
+ toBlock: decimal$1,
1609
+ candidates: z$1.array(approvalCandidate).check(z$1.maxLength(500)),
1610
+ /** True when the scan found more candidates than one response carries. */
1611
+ truncated: z$1.boolean()
1612
+ });
1613
+ const approvals = endpoint("POST", "/v1/approvals/:caip2", approvalsRequest, approvalsResponse);
1614
+ /** The approvals path for one network. */
1615
+ const approvalsPath = (caip2) => approvals.path.replace(":caip2", caip2);
1616
+ // src/gateway/contract/nfts.ts
1617
+ /** One inventory page is at most this many items. */
1618
+ const NFT_PAGE_MAX = 100;
1619
+ /** Detail attributes kept per item. */
1620
+ const NFT_ATTRIBUTES_MAX = 50;
1621
+ /** A remote (non-`data:`) media or link URL is at most this many characters. */
1622
+ const NFT_URL_MAX = 2048;
1623
+ /** A `data:` media URI may run to this many characters. */
1624
+ const NFT_DATA_URI_MAX = 65536;
1625
+ /** Display text an item or collection name may carry. */
1626
+ const NFT_NAME_MAX = 200;
1627
+ /** A description may run to this many characters. */
1628
+ const NFT_DESCRIPTION_MAX = 4e3;
1629
+ /** One attribute key or value. */
1630
+ const NFT_ATTRIBUTE_TEXT_MAX = 128;
1631
+ const NFT_STANDARDS = [
1632
+ "erc721",
1633
+ "erc1155",
1634
+ "metaplex",
1635
+ "metaplex-programmable",
1636
+ "metaplex-core",
1637
+ "metaplex-compressed"
1638
+ ];
1639
+ const DECIMAL = /^(0|[1-9][0-9]*)$/;
1640
+ /** A non-negative integer in decimal — no leading zeros, floats, signs or hex. */
1641
+ const decimal = z$1.string().check(z$1.regex(DECIMAL));
1642
+ const UINT256_MAX = 2n ** 256n - 1n;
1643
+ /** An EVM token id or balance unit: decimal, no leading zeros, inside uint256. */
1644
+ const nftTokenId = z$1.string().check(z$1.regex(DECIMAL), z$1.refine((value) => BigInt(value) <= UINT256_MAX, { error: "over uint256" }));
1645
+ /** A held amount: decimal, no leading zeros, at least 1, inside uint256. */
1646
+ const nftBalance = z$1.string().check(z$1.regex(DECIMAL), z$1.refine((value) => BigInt(value) >= 1n && BigInt(value) <= UINT256_MAX, { error: "balance out of range" }));
1647
+ /**
1648
+ * Where the host may look for media: a remote URL capped at {@link NFT_URL_MAX} characters or a
1649
+ * `data:` URI capped at {@link NFT_DATA_URI_MAX}. The scheme itself is the client's problem —
1650
+ * nothing here is fetched.
1651
+ */
1652
+ const nftMediaRef = z$1.strictObject({
1653
+ url: z$1.string().check(z$1.minLength(1), z$1.maxLength(NFT_DATA_URI_MAX), z$1.refine((url) => url.startsWith("data:") || url.length <= 2048, { error: "remote url over cap" })),
1654
+ mime: z$1.union([z$1.string().check(z$1.maxLength(64)), z$1.null()])
1655
+ });
1656
+ const nftCollectionRef = z$1.strictObject({
1657
+ /** The collection's on-chain id (contract or asset) when the provider knows it. */
1658
+ id: z$1.union([z$1.string().check(z$1.maxLength(64)), z$1.null()]),
1659
+ name: z$1.union([z$1.string().check(z$1.maxLength(200)), z$1.null()]),
1660
+ verified: z$1.boolean()
1661
+ });
1662
+ const nftItemSchema = z$1.strictObject({
1663
+ contract: z$1.string().check(z$1.maxLength(64)),
1664
+ /** Decimal on EVM; null on Solana — the asset id is the contract. */
1665
+ tokenId: z$1.union([nftTokenId, z$1.null()]),
1666
+ standard: z$1.enum(NFT_STANDARDS),
1667
+ balance: nftBalance,
1668
+ name: z$1.union([z$1.string().check(z$1.maxLength(200)), z$1.null()]),
1669
+ image: z$1.union([nftMediaRef, z$1.null()]),
1670
+ animation: z$1.union([nftMediaRef, z$1.null()]),
1671
+ collection: z$1.union([nftCollectionRef, z$1.null()]),
1672
+ spam: z$1.boolean()
1673
+ });
1674
+ /** The opaque page cursor: ASCII-safe, bounded — never echoed back unvalidated. */
1675
+ const nftCursor = z$1.string().check(z$1.regex(/^[A-Za-z0-9_.:-]{1,512}$/));
1676
+ const nftItemsRequest = z$1.strictObject({
1677
+ owner: z$1.string().check(z$1.maxLength(64)),
1678
+ cursor: z$1.optional(nftCursor)
1679
+ });
1680
+ const nftItemRequest = z$1.strictObject({
1681
+ contract: z$1.string().check(z$1.maxLength(64)),
1682
+ tokenId: z$1.optional(nftTokenId)
1683
+ });
1684
+ const nftCollectionRequest = z$1.strictObject({ collection: z$1.string().check(z$1.maxLength(64)) });
1685
+ const nftFloorRequest = nftCollectionRequest;
1686
+ const nftPage = z$1.strictObject({
1687
+ items: z$1.array(nftItemSchema).check(z$1.maxLength(100)),
1688
+ /** Null: there is no next page. */
1689
+ cursor: z$1.union([nftCursor, z$1.null()])
1690
+ });
1691
+ const nftAttribute = z$1.strictObject({
1692
+ trait: z$1.string().check(z$1.minLength(1), z$1.maxLength(128)),
1693
+ value: z$1.string().check(z$1.maxLength(128))
1694
+ });
1695
+ const nftDetail = z$1.strictObject({
1696
+ item: nftItemSchema,
1697
+ description: z$1.union([z$1.string().check(z$1.maxLength(NFT_DESCRIPTION_MAX)), z$1.null()]),
1698
+ attributes: z$1.array(nftAttribute).check(z$1.maxLength(50)),
1699
+ externalUrl: z$1.union([z$1.string().check(z$1.maxLength(NFT_URL_MAX)), z$1.null()])
1700
+ });
1701
+ const nftCollectionResponse = z$1.strictObject({
1702
+ id: z$1.string().check(z$1.maxLength(64)),
1703
+ name: z$1.union([z$1.string().check(z$1.maxLength(200)), z$1.null()]),
1704
+ symbol: z$1.union([z$1.string().check(z$1.maxLength(32)), z$1.null()]),
1705
+ description: z$1.union([z$1.string().check(z$1.maxLength(NFT_DESCRIPTION_MAX)), z$1.null()]),
1706
+ image: z$1.union([nftMediaRef, z$1.null()]),
1707
+ totalSupply: z$1.union([decimal, z$1.null()]),
1708
+ standard: z$1.union([z$1.enum(NFT_STANDARDS), z$1.null()]),
1709
+ spam: z$1.boolean(),
1710
+ verified: z$1.boolean()
1711
+ });
1712
+ const NFT_MARKETPLACES = ["opensea", "looksrare"];
1713
+ /**
1714
+ * A floor quote as a canonical decimal string — never a binary float, no trailing zeros in the
1715
+ * fraction, at most 18 decimals.
1716
+ */
1717
+ const floorAmount = z$1.string().check(z$1.regex(/^(0|[1-9][0-9]*)(\.[0-9]{0,17}[1-9])?$/));
1718
+ const nftFloorResponse = z$1.strictObject({ floors: z$1.array(z$1.strictObject({
1719
+ marketplace: z$1.enum(NFT_MARKETPLACES),
1720
+ amount: floorAmount,
1721
+ currency: z$1.string().check(z$1.regex(/^[A-Z0-9]{1,10}$/)),
1722
+ /** Milliseconds since the epoch; null when the provider gave none. */
1723
+ retrievedAt: z$1.union([z$1.int().check(z$1.minimum(0)), z$1.null()])
1724
+ })).check(z$1.maxLength(2)) });
1725
+ const nftItems = endpoint("POST", "/v1/nfts/items/:caip2", nftItemsRequest, nftPage);
1726
+ const nftItem = endpoint("POST", "/v1/nfts/item/:caip2", nftItemRequest, nftDetail);
1727
+ const nftCollection = endpoint("POST", "/v1/nfts/collection/:caip2", nftCollectionRequest, nftCollectionResponse);
1728
+ const nftFloor = endpoint("POST", "/v1/nfts/floor/:caip2", nftFloorRequest, nftFloorResponse);
1729
+ /** The items path for one network. */
1730
+ const nftItemsPath = (caip2) => nftItems.path.replace(":caip2", caip2);
1731
+ /** The item path for one network. */
1732
+ const nftItemPath = (caip2) => nftItem.path.replace(":caip2", caip2);
1733
+ /** The collection path for one network. */
1734
+ const nftCollectionPath = (caip2) => nftCollection.path.replace(":caip2", caip2);
1735
+ /** The floor path for one network. */
1736
+ const nftFloorPath = (caip2) => nftFloor.path.replace(":caip2", caip2);
1737
+ const EVM_ADDRESS = /^0x[0-9a-f]{40}$/;
1738
+ const SOLANA_ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
1739
+ const namespaceOf = (network) => network.split(":")[0] ?? "";
1740
+ /**
1741
+ * Whether `address` has the shape `network` spells on-chain — a contract, an asset id, an owner or
1742
+ * a collection id. EVM ids are lowercase hex only; Solana ids are base58. Other namespaces have no
1743
+ * NFT inventory at all.
1744
+ */
1745
+ function nftAddressFits(network, address) {
1746
+ const namespace = namespaceOf(network);
1747
+ if (namespace === "eip155") return EVM_ADDRESS.test(address);
1748
+ if (namespace === "solana") return SOLANA_ADDRESS.test(address);
1749
+ return false;
1750
+ }
1751
+ /**
1752
+ * Whether an item can belong to `network`: the contract fits, the token id and standard match the
1753
+ * family's rules (EVM ids are mandatory, Solana's asset id is the contract), an erc721 holds
1754
+ * exactly one, and a named collection points at an address of the same family.
1755
+ */
1756
+ function nftItemFits(network, item) {
1757
+ const namespace = namespaceOf(network);
1758
+ if (!nftAddressFits(network, item.contract)) return false;
1759
+ if (namespace === "eip155") {
1760
+ if (item.tokenId === null) return false;
1761
+ if (item.standard !== "erc721" && item.standard !== "erc1155") return false;
1762
+ if (item.standard === "erc721" && item.balance !== "1") return false;
1763
+ } else if (namespace === "solana") {
1764
+ if (item.tokenId !== null || !item.standard.startsWith("metaplex")) return false;
1765
+ } else return false;
1766
+ const collectionId = item.collection?.id;
1767
+ return collectionId === null || collectionId === void 0 ? true : nftAddressFits(network, collectionId);
1768
+ }
1769
+ /** Every item fits the network and no `(contract, tokenId)` pair repeats inside the page. */
1770
+ function nftPageFits(network, page) {
1771
+ const seen = /* @__PURE__ */ new Set();
1772
+ for (const item of page.items) {
1773
+ if (!nftItemFits(network, item)) return false;
1774
+ const key = `${item.contract}${item.tokenId ?? ""}`;
1775
+ if (seen.has(key)) return false;
1776
+ seen.add(key);
1777
+ }
1778
+ return true;
1779
+ }
1780
+ /** The collection id fits the network and its standard is the family's (or unreported). */
1781
+ function nftCollectionFits(network, collection) {
1782
+ const namespace = namespaceOf(network);
1783
+ if (!nftAddressFits(network, collection.id)) return false;
1784
+ if (collection.standard === null) return true;
1785
+ if (namespace === "eip155") return collection.standard === "erc721" || collection.standard === "erc1155";
1786
+ if (namespace === "solana") return collection.standard.startsWith("metaplex");
1787
+ return false;
1788
+ }
1789
+ // src/gateway/contract/push.ts
1790
+ const PUSH_FAMILIES = [
1791
+ "evm",
1792
+ "solana",
1793
+ "bitcoin",
1794
+ "tron"
1795
+ ];
1796
+ const PUSH_PLATFORMS = ["apns", "fcm"];
1797
+ const PUSH_ADDRESSES_MAX = 64;
1798
+ const PUSH_NETWORKS_MAX = 64;
1799
+ /** A subscription not refreshed within this window is deleted. */
1800
+ const PUSH_TTL_MS = 2592e6;
1801
+ /** `Authorization: Bearer base64url(secret)` — the subscription's only credential. */
1802
+ const PUSH_AUTH_SCHEME = "Bearer";
1803
+ /**
1804
+ * `title-loc-key` / `loc-key` values the gateway puts in the APNs alert: hosts ship these keys in
1805
+ * `Localizable.strings` as the fallback copy for a notification the extension cannot open.
1806
+ */
1807
+ const PUSH_APNS_TITLE_KEY = "QNTX_PUSH_TITLE";
1808
+ const PUSH_APNS_BODY_KEY = "QNTX_PUSH_BODY";
1809
+ /** The bearer secret and payload key encoding. */
1810
+ const pushSecret = z$1.string().check(z$1.regex(/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/));
1811
+ const pushSubscriptionId = /^[0-9a-f]{32}$/;
1812
+ const alnum = z$1.string().check(z$1.regex(/^[0-9A-Za-z]{1,128}$/));
1813
+ const pushCapabilities = endpoint("GET", "/v1/push", z$1.undefined(), z$1.strictObject({
1814
+ platforms: z$1.array(z$1.enum(PUSH_PLATFORMS)).check(z$1.maxLength(PUSH_PLATFORMS.length)),
1815
+ families: z$1.array(z$1.enum(PUSH_FAMILIES)).check(z$1.maxLength(PUSH_FAMILIES.length))
1816
+ }));
1817
+ const pushSubscriptionRequest = z$1.strictObject({
1818
+ platform: z$1.enum(PUSH_PLATFORMS),
1819
+ /** The provider device token — printable ASCII, opaque to the gateway. */
1820
+ token: z$1.string().check(z$1.regex(/^[!-~]{1,4096}$/)),
1821
+ /** The payload key the gateway seals subscription-side. */
1822
+ key: pushSecret,
1823
+ networks: z$1.array(caip2).check(z$1.minLength(1), z$1.maxLength(64)),
1824
+ addresses: z$1.array(alnum).check(z$1.minLength(1), z$1.maxLength(64))
1825
+ });
1826
+ const pushSubscriptionResponse = z$1.strictObject({
1827
+ id: z$1.string().check(z$1.regex(pushSubscriptionId)),
1828
+ /** The intersection of requested networks and what the gateway watches. */
1829
+ networks: z$1.array(caip2).check(z$1.maxLength(64)),
1830
+ expiresAt: z$1.int().check(z$1.minimum(0))
1831
+ });
1832
+ const pushSubscribe = endpoint("PUT", "/v1/push/:family/subscription", pushSubscriptionRequest, pushSubscriptionResponse);
1833
+ const pushUnsubscribe = endpoint("DELETE", "/v1/push/:family/subscription", z$1.undefined(), z$1.undefined());
1834
+ /** Registers a submitted outgoing hash so the gateway watches it to a settlement or failure. */
1835
+ const pushTransactionRequest = z$1.strictObject({
1836
+ network: caip2,
1837
+ hash: alnum
1838
+ });
1839
+ const pushWatch = endpoint("POST", "/v1/push/:family/transactions", pushTransactionRequest, z$1.strictObject({}));
1840
+ /** A push route path for one family. */
1841
+ const pushPath = (template, family) => template.replace(":family", family);
1842
+ export { APPROVAL_CANDIDATES_MAX, APP_ID, BITCOIN_NETWORKS, CLIENT_ID_HEADER, ESPLORA_ROUTES, EVM_RPC_METHODS, FEE_HISTORY_BLOCKS_MAX, FEE_HISTORY_PERCENTILES_MAX, FIAT_CURRENCIES, GATEWAY_ERRORS, HISTORY_CURSOR_MAX, HISTORY_ITEMS_MAX, HISTORY_PAGE_MAX, HISTORY_TRANSFERS_MAX, LOGS_ADDRESS_MAX, LOGS_BLOCK_RANGE_MAX, LOGS_TOPIC_ALTERNATIVES_MAX, MAX_PRICE_ASSETS, NATIVE_SLIP44, NETWORKS, NFT_ATTRIBUTES_MAX, NFT_ATTRIBUTE_TEXT_MAX, NFT_DATA_URI_MAX, NFT_DESCRIPTION_MAX, NFT_NAME_MAX, NFT_PAGE_MAX, NFT_STANDARDS, NFT_URL_MAX, PHISHING_HASH_BYTES, PHISHING_MAX_PATH_SEGMENTS, PRICE_FAMILIES, PROVIDERS_HEADER, PROVIDER_PIN_HEADER, PUSH_AAD_PREFIX, PUSH_ADDRESSES_MAX, PUSH_APNS_BODY_KEY, PUSH_APNS_TITLE_KEY, PUSH_AUTH_SCHEME, PUSH_BLOB_MAX, PUSH_EVENT_DOMAIN, PUSH_EVENT_KINDS, PUSH_FAMILIES, PUSH_ID_DOMAIN, PUSH_KEYS_MAX, PUSH_NETWORKS_MAX, PUSH_PLAINTEXT_MAX, PUSH_PLATFORMS, PUSH_TTL_MS, PUSH_VERSION, RPC_BATCH_MAX, RPC_BROADCAST_METHODS, RPC_PROOF_KEYS_MAX, RPC_SIMULATE_BLOCKS_MAX, RPC_SIMULATE_CALLS_MAX, SOLANA_MAINNET, SOLANA_NETWORKS, SOLANA_RPC_METHODS, TOKEN_LIST_MAX_ENTRIES, TOKEN_LIST_SOURCES, TRON_BROADCAST_PATH, TRON_INDEXER_LIMIT_MAX, TRON_INDEXER_PATHS, TRON_NETWORKS, TRON_NODE_PATHS, TronJsonParseError, ZEROX_NATIVE_TOKEN, accepts, appAvailability, applyDiff, approvalCandidate, approvals, approvalsPath, approvalsRequest, approvalsResponse, bridgeQuote, bridgeQuoteRequest, bridgeQuoteResponse, caip2, clientId, contains, containsBroadcast, decodeHashList, difference, eligibility, eligibilityRequest, eligibilityResponse, encodeHashList, endpoint, esploraBasePath, esploraGet, esploraPathAllowed, esploraPost, evmRpcRequest, fiatCurrency, fiatPrice, gatewayError, hashCount, hashList, health, healthRequest, healthResponse, history, historyItem, historyPath, historyRequest, historyResponse, historyTransfer, isTronIndexerPath, jsonRpcId, jsonRpcRequestId, jsonRpcResponse, logsFilterViolation, nativeAssetId, networkById, networksPath, nftAddressFits, nftAttribute, nftBalance, nftCollection, nftCollectionFits, nftCollectionPath, nftCollectionRef, nftCollectionRequest, nftCollectionResponse, nftCursor, nftDetail, nftFloor, nftFloorPath, nftFloorRequest, nftFloorResponse, nftItem, nftItemFits, nftItemPath, nftItemRequest, nftItemSchema, nftItems, nftItemsPath, nftItemsRequest, nftMediaRef, nftPage, nftPageFits, nftTokenId, parsePushMessage, parsePushPlaintext, parseTronJson, parseWith, percentChange, phishingCandidates, phishingHash, phishingKey, phishingList, phishingListPath, phishingListRequest, phishingListResponse, priceAssetFamily, priceAssetId, priceFamily, priceQuote, prices, pricesPath, pricesRequest, pricesResponse, pushAad, pushCapabilities, pushEventInput, pushPath, pushSecret, pushSubscribe, pushSubscriptionId, pushSubscriptionRequest, pushSubscriptionResponse, pushTransactionRequest, pushUnsubscribe, pushWatch, rpc, rpcPath, rpcRequest, rpcResponse, serializePushPlaintext, servedNetworks, servedNetworksRequest, servedNetworksResponse, solanaInstruction, solanaRpcRequest, swapQuote, swapQuoteRequest, swapQuoteResponse, swapQuoteSolana, swapQuoteSolanaRequest, swapQuoteSolanaResponse, tokenAssetId, tokenList, tokenListEntry, tokenListPath, tokenListResponse, tokenName, tokenSymbol, tron, tronAccount, tronAccountResource, tronAccountResponse, tronAssetIssueResponse, tronBasePath, tronBlockResponse, tronBroadcastResponse, tronCanDelegateMaxSizeResponse, tronChainParameters, tronConstantCallResponse, tronDelegatedResourceResponse, tronIndexerPageResponse, tronIndexerTransaction, tronIndexerTrc20, tronLog, tronMaybeBlockResponse, tronPathAllowed, tronPathEntry, tronRewardResponse, tronTransactionInfo, tronTransactionInfoResponse, tronTransactionResponse, tronUnfreezeCountResponse, tronWitnessListResponse, union };
393
1843
 
394
1844
  //# sourceMappingURL=gateway-contract.mjs.map