@manifoldxyz/dropkit 0.3.0 → 0.4.1

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.js CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  manifoldClaimAdapter,
21
21
  openConnectModal,
22
22
  parseMintReceipt,
23
+ recordClaimMint,
23
24
  reducer,
24
25
  selectMaxQuantity,
25
26
  selectTotal,
@@ -27,11 +28,11 @@ import {
27
28
  switchToChain,
28
29
  toReason,
29
30
  waitForDeposit
30
- } from "./chunk-3PA74M2L.js";
31
+ } from "./chunk-MXKJAZDW.js";
31
32
 
32
33
  // src/react/useMint.ts
33
34
  import { useCallback, useEffect, useReducer, useRef, useState } from "react";
34
- import { BaseError as BaseError2, ExecutionRevertedError, publicActions } from "viem";
35
+ import { BaseError as BaseError3, ExecutionRevertedError, publicActions } from "viem";
35
36
 
36
37
  // src/core/relay/client.ts
37
38
  import { formatUnits, getAddress, isHex, keccak256, zeroAddress } from "viem";
@@ -83,8 +84,8 @@ function parseQuote(body, originChainId) {
83
84
  });
84
85
  const requestId = isHex(step.requestId) ? step.requestId : isHex(b.requestId) ? b.requestId : null;
85
86
  if (!requestId) throw unknownStep();
86
- const details = obj(b.details);
87
- const currencyIn = obj(details.currencyIn);
87
+ const details2 = obj(b.details);
88
+ const currencyIn = obj(details2.currencyIn);
88
89
  const fees = obj(b.fees);
89
90
  const amountIn = moneyOf(currencyIn.amount, currencyIn.currency);
90
91
  if (obj(currencyIn.currency).address !== void 0 && obj(currencyIn.currency).address !== zeroAddress) throw unknownStep();
@@ -243,12 +244,621 @@ async function pollUntilTerminal(a) {
243
244
  }
244
245
  }
245
246
 
247
+ // src/core/adapters/tl-stacks/index.ts
248
+ import {
249
+ BaseError,
250
+ ContractFunctionRevertedError,
251
+ ContractFunctionZeroDataError,
252
+ InsufficientFundsError,
253
+ decodeErrorResult,
254
+ encodeFunctionData,
255
+ formatUnits as formatUnits2,
256
+ getAddress as getAddress3,
257
+ isAddress,
258
+ zeroAddress as zeroAddress2
259
+ } from "viem";
260
+
261
+ // src/core/adapters/tl-stacks/abis.ts
262
+ var DROP_PHASE = { NOT_CONFIGURED: 0, NOT_STARTED: 1, PRESALE: 2, PUBLIC_SALE: 3, ENDED: 4 };
263
+ var SUPPORTED_VERSIONS = ["2.3.0", "2.3.1"];
264
+ var stacksAbi = [
265
+ { type: "function", name: "VERSION", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] },
266
+ { type: "function", name: "protocolFee", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "uint256" }] },
267
+ {
268
+ type: "function",
269
+ name: "getDrop",
270
+ stateMutability: "view",
271
+ inputs: [{ name: "nftAddress", type: "address" }],
272
+ outputs: [
273
+ {
274
+ name: "",
275
+ type: "tuple",
276
+ components: [
277
+ { name: "dropType", type: "uint8" },
278
+ { name: "payoutReceiver", type: "address" },
279
+ { name: "initialSupply", type: "uint256" },
280
+ { name: "supply", type: "uint256" },
281
+ { name: "allowance", type: "uint256" },
282
+ { name: "currencyAddress", type: "address" },
283
+ { name: "startTime", type: "uint256" },
284
+ { name: "presaleDuration", type: "uint256" },
285
+ { name: "presaleCost", type: "uint256" },
286
+ { name: "presaleMerkleRoot", type: "bytes32" },
287
+ { name: "publicDuration", type: "uint256" },
288
+ { name: "publicCost", type: "uint256" },
289
+ { name: "decayRate", type: "int256" },
290
+ { name: "baseUri", type: "string" }
291
+ ]
292
+ }
293
+ ]
294
+ },
295
+ {
296
+ type: "function",
297
+ name: "getDropPhase",
298
+ stateMutability: "view",
299
+ inputs: [{ name: "nftAddress", type: "address" }],
300
+ outputs: [{ name: "", type: "uint8" }]
301
+ },
302
+ {
303
+ type: "function",
304
+ name: "getNumberMinted",
305
+ stateMutability: "view",
306
+ inputs: [
307
+ { name: "nftAddress", type: "address" },
308
+ { name: "recipient", type: "address" }
309
+ ],
310
+ outputs: [{ name: "", type: "uint256" }]
311
+ },
312
+ {
313
+ type: "function",
314
+ name: "purchase",
315
+ stateMutability: "payable",
316
+ inputs: [
317
+ { name: "nftAddress", type: "address" },
318
+ { name: "recipient", type: "address" },
319
+ { name: "numberToMint", type: "uint256" },
320
+ { name: "presaleNumberCanMint", type: "uint256" },
321
+ { name: "proof", type: "bytes32[]" }
322
+ ],
323
+ outputs: [{ name: "refundAmount", type: "uint256" }]
324
+ },
325
+ { type: "error", name: "MintZeroTokens", inputs: [] },
326
+ { type: "error", name: "NotOnAllowlist", inputs: [] },
327
+ { type: "error", name: "YouShallNotMint", inputs: [] },
328
+ { type: "error", name: "AlreadyReachedMintAllowance", inputs: [] },
329
+ { type: "error", name: "InsufficientFunds", inputs: [] },
330
+ { type: "error", name: "SanctionedAddress", inputs: [] },
331
+ // OpenZeppelin v5 Pausable: purchase is whenNotPaused.
332
+ { type: "error", name: "EnforcedPause", inputs: [] }
333
+ ];
334
+
335
+ // src/core/adapters/tl-stacks/allowlist.ts
336
+ import { concatHex, encodeAbiParameters, getAddress as getAddress2, keccak256 as keccak2562 } from "viem";
337
+ var HASH = /^0x[0-9a-fA-F]{64}$/;
338
+ var UINT = /^\d+$/;
339
+ var MAX_UINT256 = 2n ** 256n - 1n;
340
+ var unavailable = (message, cause) => new MintError("ALLOWLIST_UNAVAILABLE", message, cause === void 0 ? void 0 : { cause });
341
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
342
+ var hashWallet = (wallet) => keccak2562(encodeAbiParameters([{ type: "address" }], [getAddress2(wallet)]));
343
+ var leafOf = (hashedWallet, allowance) => keccak2562(concatHex([keccak2562(encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [hashedWallet, allowance]))]));
344
+ var hashPair = (a, b) => BigInt(a) < BigInt(b) ? keccak2562(concatHex([a, b])) : keccak2562(concatHex([b, a]));
345
+ var processProof = (leaf, proof) => proof.reduce((node, sibling) => hashPair(node, sibling), leaf);
346
+ function parseAllowlist(body) {
347
+ if (!isRecord(body)) throw unavailable("The allowlist file is not a merkle tree dump.");
348
+ if (body.format !== "standard-v1") throw unavailable("The allowlist file is in an unsupported format.");
349
+ const enc = body.leafEncoding;
350
+ if (!Array.isArray(enc) || enc.length !== 2 || enc[0] !== "bytes32" || enc[1] !== "uint256") {
351
+ throw unavailable("The allowlist file uses an unsupported leaf encoding.");
352
+ }
353
+ const { tree, values } = body;
354
+ if (!Array.isArray(tree) || tree.length === 0 || !tree.every((n) => typeof n === "string" && HASH.test(n))) {
355
+ throw unavailable("The allowlist file has no readable merkle tree.");
356
+ }
357
+ if (!Array.isArray(values)) throw unavailable("The allowlist file has no wallet values.");
358
+ const entries = /* @__PURE__ */ new Map();
359
+ for (const row of values) {
360
+ const value = isRecord(row) ? row.value : void 0;
361
+ const treeIndex = isRecord(row) ? row.treeIndex : void 0;
362
+ if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== "string" || !HASH.test(value[0])) {
363
+ throw unavailable("The allowlist file has an unreadable wallet entry.");
364
+ }
365
+ const raw = value[1];
366
+ const allowanceText = typeof raw === "string" ? raw : typeof raw === "number" && Number.isSafeInteger(raw) ? String(raw) : "";
367
+ if (!UINT.test(allowanceText) || BigInt(allowanceText) > MAX_UINT256) throw unavailable("The allowlist file has an unreadable allowance.");
368
+ if (typeof treeIndex !== "number") throw unavailable("The allowlist file has an unreadable tree index.");
369
+ const key = value[0].toLowerCase();
370
+ const allowance = BigInt(allowanceText);
371
+ const prev = entries.get(key);
372
+ if (!prev || allowance > prev.allowance) entries.set(key, { allowance, treeIndex });
373
+ }
374
+ return { root: tree[0].toLowerCase(), tree, entries };
375
+ }
376
+ var findEntry = (list, recipient) => list.entries.get(hashWallet(recipient).toLowerCase()) ?? null;
377
+ function assertRoot(list, presaleMerkleRoot) {
378
+ if (list.root !== presaleMerkleRoot.toLowerCase()) {
379
+ throw unavailable("The allowlist file does not match this drop. The creator may have updated the allowlist; reload the page.");
380
+ }
381
+ }
382
+ var buildProof = (list, recipient, entry) => buildProofForHash(list, hashWallet(recipient), entry);
383
+ function buildProofForHash(list, hashedWallet, entry) {
384
+ const { tree } = list;
385
+ const { treeIndex } = entry;
386
+ if (!Number.isInteger(treeIndex) || treeIndex < 1 || treeIndex >= tree.length) {
387
+ throw unavailable("The allowlist file has a tree index outside the tree.");
388
+ }
389
+ const leaf = leafOf(hashedWallet, entry.allowance);
390
+ if (tree[treeIndex].toLowerCase() !== leaf.toLowerCase()) throw unavailable("The allowlist file entry does not match its merkle leaf.");
391
+ const proof = [];
392
+ let i = treeIndex;
393
+ while (i > 0) {
394
+ const sibling = i % 2 === 0 ? i - 1 : i + 1;
395
+ const node = tree[sibling];
396
+ if (node === void 0) throw unavailable("The allowlist file has a broken merkle tree.");
397
+ proof.push(node);
398
+ i = Math.floor((i - 1) / 2);
399
+ }
400
+ if (processProof(leaf, proof).toLowerCase() !== list.root) throw unavailable("The allowlist file does not produce a valid proof for this wallet.");
401
+ return proof;
402
+ }
403
+ var scopeCaches = /* @__PURE__ */ new WeakMap();
404
+ function withSignal(p, signal) {
405
+ if (!signal) return p;
406
+ return new Promise((resolve, reject) => {
407
+ const onAbort = () => reject(unavailable("The allowlist request was cancelled.", signal.reason));
408
+ p.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
409
+ if (signal.aborted) return onAbort();
410
+ signal.addEventListener("abort", onAbort, { once: true });
411
+ });
412
+ }
413
+ var ALLOWLIST_TIMEOUT_MS = 3e4;
414
+ var ALLOWLIST_MAX_BYTES = 10 * 1024 * 1024;
415
+ var tooLarge = () => unavailable(`The allowlist file is larger than ${ALLOWLIST_MAX_BYTES / (1024 * 1024)} MB.`);
416
+ async function readCapped(res) {
417
+ const declared = Number(res.headers.get("content-length"));
418
+ if (Number.isFinite(declared) && declared > ALLOWLIST_MAX_BYTES) throw tooLarge();
419
+ if (!res.body) return "";
420
+ const reader = res.body.getReader();
421
+ const chunks = [];
422
+ let total = 0;
423
+ for (; ; ) {
424
+ const { done, value } = await reader.read();
425
+ if (done) break;
426
+ total += value.byteLength;
427
+ if (total > ALLOWLIST_MAX_BYTES) {
428
+ void reader.cancel().catch(() => void 0);
429
+ throw tooLarge();
430
+ }
431
+ chunks.push(value);
432
+ }
433
+ const bytes = new Uint8Array(total);
434
+ let offset = 0;
435
+ for (const c of chunks) {
436
+ bytes.set(c, offset);
437
+ offset += c.byteLength;
438
+ }
439
+ return new TextDecoder().decode(bytes);
440
+ }
441
+ async function fetchAndParse(fetchFn, url, signal) {
442
+ let res;
443
+ try {
444
+ signal.throwIfAborted();
445
+ res = await fetchFn(url, { signal });
446
+ } catch (cause) {
447
+ throw unavailable("Could not reach the allowlist file.", cause);
448
+ }
449
+ if (res.status === 429) throw new MintError("RATE_LIMITED", "The allowlist host is rate limiting requests. Try again shortly.");
450
+ if (!res.ok) throw unavailable(`The allowlist file is not available (HTTP ${res.status}).`);
451
+ let body;
452
+ try {
453
+ const text = await readCapped(res);
454
+ body = JSON.parse(text);
455
+ } catch (cause) {
456
+ if (cause instanceof MintError) throw cause;
457
+ throw unavailable("The allowlist file could not be read.", cause);
458
+ }
459
+ return parseAllowlist(body);
460
+ }
461
+ async function download(fetchFn, url, signal) {
462
+ const controller = new AbortController();
463
+ let onAbort;
464
+ const stopped = new Promise((_, reject) => {
465
+ onAbort = () => {
466
+ const reason = controller.signal.reason;
467
+ reject(reason instanceof MintError ? reason : unavailable("The allowlist request was cancelled.", reason));
468
+ };
469
+ controller.signal.addEventListener("abort", onAbort, { once: true });
470
+ });
471
+ const onLifetimeAbort = () => controller.abort(signal?.reason);
472
+ if (signal?.aborted) onLifetimeAbort();
473
+ else signal?.addEventListener("abort", onLifetimeAbort, { once: true });
474
+ const timer = setTimeout(
475
+ () => controller.abort(unavailable(`The allowlist file did not load within ${ALLOWLIST_TIMEOUT_MS / 1e3} seconds. Try again.`)),
476
+ ALLOWLIST_TIMEOUT_MS
477
+ );
478
+ try {
479
+ return await Promise.race([fetchAndParse(fetchFn, url, controller.signal), stopped]);
480
+ } finally {
481
+ clearTimeout(timer);
482
+ if (onAbort) controller.signal.removeEventListener("abort", onAbort);
483
+ signal?.removeEventListener("abort", onLifetimeAbort);
484
+ }
485
+ }
486
+ function loadAllowlist(args) {
487
+ if (!args.url) {
488
+ return Promise.reject(unavailable("This presale has no allowlist file configured (allowlistUrl). Ask the creator to add it."));
489
+ }
490
+ if (args.signal?.aborted) return Promise.reject(unavailable("The allowlist request was cancelled.", args.signal.reason));
491
+ const fetchFn = args.fetch ?? ((input, init) => globalThis.fetch(input, init));
492
+ let scoped = scopeCaches.get(args.scope);
493
+ if (!scoped || scoped.signal?.aborted) {
494
+ scoped = { signal: args.signal, loads: /* @__PURE__ */ new Map() };
495
+ scopeCaches.set(args.scope, scoped);
496
+ }
497
+ const cache2 = scoped;
498
+ const hit = cache2.loads.get(args.url);
499
+ if (hit) return hit;
500
+ const url = args.url;
501
+ const p = withSignal(download(fetchFn, url, cache2.signal), cache2.signal);
502
+ cache2.loads.set(url, p);
503
+ p.catch(() => {
504
+ if (cache2.loads.get(url) === p) cache2.loads.delete(url);
505
+ });
506
+ return p;
507
+ }
508
+
509
+ // src/core/adapters/tl-stacks/index.ts
510
+ var FALLBACK_GAS_BASE = 150000n;
511
+ var FALLBACK_GAS_PER_TOKEN = 150000n;
512
+ var details = /* @__PURE__ */ new WeakMap();
513
+ function bad(field, message) {
514
+ throw new MintError("INVALID_CONFIG", `${field} ${message}`, { field });
515
+ }
516
+ function validateTlStacksConfig(config) {
517
+ if (!Number.isInteger(config.chainId) || config.chainId <= 0) bad("chainId", "must be a positive integer");
518
+ if (typeof config.stacks !== "string" || !isAddress(config.stacks, { strict: false })) bad("stacks", "is not a valid address");
519
+ if (typeof config.nftContract !== "string" || !isAddress(config.nftContract, { strict: false })) bad("nftContract", "is not a valid address");
520
+ if (config.allowlistUrl !== void 0) {
521
+ const https = (() => {
522
+ try {
523
+ return typeof config.allowlistUrl === "string" && new URL(config.allowlistUrl).protocol === "https:";
524
+ } catch {
525
+ return false;
526
+ }
527
+ })();
528
+ if (!https) bad("allowlistUrl", "must be an https: URL");
529
+ }
530
+ }
531
+ var abortError = () => new DOMException("The operation was aborted", "AbortError");
532
+ var isAbortError = (e) => e?.name === "AbortError";
533
+ function throwIfAborted(ctx) {
534
+ if (ctx.signal?.aborted) throw abortError();
535
+ }
536
+ function io(ctx, start) {
537
+ const signal = ctx.signal;
538
+ if (!signal) return start();
539
+ if (signal.aborted) return Promise.reject(abortError());
540
+ return new Promise((resolve, reject) => {
541
+ const onAbort = () => reject(abortError());
542
+ signal.addEventListener("abort", onAbort, { once: true });
543
+ start().then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
544
+ });
545
+ }
546
+ var shortMessage = (e) => e instanceof BaseError ? e.shortMessage : e instanceof Error ? e.message : String(e);
547
+ function rpcError(e) {
548
+ if (isMintError(e) || isAbortError(e)) throw e;
549
+ throw new MintError("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
550
+ }
551
+ async function readStacks(ctx, config, functionName, args = []) {
552
+ try {
553
+ return await io(
554
+ ctx,
555
+ () => ctx.client.readContract({ address: getAddress3(config.stacks), abi: stacksAbi, functionName, args })
556
+ );
557
+ } catch (e) {
558
+ if (isMintError(e) || isAbortError(e)) throw e;
559
+ if (e instanceof BaseError && e.walk((x) => x instanceof ContractFunctionRevertedError || x instanceof ContractFunctionZeroDataError)) {
560
+ throw new MintError("INVALID_CONFIG", `stacks ${functionName}() reverted or returned no data. Is ${config.stacks} a TL Stacks 721 contract on chain ${config.chainId}?`, {
561
+ field: "stacks",
562
+ cause: e
563
+ });
564
+ }
565
+ return rpcError(e);
566
+ }
567
+ }
568
+ var versions = /* @__PURE__ */ new WeakMap();
569
+ async function checkVersion(ctx, config) {
570
+ const load = () => readStacks(ctx, config, "VERSION");
571
+ let version;
572
+ if (ctx.cacheScope) {
573
+ let byStacks = versions.get(ctx.cacheScope);
574
+ if (!byStacks) versions.set(ctx.cacheScope, byStacks = /* @__PURE__ */ new Map());
575
+ const key = `${config.chainId}:${config.stacks.toLowerCase()}`;
576
+ const cache2 = byStacks;
577
+ let hit = cache2.get(key);
578
+ if (!hit) {
579
+ const p = load();
580
+ cache2.set(key, hit = p);
581
+ p.catch(() => {
582
+ if (cache2.get(key) === p) cache2.delete(key);
583
+ });
584
+ }
585
+ version = hit;
586
+ } else {
587
+ version = load();
588
+ }
589
+ const v = await version;
590
+ if (!SUPPORTED_VERSIONS.includes(v)) {
591
+ bad("stacks", `is TL Stacks ${v}. Dropkit supports ${SUPPORTED_VERSIONS.join(" and ")} only.`);
592
+ }
593
+ }
594
+ var money = (value, decimals, symbol) => ({ value, decimals, symbol, formatted: formatUnits2(value, decimals) });
595
+ function nativeMeta(ctx) {
596
+ const n = ctx.client.chain?.nativeCurrency;
597
+ return { decimals: n?.decimals ?? 18, symbol: n?.symbol ?? "ETH" };
598
+ }
599
+ function seconds(v, field) {
600
+ if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new MintError("INVALID_CONFIG", `${field} is too large for a unix timestamp`, { field });
601
+ return Number(v);
602
+ }
603
+ function priceFor(drop, phase) {
604
+ const presalePrice = phase === DROP_PHASE.PRESALE || phase === DROP_PHASE.NOT_STARTED && drop.presaleDuration > 0n;
605
+ return { presalePrice, unitPrice: presalePrice ? drop.presaleCost : drop.publicCost };
606
+ }
607
+ async function readDrop(ctx, config) {
608
+ validateTlStacksConfig(config);
609
+ throwIfAborted(ctx);
610
+ await checkVersion(ctx, config);
611
+ const nft = getAddress3(config.nftContract);
612
+ const [drop, phaseRaw, fee] = await Promise.all([
613
+ readStacks(ctx, config, "getDrop", [nft]),
614
+ readStacks(ctx, config, "getDropPhase", [nft]),
615
+ readStacks(ctx, config, "protocolFee")
616
+ ]);
617
+ const phase = Number(phaseRaw);
618
+ if (phase === DROP_PHASE.NOT_CONFIGURED) {
619
+ throw new MintError("DROP_NOT_FOUND", "No Transient Labs drop is configured for this NFT contract on this chain.");
620
+ }
621
+ if (drop.currencyAddress !== zeroAddress2) {
622
+ bad("nftContract", `is sold for an ERC-20 (${drop.currencyAddress}). Dropkit supports drops priced in the native token only.`);
623
+ }
624
+ const { presalePrice, unitPrice } = priceFor(drop, phase);
625
+ const startTime = seconds(drop.startTime, "startTime");
626
+ const presaleEnd = seconds(drop.startTime + drop.presaleDuration, "presaleDuration");
627
+ const soldOut = drop.supply === 0n;
628
+ const neverMintable = drop.initialSupply === 0n;
629
+ const native = nativeMeta(ctx);
630
+ const info = {
631
+ chainId: config.chainId,
632
+ unitPrice: money(unitPrice, native.decimals, native.symbol),
633
+ unitFee: money(fee, native.decimals, native.symbol),
634
+ totalMinted: drop.initialSupply - drop.supply,
635
+ maxSupply: drop.initialSupply,
636
+ // A never-mintable drop has no start either, so the hook clock has no boundary ahead to tick towards (review F13).
637
+ startTime: neverMintable || startTime === 0 ? null : startTime,
638
+ // At supply 0 the drop is sold out for good: no end time, so it never turns into `ended` (D14).
639
+ endTime: neverMintable ? 0 : soldOut ? null : seconds(drop.startTime + drop.presaleDuration + drop.publicDuration, "publicDuration"),
640
+ isAllowlist: phase === DROP_PHASE.PRESALE,
641
+ paymentToken: null,
642
+ pricePer: "unit",
643
+ phaseEndsAt: presalePrice ? presaleEnd : null,
644
+ walletKey: `${phase}:${drop.presaleMerkleRoot}:${unitPrice}:${fee}`
645
+ };
646
+ details.set(info, {
647
+ phase,
648
+ presaleMerkleRoot: drop.presaleMerkleRoot,
649
+ allowance: drop.allowance,
650
+ presaleDuration: drop.presaleDuration,
651
+ publicDuration: drop.publicDuration,
652
+ startTime: drop.startTime
653
+ });
654
+ return info;
655
+ }
656
+ async function detailOf(ctx, config, drop) {
657
+ const hit = details.get(drop);
658
+ if (hit) return hit;
659
+ const nft = getAddress3(config.nftContract);
660
+ const [raw, phase] = await Promise.all([
661
+ readStacks(ctx, config, "getDrop", [nft]),
662
+ readStacks(ctx, config, "getDropPhase", [nft])
663
+ ]);
664
+ return {
665
+ phase: Number(phase),
666
+ presaleMerkleRoot: raw.presaleMerkleRoot,
667
+ allowance: raw.allowance,
668
+ presaleDuration: raw.presaleDuration,
669
+ publicDuration: raw.publicDuration,
670
+ startTime: raw.startTime
671
+ };
672
+ }
673
+ var dayTime = (unix) => new Date(unix * 1e3).toLocaleString(void 0, { dateStyle: "medium", timeStyle: "short" });
674
+ function notOnAllowlist(d) {
675
+ const opens = Number(d.startTime + d.presaleDuration);
676
+ const message = d.publicDuration > 0n ? `This wallet is not on the allowlist. The public sale opens ${dayTime(opens)}.` : "This wallet is not on the allowlist. This drop is allowlist only.";
677
+ return { reason: "NOT_ON_ALLOWLIST", message };
678
+ }
679
+ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
680
+ validateTlStacksConfig(config);
681
+ throwIfAborted(ctx);
682
+ const detail = await detailOf(ctx, config, drop);
683
+ const nft = getAddress3(config.nftContract);
684
+ const presale = detail.phase === DROP_PHASE.PRESALE;
685
+ const [minted, native, gasPrice, list] = await Promise.all([
686
+ readStacks(ctx, config, "getNumberMinted", [nft, getAddress3(recipient)]),
687
+ io(ctx, () => ctx.client.getBalance({ address: payer })).catch(rpcError),
688
+ io(ctx, () => ctx.client.getGasPrice()).catch(rpcError),
689
+ presale ? loadAllowlist({ scope: ctx.cacheScope ?? drop, url: config.allowlistUrl, fetch: ctx.fetch, signal: ctx.signal }) : Promise.resolve(null)
690
+ ]);
691
+ let walletMax = detail.allowance;
692
+ let proof = [];
693
+ let presaleNumberCanMint = 0n;
694
+ let ineligible = null;
695
+ let allowlistRemaining = null;
696
+ if (presale && list) {
697
+ assertRoot(list, detail.presaleMerkleRoot);
698
+ const entry = findEntry(list, recipient);
699
+ if (!entry) {
700
+ walletMax = 0n;
701
+ ineligible = notOnAllowlist(detail);
702
+ } else {
703
+ walletMax = entry.allowance;
704
+ presaleNumberCanMint = entry.allowance;
705
+ proof = buildProof(list, recipient, entry);
706
+ }
707
+ }
708
+ const remaining = walletMax > minted ? walletMax - minted : 0n;
709
+ if (presale && ineligible === null) {
710
+ allowlistRemaining = Number(remaining < BigInt(MAX_QUANTITY) ? remaining : BigInt(MAX_QUANTITY));
711
+ if (remaining === 0n) ineligible = { reason: "ALLOWLIST_USED", message: `This wallet has already minted its allowlist allocation of ${walletMax}.` };
712
+ } else if (!presale && remaining === 0n) {
713
+ ineligible = { reason: "WALLET_LIMIT", message: `This wallet has already minted its limit of ${walletMax}.` };
714
+ }
715
+ const maxQuantity = Number(remaining < BigInt(MAX_QUANTITY) ? remaining : BigInt(MAX_QUANTITY));
716
+ const data = { presaleNumberCanMint, proof, unitPrice: drop.unitPrice.value, unitFee: drop.unitFee.value };
717
+ const qty = BigInt(quantity);
718
+ const value = qty * (data.unitPrice + data.unitFee);
719
+ let gas = FALLBACK_GAS_BASE + FALLBACK_GAS_PER_TOKEN * qty;
720
+ const open = detail.phase === DROP_PHASE.PRESALE || detail.phase === DROP_PHASE.PUBLIC_SALE;
721
+ if (open && ineligible === null && native >= value) {
722
+ try {
723
+ const estimated = await io(
724
+ ctx,
725
+ () => ctx.client.estimateGas({ account: payer, to: getAddress3(config.stacks), data: encodePurchase(config, recipient, qty, data), value })
726
+ );
727
+ gas = estimated;
728
+ } catch (e) {
729
+ if (isAbortError(e)) throw e;
730
+ }
731
+ }
732
+ return {
733
+ walletMinted: minted,
734
+ walletMax,
735
+ allowlistRemaining,
736
+ maxQuantity,
737
+ ineligible,
738
+ balances: { native, erc20: null },
739
+ gasReserve: gas * gasPrice,
740
+ data
741
+ };
742
+ }
743
+ function encodePurchase(config, recipient, quantity, data) {
744
+ return encodeFunctionData({
745
+ abi: stacksAbi,
746
+ functionName: "purchase",
747
+ args: [getAddress3(config.nftContract), getAddress3(recipient), quantity, data.presaleNumberCanMint, [...data.proof]]
748
+ });
749
+ }
750
+ function walletData(wallet) {
751
+ const d = wallet.data;
752
+ if (!d || typeof d.presaleNumberCanMint !== "bigint" || typeof d.unitPrice !== "bigint" || typeof d.unitFee !== "bigint" || !Array.isArray(d.proof)) {
753
+ throw new MintError("RPC_ERROR", "The wallet read is missing the data this mint needs. Reload and try again.");
754
+ }
755
+ return d;
756
+ }
757
+ async function buildPlan(ctx, attempt, wallet) {
758
+ const { config, recipient } = attempt;
759
+ validateTlStacksConfig(config);
760
+ throwIfAborted(ctx);
761
+ if (!Number.isInteger(attempt.quantity) || attempt.quantity < 1) {
762
+ throw new MintError("SIMULATION_REVERTED", "Choose at least one token to mint.");
763
+ }
764
+ const data = walletData(wallet);
765
+ const qty = BigInt(attempt.quantity);
766
+ return {
767
+ approve: null,
768
+ mint: {
769
+ to: getAddress3(config.stacks),
770
+ data: encodePurchase(config, recipient, qty, data),
771
+ value: qty * (data.unitPrice + data.unitFee)
772
+ },
773
+ tokenContract: getAddress3(config.nftContract)
774
+ };
775
+ }
776
+ var TL_MESSAGES = {
777
+ NotOnAllowlist: "This wallet is not on the allowlist for the current sale.",
778
+ YouShallNotMint: "This drop is not open for minting right now.",
779
+ AlreadyReachedMintAllowance: "This wallet has already minted its limit.",
780
+ InsufficientFunds: "The price or fee changed since the page loaded, so the payment is too low. Reload the page and try again.",
781
+ MintZeroTokens: "Choose at least one token to mint.",
782
+ SanctionedAddress: "This wallet or the recipient is blocked by a sanctions check, so it cannot mint.",
783
+ EnforcedPause: "Minting is paused by Transient Labs right now. Try again later."
784
+ };
785
+ function revertData(e) {
786
+ for (let cur = e, depth = 0; cur && depth < 12; depth++) {
787
+ const d = cur.data;
788
+ if (typeof d === "string" && d.startsWith("0x") && d.length >= 10) return d;
789
+ if (d && typeof d === "object" && typeof d.data === "string") {
790
+ const inner = d.data;
791
+ if (inner.startsWith("0x") && inner.length >= 10) return inner;
792
+ }
793
+ cur = cur.cause;
794
+ }
795
+ return null;
796
+ }
797
+ function decodeTlRevert(e) {
798
+ if (isMintError(e)) return e;
799
+ if (isAbortError(e)) throw e;
800
+ if (e instanceof BaseError && e.walk((x) => x instanceof InsufficientFundsError)) {
801
+ return new MintError("INSUFFICIENT_FUNDS", `The wallet cannot cover the mint: ${e.shortMessage}`, { cause: e });
802
+ }
803
+ const data = revertData(e);
804
+ if (data) {
805
+ try {
806
+ const { errorName, args } = decodeErrorResult({ abi: stacksAbi, data });
807
+ const known = TL_MESSAGES[errorName];
808
+ if (known) return new MintError("SIMULATION_REVERTED", known, { cause: e, domain: "tl-stacks" });
809
+ const shown = (args ?? []).map(String).join(", ");
810
+ return new MintError("SIMULATION_REVERTED", `Transient Labs rejected the mint (${errorName}(${shown})).`, { cause: e, domain: "tl-stacks" });
811
+ } catch {
812
+ return new MintError("SIMULATION_REVERTED", `Transient Labs rejected the mint (unrecognized error ${data.slice(0, 10)}).`, { cause: e, domain: "tl-stacks" });
813
+ }
814
+ }
815
+ const reverted = e instanceof BaseError && e.walk((x) => x.code === 3 || /execution reverted/i.test(x.message));
816
+ if (reverted) return new MintError("SIMULATION_REVERTED", shortMessage(e), { cause: e });
817
+ return new MintError("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
818
+ }
819
+ async function simulate(ctx, attempt, plan) {
820
+ throwIfAborted(ctx);
821
+ const { config } = attempt;
822
+ const nft = getAddress3(config.nftContract);
823
+ const [drop, phaseRaw, fee] = await Promise.all([
824
+ readStacks(ctx, config, "getDrop", [nft]),
825
+ readStacks(ctx, config, "getDropPhase", [nft]),
826
+ readStacks(ctx, config, "protocolFee")
827
+ ]);
828
+ if (drop.currencyAddress !== zeroAddress2) {
829
+ throw new MintError("SIMULATION_REVERTED", "This drop is now sold for a token instead of the native currency, so it cannot be minted here. Reload the page.", { domain: "tl-stacks" });
830
+ }
831
+ const current = BigInt(attempt.quantity) * (priceFor(drop, Number(phaseRaw)).unitPrice + fee);
832
+ if (current !== plan.mint.value) {
833
+ throw new MintError("SIMULATION_REVERTED", TL_MESSAGES.InsufficientFunds, { domain: "tl-stacks" });
834
+ }
835
+ try {
836
+ await io(ctx, () => ctx.client.call({ account: attempt.payer, to: plan.mint.to, data: plan.mint.data, value: plan.mint.value }));
837
+ } catch (e) {
838
+ throw decodeTlRevert(e);
839
+ }
840
+ }
841
+ var tlStacksAdapter = { readDrop, readWallet, buildPlan, simulate };
842
+
246
843
  // src/core/relay/outstanding.ts
247
844
  var memory = /* @__PURE__ */ new Map();
248
845
  var claimed = /* @__PURE__ */ new Set();
846
+ function targetOf(config) {
847
+ switch (config.type) {
848
+ case "manifold-claim":
849
+ return `${config.creatorContract.toLowerCase()}:${config.instanceId}`;
850
+ case "contract":
851
+ return config.address.toLowerCase();
852
+ case "tl-stacks":
853
+ return `stacks:${config.nftContract.toLowerCase()}`;
854
+ default: {
855
+ const unreachable = config;
856
+ return unreachable;
857
+ }
858
+ }
859
+ }
249
860
  function outstandingKey(config, payer) {
250
- const target = config.type === "manifold-claim" ? `${config.creatorContract.toLowerCase()}:${config.instanceId}` : config.address.toLowerCase();
251
- return `${String(config.chainId)}:${target}:${payer.toLowerCase()}`;
861
+ return `${String(config.chainId)}:${targetOf(config)}:${payer.toLowerCase()}`;
252
862
  }
253
863
  var getOutstanding = (key) => memory.get(key) ?? null;
254
864
  var setOutstanding = (key, out) => void memory.set(key, out);
@@ -262,15 +872,15 @@ var releaseDeposit = (key) => void claimed.delete(key);
262
872
 
263
873
  // src/core/adapters/contract/index.ts
264
874
  import {
265
- BaseError,
266
- ContractFunctionRevertedError,
267
- ContractFunctionZeroDataError,
268
- InsufficientFundsError,
269
- decodeErrorResult,
270
- encodeFunctionData,
271
- formatUnits as formatUnits2,
272
- getAddress as getAddress2,
273
- isAddress,
875
+ BaseError as BaseError2,
876
+ ContractFunctionRevertedError as ContractFunctionRevertedError2,
877
+ ContractFunctionZeroDataError as ContractFunctionZeroDataError2,
878
+ InsufficientFundsError as InsufficientFundsError2,
879
+ decodeErrorResult as decodeErrorResult2,
880
+ encodeFunctionData as encodeFunctionData2,
881
+ formatUnits as formatUnits3,
882
+ getAddress as getAddress4,
883
+ isAddress as isAddress2,
274
884
  parseAbi,
275
885
  parseUnits
276
886
  } from "viem";
@@ -287,25 +897,25 @@ var APPROVE_GAS = 65000n;
287
897
  var PLACEHOLDER_TOKEN = /\{[A-Za-z_]\w*\}/g;
288
898
  var DISPLAY_AMOUNT = /^\d+(\.\d+)?$/;
289
899
  var NUMERIC_TYPE = /^u?int\d*$/;
290
- function bad(field, message) {
900
+ function bad2(field, message) {
291
901
  throw new MintError("INVALID_CONFIG", `${field} ${message}`, { field });
292
902
  }
293
- var isHexAddress = (a) => typeof a === "string" && isAddress(a, { strict: false });
903
+ var isHexAddress = (a) => typeof a === "string" && isAddress2(a, { strict: false });
294
904
  function functionsNamed(abi, name) {
295
905
  return abi.filter((i) => i.type === "function" && i.name === name);
296
906
  }
297
907
  function validateTemplate(t, path, allowed) {
298
908
  if (typeof t === "string") {
299
909
  for (const token of t.match(PLACEHOLDER_TOKEN) ?? []) {
300
- if (!PLACEHOLDERS.includes(token)) bad(path, `"${t}" is not a known placeholder (${token})`);
301
- if (!allowed.includes(token)) bad(path, `"${t}" uses ${token}, which is not available in this field`);
910
+ if (!PLACEHOLDERS.includes(token)) bad2(path, `"${t}" is not a known placeholder (${token})`);
911
+ if (!allowed.includes(token)) bad2(path, `"${t}" uses ${token}, which is not available in this field`);
302
912
  }
303
913
  } else if (Array.isArray(t)) {
304
914
  t.forEach((x, i) => validateTemplate(x, `${path}[${i}]`, allowed));
305
915
  } else if (typeof t === "number") {
306
- if (!Number.isSafeInteger(t)) bad(path, `${t} is not a safe integer; pass larger or fractional values as a bigint or decimal string`);
916
+ if (!Number.isSafeInteger(t)) bad2(path, `${t} is not a safe integer; pass larger or fractional values as a bigint or decimal string`);
307
917
  } else if (typeof t !== "bigint" && typeof t !== "boolean") {
308
- bad(path, "must be a string, number, bigint, boolean or array");
918
+ bad2(path, "must be a string, number, bigint, boolean or array");
309
919
  }
310
920
  }
311
921
  var ARRAY_TYPE = /^(.*)\[(\d*)\]$/;
@@ -347,7 +957,7 @@ function typeIssue(t, p, path) {
347
957
  if (Array.isArray(t)) return no(`must not be an array for ${p.type}`);
348
958
  if (p.type === "address") {
349
959
  if (isExactPlaceholder(t)) return t === "{recipient}" || t === "{payer}" ? null : no(`${t} is a number, but the abi input is an address`);
350
- return typeof t === "string" && !hasPlaceholder(t) && isAddress(t) ? null : no(`${JSON.stringify(String(t))} is not an address`);
960
+ return typeof t === "string" && !hasPlaceholder(t) && isAddress2(t) ? null : no(`${JSON.stringify(String(t))} is not an address`);
351
961
  }
352
962
  if (p.type === "bool") return typeof t === "boolean" ? null : no(`${JSON.stringify(String(t))} is not a boolean`);
353
963
  if (p.type === "string") return typeof t === "string" ? null : no(`${JSON.stringify(String(t))} is not a string`);
@@ -373,15 +983,15 @@ var NO_PLACEHOLDERS = [];
373
983
  function validateCall(abi, call, prefix, kind, allowed) {
374
984
  const c = call ?? {};
375
985
  const named = typeof c.functionName === "string" ? functionsNamed(abi, c.functionName) : [];
376
- if (named.length === 0) bad(`${prefix}.functionName`, `"${String(c.functionName)}" is not a function in the abi`);
377
- if (c.args !== void 0 && !Array.isArray(c.args)) bad(`${prefix}.args`, "must be an array");
378
- if (kind === "mint" && c.args === void 0) bad(`${prefix}.args`, "is required");
986
+ if (named.length === 0) bad2(`${prefix}.functionName`, `"${String(c.functionName)}" is not a function in the abi`);
987
+ if (c.args !== void 0 && !Array.isArray(c.args)) bad2(`${prefix}.args`, "must be an array");
988
+ if (kind === "mint" && c.args === void 0) bad2(`${prefix}.args`, "is required");
379
989
  const args = c.args ?? [];
380
990
  args.forEach((a, i) => validateTemplate(a, `${prefix}.args[${i}]`, allowed));
381
991
  const sameArity = named.filter((f) => f.inputs.length === args.length);
382
992
  if (sameArity.length === 0) {
383
993
  const want = [...new Set(named.map((f) => f.inputs.length))].join(" or ");
384
- bad(`${prefix}.args`, `has ${args.length} argument(s) but "${String(c.functionName)}" takes ${want}`);
994
+ bad2(`${prefix}.args`, `has ${args.length} argument(s) but "${String(c.functionName)}" takes ${want}`);
385
995
  }
386
996
  const checked = sameArity.map((f) => {
387
997
  let issue = null;
@@ -391,75 +1001,75 @@ function validateCall(abi, call, prefix, kind, allowed) {
391
1001
  const fits = checked.filter((x) => !x.issue);
392
1002
  if (fits.length === 0) {
393
1003
  const first = checked[0].issue;
394
- if (sameArity.length === 1) bad(first.path, first.message);
395
- bad(`${prefix}.args`, `fit none of the overloads ${sameArity.map(signature).join(", ")}: ${first.path} ${first.message}`);
1004
+ if (sameArity.length === 1) bad2(first.path, first.message);
1005
+ bad2(`${prefix}.args`, `fit none of the overloads ${sameArity.map(signature).join(", ")}: ${first.path} ${first.message}`);
396
1006
  }
397
1007
  const roleFits = fits.filter(
398
1008
  ({ f }) => kind === "read" ? f.stateMutability === "view" || f.stateMutability === "pure" : f.stateMutability === "payable" || f.stateMutability === "nonpayable"
399
1009
  );
400
1010
  if (roleFits.length === 0) {
401
1011
  const name = fits[0].f.name;
402
- if (kind === "read") bad(`${prefix}.functionName`, `"${name}" is not a view or pure function`);
1012
+ if (kind === "read") bad2(`${prefix}.functionName`, `"${name}" is not a view or pure function`);
403
1013
  if (fits.some(({ f }) => f.stateMutability !== "view" && f.stateMutability !== "pure")) {
404
- bad(`${prefix}.functionName`, `"${name}" has missing or invalid stateMutability; mint requires payable or nonpayable`);
1014
+ bad2(`${prefix}.functionName`, `"${name}" has missing or invalid stateMutability; mint requires payable or nonpayable`);
405
1015
  }
406
- bad(`${prefix}.functionName`, `"${name}" is a view or pure function and cannot mint`);
1016
+ bad2(`${prefix}.functionName`, `"${name}" is a view or pure function and cannot mint`);
407
1017
  }
408
1018
  if (roleFits.length > 1) {
409
- bad(`${prefix}.functionName`, `"${String(c.functionName)}" is ambiguous: ${roleFits.map((x) => signature(x.f)).join(" and ")} both accept these arguments`);
1019
+ bad2(`${prefix}.functionName`, `"${String(c.functionName)}" is ambiguous: ${roleFits.map((x) => signature(x.f)).join(" and ")} both accept these arguments`);
410
1020
  }
411
1021
  return roleFits[0].f;
412
1022
  }
413
1023
  function resolveOutput(fn, output, path) {
414
1024
  const outs = fn.outputs;
415
- if (outs.length === 0) bad(`${path}.functionName`, `"${fn.name}" returns nothing`);
1025
+ if (outs.length === 0) bad2(`${path}.functionName`, `"${fn.name}" returns nothing`);
416
1026
  const first = outs[0];
417
1027
  const tuple = outs.length === 1 && first.type === "tuple";
418
1028
  const members = tuple ? first.components ?? [] : outs;
419
1029
  const memberNames = members.map((m, i) => m.name || String(i)).join(", ");
420
1030
  let index;
421
1031
  if (output === void 0) {
422
- if (members.length !== 1) bad(`${path}.output`, `is required: "${fn.name}" returns several values (${memberNames})`);
1032
+ if (members.length !== 1) bad2(`${path}.output`, `is required: "${fn.name}" returns several values (${memberNames})`);
423
1033
  index = 0;
424
1034
  } else if (typeof output === "number") {
425
1035
  if (!Number.isInteger(output) || output < 0 || output >= members.length) {
426
- bad(`${path}.output`, `${output} is not in the abi outputs of "${fn.name}" (${memberNames})`);
1036
+ bad2(`${path}.output`, `${output} is not in the abi outputs of "${fn.name}" (${memberNames})`);
427
1037
  }
428
1038
  index = output;
429
1039
  } else if (typeof output === "string") {
430
1040
  index = members.findIndex((m) => m.name === output);
431
- if (index < 0) bad(`${path}.output`, `"${output}" is not in the abi outputs of "${fn.name}" (${memberNames})`);
1041
+ if (index < 0) bad2(`${path}.output`, `"${output}" is not in the abi outputs of "${fn.name}" (${memberNames})`);
432
1042
  } else {
433
- return bad(`${path}.output`, "must be an index or a name");
1043
+ return bad2(`${path}.output`, "must be an index or a name");
434
1044
  }
435
1045
  const type = members[index].type;
436
1046
  if (!NUMERIC_TYPE.test(type)) {
437
1047
  const reason = `returns ${type}, not a number`;
438
- if (output === void 0) bad(`${path}.functionName`, `"${fn.name}" ${reason}`);
439
- bad(`${path}.output`, `selects a value that is ${type}, not a number`);
1048
+ if (output === void 0) bad2(`${path}.functionName`, `"${fn.name}" ${reason}`);
1049
+ bad2(`${path}.output`, `selects a value that is ${type}, not a number`);
440
1050
  }
441
1051
  return { tuple, index, type };
442
1052
  }
443
1053
  function validateField(abi, name, src, allowed, isPrice) {
444
- if (typeof src !== "object" || src === null) bad(name, "is required and must be { value } or { read }");
1054
+ if (typeof src !== "object" || src === null) bad2(name, "is required and must be { value } or { read }");
445
1055
  const s = src;
446
1056
  const hasRead = Object.hasOwn(s, "read");
447
1057
  const hasValue = Object.hasOwn(s, "value");
448
- if (hasRead && hasValue) bad(name, "must be exactly one of { value } or { read }, not both");
1058
+ if (hasRead && hasValue) bad2(name, "must be exactly one of { value } or { read }, not both");
449
1059
  if (hasRead) {
450
- if (typeof s.read !== "object" || s.read === null) bad(`${name}.read`, "must be { functionName, args?, output? }");
451
- if (s.unit !== void 0) bad(name, "unit is only valid with a string value");
1060
+ if (typeof s.read !== "object" || s.read === null) bad2(`${name}.read`, "must be { functionName, args?, output? }");
1061
+ if (s.unit !== void 0) bad2(name, "unit is only valid with a string value");
452
1062
  const fn = validateCall(abi, s.read, `${name}.read`, "read", allowed);
453
1063
  resolveOutput(fn, s.read.output, `${name}.read`);
454
1064
  } else if (typeof s.value === "bigint") {
455
- if (s.unit !== void 0) bad(name, "unit is only valid with a string value");
456
- if (s.value < 0n) bad(`${name}.value`, "must not be negative");
1065
+ if (s.unit !== void 0) bad2(name, "unit is only valid with a string value");
1066
+ if (s.value < 0n) bad2(`${name}.value`, "must not be negative");
457
1067
  } else if (typeof s.value === "string") {
458
- if (s.unit !== "display") bad(name, 'string values need unit: "display"');
459
- if (!isPrice) bad(name, "display units are only valid for price; use a bigint in base units");
460
- if (!DISPLAY_AMOUNT.test(s.value)) bad(`${name}.value`, `"${s.value}" is not a decimal number like "0.01"`);
1068
+ if (s.unit !== "display") bad2(name, 'string values need unit: "display"');
1069
+ if (!isPrice) bad2(name, "display units are only valid for price; use a bigint in base units");
1070
+ if (!DISPLAY_AMOUNT.test(s.value)) bad2(`${name}.value`, `"${s.value}" is not a decimal number like "0.01"`);
461
1071
  } else {
462
- bad(name, 'must be { value: bigint }, { value: string, unit: "display" } (price only) or { read: {...} }');
1072
+ bad2(name, 'must be { value: bigint }, { value: string, unit: "display" } (price only) or { read: {...} }');
463
1073
  }
464
1074
  }
465
1075
  function hasNonzeroStaticPrice(price) {
@@ -469,27 +1079,27 @@ function hasNonzeroStaticPrice(price) {
469
1079
  }
470
1080
  function validateContractConfig(config) {
471
1081
  const c = config;
472
- if (!c || typeof c !== "object") bad("config", "must be an object");
473
- if (c.type !== "contract") bad("type", 'must be "contract"');
474
- if (!Number.isSafeInteger(c.chainId) || c.chainId <= 0) bad("chainId", "must be a positive safe integer");
475
- if (!isHexAddress(c.address)) bad("address", `"${String(c.address)}" is not a valid address`);
1082
+ if (!c || typeof c !== "object") bad2("config", "must be an object");
1083
+ if (c.type !== "contract") bad2("type", 'must be "contract"');
1084
+ if (!Number.isSafeInteger(c.chainId) || c.chainId <= 0) bad2("chainId", "must be a positive safe integer");
1085
+ if (!isHexAddress(c.address)) bad2("address", `"${String(c.address)}" is not a valid address`);
476
1086
  if (c.tokenContract !== void 0 && !isHexAddress(c.tokenContract)) {
477
- bad("tokenContract", `"${String(c.tokenContract)}" is not a valid address`);
1087
+ bad2("tokenContract", `"${String(c.tokenContract)}" is not a valid address`);
478
1088
  }
479
- if (!Array.isArray(c.abi)) bad("abi", "must be an abi array");
1089
+ if (!Array.isArray(c.abi)) bad2("abi", "must be an abi array");
480
1090
  const abi = c.abi;
481
1091
  const mintFn = validateCall(abi, c.mint, "mint", "mint", PLACEHOLDERS);
482
- if (c.price === void 0 || c.price === null) bad("price", "is required");
1092
+ if (c.price === void 0 || c.price === null) bad2("price", "is required");
483
1093
  validateField(abi, "price", c.price, NO_PLACEHOLDERS, true);
484
1094
  const cur = c.price.currency;
485
1095
  if (cur !== "native" && !(typeof cur === "object" && cur !== null && isHexAddress(cur.address))) {
486
- bad("price.currency", 'must be "native" or { address } with a valid ERC20 address');
1096
+ bad2("price.currency", 'must be "native" or { address } with a valid ERC20 address');
487
1097
  }
488
1098
  if (cur === "native" && mintFn.stateMutability === "nonpayable" && hasNonzeroStaticPrice(c.price)) {
489
- bad("price", `is a native price, but "${mintFn.name}" is nonpayable and cannot take value`);
1099
+ bad2("price", `is a native price, but "${mintFn.name}" is nonpayable and cannot take value`);
490
1100
  }
491
1101
  const per = c.price.per;
492
- if (per !== void 0 && per !== "unit" && per !== "total") bad("price.per", 'must be "unit" or "total"');
1102
+ if (per !== void 0 && per !== "unit" && per !== "total") bad2("price.per", 'must be "unit" or "total"');
493
1103
  validateOptional(abi, "totalMinted", c.totalMinted, NO_PLACEHOLDERS);
494
1104
  validateOptional(abi, "maxSupply", c.maxSupply, NO_PLACEHOLDERS);
495
1105
  validateOptional(abi, "startTime", c.startTime, NO_PLACEHOLDERS);
@@ -504,7 +1114,7 @@ function varFor(token, vars) {
504
1114
  const key = token.slice(1, -1);
505
1115
  const v = vars[key];
506
1116
  if (v === void 0) throw new MintError("INVALID_CONFIG", `placeholder ${token} has no value here`);
507
- return typeof v === "string" ? getAddress2(v) : v;
1117
+ return typeof v === "string" ? getAddress4(v) : v;
508
1118
  }
509
1119
  function fill(t, p, vars) {
510
1120
  const arr = ARRAY_TYPE.exec(p.type);
@@ -519,38 +1129,38 @@ function fill(t, p, vars) {
519
1129
  }
520
1130
  var fillArgs = (args, inputs, vars) => (args ?? []).map((a, i) => fill(a, inputs[i], vars));
521
1131
  var totalFor = (per, price, quantity) => per === "total" ? price : price * quantity;
522
- function shortMessage(e) {
523
- return e instanceof BaseError ? e.shortMessage : e instanceof Error ? e.message : String(e);
1132
+ function shortMessage2(e) {
1133
+ return e instanceof BaseError2 ? e.shortMessage : e instanceof Error ? e.message : String(e);
524
1134
  }
525
- var abortError = () => new DOMException("The operation was aborted", "AbortError");
526
- var isAbortError = (e) => e?.name === "AbortError";
527
- function throwIfAborted(ctx) {
528
- if (ctx.signal?.aborted) throw abortError();
1135
+ var abortError2 = () => new DOMException("The operation was aborted", "AbortError");
1136
+ var isAbortError2 = (e) => e?.name === "AbortError";
1137
+ function throwIfAborted2(ctx) {
1138
+ if (ctx.signal?.aborted) throw abortError2();
529
1139
  }
530
- function io(ctx, start) {
1140
+ function io2(ctx, start) {
531
1141
  const signal = ctx.signal;
532
1142
  if (!signal) return start();
533
- if (signal.aborted) return Promise.reject(abortError());
1143
+ if (signal.aborted) return Promise.reject(abortError2());
534
1144
  return new Promise((resolve, reject) => {
535
- const onAbort = () => reject(abortError());
1145
+ const onAbort = () => reject(abortError2());
536
1146
  signal.addEventListener("abort", onAbort, { once: true });
537
1147
  start().then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
538
1148
  });
539
1149
  }
540
- function rpcError(e) {
541
- if (isMintError(e) || isAbortError(e)) throw e;
542
- throw new MintError("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
1150
+ function rpcError2(e) {
1151
+ if (isMintError(e) || isAbortError2(e)) throw e;
1152
+ throw new MintError("RPC_ERROR", `RPC request failed: ${shortMessage2(e)}`, { cause: e });
543
1153
  }
544
1154
  function classifyReadError(e, field) {
545
- if (isMintError(e) || isAbortError(e)) throw e;
546
- if (e instanceof BaseError && e.walk((x) => x instanceof ContractFunctionRevertedError || x instanceof ContractFunctionZeroDataError)) {
1155
+ if (isMintError(e) || isAbortError2(e)) throw e;
1156
+ if (e instanceof BaseError2 && e.walk((x) => x instanceof ContractFunctionRevertedError2 || x instanceof ContractFunctionZeroDataError2)) {
547
1157
  throw new MintError("INVALID_CONFIG", `${field} read reverted or returned no data: ${e.shortMessage}`, { field, cause: e });
548
1158
  }
549
- return rpcError(e);
1159
+ return rpcError2(e);
550
1160
  }
551
1161
  async function readCall(ctx, params, field) {
552
1162
  try {
553
- return await io(ctx, () => ctx.client.readContract(params));
1163
+ return await io2(ctx, () => ctx.client.readContract(params));
554
1164
  } catch (e) {
555
1165
  return classifyReadError(e, field);
556
1166
  }
@@ -589,14 +1199,14 @@ function toSeconds(v, field) {
589
1199
  if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new MintError("INVALID_CONFIG", `${field} is too large for a unix timestamp`, { field });
590
1200
  return Number(v);
591
1201
  }
592
- function nativeMeta(ctx) {
1202
+ function nativeMeta2(ctx) {
593
1203
  const n = ctx.client.chain?.nativeCurrency;
594
1204
  return { decimals: n?.decimals ?? 18, symbol: n?.symbol ?? "ETH" };
595
1205
  }
596
- var erc20Of = (config) => config.price.currency === "native" ? null : getAddress2(config.price.currency.address);
1206
+ var erc20Of = (config) => config.price.currency === "native" ? null : getAddress4(config.price.currency.address);
597
1207
  async function currencyMeta(ctx, config) {
598
1208
  const token = erc20Of(config);
599
- if (!token) return { token, ...nativeMeta(ctx) };
1209
+ if (!token) return { token, ...nativeMeta2(ctx) };
600
1210
  const field = "price.currency.address";
601
1211
  const [symbol, decimals] = await Promise.all([
602
1212
  readCall(ctx, { address: token, abi: ERC20_ABI, functionName: "symbol" }, field),
@@ -621,13 +1231,13 @@ async function resolvePrice(ctx, config, meta) {
621
1231
  if (typeof value === "bigint") return value;
622
1232
  return parseDisplay(value, (meta ?? await currencyMeta(ctx, config)).decimals);
623
1233
  }
624
- var money = (value, decimals, symbol) => ({
1234
+ var money2 = (value, decimals, symbol) => ({
625
1235
  value,
626
1236
  decimals,
627
1237
  symbol,
628
- formatted: formatUnits2(value, decimals)
1238
+ formatted: formatUnits3(value, decimals)
629
1239
  });
630
- function revertData(e) {
1240
+ function revertData2(e) {
631
1241
  for (let cur = e, depth = 0; cur && depth < 12; depth++) {
632
1242
  const d = cur.data;
633
1243
  if (typeof d === "string" && d.startsWith("0x") && d.length >= 10) return d;
@@ -641,7 +1251,7 @@ function revertData(e) {
641
1251
  }
642
1252
  function describeRevert(abi, data) {
643
1253
  try {
644
- const d = decodeErrorResult({ abi, data });
1254
+ const d = decodeErrorResult2({ abi, data });
645
1255
  const args = d.args ?? [];
646
1256
  if (d.errorName === "Error") return String(args[0] ?? "execution reverted");
647
1257
  const inputs = d.abiItem?.inputs ?? [];
@@ -653,19 +1263,19 @@ function describeRevert(abi, data) {
653
1263
  }
654
1264
  function toSimulationError(e, abi) {
655
1265
  if (isMintError(e)) return e;
656
- if (isAbortError(e)) throw e;
657
- if (e instanceof BaseError && e.walk((x) => x instanceof InsufficientFundsError)) {
1266
+ if (isAbortError2(e)) throw e;
1267
+ if (e instanceof BaseError2 && e.walk((x) => x instanceof InsufficientFundsError2)) {
658
1268
  return new MintError("INSUFFICIENT_FUNDS", `Payer cannot cover the mint: ${e.shortMessage}`, { cause: e });
659
1269
  }
660
- const data = revertData(e);
1270
+ const data = revertData2(e);
661
1271
  if (data) return new MintError("SIMULATION_REVERTED", describeRevert(abi, data), { cause: e });
662
- const isRevert = e instanceof BaseError && e.walk((x) => x.code === 3 || /execution reverted/i.test(x.message));
663
- if (isRevert) return new MintError("SIMULATION_REVERTED", shortMessage(e), { cause: e });
664
- return new MintError("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
1272
+ const isRevert = e instanceof BaseError2 && e.walk((x) => x.code === 3 || /execution reverted/i.test(x.message));
1273
+ if (isRevert) return new MintError("SIMULATION_REVERTED", shortMessage2(e), { cause: e });
1274
+ return new MintError("RPC_ERROR", `RPC request failed: ${shortMessage2(e)}`, { cause: e });
665
1275
  }
666
1276
  async function simulateMint(ctx, config, call) {
667
1277
  try {
668
- await io(ctx, () => ctx.client.call({ account: call.payer, to: call.to, data: call.data, value: call.value }));
1278
+ await io2(ctx, () => ctx.client.call({ account: call.payer, to: call.to, data: call.data, value: call.value }));
669
1279
  } catch (e) {
670
1280
  throw toSimulationError(e, config.abi);
671
1281
  }
@@ -673,24 +1283,24 @@ async function simulateMint(ctx, config, call) {
673
1283
  function encodeMint(config, vars) {
674
1284
  const fn = validateCall(config.abi, config.mint, "mint", "mint", PLACEHOLDERS);
675
1285
  try {
676
- return encodeFunctionData({ abi: [fn], functionName: fn.name, args: fillArgs(config.mint.args, fn.inputs, vars) });
1286
+ return encodeFunctionData2({ abi: [fn], functionName: fn.name, args: fillArgs(config.mint.args, fn.inputs, vars) });
677
1287
  } catch (e) {
678
1288
  if (isMintError(e)) throw e;
679
- throw new MintError("INVALID_CONFIG", `mint.args cannot be encoded for ${signature(fn)}: ${shortMessage(e)}`, { field: "mint.args", cause: e });
1289
+ throw new MintError("INVALID_CONFIG", `mint.args cannot be encoded for ${signature(fn)}: ${shortMessage2(e)}`, { field: "mint.args", cause: e });
680
1290
  }
681
1291
  }
682
1292
  function mintValue(config, token, totalPrice) {
683
1293
  if (token) return 0n;
684
1294
  const fn = validateCall(config.abi, config.mint, "mint", "mint", PLACEHOLDERS);
685
1295
  if (fn.stateMutability === "nonpayable") {
686
- if (totalPrice > 0n) bad("price", `is ${totalPrice} wei in native currency, but "${fn.name}" is nonpayable and cannot take value`);
1296
+ if (totalPrice > 0n) bad2("price", `is ${totalPrice} wei in native currency, but "${fn.name}" is nonpayable and cannot take value`);
687
1297
  return 0n;
688
1298
  }
689
1299
  return totalPrice;
690
1300
  }
691
- async function readDrop(ctx, config) {
1301
+ async function readDrop2(ctx, config) {
692
1302
  validateContractConfig(config);
693
- throwIfAborted(ctx);
1303
+ throwIfAborted2(ctx);
694
1304
  const meta = await currencyMeta(ctx, config);
695
1305
  const none = {};
696
1306
  const [price, totalMinted, maxSupply, start, end] = await Promise.all([
@@ -701,11 +1311,11 @@ async function readDrop(ctx, config) {
701
1311
  optField(ctx, config, "endTime", config.endTime, none)
702
1312
  ]);
703
1313
  mintValue(config, meta.token, price);
704
- const native = nativeMeta(ctx);
1314
+ const native = nativeMeta2(ctx);
705
1315
  return {
706
1316
  chainId: config.chainId,
707
- unitPrice: money(price, meta.decimals, meta.symbol),
708
- unitFee: money(0n, native.decimals, native.symbol),
1317
+ unitPrice: money2(price, meta.decimals, meta.symbol),
1318
+ unitFee: money2(0n, native.decimals, native.symbol),
709
1319
  totalMinted: totalMinted ?? 0n,
710
1320
  maxSupply: maxSupply === null || maxSupply === 0n ? null : maxSupply,
711
1321
  startTime: toSeconds(start, "startTime"),
@@ -715,9 +1325,9 @@ async function readDrop(ctx, config) {
715
1325
  pricePer: config.price.per ?? "unit"
716
1326
  };
717
1327
  }
718
- async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
1328
+ async function readWallet2(ctx, config, { payer, recipient, quantity, drop }) {
719
1329
  validateContractConfig(config);
720
- throwIfAborted(ctx);
1330
+ throwIfAborted2(ctx);
721
1331
  const qty = BigInt(quantity);
722
1332
  const unitPrice = drop.unitPrice.value;
723
1333
  const totalPrice = totalFor(drop.pricePer, unitPrice, qty);
@@ -725,7 +1335,7 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
725
1335
  const [walletMinted, rawMax, native, erc20] = await Promise.all([
726
1336
  optField(ctx, config, "walletMinted", config.walletMinted, vars),
727
1337
  optField(ctx, config, "walletMax", config.walletMax, vars),
728
- io(ctx, () => ctx.client.getBalance({ address: payer })).catch(rpcError),
1338
+ io2(ctx, () => ctx.client.getBalance({ address: payer })).catch(rpcError2),
729
1339
  drop.paymentToken ? readCall(ctx, { address: drop.paymentToken, abi: ERC20_ABI, functionName: "balanceOf", args: [payer] }, "price.currency.address").then(
730
1340
  (v) => toBigInt(v, "price.currency.address")
731
1341
  ) : Promise.resolve(null)
@@ -738,10 +1348,10 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
738
1348
  if (remaining === 0n) {
739
1349
  ineligible = { reason: "WALLET_LIMIT", message: `This wallet has already minted its limit of ${walletMax}.` };
740
1350
  } else if (drop.paymentToken === null && native >= totalPrice) {
741
- const call = { payer, to: getAddress2(config.address), data: encodeMint(config, vars), value: mintValue(config, null, totalPrice) };
1351
+ const call = { payer, to: getAddress4(config.address), data: encodeMint(config, vars), value: mintValue(config, null, totalPrice) };
742
1352
  try {
743
1353
  await simulateMint(ctx, config, call);
744
- gas = await io(ctx, () => ctx.client.estimateGas({ account: payer, to: call.to, data: call.data, value: call.value })).catch((e) => {
1354
+ gas = await io2(ctx, () => ctx.client.estimateGas({ account: payer, to: call.to, data: call.data, value: call.value })).catch((e) => {
745
1355
  throw toSimulationError(e, config.abi);
746
1356
  });
747
1357
  } catch (e) {
@@ -750,7 +1360,7 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
750
1360
  }
751
1361
  }
752
1362
  if (drop.paymentToken) gas += APPROVE_GAS;
753
- const gasPrice = await io(ctx, () => ctx.client.getGasPrice()).catch(rpcError);
1363
+ const gasPrice = await io2(ctx, () => ctx.client.getGasPrice()).catch(rpcError2);
754
1364
  return {
755
1365
  walletMinted,
756
1366
  walletMax,
@@ -761,15 +1371,15 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
761
1371
  gasReserve: gas * gasPrice
762
1372
  };
763
1373
  }
764
- async function buildPlan(ctx, attempt, wallet) {
1374
+ async function buildPlan2(ctx, attempt, wallet) {
765
1375
  void wallet;
766
1376
  const { config, payer, recipient } = attempt;
767
1377
  validateContractConfig(config);
768
- throwIfAborted(ctx);
1378
+ throwIfAborted2(ctx);
769
1379
  const qty = BigInt(attempt.quantity);
770
1380
  const unitPrice = await resolvePrice(ctx, config);
771
1381
  const totalPrice = totalFor(config.price.per ?? "unit", unitPrice, qty);
772
- const to = getAddress2(config.address);
1382
+ const to = getAddress4(config.address);
773
1383
  const token = erc20Of(config);
774
1384
  const mint = {
775
1385
  to,
@@ -787,21 +1397,23 @@ async function buildPlan(ctx, attempt, wallet) {
787
1397
  token,
788
1398
  spender: to,
789
1399
  amount: totalPrice,
790
- tx: { to: token, data: encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [to, totalPrice] }), value: 0n }
1400
+ tx: { to: token, data: encodeFunctionData2({ abi: ERC20_ABI, functionName: "approve", args: [to, totalPrice] }), value: 0n }
791
1401
  };
792
1402
  }
793
1403
  }
794
- return { approve, mint, tokenContract: getAddress2(attempt.tokenContract) };
1404
+ return { approve, mint, tokenContract: getAddress4(attempt.tokenContract) };
795
1405
  }
796
- async function simulate(ctx, attempt, plan) {
797
- throwIfAborted(ctx);
1406
+ async function simulate2(ctx, attempt, plan) {
1407
+ throwIfAborted2(ctx);
798
1408
  await simulateMint(ctx, attempt.config, { payer: attempt.payer, to: plan.mint.to, data: plan.mint.data, value: plan.mint.value });
799
1409
  }
800
- var contractAdapter = { readDrop, readWallet, buildPlan, simulate };
1410
+ var contractAdapter = { readDrop: readDrop2, readWallet: readWallet2, buildPlan: buildPlan2, simulate: simulate2 };
801
1411
 
802
1412
  // src/react/useMint.ts
803
1413
  var REFRESH_MS = 3e4;
804
1414
  var TICK_MS = 1e3;
1415
+ var BOUNDARY_RETRY_MS = 3e3;
1416
+ var BOUNDARY_RETRY_MAX = 10;
805
1417
  var ASYNC_STATES = ["loading", "connecting", "switching-chain", "approving", "minting", "confirming"];
806
1418
  function isAsyncState(name) {
807
1419
  return ASYNC_STATES.includes(name);
@@ -811,7 +1423,18 @@ function configKeyOf(config) {
811
1423
  return JSON.stringify(config, (_k, v) => typeof v === "bigint" ? { __dropkitBigInt: v.toString() } : v);
812
1424
  }
813
1425
  function adapterFor(config) {
814
- return config.type === "manifold-claim" ? manifoldClaimAdapter : contractAdapter;
1426
+ switch (config.type) {
1427
+ case "manifold-claim":
1428
+ return manifoldClaimAdapter;
1429
+ case "contract":
1430
+ return contractAdapter;
1431
+ case "tl-stacks":
1432
+ return tlStacksAdapter;
1433
+ default: {
1434
+ const unreachable = config;
1435
+ return unreachable;
1436
+ }
1437
+ }
815
1438
  }
816
1439
  var bridgeEnabled = (config) => config.type === "manifold-claim";
817
1440
  function payChainsOf(config, option) {
@@ -834,10 +1457,32 @@ var symbolOf = (chainId) => {
834
1457
  };
835
1458
  var shortOf = (chainId) => ({ chainId, symbol: symbolOf(chainId), name: chainName(chainId) });
836
1459
  function tokenContractOf(config) {
837
- return config.type === "manifold-claim" ? config.creatorContract : config.tokenContract ?? config.address;
1460
+ switch (config.type) {
1461
+ case "manifold-claim":
1462
+ return config.creatorContract;
1463
+ case "contract":
1464
+ return config.tokenContract ?? config.address;
1465
+ case "tl-stacks":
1466
+ return config.nftContract;
1467
+ default: {
1468
+ const unreachable = config;
1469
+ return unreachable;
1470
+ }
1471
+ }
838
1472
  }
839
1473
  function eventAddressOf(config) {
840
- return config.type === "manifold-claim" ? config.creatorContract : config.address;
1474
+ switch (config.type) {
1475
+ case "manifold-claim":
1476
+ return config.creatorContract;
1477
+ case "contract":
1478
+ return config.address;
1479
+ case "tl-stacks":
1480
+ return config.nftContract;
1481
+ default: {
1482
+ const unreachable = config;
1483
+ return unreachable;
1484
+ }
1485
+ }
841
1486
  }
842
1487
  var isUnsupported = (reason) => UNSUPPORTED_REASONS.includes(reason);
843
1488
  function errorReasonOf(e) {
@@ -870,6 +1515,7 @@ function useMint(options) {
870
1515
  const accountKeyRef = useRef(null);
871
1516
  const connectingRef = useRef(false);
872
1517
  const pendingRefreshRef = useRef(false);
1518
+ const boundaryRetryRef = useRef(null);
873
1519
  const pendingQuantityRef = useRef(null);
874
1520
  const widgetFailRef = useRef(null);
875
1521
  const widgetLoadRef = useRef(null);
@@ -925,7 +1571,7 @@ function useMint(options) {
925
1571
  }),
926
1572
  [clientFor]
927
1573
  );
928
- const readDrop2 = useCallback(
1574
+ const readDrop3 = useCallback(
929
1575
  async (life, gen, cfg) => {
930
1576
  const adapter = adapterFor(cfg);
931
1577
  try {
@@ -950,9 +1596,9 @@ function useMint(options) {
950
1596
  const life = { key, controller: new AbortController(), cacheScope: {}, gen };
951
1597
  lifeRef.current = life;
952
1598
  dispatch({ type: "LOAD", gen, kind: "config" });
953
- void readDrop2(life, gen, cfg);
1599
+ void readDrop3(life, gen, cfg);
954
1600
  },
955
- [dispatch, readDrop2]
1601
+ [dispatch, readDrop3]
956
1602
  );
957
1603
  const refreshNow = useCallback(
958
1604
  async (kind = "refresh") => {
@@ -965,9 +1611,9 @@ function useMint(options) {
965
1611
  const gen = ++genRef.current;
966
1612
  life.gen = gen;
967
1613
  dispatch({ type: "LOAD", gen, kind });
968
- await readDrop2(life, gen, propsRef.current.config);
1614
+ await readDrop3(life, gen, propsRef.current.config);
969
1615
  },
970
- [dispatch, readDrop2]
1616
+ [dispatch, readDrop3]
971
1617
  );
972
1618
  const refresh = useCallback(() => refreshNow("refresh"), [refreshNow]);
973
1619
  const isBusy = useCallback(
@@ -1043,7 +1689,7 @@ function useMint(options) {
1043
1689
  }
1044
1690
  } catch (e) {
1045
1691
  if (isMintError(e)) throw e;
1046
- const reverted = e instanceof BaseError2 ? e.walk((cause) => cause instanceof ExecutionRevertedError) : null;
1692
+ const reverted = e instanceof BaseError3 ? e.walk((cause) => cause instanceof ExecutionRevertedError) : null;
1047
1693
  if (reverted instanceof ExecutionRevertedError) {
1048
1694
  throw new MintError("SIMULATION_REVERTED", reverted.shortMessage);
1049
1695
  }
@@ -1081,6 +1727,7 @@ function useMint(options) {
1081
1727
  assertPayer();
1082
1728
  dispatch({ type: "MINT_PROMPTED", attemptId: attempt.attemptId });
1083
1729
  const hash = await submit(plan.mint);
1730
+ if (cfg.type === "manifold-claim") void recordClaimMint({ instanceId: cfg.instanceId, hash });
1084
1731
  assertActive();
1085
1732
  dispatch({ type: "TX_SUBMITTED", attemptId: attempt.attemptId });
1086
1733
  emit("tx-submitted", { state: "confirming", reason: null, txHash: hash, quantity: attempt.quantity, chainId: attempt.chainId });
@@ -1094,7 +1741,7 @@ function useMint(options) {
1094
1741
  tokenContract: plan.tokenContract ?? attempt.tokenContract,
1095
1742
  recipient: attempt.recipient
1096
1743
  });
1097
- const result = { txHash: confirmedHash, explorerUrl: explorerUrlFor(attempt.chainId, confirmedHash), tokens };
1744
+ const result = { txHash: confirmedHash, explorerUrl: explorerUrlFor(attempt.chainId, confirmedHash), tokens, requested: attempt.quantity };
1098
1745
  dispatch({ type: "ATTEMPT_SUCCEEDED", attemptId: attempt.attemptId, result });
1099
1746
  emit("success", { state: "success", reason: null, txHash: confirmedHash, quantity: attempt.quantity, chainId: attempt.chainId });
1100
1747
  },
@@ -1127,6 +1774,7 @@ function useMint(options) {
1127
1774
  throw new MintError("BRIDGE_FAILED", `Relay could not complete the mint paid on ${where}${why}.${noRefund}`);
1128
1775
  }
1129
1776
  const fillHash = status.txHashes[0] ?? null;
1777
+ if (fillHash && cfg.type === "manifold-claim") void recordClaimMint({ instanceId: cfg.instanceId, hash: fillHash });
1130
1778
  let tokens = [];
1131
1779
  if (fillHash) {
1132
1780
  try {
@@ -1143,6 +1791,7 @@ function useMint(options) {
1143
1791
  txHash,
1144
1792
  explorerUrl: explorerUrlFor(fillHash ? cfg.chainId : out.originChainId, txHash),
1145
1793
  tokens,
1794
+ requested: attempt.quantity,
1146
1795
  relay: { requestId: out.requestId, originTxHash: out.originTxHash, originChainId: out.originChainId }
1147
1796
  };
1148
1797
  clearOutstanding(key);
@@ -1298,7 +1947,7 @@ function useMint(options) {
1298
1947
  if (life2) life2.gen = gen;
1299
1948
  dispatch({ type: "RESET", gen });
1300
1949
  dispatch({ type: "LOAD", gen, kind: "config" });
1301
- if (life2) void readDrop2(life2, gen, propsRef.current.config);
1950
+ if (life2) void readDrop3(life2, gen, propsRef.current.config);
1302
1951
  return;
1303
1952
  }
1304
1953
  if (s.name !== "live") return;
@@ -1332,7 +1981,7 @@ function useMint(options) {
1332
1981
  } finally {
1333
1982
  attemptRef.current = null;
1334
1983
  }
1335
- }, [dispatch, emit, readDrop2, executeAttempt, executeRelayAttempt, resumeOutstanding, refreshNow]);
1984
+ }, [dispatch, emit, readDrop3, executeAttempt, executeRelayAttempt, resumeOutstanding, refreshNow]);
1336
1985
  const mint = useCallback(() => {
1337
1986
  void runMint();
1338
1987
  }, [runMint]);
@@ -1340,6 +1989,8 @@ function useMint(options) {
1340
1989
  mounted.current = true;
1341
1990
  return () => {
1342
1991
  mounted.current = false;
1992
+ if (boundaryRetryRef.current) clearTimeout(boundaryRetryRef.current);
1993
+ boundaryRetryRef.current = null;
1343
1994
  lifeRef.current?.controller.abort();
1344
1995
  lifeRef.current = null;
1345
1996
  };
@@ -1541,18 +2192,37 @@ function useMint(options) {
1541
2192
  document.removeEventListener("visibilitychange", onVisible);
1542
2193
  };
1543
2194
  }, [refreshNow]);
1544
- const boundary = machine.drop ? [machine.drop.startTime, machine.drop.endTime].some((t) => t !== null && t > machine.now) : false;
2195
+ const retryWhileStale = useCallback(
2196
+ (staleKey, life) => {
2197
+ if (staleKey === void 0) return;
2198
+ const step = (tries) => {
2199
+ if (tries >= BOUNDARY_RETRY_MAX || !mounted.current || lifeRef.current !== life || stateRef.current.drop?.walletKey !== staleKey) return;
2200
+ if (boundaryRetryRef.current) clearTimeout(boundaryRetryRef.current);
2201
+ boundaryRetryRef.current = setTimeout(() => {
2202
+ boundaryRetryRef.current = null;
2203
+ if (!mounted.current || lifeRef.current !== life) return;
2204
+ void refreshNow().then(() => step(tries + 1));
2205
+ }, BOUNDARY_RETRY_MS);
2206
+ };
2207
+ step(0);
2208
+ },
2209
+ [refreshNow]
2210
+ );
2211
+ const boundary = machine.drop ? [machine.drop.startTime, machine.drop.endTime, machine.drop.phaseEndsAt ?? null].some((t) => t !== null && t > machine.now) : false;
1545
2212
  useEffect(() => {
1546
2213
  if (!boundary) return;
1547
2214
  const timer = setInterval(() => {
1548
2215
  const s = stateRef.current;
1549
2216
  const now = nowSec();
1550
- const crossed = s.drop && [s.drop.startTime, s.drop.endTime].some((t) => t !== null && t > s.now && t <= now);
2217
+ const crossed = s.drop && [s.drop.startTime, s.drop.endTime, s.drop.phaseEndsAt ?? null].some((t) => t !== null && t > s.now && t <= now);
1551
2218
  dispatch({ type: "TICK", now });
1552
- if (crossed) void refreshNow();
2219
+ if (crossed) {
2220
+ const life = lifeRef.current;
2221
+ void refreshNow().then(() => life && retryWhileStale(s.drop?.walletKey, life));
2222
+ }
1553
2223
  }, TICK_MS);
1554
2224
  return () => clearInterval(timer);
1555
- }, [boundary, dispatch, refreshNow]);
2225
+ }, [boundary, dispatch, refreshNow, retryWhileStale]);
1556
2226
  const prevName = useRef(null);
1557
2227
  useEffect(() => {
1558
2228
  const name = widgetFail ? isUnsupported(widgetFail.reason) ? "unsupported" : "error" : machine.name;
@@ -1613,13 +2283,13 @@ function useMint(options) {
1613
2283
 
1614
2284
  // src/react/PayWithPicker.ts
1615
2285
  import { createElement, useCallback as useCallback2, useEffect as useEffect2, useState as useState2 } from "react";
1616
- import { formatUnits as formatUnits3 } from "viem";
2286
+ import { formatUnits as formatUnits4 } from "viem";
1617
2287
  var PICKER_REFRESH_MS = 2e4;
1618
2288
  var PICKER_DEBOUNCE_MS = 500;
1619
2289
  var RELAY_REASONS = /* @__PURE__ */ new Set(["BRIDGE_UNAVAILABLE", "BRIDGE_TIMEOUT", "BRIDGE_REFUNDED", "BRIDGE_FAILED"]);
1620
- var money2 = (value, chainId) => {
2290
+ var money3 = (value, chainId) => {
1621
2291
  const c = getChain(chainId).nativeCurrency;
1622
- return { value, decimals: c.decimals, symbol: c.symbol, formatted: formatUnits3(value, c.decimals) };
2292
+ return { value, decimals: c.decimals, symbol: c.symbol, formatted: formatUnits4(value, c.decimals) };
1623
2293
  };
1624
2294
  function usePayOptions(mint, onSelect) {
1625
2295
  const info = mint.crossChain;
@@ -1695,7 +2365,7 @@ function usePayOptions(mint, onSelect) {
1695
2365
  isDropChain,
1696
2366
  relayFee: isDropChain ? null : quoted?.relayFee ?? null,
1697
2367
  amountIn: isDropChain ? null : quoted?.amountIn ?? null,
1698
- balance: balance && balance.chainId === chainId && chainId === current ? money2(balance.value, chainId) : null,
2368
+ balance: balance && balance.chainId === chainId && chainId === current ? money3(balance.value, chainId) : null,
1699
2369
  loading: !isDropChain && q === void 0,
1700
2370
  select: () => select(chainId)
1701
2371
  };
@@ -1806,7 +2476,7 @@ function MintButton(props) {
1806
2476
  }
1807
2477
 
1808
2478
  // src/index.ts
1809
- var VERSION = "0.3.0";
2479
+ var VERSION = "0.4.1";
1810
2480
  export {
1811
2481
  CLICKABLE_STATES,
1812
2482
  MAX_QUANTITY,