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