@manifoldxyz/dropkit 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,430 +1,40 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
19
16
 
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- CLICKABLE_STATES: () => CLICKABLE_STATES,
24
- MAX_QUANTITY: () => MAX_QUANTITY,
25
- MINT_STATES: () => MINT_STATES,
26
- MintButton: () => MintButton,
27
- MintError: () => MintError,
28
- PayWithPicker: () => PayWithPicker,
29
- REASON_CODES: () => REASON_CODES,
30
- VERSION: () => VERSION,
31
- isMintError: () => isMintError,
32
- useMint: () => useMint,
33
- usePayOptions: () => usePayOptions
34
- });
35
- module.exports = __toCommonJS(index_exports);
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+ var _chunkOO6QQT3Mcjs = require('./chunk-OO6QQT3M.cjs');
36
31
 
37
32
  // src/react/useMint.ts
38
- var import_react = require("react");
39
- var import_viem9 = require("viem");
40
-
41
- // src/core/rpc/index.ts
42
- var import_viem = require("viem");
43
- var import_chains = require("viem/chains");
44
-
45
- // src/core/errors.ts
46
- var UNSUPPORTED_REASONS = [
47
- "UNKNOWN_EXTENSION",
48
- "AMBIGUOUS_EXTENSION",
49
- "CLAIM_NOT_FOUND",
50
- "SIGNATURE_CLAIM",
51
- "INVALID_CONFIG",
52
- "CONNECT_WIDGET_TOO_OLD"
53
- ];
54
- var INELIGIBLE_REASONS = ["NOT_ON_ALLOWLIST", "ALLOWLIST_USED", "WALLET_LIMIT", "SIMULATION_REVERTED"];
55
- var ERROR_REASONS = [
56
- "USER_REJECTED",
57
- "TX_REVERTED",
58
- "RATE_LIMITED",
59
- "RPC_ERROR",
60
- "CHAIN_SWITCH_FAILED",
61
- "ALLOWLIST_UNAVAILABLE",
62
- // Relay cross-chain mint (spec relay-cross-chain-mint #execute-click).
63
- "BRIDGE_UNAVAILABLE",
64
- "BRIDGE_REFUNDED",
65
- "BRIDGE_FAILED",
66
- "BRIDGE_TIMEOUT"
67
- ];
68
- var FUNDS_REASONS = ["INSUFFICIENT_FUNDS"];
69
- var REASON_CODES = [
70
- ...UNSUPPORTED_REASONS,
71
- ...INELIGIBLE_REASONS,
72
- ...ERROR_REASONS,
73
- ...FUNDS_REASONS
74
- ];
75
- var MintError = class extends Error {
76
- reason;
77
- /** INVALID_CONFIG only: dotted path of the bad field, e.g. "mint.args[1]" or "price". */
78
- field;
79
- /** 'relay': the message is Relay's decoded destination revert, shown as-is. */
80
- domain;
81
- constructor(reason, message, opts) {
82
- super(message, opts?.cause === void 0 ? void 0 : { cause: opts.cause });
83
- this.name = "MintError";
84
- this.reason = reason;
85
- if (opts?.field !== void 0) this.field = opts.field;
86
- if (opts?.domain !== void 0) this.domain = opts.domain;
87
- }
88
- };
89
- function isMintError(e) {
90
- return e instanceof MintError;
91
- }
92
-
93
- // src/core/rpc/index.ts
94
- var BRIDGE_URLS = {
95
- 1: "https://bridge.manifoldxyz.dev/rpc",
96
- 11155111: "https://sepolia.bridge.manifoldxyz.dev/rpc",
97
- 8453: "https://base.bridge.manifoldxyz.dev/rpc",
98
- 10: "https://optimism.bridge.manifoldxyz.dev/rpc",
99
- 360: "https://shape.bridge.manifoldxyz.dev/rpc",
100
- 33139: "https://apechain.bridge.manifoldxyz.dev/rpc"
101
- };
102
- var CHAINS = {
103
- [import_chains.mainnet.id]: import_chains.mainnet,
104
- [import_chains.sepolia.id]: import_chains.sepolia,
105
- [import_chains.base.id]: import_chains.base,
106
- [import_chains.optimism.id]: import_chains.optimism,
107
- [import_chains.shape.id]: import_chains.shape,
108
- [import_chains.apeChain.id]: import_chains.apeChain,
109
- // Relay pay chain for Sepolia drops only: never a drop chain, no Manifold bridge.
110
- [import_chains.baseSepolia.id]: import_chains.baseSepolia
111
- };
112
- var CHAIN_NAMES = {
113
- 1: "Ethereum",
114
- 8453: "Base",
115
- 10: "Optimism",
116
- 360: "Shape",
117
- 33139: "ApeChain",
118
- 11155111: "Sepolia",
119
- 84532: "Base Sepolia"
120
- };
121
- function chainName(chainId) {
122
- return CHAIN_NAMES[chainId] ?? CHAINS[chainId]?.name ?? `chain ${String(chainId)}`;
123
- }
124
- var TRANSPORT_TIMEOUT_MS = 8e3;
125
- function getChain(chainId) {
126
- const chain = CHAINS[chainId];
127
- if (!chain) {
128
- throw new MintError("INVALID_CONFIG", `chainId ${String(chainId)} is not supported`, { field: "chainId" });
129
- }
130
- return chain;
131
- }
132
- var TERMINAL_CODES = /* @__PURE__ */ new Set([3, -32602, -32003, 4001, 4100, 4200, 4900, 4901, 4902]);
133
- var FALLBACK_CODES = /* @__PURE__ */ new Set([-32700, -32600, -32601, -32001, -32002, -32004, -32005, 429]);
134
- var EXECUTION_WORDING = /execution reverted|execution error|\breverted?\b|out of gas|invalid opcode|insufficient funds|nonce too low|gas required exceeds/i;
135
- var UPSTREAM_WORDING = /\btimeout\b|\btimed out\b|\btoo many requests\b|\brate limit\b|\brequest limit reached\b|\b(?:exceeded.*capacity|capacity.*exceeded)\b|\bheader not found\b|\binternal (?:json-rpc )?(?:server )?error\b|\bnon-200 status code:\s*['"]?503\b/i;
136
- var TRANSPORT_ERROR_NAMES = /* @__PURE__ */ new Set(["HttpRequestError", "TimeoutError", "SocketClosedError", "WebSocketRequestError"]);
137
- function carriesExecutionEvidence(value, seen = /* @__PURE__ */ new Set()) {
138
- if (typeof value === "string") return /^(?:Reverted\s+)?0x(?:[a-f\d]{2})*$/i.test(value) || EXECUTION_WORDING.test(value);
139
- if (!value || typeof value !== "object" || seen.has(value)) return false;
140
- seen.add(value);
141
- const e = value;
142
- if (typeof e.code === "number" && TERMINAL_CODES.has(e.code)) return true;
143
- if (typeof e.message === "string" && EXECUTION_WORDING.test(e.message)) return true;
144
- return ["data", "error", "originalError", "cause", "result"].some((key) => carriesExecutionEvidence(e[key], seen));
145
- }
146
- function shouldFallback(err) {
147
- let retry = false;
148
- const seen = /* @__PURE__ */ new Set();
149
- for (let e = err; e && typeof e === "object" && !seen.has(e); ) {
150
- seen.add(e);
151
- const error = e;
152
- const message = typeof error.details === "string" ? error.details : typeof error.shortMessage !== "string" ? error.message : "";
153
- if (typeof message === "string" && EXECUTION_WORDING.test(message)) return false;
154
- if (carriesExecutionEvidence(error.data)) return false;
155
- if (typeof error.code === "number" && TERMINAL_CODES.has(error.code)) return false;
156
- if (error.name === "ContractFunctionRevertedError" || error.name === "ExecutionRevertedError") return false;
157
- if (typeof error.name === "string" && TRANSPORT_ERROR_NAMES.has(error.name)) retry = true;
158
- if (typeof error.code === "number" && FALLBACK_CODES.has(error.code)) retry = true;
159
- if (typeof message === "string" && UPSTREAM_WORDING.test(message)) retry = true;
160
- e = error.cause;
161
- }
162
- return retry;
163
- }
164
- function createReadClient(opts) {
165
- const chain = getChain(opts.chainId);
166
- const urls = [opts.rpcUrls?.[opts.chainId], opts.useBridge ? BRIDGE_URLS[opts.chainId] : void 0, chain.rpcUrls.default.http[0]].filter(
167
- (u, i, all) => !!u && all.indexOf(u) === i
168
- );
169
- const transport = ({ chain: c, pollingInterval }) => {
170
- const transports = urls.map((url) => (0, import_viem.http)(url, { timeout: TRANSPORT_TIMEOUT_MS, retryCount: 0 })({ chain: c, pollingInterval, retryCount: 0, timeout: TRANSPORT_TIMEOUT_MS }));
171
- const request = (async (args) => {
172
- let last;
173
- for (const t of transports) {
174
- try {
175
- return await t.request(args);
176
- } catch (err) {
177
- if (!shouldFallback(err)) throw err;
178
- last = err;
179
- }
180
- }
181
- console.warn(`dropkit: all RPC endpoints failed for chain ${String(opts.chainId)}; pass rpcUrls={{ ${String(opts.chainId)}: '<your RPC url>' }} to <MintButton>.`);
182
- throw new MintError("RPC_ERROR", `All RPC endpoints failed for chain ${String(opts.chainId)}`, { cause: last });
183
- });
184
- return {
185
- config: { key: "dropkit-fallback", name: "Dropkit fallback", request, retryCount: 0, retryDelay: 0, timeout: TRANSPORT_TIMEOUT_MS, type: "fallback" },
186
- request,
187
- value: {}
188
- };
189
- };
190
- return (0, import_viem.createPublicClient)({ chain, transport });
191
- }
192
-
193
- // src/core/wallet/index.ts
194
- var import_viem2 = require("viem");
195
- var CONNECT_WIDGET_VERSION = "6.5.0";
196
- var CONNECT_BASE_URL = `https://connect.manifoldxyz.dev/${CONNECT_WIDGET_VERSION}`;
197
- var CONNECT_ID = "mint-button";
198
- var ADDRESS_CHANGED = "ethereum-address-changed";
199
- var CHAIN_CHANGED = "frontend-provider-chain-changed";
200
- var LOADER_KEY = "__manifoldMintConnectLoader";
201
- var DEFAULT_WALLETCONNECT_PROJECT_ID = "a03ac1695f309dc8d756e7b4006e5e7d";
202
- var STATE_KEY = "__manifoldMintConnectStateV1";
203
- var win = () => window;
204
- var pageState = () => win()[STATE_KEY] ??= {};
205
- var TOO_OLD = "A Manifold connect widget older than 6.4.0 is already on this page; update it or remove it so dropkit can load " + CONNECT_WIDGET_VERSION + ".";
206
- var MANIFOLD_HOST = /(^|\.)(manifoldxyz\.dev|manifold\.xyz)$/;
207
- function isManifoldConnectScript(src) {
208
- try {
209
- const url = new URL(src, document.baseURI);
210
- return url.hostname === "connect.manifoldxyz.dev" || MANIFOLD_HOST.test(url.hostname) && /\/connect\.umd[^/]*\.js$/.test(url.pathname);
211
- } catch {
212
- return false;
213
- }
214
- }
215
- function applyState(state) {
216
- if (!state.div) return;
217
- const network = state.networks.join(",");
218
- if (state.div.dataset.network !== network) state.div.dataset.network = network;
219
- const projectId = state.projectId ?? state.div.dataset.walletConnectProjectId ?? DEFAULT_WALLETCONNECT_PROJECT_ID;
220
- if (state.div.dataset.walletConnectProjectId !== projectId) state.div.dataset.walletConnectProjectId = projectId;
221
- }
222
- function register(state, opts) {
223
- for (const id2 of opts.chainIds) if (!state.networks.includes(id2)) state.networks.push(id2);
224
- const id = opts.walletConnectProjectId;
225
- if (id) {
226
- if (!state.projectId) state.projectId = id;
227
- else if (state.projectId !== id) {
228
- console.warn(`dropkit: walletConnectProjectId "${id}" ignored; this page already uses "${state.projectId}" for the shared connect widget.`);
229
- }
230
- }
231
- applyState(state);
232
- }
233
- function startLoad(state) {
234
- const connect = win().ManifoldConnect;
235
- if (connect?.capabilities?.includes("open")) return Promise.resolve(connect.ready).then(() => void 0);
236
- const hasScript = Array.from(document.querySelectorAll("script[src]")).some((s) => isManifoldConnectScript(s.src));
237
- if (hasScript || document.querySelector('[data-widget="m-connect"]')) {
238
- return Promise.reject(new MintError("CONNECT_WIDGET_TOO_OLD", TOO_OLD));
239
- }
240
- return new Promise((resolve, reject) => {
241
- const css = document.createElement("link");
242
- css.rel = "stylesheet";
243
- css.href = `${CONNECT_BASE_URL}/connect.css`;
244
- document.head.appendChild(css);
245
- state.nodes.push(css);
246
- const div = document.createElement("div");
247
- div.hidden = true;
248
- div.style.display = "none";
249
- div.dataset.widget = "m-connect";
250
- div.dataset.connectId = CONNECT_ID;
251
- div.dataset.autoReconnect = "true";
252
- div.dataset.enableNetworkSwitching = "true";
253
- state.div = div;
254
- applyState(state);
255
- document.body.appendChild(div);
256
- state.nodes.push(div);
257
- const script = document.createElement("script");
258
- script.src = `${CONNECT_BASE_URL}/connect.umd.min.js`;
259
- script.async = true;
260
- script.addEventListener("load", () => {
261
- const ready = win().ManifoldConnect?.ready;
262
- if (!ready) return reject(new MintError("CONNECT_WIDGET_TOO_OLD", TOO_OLD));
263
- Promise.resolve(ready).then(() => resolve(), reject);
264
- });
265
- script.addEventListener("error", () => reject(new MintError("RPC_ERROR", `Could not load the Manifold connect widget from ${CONNECT_BASE_URL}`)));
266
- document.head.appendChild(script);
267
- state.nodes.push(script);
268
- });
269
- }
270
- function loadConnectWidget(opts) {
271
- const w = win();
272
- const page = pageState();
273
- const existing = w[LOADER_KEY];
274
- if (existing) {
275
- if (page.load?.promise !== existing) {
276
- const div = document.querySelector(`[data-widget="m-connect"][data-connect-id="${CONNECT_ID}"]`) ?? void 0;
277
- page.load = {
278
- promise: existing,
279
- networks: div?.dataset.network?.split(",").filter(Boolean).map(Number) ?? [],
280
- // The default id is a placeholder, not a choice: a caller's real id may still replace it.
281
- projectId: div?.dataset.walletConnectProjectId === DEFAULT_WALLETCONNECT_PROJECT_ID ? void 0 : div?.dataset.walletConnectProjectId,
282
- div,
283
- nodes: []
284
- };
285
- }
286
- register(page.load, opts);
287
- return existing;
288
- }
289
- let resolve;
290
- let reject;
291
- const p = new Promise((res, rej) => {
292
- resolve = res;
293
- reject = rej;
294
- });
295
- const state = { promise: p, networks: [], nodes: [] };
296
- page.load = state;
297
- w[LOADER_KEY] = p;
298
- p.catch(() => {
299
- if (w[LOADER_KEY] === p) delete w[LOADER_KEY];
300
- if (page.load === state) page.load = void 0;
301
- for (const node of state.nodes) node.parentNode?.removeChild(node);
302
- state.nodes.length = 0;
303
- state.div = void 0;
304
- });
305
- register(state, opts);
306
- try {
307
- startLoad(state).then(resolve, reject);
308
- } catch (error) {
309
- reject(error);
310
- }
311
- return p;
312
- }
313
- function openConnectModal() {
314
- const page = pageState();
315
- if (page.pendingModal) return page.pendingModal;
316
- const p = new Promise((resolve) => {
317
- const onClosed = (e) => {
318
- const detail = e.detail ?? {};
319
- if (detail.connectId !== void 0 && detail.connectId !== CONNECT_ID) return;
320
- window.removeEventListener("m-connect:closed", onClosed);
321
- page.pendingModal = void 0;
322
- resolve(detail.reason === "connected" ? "connected" : "dismissed");
323
- };
324
- window.addEventListener("m-connect:closed", onClosed);
325
- });
326
- page.pendingModal = p;
327
- window.dispatchEvent(new CustomEvent("m-connect:open", { detail: { connectId: CONNECT_ID } }));
328
- return p;
329
- }
330
- function getAccount() {
331
- const p = win().ManifoldEthereumProvider;
332
- const address = p?.selectedAddress?.();
333
- let chainId = p?.chainId?.();
334
- if (chainId === void 0 || chainId === null) {
335
- try {
336
- chainId = p?.browserChainId?.();
337
- } catch {
338
- chainId = void 0;
339
- }
340
- }
341
- if (!address || chainId === void 0 || chainId === null) return null;
342
- return { address: (0, import_viem2.getAddress)(address), chainId: Number(chainId) };
343
- }
344
- function subscribeAccount(cb) {
345
- const handler = () => cb(getAccount());
346
- window.addEventListener(ADDRESS_CHANGED, handler);
347
- window.addEventListener(CHAIN_CHANGED, handler);
348
- return () => {
349
- window.removeEventListener(ADDRESS_CHANGED, handler);
350
- window.removeEventListener(CHAIN_CHANGED, handler);
351
- };
352
- }
353
- function eip1193() {
354
- const p = win().ManifoldEthereumProvider;
355
- const provider = (p?.provider?.(true) ?? p?.browserProvider?.())?.provider;
356
- if (!provider) throw new MintError("CHAIN_SWITCH_FAILED", "No wallet is connected.");
357
- return provider;
358
- }
359
- function getWalletClient(chainId) {
360
- const provider = eip1193();
361
- const request = ((args) => provider.request(args));
362
- return (0, import_viem2.createWalletClient)({ chain: getChain(chainId), transport: (0, import_viem2.custom)({ request }) });
363
- }
364
- async function waitForDeposit(chainId, hash, timeoutMs = 12e4) {
365
- try {
366
- const receipt = await getWalletClient(chainId).extend(import_viem2.publicActions).waitForTransactionReceipt({ hash, confirmations: 1, timeout: timeoutMs });
367
- return receipt.status === "reverted" ? "reverted" : "mined";
368
- } catch {
369
- return "unknown";
370
- }
371
- }
372
- var WALLET_READ_TIMEOUT = { ms: 1e4 };
373
- async function getConnectedBalance(address, chainId) {
374
- const provider = eip1193();
375
- let timer;
376
- const timeout = new Promise((_, reject) => {
377
- timer = setTimeout(() => reject(new MintError("RPC_ERROR", "The wallet did not report a balance in time.")), WALLET_READ_TIMEOUT.ms);
378
- });
379
- try {
380
- return await Promise.race([
381
- (async () => {
382
- const current = Number(await provider.request({ method: "eth_chainId" }));
383
- if (current !== chainId) {
384
- throw new MintError("CHAIN_SWITCH_FAILED", `The wallet is on chain ${String(current)}, not ${String(chainId)}.`);
385
- }
386
- const hex = await provider.request({ method: "eth_getBalance", params: [address, "latest"] });
387
- return BigInt(hex);
388
- })(),
389
- timeout
390
- ]);
391
- } finally {
392
- clearTimeout(timer);
393
- }
394
- }
395
- var code = (e) => e?.code;
396
- async function switchToChain(chainId) {
397
- const chain = getChain(chainId);
398
- const provider = eip1193();
399
- const hexId = `0x${chainId.toString(16)}`;
400
- const switchChain = () => provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: hexId }] });
401
- try {
402
- try {
403
- await switchChain();
404
- } catch (e) {
405
- if (code(e) !== 4902) throw e;
406
- await provider.request({
407
- method: "wallet_addEthereumChain",
408
- params: [
409
- {
410
- chainId: hexId,
411
- chainName: chain.name,
412
- nativeCurrency: chain.nativeCurrency,
413
- rpcUrls: [...chain.rpcUrls.default.http],
414
- ...chain.blockExplorers ? { blockExplorerUrls: [chain.blockExplorers.default.url] } : {}
415
- }
416
- ]
417
- });
418
- await switchChain();
419
- }
420
- } catch (e) {
421
- if (code(e) === 4001) throw new MintError("USER_REJECTED", "You rejected the network switch.", { cause: e });
422
- throw new MintError("CHAIN_SWITCH_FAILED", `Could not switch the wallet to chain ${String(chainId)}.`, { cause: e });
423
- }
424
- }
33
+ var _react = require('react');
34
+ var _viem = require('viem');
425
35
 
426
36
  // src/core/relay/client.ts
427
- var import_viem3 = require("viem");
37
+
428
38
  var RELAY_API = { mainnet: "https://api.relay.link", testnet: "https://api.testnets.relay.link" };
429
39
  var MAINNET_PAY_CHAINS = [1, 8453, 10, 360, 33139];
430
40
  var MAINNET_DROP_CHAINS = [1, 8453, 10, 360];
@@ -438,7 +48,7 @@ function payChainsFor(dropChainId) {
438
48
  }
439
49
  var CACHE_MS = 3e4;
440
50
  var cache = /* @__PURE__ */ new Map();
441
- var cacheKey = (a) => [a.testnet, a.originChainId, a.destinationChainId, a.tx.to.toLowerCase(), a.tx.value, (0, import_viem3.keccak256)(a.tx.data), a.payer.toLowerCase(), a.recipient.toLowerCase()].join(":");
51
+ var cacheKey = (a) => [a.testnet, a.originChainId, a.destinationChainId, a.tx.to.toLowerCase(), a.tx.value, _viem.keccak256.call(void 0, a.tx.data), a.payer.toLowerCase(), a.recipient.toLowerCase()].join(":");
442
52
  var big = (v) => {
443
53
  if (typeof v === "string" && /^\d+$/.test(v)) return BigInt(v);
444
54
  if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0) return BigInt(v);
@@ -450,42 +60,42 @@ function moneyOf(amount, currency) {
450
60
  const decimals = typeof c.decimals === "number" ? c.decimals : 18;
451
61
  const symbol = typeof c.symbol === "string" ? c.symbol : "ETH";
452
62
  const value = big(amount);
453
- return { value, decimals, symbol, formatted: (0, import_viem3.formatUnits)(value, decimals) };
63
+ return { value, decimals, symbol, formatted: _viem.formatUnits.call(void 0, value, decimals) };
454
64
  }
455
65
  function revertReason(errorData) {
456
66
  if (typeof errorData !== "string") return "";
457
- const text2 = errorData.replace(/^execution reverted:?\s*/i, "").trim();
458
- return text2 === "execution reverted" ? "" : text2;
67
+ const text = errorData.replace(/^execution reverted:?\s*/i, "").trim();
68
+ return text === "execution reverted" ? "" : text;
459
69
  }
460
70
  function parseQuote(body, originChainId) {
461
71
  const b = obj(body);
462
72
  const steps = Array.isArray(b.steps) ? b.steps.map(obj) : [];
463
- const unknownStep = () => new MintError("BRIDGE_UNAVAILABLE", "Relay returned a route this button cannot execute.");
73
+ const unknownStep = () => new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_UNAVAILABLE", "Relay returned a route this button cannot execute.");
464
74
  if (steps.length !== 1 || steps[0].kind !== "transaction") throw unknownStep();
465
- const step2 = steps[0];
466
- const rawItems = Array.isArray(step2.items) ? step2.items.map(obj) : [];
75
+ const step = steps[0];
76
+ const rawItems = Array.isArray(step.items) ? step.items.map(obj) : [];
467
77
  if (rawItems.length !== 1) throw unknownStep();
468
78
  const items = rawItems.map((item) => {
469
79
  const d = obj(item.data);
470
80
  const chainId = Number(d.chainId);
471
- if (chainId !== originChainId || typeof d.to !== "string" || !(0, import_viem3.isHex)(d.data)) throw unknownStep();
472
- return { chainId, to: (0, import_viem3.getAddress)(d.to), data: d.data, value: big(d.value), gas: d.gas === void 0 ? null : big(d.gas) };
81
+ if (chainId !== originChainId || typeof d.to !== "string" || !_viem.isHex.call(void 0, d.data)) throw unknownStep();
82
+ return { chainId, to: _viem.getAddress.call(void 0, d.to), data: d.data, value: big(d.value), gas: d.gas === void 0 ? null : big(d.gas) };
473
83
  });
474
- const requestId = (0, import_viem3.isHex)(step2.requestId) ? step2.requestId : (0, import_viem3.isHex)(b.requestId) ? b.requestId : null;
84
+ const requestId = _viem.isHex.call(void 0, step.requestId) ? step.requestId : _viem.isHex.call(void 0, b.requestId) ? b.requestId : null;
475
85
  if (!requestId) throw unknownStep();
476
86
  const details = obj(b.details);
477
87
  const currencyIn = obj(details.currencyIn);
478
88
  const fees = obj(b.fees);
479
89
  const amountIn = moneyOf(currencyIn.amount, currencyIn.currency);
480
- if (obj(currencyIn.currency).address !== void 0 && obj(currencyIn.currency).address !== import_viem3.zeroAddress) throw unknownStep();
90
+ if (obj(currencyIn.currency).address !== void 0 && obj(currencyIn.currency).address !== _viem.zeroAddress) throw unknownStep();
481
91
  if (items[0].value !== amountIn.value) throw unknownStep();
482
92
  return {
483
93
  requestId,
484
94
  originChainId,
485
95
  items,
486
96
  amountIn,
487
- relayFee: moneyOf(obj(fees.relayer).amount, obj(fees.relayer).currency ?? currencyIn.currency),
488
- originGas: moneyOf(obj(fees.gas).amount, obj(fees.gas).currency ?? currencyIn.currency),
97
+ relayFee: moneyOf(obj(fees.relayer).amount, _nullishCoalesce(obj(fees.relayer).currency, () => ( currencyIn.currency))),
98
+ originGas: moneyOf(obj(fees.gas).amount, _nullishCoalesce(obj(fees.gas).currency, () => ( currencyIn.currency))),
489
99
  quotedAt: Math.floor(Date.now() / 1e3)
490
100
  };
491
101
  }
@@ -531,7 +141,7 @@ async function timedFetch(f, url, init, ms) {
531
141
  }
532
142
  }
533
143
  async function requestQuote(a) {
534
- const f = a.fetch ?? globalThis.fetch;
144
+ const f = _nullishCoalesce(a.fetch, () => ( globalThis.fetch));
535
145
  const body = {
536
146
  user: a.payer,
537
147
  recipient: a.recipient,
@@ -539,8 +149,8 @@ async function requestQuote(a) {
539
149
  // R11: without refundTo, Relay disables automatic refunds.
540
150
  originChainId: a.originChainId,
541
151
  destinationChainId: a.destinationChainId,
542
- originCurrency: import_viem3.zeroAddress,
543
- destinationCurrency: import_viem3.zeroAddress,
152
+ originCurrency: _viem.zeroAddress,
153
+ destinationCurrency: _viem.zeroAddress,
544
154
  tradeType: "EXACT_OUTPUT",
545
155
  amount: a.tx.value.toString(),
546
156
  txs: [{ to: a.tx.to, value: a.tx.value.toString(), data: a.tx.data }]
@@ -553,21 +163,21 @@ async function requestQuote(a) {
553
163
  body: JSON.stringify(body)
554
164
  }, RELAY_TIMEOUTS.quoteMs);
555
165
  } catch (e) {
556
- throw new MintError("BRIDGE_UNAVAILABLE", "Could not reach Relay for a cross-chain quote.", { cause: e });
166
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_UNAVAILABLE", "Could not reach Relay for a cross-chain quote.", { cause: e });
557
167
  }
558
168
  const json = res.json;
559
169
  if (res.ok) return parseQuote(json, a.originChainId);
560
170
  const j = obj(json);
561
171
  if (j.errorCode === "DESTINATION_TX_FAILED") {
562
172
  const reason = revertReason(j.errorData);
563
- throw new MintError("SIMULATION_REVERTED", reason || "The mint would fail on the drop network.", { cause: json, domain: "relay" });
173
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("SIMULATION_REVERTED", reason || "The mint would fail on the drop network.", { cause: json, domain: "relay" });
564
174
  }
565
175
  if (res.status === 401 || j.errorCode === "UNAUTHORIZED_QUOTE") {
566
176
  console.warn("dropkit: Relay rejected the quote (401 UNAUTHORIZED_QUOTE). Relay gates quotes that carry a referrer or need an API key.");
567
- throw new MintError("BRIDGE_UNAVAILABLE", "Relay refused the cross-chain quote.", { cause: json });
177
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_UNAVAILABLE", "Relay refused the cross-chain quote.", { cause: json });
568
178
  }
569
- if (res.status === 429) throw new MintError("RATE_LIMITED", "Relay is rate limiting quotes. Try again in a moment.", { cause: json });
570
- throw new MintError("BRIDGE_UNAVAILABLE", `Relay could not quote this mint (${String(res.status)}).`, { cause: json });
179
+ if (res.status === 429) throw new (0, _chunkOO6QQT3Mcjs.MintError)("RATE_LIMITED", "Relay is rate limiting quotes. Try again in a moment.", { cause: json });
180
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_UNAVAILABLE", `Relay could not quote this mint (${String(res.status)}).`, { cause: json });
571
181
  }
572
182
  function getQuote(a) {
573
183
  const k = cacheKey(a);
@@ -577,19 +187,19 @@ function getQuote(a) {
577
187
  const quote = requestQuote(a);
578
188
  cache.set(k, { at: now, quote });
579
189
  quote.catch(() => {
580
- if (cache.get(k)?.quote === quote) cache.delete(k);
190
+ if (_optionalChain([cache, 'access', _2 => _2.get, 'call', _3 => _3(k), 'optionalAccess', _4 => _4.quote]) === quote) cache.delete(k);
581
191
  });
582
192
  return raceSignal(quote, a.signal);
583
193
  }
584
194
  var realReason = (v) => typeof v === "string" && v !== "" && v !== "N/A" ? v : null;
585
195
  async function getStatus(a) {
586
- const f = a.fetch ?? globalThis.fetch;
196
+ const f = _nullishCoalesce(a.fetch, () => ( globalThis.fetch));
587
197
  const res = await raceSignal(timedFetch(f, `${a.testnet ? RELAY_API.testnet : RELAY_API.mainnet}/intents/status/v3?requestId=${a.requestId}`, {}, RELAY_TIMEOUTS.statusMs), a.signal);
588
198
  if (!res.ok) throw new Error(`Relay status ${String(res.status)}`);
589
199
  const j = obj(res.json);
590
200
  return {
591
201
  status: typeof j.status === "string" ? j.status : "unknown",
592
- txHashes: Array.isArray(j.txHashes) ? j.txHashes.filter((h) => (0, import_viem3.isHex)(h)) : [],
202
+ txHashes: Array.isArray(j.txHashes) ? j.txHashes.filter((h) => _viem.isHex.call(void 0, h)) : [],
593
203
  failReason: realReason(j.failReason),
594
204
  refundFailReason: realReason(j.refundFailReason)
595
205
  };
@@ -604,18 +214,18 @@ var POLL_FAST_FOR_MS = 6e4;
604
214
  var POLL_CAP_MS = 10 * 6e4;
605
215
  var defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
606
216
  const t = setTimeout(resolve, ms);
607
- signal?.addEventListener("abort", () => {
217
+ _optionalChain([signal, 'optionalAccess', _5 => _5.addEventListener, 'call', _6 => _6("abort", () => {
608
218
  clearTimeout(t);
609
219
  reject(new DOMException("Relay polling cancelled", "AbortError"));
610
- }, { once: true });
220
+ }, { once: true })]);
611
221
  });
612
222
  async function pollUntilTerminal(a) {
613
- const sleep = a.sleep ?? defaultSleep;
614
- const now = a.now ?? Date.now;
223
+ const sleep = _nullishCoalesce(a.sleep, () => ( defaultSleep));
224
+ const now = _nullishCoalesce(a.now, () => ( Date.now));
615
225
  const start = now();
616
226
  let warned = false;
617
227
  for (; ; ) {
618
- a.assertActive?.();
228
+ _optionalChain([a, 'access', _7 => _7.assertActive, 'optionalCall', _8 => _8()]);
619
229
  try {
620
230
  const status = await getStatus({ testnet: a.testnet, requestId: a.requestId, ...a.signal ? { signal: a.signal } : {}, ...a.fetch ? { fetch: a.fetch } : {} });
621
231
  if (TERMINAL.includes(status.status)) return { kind: "terminal", status };
@@ -624,9 +234,9 @@ async function pollUntilTerminal(a) {
624
234
  console.warn(`dropkit: Relay status "${status.status}" for ${a.requestId}; still waiting.`);
625
235
  }
626
236
  } catch (e) {
627
- if (e?.name === "AbortError") throw e;
237
+ if (_optionalChain([e, 'optionalAccess', _9 => _9.name]) === "AbortError") throw e;
628
238
  }
629
- a.assertActive?.();
239
+ _optionalChain([a, 'access', _10 => _10.assertActive, 'optionalCall', _11 => _11()]);
630
240
  const elapsed = now() - start;
631
241
  if (elapsed >= POLL_CAP_MS) return { kind: "timeout" };
632
242
  await sleep(elapsed < POLL_FAST_FOR_MS ? POLL_FAST_MS : POLL_SLOW_MS, a.signal);
@@ -640,7 +250,7 @@ function outstandingKey(config, payer) {
640
250
  const target = config.type === "manifold-claim" ? `${config.creatorContract.toLowerCase()}:${config.instanceId}` : config.address.toLowerCase();
641
251
  return `${String(config.chainId)}:${target}:${payer.toLowerCase()}`;
642
252
  }
643
- var getOutstanding = (key) => memory.get(key) ?? null;
253
+ var getOutstanding = (key) => _nullishCoalesce(memory.get(key), () => ( null));
644
254
  var setOutstanding = (key, out) => void memory.set(key, out);
645
255
  var clearOutstanding = (key) => void memory.delete(key);
646
256
  function claimDeposit(key) {
@@ -650,768 +260,22 @@ function claimDeposit(key) {
650
260
  }
651
261
  var releaseDeposit = (key) => void claimed.delete(key);
652
262
 
653
- // src/core/adapters/manifold-claim/index.ts
654
- var import_viem5 = require("viem");
263
+ // src/core/adapters/contract/index.ts
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+
655
273
 
656
- // src/core/adapters/manifold-claim/abis.ts
657
- var import_viem4 = require("viem");
658
- var CLAIM_721_V5_ABI = (0, import_viem4.parseAbi)([
659
- "function getClaim(address creatorContractAddress, uint256 instanceId) view returns ((uint32 total, uint32 totalMax, uint32 walletMax, uint48 startDate, uint48 endDate, uint8 storageProtocol, uint8 contractVersion, bool identical, bytes32 merkleRoot, string location, uint256 cost, address paymentReceiver, address erc20) claim)"
660
- ]);
661
- var CLAIM_1155_V5_ABI = (0, import_viem4.parseAbi)([
662
- "function getClaim(address creatorContractAddress, uint256 instanceId) view returns ((uint32 total, uint32 totalMax, uint32 walletMax, uint48 startDate, uint48 endDate, uint8 storageProtocol, bytes32 merkleRoot, string location, uint256 tokenId, uint256 cost, address paymentReceiver, address erc20) claim)"
663
- ]);
664
- var CLAIM_721_V7_ABI = (0, import_viem4.parseAbi)([
665
- "function getClaim(address creatorContractAddress, uint256 instanceId) view returns ((uint32 total, uint32 totalMax, uint32 walletMax, uint48 startDate, uint48 endDate, uint8 storageProtocol, uint8 contractVersion, bool identical, bytes32 merkleRoot, string location, uint256 cost, address paymentReceiver, address erc20, address signingAddress) claim)"
666
- ]);
667
- var CLAIM_1155_V7_ABI = (0, import_viem4.parseAbi)([
668
- "function getClaim(address creatorContractAddress, uint256 instanceId) view returns ((uint32 total, uint32 totalMax, uint32 walletMax, uint48 startDate, uint48 endDate, uint8 storageProtocol, bytes32 merkleRoot, string location, uint256 tokenId, uint256 cost, address paymentReceiver, address erc20, address signingAddress) claim)"
669
- ]);
670
- var EXTENSION_COMMON_ABI = (0, import_viem4.parseAbi)([
671
- "function MINT_FEE() view returns (uint256)",
672
- "function MINT_FEE_MERKLE() view returns (uint256)",
673
- "function getTotalMints(address minter, address creatorContractAddress, uint256 instanceId) view returns (uint32)",
674
- "function checkMintIndices(address creatorContractAddress, uint256 instanceId, uint32[] mintIndices) view returns (bool[] minted)",
675
- "function mintProxy(address creatorContractAddress, uint256 instanceId, uint16 mintCount, uint32[] mintIndices, bytes32[][] merkleProofs, address mintFor) payable"
676
- ]);
677
- var EXTENSION_ERRORS_ABI = (0, import_viem4.parseAbi)([
678
- "error Error(string message)",
679
- "error Panic(uint256 code)",
680
- "error ClaimInactive()",
681
- "error ClaimNotInitialized()",
682
- "error ExpiredSignature()",
683
- "error FailedToTransfer()",
684
- "error InvalidAirdrop()",
685
- "error InvalidInput()",
686
- "error InvalidInstance()",
687
- "error InvalidSignature()",
688
- "error InvalidStartDate()",
689
- "error InvalidStorageProtocol()",
690
- "error MustUseSignatureMinting()",
691
- "error TokenDNE()",
692
- "error TooManyRequested()"
693
- ]);
694
- var CREATOR_ABI = (0, import_viem4.parseAbi)(["function getExtensions() view returns (address[])"]);
695
- var ERC20_ABI = (0, import_viem4.parseAbi)([
696
- "function symbol() view returns (string)",
697
- "function decimals() view returns (uint8)",
698
- "function balanceOf(address owner) view returns (uint256)",
699
- "function allowance(address owner, address spender) view returns (uint256)",
700
- "function approve(address spender, uint256 amount) returns (bool)"
701
- ]);
702
274
 
703
- // src/core/adapters/manifold-claim/merkle.ts
704
- var UINT32_MAX = 4294967295;
705
- async function getJson(fetchFn, url, signal, what) {
706
- let res;
707
- try {
708
- signal?.throwIfAborted();
709
- res = await fetchFn(url, signal ? { signal } : void 0);
710
- } catch (cause) {
711
- throw new MintError("ALLOWLIST_UNAVAILABLE", `Could not reach the allowlist service (${what}).`, { cause });
712
- }
713
- if (res.status === 429) throw new MintError("RATE_LIMITED", "The allowlist service is rate limiting requests. Try again shortly.");
714
- if (!res.ok) throw new MintError("ALLOWLIST_UNAVAILABLE", `The allowlist service has no data for this claim (${what}: HTTP ${res.status}).`);
715
- try {
716
- return await res.json();
717
- } catch (cause) {
718
- throw new MintError("ALLOWLIST_UNAVAILABLE", `The allowlist service returned an unreadable response (${what}).`, { cause });
719
- }
720
- }
721
- var isRecord = (v) => typeof v === "object" && v !== null;
722
- var scopeCaches = /* @__PURE__ */ new WeakMap();
723
- function memo(cache2, key, signal, load) {
724
- const hit = cache2.get(key);
725
- if (hit) return hit;
726
- const p = withSignal(load(), signal);
727
- cache2.set(key, p);
728
- p.catch(() => {
729
- if (cache2.get(key) === p) cache2.delete(key);
730
- });
731
- return p;
732
- }
733
- function withSignal(p, signal) {
734
- if (!signal) return p;
735
- return new Promise((resolve, reject) => {
736
- const onAbort = () => reject(new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist request was cancelled.", { cause: signal.reason }));
737
- p.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
738
- if (signal.aborted) return onAbort();
739
- signal.addEventListener("abort", onAbort, { once: true });
740
- });
741
- }
742
- async function loadInstance(fetchFn, api, instanceId, signal) {
743
- const instance = await getJson(fetchFn, `${api}/public/instance/data?id=${instanceId}`, signal, "instance data");
744
- const publicData = isRecord(instance) ? instance.publicData : void 0;
745
- const allowlist = isRecord(publicData) ? publicData.instanceAllowlist : void 0;
746
- const merkleTreeId = isRecord(allowlist) ? allowlist.merkleTreeId : void 0;
747
- const appId = isRecord(instance) ? instance.appId : void 0;
748
- if (typeof merkleTreeId !== "number" && typeof merkleTreeId !== "string" || typeof appId !== "number" && typeof appId !== "string") {
749
- throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist for this claim is not published yet.");
750
- }
751
- return { merkleTreeId, appId };
752
- }
753
- async function loadEntries(fetchFn, api, instanceId, recipient, scoped) {
754
- const { signal } = scoped;
755
- const { merkleTreeId, appId } = await memo(scoped.instances, `${api}|${instanceId}`, signal, () => loadInstance(fetchFn, api, instanceId, signal));
756
- const url = `${api}/public/merkleTree/${encodeURIComponent(String(merkleTreeId))}/merkleInfo?address=${recipient}&appId=${encodeURIComponent(String(appId))}`;
757
- const body = await getJson(fetchFn, url, signal, "merkle info");
758
- if (!Array.isArray(body)) throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist service returned an unexpected response.");
759
- return body.map((row) => {
760
- const proof = isRecord(row) ? row.merkleProof : void 0;
761
- const value = isRecord(row) ? row.value : void 0;
762
- if (!Array.isArray(proof) || !proof.every((p) => typeof p === "string" && /^0x[0-9a-fA-F]{64}$/.test(p)) || typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > UINT32_MAX) {
763
- throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist service returned an unexpected response.");
764
- }
765
- return { mintIndex: value, proof };
766
- });
767
- }
768
- async function fetchMerkleEntries(args) {
769
- if (args.signal?.aborted) {
770
- throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist request was cancelled.", { cause: args.signal.reason });
771
- }
772
- const fetchFn = args.fetch ?? ((input, init) => globalThis.fetch(input, init));
773
- const key = `${args.api}|${args.instanceId}|${args.recipient.toLowerCase()}`;
774
- let scoped = scopeCaches.get(args.scope);
775
- if (!scoped || scoped.signal?.aborted) {
776
- scoped = { signal: args.signal, instances: /* @__PURE__ */ new Map(), entries: /* @__PURE__ */ new Map() };
777
- scopeCaches.set(args.scope, scoped);
778
- }
779
- const cache2 = scoped;
780
- const entries = await memo(cache2.entries, key, cache2.signal, () => loadEntries(fetchFn, args.api, args.instanceId, args.recipient, cache2));
781
- return entries.slice();
782
- }
783
-
784
- // src/core/adapters/manifold-claim/index.ts
785
- var V6_721 = "0x1eb73fee2090fb1c20105d5ba887e3c3ba14a17e";
786
- var V6_1155 = "0x04ba6cf3c5aa6d4946f5b7f7adf111012a9fac65";
787
- var V7_721 = "0x23aa05a271debffaa3d75739af5581f744b326e4";
788
- var V7_1155 = "0x26bbea7803dcac346d5f5f135b57cf2c752a02be";
789
- var V8_721 = "0x5889e848b2423344f7969bc158100c07595c0137";
790
- var V8_1155 = "0x88438f4d4b8516e758a319ad16924da60e1e56cc";
791
- var v6 = (chainId) => [
792
- { chainId, address: V6_721, generation: "V6", spec: "721", abi: "Claim721V5Optimization" },
793
- { chainId, address: V6_1155, generation: "V6", spec: "1155", abi: "Claim1155V5Optimization" }
794
- ];
795
- var v7 = (chainId) => [
796
- { chainId, address: V7_721, generation: "V7", spec: "721", abi: "Claim721V7" },
797
- { chainId, address: V7_1155, generation: "V7", spec: "1155", abi: "Claim1155V7" }
798
- ];
799
- var EXTENSIONS = [
800
- ...v6(1),
801
- ...v7(1),
802
- ...v6(8453),
803
- ...v7(8453),
804
- ...v6(10),
805
- ...v7(10),
806
- ...v7(360),
807
- { chainId: 360, address: V8_1155, generation: "V8", spec: "1155", abi: "Claim1155V7" },
808
- ...v6(11155111),
809
- ...v7(11155111),
810
- { chainId: 11155111, address: V8_721, generation: "V8", spec: "721", abi: "Claim721V7" },
811
- { chainId: 11155111, address: V8_1155, generation: "V8", spec: "1155", abi: "Claim1155V7" }
812
- ];
813
- function findExtension(chainId, address) {
814
- const a = address.toLowerCase();
815
- return EXTENSIONS.find((e) => e.chainId === chainId && e.address === a);
816
- }
817
- var MERKLE_API = "https://apps.api.manifoldxyz.dev";
818
- var MAX_MINT_COUNT = 65535;
819
- var GAS_UNITS_BASE = 100000n;
820
- var GAS_UNITS_PER_TOKEN = 150000n;
821
- var GAS_UNITS_APPROVE = 60000n;
822
- var dropResolved = /* @__PURE__ */ new WeakMap();
823
- var WALLET_DATA_BRAND = /* @__PURE__ */ Symbol("manifold-claim-wallet-data");
824
- var isWalletData = (d) => typeof d === "object" && d !== null && d.brand === WALLET_DATA_BRAND;
825
- var isAllowlist = (claim) => claim.merkleRoot !== import_viem5.zeroHash;
826
- function isContractFailure(e) {
827
- if (!(e instanceof import_viem5.BaseError)) return false;
828
- return e.walk((x) => x instanceof import_viem5.ContractFunctionRevertedError || x.name === "ContractFunctionZeroDataError") !== null;
829
- }
830
- function toRpcError(e) {
831
- if (e instanceof MintError) return e;
832
- const msg = e instanceof import_viem5.BaseError ? e.shortMessage : e instanceof Error ? e.message : String(e);
833
- return new MintError("RPC_ERROR", `RPC request failed: ${msg}`, { cause: e });
834
- }
835
- async function rpc(fn) {
836
- try {
837
- return await fn();
838
- } catch (e) {
839
- throw toRpcError(e);
840
- }
841
- }
842
- function revertData(e) {
843
- const hit = e.walk((x) => {
844
- const d2 = x.data;
845
- return (0, import_viem5.isHex)(d2) && d2.length >= 10 || typeof d2 === "object" && d2 !== null && (0, import_viem5.isHex)(d2.data);
846
- });
847
- const d = hit?.data;
848
- if ((0, import_viem5.isHex)(d)) return d;
849
- const inner = d?.data;
850
- return (0, import_viem5.isHex)(inner) ? inner : void 0;
851
- }
852
- function decodeRevert(e) {
853
- if (!(e instanceof import_viem5.BaseError)) return null;
854
- const data = revertData(e);
855
- if (data) {
856
- try {
857
- const d = (0, import_viem5.decodeErrorResult)({ abi: EXTENSION_ERRORS_ABI, data });
858
- if (d.errorName === "Error" && typeof d.args?.[0] === "string") return d.args[0];
859
- if (d.errorName === "Panic") return `Panic(${String(d.args?.[0])})`;
860
- return d.errorName;
861
- } catch {
862
- return `reverted with unknown error ${data.slice(0, 10)}`;
863
- }
864
- }
865
- const named = e.walk((x) => ["ExecutionRevertedError", "InsufficientFundsError"].includes(x.name));
866
- return named instanceof import_viem5.BaseError ? named.shortMessage : null;
867
- }
868
- var money = (value, decimals, symbol) => ({ value, decimals, symbol, formatted: (0, import_viem5.formatUnits)(value, decimals) });
869
- function timestamp(v, field) {
870
- if (v === 0n) return null;
871
- if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new MintError("RPC_ERROR", `Claim ${field} does not fit a safe integer`);
872
- return Number(v);
873
- }
874
- function parseConfig(config) {
875
- if (!(0, import_viem5.isAddress)(config.creatorContract, { strict: false })) {
876
- throw new MintError("INVALID_CONFIG", "creatorContract is not a valid address.", { field: "creatorContract" });
877
- }
878
- if (config.extension !== void 0 && !(0, import_viem5.isAddress)(config.extension, { strict: false })) {
879
- throw new MintError("INVALID_CONFIG", "extension is not a valid address.", { field: "extension" });
880
- }
881
- if (typeof config.instanceId !== "string" || !/^\d+$/.test(config.instanceId)) {
882
- throw new MintError("INVALID_CONFIG", "instanceId must be a non-negative integer string.", { field: "instanceId" });
883
- }
884
- return {
885
- creator: (0, import_viem5.getAddress)(config.creatorContract),
886
- instanceId: BigInt(config.instanceId),
887
- extension: config.extension === void 0 ? void 0 : (0, import_viem5.getAddress)(config.extension)
888
- };
889
- }
890
- var notFound = (config) => new MintError("CLAIM_NOT_FOUND", `No Manifold claim ${config.instanceId} found on ${config.creatorContract}.`);
891
- async function readClaim(client, entry, creator, instanceId, config) {
892
- const address = (0, import_viem5.getAddress)(entry.address);
893
- const args = [creator, instanceId];
894
- try {
895
- switch (entry.abi) {
896
- case "Claim721V5Optimization": {
897
- const c = await client.readContract({ address, abi: CLAIM_721_V5_ABI, functionName: "getClaim", args });
898
- return { ...base2(c), signingAddress: null };
899
- }
900
- case "Claim1155V5Optimization": {
901
- const c = await client.readContract({ address, abi: CLAIM_1155_V5_ABI, functionName: "getClaim", args });
902
- return { ...base2(c), signingAddress: null };
903
- }
904
- case "Claim721V7": {
905
- const c = await client.readContract({ address, abi: CLAIM_721_V7_ABI, functionName: "getClaim", args });
906
- return { ...base2(c), signingAddress: c.signingAddress };
907
- }
908
- case "Claim1155V7": {
909
- const c = await client.readContract({ address, abi: CLAIM_1155_V7_ABI, functionName: "getClaim", args });
910
- return { ...base2(c), signingAddress: c.signingAddress };
911
- }
912
- }
913
- } catch (e) {
914
- if (isContractFailure(e)) throw notFound(config);
915
- throw toRpcError(e);
916
- }
917
- }
918
- function base2(c) {
919
- return {
920
- total: BigInt(c.total),
921
- totalMax: BigInt(c.totalMax),
922
- walletMax: BigInt(c.walletMax),
923
- startDate: BigInt(c.startDate),
924
- endDate: BigInt(c.endDate),
925
- merkleRoot: c.merkleRoot,
926
- cost: c.cost,
927
- erc20: c.erc20
928
- };
929
- }
930
- async function hasCode(client, address) {
931
- const code2 = await rpc(() => client.getCode({ address: (0, import_viem5.getAddress)(address) }));
932
- return code2 !== void 0 && code2 !== "0x";
933
- }
934
- var unknownExtension = (address, why) => new MintError("UNKNOWN_EXTENSION", `Extension ${address} ${why}.`);
935
- async function resolveExtension(ctx, config) {
936
- const { creator, instanceId, extension } = parseConfig(config);
937
- const { client } = ctx;
938
- if (extension) {
939
- const entry = findExtension(config.chainId, extension);
940
- if (!entry) throw unknownExtension(extension, `is not a supported Manifold claim extension on chain ${config.chainId}`);
941
- if (!await hasCode(client, extension)) throw unknownExtension(extension, "has no contract code on this chain");
942
- return { entry, claim: await readClaim(client, entry, creator, instanceId, config) };
943
- }
944
- let registered;
945
- try {
946
- registered = await client.readContract({ address: creator, abi: CREATOR_ABI, functionName: "getExtensions" });
947
- } catch (e) {
948
- if (isContractFailure(e)) throw notFound(config);
949
- throw toRpcError(e);
950
- }
951
- const candidates = [...new Set(registered.map((a) => a.toLowerCase()))].map((a) => findExtension(config.chainId, a)).filter((e) => e !== void 0);
952
- const found = await Promise.all(
953
- candidates.map(async (entry) => {
954
- if (!await hasCode(client, entry.address)) return null;
955
- try {
956
- return { entry, claim: await readClaim(client, entry, creator, instanceId, config) };
957
- } catch (e) {
958
- if (e instanceof MintError && e.reason === "CLAIM_NOT_FOUND") return null;
959
- throw e;
960
- }
961
- })
962
- );
963
- const hits = found.filter((f) => f !== null);
964
- if (hits.length === 0) throw notFound(config);
965
- if (hits.length > 1) {
966
- throw new MintError(
967
- "AMBIGUOUS_EXTENSION",
968
- `Claim ${config.instanceId} exists on ${hits.length} extensions (${hits.map((h) => h.entry.address).join(", ")}). Set config.extension.`
969
- );
970
- }
971
- return hits[0];
972
- }
973
- async function loadDrop(ctx, config) {
974
- const { entry, claim } = await resolveExtension(ctx, config);
975
- if (claim.signingAddress !== null && claim.signingAddress !== import_viem5.zeroAddress) {
976
- throw new MintError("SIGNATURE_CLAIM", "This claim mints with a signature (redemption code), which this button does not support.");
977
- }
978
- const { client } = ctx;
979
- const extension = (0, import_viem5.getAddress)(entry.address);
980
- const fee = await rpc(
981
- () => client.readContract({ address: extension, abi: EXTENSION_COMMON_ABI, functionName: isAllowlist(claim) ? "MINT_FEE_MERKLE" : "MINT_FEE" })
982
- );
983
- const native = client.chain?.nativeCurrency ?? { symbol: "ETH", decimals: 18 };
984
- let unitPrice;
985
- let paymentToken = null;
986
- if (claim.erc20 === import_viem5.zeroAddress) {
987
- unitPrice = money(claim.cost, native.decimals, native.symbol);
988
- } else {
989
- paymentToken = (0, import_viem5.getAddress)(claim.erc20);
990
- const token = paymentToken;
991
- const [symbol, decimals] = await rpc(
992
- () => Promise.all([
993
- client.readContract({ address: token, abi: ERC20_ABI, functionName: "symbol" }),
994
- client.readContract({ address: token, abi: ERC20_ABI, functionName: "decimals" })
995
- ])
996
- );
997
- unitPrice = money(claim.cost, decimals, symbol);
998
- }
999
- const drop = {
1000
- chainId: config.chainId,
1001
- unitPrice,
1002
- unitFee: money(fee, native.decimals, native.symbol),
1003
- totalMinted: claim.total,
1004
- maxSupply: claim.totalMax === 0n ? null : claim.totalMax,
1005
- startTime: timestamp(claim.startDate, "startDate"),
1006
- endTime: timestamp(claim.endDate, "endDate"),
1007
- isAllowlist: isAllowlist(claim),
1008
- paymentToken,
1009
- pricePer: "unit"
1010
- };
1011
- const resolved = { entry, claim, fee };
1012
- dropResolved.set(drop, resolved);
1013
- return { drop, resolved };
1014
- }
1015
- async function loadWallet(ctx, config, args) {
1016
- const { creator, instanceId } = parseConfig(config);
1017
- const { client } = ctx;
1018
- const resolved = dropResolved.get(args.drop) ?? (await loadDrop(ctx, config)).resolved;
1019
- const { entry, claim } = resolved;
1020
- const extension = (0, import_viem5.getAddress)(entry.address);
1021
- const payer = (0, import_viem5.getAddress)(args.payer);
1022
- const recipient = (0, import_viem5.getAddress)(args.recipient);
1023
- let walletMinted = null;
1024
- let walletMax = null;
1025
- let allowlistRemaining = null;
1026
- let maxQuantity = null;
1027
- let ineligible = null;
1028
- let unused = [];
1029
- if (isAllowlist(claim)) {
1030
- const entries = await fetchMerkleEntries({ scope: ctx.cacheScope ?? args.drop, api: MERKLE_API, instanceId: config.instanceId, recipient, fetch: ctx.fetch, signal: ctx.signal });
1031
- if (entries.length > 0) {
1032
- const minted = await rpc(
1033
- () => client.readContract({
1034
- address: extension,
1035
- abi: EXTENSION_COMMON_ABI,
1036
- functionName: "checkMintIndices",
1037
- args: [creator, instanceId, entries.map((e) => e.mintIndex)]
1038
- })
1039
- );
1040
- unused = entries.filter((_, i) => minted[i] === false);
1041
- }
1042
- allowlistRemaining = unused.length;
1043
- maxQuantity = unused.length;
1044
- if (entries.length === 0) {
1045
- ineligible = { reason: "NOT_ON_ALLOWLIST", message: "This wallet is not on the allowlist." };
1046
- } else if (unused.length === 0) {
1047
- ineligible = { reason: "ALLOWLIST_USED", message: "This wallet has already used all its allowlist spots." };
1048
- }
1049
- } else if (claim.walletMax > 0n) {
1050
- walletMax = claim.walletMax;
1051
- walletMinted = BigInt(
1052
- await rpc(() => client.readContract({ address: extension, abi: EXTENSION_COMMON_ABI, functionName: "getTotalMints", args: [recipient, creator, instanceId] }))
1053
- );
1054
- const left = walletMax > walletMinted ? walletMax - walletMinted : 0n;
1055
- maxQuantity = Number(left);
1056
- if (left === 0n) ineligible = { reason: "WALLET_LIMIT", message: `This wallet has already minted its limit of ${walletMax}.` };
1057
- }
1058
- const token = claim.erc20 === import_viem5.zeroAddress ? null : (0, import_viem5.getAddress)(claim.erc20);
1059
- const [native, erc20, gasPrice] = await rpc(
1060
- () => Promise.all([
1061
- client.getBalance({ address: payer }),
1062
- token ? client.readContract({ address: token, abi: ERC20_ABI, functionName: "balanceOf", args: [payer] }) : Promise.resolve(null),
1063
- client.getGasPrice()
1064
- ])
1065
- );
1066
- const gasUnits = GAS_UNITS_BASE + GAS_UNITS_PER_TOKEN * BigInt(Math.max(1, args.quantity)) + (token ? GAS_UNITS_APPROVE : 0n);
1067
- const data = { brand: WALLET_DATA_BRAND, resolved, config, recipient, unused };
1068
- return {
1069
- walletMinted,
1070
- walletMax,
1071
- allowlistRemaining,
1072
- maxQuantity,
1073
- ineligible,
1074
- balances: { native, erc20 },
1075
- gasReserve: gasPrice * gasUnits,
1076
- data
1077
- };
1078
- }
1079
- var sameClaim = (a, b) => a.chainId === b.chainId && a.creatorContract.toLowerCase() === b.creatorContract.toLowerCase() && a.instanceId === b.instanceId && a.extension?.toLowerCase() === b.extension?.toLowerCase();
1080
- async function buildPlan(ctx, attempt, wallet) {
1081
- const { config, quantity } = attempt;
1082
- if (!Number.isInteger(quantity) || quantity < 1 || quantity > MAX_MINT_COUNT) {
1083
- throw new MintError("INVALID_CONFIG", `quantity must be an integer from 1 to ${MAX_MINT_COUNT}.`, { field: "quantity" });
1084
- }
1085
- const { creator, instanceId } = parseConfig(config);
1086
- const recipient = (0, import_viem5.getAddress)(attempt.recipient);
1087
- const payer = (0, import_viem5.getAddress)(attempt.payer);
1088
- let data = wallet.data;
1089
- if (!isWalletData(data) || !sameClaim(data.config, config) || data.recipient !== recipient) {
1090
- const drop = (await loadDrop(ctx, config)).drop;
1091
- data = (await loadWallet(ctx, config, { payer, recipient, quantity, drop })).data;
1092
- }
1093
- if (!isWalletData(data)) throw new MintError("RPC_ERROR", "Wallet read produced no plan data.");
1094
- const { entry, claim, fee } = data.resolved;
1095
- const extension = (0, import_viem5.getAddress)(entry.address);
1096
- let mintIndices = [];
1097
- let merkleProofs = [];
1098
- if (isAllowlist(claim)) {
1099
- if (quantity > data.unused.length) {
1100
- throw new MintError("WALLET_LIMIT", `Only ${data.unused.length} allowlist spot(s) left for this wallet.`);
1101
- }
1102
- const picked = data.unused.slice(0, quantity);
1103
- mintIndices = picked.map((p) => p.mintIndex);
1104
- merkleProofs = picked.map((p) => p.proof);
1105
- }
1106
- const qty = BigInt(quantity);
1107
- const erc20 = claim.erc20 === import_viem5.zeroAddress ? null : (0, import_viem5.getAddress)(claim.erc20);
1108
- const cost = claim.cost * qty;
1109
- const value = fee * qty + (erc20 ? 0n : cost);
1110
- let approve = null;
1111
- if (erc20 && cost > 0n) {
1112
- const allowance = await rpc(() => ctx.client.readContract({ address: erc20, abi: ERC20_ABI, functionName: "allowance", args: [payer, extension] }));
1113
- if (allowance < cost) {
1114
- approve = {
1115
- token: erc20,
1116
- spender: extension,
1117
- amount: cost,
1118
- tx: { to: erc20, data: (0, import_viem5.encodeFunctionData)({ abi: ERC20_ABI, functionName: "approve", args: [extension, cost] }), value: 0n }
1119
- };
1120
- }
1121
- }
1122
- return {
1123
- approve,
1124
- mint: {
1125
- to: extension,
1126
- data: (0, import_viem5.encodeFunctionData)({
1127
- abi: EXTENSION_COMMON_ABI,
1128
- functionName: "mintProxy",
1129
- args: [creator, instanceId, quantity, mintIndices, merkleProofs.map((p) => [...p]), recipient]
1130
- }),
1131
- value
1132
- },
1133
- tokenContract: creator
1134
- };
1135
- }
1136
- var RELAY_VERIFIED = ["V6", "V7"];
1137
- var manifoldClaimAdapter = {
1138
- supportsRelay: (drop) => {
1139
- const resolved = dropResolved.get(drop);
1140
- return resolved !== void 0 && RELAY_VERIFIED.includes(resolved.entry.generation) && drop.paymentToken === null;
1141
- },
1142
- readDrop: async (ctx, config) => (await loadDrop(ctx, config)).drop,
1143
- readWallet: loadWallet,
1144
- buildPlan,
1145
- simulate: async (ctx, attempt, plan) => {
1146
- try {
1147
- await ctx.client.call({ account: (0, import_viem5.getAddress)(attempt.payer), to: plan.mint.to, data: plan.mint.data, value: plan.mint.value });
1148
- } catch (e) {
1149
- const text2 = decodeRevert(e);
1150
- if (text2 === null) throw toRpcError(e);
1151
- throw new MintError("SIMULATION_REVERTED", text2, { cause: e });
1152
- }
1153
- }
1154
- };
1155
275
 
1156
- // src/core/adapters/contract/index.ts
1157
- var import_viem7 = require("viem");
1158
-
1159
- // src/core/machine.ts
1160
- var import_viem6 = require("viem");
1161
- var MINT_STATES = [
1162
- "loading",
1163
- "unsupported",
1164
- "upcoming",
1165
- "ended",
1166
- "sold-out",
1167
- "disconnected",
1168
- "connecting",
1169
- "live",
1170
- "ineligible",
1171
- "insufficient-funds",
1172
- "switching-chain",
1173
- "approving",
1174
- "minting",
1175
- "confirming",
1176
- "success",
1177
- "error"
1178
- ];
1179
- var CLICKABLE_STATES = ["disconnected", "live", "success", "error"];
1180
- var IN_FLIGHT_STATES = ["switching-chain", "approving", "minting", "confirming"];
1181
- var MAX_QUANTITY = 65535;
1182
- function initialState(opts) {
1183
- return {
1184
- name: "loading",
1185
- reason: null,
1186
- message: null,
1187
- readGen: 0,
1188
- walletGen: 0,
1189
- drop: null,
1190
- account: null,
1191
- walletRead: null,
1192
- blocked: null,
1193
- quantity: toQuantity(opts?.quantity ?? 1, MAX_QUANTITY),
1194
- attempt: null,
1195
- result: null,
1196
- pendingRefresh: false,
1197
- now: 0,
1198
- crossChain: false,
1199
- routePending: false,
1200
- route: null,
1201
- short: null
1202
- };
1203
- }
1204
- var NO_ROUTE = { crossChain: false, routePending: false, route: null, short: null };
1205
- var PICK_ANOTHER = "Pick another network to pay from.";
1206
- function toQuantity(q, max) {
1207
- if (Number.isNaN(q)) return 1;
1208
- return Math.max(1, Math.min(Math.floor(q), max));
1209
- }
1210
- function isInFlight(s) {
1211
- return s.attempt !== null || IN_FLIGHT_STATES.includes(s.name);
1212
- }
1213
- function isIdle(s) {
1214
- return !isInFlight(s) && s.name !== "connecting" && s.name !== "success" && s.name !== "error";
1215
- }
1216
- function derive(s, unsupported) {
1217
- const named = (name) => ({ name, reason: null, message: null });
1218
- const { drop, walletRead } = s;
1219
- if (unsupported) return { name: "unsupported", reason: s.reason, message: s.message };
1220
- if (drop === null) return named("loading");
1221
- if (drop.endTime !== null && drop.endTime <= s.now) return named("ended");
1222
- if (drop.maxSupply !== null && drop.maxSupply > 0n && drop.totalMinted >= drop.maxSupply) return named("sold-out");
1223
- if (drop.startTime !== null && drop.startTime > s.now) return named("upcoming");
1224
- if (s.account === null) return named("disconnected");
1225
- if (walletRead === null) return named("loading");
1226
- if (s.blocked !== null) return s.blocked;
1227
- if (walletRead.ineligible !== null) {
1228
- return { name: "ineligible", reason: walletRead.ineligible.reason, message: walletRead.ineligible.message };
1229
- }
1230
- if (s.routePending) return named("loading");
1231
- if (s.route?.kind === "relay") return named("live");
1232
- if (s.short !== null) {
1233
- return { name: "insufficient-funds", reason: "INSUFFICIENT_FUNDS", message: `Not enough ${s.short.symbol} on ${s.short.name}. ${PICK_ANOTHER}` };
1234
- }
1235
- const total = selectTotal(s);
1236
- if (total !== null) {
1237
- const { native, erc20 } = total;
1238
- if (native.value + walletRead.gasReserve > walletRead.balances.native) {
1239
- const more = s.crossChain ? ` ${PICK_ANOTHER}` : "";
1240
- return { name: "insufficient-funds", reason: "INSUFFICIENT_FUNDS", message: `Not enough ${native.symbol} to cover the mint.${more}` };
1241
- }
1242
- if (erc20 !== null && walletRead.balances.erc20 !== null && erc20.value > walletRead.balances.erc20) {
1243
- return { name: "insufficient-funds", reason: "INSUFFICIENT_FUNDS", message: `Not enough ${erc20.symbol} to cover the mint.` };
1244
- }
1245
- }
1246
- return named("live");
1247
- }
1248
- function settle(s, unsupported = s.name === "unsupported") {
1249
- if (!isIdle(s)) return s;
1250
- return { ...s, ...derive(s, unsupported) };
1251
- }
1252
- function clampQuantity(s) {
1253
- const quantity = toQuantity(s.quantity, selectMaxQuantity(s) ?? MAX_QUANTITY);
1254
- return quantity === s.quantity ? s : { ...s, quantity };
1255
- }
1256
- function reducer(state, event) {
1257
- const inFlight = isInFlight(state);
1258
- const failed = (reason, message) => {
1259
- if (inFlight) return { ...state, pendingRefresh: true };
1260
- if (state.name === "success" || state.name === "error") return state;
1261
- return { ...state, name: "error", reason, message };
1262
- };
1263
- switch (event.type) {
1264
- case "LOAD": {
1265
- if (event.kind === "refresh") {
1266
- const next2 = { ...state, readGen: event.gen };
1267
- return inFlight ? { ...next2, pendingRefresh: true } : settle(next2);
1268
- }
1269
- const next = { ...state, ...NO_ROUTE, readGen: event.gen, drop: null, walletRead: null, blocked: null, walletGen: state.walletGen + 1 };
1270
- return inFlight ? { ...next, pendingRefresh: true } : settle(next, false);
1271
- }
1272
- case "DROP_LOADED": {
1273
- if (event.gen !== state.readGen) return state;
1274
- const next = { ...state, drop: event.drop, now: Math.max(state.now, event.now) };
1275
- if (inFlight) return { ...next, pendingRefresh: true };
1276
- return isIdle(next) ? settle(clampQuantity(next), false) : clampQuantity(next);
1277
- }
1278
- case "DROP_UNSUPPORTED": {
1279
- if (event.gen !== state.readGen) return state;
1280
- if (inFlight) return { ...state, pendingRefresh: true };
1281
- if (state.name === "success" || state.name === "error") return state;
1282
- return { ...state, name: "unsupported", reason: event.reason, message: event.message };
1283
- }
1284
- case "READ_FAILED":
1285
- return event.gen !== state.readGen ? state : failed(event.reason, event.message);
1286
- case "ACCOUNT_CHANGED": {
1287
- const next = { ...state, ...NO_ROUTE, account: event.account, walletRead: null, blocked: null, walletGen: state.walletGen + 1 };
1288
- if (inFlight) return { ...next, pendingRefresh: true };
1289
- if (state.name === "connecting") return event.account === null ? next : settle({ ...next, name: "loading" }, false);
1290
- return settle(next);
1291
- }
1292
- case "WALLET_LOADED": {
1293
- if (event.gen !== state.walletGen) return state;
1294
- const route = event.routePending ? { routePending: state.route === null && state.short === null, route: state.route, short: state.short } : { routePending: false, route: null, short: null };
1295
- const next = { ...state, ...route, crossChain: event.crossChain ?? false, walletRead: event.read, blocked: null };
1296
- return inFlight ? { ...next, pendingRefresh: true } : settle(clampQuantity(next));
1297
- }
1298
- case "ROUTE_LOADED": {
1299
- if (event.gen !== state.walletGen) return state;
1300
- const next = { ...state, routePending: false, route: event.route, short: event.short };
1301
- return inFlight ? { ...next, pendingRefresh: true } : settle(next);
1302
- }
1303
- case "WALLET_FAILED":
1304
- return event.gen !== state.walletGen ? state : failed(event.reason, event.message);
1305
- case "CONNECT_STARTED":
1306
- return state.name === "disconnected" && state.attempt === null ? { ...state, name: "connecting", reason: null, message: null } : state;
1307
- case "CONNECT_DISMISSED":
1308
- return state.name === "connecting" ? settle({ ...state, name: "disconnected" }, false) : state;
1309
- case "TICK":
1310
- return settle({ ...state, now: Math.max(state.now, event.now) });
1311
- case "SET_QUANTITY": {
1312
- const next = { ...state, quantity: toQuantity(event.quantity, selectMaxQuantity(state) ?? MAX_QUANTITY) };
1313
- return inFlight ? { ...next, pendingRefresh: true } : settle(next);
1314
- }
1315
- case "ATTEMPT_STARTED":
1316
- if (state.attempt !== null) return state;
1317
- if (event.resume === true) return IN_FLIGHT_STATES.includes(state.name) ? state : { ...state, attempt: event.attempt };
1318
- return state.name === "live" ? { ...state, attempt: event.attempt } : state;
1319
- case "SWITCHING_CHAIN":
1320
- return step(state, event.attemptId, "switching-chain");
1321
- case "APPROVING":
1322
- return step(state, event.attemptId, "approving");
1323
- case "MINT_PROMPTED":
1324
- return step(state, event.attemptId, "minting");
1325
- case "TX_SUBMITTED":
1326
- return step(state, event.attemptId, "confirming");
1327
- case "ATTEMPT_SUCCEEDED":
1328
- return state.attempt?.attemptId === event.attemptId ? {
1329
- ...state,
1330
- name: "success",
1331
- reason: null,
1332
- message: null,
1333
- attempt: null,
1334
- result: event.result,
1335
- drop: null,
1336
- readGen: state.readGen + 1
1337
- } : state;
1338
- case "ATTEMPT_FAILED": {
1339
- if (state.attempt?.attemptId !== event.attemptId) return state;
1340
- const { reason, message } = event;
1341
- const done = { ...state, reason, message, attempt: null, result: null };
1342
- if (INELIGIBLE_REASONS.includes(reason)) {
1343
- return { ...done, name: "ineligible", blocked: { name: "ineligible", reason, message } };
1344
- }
1345
- if (reason === "INSUFFICIENT_FUNDS") {
1346
- return { ...done, name: "insufficient-funds", blocked: { name: "insufficient-funds", reason, message } };
1347
- }
1348
- return {
1349
- ...done,
1350
- name: "error",
1351
- drop: state.name === "confirming" ? null : state.drop,
1352
- readGen: state.name === "confirming" ? state.readGen + 1 : state.readGen
1353
- };
1354
- }
1355
- case "RESET": {
1356
- if (state.name !== "success" && state.name !== "error") return state;
1357
- const next = {
1358
- ...state,
1359
- readGen: event.gen,
1360
- ...NO_ROUTE,
1361
- walletRead: null,
1362
- blocked: null,
1363
- walletGen: state.walletGen + 1,
1364
- result: null,
1365
- pendingRefresh: false
1366
- };
1367
- return settle(clampQuantity({ ...next, name: "loading" }), false);
1368
- }
1369
- }
1370
- }
1371
- var STEP_ORDER = ["switching-chain", "approving", "minting", "confirming"];
1372
- function step(state, attemptId, name) {
1373
- if (state.attempt?.attemptId !== attemptId) return state;
1374
- if (STEP_ORDER.indexOf(name) <= STEP_ORDER.indexOf(state.name)) return state;
1375
- return { ...state, name, reason: null, message: null };
1376
- }
1377
- function selectMaxQuantity(state) {
1378
- const { drop, walletRead } = state;
1379
- if (drop === null) return null;
1380
- let max = MAX_QUANTITY;
1381
- if (drop.maxSupply !== null && drop.maxSupply > 0n) {
1382
- const remaining = drop.maxSupply - drop.totalMinted;
1383
- if (remaining < BigInt(max)) max = remaining > 0n ? Number(remaining) : 0;
1384
- }
1385
- if (walletRead !== null && walletRead.maxQuantity !== null) {
1386
- max = Math.min(max, Math.max(0, Math.floor(walletRead.maxQuantity)));
1387
- }
1388
- return max;
1389
- }
1390
- function selectTotal(state) {
1391
- const { drop } = state;
1392
- if (drop === null) return null;
1393
- const q = BigInt(state.quantity);
1394
- const price = drop.unitPrice;
1395
- const fee = drop.unitFee;
1396
- const priceTotal = drop.pricePer === "total" ? price.value : price.value * q;
1397
- if (drop.paymentToken !== null) {
1398
- return {
1399
- native: money2(fee.value * q, fee),
1400
- erc20: money2(priceTotal, price)
1401
- };
1402
- }
1403
- return { native: money2(priceTotal + fee.value * q, price), erc20: null };
1404
- }
1405
- function money2(value, like) {
1406
- return { value, decimals: like.decimals, symbol: like.symbol, formatted: (0, import_viem6.formatUnits)(value, like.decimals) };
1407
- }
1408
- function canAct(state) {
1409
- return state.attempt === null && CLICKABLE_STATES.includes(state.name);
1410
- }
1411
276
 
1412
- // src/core/adapters/contract/index.ts
1413
277
  var PLACEHOLDERS = ["{recipient}", "{payer}", "{quantity}", "{unitPrice}", "{totalPrice}"];
1414
- var ERC20_ABI2 = (0, import_viem7.parseAbi)([
278
+ var ERC20_ABI = _viem.parseAbi.call(void 0, [
1415
279
  "function symbol() view returns (string)",
1416
280
  "function decimals() view returns (uint8)",
1417
281
  "function balanceOf(address) view returns (uint256)",
@@ -1424,15 +288,15 @@ var PLACEHOLDER_TOKEN = /\{[A-Za-z_]\w*\}/g;
1424
288
  var DISPLAY_AMOUNT = /^\d+(\.\d+)?$/;
1425
289
  var NUMERIC_TYPE = /^u?int\d*$/;
1426
290
  function bad(field, message) {
1427
- throw new MintError("INVALID_CONFIG", `${field} ${message}`, { field });
291
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `${field} ${message}`, { field });
1428
292
  }
1429
- var isHexAddress = (a) => typeof a === "string" && (0, import_viem7.isAddress)(a, { strict: false });
293
+ var isHexAddress = (a) => typeof a === "string" && _viem.isAddress.call(void 0, a, { strict: false });
1430
294
  function functionsNamed(abi, name) {
1431
295
  return abi.filter((i) => i.type === "function" && i.name === name);
1432
296
  }
1433
297
  function validateTemplate(t, path, allowed) {
1434
298
  if (typeof t === "string") {
1435
- for (const token of t.match(PLACEHOLDER_TOKEN) ?? []) {
299
+ for (const token of _nullishCoalesce(t.match(PLACEHOLDER_TOKEN), () => ( []))) {
1436
300
  if (!PLACEHOLDERS.includes(token)) bad(path, `"${t}" is not a known placeholder (${token})`);
1437
301
  if (!allowed.includes(token)) bad(path, `"${t}" uses ${token}, which is not available in this field`);
1438
302
  }
@@ -1448,7 +312,7 @@ var ARRAY_TYPE = /^(.*)\[(\d*)\]$/;
1448
312
  var BYTES_TYPE = /^bytes(\d*)$/;
1449
313
  var INT_TYPE = /^(u?)int(\d*)$/;
1450
314
  var isExactPlaceholder = (t) => typeof t === "string" && PLACEHOLDERS.includes(t);
1451
- var hasPlaceholder = (t) => typeof t === "string" && (t.match(PLACEHOLDER_TOKEN) ?? []).length > 0;
315
+ var hasPlaceholder = (t) => typeof t === "string" && (_nullishCoalesce(t.match(PLACEHOLDER_TOKEN), () => ( []))).length > 0;
1452
316
  function intBounds(type) {
1453
317
  const m = INT_TYPE.exec(type);
1454
318
  if (!m) return null;
@@ -1456,7 +320,7 @@ function intBounds(type) {
1456
320
  return m[1] ? { min: 0n, max: 2n ** bits - 1n } : { min: -(2n ** (bits - 1n)), max: 2n ** (bits - 1n) - 1n };
1457
321
  }
1458
322
  var elementParam = (p, type) => ({ ...p, type });
1459
- var componentsOf = (p) => p.components ?? [];
323
+ var componentsOf = (p) => _nullishCoalesce(p.components, () => ( []));
1460
324
  function typeIssue(t, p, path) {
1461
325
  const no = (message) => ({ path, message });
1462
326
  const arr = ARRAY_TYPE.exec(p.type);
@@ -1483,7 +347,7 @@ function typeIssue(t, p, path) {
1483
347
  if (Array.isArray(t)) return no(`must not be an array for ${p.type}`);
1484
348
  if (p.type === "address") {
1485
349
  if (isExactPlaceholder(t)) return t === "{recipient}" || t === "{payer}" ? null : no(`${t} is a number, but the abi input is an address`);
1486
- return typeof t === "string" && !hasPlaceholder(t) && (0, import_viem7.isAddress)(t) ? null : no(`${JSON.stringify(String(t))} is not an address`);
350
+ return typeof t === "string" && !hasPlaceholder(t) && _viem.isAddress.call(void 0, t) ? null : no(`${JSON.stringify(String(t))} is not an address`);
1487
351
  }
1488
352
  if (p.type === "bool") return typeof t === "boolean" ? null : no(`${JSON.stringify(String(t))} is not a boolean`);
1489
353
  if (p.type === "string") return typeof t === "string" ? null : no(`${JSON.stringify(String(t))} is not a string`);
@@ -1507,12 +371,12 @@ function typeIssue(t, p, path) {
1507
371
  var signature = (f) => `${f.name}(${f.inputs.map((i) => i.type).join(",")})`;
1508
372
  var NO_PLACEHOLDERS = [];
1509
373
  function validateCall(abi, call, prefix, kind, allowed) {
1510
- const c = call ?? {};
374
+ const c = _nullishCoalesce(call, () => ( {}));
1511
375
  const named = typeof c.functionName === "string" ? functionsNamed(abi, c.functionName) : [];
1512
376
  if (named.length === 0) bad(`${prefix}.functionName`, `"${String(c.functionName)}" is not a function in the abi`);
1513
377
  if (c.args !== void 0 && !Array.isArray(c.args)) bad(`${prefix}.args`, "must be an array");
1514
378
  if (kind === "mint" && c.args === void 0) bad(`${prefix}.args`, "is required");
1515
- const args = c.args ?? [];
379
+ const args = _nullishCoalesce(c.args, () => ( []));
1516
380
  args.forEach((a, i) => validateTemplate(a, `${prefix}.args[${i}]`, allowed));
1517
381
  const sameArity = named.filter((f) => f.inputs.length === args.length);
1518
382
  if (sameArity.length === 0) {
@@ -1551,7 +415,7 @@ function resolveOutput(fn, output, path) {
1551
415
  if (outs.length === 0) bad(`${path}.functionName`, `"${fn.name}" returns nothing`);
1552
416
  const first = outs[0];
1553
417
  const tuple = outs.length === 1 && first.type === "tuple";
1554
- const members = tuple ? first.components ?? [] : outs;
418
+ const members = tuple ? _nullishCoalesce(first.components, () => ( [])) : outs;
1555
419
  const memberNames = members.map((m, i) => m.name || String(i)).join(", ");
1556
420
  let index;
1557
421
  if (output === void 0) {
@@ -1639,8 +503,8 @@ function validateOptional(abi, name, src, allowed) {
1639
503
  function varFor(token, vars) {
1640
504
  const key = token.slice(1, -1);
1641
505
  const v = vars[key];
1642
- if (v === void 0) throw new MintError("INVALID_CONFIG", `placeholder ${token} has no value here`);
1643
- return typeof v === "string" ? (0, import_viem7.getAddress)(v) : v;
506
+ if (v === void 0) throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `placeholder ${token} has no value here`);
507
+ return typeof v === "string" ? _viem.getAddress.call(void 0, v) : v;
1644
508
  }
1645
509
  function fill(t, p, vars) {
1646
510
  const arr = ARRAY_TYPE.exec(p.type);
@@ -1653,15 +517,15 @@ function fill(t, p, vars) {
1653
517
  if (intBounds(p.type)) return BigInt(t);
1654
518
  return t;
1655
519
  }
1656
- var fillArgs = (args, inputs, vars) => (args ?? []).map((a, i) => fill(a, inputs[i], vars));
520
+ var fillArgs = (args, inputs, vars) => (_nullishCoalesce(args, () => ( []))).map((a, i) => fill(a, inputs[i], vars));
1657
521
  var totalFor = (per, price, quantity) => per === "total" ? price : price * quantity;
1658
522
  function shortMessage(e) {
1659
- return e instanceof import_viem7.BaseError ? e.shortMessage : e instanceof Error ? e.message : String(e);
523
+ return e instanceof _viem.BaseError ? e.shortMessage : e instanceof Error ? e.message : String(e);
1660
524
  }
1661
525
  var abortError = () => new DOMException("The operation was aborted", "AbortError");
1662
- var isAbortError = (e) => e?.name === "AbortError";
526
+ var isAbortError = (e) => _optionalChain([e, 'optionalAccess', _12 => _12.name]) === "AbortError";
1663
527
  function throwIfAborted(ctx) {
1664
- if (ctx.signal?.aborted) throw abortError();
528
+ if (_optionalChain([ctx, 'access', _13 => _13.signal, 'optionalAccess', _14 => _14.aborted])) throw abortError();
1665
529
  }
1666
530
  function io(ctx, start) {
1667
531
  const signal = ctx.signal;
@@ -1674,13 +538,13 @@ function io(ctx, start) {
1674
538
  });
1675
539
  }
1676
540
  function rpcError(e) {
1677
- if (isMintError(e) || isAbortError(e)) throw e;
1678
- throw new MintError("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
541
+ if (_chunkOO6QQT3Mcjs.isMintError.call(void 0, e) || isAbortError(e)) throw e;
542
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
1679
543
  }
1680
544
  function classifyReadError(e, field) {
1681
- if (isMintError(e) || isAbortError(e)) throw e;
1682
- if (e instanceof import_viem7.BaseError && e.walk((x) => x instanceof import_viem7.ContractFunctionRevertedError || x instanceof import_viem7.ContractFunctionZeroDataError)) {
1683
- throw new MintError("INVALID_CONFIG", `${field} read reverted or returned no data: ${e.shortMessage}`, { field, cause: e });
545
+ if (_chunkOO6QQT3Mcjs.isMintError.call(void 0, e) || isAbortError(e)) throw e;
546
+ if (e instanceof _viem.BaseError && e.walk((x) => x instanceof _viem.ContractFunctionRevertedError || x instanceof _viem.ContractFunctionZeroDataError)) {
547
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `${field} read reverted or returned no data: ${e.shortMessage}`, { field, cause: e });
1684
548
  }
1685
549
  return rpcError(e);
1686
550
  }
@@ -1693,8 +557,8 @@ async function readCall(ctx, params, field) {
1693
557
  }
1694
558
  function toBigInt(v, field) {
1695
559
  const n = typeof v === "number" ? BigInt(v) : v;
1696
- if (typeof n !== "bigint") throw new MintError("INVALID_CONFIG", `${field} did not return a number`, { field });
1697
- if (n < 0n) throw new MintError("INVALID_CONFIG", `${field} returned a negative number`, { field });
560
+ if (typeof n !== "bigint") throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `${field} did not return a number`, { field });
561
+ if (n < 0n) throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `${field} returned a negative number`, { field });
1698
562
  return n;
1699
563
  }
1700
564
  async function readField(ctx, config, name, src, vars) {
@@ -1710,60 +574,60 @@ async function readField(ctx, config, name, src, vars) {
1710
574
  }
1711
575
  const value = src.value;
1712
576
  if (typeof value === "bigint") return value;
1713
- throw new MintError("INVALID_CONFIG", `${name} display units are only valid for price`, { field: name });
577
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `${name} display units are only valid for price`, { field: name });
1714
578
  }
1715
579
  function tupleMembers(res, fn, index) {
1716
580
  if (Array.isArray(res)) return res;
1717
- const comps = fn.outputs[0].components ?? [];
581
+ const comps = _nullishCoalesce(fn.outputs[0].components, () => ( []));
1718
582
  const out = [];
1719
- out[index] = res[comps[index]?.name ?? ""];
583
+ out[index] = res[_nullishCoalesce(_optionalChain([comps, 'access', _15 => _15[index], 'optionalAccess', _16 => _16.name]), () => ( ""))];
1720
584
  return out;
1721
585
  }
1722
586
  var optField = (ctx, config, name, src, vars) => src ? readField(ctx, config, name, src, vars) : Promise.resolve(null);
1723
587
  function toSeconds(v, field) {
1724
588
  if (v === null || v === 0n) return null;
1725
- if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new MintError("INVALID_CONFIG", `${field} is too large for a unix timestamp`, { field });
589
+ if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `${field} is too large for a unix timestamp`, { field });
1726
590
  return Number(v);
1727
591
  }
1728
592
  function nativeMeta(ctx) {
1729
- const n = ctx.client.chain?.nativeCurrency;
1730
- return { decimals: n?.decimals ?? 18, symbol: n?.symbol ?? "ETH" };
593
+ const n = _optionalChain([ctx, 'access', _17 => _17.client, 'access', _18 => _18.chain, 'optionalAccess', _19 => _19.nativeCurrency]);
594
+ return { decimals: _nullishCoalesce(_optionalChain([n, 'optionalAccess', _20 => _20.decimals]), () => ( 18)), symbol: _nullishCoalesce(_optionalChain([n, 'optionalAccess', _21 => _21.symbol]), () => ( "ETH")) };
1731
595
  }
1732
- var erc20Of = (config) => config.price.currency === "native" ? null : (0, import_viem7.getAddress)(config.price.currency.address);
596
+ var erc20Of = (config) => config.price.currency === "native" ? null : _viem.getAddress.call(void 0, config.price.currency.address);
1733
597
  async function currencyMeta(ctx, config) {
1734
598
  const token = erc20Of(config);
1735
599
  if (!token) return { token, ...nativeMeta(ctx) };
1736
600
  const field = "price.currency.address";
1737
601
  const [symbol, decimals] = await Promise.all([
1738
- readCall(ctx, { address: token, abi: ERC20_ABI2, functionName: "symbol" }, field),
1739
- readCall(ctx, { address: token, abi: ERC20_ABI2, functionName: "decimals" }, field)
602
+ readCall(ctx, { address: token, abi: ERC20_ABI, functionName: "symbol" }, field),
603
+ readCall(ctx, { address: token, abi: ERC20_ABI, functionName: "decimals" }, field)
1740
604
  ]);
1741
605
  if (typeof symbol !== "string" || typeof decimals !== "number") {
1742
- throw new MintError("INVALID_CONFIG", `${field} ${token} is not an ERC20 (symbol/decimals unreadable)`, { field });
606
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `${field} ${token} is not an ERC20 (symbol/decimals unreadable)`, { field });
1743
607
  }
1744
608
  return { token, decimals, symbol };
1745
609
  }
1746
610
  function parseDisplay(value, decimals) {
1747
- const frac = value.split(".")[1] ?? "";
611
+ const frac = _nullishCoalesce(value.split(".")[1], () => ( ""));
1748
612
  if (frac.length > decimals) {
1749
- throw new MintError("INVALID_CONFIG", `price.value "${value}" has more than ${decimals} decimal places`, { field: "price.value" });
613
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `price.value "${value}" has more than ${decimals} decimal places`, { field: "price.value" });
1750
614
  }
1751
- return (0, import_viem7.parseUnits)(value, decimals);
615
+ return _viem.parseUnits.call(void 0, value, decimals);
1752
616
  }
1753
617
  async function resolvePrice(ctx, config, meta) {
1754
618
  const price = config.price;
1755
619
  if (Object.hasOwn(price, "read")) return readField(ctx, config, "price", price, {});
1756
620
  const value = price.value;
1757
621
  if (typeof value === "bigint") return value;
1758
- return parseDisplay(value, (meta ?? await currencyMeta(ctx, config)).decimals);
622
+ return parseDisplay(value, (await _asyncNullishCoalesce(meta, async () => ( await currencyMeta(ctx, config)))).decimals);
1759
623
  }
1760
- var money3 = (value, decimals, symbol) => ({
624
+ var money = (value, decimals, symbol) => ({
1761
625
  value,
1762
626
  decimals,
1763
627
  symbol,
1764
- formatted: (0, import_viem7.formatUnits)(value, decimals)
628
+ formatted: _viem.formatUnits.call(void 0, value, decimals)
1765
629
  });
1766
- function revertData2(e) {
630
+ function revertData(e) {
1767
631
  for (let cur = e, depth = 0; cur && depth < 12; depth++) {
1768
632
  const d = cur.data;
1769
633
  if (typeof d === "string" && d.startsWith("0x") && d.length >= 10) return d;
@@ -1777,27 +641,27 @@ function revertData2(e) {
1777
641
  }
1778
642
  function describeRevert(abi, data) {
1779
643
  try {
1780
- const d = (0, import_viem7.decodeErrorResult)({ abi, data });
1781
- const args = d.args ?? [];
1782
- if (d.errorName === "Error") return String(args[0] ?? "execution reverted");
1783
- const inputs = d.abiItem?.inputs ?? [];
1784
- const shown = args.map((a, i) => inputs[i]?.name ? `${inputs[i].name}: ${String(a)}` : String(a));
644
+ const d = _viem.decodeErrorResult.call(void 0, { abi, data });
645
+ const args = _nullishCoalesce(d.args, () => ( []));
646
+ if (d.errorName === "Error") return String(_nullishCoalesce(args[0], () => ( "execution reverted")));
647
+ const inputs = _nullishCoalesce(_optionalChain([d, 'access', _22 => _22.abiItem, 'optionalAccess', _23 => _23.inputs]), () => ( []));
648
+ const shown = args.map((a, i) => _optionalChain([inputs, 'access', _24 => _24[i], 'optionalAccess', _25 => _25.name]) ? `${inputs[i].name}: ${String(a)}` : String(a));
1785
649
  return `${d.errorName}(${shown.join(", ")})`;
1786
- } catch {
650
+ } catch (e2) {
1787
651
  return `reverted with unrecognized error ${data.slice(0, 10)}`;
1788
652
  }
1789
653
  }
1790
654
  function toSimulationError(e, abi) {
1791
- if (isMintError(e)) return e;
655
+ if (_chunkOO6QQT3Mcjs.isMintError.call(void 0, e)) return e;
1792
656
  if (isAbortError(e)) throw e;
1793
- if (e instanceof import_viem7.BaseError && e.walk((x) => x instanceof import_viem7.InsufficientFundsError)) {
1794
- return new MintError("INSUFFICIENT_FUNDS", `Payer cannot cover the mint: ${e.shortMessage}`, { cause: e });
657
+ if (e instanceof _viem.BaseError && e.walk((x) => x instanceof _viem.InsufficientFundsError)) {
658
+ return new (0, _chunkOO6QQT3Mcjs.MintError)("INSUFFICIENT_FUNDS", `Payer cannot cover the mint: ${e.shortMessage}`, { cause: e });
1795
659
  }
1796
- const data = revertData2(e);
1797
- if (data) return new MintError("SIMULATION_REVERTED", describeRevert(abi, data), { cause: e });
1798
- const isRevert = e instanceof import_viem7.BaseError && e.walk((x) => x.code === 3 || /execution reverted/i.test(x.message));
1799
- if (isRevert) return new MintError("SIMULATION_REVERTED", shortMessage(e), { cause: e });
1800
- return new MintError("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
660
+ const data = revertData(e);
661
+ if (data) return new (0, _chunkOO6QQT3Mcjs.MintError)("SIMULATION_REVERTED", describeRevert(abi, data), { cause: e });
662
+ const isRevert = e instanceof _viem.BaseError && e.walk((x) => x.code === 3 || /execution reverted/i.test(x.message));
663
+ if (isRevert) return new (0, _chunkOO6QQT3Mcjs.MintError)("SIMULATION_REVERTED", shortMessage(e), { cause: e });
664
+ return new (0, _chunkOO6QQT3Mcjs.MintError)("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
1801
665
  }
1802
666
  async function simulateMint(ctx, config, call) {
1803
667
  try {
@@ -1809,10 +673,10 @@ async function simulateMint(ctx, config, call) {
1809
673
  function encodeMint(config, vars) {
1810
674
  const fn = validateCall(config.abi, config.mint, "mint", "mint", PLACEHOLDERS);
1811
675
  try {
1812
- return (0, import_viem7.encodeFunctionData)({ abi: [fn], functionName: fn.name, args: fillArgs(config.mint.args, fn.inputs, vars) });
676
+ return _viem.encodeFunctionData.call(void 0, { abi: [fn], functionName: fn.name, args: fillArgs(config.mint.args, fn.inputs, vars) });
1813
677
  } catch (e) {
1814
- if (isMintError(e)) throw e;
1815
- throw new MintError("INVALID_CONFIG", `mint.args cannot be encoded for ${signature(fn)}: ${shortMessage(e)}`, { field: "mint.args", cause: e });
678
+ if (_chunkOO6QQT3Mcjs.isMintError.call(void 0, e)) throw e;
679
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("INVALID_CONFIG", `mint.args cannot be encoded for ${signature(fn)}: ${shortMessage(e)}`, { field: "mint.args", cause: e });
1816
680
  }
1817
681
  }
1818
682
  function mintValue(config, token, totalPrice) {
@@ -1840,15 +704,15 @@ async function readDrop(ctx, config) {
1840
704
  const native = nativeMeta(ctx);
1841
705
  return {
1842
706
  chainId: config.chainId,
1843
- unitPrice: money3(price, meta.decimals, meta.symbol),
1844
- unitFee: money3(0n, native.decimals, native.symbol),
1845
- totalMinted: totalMinted ?? 0n,
707
+ unitPrice: money(price, meta.decimals, meta.symbol),
708
+ unitFee: money(0n, native.decimals, native.symbol),
709
+ totalMinted: _nullishCoalesce(totalMinted, () => ( 0n)),
1846
710
  maxSupply: maxSupply === null || maxSupply === 0n ? null : maxSupply,
1847
711
  startTime: toSeconds(start, "startTime"),
1848
712
  endTime: toSeconds(end, "endTime"),
1849
713
  isAllowlist: false,
1850
714
  paymentToken: meta.token,
1851
- pricePer: config.price.per ?? "unit"
715
+ pricePer: _nullishCoalesce(config.price.per, () => ( "unit"))
1852
716
  };
1853
717
  }
1854
718
  async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
@@ -1862,26 +726,26 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
1862
726
  optField(ctx, config, "walletMinted", config.walletMinted, vars),
1863
727
  optField(ctx, config, "walletMax", config.walletMax, vars),
1864
728
  io(ctx, () => ctx.client.getBalance({ address: payer })).catch(rpcError),
1865
- drop.paymentToken ? readCall(ctx, { address: drop.paymentToken, abi: ERC20_ABI2, functionName: "balanceOf", args: [payer] }, "price.currency.address").then(
729
+ drop.paymentToken ? readCall(ctx, { address: drop.paymentToken, abi: ERC20_ABI, functionName: "balanceOf", args: [payer] }, "price.currency.address").then(
1866
730
  (v) => toBigInt(v, "price.currency.address")
1867
731
  ) : Promise.resolve(null)
1868
732
  ]);
1869
733
  const walletMax = rawMax === null || rawMax === 0n ? null : rawMax;
1870
- const remaining = walletMax === null ? null : walletMax > (walletMinted ?? 0n) ? walletMax - (walletMinted ?? 0n) : 0n;
1871
- const maxQuantity = remaining === null ? null : Number(remaining < BigInt(MAX_QUANTITY) ? remaining : BigInt(MAX_QUANTITY));
734
+ const remaining = walletMax === null ? null : walletMax > (_nullishCoalesce(walletMinted, () => ( 0n))) ? walletMax - (_nullishCoalesce(walletMinted, () => ( 0n))) : 0n;
735
+ const maxQuantity = remaining === null ? null : Number(remaining < BigInt(_chunkOO6QQT3Mcjs.MAX_QUANTITY) ? remaining : BigInt(_chunkOO6QQT3Mcjs.MAX_QUANTITY));
1872
736
  let ineligible = null;
1873
737
  let gas = FALLBACK_MINT_GAS;
1874
738
  if (remaining === 0n) {
1875
739
  ineligible = { reason: "WALLET_LIMIT", message: `This wallet has already minted its limit of ${walletMax}.` };
1876
740
  } else if (drop.paymentToken === null && native >= totalPrice) {
1877
- const call = { payer, to: (0, import_viem7.getAddress)(config.address), data: encodeMint(config, vars), value: mintValue(config, null, totalPrice) };
741
+ const call = { payer, to: _viem.getAddress.call(void 0, config.address), data: encodeMint(config, vars), value: mintValue(config, null, totalPrice) };
1878
742
  try {
1879
743
  await simulateMint(ctx, config, call);
1880
744
  gas = await io(ctx, () => ctx.client.estimateGas({ account: payer, to: call.to, data: call.data, value: call.value })).catch((e) => {
1881
745
  throw toSimulationError(e, config.abi);
1882
746
  });
1883
747
  } catch (e) {
1884
- if (!isMintError(e) || e.reason !== "SIMULATION_REVERTED") throw e;
748
+ if (!_chunkOO6QQT3Mcjs.isMintError.call(void 0, e) || e.reason !== "SIMULATION_REVERTED") throw e;
1885
749
  ineligible = { reason: "SIMULATION_REVERTED", message: e.message };
1886
750
  }
1887
751
  }
@@ -1897,15 +761,15 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
1897
761
  gasReserve: gas * gasPrice
1898
762
  };
1899
763
  }
1900
- async function buildPlan2(ctx, attempt, wallet) {
764
+ async function buildPlan(ctx, attempt, wallet) {
1901
765
  void wallet;
1902
766
  const { config, payer, recipient } = attempt;
1903
767
  validateContractConfig(config);
1904
768
  throwIfAborted(ctx);
1905
769
  const qty = BigInt(attempt.quantity);
1906
770
  const unitPrice = await resolvePrice(ctx, config);
1907
- const totalPrice = totalFor(config.price.per ?? "unit", unitPrice, qty);
1908
- const to = (0, import_viem7.getAddress)(config.address);
771
+ const totalPrice = totalFor(_nullishCoalesce(config.price.per, () => ( "unit")), unitPrice, qty);
772
+ const to = _viem.getAddress.call(void 0, config.address);
1909
773
  const token = erc20Of(config);
1910
774
  const mint = {
1911
775
  to,
@@ -1915,7 +779,7 @@ async function buildPlan2(ctx, attempt, wallet) {
1915
779
  let approve = null;
1916
780
  if (token) {
1917
781
  const allowance = toBigInt(
1918
- await readCall(ctx, { address: token, abi: ERC20_ABI2, functionName: "allowance", args: [payer, to] }, "price.currency.address"),
782
+ await readCall(ctx, { address: token, abi: ERC20_ABI, functionName: "allowance", args: [payer, to] }, "price.currency.address"),
1919
783
  "price.currency.address"
1920
784
  );
1921
785
  if (allowance < totalPrice) {
@@ -1923,134 +787,17 @@ async function buildPlan2(ctx, attempt, wallet) {
1923
787
  token,
1924
788
  spender: to,
1925
789
  amount: totalPrice,
1926
- tx: { to: token, data: (0, import_viem7.encodeFunctionData)({ abi: ERC20_ABI2, functionName: "approve", args: [to, totalPrice] }), value: 0n }
790
+ tx: { to: token, data: _viem.encodeFunctionData.call(void 0, { abi: ERC20_ABI, functionName: "approve", args: [to, totalPrice] }), value: 0n }
1927
791
  };
1928
792
  }
1929
793
  }
1930
- return { approve, mint, tokenContract: (0, import_viem7.getAddress)(attempt.tokenContract) };
794
+ return { approve, mint, tokenContract: _viem.getAddress.call(void 0, attempt.tokenContract) };
1931
795
  }
1932
796
  async function simulate(ctx, attempt, plan) {
1933
797
  throwIfAborted(ctx);
1934
798
  await simulateMint(ctx, attempt.config, { payer: attempt.payer, to: plan.mint.to, data: plan.mint.data, value: plan.mint.value });
1935
799
  }
1936
- var contractAdapter = { readDrop, readWallet, buildPlan: buildPlan2, simulate };
1937
-
1938
- // src/core/adapters/receipt.ts
1939
- var import_viem8 = require("viem");
1940
- var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
1941
- var TRANSFER_SINGLE_TOPIC = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62";
1942
- var TRANSFER_BATCH_TOPIC = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb";
1943
- var topicAddress = (t) => t && t.length === 66 ? (0, import_viem8.getAddress)(`0x${t.slice(26)}`) : null;
1944
- function parseMintReceipt(logs, { tokenContract, recipient }) {
1945
- const contract = (0, import_viem8.getAddress)(tokenContract);
1946
- const to = (0, import_viem8.getAddress)(recipient);
1947
- const out = /* @__PURE__ */ new Map();
1948
- const add = (id, amount) => out.set(id, (out.get(id) ?? 0n) + amount);
1949
- for (const log of logs) {
1950
- if ((0, import_viem8.getAddress)(log.address) !== contract) continue;
1951
- const [t0, t1, t2, t3] = log.topics;
1952
- if (t0 === TRANSFER_TOPIC && log.topics.length === 4) {
1953
- if (topicAddress(t1) !== import_viem8.zeroAddress || topicAddress(t2) !== to || !t3) continue;
1954
- add(BigInt(t3), 1n);
1955
- } else if (t0 === TRANSFER_SINGLE_TOPIC && log.topics.length === 4) {
1956
- if (topicAddress(t2) !== import_viem8.zeroAddress || topicAddress(t3) !== to) continue;
1957
- const [id, value] = (0, import_viem8.decodeAbiParameters)([{ type: "uint256" }, { type: "uint256" }], log.data);
1958
- add(id, value);
1959
- } else if (t0 === TRANSFER_BATCH_TOPIC && log.topics.length === 4) {
1960
- if (topicAddress(t2) !== import_viem8.zeroAddress || topicAddress(t3) !== to) continue;
1961
- const [ids, values] = (0, import_viem8.decodeAbiParameters)([{ type: "uint256[]" }, { type: "uint256[]" }], log.data);
1962
- if (ids.length !== values.length) continue;
1963
- ids.forEach((id, i) => add(id, values[i]));
1964
- }
1965
- }
1966
- return [...out].map(([tokenId, amount]) => ({ contract, tokenId, amount }));
1967
- }
1968
-
1969
- // src/core/friendly-errors.ts
1970
- var GENERIC = "Transaction failed. Please try again. If it fails again, please contact support.";
1971
- var REVERTED = "Transaction reverted";
1972
- var record = (value) => value !== null && typeof value === "object" ? value : void 0;
1973
- var text = (value) => typeof value === "string" ? value.toLowerCase() : "";
1974
- function collect(error) {
1975
- const pending = [error];
1976
- const seen = /* @__PURE__ */ new Set();
1977
- const errors = [];
1978
- while (pending.length) {
1979
- const e = record(pending.pop());
1980
- if (!e || seen.has(e)) continue;
1981
- seen.add(e);
1982
- const data = record(e.data);
1983
- errors.push({
1984
- name: e.name,
1985
- code: e.code,
1986
- cancelled: e.cancelled,
1987
- replacement: e.replacement,
1988
- message: [e.message, e.shortMessage, isMintError(e) ? void 0 : e.reason, data?.message].map(text).join("\n")
1989
- });
1990
- pending.push(e.cause, data?.originalError);
1991
- }
1992
- return errors;
1993
- }
1994
- function fundsMessage(errors) {
1995
- const hasText = (phrase) => errors.some((e) => e.message.includes(phrase));
1996
- if (hasText("insufficient funds for gas")) {
1997
- return "Your wallet does not have enough funds to pay for gas fees. Please try again with a different wallet or add more funds to your wallet.";
1998
- }
1999
- if (errors.some((e) => e.name === "InsufficientFundsError" || e.code === "INSUFFICIENT_FUNDS") || hasText("insufficient funds") || hasText("balance too low to proceed")) {
2000
- return "Your wallet does not have enough funds to complete this transaction. Please try again with a different wallet or add more funds to your wallet.";
2001
- }
2002
- return null;
2003
- }
2004
- function friendlyErrorMessage(error) {
2005
- if (isMintError(error)) {
2006
- if (error.reason === "INSUFFICIENT_FUNDS") return fundsMessage(collect(error.cause)) ?? error.message;
2007
- if (error.reason !== "RPC_ERROR" && error.reason !== "SIMULATION_REVERTED") return error.message;
2008
- if (error.reason === "SIMULATION_REVERTED" && error.domain === "relay") return error.message;
2009
- if (error.reason === "SIMULATION_REVERTED" && (error.message === "The token refused the approval." || error.message === "The drop is no longer available for this quantity.")) return error.message;
2010
- }
2011
- const errors = collect(error);
2012
- const hasText = (phrase) => errors.some((e) => e.message.includes(phrase));
2013
- const hasName = (name) => errors.some((e) => e.name === name);
2014
- const hasCode2 = (code2) => errors.some((e) => e.code === code2);
2015
- if (hasName("UserRejectedRequestError") || hasCode2("ACTION_REJECTED") || hasCode2(4001) || hasText("user denied transaction signature") || hasText("userrefusedondevice") || hasText("rejected transaction") || hasText("user rejected") || errors.some((e) => e.message.includes("cancelled") && !e.cancelled)) {
2016
- return "Transaction Rejected";
2017
- }
2018
- if (hasCode2(4902)) return "Network not available in wallet";
2019
- const replaced = errors.find((e) => e.name === "TransactionReplacedError" || e.code === "TRANSACTION_REPLACED");
2020
- if (replaced?.cancelled) return "Transaction was cancelled";
2021
- if (replaced?.replacement) return "Transaction was replaced with a new transaction (usually due to speed up)";
2022
- if (hasText("ledger")) return "Error with Ledger device. Please ensure device is connected and unlocked";
2023
- if (errors.some((e) => e.code === -32002 && e.message.includes("pending"))) {
2024
- return "Transaction already pending in wallet. Please check your wallet";
2025
- }
2026
- if (hasText("invalid amount")) return "Price calculation is incorrect, contact support!";
2027
- const funds = fundsMessage(errors);
2028
- if (funds) return funds;
2029
- if (hasName("NonceTooLowError") || hasName("NonceExhaustedError") || hasText("nonce too low")) {
2030
- return "Transaction nonce is too low. Please try again";
2031
- }
2032
- if (hasName("FeeCapTooLowError") || hasText("max fee per gas less than block base fee")) {
2033
- return "Gas price too low for current network conditions. Please try again";
2034
- }
2035
- if (hasName("TimeoutError") || hasCode2("TIMEOUT") || hasText("timeout")) {
2036
- return "Transaction timed out. Your wallet connection is having issues. Disconnect and reconnect your wallet, then please try again";
2037
- }
2038
- if (hasText("network disconnected")) return "Network connection lost. Please check your internet connection and try again";
2039
- if (hasName("ChainMismatchError") || hasText("wrong network")) return "Wrong network selected. Please switch to the correct network";
2040
- if (hasText("erc20: transfer amount exceeds balance")) {
2041
- return "You do not have the required amount of ERC20 tokens to complete this transaction.";
2042
- }
2043
- if (hasName("EstimateGasExecutionError") || hasCode2("UNPREDICTABLE_GAS_LIMIT") || hasText("cannot estimate gas")) {
2044
- return "Unable to estimate gas for transaction. The transaction may fail. Please try again.";
2045
- }
2046
- if (hasName("ContractFunctionExecutionError") || hasCode2("CALL_EXCEPTION")) {
2047
- return "Transaction failed due to contract execution error";
2048
- }
2049
- if (hasName("ContractFunctionRevertedError") || hasName("ExecutionRevertedError") || hasText("revert")) return REVERTED;
2050
- if (hasName("TransactionExecutionError")) return "Transaction execution failed";
2051
- if (hasCode2("NETWORK_ERROR") || hasName("HttpRequestError") || hasText("network")) return "Network error occurred";
2052
- return isMintError(error) && error.reason === "SIMULATION_REVERTED" ? REVERTED : GENERIC;
2053
- }
800
+ var contractAdapter = { readDrop, readWallet, buildPlan, simulate };
2054
801
 
2055
802
  // src/react/useMint.ts
2056
803
  var REFRESH_MS = 3e4;
@@ -2064,7 +811,7 @@ function configKeyOf(config) {
2064
811
  return JSON.stringify(config, (_k, v) => typeof v === "bigint" ? { __dropkitBigInt: v.toString() } : v);
2065
812
  }
2066
813
  function adapterFor(config) {
2067
- return config.type === "manifold-claim" ? manifoldClaimAdapter : contractAdapter;
814
+ return config.type === "manifold-claim" ? _chunkOO6QQT3Mcjs.manifoldClaimAdapter : contractAdapter;
2068
815
  }
2069
816
  var bridgeEnabled = (config) => config.type === "manifold-claim";
2070
817
  function payChainsOf(config, option) {
@@ -2080,87 +827,71 @@ function routeChainOf(payChains, accountChainId, payChainId) {
2080
827
  var ROUTE_DEBOUNCE_MS = 500;
2081
828
  var symbolOf = (chainId) => {
2082
829
  try {
2083
- return getChain(chainId).nativeCurrency.symbol;
2084
- } catch {
830
+ return _chunkOO6QQT3Mcjs.getChain.call(void 0, chainId).nativeCurrency.symbol;
831
+ } catch (e3) {
2085
832
  return "ETH";
2086
833
  }
2087
834
  };
2088
- var shortOf = (chainId) => ({ chainId, symbol: symbolOf(chainId), name: chainName(chainId) });
835
+ var shortOf = (chainId) => ({ chainId, symbol: symbolOf(chainId), name: _chunkOO6QQT3Mcjs.chainName.call(void 0, chainId) });
2089
836
  function tokenContractOf(config) {
2090
- return config.type === "manifold-claim" ? config.creatorContract : config.tokenContract ?? config.address;
837
+ return config.type === "manifold-claim" ? config.creatorContract : _nullishCoalesce(config.tokenContract, () => ( config.address));
2091
838
  }
2092
839
  function eventAddressOf(config) {
2093
840
  return config.type === "manifold-claim" ? config.creatorContract : config.address;
2094
841
  }
2095
- var isUnsupported = (reason) => UNSUPPORTED_REASONS.includes(reason);
2096
- function isRejection(error) {
2097
- for (let e = error, depth = 0; e && depth < 8; depth++) {
2098
- if (e.code === 4001) return true;
2099
- e = e.cause;
2100
- }
2101
- return false;
2102
- }
2103
- function toReason(e) {
2104
- if (isMintError(e)) return { reason: e.reason, message: friendlyErrorMessage(e) };
2105
- if (isRejection(e)) return { reason: "USER_REJECTED", message: "You rejected the request." };
2106
- for (let cause = e, depth = 0; cause && depth < 8; depth++) {
2107
- if (cause.name === "ChainMismatchError") return { reason: "CHAIN_SWITCH_FAILED", message: "The wallet network changed before the transaction was sent." };
2108
- cause = cause.cause;
2109
- }
2110
- return { reason: "RPC_ERROR", message: friendlyErrorMessage(e) };
2111
- }
842
+ var isUnsupported = (reason) => _chunkOO6QQT3Mcjs.UNSUPPORTED_REASONS.includes(reason);
2112
843
  function errorReasonOf(e) {
2113
- const { reason, message } = toReason(e);
844
+ const { reason, message } = _chunkOO6QQT3Mcjs.toReason.call(void 0, e);
2114
845
  const ok = ["USER_REJECTED", "TX_REVERTED", "RATE_LIMITED", "RPC_ERROR", "CHAIN_SWITCH_FAILED", "ALLOWLIST_UNAVAILABLE"];
2115
846
  return { reason: ok.includes(reason) ? reason : "RPC_ERROR", message };
2116
847
  }
2117
848
  function explorerUrlFor(chainId, hash) {
2118
849
  try {
2119
- const url = getChain(chainId).blockExplorers?.default.url;
850
+ const url = _optionalChain([_chunkOO6QQT3Mcjs.getChain.call(void 0, chainId), 'access', _26 => _26.blockExplorers, 'optionalAccess', _27 => _27.default, 'access', _28 => _28.url]);
2120
851
  return url ? `${url.replace(/\/$/, "")}/tx/${hash}` : null;
2121
- } catch {
852
+ } catch (e4) {
2122
853
  return null;
2123
854
  }
2124
855
  }
2125
856
  var receiptOk = (status) => status === "success" || status === 1 || status === 1n || status === "0x1";
2126
857
  function useMint(options) {
2127
858
  const { config, recipient, quantity: quantityProp, connect } = options;
2128
- const [machine, rawDispatch] = (0, import_react.useReducer)(reducer, void 0, () => initialState({ quantity: quantityProp }));
2129
- const [widgetFail, setWidgetFail] = (0, import_react.useState)(null);
2130
- const [widgetRetry, setWidgetRetry] = (0, import_react.useState)(0);
859
+ const [machine, rawDispatch] = _react.useReducer.call(void 0, _chunkOO6QQT3Mcjs.reducer, void 0, () => _chunkOO6QQT3Mcjs.initialState.call(void 0, { quantity: quantityProp }));
860
+ const [widgetFail, setWidgetFail] = _react.useState.call(void 0, null);
861
+ const [widgetRetry, setWidgetRetry] = _react.useState.call(void 0, 0);
2131
862
  const configKey = configKeyOf(config);
2132
- const mounted = (0, import_react.useRef)(false);
2133
- const stateRef = (0, import_react.useRef)(machine);
2134
- const propsRef = (0, import_react.useRef)(options);
2135
- const lifeRef = (0, import_react.useRef)(null);
2136
- const genRef = (0, import_react.useRef)(0);
2137
- const attemptRef = (0, import_react.useRef)(null);
2138
- const attemptIdRef = (0, import_react.useRef)(0);
2139
- const accountKeyRef = (0, import_react.useRef)(null);
2140
- const connectingRef = (0, import_react.useRef)(false);
2141
- const pendingRefreshRef = (0, import_react.useRef)(false);
2142
- const pendingQuantityRef = (0, import_react.useRef)(null);
2143
- const widgetFailRef = (0, import_react.useRef)(null);
2144
- const widgetLoadRef = (0, import_react.useRef)(null);
2145
- const pushAccountRef = (0, import_react.useRef)(null);
2146
- const autoResumedRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
2147
- const [crossChainInfo, setCrossChainInfo] = (0, import_react.useState)(null);
2148
- (0, import_react.useEffect)(() => {
863
+ const mounted = _react.useRef.call(void 0, false);
864
+ const stateRef = _react.useRef.call(void 0, machine);
865
+ const propsRef = _react.useRef.call(void 0, options);
866
+ const lifeRef = _react.useRef.call(void 0, null);
867
+ const genRef = _react.useRef.call(void 0, 0);
868
+ const attemptRef = _react.useRef.call(void 0, null);
869
+ const attemptIdRef = _react.useRef.call(void 0, 0);
870
+ const accountKeyRef = _react.useRef.call(void 0, null);
871
+ const connectingRef = _react.useRef.call(void 0, false);
872
+ const pendingRefreshRef = _react.useRef.call(void 0, false);
873
+ const pendingQuantityRef = _react.useRef.call(void 0, null);
874
+ const widgetFailRef = _react.useRef.call(void 0, null);
875
+ const widgetLoadRef = _react.useRef.call(void 0, null);
876
+ const pushAccountRef = _react.useRef.call(void 0, null);
877
+ const autoResumedRef = _react.useRef.call(void 0, /* @__PURE__ */ new Set());
878
+ const [crossChainInfo, setCrossChainInfo] = _react.useState.call(void 0, null);
879
+ _react.useEffect.call(void 0, () => {
2149
880
  stateRef.current = machine;
2150
881
  propsRef.current = options;
2151
882
  widgetFailRef.current = widgetFail;
2152
883
  });
2153
- const dispatch = (0, import_react.useCallback)((event) => {
884
+ const dispatch = _react.useCallback.call(void 0, (event) => {
2154
885
  if (!mounted.current) return;
2155
- stateRef.current = reducer(stateRef.current, event);
886
+ stateRef.current = _chunkOO6QQT3Mcjs.reducer.call(void 0, stateRef.current, event);
2156
887
  rawDispatch(event);
2157
888
  }, []);
2158
- const emit = (0, import_react.useCallback)((type, over = {}) => {
889
+ const emit = _react.useCallback.call(void 0, (type, over = {}) => {
2159
890
  const handler = propsRef.current.onEvent;
2160
891
  if (!handler || !mounted.current) return;
2161
- const cfg = attemptRef.current?.config ?? propsRef.current.config;
892
+ const cfg = _nullishCoalesce(_optionalChain([attemptRef, 'access', _29 => _29.current, 'optionalAccess', _30 => _30.config]), () => ( propsRef.current.config));
2162
893
  const s = stateRef.current;
2163
- const originChainId = attemptRef.current?.originChainId ?? (s.route?.kind === "relay" ? s.route.originChainId : s.short?.chainId ?? cfg.chainId);
894
+ const originChainId = _nullishCoalesce(_optionalChain([attemptRef, 'access', _31 => _31.current, 'optionalAccess', _32 => _32.originChainId]), () => ( (_optionalChain([s, 'access', _33 => _33.route, 'optionalAccess', _34 => _34.kind]) === "relay" ? s.route.originChainId : _nullishCoalesce(_optionalChain([s, 'access', _35 => _35.short, 'optionalAccess', _36 => _36.chainId]), () => ( cfg.chainId)))));
2164
895
  const payload = {
2165
896
  type,
2166
897
  state: s.name,
@@ -2174,18 +905,18 @@ function useMint(options) {
2174
905
  };
2175
906
  try {
2176
907
  handler(payload);
2177
- } catch {
908
+ } catch (e5) {
2178
909
  }
2179
910
  }, []);
2180
- const clientFor = (0, import_react.useCallback)((life, cfg) => {
2181
- const rpcUrl = propsRef.current.rpcUrls?.[cfg.chainId];
911
+ const clientFor = _react.useCallback.call(void 0, (life, cfg) => {
912
+ const rpcUrl = _optionalChain([propsRef, 'access', _37 => _37.current, 'access', _38 => _38.rpcUrls, 'optionalAccess', _39 => _39[cfg.chainId]]);
2182
913
  if (!life.client || life.rpcUrl !== rpcUrl) {
2183
914
  life.rpcUrl = rpcUrl;
2184
- life.client = createReadClient({ chainId: cfg.chainId, rpcUrls: propsRef.current.rpcUrls, useBridge: bridgeEnabled(cfg) });
915
+ life.client = _chunkOO6QQT3Mcjs.createReadClient.call(void 0, { chainId: cfg.chainId, rpcUrls: propsRef.current.rpcUrls, useBridge: bridgeEnabled(cfg) });
2185
916
  }
2186
917
  return life.client;
2187
918
  }, []);
2188
- const ctxFor = (0, import_react.useCallback)(
919
+ const ctxFor = _react.useCallback.call(void 0,
2189
920
  (life, cfg) => ({
2190
921
  client: clientFor(life, cfg),
2191
922
  cacheScope: life.cacheScope,
@@ -2194,7 +925,7 @@ function useMint(options) {
2194
925
  }),
2195
926
  [clientFor]
2196
927
  );
2197
- const readDrop2 = (0, import_react.useCallback)(
928
+ const readDrop2 = _react.useCallback.call(void 0,
2198
929
  async (life, gen, cfg) => {
2199
930
  const adapter = adapterFor(cfg);
2200
931
  try {
@@ -2203,18 +934,18 @@ function useMint(options) {
2203
934
  dispatch({ type: "DROP_LOADED", gen, drop, now: Math.max(stateRef.current.now, nowSec()) });
2204
935
  } catch (e) {
2205
936
  if (life.controller.signal.aborted || life.gen !== gen || lifeRef.current !== life) return;
2206
- const { reason, message } = toReason(e);
937
+ const { reason, message } = _chunkOO6QQT3Mcjs.toReason.call(void 0, e);
2207
938
  if (isUnsupported(reason)) dispatch({ type: "DROP_UNSUPPORTED", gen, reason, message });
2208
939
  else dispatch({ type: "READ_FAILED", gen, ...errorReasonOf(e) });
2209
940
  }
2210
941
  },
2211
942
  [ctxFor, dispatch]
2212
943
  );
2213
- const startLifetime = (0, import_react.useCallback)(
944
+ const startLifetime = _react.useCallback.call(void 0,
2214
945
  (key, cfg) => {
2215
946
  const prev = lifeRef.current;
2216
947
  lifeRef.current = null;
2217
- prev?.controller.abort();
948
+ _optionalChain([prev, 'optionalAccess', _40 => _40.controller, 'access', _41 => _41.abort, 'call', _42 => _42()]);
2218
949
  const gen = ++genRef.current;
2219
950
  const life = { key, controller: new AbortController(), cacheScope: {}, gen };
2220
951
  lifeRef.current = life;
@@ -2223,7 +954,7 @@ function useMint(options) {
2223
954
  },
2224
955
  [dispatch, readDrop2]
2225
956
  );
2226
- const refreshNow = (0, import_react.useCallback)(
957
+ const refreshNow = _react.useCallback.call(void 0,
2227
958
  async (kind = "refresh") => {
2228
959
  const life = lifeRef.current;
2229
960
  if (!life || !mounted.current) return;
@@ -2238,12 +969,12 @@ function useMint(options) {
2238
969
  },
2239
970
  [dispatch, readDrop2]
2240
971
  );
2241
- const refresh = (0, import_react.useCallback)(() => refreshNow("refresh"), [refreshNow]);
2242
- const isBusy = (0, import_react.useCallback)(
2243
- () => connectingRef.current || attemptRef.current !== null || stateRef.current.attempt !== null || IN_FLIGHT_STATES.includes(stateRef.current.name),
972
+ const refresh = _react.useCallback.call(void 0, () => refreshNow("refresh"), [refreshNow]);
973
+ const isBusy = _react.useCallback.call(void 0,
974
+ () => connectingRef.current || attemptRef.current !== null || stateRef.current.attempt !== null || _chunkOO6QQT3Mcjs.IN_FLIGHT_STATES.includes(stateRef.current.name),
2244
975
  []
2245
976
  );
2246
- const executeAttempt = (0, import_react.useCallback)(
977
+ const executeAttempt = _react.useCallback.call(void 0,
2247
978
  async (attempt, walletRead, life, account2) => {
2248
979
  const cfg = attempt.config;
2249
980
  const adapter = adapterFor(cfg);
@@ -2256,20 +987,20 @@ function useMint(options) {
2256
987
  };
2257
988
  const assertPayer = () => {
2258
989
  assertActive();
2259
- const live = getAccount();
990
+ const live = _chunkOO6QQT3Mcjs.getAccount.call(void 0, );
2260
991
  if (!live || live.address.toLowerCase() !== attempt.payer.toLowerCase()) {
2261
- throw new MintError("USER_REJECTED", "The connected wallet changed before the transaction was sent.");
992
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("USER_REJECTED", "The connected wallet changed before the transaction was sent.");
2262
993
  }
2263
994
  };
2264
995
  let wallet2 = null;
2265
996
  const walletFor = () => {
2266
- if (!wallet2) wallet2 = getWalletClient(attempt.chainId);
997
+ if (!wallet2) wallet2 = _chunkOO6QQT3Mcjs.getWalletClient.call(void 0, attempt.chainId);
2267
998
  return wallet2;
2268
999
  };
2269
1000
  const submit = async (tx) => {
2270
1001
  assertPayer();
2271
1002
  const w = walletFor();
2272
- return w.sendTransaction({ account: attempt.payer, to: tx.to, data: tx.data, value: tx.value, chain: getChain(attempt.chainId) });
1003
+ return w.sendTransaction({ account: attempt.payer, to: tx.to, data: tx.data, value: tx.value, chain: _chunkOO6QQT3Mcjs.getChain.call(void 0, attempt.chainId) });
2273
1004
  };
2274
1005
  const waitReceipt = async (hash2) => {
2275
1006
  let cancelled = false;
@@ -2286,19 +1017,19 @@ function useMint(options) {
2286
1017
  receipt2 = await client.waitForTransactionReceipt(params);
2287
1018
  } catch (e) {
2288
1019
  assertActive();
2289
- if (cancelled) throw new MintError("USER_REJECTED", "The transaction was cancelled or replaced with a different transaction.");
1020
+ if (cancelled) throw new (0, _chunkOO6QQT3Mcjs.MintError)("USER_REJECTED", "The transaction was cancelled or replaced with a different transaction.");
2290
1021
  if (await walletFor().getChainId() !== attempt.chainId) throw e;
2291
1022
  assertActive();
2292
- receipt2 = await walletFor().extend(import_viem9.publicActions).waitForTransactionReceipt(params);
1023
+ receipt2 = await walletFor().extend(_viem.publicActions).waitForTransactionReceipt(params);
2293
1024
  }
2294
1025
  assertActive();
2295
- if (cancelled) throw new MintError("USER_REJECTED", "The transaction was cancelled or replaced with a different transaction.");
1026
+ if (cancelled) throw new (0, _chunkOO6QQT3Mcjs.MintError)("USER_REJECTED", "The transaction was cancelled or replaced with a different transaction.");
2296
1027
  return receipt2;
2297
1028
  };
2298
1029
  assertPayer();
2299
1030
  if (account2.chainId !== attempt.chainId) {
2300
1031
  dispatch({ type: "SWITCHING_CHAIN", attemptId: attempt.attemptId });
2301
- await switchToChain(attempt.chainId);
1032
+ await _chunkOO6QQT3Mcjs.switchToChain.call(void 0, attempt.chainId);
2302
1033
  }
2303
1034
  assertPayer();
2304
1035
  let plan = await adapter.buildPlan(ctx, attempt, walletRead);
@@ -2308,13 +1039,13 @@ function useMint(options) {
2308
1039
  try {
2309
1040
  const simulated = await client.call({ account: attempt.payer, to: a.tx.to, data: a.tx.data, value: a.tx.value });
2310
1041
  if (simulated.data && simulated.data !== "0x" && BigInt(simulated.data) === 0n) {
2311
- throw new MintError("SIMULATION_REVERTED", "The token refused the approval.");
1042
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("SIMULATION_REVERTED", "The token refused the approval.");
2312
1043
  }
2313
1044
  } catch (e) {
2314
- if (isMintError(e)) throw e;
2315
- const reverted = e instanceof import_viem9.BaseError ? e.walk((cause) => cause instanceof import_viem9.ExecutionRevertedError) : null;
2316
- if (reverted instanceof import_viem9.ExecutionRevertedError) {
2317
- throw new MintError("SIMULATION_REVERTED", reverted.shortMessage);
1045
+ if (_chunkOO6QQT3Mcjs.isMintError.call(void 0, e)) throw e;
1046
+ const reverted = e instanceof _viem.BaseError ? e.walk((cause) => cause instanceof _viem.ExecutionRevertedError) : null;
1047
+ if (reverted instanceof _viem.ExecutionRevertedError) {
1048
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("SIMULATION_REVERTED", reverted.shortMessage);
2318
1049
  }
2319
1050
  throw e;
2320
1051
  }
@@ -2326,7 +1057,7 @@ function useMint(options) {
2326
1057
  const approveReceipt = await waitReceipt(approveHash);
2327
1058
  assertActive();
2328
1059
  if (!receiptOk(approveReceipt.status)) {
2329
- throw new MintError("TX_REVERTED", `The approval transaction reverted (${approveHash}).`);
1060
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("TX_REVERTED", `The approval transaction reverted (${approveHash}).`);
2330
1061
  }
2331
1062
  const freshDrop = await adapter.readDrop(ctx, cfg);
2332
1063
  assertActive();
@@ -2337,11 +1068,11 @@ function useMint(options) {
2337
1068
  drop: freshDrop
2338
1069
  });
2339
1070
  assertPayer();
2340
- let checked = reducer(initialState({ quantity: attempt.quantity }), { type: "ACCOUNT_CHANGED", account: account2 });
2341
- checked = reducer(checked, { type: "DROP_LOADED", gen: checked.readGen, drop: freshDrop, now: nowSec() });
2342
- checked = reducer(checked, { type: "WALLET_LOADED", gen: checked.walletGen, read: freshWallet });
2343
- if (checked.name !== "live" || (selectMaxQuantity(checked) ?? 0) < attempt.quantity) {
2344
- throw new MintError(checked.reason ?? "SIMULATION_REVERTED", checked.message ?? "The drop is no longer available for this quantity.");
1071
+ let checked = _chunkOO6QQT3Mcjs.reducer.call(void 0, _chunkOO6QQT3Mcjs.initialState.call(void 0, { quantity: attempt.quantity }), { type: "ACCOUNT_CHANGED", account: account2 });
1072
+ checked = _chunkOO6QQT3Mcjs.reducer.call(void 0, checked, { type: "DROP_LOADED", gen: checked.readGen, drop: freshDrop, now: nowSec() });
1073
+ checked = _chunkOO6QQT3Mcjs.reducer.call(void 0, checked, { type: "WALLET_LOADED", gen: checked.walletGen, read: freshWallet });
1074
+ if (checked.name !== "live" || (_nullishCoalesce(_chunkOO6QQT3Mcjs.selectMaxQuantity.call(void 0, checked), () => ( 0))) < attempt.quantity) {
1075
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)(_nullishCoalesce(checked.reason, () => ( "SIMULATION_REVERTED")), _nullishCoalesce(checked.message, () => ( "The drop is no longer available for this quantity.")));
2345
1076
  }
2346
1077
  plan = await adapter.buildPlan(ctx, attempt, freshWallet);
2347
1078
  assertPayer();
@@ -2355,12 +1086,12 @@ function useMint(options) {
2355
1086
  emit("tx-submitted", { state: "confirming", reason: null, txHash: hash, quantity: attempt.quantity, chainId: attempt.chainId });
2356
1087
  const receipt = await waitReceipt(hash);
2357
1088
  assertActive();
2358
- const confirmedHash = receipt.transactionHash ?? hash;
1089
+ const confirmedHash = _nullishCoalesce(receipt.transactionHash, () => ( hash));
2359
1090
  if (!receiptOk(receipt.status)) {
2360
- throw new MintError("TX_REVERTED", `The mint transaction reverted (${confirmedHash}).`);
1091
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("TX_REVERTED", `The mint transaction reverted (${confirmedHash}).`);
2361
1092
  }
2362
- const tokens = parseMintReceipt(receipt.logs ?? [], {
2363
- tokenContract: plan.tokenContract ?? attempt.tokenContract,
1093
+ const tokens = _chunkOO6QQT3Mcjs.parseMintReceipt.call(void 0, _nullishCoalesce(receipt.logs, () => ( [])), {
1094
+ tokenContract: _nullishCoalesce(plan.tokenContract, () => ( attempt.tokenContract)),
2364
1095
  recipient: attempt.recipient
2365
1096
  });
2366
1097
  const result = { txHash: confirmedHash, explorerUrl: explorerUrlFor(attempt.chainId, confirmedHash), tokens };
@@ -2369,7 +1100,7 @@ function useMint(options) {
2369
1100
  },
2370
1101
  [clientFor, ctxFor, dispatch, emit]
2371
1102
  );
2372
- const finishRelay = (0, import_react.useCallback)(
1103
+ const finishRelay = _react.useCallback.call(void 0,
2373
1104
  async (attempt, out, life) => {
2374
1105
  const cfg = attempt.config;
2375
1106
  const client = clientFor(life, cfg);
@@ -2380,34 +1111,34 @@ function useMint(options) {
2380
1111
  };
2381
1112
  const outcome = await pollUntilTerminal({ testnet: out.testnet, requestId: out.requestId, signal: life.controller.signal, assertActive });
2382
1113
  assertActive();
2383
- const where = chainName(out.originChainId);
1114
+ const where = _chunkOO6QQT3Mcjs.chainName.call(void 0, out.originChainId);
2384
1115
  if (outcome.kind === "timeout") {
2385
- throw new MintError("BRIDGE_TIMEOUT", "The bridge is still processing. Your mint may still complete.");
1116
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_TIMEOUT", "The bridge is still processing. Your mint may still complete.");
2386
1117
  }
2387
1118
  const key = outstandingKey(attempt.config, attempt.payer);
2388
1119
  const { status } = outcome;
2389
1120
  if (status.status !== "success") clearOutstanding(key);
2390
1121
  if (status.status === "refund") {
2391
- throw new MintError("BRIDGE_REFUNDED", `Relay could not complete the mint and is refunding your payment. Relay request ${out.requestId}.`);
1122
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_REFUNDED", `Relay could not complete the mint and is refunding your payment. Relay request ${out.requestId}.`);
2392
1123
  }
2393
1124
  if (status.status === "failure") {
2394
1125
  const why = status.failReason ? ` (${status.failReason})` : "";
2395
1126
  const noRefund = status.refundFailReason ? ` No automatic refund was sent. Contact support with Relay request ${out.requestId}.` : "";
2396
- throw new MintError("BRIDGE_FAILED", `Relay could not complete the mint paid on ${where}${why}.${noRefund}`);
1127
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_FAILED", `Relay could not complete the mint paid on ${where}${why}.${noRefund}`);
2397
1128
  }
2398
- const fillHash = status.txHashes[0] ?? null;
1129
+ const fillHash = _nullishCoalesce(status.txHashes[0], () => ( null));
2399
1130
  let tokens = [];
2400
1131
  if (fillHash) {
2401
1132
  try {
2402
1133
  const receipt = await client.waitForTransactionReceipt({ hash: fillHash, confirmations: 1, timeout: 6e4 });
2403
1134
  if (receiptOk(receipt.status)) {
2404
- tokens = parseMintReceipt(receipt.logs ?? [], { tokenContract: attempt.tokenContract, recipient: attempt.recipient });
1135
+ tokens = _chunkOO6QQT3Mcjs.parseMintReceipt.call(void 0, _nullishCoalesce(receipt.logs, () => ( [])), { tokenContract: attempt.tokenContract, recipient: attempt.recipient });
2405
1136
  }
2406
- } catch {
1137
+ } catch (e6) {
2407
1138
  }
2408
1139
  assertActive();
2409
1140
  }
2410
- const txHash = fillHash ?? out.originTxHash;
1141
+ const txHash = _nullishCoalesce(fillHash, () => ( out.originTxHash));
2411
1142
  const result = {
2412
1143
  txHash,
2413
1144
  explorerUrl: explorerUrlFor(fillHash ? cfg.chainId : out.originChainId, txHash),
@@ -2420,7 +1151,7 @@ function useMint(options) {
2420
1151
  },
2421
1152
  [clientFor, dispatch, emit]
2422
1153
  );
2423
- const executeRelayAttempt = (0, import_react.useCallback)(
1154
+ const executeRelayAttempt = _react.useCallback.call(void 0,
2424
1155
  async (attempt, walletRead, life, account2) => {
2425
1156
  const cfg = attempt.config;
2426
1157
  const adapter = adapterFor(cfg);
@@ -2431,19 +1162,19 @@ function useMint(options) {
2431
1162
  if (!mounted.current || life.controller.signal.aborted || lifeRef.current !== life || attemptRef.current !== attempt) {
2432
1163
  throw new DOMException("Mint attempt cancelled", "AbortError");
2433
1164
  }
2434
- const live = getAccount();
1165
+ const live = _chunkOO6QQT3Mcjs.getAccount.call(void 0, );
2435
1166
  if (!live || live.address.toLowerCase() !== attempt.payer.toLowerCase()) {
2436
- throw new MintError("USER_REJECTED", "The connected wallet changed before the transaction was sent.");
1167
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("USER_REJECTED", "The connected wallet changed before the transaction was sent.");
2437
1168
  }
2438
1169
  };
2439
1170
  assertPayer();
2440
1171
  if (account2.chainId !== origin) {
2441
1172
  dispatch({ type: "SWITCHING_CHAIN", attemptId: attempt.attemptId });
2442
- await switchToChain(origin);
1173
+ await _chunkOO6QQT3Mcjs.switchToChain.call(void 0, origin);
2443
1174
  }
2444
1175
  assertPayer();
2445
1176
  const plan = await adapter.buildPlan(ctx, attempt, walletRead);
2446
- if (plan.approve) throw new MintError("BRIDGE_UNAVAILABLE", "Cross-chain mint supports native-priced drops only.");
1177
+ if (plan.approve) throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_UNAVAILABLE", "Cross-chain mint supports native-priced drops only.");
2447
1178
  assertPayer();
2448
1179
  const quote = await getQuote({
2449
1180
  testnet,
@@ -2456,18 +1187,18 @@ function useMint(options) {
2456
1187
  signal: life.controller.signal
2457
1188
  });
2458
1189
  assertPayer();
2459
- const balance = await getConnectedBalance(attempt.payer, origin);
1190
+ const balance = await _chunkOO6QQT3Mcjs.getConnectedBalance.call(void 0, attempt.payer, origin);
2460
1191
  if (balance < quote.amountIn.value + quote.originGas.value) {
2461
1192
  const s = shortOf(origin);
2462
- throw new MintError("INSUFFICIENT_FUNDS", `Not enough ${s.symbol} on ${s.name}. Pick another network to pay from.`);
1193
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("INSUFFICIENT_FUNDS", `Not enough ${s.symbol} on ${s.name}. Pick another network to pay from.`);
2463
1194
  }
2464
1195
  assertPayer();
2465
1196
  const item = quote.items[0];
2466
1197
  const key = outstandingKey(cfg, attempt.payer);
2467
- const wallet2 = getWalletClient(origin);
1198
+ const wallet2 = _chunkOO6QQT3Mcjs.getWalletClient.call(void 0, origin);
2468
1199
  assertPayer();
2469
1200
  if (!claimDeposit(key)) {
2470
- throw new MintError("BRIDGE_UNAVAILABLE", "A cross-chain payment for this drop is already in progress. Try again once it finishes.");
1201
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("BRIDGE_UNAVAILABLE", "A cross-chain payment for this drop is already in progress. Try again once it finishes.");
2471
1202
  }
2472
1203
  let out;
2473
1204
  try {
@@ -2479,7 +1210,7 @@ function useMint(options) {
2479
1210
  data: item.data,
2480
1211
  value: item.value,
2481
1212
  ...item.gas !== null && item.gas > 0n ? { gas: item.gas } : {},
2482
- chain: getChain(origin)
1213
+ chain: _chunkOO6QQT3Mcjs.getChain.call(void 0, origin)
2483
1214
  });
2484
1215
  out = { requestId: quote.requestId, testnet, originChainId: origin, originTxHash: originTxHash2, attempt };
2485
1216
  setOutstanding(key, out);
@@ -2490,16 +1221,16 @@ function useMint(options) {
2490
1221
  autoResumedRef.current.add(key);
2491
1222
  dispatch({ type: "TX_SUBMITTED", attemptId: attempt.attemptId });
2492
1223
  emit("tx-submitted", { state: "confirming", reason: null, txHash: originTxHash, quantity: attempt.quantity, chainId: cfg.chainId });
2493
- const deposit = await waitForDeposit(origin, originTxHash);
1224
+ const deposit = await _chunkOO6QQT3Mcjs.waitForDeposit.call(void 0, origin, originTxHash);
2494
1225
  if (deposit === "reverted") {
2495
1226
  clearOutstanding(key);
2496
- throw new MintError("TX_REVERTED", `The payment transaction reverted (${originTxHash}).`);
1227
+ throw new (0, _chunkOO6QQT3Mcjs.MintError)("TX_REVERTED", `The payment transaction reverted (${originTxHash}).`);
2497
1228
  }
2498
1229
  await finishRelay(attempt, out, life);
2499
1230
  },
2500
1231
  [ctxFor, dispatch, emit, finishRelay]
2501
1232
  );
2502
- const resumeOutstanding = (0, import_react.useCallback)(
1233
+ const resumeOutstanding = _react.useCallback.call(void 0,
2503
1234
  async (out, life) => {
2504
1235
  const attempt = Object.freeze({ ...out.attempt, attemptId: ++attemptIdRef.current });
2505
1236
  attemptRef.current = attempt;
@@ -2510,7 +1241,7 @@ function useMint(options) {
2510
1241
  await finishRelay(attempt, out, life);
2511
1242
  } catch (e) {
2512
1243
  if (!mounted.current || life.controller.signal.aborted || lifeRef.current !== life) return;
2513
- const { reason, message } = toReason(e);
1244
+ const { reason, message } = _chunkOO6QQT3Mcjs.toReason.call(void 0, e);
2514
1245
  dispatch({ type: "ATTEMPT_FAILED", attemptId: attempt.attemptId, reason, message });
2515
1246
  emit("error", { quantity: attempt.quantity, chainId: attempt.chainId });
2516
1247
  } finally {
@@ -2519,7 +1250,7 @@ function useMint(options) {
2519
1250
  },
2520
1251
  [dispatch, emit, finishRelay]
2521
1252
  );
2522
- const runMint = (0, import_react.useCallback)(async () => {
1253
+ const runMint = _react.useCallback.call(void 0, async () => {
2523
1254
  if (!mounted.current) return;
2524
1255
  if (attemptRef.current !== null) return;
2525
1256
  if (widgetFailRef.current) {
@@ -2531,31 +1262,31 @@ function useMint(options) {
2531
1262
  return;
2532
1263
  }
2533
1264
  const s = stateRef.current;
2534
- if (!canAct(s) || s.attempt !== null) return;
1265
+ if (!_chunkOO6QQT3Mcjs.canAct.call(void 0, s) || s.attempt !== null) return;
2535
1266
  if (s.name === "disconnected") {
2536
1267
  if (connectingRef.current) return;
2537
1268
  connectingRef.current = true;
2538
1269
  dispatch({ type: "CONNECT_STARTED" });
2539
1270
  const connectLife = lifeRef.current;
2540
- const active = () => mounted.current && lifeRef.current === connectLife && !connectLife?.controller.signal.aborted;
1271
+ const active = () => mounted.current && lifeRef.current === connectLife && !_optionalChain([connectLife, 'optionalAccess', _43 => _43.controller, 'access', _44 => _44.signal, 'access', _45 => _45.aborted]);
2541
1272
  try {
2542
1273
  await widgetLoadRef.current;
2543
1274
  if (!active()) return;
2544
- const outcome = await openConnectModal();
1275
+ const outcome = await _chunkOO6QQT3Mcjs.openConnectModal.call(void 0, );
2545
1276
  if (!active()) return;
2546
1277
  connectingRef.current = false;
2547
1278
  if (outcome === "connected") {
2548
1279
  accountKeyRef.current = null;
2549
- pushAccountRef.current?.(getAccount());
1280
+ _optionalChain([pushAccountRef, 'access', _46 => _46.current, 'optionalCall', _47 => _47(_chunkOO6QQT3Mcjs.getAccount.call(void 0, ))]);
2550
1281
  } else dispatch({ type: "CONNECT_DISMISSED" });
2551
- } catch {
1282
+ } catch (e7) {
2552
1283
  if (active()) dispatch({ type: "CONNECT_DISMISSED" });
2553
1284
  } finally {
2554
1285
  connectingRef.current = false;
2555
1286
  }
2556
1287
  return;
2557
1288
  }
2558
- const payer = s.account?.address;
1289
+ const payer = _optionalChain([s, 'access', _48 => _48.account, 'optionalAccess', _49 => _49.address]);
2559
1290
  const out = payer ? getOutstanding(outstandingKey(propsRef.current.config, payer)) : null;
2560
1291
  if (out && lifeRef.current) {
2561
1292
  await resumeOutstanding(out, lifeRef.current);
@@ -2576,12 +1307,12 @@ function useMint(options) {
2576
1307
  const life = lifeRef.current;
2577
1308
  if (!account2 || !walletRead || !life) return;
2578
1309
  const cfg = propsRef.current.config;
2579
- const relayRoute = s.route?.kind === "relay" ? s.route : null;
1310
+ const relayRoute = _optionalChain([s, 'access', _50 => _50.route, 'optionalAccess', _51 => _51.kind]) === "relay" ? s.route : null;
2580
1311
  const attempt = Object.freeze({
2581
1312
  attemptId: ++attemptIdRef.current,
2582
1313
  config: structuredClone(cfg),
2583
1314
  payer: account2.address,
2584
- recipient: propsRef.current.recipient ?? account2.address,
1315
+ recipient: _nullishCoalesce(propsRef.current.recipient, () => ( account2.address)),
2585
1316
  quantity: s.quantity,
2586
1317
  chainId: cfg.chainId,
2587
1318
  tokenContract: tokenContractOf(cfg),
@@ -2595,51 +1326,51 @@ function useMint(options) {
2595
1326
  else await executeAttempt(attempt, walletRead, life, account2);
2596
1327
  } catch (e) {
2597
1328
  if (!mounted.current || life.controller.signal.aborted || lifeRef.current !== life) return;
2598
- const { reason, message } = toReason(e);
1329
+ const { reason, message } = _chunkOO6QQT3Mcjs.toReason.call(void 0, e);
2599
1330
  dispatch({ type: "ATTEMPT_FAILED", attemptId: attempt.attemptId, reason, message });
2600
1331
  emit("error", { quantity: attempt.quantity, chainId: attempt.chainId });
2601
1332
  } finally {
2602
1333
  attemptRef.current = null;
2603
1334
  }
2604
1335
  }, [dispatch, emit, readDrop2, executeAttempt, executeRelayAttempt, resumeOutstanding, refreshNow]);
2605
- const mint = (0, import_react.useCallback)(() => {
1336
+ const mint = _react.useCallback.call(void 0, () => {
2606
1337
  void runMint();
2607
1338
  }, [runMint]);
2608
- (0, import_react.useEffect)(() => {
1339
+ _react.useEffect.call(void 0, () => {
2609
1340
  mounted.current = true;
2610
1341
  return () => {
2611
1342
  mounted.current = false;
2612
- lifeRef.current?.controller.abort();
1343
+ _optionalChain([lifeRef, 'access', _52 => _52.current, 'optionalAccess', _53 => _53.controller, 'access', _54 => _54.abort, 'call', _55 => _55()]);
2613
1344
  lifeRef.current = null;
2614
1345
  };
2615
1346
  }, []);
2616
- (0, import_react.useEffect)(() => {
1347
+ _react.useEffect.call(void 0, () => {
2617
1348
  const push = (a) => {
2618
- const key = a ? `${a.address.toLowerCase()}:${a.chainId}:${(propsRef.current.recipient ?? "").toLowerCase()}` : "null";
1349
+ const key = a ? `${a.address.toLowerCase()}:${a.chainId}:${(_nullishCoalesce(propsRef.current.recipient, () => ( ""))).toLowerCase()}` : "null";
2619
1350
  if (key === accountKeyRef.current) return;
2620
1351
  accountKeyRef.current = key;
2621
1352
  if (attemptRef.current || stateRef.current.attempt) pendingRefreshRef.current = true;
2622
1353
  dispatch({ type: "ACCOUNT_CHANGED", account: a });
2623
1354
  };
2624
1355
  pushAccountRef.current = push;
2625
- push(getAccount());
2626
- const unsubscribe = subscribeAccount(push);
1356
+ push(_chunkOO6QQT3Mcjs.getAccount.call(void 0, ));
1357
+ const unsubscribe = _chunkOO6QQT3Mcjs.subscribeAccount.call(void 0, push);
2627
1358
  return () => {
2628
1359
  unsubscribe();
2629
1360
  };
2630
1361
  }, [dispatch]);
2631
- const recipientRef = (0, import_react.useRef)(recipient);
2632
- (0, import_react.useEffect)(() => {
1362
+ const recipientRef = _react.useRef.call(void 0, recipient);
1363
+ _react.useEffect.call(void 0, () => {
2633
1364
  if (isBusy() || recipientRef.current === recipient) return;
2634
1365
  recipientRef.current = recipient;
2635
1366
  accountKeyRef.current = null;
2636
- pushAccountRef.current?.(getAccount());
1367
+ _optionalChain([pushAccountRef, 'access', _56 => _56.current, 'optionalCall', _57 => _57(_chunkOO6QQT3Mcjs.getAccount.call(void 0, ))]);
2637
1368
  }, [recipient, machine.attempt, isBusy]);
2638
- const projectId = connect?.walletConnectProjectId;
1369
+ const projectId = _optionalChain([connect, 'optionalAccess', _58 => _58.walletConnectProjectId]);
2639
1370
  const widgetChains = [config.chainId, ...payChainsOf(config, options.crossChain).filter((id) => id !== config.chainId)].join(",");
2640
- (0, import_react.useEffect)(() => {
1371
+ _react.useEffect.call(void 0, () => {
2641
1372
  let alive = true;
2642
- const loading = loadConnectWidget({ chainIds: widgetChains.split(",").map(Number), ...projectId ? { walletConnectProjectId: projectId } : {} });
1373
+ const loading = _chunkOO6QQT3Mcjs.loadConnectWidget.call(void 0, { chainIds: widgetChains.split(",").map(Number), ...projectId ? { walletConnectProjectId: projectId } : {} });
2643
1374
  widgetLoadRef.current = loading;
2644
1375
  loading.then(
2645
1376
  () => {
@@ -2647,7 +1378,7 @@ function useMint(options) {
2647
1378
  },
2648
1379
  (e) => {
2649
1380
  if (!alive) return;
2650
- const { reason, message } = toReason(e);
1381
+ const { reason, message } = _chunkOO6QQT3Mcjs.toReason.call(void 0, e);
2651
1382
  setWidgetFail({ reason, message });
2652
1383
  }
2653
1384
  );
@@ -2655,7 +1386,7 @@ function useMint(options) {
2655
1386
  alive = false;
2656
1387
  };
2657
1388
  }, [widgetChains, projectId, widgetRetry]);
2658
- (0, import_react.useEffect)(() => {
1389
+ _react.useEffect.call(void 0, () => {
2659
1390
  if (!mounted.current) return;
2660
1391
  if (isBusy()) return;
2661
1392
  if (pendingQuantityRef.current !== null) {
@@ -2663,16 +1394,16 @@ function useMint(options) {
2663
1394
  pendingQuantityRef.current = null;
2664
1395
  dispatch({ type: "SET_QUANTITY", quantity });
2665
1396
  }
2666
- if (lifeRef.current?.key !== configKey) {
1397
+ if (_optionalChain([lifeRef, 'access', _59 => _59.current, 'optionalAccess', _60 => _60.key]) !== configKey) {
2667
1398
  pendingRefreshRef.current = false;
2668
1399
  startLifetime(configKey, config);
2669
- } else if (pendingRefreshRef.current || lifeRef.current.rpcUrl !== options.rpcUrls?.[config.chainId]) {
1400
+ } else if (pendingRefreshRef.current || lifeRef.current.rpcUrl !== _optionalChain([options, 'access', _61 => _61.rpcUrls, 'optionalAccess', _62 => _62[config.chainId]])) {
2670
1401
  pendingRefreshRef.current = false;
2671
1402
  void refreshNow();
2672
1403
  }
2673
1404
  });
2674
1405
  const resumeKey = machine.account ? outstandingKey(config, machine.account.address) : null;
2675
- (0, import_react.useEffect)(() => {
1406
+ _react.useEffect.call(void 0, () => {
2676
1407
  if (!resumeKey || autoResumedRef.current.has(resumeKey) || attemptRef.current !== null || isBusy()) return;
2677
1408
  const out = getOutstanding(resumeKey);
2678
1409
  const life = lifeRef.current;
@@ -2680,15 +1411,15 @@ function useMint(options) {
2680
1411
  autoResumedRef.current.add(resumeKey);
2681
1412
  void resumeOutstanding(out, life);
2682
1413
  }, [resumeKey, machine.attempt, isBusy, resumeOutstanding]);
2683
- const routeOptionsKey = `${String(options.payChainId ?? "")}|${JSON.stringify(options.crossChain ?? null)}`;
2684
- const previousRouteOptions = (0, import_react.useRef)(routeOptionsKey);
2685
- (0, import_react.useEffect)(() => {
1414
+ const routeOptionsKey = `${String(_nullishCoalesce(options.payChainId, () => ( "")))}|${JSON.stringify(_nullishCoalesce(options.crossChain, () => ( null)))}`;
1415
+ const previousRouteOptions = _react.useRef.call(void 0, routeOptionsKey);
1416
+ _react.useEffect.call(void 0, () => {
2686
1417
  if (previousRouteOptions.current === routeOptionsKey || isBusy()) return;
2687
1418
  previousRouteOptions.current = routeOptionsKey;
2688
1419
  if (stateRef.current.account) dispatch({ type: "ACCOUNT_CHANGED", account: stateRef.current.account });
2689
1420
  }, [routeOptionsKey, machine.attempt, dispatch, isBusy]);
2690
- const previousQuantity = (0, import_react.useRef)(machine.quantity);
2691
- (0, import_react.useEffect)(() => {
1421
+ const previousQuantity = _react.useRef.call(void 0, machine.quantity);
1422
+ _react.useEffect.call(void 0, () => {
2692
1423
  if (previousQuantity.current === machine.quantity || isBusy()) return;
2693
1424
  previousQuantity.current = machine.quantity;
2694
1425
  if (stateRef.current.walletRead) dispatch({ type: "ACCOUNT_CHANGED", account: stateRef.current.account });
@@ -2696,11 +1427,11 @@ function useMint(options) {
2696
1427
  const loadedDrop = machine.drop;
2697
1428
  const walletGen = machine.walletGen;
2698
1429
  const account = machine.account;
2699
- const lastWalletRead = (0, import_react.useRef)(null);
2700
- (0, import_react.useEffect)(() => {
1430
+ const lastWalletRead = _react.useRef.call(void 0, null);
1431
+ _react.useEffect.call(void 0, () => {
2701
1432
  if (!account || !loadedDrop || isBusy()) return;
2702
1433
  const previous = lastWalletRead.current;
2703
- if (stateRef.current.blocked && previous?.drop === loadedDrop && previous.gen === walletGen && previous.quantity === machine.quantity) return;
1434
+ if (stateRef.current.blocked && _optionalChain([previous, 'optionalAccess', _63 => _63.drop]) === loadedDrop && previous.gen === walletGen && previous.quantity === machine.quantity) return;
2704
1435
  lastWalletRead.current = { drop: loadedDrop, gen: walletGen, quantity: machine.quantity };
2705
1436
  const life = lifeRef.current;
2706
1437
  const drop = stateRef.current.drop;
@@ -2713,15 +1444,15 @@ function useMint(options) {
2713
1444
  try {
2714
1445
  const read = await adapter.readWallet(ctxFor(life, cfg), cfg, {
2715
1446
  payer: account.address,
2716
- recipient: propsRef.current.recipient ?? account.address,
1447
+ recipient: _nullishCoalesce(propsRef.current.recipient, () => ( account.address)),
2717
1448
  quantity: stateRef.current.quantity,
2718
1449
  drop
2719
1450
  });
2720
1451
  if (!alive || life.controller.signal.aborted || lifeRef.current !== life || life.gen !== readGen) return;
2721
- const ineligible = read.ineligible?.reason === "SIMULATION_REVERTED" ? { ...read.ineligible, message: friendlyErrorMessage(new MintError("SIMULATION_REVERTED", read.ineligible.message)) } : read.ineligible;
1452
+ const ineligible = _optionalChain([read, 'access', _64 => _64.ineligible, 'optionalAccess', _65 => _65.reason]) === "SIMULATION_REVERTED" ? { ...read.ineligible, message: _chunkOO6QQT3Mcjs.friendlyErrorMessage.call(void 0, new (0, _chunkOO6QQT3Mcjs.MintError)("SIMULATION_REVERTED", read.ineligible.message)) } : read.ineligible;
2722
1453
  const fullRead = { ...read, ineligible };
2723
1454
  const payChains = payChainsOf(cfg, propsRef.current.crossChain);
2724
- const crossChain = payChains.length > 0 && ineligible === null && (adapter.supportsRelay?.(drop) ?? false);
1455
+ const crossChain = payChains.length > 0 && ineligible === null && (_nullishCoalesce(_optionalChain([adapter, 'access', _66 => _66.supportsRelay, 'optionalCall', _67 => _67(drop)]), () => ( false)));
2725
1456
  const routeChain = routeChainOf(payChains, account.chainId, propsRef.current.payChainId);
2726
1457
  const routePending = crossChain && routeChain !== cfg.chainId && payChains.includes(routeChain);
2727
1458
  dispatch({ type: "WALLET_LOADED", gen: walletGen, read: fullRead, crossChain, routePending });
@@ -2729,7 +1460,7 @@ function useMint(options) {
2729
1460
  setCrossChainInfo(null);
2730
1461
  return;
2731
1462
  }
2732
- const recipientAddr = propsRef.current.recipient ?? account.address;
1463
+ const recipientAddr = _nullishCoalesce(propsRef.current.recipient, () => ( account.address));
2733
1464
  const draft = {
2734
1465
  attemptId: 0,
2735
1466
  config: cfg,
@@ -2744,7 +1475,7 @@ function useMint(options) {
2744
1475
  let tx;
2745
1476
  try {
2746
1477
  tx = (await adapter.buildPlan(ctxFor(life, cfg), draft, fullRead)).mint;
2747
- } catch {
1478
+ } catch (e8) {
2748
1479
  if (!alive) return;
2749
1480
  setCrossChainInfo(null);
2750
1481
  if (routePending) dispatch({ type: "ROUTE_LOADED", gen: walletGen, route: { kind: "direct", chainId: cfg.chainId }, short: null });
@@ -2766,11 +1497,11 @@ function useMint(options) {
2766
1497
  if (routeChain !== account.chainId) {
2767
1498
  route = relay;
2768
1499
  } else {
2769
- const balance = await getConnectedBalance(account.address, routeChain);
1500
+ const balance = await _chunkOO6QQT3Mcjs.getConnectedBalance.call(void 0, account.address, routeChain);
2770
1501
  if (balance >= quote.amountIn.value + quote.originGas.value) route = relay;
2771
1502
  else short = shortOf(routeChain);
2772
1503
  }
2773
- } catch {
1504
+ } catch (e9) {
2774
1505
  }
2775
1506
  if (!alive || life.controller.signal.aborted || lifeRef.current !== life) return;
2776
1507
  dispatch({ type: "ROUTE_LOADED", gen: walletGen, route: short ? null : route, short });
@@ -2783,8 +1514,8 @@ function useMint(options) {
2783
1514
  alive = false;
2784
1515
  };
2785
1516
  }, [account, loadedDrop, walletGen, machine.quantity, machine.attempt, ctxFor, dispatch, isBusy]);
2786
- const prevQuantityProp = (0, import_react.useRef)(quantityProp);
2787
- (0, import_react.useEffect)(() => {
1517
+ const prevQuantityProp = _react.useRef.call(void 0, quantityProp);
1518
+ _react.useEffect.call(void 0, () => {
2788
1519
  if (isBusy()) return;
2789
1520
  const propChanged = prevQuantityProp.current !== quantityProp;
2790
1521
  prevQuantityProp.current = quantityProp;
@@ -2792,11 +1523,11 @@ function useMint(options) {
2792
1523
  const state = stateRef.current;
2793
1524
  if (!propChanged && state.account && !state.walletRead) return;
2794
1525
  const event = { type: "SET_QUANTITY", quantity: quantityProp };
2795
- const clamped = reducer(state, event).quantity;
1526
+ const clamped = _chunkOO6QQT3Mcjs.reducer.call(void 0, state, event).quantity;
2796
1527
  if (clamped !== state.quantity) dispatch(event);
2797
- if (clamped !== quantityProp) propsRef.current.onQuantityChange?.(clamped);
1528
+ if (clamped !== quantityProp) _optionalChain([propsRef, 'access', _68 => _68.current, 'access', _69 => _69.onQuantityChange, 'optionalCall', _70 => _70(clamped)]);
2798
1529
  }, [quantityProp, machine.quantity, machine.drop, machine.walletRead, machine.attempt, dispatch, isBusy]);
2799
- (0, import_react.useEffect)(() => {
1530
+ _react.useEffect.call(void 0, () => {
2800
1531
  const timer = setInterval(() => {
2801
1532
  if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
2802
1533
  void refreshNow("refresh");
@@ -2811,7 +1542,7 @@ function useMint(options) {
2811
1542
  };
2812
1543
  }, [refreshNow]);
2813
1544
  const boundary = machine.drop ? [machine.drop.startTime, machine.drop.endTime].some((t) => t !== null && t > machine.now) : false;
2814
- (0, import_react.useEffect)(() => {
1545
+ _react.useEffect.call(void 0, () => {
2815
1546
  if (!boundary) return;
2816
1547
  const timer = setInterval(() => {
2817
1548
  const s = stateRef.current;
@@ -2822,17 +1553,17 @@ function useMint(options) {
2822
1553
  }, TICK_MS);
2823
1554
  return () => clearInterval(timer);
2824
1555
  }, [boundary, dispatch, refreshNow]);
2825
- const prevName = (0, import_react.useRef)(null);
2826
- (0, import_react.useEffect)(() => {
1556
+ const prevName = _react.useRef.call(void 0, null);
1557
+ _react.useEffect.call(void 0, () => {
2827
1558
  const name = widgetFail ? isUnsupported(widgetFail.reason) ? "unsupported" : "error" : machine.name;
2828
1559
  if (prevName.current === name) return;
2829
1560
  prevName.current = name;
2830
- emit("state", { state: name, reason: widgetFail?.reason ?? machine.reason });
1561
+ emit("state", { state: name, reason: _nullishCoalesce(_optionalChain([widgetFail, 'optionalAccess', _71 => _71.reason]), () => ( machine.reason)) });
2831
1562
  }, [machine.name, machine.reason, widgetFail, emit]);
2832
- const setQuantity = (0, import_react.useCallback)(
1563
+ const setQuantity = _react.useCallback.call(void 0,
2833
1564
  (next) => {
2834
1565
  const s = stateRef.current;
2835
- const max = selectMaxQuantity(s) ?? 65535;
1566
+ const max = _nullishCoalesce(_chunkOO6QQT3Mcjs.selectMaxQuantity.call(void 0, s), () => ( 65535));
2836
1567
  const clamped = Math.max(1, Math.min(Math.floor(Number.isNaN(next) ? 1 : next), max));
2837
1568
  const handler = propsRef.current.onQuantityChange;
2838
1569
  if (handler) {
@@ -2854,7 +1585,7 @@ function useMint(options) {
2854
1585
  const wallet = machine.account && machine.walletRead ? {
2855
1586
  address: machine.account.address,
2856
1587
  chainId: machine.account.chainId,
2857
- recipient: recipient ?? machine.account.address,
1588
+ recipient: _nullishCoalesce(recipient, () => ( machine.account.address)),
2858
1589
  walletMinted: machine.walletRead.walletMinted,
2859
1590
  walletMax: machine.walletRead.walletMax,
2860
1591
  allowlistRemaining: machine.walletRead.allowlistRemaining
@@ -2867,46 +1598,46 @@ function useMint(options) {
2867
1598
  wallet,
2868
1599
  quantity: machine.quantity,
2869
1600
  setQuantity,
2870
- maxQuantity: selectMaxQuantity(machine),
2871
- total: selectTotal(machine),
1601
+ maxQuantity: _chunkOO6QQT3Mcjs.selectMaxQuantity.call(void 0, machine),
1602
+ total: _chunkOO6QQT3Mcjs.selectTotal.call(void 0, machine),
2872
1603
  mint,
2873
1604
  result: machine.result,
2874
1605
  refresh,
2875
1606
  // An attempt claimed by a click is not clickable, even while the reducer still reads 'live'.
2876
- canAct: canAct({ ...machine, name: effective.name }) && machine.attempt === null,
1607
+ canAct: _chunkOO6QQT3Mcjs.canAct.call(void 0, { ...machine, name: effective.name }) && machine.attempt === null,
2877
1608
  // Short on the wallet chain is neither route: nothing can be paid until the collector picks another chain.
2878
- route: machine.route ?? (machine.walletRead && machine.drop && !machine.routePending && machine.short === null ? { kind: "direct", chainId: machine.drop.chainId } : null),
2879
- crossChain: machine.crossChain && machine.account && crossChainInfo?.gen === machine.walletGen ? crossChainInfo.info : null
1609
+ route: _nullishCoalesce(machine.route, () => ( (machine.walletRead && machine.drop && !machine.routePending && machine.short === null ? { kind: "direct", chainId: machine.drop.chainId } : null))),
1610
+ crossChain: machine.crossChain && machine.account && _optionalChain([crossChainInfo, 'optionalAccess', _72 => _72.gen]) === machine.walletGen ? crossChainInfo.info : null
2880
1611
  };
2881
1612
  }
2882
1613
 
2883
1614
  // src/react/PayWithPicker.ts
2884
- var import_react2 = require("react");
2885
- var import_viem10 = require("viem");
1615
+
1616
+
2886
1617
  var PICKER_REFRESH_MS = 2e4;
2887
1618
  var PICKER_DEBOUNCE_MS = 500;
2888
1619
  var RELAY_REASONS = /* @__PURE__ */ new Set(["BRIDGE_UNAVAILABLE", "BRIDGE_TIMEOUT", "BRIDGE_REFUNDED", "BRIDGE_FAILED"]);
2889
- var money4 = (value, chainId) => {
2890
- const c = getChain(chainId).nativeCurrency;
2891
- return { value, decimals: c.decimals, symbol: c.symbol, formatted: (0, import_viem10.formatUnits)(value, c.decimals) };
1620
+ var money2 = (value, chainId) => {
1621
+ const c = _chunkOO6QQT3Mcjs.getChain.call(void 0, chainId).nativeCurrency;
1622
+ return { value, decimals: c.decimals, symbol: c.symbol, formatted: _viem.formatUnits.call(void 0, value, c.decimals) };
2892
1623
  };
2893
1624
  function usePayOptions(mint, onSelect) {
2894
1625
  const info = mint.crossChain;
2895
- const current = mint.wallet?.chainId ?? null;
2896
- const [quotes, setQuotes] = (0, import_react2.useState)({});
2897
- const [balance, setBalance] = (0, import_react2.useState)(null);
2898
- const [tick, setTick] = (0, import_react2.useState)(0);
2899
- (0, import_react2.useEffect)(() => {
1626
+ const current = _nullishCoalesce(_optionalChain([mint, 'access', _73 => _73.wallet, 'optionalAccess', _74 => _74.chainId]), () => ( null));
1627
+ const [quotes, setQuotes] = _react.useState.call(void 0, {});
1628
+ const [balance, setBalance] = _react.useState.call(void 0, null);
1629
+ const [tick, setTick] = _react.useState.call(void 0, 0);
1630
+ _react.useEffect.call(void 0, () => {
2900
1631
  const t = setInterval(() => setTick((n) => n + 1), PICKER_REFRESH_MS);
2901
1632
  return () => clearInterval(t);
2902
1633
  }, []);
2903
1634
  const key = info ? `${info.tx.to}:${info.tx.value}:${info.tx.data}:${info.payer}:${info.recipient}:${info.payChains.join()}` : "";
2904
- const [quotedKey, setQuotedKey] = (0, import_react2.useState)(key);
1635
+ const [quotedKey, setQuotedKey] = _react.useState.call(void 0, key);
2905
1636
  if (quotedKey !== key) {
2906
1637
  setQuotedKey(key);
2907
1638
  setQuotes({});
2908
1639
  }
2909
- (0, import_react2.useEffect)(() => {
1640
+ _react.useEffect.call(void 0, () => {
2910
1641
  if (!info) return;
2911
1642
  const controller = new AbortController();
2912
1643
  const timer = setTimeout(() => {
@@ -2917,7 +1648,7 @@ function usePayOptions(mint, onSelect) {
2917
1648
  if (!controller.signal.aborted) setQuotes((prev) => ({ ...prev, [chainId]: { relayFee: q.relayFee, amountIn: q.amountIn } }));
2918
1649
  },
2919
1650
  (e) => {
2920
- if (controller.signal.aborted || e?.reason === "RATE_LIMITED") return;
1651
+ if (controller.signal.aborted || _optionalChain([e, 'optionalAccess', _75 => _75.reason]) === "RATE_LIMITED") return;
2921
1652
  setQuotes((prev) => ({ ...prev, [chainId]: "failed" }));
2922
1653
  }
2923
1654
  );
@@ -2928,10 +1659,10 @@ function usePayOptions(mint, onSelect) {
2928
1659
  controller.abort();
2929
1660
  };
2930
1661
  }, [key, tick]);
2931
- (0, import_react2.useEffect)(() => {
1662
+ _react.useEffect.call(void 0, () => {
2932
1663
  if (!info || current === null || !mint.wallet) return;
2933
1664
  let alive = true;
2934
- getConnectedBalance(mint.wallet.address, current).then(
1665
+ _chunkOO6QQT3Mcjs.getConnectedBalance.call(void 0, mint.wallet.address, current).then(
2935
1666
  (value) => {
2936
1667
  if (alive) setBalance({ chainId: current, value });
2937
1668
  },
@@ -2942,12 +1673,12 @@ function usePayOptions(mint, onSelect) {
2942
1673
  return () => {
2943
1674
  alive = false;
2944
1675
  };
2945
- }, [current, mint.wallet?.address, key, tick]);
2946
- const select = (0, import_react2.useCallback)(
1676
+ }, [current, _optionalChain([mint, 'access', _76 => _76.wallet, 'optionalAccess', _77 => _77.address]), key, tick]);
1677
+ const select = _react.useCallback.call(void 0,
2947
1678
  (chainId) => {
2948
- switchToChain(chainId).then(
2949
- () => onSelect?.(chainId, null),
2950
- (e) => onSelect?.(chainId, e)
1679
+ _chunkOO6QQT3Mcjs.switchToChain.call(void 0, chainId).then(
1680
+ () => _optionalChain([onSelect, 'optionalCall', _78 => _78(chainId, null)]),
1681
+ (e) => _optionalChain([onSelect, 'optionalCall', _79 => _79(chainId, e)])
2951
1682
  );
2952
1683
  },
2953
1684
  [onSelect]
@@ -2959,12 +1690,12 @@ function usePayOptions(mint, onSelect) {
2959
1690
  const quoted = q && q !== "failed" ? q : null;
2960
1691
  return {
2961
1692
  chainId,
2962
- name: chainName(chainId),
1693
+ name: _chunkOO6QQT3Mcjs.chainName.call(void 0, chainId),
2963
1694
  selected: chainId === current,
2964
1695
  isDropChain,
2965
- relayFee: isDropChain ? null : quoted?.relayFee ?? null,
2966
- amountIn: isDropChain ? null : quoted?.amountIn ?? null,
2967
- balance: balance && balance.chainId === chainId && chainId === current ? money4(balance.value, chainId) : null,
1696
+ relayFee: isDropChain ? null : _nullishCoalesce(_optionalChain([quoted, 'optionalAccess', _80 => _80.relayFee]), () => ( null)),
1697
+ amountIn: isDropChain ? null : _nullishCoalesce(_optionalChain([quoted, 'optionalAccess', _81 => _81.amountIn]), () => ( null)),
1698
+ balance: balance && balance.chainId === chainId && chainId === current ? money2(balance.value, chainId) : null,
2968
1699
  loading: !isDropChain && q === void 0,
2969
1700
  select: () => select(chainId)
2970
1701
  };
@@ -2979,11 +1710,11 @@ function PayWithPicker(props) {
2979
1710
  const rows = usePayOptions(props.mint, props.onSelect);
2980
1711
  if (rows.length === 0) return null;
2981
1712
  const open = props.mint.state === "insufficient-funds" || props.mint.reason !== null && RELAY_REASONS.has(props.mint.reason);
2982
- return (0, import_react2.createElement)(
1713
+ return _react.createElement.call(void 0,
2983
1714
  "div",
2984
1715
  { className: props.className, role: "group", "aria-label": "Pay with", "data-open": open ? "true" : "false" },
2985
1716
  rows.map(
2986
- (row) => (0, import_react2.createElement)(
1717
+ (row) => _react.createElement.call(void 0,
2987
1718
  "button",
2988
1719
  {
2989
1720
  key: row.chainId,
@@ -3003,16 +1734,16 @@ function PayWithPicker(props) {
3003
1734
  }
3004
1735
 
3005
1736
  // src/react/MintButton.ts
3006
- var import_react3 = require("react");
1737
+
3007
1738
  function defaultLabel(m) {
3008
- const symbol = m.total?.erc20?.symbol ?? m.total?.native.symbol ?? m.drop?.unitPrice.symbol ?? "";
1739
+ const symbol = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([m, 'access', _82 => _82.total, 'optionalAccess', _83 => _83.erc20, 'optionalAccess', _84 => _84.symbol]), () => ( _optionalChain([m, 'access', _85 => _85.total, 'optionalAccess', _86 => _86.native, 'access', _87 => _87.symbol]))), () => ( _optionalChain([m, 'access', _88 => _88.drop, 'optionalAccess', _89 => _89.unitPrice, 'access', _90 => _90.symbol]))), () => ( ""));
3009
1740
  switch (m.state) {
3010
1741
  case "loading":
3011
1742
  return "Loading\u2026";
3012
1743
  case "unsupported":
3013
1744
  return "Unavailable";
3014
1745
  case "upcoming": {
3015
- const t = m.drop?.startTime;
1746
+ const t = _optionalChain([m, 'access', _91 => _91.drop, 'optionalAccess', _92 => _92.startTime]);
3016
1747
  return `Starts ${t ? new Date(t * 1e3).toLocaleString() : "soon"}`;
3017
1748
  }
3018
1749
  case "ended":
@@ -3025,8 +1756,8 @@ function defaultLabel(m) {
3025
1756
  return "Connecting\u2026";
3026
1757
  case "live": {
3027
1758
  const route = m.route;
3028
- if (route?.kind === "relay") {
3029
- return `Mint \xB7 ${route.amountIn.formatted} ${route.amountIn.symbol} on ${chainName(route.originChainId)}`;
1759
+ if (_optionalChain([route, 'optionalAccess', _93 => _93.kind]) === "relay") {
1760
+ return `Mint \xB7 ${route.amountIn.formatted} ${route.amountIn.symbol} on ${_chunkOO6QQT3Mcjs.chainName.call(void 0, route.originChainId)}`;
3030
1761
  }
3031
1762
  const total = m.total;
3032
1763
  if (!total) return "Mint";
@@ -3036,8 +1767,8 @@ function defaultLabel(m) {
3036
1767
  case "ineligible":
3037
1768
  return "Not eligible";
3038
1769
  case "insufficient-funds": {
3039
- const erc20 = m.total?.erc20;
3040
- const shortage = erc20 && m.message === `Not enough ${erc20.symbol} to cover the mint.` ? erc20.symbol : m.total?.native.symbol ?? symbol;
1770
+ const erc20 = _optionalChain([m, 'access', _94 => _94.total, 'optionalAccess', _95 => _95.erc20]);
1771
+ const shortage = erc20 && m.message === `Not enough ${erc20.symbol} to cover the mint.` ? erc20.symbol : _nullishCoalesce(_optionalChain([m, 'access', _96 => _96.total, 'optionalAccess', _97 => _97.native, 'access', _98 => _98.symbol]), () => ( symbol));
3041
1772
  return `Insufficient ${shortage}`.trimEnd();
3042
1773
  }
3043
1774
  case "switching-chain":
@@ -3058,8 +1789,8 @@ function MintButton(props) {
3058
1789
  const { className, labels, children, ...options } = props;
3059
1790
  const m = useMint(options);
3060
1791
  if (typeof children === "function") return children(m);
3061
- const label = labels?.[m.state] ?? defaultLabel(m);
3062
- return (0, import_react3.createElement)(
1792
+ const label = _nullishCoalesce(_optionalChain([labels, 'optionalAccess', _99 => _99[m.state]]), () => ( defaultLabel(m)));
1793
+ return _react.createElement.call(void 0,
3063
1794
  "button",
3064
1795
  {
3065
1796
  type: "button",
@@ -3070,24 +1801,23 @@ function MintButton(props) {
3070
1801
  disabled: !m.canAct,
3071
1802
  onClick: m.mint
3072
1803
  },
3073
- children ?? label
1804
+ _nullishCoalesce(children, () => ( label))
3074
1805
  );
3075
1806
  }
3076
1807
 
3077
1808
  // src/index.ts
3078
- var VERSION = "0.2.1";
3079
- // Annotate the CommonJS export names for ESM import in node:
3080
- 0 && (module.exports = {
3081
- CLICKABLE_STATES,
3082
- MAX_QUANTITY,
3083
- MINT_STATES,
3084
- MintButton,
3085
- MintError,
3086
- PayWithPicker,
3087
- REASON_CODES,
3088
- VERSION,
3089
- isMintError,
3090
- useMint,
3091
- usePayOptions
3092
- });
1809
+ var VERSION = "0.3.0";
1810
+
1811
+
1812
+
1813
+
1814
+
1815
+
1816
+
1817
+
1818
+
1819
+
1820
+
1821
+
1822
+ exports.CLICKABLE_STATES = _chunkOO6QQT3Mcjs.CLICKABLE_STATES; exports.MAX_QUANTITY = _chunkOO6QQT3Mcjs.MAX_QUANTITY; exports.MINT_STATES = _chunkOO6QQT3Mcjs.MINT_STATES; exports.MintButton = MintButton; exports.MintError = _chunkOO6QQT3Mcjs.MintError; exports.PayWithPicker = PayWithPicker; exports.REASON_CODES = _chunkOO6QQT3Mcjs.REASON_CODES; exports.VERSION = VERSION; exports.isMintError = _chunkOO6QQT3Mcjs.isMintError; exports.useMint = useMint; exports.usePayOptions = usePayOptions;
3093
1823
  //# sourceMappingURL=index.cjs.map