@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.js CHANGED
@@ -1,391 +1,40 @@
1
+ import {
2
+ CLICKABLE_STATES,
3
+ IN_FLIGHT_STATES,
4
+ MAX_QUANTITY,
5
+ MINT_STATES,
6
+ MintError,
7
+ REASON_CODES,
8
+ UNSUPPORTED_REASONS,
9
+ canAct,
10
+ chainName,
11
+ createReadClient,
12
+ friendlyErrorMessage,
13
+ getAccount,
14
+ getChain,
15
+ getConnectedBalance,
16
+ getWalletClient,
17
+ initialState,
18
+ isMintError,
19
+ loadConnectWidget,
20
+ manifoldClaimAdapter,
21
+ openConnectModal,
22
+ parseMintReceipt,
23
+ reducer,
24
+ selectMaxQuantity,
25
+ selectTotal,
26
+ subscribeAccount,
27
+ switchToChain,
28
+ toReason,
29
+ waitForDeposit
30
+ } from "./chunk-3PA74M2L.js";
31
+
1
32
  // src/react/useMint.ts
2
33
  import { useCallback, useEffect, useReducer, useRef, useState } from "react";
3
- import { BaseError as BaseError3, ExecutionRevertedError, publicActions as publicActions2 } from "viem";
4
-
5
- // src/core/rpc/index.ts
6
- import { createPublicClient, http } from "viem";
7
- import { apeChain, base, baseSepolia, mainnet, optimism, sepolia, shape } from "viem/chains";
8
-
9
- // src/core/errors.ts
10
- var UNSUPPORTED_REASONS = [
11
- "UNKNOWN_EXTENSION",
12
- "AMBIGUOUS_EXTENSION",
13
- "CLAIM_NOT_FOUND",
14
- "SIGNATURE_CLAIM",
15
- "INVALID_CONFIG",
16
- "CONNECT_WIDGET_TOO_OLD"
17
- ];
18
- var INELIGIBLE_REASONS = ["NOT_ON_ALLOWLIST", "ALLOWLIST_USED", "WALLET_LIMIT", "SIMULATION_REVERTED"];
19
- var ERROR_REASONS = [
20
- "USER_REJECTED",
21
- "TX_REVERTED",
22
- "RATE_LIMITED",
23
- "RPC_ERROR",
24
- "CHAIN_SWITCH_FAILED",
25
- "ALLOWLIST_UNAVAILABLE",
26
- // Relay cross-chain mint (spec relay-cross-chain-mint #execute-click).
27
- "BRIDGE_UNAVAILABLE",
28
- "BRIDGE_REFUNDED",
29
- "BRIDGE_FAILED",
30
- "BRIDGE_TIMEOUT"
31
- ];
32
- var FUNDS_REASONS = ["INSUFFICIENT_FUNDS"];
33
- var REASON_CODES = [
34
- ...UNSUPPORTED_REASONS,
35
- ...INELIGIBLE_REASONS,
36
- ...ERROR_REASONS,
37
- ...FUNDS_REASONS
38
- ];
39
- var MintError = class extends Error {
40
- reason;
41
- /** INVALID_CONFIG only: dotted path of the bad field, e.g. "mint.args[1]" or "price". */
42
- field;
43
- /** 'relay': the message is Relay's decoded destination revert, shown as-is. */
44
- domain;
45
- constructor(reason, message, opts) {
46
- super(message, opts?.cause === void 0 ? void 0 : { cause: opts.cause });
47
- this.name = "MintError";
48
- this.reason = reason;
49
- if (opts?.field !== void 0) this.field = opts.field;
50
- if (opts?.domain !== void 0) this.domain = opts.domain;
51
- }
52
- };
53
- function isMintError(e) {
54
- return e instanceof MintError;
55
- }
56
-
57
- // src/core/rpc/index.ts
58
- var BRIDGE_URLS = {
59
- 1: "https://bridge.manifoldxyz.dev/rpc",
60
- 11155111: "https://sepolia.bridge.manifoldxyz.dev/rpc",
61
- 8453: "https://base.bridge.manifoldxyz.dev/rpc",
62
- 10: "https://optimism.bridge.manifoldxyz.dev/rpc",
63
- 360: "https://shape.bridge.manifoldxyz.dev/rpc",
64
- 33139: "https://apechain.bridge.manifoldxyz.dev/rpc"
65
- };
66
- var CHAINS = {
67
- [mainnet.id]: mainnet,
68
- [sepolia.id]: sepolia,
69
- [base.id]: base,
70
- [optimism.id]: optimism,
71
- [shape.id]: shape,
72
- [apeChain.id]: apeChain,
73
- // Relay pay chain for Sepolia drops only: never a drop chain, no Manifold bridge.
74
- [baseSepolia.id]: baseSepolia
75
- };
76
- var CHAIN_NAMES = {
77
- 1: "Ethereum",
78
- 8453: "Base",
79
- 10: "Optimism",
80
- 360: "Shape",
81
- 33139: "ApeChain",
82
- 11155111: "Sepolia",
83
- 84532: "Base Sepolia"
84
- };
85
- function chainName(chainId) {
86
- return CHAIN_NAMES[chainId] ?? CHAINS[chainId]?.name ?? `chain ${String(chainId)}`;
87
- }
88
- var TRANSPORT_TIMEOUT_MS = 8e3;
89
- function getChain(chainId) {
90
- const chain = CHAINS[chainId];
91
- if (!chain) {
92
- throw new MintError("INVALID_CONFIG", `chainId ${String(chainId)} is not supported`, { field: "chainId" });
93
- }
94
- return chain;
95
- }
96
- var TERMINAL_CODES = /* @__PURE__ */ new Set([3, -32602, -32003, 4001, 4100, 4200, 4900, 4901, 4902]);
97
- var FALLBACK_CODES = /* @__PURE__ */ new Set([-32700, -32600, -32601, -32001, -32002, -32004, -32005, 429]);
98
- var EXECUTION_WORDING = /execution reverted|execution error|\breverted?\b|out of gas|invalid opcode|insufficient funds|nonce too low|gas required exceeds/i;
99
- 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;
100
- var TRANSPORT_ERROR_NAMES = /* @__PURE__ */ new Set(["HttpRequestError", "TimeoutError", "SocketClosedError", "WebSocketRequestError"]);
101
- function carriesExecutionEvidence(value, seen = /* @__PURE__ */ new Set()) {
102
- if (typeof value === "string") return /^(?:Reverted\s+)?0x(?:[a-f\d]{2})*$/i.test(value) || EXECUTION_WORDING.test(value);
103
- if (!value || typeof value !== "object" || seen.has(value)) return false;
104
- seen.add(value);
105
- const e = value;
106
- if (typeof e.code === "number" && TERMINAL_CODES.has(e.code)) return true;
107
- if (typeof e.message === "string" && EXECUTION_WORDING.test(e.message)) return true;
108
- return ["data", "error", "originalError", "cause", "result"].some((key) => carriesExecutionEvidence(e[key], seen));
109
- }
110
- function shouldFallback(err) {
111
- let retry = false;
112
- const seen = /* @__PURE__ */ new Set();
113
- for (let e = err; e && typeof e === "object" && !seen.has(e); ) {
114
- seen.add(e);
115
- const error = e;
116
- const message = typeof error.details === "string" ? error.details : typeof error.shortMessage !== "string" ? error.message : "";
117
- if (typeof message === "string" && EXECUTION_WORDING.test(message)) return false;
118
- if (carriesExecutionEvidence(error.data)) return false;
119
- if (typeof error.code === "number" && TERMINAL_CODES.has(error.code)) return false;
120
- if (error.name === "ContractFunctionRevertedError" || error.name === "ExecutionRevertedError") return false;
121
- if (typeof error.name === "string" && TRANSPORT_ERROR_NAMES.has(error.name)) retry = true;
122
- if (typeof error.code === "number" && FALLBACK_CODES.has(error.code)) retry = true;
123
- if (typeof message === "string" && UPSTREAM_WORDING.test(message)) retry = true;
124
- e = error.cause;
125
- }
126
- return retry;
127
- }
128
- function createReadClient(opts) {
129
- const chain = getChain(opts.chainId);
130
- const urls = [opts.rpcUrls?.[opts.chainId], opts.useBridge ? BRIDGE_URLS[opts.chainId] : void 0, chain.rpcUrls.default.http[0]].filter(
131
- (u, i, all) => !!u && all.indexOf(u) === i
132
- );
133
- const transport = ({ chain: c, pollingInterval }) => {
134
- const transports = urls.map((url) => http(url, { timeout: TRANSPORT_TIMEOUT_MS, retryCount: 0 })({ chain: c, pollingInterval, retryCount: 0, timeout: TRANSPORT_TIMEOUT_MS }));
135
- const request = (async (args) => {
136
- let last;
137
- for (const t of transports) {
138
- try {
139
- return await t.request(args);
140
- } catch (err) {
141
- if (!shouldFallback(err)) throw err;
142
- last = err;
143
- }
144
- }
145
- console.warn(`dropkit: all RPC endpoints failed for chain ${String(opts.chainId)}; pass rpcUrls={{ ${String(opts.chainId)}: '<your RPC url>' }} to <MintButton>.`);
146
- throw new MintError("RPC_ERROR", `All RPC endpoints failed for chain ${String(opts.chainId)}`, { cause: last });
147
- });
148
- return {
149
- config: { key: "dropkit-fallback", name: "Dropkit fallback", request, retryCount: 0, retryDelay: 0, timeout: TRANSPORT_TIMEOUT_MS, type: "fallback" },
150
- request,
151
- value: {}
152
- };
153
- };
154
- return createPublicClient({ chain, transport });
155
- }
156
-
157
- // src/core/wallet/index.ts
158
- import { createWalletClient, custom, getAddress, publicActions } from "viem";
159
- var CONNECT_WIDGET_VERSION = "6.4.0";
160
- var CONNECT_BASE_URL = `https://connect.manifoldxyz.dev/${CONNECT_WIDGET_VERSION}`;
161
- var CONNECT_ID = "mint-button";
162
- var ADDRESS_CHANGED = "ethereum-address-changed";
163
- var CHAIN_CHANGED = "frontend-provider-chain-changed";
164
- var LOADER_KEY = "__manifoldMintConnectLoader";
165
- var STATE_KEY = "__manifoldMintConnectStateV1";
166
- var win = () => window;
167
- var pageState = () => win()[STATE_KEY] ??= {};
168
- 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.";
169
- var MANIFOLD_HOST = /(^|\.)(manifoldxyz\.dev|manifold\.xyz)$/;
170
- function isManifoldConnectScript(src) {
171
- try {
172
- const url = new URL(src, document.baseURI);
173
- return url.hostname === "connect.manifoldxyz.dev" || MANIFOLD_HOST.test(url.hostname) && /\/connect\.umd[^/]*\.js$/.test(url.pathname);
174
- } catch {
175
- return false;
176
- }
177
- }
178
- function applyState(state) {
179
- if (!state.div) return;
180
- const network = state.networks.join(",");
181
- if (state.div.dataset.network !== network) state.div.dataset.network = network;
182
- if (state.projectId && state.div.dataset.walletConnectProjectId !== state.projectId) state.div.dataset.walletConnectProjectId = state.projectId;
183
- }
184
- function register(state, opts) {
185
- for (const id2 of opts.chainIds) if (!state.networks.includes(id2)) state.networks.push(id2);
186
- const id = opts.walletConnectProjectId;
187
- if (id) {
188
- if (!state.projectId) state.projectId = id;
189
- else if (state.projectId !== id) {
190
- console.warn(`dropkit: walletConnectProjectId "${id}" ignored; this page already uses "${state.projectId}" for the shared connect widget.`);
191
- }
192
- }
193
- applyState(state);
194
- }
195
- function startLoad(state) {
196
- const connect = win().ManifoldConnect;
197
- if (connect?.capabilities?.includes("open")) return Promise.resolve(connect.ready).then(() => void 0);
198
- const hasScript = Array.from(document.querySelectorAll("script[src]")).some((s) => isManifoldConnectScript(s.src));
199
- if (hasScript || document.querySelector('[data-widget="m-connect"]')) {
200
- return Promise.reject(new MintError("CONNECT_WIDGET_TOO_OLD", TOO_OLD));
201
- }
202
- return new Promise((resolve, reject) => {
203
- const css = document.createElement("link");
204
- css.rel = "stylesheet";
205
- css.href = `${CONNECT_BASE_URL}/connect.css`;
206
- document.head.appendChild(css);
207
- state.nodes.push(css);
208
- const div = document.createElement("div");
209
- div.hidden = true;
210
- div.style.display = "none";
211
- div.dataset.widget = "m-connect";
212
- div.dataset.connectId = CONNECT_ID;
213
- div.dataset.autoReconnect = "true";
214
- div.dataset.enableNetworkSwitching = "true";
215
- state.div = div;
216
- applyState(state);
217
- document.body.appendChild(div);
218
- state.nodes.push(div);
219
- const script = document.createElement("script");
220
- script.src = `${CONNECT_BASE_URL}/connect.umd.min.js`;
221
- script.async = true;
222
- script.addEventListener("load", () => {
223
- const ready = win().ManifoldConnect?.ready;
224
- if (!ready) return reject(new MintError("CONNECT_WIDGET_TOO_OLD", TOO_OLD));
225
- Promise.resolve(ready).then(() => resolve(), reject);
226
- });
227
- script.addEventListener("error", () => reject(new MintError("RPC_ERROR", `Could not load the Manifold connect widget from ${CONNECT_BASE_URL}`)));
228
- document.head.appendChild(script);
229
- state.nodes.push(script);
230
- });
231
- }
232
- function loadConnectWidget(opts) {
233
- const w = win();
234
- const page = pageState();
235
- const existing = w[LOADER_KEY];
236
- if (existing) {
237
- if (page.load?.promise !== existing) {
238
- const div = document.querySelector(`[data-widget="m-connect"][data-connect-id="${CONNECT_ID}"]`) ?? void 0;
239
- page.load = {
240
- promise: existing,
241
- networks: div?.dataset.network?.split(",").filter(Boolean).map(Number) ?? [],
242
- projectId: div?.dataset.walletConnectProjectId,
243
- div,
244
- nodes: []
245
- };
246
- }
247
- register(page.load, opts);
248
- return existing;
249
- }
250
- let resolve;
251
- let reject;
252
- const p = new Promise((res, rej) => {
253
- resolve = res;
254
- reject = rej;
255
- });
256
- const state = { promise: p, networks: [], nodes: [] };
257
- page.load = state;
258
- w[LOADER_KEY] = p;
259
- p.catch(() => {
260
- if (w[LOADER_KEY] === p) delete w[LOADER_KEY];
261
- if (page.load === state) page.load = void 0;
262
- for (const node of state.nodes) node.parentNode?.removeChild(node);
263
- state.nodes.length = 0;
264
- state.div = void 0;
265
- });
266
- register(state, opts);
267
- try {
268
- startLoad(state).then(resolve, reject);
269
- } catch (error) {
270
- reject(error);
271
- }
272
- return p;
273
- }
274
- function openConnectModal() {
275
- const page = pageState();
276
- if (page.pendingModal) return page.pendingModal;
277
- const p = new Promise((resolve) => {
278
- const onClosed = (e) => {
279
- const detail = e.detail ?? {};
280
- if (detail.connectId !== void 0 && detail.connectId !== CONNECT_ID) return;
281
- window.removeEventListener("m-connect:closed", onClosed);
282
- page.pendingModal = void 0;
283
- resolve(detail.reason === "connected" ? "connected" : "dismissed");
284
- };
285
- window.addEventListener("m-connect:closed", onClosed);
286
- });
287
- page.pendingModal = p;
288
- window.dispatchEvent(new CustomEvent("m-connect:open", { detail: { connectId: CONNECT_ID } }));
289
- return p;
290
- }
291
- function getAccount() {
292
- const p = win().ManifoldEthereumProvider;
293
- const address = p?.selectedAddress?.();
294
- let chainId = p?.chainId?.();
295
- if (chainId === void 0 || chainId === null) {
296
- try {
297
- chainId = p?.browserChainId?.();
298
- } catch {
299
- chainId = void 0;
300
- }
301
- }
302
- if (!address || chainId === void 0 || chainId === null) return null;
303
- return { address: getAddress(address), chainId: Number(chainId) };
304
- }
305
- function subscribeAccount(cb) {
306
- const handler = () => cb(getAccount());
307
- window.addEventListener(ADDRESS_CHANGED, handler);
308
- window.addEventListener(CHAIN_CHANGED, handler);
309
- return () => {
310
- window.removeEventListener(ADDRESS_CHANGED, handler);
311
- window.removeEventListener(CHAIN_CHANGED, handler);
312
- };
313
- }
314
- function eip1193() {
315
- const p = win().ManifoldEthereumProvider;
316
- const provider = (p?.provider?.(true) ?? p?.browserProvider?.())?.provider;
317
- if (!provider) throw new MintError("CHAIN_SWITCH_FAILED", "No wallet is connected.");
318
- return provider;
319
- }
320
- function getWalletClient(chainId) {
321
- const provider = eip1193();
322
- const request = ((args) => provider.request(args));
323
- return createWalletClient({ chain: getChain(chainId), transport: custom({ request }) });
324
- }
325
- async function waitForDeposit(chainId, hash, timeoutMs = 12e4) {
326
- try {
327
- const receipt = await getWalletClient(chainId).extend(publicActions).waitForTransactionReceipt({ hash, confirmations: 1, timeout: timeoutMs });
328
- return receipt.status === "reverted" ? "reverted" : "mined";
329
- } catch {
330
- return "unknown";
331
- }
332
- }
333
- var WALLET_READ_TIMEOUT = { ms: 1e4 };
334
- async function getConnectedBalance(address, chainId) {
335
- const provider = eip1193();
336
- let timer;
337
- const timeout = new Promise((_, reject) => {
338
- timer = setTimeout(() => reject(new MintError("RPC_ERROR", "The wallet did not report a balance in time.")), WALLET_READ_TIMEOUT.ms);
339
- });
340
- try {
341
- return await Promise.race([
342
- (async () => {
343
- const current = Number(await provider.request({ method: "eth_chainId" }));
344
- if (current !== chainId) {
345
- throw new MintError("CHAIN_SWITCH_FAILED", `The wallet is on chain ${String(current)}, not ${String(chainId)}.`);
346
- }
347
- const hex = await provider.request({ method: "eth_getBalance", params: [address, "latest"] });
348
- return BigInt(hex);
349
- })(),
350
- timeout
351
- ]);
352
- } finally {
353
- clearTimeout(timer);
354
- }
355
- }
356
- var code = (e) => e?.code;
357
- async function switchToChain(chainId) {
358
- const chain = getChain(chainId);
359
- const provider = eip1193();
360
- const hexId = `0x${chainId.toString(16)}`;
361
- const switchChain = () => provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: hexId }] });
362
- try {
363
- try {
364
- await switchChain();
365
- } catch (e) {
366
- if (code(e) !== 4902) throw e;
367
- await provider.request({
368
- method: "wallet_addEthereumChain",
369
- params: [
370
- {
371
- chainId: hexId,
372
- chainName: chain.name,
373
- nativeCurrency: chain.nativeCurrency,
374
- rpcUrls: [...chain.rpcUrls.default.http],
375
- ...chain.blockExplorers ? { blockExplorerUrls: [chain.blockExplorers.default.url] } : {}
376
- }
377
- ]
378
- });
379
- await switchChain();
380
- }
381
- } catch (e) {
382
- if (code(e) === 4001) throw new MintError("USER_REJECTED", "You rejected the network switch.", { cause: e });
383
- throw new MintError("CHAIN_SWITCH_FAILED", `Could not switch the wallet to chain ${String(chainId)}.`, { cause: e });
384
- }
385
- }
34
+ import { BaseError as BaseError2, ExecutionRevertedError, publicActions } from "viem";
386
35
 
387
36
  // src/core/relay/client.ts
388
- import { formatUnits, getAddress as getAddress2, isHex, keccak256, zeroAddress } from "viem";
37
+ import { formatUnits, getAddress, isHex, keccak256, zeroAddress } from "viem";
389
38
  var RELAY_API = { mainnet: "https://api.relay.link", testnet: "https://api.testnets.relay.link" };
390
39
  var MAINNET_PAY_CHAINS = [1, 8453, 10, 360, 33139];
391
40
  var MAINNET_DROP_CHAINS = [1, 8453, 10, 360];
@@ -415,24 +64,24 @@ function moneyOf(amount, currency) {
415
64
  }
416
65
  function revertReason(errorData) {
417
66
  if (typeof errorData !== "string") return "";
418
- const text2 = errorData.replace(/^execution reverted:?\s*/i, "").trim();
419
- return text2 === "execution reverted" ? "" : text2;
67
+ const text = errorData.replace(/^execution reverted:?\s*/i, "").trim();
68
+ return text === "execution reverted" ? "" : text;
420
69
  }
421
70
  function parseQuote(body, originChainId) {
422
71
  const b = obj(body);
423
72
  const steps = Array.isArray(b.steps) ? b.steps.map(obj) : [];
424
73
  const unknownStep = () => new MintError("BRIDGE_UNAVAILABLE", "Relay returned a route this button cannot execute.");
425
74
  if (steps.length !== 1 || steps[0].kind !== "transaction") throw unknownStep();
426
- const step2 = steps[0];
427
- 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) : [];
428
77
  if (rawItems.length !== 1) throw unknownStep();
429
78
  const items = rawItems.map((item) => {
430
79
  const d = obj(item.data);
431
80
  const chainId = Number(d.chainId);
432
81
  if (chainId !== originChainId || typeof d.to !== "string" || !isHex(d.data)) throw unknownStep();
433
- return { chainId, to: getAddress2(d.to), data: d.data, value: big(d.value), gas: d.gas === void 0 ? null : big(d.gas) };
82
+ return { chainId, to: getAddress(d.to), data: d.data, value: big(d.value), gas: d.gas === void 0 ? null : big(d.gas) };
434
83
  });
435
- const requestId = isHex(step2.requestId) ? step2.requestId : isHex(b.requestId) ? b.requestId : null;
84
+ const requestId = isHex(step.requestId) ? step.requestId : isHex(b.requestId) ? b.requestId : null;
436
85
  if (!requestId) throw unknownStep();
437
86
  const details = obj(b.details);
438
87
  const currencyIn = obj(details.currencyIn);
@@ -611,791 +260,22 @@ function claimDeposit(key) {
611
260
  }
612
261
  var releaseDeposit = (key) => void claimed.delete(key);
613
262
 
614
- // src/core/adapters/manifold-claim/index.ts
263
+ // src/core/adapters/contract/index.ts
615
264
  import {
616
265
  BaseError,
617
266
  ContractFunctionRevertedError,
267
+ ContractFunctionZeroDataError,
268
+ InsufficientFundsError,
618
269
  decodeErrorResult,
619
270
  encodeFunctionData,
620
271
  formatUnits as formatUnits2,
621
- getAddress as getAddress3,
272
+ getAddress as getAddress2,
622
273
  isAddress,
623
- isHex as isHex2,
624
- zeroAddress as zeroAddress2,
625
- zeroHash
626
- } from "viem";
627
-
628
- // src/core/adapters/manifold-claim/abis.ts
629
- import { parseAbi } from "viem";
630
- var CLAIM_721_V5_ABI = parseAbi([
631
- "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)"
632
- ]);
633
- var CLAIM_1155_V5_ABI = parseAbi([
634
- "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)"
635
- ]);
636
- var CLAIM_721_V7_ABI = parseAbi([
637
- "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)"
638
- ]);
639
- var CLAIM_1155_V7_ABI = parseAbi([
640
- "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)"
641
- ]);
642
- var EXTENSION_COMMON_ABI = parseAbi([
643
- "function MINT_FEE() view returns (uint256)",
644
- "function MINT_FEE_MERKLE() view returns (uint256)",
645
- "function getTotalMints(address minter, address creatorContractAddress, uint256 instanceId) view returns (uint32)",
646
- "function checkMintIndices(address creatorContractAddress, uint256 instanceId, uint32[] mintIndices) view returns (bool[] minted)",
647
- "function mintProxy(address creatorContractAddress, uint256 instanceId, uint16 mintCount, uint32[] mintIndices, bytes32[][] merkleProofs, address mintFor) payable"
648
- ]);
649
- var EXTENSION_ERRORS_ABI = parseAbi([
650
- "error Error(string message)",
651
- "error Panic(uint256 code)",
652
- "error ClaimInactive()",
653
- "error ClaimNotInitialized()",
654
- "error ExpiredSignature()",
655
- "error FailedToTransfer()",
656
- "error InvalidAirdrop()",
657
- "error InvalidInput()",
658
- "error InvalidInstance()",
659
- "error InvalidSignature()",
660
- "error InvalidStartDate()",
661
- "error InvalidStorageProtocol()",
662
- "error MustUseSignatureMinting()",
663
- "error TokenDNE()",
664
- "error TooManyRequested()"
665
- ]);
666
- var CREATOR_ABI = parseAbi(["function getExtensions() view returns (address[])"]);
667
- var ERC20_ABI = parseAbi([
668
- "function symbol() view returns (string)",
669
- "function decimals() view returns (uint8)",
670
- "function balanceOf(address owner) view returns (uint256)",
671
- "function allowance(address owner, address spender) view returns (uint256)",
672
- "function approve(address spender, uint256 amount) returns (bool)"
673
- ]);
674
-
675
- // src/core/adapters/manifold-claim/merkle.ts
676
- var UINT32_MAX = 4294967295;
677
- async function getJson(fetchFn, url, signal, what) {
678
- let res;
679
- try {
680
- signal?.throwIfAborted();
681
- res = await fetchFn(url, signal ? { signal } : void 0);
682
- } catch (cause) {
683
- throw new MintError("ALLOWLIST_UNAVAILABLE", `Could not reach the allowlist service (${what}).`, { cause });
684
- }
685
- if (res.status === 429) throw new MintError("RATE_LIMITED", "The allowlist service is rate limiting requests. Try again shortly.");
686
- if (!res.ok) throw new MintError("ALLOWLIST_UNAVAILABLE", `The allowlist service has no data for this claim (${what}: HTTP ${res.status}).`);
687
- try {
688
- return await res.json();
689
- } catch (cause) {
690
- throw new MintError("ALLOWLIST_UNAVAILABLE", `The allowlist service returned an unreadable response (${what}).`, { cause });
691
- }
692
- }
693
- var isRecord = (v) => typeof v === "object" && v !== null;
694
- var scopeCaches = /* @__PURE__ */ new WeakMap();
695
- function memo(cache2, key, signal, load) {
696
- const hit = cache2.get(key);
697
- if (hit) return hit;
698
- const p = withSignal(load(), signal);
699
- cache2.set(key, p);
700
- p.catch(() => {
701
- if (cache2.get(key) === p) cache2.delete(key);
702
- });
703
- return p;
704
- }
705
- function withSignal(p, signal) {
706
- if (!signal) return p;
707
- return new Promise((resolve, reject) => {
708
- const onAbort = () => reject(new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist request was cancelled.", { cause: signal.reason }));
709
- p.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
710
- if (signal.aborted) return onAbort();
711
- signal.addEventListener("abort", onAbort, { once: true });
712
- });
713
- }
714
- async function loadInstance(fetchFn, api, instanceId, signal) {
715
- const instance = await getJson(fetchFn, `${api}/public/instance/data?id=${instanceId}`, signal, "instance data");
716
- const publicData = isRecord(instance) ? instance.publicData : void 0;
717
- const allowlist = isRecord(publicData) ? publicData.instanceAllowlist : void 0;
718
- const merkleTreeId = isRecord(allowlist) ? allowlist.merkleTreeId : void 0;
719
- const appId = isRecord(instance) ? instance.appId : void 0;
720
- if (typeof merkleTreeId !== "number" && typeof merkleTreeId !== "string" || typeof appId !== "number" && typeof appId !== "string") {
721
- throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist for this claim is not published yet.");
722
- }
723
- return { merkleTreeId, appId };
724
- }
725
- async function loadEntries(fetchFn, api, instanceId, recipient, scoped) {
726
- const { signal } = scoped;
727
- const { merkleTreeId, appId } = await memo(scoped.instances, `${api}|${instanceId}`, signal, () => loadInstance(fetchFn, api, instanceId, signal));
728
- const url = `${api}/public/merkleTree/${encodeURIComponent(String(merkleTreeId))}/merkleInfo?address=${recipient}&appId=${encodeURIComponent(String(appId))}`;
729
- const body = await getJson(fetchFn, url, signal, "merkle info");
730
- if (!Array.isArray(body)) throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist service returned an unexpected response.");
731
- return body.map((row) => {
732
- const proof = isRecord(row) ? row.merkleProof : void 0;
733
- const value = isRecord(row) ? row.value : void 0;
734
- 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) {
735
- throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist service returned an unexpected response.");
736
- }
737
- return { mintIndex: value, proof };
738
- });
739
- }
740
- async function fetchMerkleEntries(args) {
741
- if (args.signal?.aborted) {
742
- throw new MintError("ALLOWLIST_UNAVAILABLE", "The allowlist request was cancelled.", { cause: args.signal.reason });
743
- }
744
- const fetchFn = args.fetch ?? ((input, init) => globalThis.fetch(input, init));
745
- const key = `${args.api}|${args.instanceId}|${args.recipient.toLowerCase()}`;
746
- let scoped = scopeCaches.get(args.scope);
747
- if (!scoped || scoped.signal?.aborted) {
748
- scoped = { signal: args.signal, instances: /* @__PURE__ */ new Map(), entries: /* @__PURE__ */ new Map() };
749
- scopeCaches.set(args.scope, scoped);
750
- }
751
- const cache2 = scoped;
752
- const entries = await memo(cache2.entries, key, cache2.signal, () => loadEntries(fetchFn, args.api, args.instanceId, args.recipient, cache2));
753
- return entries.slice();
754
- }
755
-
756
- // src/core/adapters/manifold-claim/index.ts
757
- var V6_721 = "0x1eb73fee2090fb1c20105d5ba887e3c3ba14a17e";
758
- var V6_1155 = "0x04ba6cf3c5aa6d4946f5b7f7adf111012a9fac65";
759
- var V7_721 = "0x23aa05a271debffaa3d75739af5581f744b326e4";
760
- var V7_1155 = "0x26bbea7803dcac346d5f5f135b57cf2c752a02be";
761
- var V8_721 = "0x5889e848b2423344f7969bc158100c07595c0137";
762
- var V8_1155 = "0x88438f4d4b8516e758a319ad16924da60e1e56cc";
763
- var v6 = (chainId) => [
764
- { chainId, address: V6_721, generation: "V6", spec: "721", abi: "Claim721V5Optimization" },
765
- { chainId, address: V6_1155, generation: "V6", spec: "1155", abi: "Claim1155V5Optimization" }
766
- ];
767
- var v7 = (chainId) => [
768
- { chainId, address: V7_721, generation: "V7", spec: "721", abi: "Claim721V7" },
769
- { chainId, address: V7_1155, generation: "V7", spec: "1155", abi: "Claim1155V7" }
770
- ];
771
- var EXTENSIONS = [
772
- ...v6(1),
773
- ...v7(1),
774
- ...v6(8453),
775
- ...v7(8453),
776
- ...v6(10),
777
- ...v7(10),
778
- ...v7(360),
779
- { chainId: 360, address: V8_1155, generation: "V8", spec: "1155", abi: "Claim1155V7" },
780
- ...v6(11155111),
781
- ...v7(11155111),
782
- { chainId: 11155111, address: V8_721, generation: "V8", spec: "721", abi: "Claim721V7" },
783
- { chainId: 11155111, address: V8_1155, generation: "V8", spec: "1155", abi: "Claim1155V7" }
784
- ];
785
- function findExtension(chainId, address) {
786
- const a = address.toLowerCase();
787
- return EXTENSIONS.find((e) => e.chainId === chainId && e.address === a);
788
- }
789
- var MERKLE_API = "https://apps.api.manifoldxyz.dev";
790
- var MAX_MINT_COUNT = 65535;
791
- var GAS_UNITS_BASE = 100000n;
792
- var GAS_UNITS_PER_TOKEN = 150000n;
793
- var GAS_UNITS_APPROVE = 60000n;
794
- var dropResolved = /* @__PURE__ */ new WeakMap();
795
- var WALLET_DATA_BRAND = /* @__PURE__ */ Symbol("manifold-claim-wallet-data");
796
- var isWalletData = (d) => typeof d === "object" && d !== null && d.brand === WALLET_DATA_BRAND;
797
- var isAllowlist = (claim) => claim.merkleRoot !== zeroHash;
798
- function isContractFailure(e) {
799
- if (!(e instanceof BaseError)) return false;
800
- return e.walk((x) => x instanceof ContractFunctionRevertedError || x.name === "ContractFunctionZeroDataError") !== null;
801
- }
802
- function toRpcError(e) {
803
- if (e instanceof MintError) return e;
804
- const msg = e instanceof BaseError ? e.shortMessage : e instanceof Error ? e.message : String(e);
805
- return new MintError("RPC_ERROR", `RPC request failed: ${msg}`, { cause: e });
806
- }
807
- async function rpc(fn) {
808
- try {
809
- return await fn();
810
- } catch (e) {
811
- throw toRpcError(e);
812
- }
813
- }
814
- function revertData(e) {
815
- const hit = e.walk((x) => {
816
- const d2 = x.data;
817
- return isHex2(d2) && d2.length >= 10 || typeof d2 === "object" && d2 !== null && isHex2(d2.data);
818
- });
819
- const d = hit?.data;
820
- if (isHex2(d)) return d;
821
- const inner = d?.data;
822
- return isHex2(inner) ? inner : void 0;
823
- }
824
- function decodeRevert(e) {
825
- if (!(e instanceof BaseError)) return null;
826
- const data = revertData(e);
827
- if (data) {
828
- try {
829
- const d = decodeErrorResult({ abi: EXTENSION_ERRORS_ABI, data });
830
- if (d.errorName === "Error" && typeof d.args?.[0] === "string") return d.args[0];
831
- if (d.errorName === "Panic") return `Panic(${String(d.args?.[0])})`;
832
- return d.errorName;
833
- } catch {
834
- return `reverted with unknown error ${data.slice(0, 10)}`;
835
- }
836
- }
837
- const named = e.walk((x) => ["ExecutionRevertedError", "InsufficientFundsError"].includes(x.name));
838
- return named instanceof BaseError ? named.shortMessage : null;
839
- }
840
- var money = (value, decimals, symbol) => ({ value, decimals, symbol, formatted: formatUnits2(value, decimals) });
841
- function timestamp(v, field) {
842
- if (v === 0n) return null;
843
- if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw new MintError("RPC_ERROR", `Claim ${field} does not fit a safe integer`);
844
- return Number(v);
845
- }
846
- function parseConfig(config) {
847
- if (!isAddress(config.creatorContract, { strict: false })) {
848
- throw new MintError("INVALID_CONFIG", "creatorContract is not a valid address.", { field: "creatorContract" });
849
- }
850
- if (config.extension !== void 0 && !isAddress(config.extension, { strict: false })) {
851
- throw new MintError("INVALID_CONFIG", "extension is not a valid address.", { field: "extension" });
852
- }
853
- if (typeof config.instanceId !== "string" || !/^\d+$/.test(config.instanceId)) {
854
- throw new MintError("INVALID_CONFIG", "instanceId must be a non-negative integer string.", { field: "instanceId" });
855
- }
856
- return {
857
- creator: getAddress3(config.creatorContract),
858
- instanceId: BigInt(config.instanceId),
859
- extension: config.extension === void 0 ? void 0 : getAddress3(config.extension)
860
- };
861
- }
862
- var notFound = (config) => new MintError("CLAIM_NOT_FOUND", `No Manifold claim ${config.instanceId} found on ${config.creatorContract}.`);
863
- async function readClaim(client, entry, creator, instanceId, config) {
864
- const address = getAddress3(entry.address);
865
- const args = [creator, instanceId];
866
- try {
867
- switch (entry.abi) {
868
- case "Claim721V5Optimization": {
869
- const c = await client.readContract({ address, abi: CLAIM_721_V5_ABI, functionName: "getClaim", args });
870
- return { ...base2(c), signingAddress: null };
871
- }
872
- case "Claim1155V5Optimization": {
873
- const c = await client.readContract({ address, abi: CLAIM_1155_V5_ABI, functionName: "getClaim", args });
874
- return { ...base2(c), signingAddress: null };
875
- }
876
- case "Claim721V7": {
877
- const c = await client.readContract({ address, abi: CLAIM_721_V7_ABI, functionName: "getClaim", args });
878
- return { ...base2(c), signingAddress: c.signingAddress };
879
- }
880
- case "Claim1155V7": {
881
- const c = await client.readContract({ address, abi: CLAIM_1155_V7_ABI, functionName: "getClaim", args });
882
- return { ...base2(c), signingAddress: c.signingAddress };
883
- }
884
- }
885
- } catch (e) {
886
- if (isContractFailure(e)) throw notFound(config);
887
- throw toRpcError(e);
888
- }
889
- }
890
- function base2(c) {
891
- return {
892
- total: BigInt(c.total),
893
- totalMax: BigInt(c.totalMax),
894
- walletMax: BigInt(c.walletMax),
895
- startDate: BigInt(c.startDate),
896
- endDate: BigInt(c.endDate),
897
- merkleRoot: c.merkleRoot,
898
- cost: c.cost,
899
- erc20: c.erc20
900
- };
901
- }
902
- async function hasCode(client, address) {
903
- const code2 = await rpc(() => client.getCode({ address: getAddress3(address) }));
904
- return code2 !== void 0 && code2 !== "0x";
905
- }
906
- var unknownExtension = (address, why) => new MintError("UNKNOWN_EXTENSION", `Extension ${address} ${why}.`);
907
- async function resolveExtension(ctx, config) {
908
- const { creator, instanceId, extension } = parseConfig(config);
909
- const { client } = ctx;
910
- if (extension) {
911
- const entry = findExtension(config.chainId, extension);
912
- if (!entry) throw unknownExtension(extension, `is not a supported Manifold claim extension on chain ${config.chainId}`);
913
- if (!await hasCode(client, extension)) throw unknownExtension(extension, "has no contract code on this chain");
914
- return { entry, claim: await readClaim(client, entry, creator, instanceId, config) };
915
- }
916
- let registered;
917
- try {
918
- registered = await client.readContract({ address: creator, abi: CREATOR_ABI, functionName: "getExtensions" });
919
- } catch (e) {
920
- if (isContractFailure(e)) throw notFound(config);
921
- throw toRpcError(e);
922
- }
923
- const candidates = [...new Set(registered.map((a) => a.toLowerCase()))].map((a) => findExtension(config.chainId, a)).filter((e) => e !== void 0);
924
- const found = await Promise.all(
925
- candidates.map(async (entry) => {
926
- if (!await hasCode(client, entry.address)) return null;
927
- try {
928
- return { entry, claim: await readClaim(client, entry, creator, instanceId, config) };
929
- } catch (e) {
930
- if (e instanceof MintError && e.reason === "CLAIM_NOT_FOUND") return null;
931
- throw e;
932
- }
933
- })
934
- );
935
- const hits = found.filter((f) => f !== null);
936
- if (hits.length === 0) throw notFound(config);
937
- if (hits.length > 1) {
938
- throw new MintError(
939
- "AMBIGUOUS_EXTENSION",
940
- `Claim ${config.instanceId} exists on ${hits.length} extensions (${hits.map((h) => h.entry.address).join(", ")}). Set config.extension.`
941
- );
942
- }
943
- return hits[0];
944
- }
945
- async function loadDrop(ctx, config) {
946
- const { entry, claim } = await resolveExtension(ctx, config);
947
- if (claim.signingAddress !== null && claim.signingAddress !== zeroAddress2) {
948
- throw new MintError("SIGNATURE_CLAIM", "This claim mints with a signature (redemption code), which this button does not support.");
949
- }
950
- const { client } = ctx;
951
- const extension = getAddress3(entry.address);
952
- const fee = await rpc(
953
- () => client.readContract({ address: extension, abi: EXTENSION_COMMON_ABI, functionName: isAllowlist(claim) ? "MINT_FEE_MERKLE" : "MINT_FEE" })
954
- );
955
- const native = client.chain?.nativeCurrency ?? { symbol: "ETH", decimals: 18 };
956
- let unitPrice;
957
- let paymentToken = null;
958
- if (claim.erc20 === zeroAddress2) {
959
- unitPrice = money(claim.cost, native.decimals, native.symbol);
960
- } else {
961
- paymentToken = getAddress3(claim.erc20);
962
- const token = paymentToken;
963
- const [symbol, decimals] = await rpc(
964
- () => Promise.all([
965
- client.readContract({ address: token, abi: ERC20_ABI, functionName: "symbol" }),
966
- client.readContract({ address: token, abi: ERC20_ABI, functionName: "decimals" })
967
- ])
968
- );
969
- unitPrice = money(claim.cost, decimals, symbol);
970
- }
971
- const drop = {
972
- chainId: config.chainId,
973
- unitPrice,
974
- unitFee: money(fee, native.decimals, native.symbol),
975
- totalMinted: claim.total,
976
- maxSupply: claim.totalMax === 0n ? null : claim.totalMax,
977
- startTime: timestamp(claim.startDate, "startDate"),
978
- endTime: timestamp(claim.endDate, "endDate"),
979
- isAllowlist: isAllowlist(claim),
980
- paymentToken,
981
- pricePer: "unit"
982
- };
983
- const resolved = { entry, claim, fee };
984
- dropResolved.set(drop, resolved);
985
- return { drop, resolved };
986
- }
987
- async function loadWallet(ctx, config, args) {
988
- const { creator, instanceId } = parseConfig(config);
989
- const { client } = ctx;
990
- const resolved = dropResolved.get(args.drop) ?? (await loadDrop(ctx, config)).resolved;
991
- const { entry, claim } = resolved;
992
- const extension = getAddress3(entry.address);
993
- const payer = getAddress3(args.payer);
994
- const recipient = getAddress3(args.recipient);
995
- let walletMinted = null;
996
- let walletMax = null;
997
- let allowlistRemaining = null;
998
- let maxQuantity = null;
999
- let ineligible = null;
1000
- let unused = [];
1001
- if (isAllowlist(claim)) {
1002
- const entries = await fetchMerkleEntries({ scope: ctx.cacheScope ?? args.drop, api: MERKLE_API, instanceId: config.instanceId, recipient, fetch: ctx.fetch, signal: ctx.signal });
1003
- if (entries.length > 0) {
1004
- const minted = await rpc(
1005
- () => client.readContract({
1006
- address: extension,
1007
- abi: EXTENSION_COMMON_ABI,
1008
- functionName: "checkMintIndices",
1009
- args: [creator, instanceId, entries.map((e) => e.mintIndex)]
1010
- })
1011
- );
1012
- unused = entries.filter((_, i) => minted[i] === false);
1013
- }
1014
- allowlistRemaining = unused.length;
1015
- maxQuantity = unused.length;
1016
- if (entries.length === 0) {
1017
- ineligible = { reason: "NOT_ON_ALLOWLIST", message: "This wallet is not on the allowlist." };
1018
- } else if (unused.length === 0) {
1019
- ineligible = { reason: "ALLOWLIST_USED", message: "This wallet has already used all its allowlist spots." };
1020
- }
1021
- } else if (claim.walletMax > 0n) {
1022
- walletMax = claim.walletMax;
1023
- walletMinted = BigInt(
1024
- await rpc(() => client.readContract({ address: extension, abi: EXTENSION_COMMON_ABI, functionName: "getTotalMints", args: [recipient, creator, instanceId] }))
1025
- );
1026
- const left = walletMax > walletMinted ? walletMax - walletMinted : 0n;
1027
- maxQuantity = Number(left);
1028
- if (left === 0n) ineligible = { reason: "WALLET_LIMIT", message: `This wallet has already minted its limit of ${walletMax}.` };
1029
- }
1030
- const token = claim.erc20 === zeroAddress2 ? null : getAddress3(claim.erc20);
1031
- const [native, erc20, gasPrice] = await rpc(
1032
- () => Promise.all([
1033
- client.getBalance({ address: payer }),
1034
- token ? client.readContract({ address: token, abi: ERC20_ABI, functionName: "balanceOf", args: [payer] }) : Promise.resolve(null),
1035
- client.getGasPrice()
1036
- ])
1037
- );
1038
- const gasUnits = GAS_UNITS_BASE + GAS_UNITS_PER_TOKEN * BigInt(Math.max(1, args.quantity)) + (token ? GAS_UNITS_APPROVE : 0n);
1039
- const data = { brand: WALLET_DATA_BRAND, resolved, config, recipient, unused };
1040
- return {
1041
- walletMinted,
1042
- walletMax,
1043
- allowlistRemaining,
1044
- maxQuantity,
1045
- ineligible,
1046
- balances: { native, erc20 },
1047
- gasReserve: gasPrice * gasUnits,
1048
- data
1049
- };
1050
- }
1051
- var sameClaim = (a, b) => a.chainId === b.chainId && a.creatorContract.toLowerCase() === b.creatorContract.toLowerCase() && a.instanceId === b.instanceId && a.extension?.toLowerCase() === b.extension?.toLowerCase();
1052
- async function buildPlan(ctx, attempt, wallet) {
1053
- const { config, quantity } = attempt;
1054
- if (!Number.isInteger(quantity) || quantity < 1 || quantity > MAX_MINT_COUNT) {
1055
- throw new MintError("INVALID_CONFIG", `quantity must be an integer from 1 to ${MAX_MINT_COUNT}.`, { field: "quantity" });
1056
- }
1057
- const { creator, instanceId } = parseConfig(config);
1058
- const recipient = getAddress3(attempt.recipient);
1059
- const payer = getAddress3(attempt.payer);
1060
- let data = wallet.data;
1061
- if (!isWalletData(data) || !sameClaim(data.config, config) || data.recipient !== recipient) {
1062
- const drop = (await loadDrop(ctx, config)).drop;
1063
- data = (await loadWallet(ctx, config, { payer, recipient, quantity, drop })).data;
1064
- }
1065
- if (!isWalletData(data)) throw new MintError("RPC_ERROR", "Wallet read produced no plan data.");
1066
- const { entry, claim, fee } = data.resolved;
1067
- const extension = getAddress3(entry.address);
1068
- let mintIndices = [];
1069
- let merkleProofs = [];
1070
- if (isAllowlist(claim)) {
1071
- if (quantity > data.unused.length) {
1072
- throw new MintError("WALLET_LIMIT", `Only ${data.unused.length} allowlist spot(s) left for this wallet.`);
1073
- }
1074
- const picked = data.unused.slice(0, quantity);
1075
- mintIndices = picked.map((p) => p.mintIndex);
1076
- merkleProofs = picked.map((p) => p.proof);
1077
- }
1078
- const qty = BigInt(quantity);
1079
- const erc20 = claim.erc20 === zeroAddress2 ? null : getAddress3(claim.erc20);
1080
- const cost = claim.cost * qty;
1081
- const value = fee * qty + (erc20 ? 0n : cost);
1082
- let approve = null;
1083
- if (erc20 && cost > 0n) {
1084
- const allowance = await rpc(() => ctx.client.readContract({ address: erc20, abi: ERC20_ABI, functionName: "allowance", args: [payer, extension] }));
1085
- if (allowance < cost) {
1086
- approve = {
1087
- token: erc20,
1088
- spender: extension,
1089
- amount: cost,
1090
- tx: { to: erc20, data: encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [extension, cost] }), value: 0n }
1091
- };
1092
- }
1093
- }
1094
- return {
1095
- approve,
1096
- mint: {
1097
- to: extension,
1098
- data: encodeFunctionData({
1099
- abi: EXTENSION_COMMON_ABI,
1100
- functionName: "mintProxy",
1101
- args: [creator, instanceId, quantity, mintIndices, merkleProofs.map((p) => [...p]), recipient]
1102
- }),
1103
- value
1104
- },
1105
- tokenContract: creator
1106
- };
1107
- }
1108
- var RELAY_VERIFIED = ["V6", "V7"];
1109
- var manifoldClaimAdapter = {
1110
- supportsRelay: (drop) => {
1111
- const resolved = dropResolved.get(drop);
1112
- return resolved !== void 0 && RELAY_VERIFIED.includes(resolved.entry.generation) && drop.paymentToken === null;
1113
- },
1114
- readDrop: async (ctx, config) => (await loadDrop(ctx, config)).drop,
1115
- readWallet: loadWallet,
1116
- buildPlan,
1117
- simulate: async (ctx, attempt, plan) => {
1118
- try {
1119
- await ctx.client.call({ account: getAddress3(attempt.payer), to: plan.mint.to, data: plan.mint.data, value: plan.mint.value });
1120
- } catch (e) {
1121
- const text2 = decodeRevert(e);
1122
- if (text2 === null) throw toRpcError(e);
1123
- throw new MintError("SIMULATION_REVERTED", text2, { cause: e });
1124
- }
1125
- }
1126
- };
1127
-
1128
- // src/core/adapters/contract/index.ts
1129
- import {
1130
- BaseError as BaseError2,
1131
- ContractFunctionRevertedError as ContractFunctionRevertedError2,
1132
- ContractFunctionZeroDataError,
1133
- InsufficientFundsError,
1134
- decodeErrorResult as decodeErrorResult2,
1135
- encodeFunctionData as encodeFunctionData2,
1136
- formatUnits as formatUnits4,
1137
- getAddress as getAddress4,
1138
- isAddress as isAddress2,
1139
- parseAbi as parseAbi2,
274
+ parseAbi,
1140
275
  parseUnits
1141
276
  } from "viem";
1142
-
1143
- // src/core/machine.ts
1144
- import { formatUnits as formatUnits3 } from "viem";
1145
- var MINT_STATES = [
1146
- "loading",
1147
- "unsupported",
1148
- "upcoming",
1149
- "ended",
1150
- "sold-out",
1151
- "disconnected",
1152
- "connecting",
1153
- "live",
1154
- "ineligible",
1155
- "insufficient-funds",
1156
- "switching-chain",
1157
- "approving",
1158
- "minting",
1159
- "confirming",
1160
- "success",
1161
- "error"
1162
- ];
1163
- var CLICKABLE_STATES = ["disconnected", "live", "success", "error"];
1164
- var IN_FLIGHT_STATES = ["switching-chain", "approving", "minting", "confirming"];
1165
- var MAX_QUANTITY = 65535;
1166
- function initialState(opts) {
1167
- return {
1168
- name: "loading",
1169
- reason: null,
1170
- message: null,
1171
- readGen: 0,
1172
- walletGen: 0,
1173
- drop: null,
1174
- account: null,
1175
- walletRead: null,
1176
- blocked: null,
1177
- quantity: toQuantity(opts?.quantity ?? 1, MAX_QUANTITY),
1178
- attempt: null,
1179
- result: null,
1180
- pendingRefresh: false,
1181
- now: 0,
1182
- crossChain: false,
1183
- routePending: false,
1184
- route: null,
1185
- short: null
1186
- };
1187
- }
1188
- var NO_ROUTE = { crossChain: false, routePending: false, route: null, short: null };
1189
- var PICK_ANOTHER = "Pick another network to pay from.";
1190
- function toQuantity(q, max) {
1191
- if (Number.isNaN(q)) return 1;
1192
- return Math.max(1, Math.min(Math.floor(q), max));
1193
- }
1194
- function isInFlight(s) {
1195
- return s.attempt !== null || IN_FLIGHT_STATES.includes(s.name);
1196
- }
1197
- function isIdle(s) {
1198
- return !isInFlight(s) && s.name !== "connecting" && s.name !== "success" && s.name !== "error";
1199
- }
1200
- function derive(s, unsupported) {
1201
- const named = (name) => ({ name, reason: null, message: null });
1202
- const { drop, walletRead } = s;
1203
- if (unsupported) return { name: "unsupported", reason: s.reason, message: s.message };
1204
- if (drop === null) return named("loading");
1205
- if (drop.endTime !== null && drop.endTime <= s.now) return named("ended");
1206
- if (drop.maxSupply !== null && drop.maxSupply > 0n && drop.totalMinted >= drop.maxSupply) return named("sold-out");
1207
- if (drop.startTime !== null && drop.startTime > s.now) return named("upcoming");
1208
- if (s.account === null) return named("disconnected");
1209
- if (walletRead === null) return named("loading");
1210
- if (s.blocked !== null) return s.blocked;
1211
- if (walletRead.ineligible !== null) {
1212
- return { name: "ineligible", reason: walletRead.ineligible.reason, message: walletRead.ineligible.message };
1213
- }
1214
- if (s.routePending) return named("loading");
1215
- if (s.route?.kind === "relay") return named("live");
1216
- if (s.short !== null) {
1217
- return { name: "insufficient-funds", reason: "INSUFFICIENT_FUNDS", message: `Not enough ${s.short.symbol} on ${s.short.name}. ${PICK_ANOTHER}` };
1218
- }
1219
- const total = selectTotal(s);
1220
- if (total !== null) {
1221
- const { native, erc20 } = total;
1222
- if (native.value + walletRead.gasReserve > walletRead.balances.native) {
1223
- const more = s.crossChain ? ` ${PICK_ANOTHER}` : "";
1224
- return { name: "insufficient-funds", reason: "INSUFFICIENT_FUNDS", message: `Not enough ${native.symbol} to cover the mint.${more}` };
1225
- }
1226
- if (erc20 !== null && walletRead.balances.erc20 !== null && erc20.value > walletRead.balances.erc20) {
1227
- return { name: "insufficient-funds", reason: "INSUFFICIENT_FUNDS", message: `Not enough ${erc20.symbol} to cover the mint.` };
1228
- }
1229
- }
1230
- return named("live");
1231
- }
1232
- function settle(s, unsupported = s.name === "unsupported") {
1233
- if (!isIdle(s)) return s;
1234
- return { ...s, ...derive(s, unsupported) };
1235
- }
1236
- function clampQuantity(s) {
1237
- const quantity = toQuantity(s.quantity, selectMaxQuantity(s) ?? MAX_QUANTITY);
1238
- return quantity === s.quantity ? s : { ...s, quantity };
1239
- }
1240
- function reducer(state, event) {
1241
- const inFlight = isInFlight(state);
1242
- const failed = (reason, message) => {
1243
- if (inFlight) return { ...state, pendingRefresh: true };
1244
- if (state.name === "success" || state.name === "error") return state;
1245
- return { ...state, name: "error", reason, message };
1246
- };
1247
- switch (event.type) {
1248
- case "LOAD": {
1249
- if (event.kind === "refresh") {
1250
- const next2 = { ...state, readGen: event.gen };
1251
- return inFlight ? { ...next2, pendingRefresh: true } : settle(next2);
1252
- }
1253
- const next = { ...state, ...NO_ROUTE, readGen: event.gen, drop: null, walletRead: null, blocked: null, walletGen: state.walletGen + 1 };
1254
- return inFlight ? { ...next, pendingRefresh: true } : settle(next, false);
1255
- }
1256
- case "DROP_LOADED": {
1257
- if (event.gen !== state.readGen) return state;
1258
- const next = { ...state, drop: event.drop, now: Math.max(state.now, event.now) };
1259
- if (inFlight) return { ...next, pendingRefresh: true };
1260
- return isIdle(next) ? settle(clampQuantity(next), false) : clampQuantity(next);
1261
- }
1262
- case "DROP_UNSUPPORTED": {
1263
- if (event.gen !== state.readGen) return state;
1264
- if (inFlight) return { ...state, pendingRefresh: true };
1265
- if (state.name === "success" || state.name === "error") return state;
1266
- return { ...state, name: "unsupported", reason: event.reason, message: event.message };
1267
- }
1268
- case "READ_FAILED":
1269
- return event.gen !== state.readGen ? state : failed(event.reason, event.message);
1270
- case "ACCOUNT_CHANGED": {
1271
- const next = { ...state, ...NO_ROUTE, account: event.account, walletRead: null, blocked: null, walletGen: state.walletGen + 1 };
1272
- if (inFlight) return { ...next, pendingRefresh: true };
1273
- if (state.name === "connecting") return event.account === null ? next : settle({ ...next, name: "loading" }, false);
1274
- return settle(next);
1275
- }
1276
- case "WALLET_LOADED": {
1277
- if (event.gen !== state.walletGen) return state;
1278
- const route = event.routePending ? { routePending: state.route === null && state.short === null, route: state.route, short: state.short } : { routePending: false, route: null, short: null };
1279
- const next = { ...state, ...route, crossChain: event.crossChain ?? false, walletRead: event.read, blocked: null };
1280
- return inFlight ? { ...next, pendingRefresh: true } : settle(clampQuantity(next));
1281
- }
1282
- case "ROUTE_LOADED": {
1283
- if (event.gen !== state.walletGen) return state;
1284
- const next = { ...state, routePending: false, route: event.route, short: event.short };
1285
- return inFlight ? { ...next, pendingRefresh: true } : settle(next);
1286
- }
1287
- case "WALLET_FAILED":
1288
- return event.gen !== state.walletGen ? state : failed(event.reason, event.message);
1289
- case "CONNECT_STARTED":
1290
- return state.name === "disconnected" && state.attempt === null ? { ...state, name: "connecting", reason: null, message: null } : state;
1291
- case "CONNECT_DISMISSED":
1292
- return state.name === "connecting" ? settle({ ...state, name: "disconnected" }, false) : state;
1293
- case "TICK":
1294
- return settle({ ...state, now: Math.max(state.now, event.now) });
1295
- case "SET_QUANTITY": {
1296
- const next = { ...state, quantity: toQuantity(event.quantity, selectMaxQuantity(state) ?? MAX_QUANTITY) };
1297
- return inFlight ? { ...next, pendingRefresh: true } : settle(next);
1298
- }
1299
- case "ATTEMPT_STARTED":
1300
- if (state.attempt !== null) return state;
1301
- if (event.resume === true) return IN_FLIGHT_STATES.includes(state.name) ? state : { ...state, attempt: event.attempt };
1302
- return state.name === "live" ? { ...state, attempt: event.attempt } : state;
1303
- case "SWITCHING_CHAIN":
1304
- return step(state, event.attemptId, "switching-chain");
1305
- case "APPROVING":
1306
- return step(state, event.attemptId, "approving");
1307
- case "MINT_PROMPTED":
1308
- return step(state, event.attemptId, "minting");
1309
- case "TX_SUBMITTED":
1310
- return step(state, event.attemptId, "confirming");
1311
- case "ATTEMPT_SUCCEEDED":
1312
- return state.attempt?.attemptId === event.attemptId ? {
1313
- ...state,
1314
- name: "success",
1315
- reason: null,
1316
- message: null,
1317
- attempt: null,
1318
- result: event.result,
1319
- drop: null,
1320
- readGen: state.readGen + 1
1321
- } : state;
1322
- case "ATTEMPT_FAILED": {
1323
- if (state.attempt?.attemptId !== event.attemptId) return state;
1324
- const { reason, message } = event;
1325
- const done = { ...state, reason, message, attempt: null, result: null };
1326
- if (INELIGIBLE_REASONS.includes(reason)) {
1327
- return { ...done, name: "ineligible", blocked: { name: "ineligible", reason, message } };
1328
- }
1329
- if (reason === "INSUFFICIENT_FUNDS") {
1330
- return { ...done, name: "insufficient-funds", blocked: { name: "insufficient-funds", reason, message } };
1331
- }
1332
- return {
1333
- ...done,
1334
- name: "error",
1335
- drop: state.name === "confirming" ? null : state.drop,
1336
- readGen: state.name === "confirming" ? state.readGen + 1 : state.readGen
1337
- };
1338
- }
1339
- case "RESET": {
1340
- if (state.name !== "success" && state.name !== "error") return state;
1341
- const next = {
1342
- ...state,
1343
- readGen: event.gen,
1344
- ...NO_ROUTE,
1345
- walletRead: null,
1346
- blocked: null,
1347
- walletGen: state.walletGen + 1,
1348
- result: null,
1349
- pendingRefresh: false
1350
- };
1351
- return settle(clampQuantity({ ...next, name: "loading" }), false);
1352
- }
1353
- }
1354
- }
1355
- var STEP_ORDER = ["switching-chain", "approving", "minting", "confirming"];
1356
- function step(state, attemptId, name) {
1357
- if (state.attempt?.attemptId !== attemptId) return state;
1358
- if (STEP_ORDER.indexOf(name) <= STEP_ORDER.indexOf(state.name)) return state;
1359
- return { ...state, name, reason: null, message: null };
1360
- }
1361
- function selectMaxQuantity(state) {
1362
- const { drop, walletRead } = state;
1363
- if (drop === null) return null;
1364
- let max = MAX_QUANTITY;
1365
- if (drop.maxSupply !== null && drop.maxSupply > 0n) {
1366
- const remaining = drop.maxSupply - drop.totalMinted;
1367
- if (remaining < BigInt(max)) max = remaining > 0n ? Number(remaining) : 0;
1368
- }
1369
- if (walletRead !== null && walletRead.maxQuantity !== null) {
1370
- max = Math.min(max, Math.max(0, Math.floor(walletRead.maxQuantity)));
1371
- }
1372
- return max;
1373
- }
1374
- function selectTotal(state) {
1375
- const { drop } = state;
1376
- if (drop === null) return null;
1377
- const q = BigInt(state.quantity);
1378
- const price = drop.unitPrice;
1379
- const fee = drop.unitFee;
1380
- const priceTotal = drop.pricePer === "total" ? price.value : price.value * q;
1381
- if (drop.paymentToken !== null) {
1382
- return {
1383
- native: money2(fee.value * q, fee),
1384
- erc20: money2(priceTotal, price)
1385
- };
1386
- }
1387
- return { native: money2(priceTotal + fee.value * q, price), erc20: null };
1388
- }
1389
- function money2(value, like) {
1390
- return { value, decimals: like.decimals, symbol: like.symbol, formatted: formatUnits3(value, like.decimals) };
1391
- }
1392
- function canAct(state) {
1393
- return state.attempt === null && CLICKABLE_STATES.includes(state.name);
1394
- }
1395
-
1396
- // src/core/adapters/contract/index.ts
1397
277
  var PLACEHOLDERS = ["{recipient}", "{payer}", "{quantity}", "{unitPrice}", "{totalPrice}"];
1398
- var ERC20_ABI2 = parseAbi2([
278
+ var ERC20_ABI = parseAbi([
1399
279
  "function symbol() view returns (string)",
1400
280
  "function decimals() view returns (uint8)",
1401
281
  "function balanceOf(address) view returns (uint256)",
@@ -1410,7 +290,7 @@ var NUMERIC_TYPE = /^u?int\d*$/;
1410
290
  function bad(field, message) {
1411
291
  throw new MintError("INVALID_CONFIG", `${field} ${message}`, { field });
1412
292
  }
1413
- var isHexAddress = (a) => typeof a === "string" && isAddress2(a, { strict: false });
293
+ var isHexAddress = (a) => typeof a === "string" && isAddress(a, { strict: false });
1414
294
  function functionsNamed(abi, name) {
1415
295
  return abi.filter((i) => i.type === "function" && i.name === name);
1416
296
  }
@@ -1467,7 +347,7 @@ function typeIssue(t, p, path) {
1467
347
  if (Array.isArray(t)) return no(`must not be an array for ${p.type}`);
1468
348
  if (p.type === "address") {
1469
349
  if (isExactPlaceholder(t)) return t === "{recipient}" || t === "{payer}" ? null : no(`${t} is a number, but the abi input is an address`);
1470
- return typeof t === "string" && !hasPlaceholder(t) && isAddress2(t) ? null : no(`${JSON.stringify(String(t))} is not an address`);
350
+ return typeof t === "string" && !hasPlaceholder(t) && isAddress(t) ? null : no(`${JSON.stringify(String(t))} is not an address`);
1471
351
  }
1472
352
  if (p.type === "bool") return typeof t === "boolean" ? null : no(`${JSON.stringify(String(t))} is not a boolean`);
1473
353
  if (p.type === "string") return typeof t === "string" ? null : no(`${JSON.stringify(String(t))} is not a string`);
@@ -1624,7 +504,7 @@ function varFor(token, vars) {
1624
504
  const key = token.slice(1, -1);
1625
505
  const v = vars[key];
1626
506
  if (v === void 0) throw new MintError("INVALID_CONFIG", `placeholder ${token} has no value here`);
1627
- return typeof v === "string" ? getAddress4(v) : v;
507
+ return typeof v === "string" ? getAddress2(v) : v;
1628
508
  }
1629
509
  function fill(t, p, vars) {
1630
510
  const arr = ARRAY_TYPE.exec(p.type);
@@ -1640,7 +520,7 @@ function fill(t, p, vars) {
1640
520
  var fillArgs = (args, inputs, vars) => (args ?? []).map((a, i) => fill(a, inputs[i], vars));
1641
521
  var totalFor = (per, price, quantity) => per === "total" ? price : price * quantity;
1642
522
  function shortMessage(e) {
1643
- return e instanceof BaseError2 ? e.shortMessage : e instanceof Error ? e.message : String(e);
523
+ return e instanceof BaseError ? e.shortMessage : e instanceof Error ? e.message : String(e);
1644
524
  }
1645
525
  var abortError = () => new DOMException("The operation was aborted", "AbortError");
1646
526
  var isAbortError = (e) => e?.name === "AbortError";
@@ -1663,7 +543,7 @@ function rpcError(e) {
1663
543
  }
1664
544
  function classifyReadError(e, field) {
1665
545
  if (isMintError(e) || isAbortError(e)) throw e;
1666
- if (e instanceof BaseError2 && e.walk((x) => x instanceof ContractFunctionRevertedError2 || x instanceof ContractFunctionZeroDataError)) {
546
+ if (e instanceof BaseError && e.walk((x) => x instanceof ContractFunctionRevertedError || x instanceof ContractFunctionZeroDataError)) {
1667
547
  throw new MintError("INVALID_CONFIG", `${field} read reverted or returned no data: ${e.shortMessage}`, { field, cause: e });
1668
548
  }
1669
549
  return rpcError(e);
@@ -1713,14 +593,14 @@ function nativeMeta(ctx) {
1713
593
  const n = ctx.client.chain?.nativeCurrency;
1714
594
  return { decimals: n?.decimals ?? 18, symbol: n?.symbol ?? "ETH" };
1715
595
  }
1716
- var erc20Of = (config) => config.price.currency === "native" ? null : getAddress4(config.price.currency.address);
596
+ var erc20Of = (config) => config.price.currency === "native" ? null : getAddress2(config.price.currency.address);
1717
597
  async function currencyMeta(ctx, config) {
1718
598
  const token = erc20Of(config);
1719
599
  if (!token) return { token, ...nativeMeta(ctx) };
1720
600
  const field = "price.currency.address";
1721
601
  const [symbol, decimals] = await Promise.all([
1722
- readCall(ctx, { address: token, abi: ERC20_ABI2, functionName: "symbol" }, field),
1723
- 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)
1724
604
  ]);
1725
605
  if (typeof symbol !== "string" || typeof decimals !== "number") {
1726
606
  throw new MintError("INVALID_CONFIG", `${field} ${token} is not an ERC20 (symbol/decimals unreadable)`, { field });
@@ -1741,13 +621,13 @@ async function resolvePrice(ctx, config, meta) {
1741
621
  if (typeof value === "bigint") return value;
1742
622
  return parseDisplay(value, (meta ?? await currencyMeta(ctx, config)).decimals);
1743
623
  }
1744
- var money3 = (value, decimals, symbol) => ({
624
+ var money = (value, decimals, symbol) => ({
1745
625
  value,
1746
626
  decimals,
1747
627
  symbol,
1748
- formatted: formatUnits4(value, decimals)
628
+ formatted: formatUnits2(value, decimals)
1749
629
  });
1750
- function revertData2(e) {
630
+ function revertData(e) {
1751
631
  for (let cur = e, depth = 0; cur && depth < 12; depth++) {
1752
632
  const d = cur.data;
1753
633
  if (typeof d === "string" && d.startsWith("0x") && d.length >= 10) return d;
@@ -1761,7 +641,7 @@ function revertData2(e) {
1761
641
  }
1762
642
  function describeRevert(abi, data) {
1763
643
  try {
1764
- const d = decodeErrorResult2({ abi, data });
644
+ const d = decodeErrorResult({ abi, data });
1765
645
  const args = d.args ?? [];
1766
646
  if (d.errorName === "Error") return String(args[0] ?? "execution reverted");
1767
647
  const inputs = d.abiItem?.inputs ?? [];
@@ -1774,12 +654,12 @@ function describeRevert(abi, data) {
1774
654
  function toSimulationError(e, abi) {
1775
655
  if (isMintError(e)) return e;
1776
656
  if (isAbortError(e)) throw e;
1777
- if (e instanceof BaseError2 && e.walk((x) => x instanceof InsufficientFundsError)) {
657
+ if (e instanceof BaseError && e.walk((x) => x instanceof InsufficientFundsError)) {
1778
658
  return new MintError("INSUFFICIENT_FUNDS", `Payer cannot cover the mint: ${e.shortMessage}`, { cause: e });
1779
659
  }
1780
- const data = revertData2(e);
660
+ const data = revertData(e);
1781
661
  if (data) return new MintError("SIMULATION_REVERTED", describeRevert(abi, data), { cause: e });
1782
- const isRevert = e instanceof BaseError2 && e.walk((x) => x.code === 3 || /execution reverted/i.test(x.message));
662
+ const isRevert = e instanceof BaseError && e.walk((x) => x.code === 3 || /execution reverted/i.test(x.message));
1783
663
  if (isRevert) return new MintError("SIMULATION_REVERTED", shortMessage(e), { cause: e });
1784
664
  return new MintError("RPC_ERROR", `RPC request failed: ${shortMessage(e)}`, { cause: e });
1785
665
  }
@@ -1793,7 +673,7 @@ async function simulateMint(ctx, config, call) {
1793
673
  function encodeMint(config, vars) {
1794
674
  const fn = validateCall(config.abi, config.mint, "mint", "mint", PLACEHOLDERS);
1795
675
  try {
1796
- return encodeFunctionData2({ abi: [fn], functionName: fn.name, args: fillArgs(config.mint.args, fn.inputs, vars) });
676
+ return encodeFunctionData({ abi: [fn], functionName: fn.name, args: fillArgs(config.mint.args, fn.inputs, vars) });
1797
677
  } catch (e) {
1798
678
  if (isMintError(e)) throw e;
1799
679
  throw new MintError("INVALID_CONFIG", `mint.args cannot be encoded for ${signature(fn)}: ${shortMessage(e)}`, { field: "mint.args", cause: e });
@@ -1824,8 +704,8 @@ async function readDrop(ctx, config) {
1824
704
  const native = nativeMeta(ctx);
1825
705
  return {
1826
706
  chainId: config.chainId,
1827
- unitPrice: money3(price, meta.decimals, meta.symbol),
1828
- unitFee: money3(0n, native.decimals, native.symbol),
707
+ unitPrice: money(price, meta.decimals, meta.symbol),
708
+ unitFee: money(0n, native.decimals, native.symbol),
1829
709
  totalMinted: totalMinted ?? 0n,
1830
710
  maxSupply: maxSupply === null || maxSupply === 0n ? null : maxSupply,
1831
711
  startTime: toSeconds(start, "startTime"),
@@ -1846,7 +726,7 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
1846
726
  optField(ctx, config, "walletMinted", config.walletMinted, vars),
1847
727
  optField(ctx, config, "walletMax", config.walletMax, vars),
1848
728
  io(ctx, () => ctx.client.getBalance({ address: payer })).catch(rpcError),
1849
- 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(
1850
730
  (v) => toBigInt(v, "price.currency.address")
1851
731
  ) : Promise.resolve(null)
1852
732
  ]);
@@ -1858,7 +738,7 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
1858
738
  if (remaining === 0n) {
1859
739
  ineligible = { reason: "WALLET_LIMIT", message: `This wallet has already minted its limit of ${walletMax}.` };
1860
740
  } else if (drop.paymentToken === null && native >= totalPrice) {
1861
- const call = { payer, to: getAddress4(config.address), data: encodeMint(config, vars), value: mintValue(config, null, totalPrice) };
741
+ const call = { payer, to: getAddress2(config.address), data: encodeMint(config, vars), value: mintValue(config, null, totalPrice) };
1862
742
  try {
1863
743
  await simulateMint(ctx, config, call);
1864
744
  gas = await io(ctx, () => ctx.client.estimateGas({ account: payer, to: call.to, data: call.data, value: call.value })).catch((e) => {
@@ -1881,7 +761,7 @@ async function readWallet(ctx, config, { payer, recipient, quantity, drop }) {
1881
761
  gasReserve: gas * gasPrice
1882
762
  };
1883
763
  }
1884
- async function buildPlan2(ctx, attempt, wallet) {
764
+ async function buildPlan(ctx, attempt, wallet) {
1885
765
  void wallet;
1886
766
  const { config, payer, recipient } = attempt;
1887
767
  validateContractConfig(config);
@@ -1889,7 +769,7 @@ async function buildPlan2(ctx, attempt, wallet) {
1889
769
  const qty = BigInt(attempt.quantity);
1890
770
  const unitPrice = await resolvePrice(ctx, config);
1891
771
  const totalPrice = totalFor(config.price.per ?? "unit", unitPrice, qty);
1892
- const to = getAddress4(config.address);
772
+ const to = getAddress2(config.address);
1893
773
  const token = erc20Of(config);
1894
774
  const mint = {
1895
775
  to,
@@ -1899,7 +779,7 @@ async function buildPlan2(ctx, attempt, wallet) {
1899
779
  let approve = null;
1900
780
  if (token) {
1901
781
  const allowance = toBigInt(
1902
- 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"),
1903
783
  "price.currency.address"
1904
784
  );
1905
785
  if (allowance < totalPrice) {
@@ -1907,134 +787,17 @@ async function buildPlan2(ctx, attempt, wallet) {
1907
787
  token,
1908
788
  spender: to,
1909
789
  amount: totalPrice,
1910
- tx: { to: token, data: encodeFunctionData2({ abi: ERC20_ABI2, functionName: "approve", args: [to, totalPrice] }), value: 0n }
790
+ tx: { to: token, data: encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [to, totalPrice] }), value: 0n }
1911
791
  };
1912
792
  }
1913
793
  }
1914
- return { approve, mint, tokenContract: getAddress4(attempt.tokenContract) };
794
+ return { approve, mint, tokenContract: getAddress2(attempt.tokenContract) };
1915
795
  }
1916
796
  async function simulate(ctx, attempt, plan) {
1917
797
  throwIfAborted(ctx);
1918
798
  await simulateMint(ctx, attempt.config, { payer: attempt.payer, to: plan.mint.to, data: plan.mint.data, value: plan.mint.value });
1919
799
  }
1920
- var contractAdapter = { readDrop, readWallet, buildPlan: buildPlan2, simulate };
1921
-
1922
- // src/core/adapters/receipt.ts
1923
- import { decodeAbiParameters, getAddress as getAddress5, zeroAddress as zeroAddress3 } from "viem";
1924
- var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
1925
- var TRANSFER_SINGLE_TOPIC = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62";
1926
- var TRANSFER_BATCH_TOPIC = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb";
1927
- var topicAddress = (t) => t && t.length === 66 ? getAddress5(`0x${t.slice(26)}`) : null;
1928
- function parseMintReceipt(logs, { tokenContract, recipient }) {
1929
- const contract = getAddress5(tokenContract);
1930
- const to = getAddress5(recipient);
1931
- const out = /* @__PURE__ */ new Map();
1932
- const add = (id, amount) => out.set(id, (out.get(id) ?? 0n) + amount);
1933
- for (const log of logs) {
1934
- if (getAddress5(log.address) !== contract) continue;
1935
- const [t0, t1, t2, t3] = log.topics;
1936
- if (t0 === TRANSFER_TOPIC && log.topics.length === 4) {
1937
- if (topicAddress(t1) !== zeroAddress3 || topicAddress(t2) !== to || !t3) continue;
1938
- add(BigInt(t3), 1n);
1939
- } else if (t0 === TRANSFER_SINGLE_TOPIC && log.topics.length === 4) {
1940
- if (topicAddress(t2) !== zeroAddress3 || topicAddress(t3) !== to) continue;
1941
- const [id, value] = decodeAbiParameters([{ type: "uint256" }, { type: "uint256" }], log.data);
1942
- add(id, value);
1943
- } else if (t0 === TRANSFER_BATCH_TOPIC && log.topics.length === 4) {
1944
- if (topicAddress(t2) !== zeroAddress3 || topicAddress(t3) !== to) continue;
1945
- const [ids, values] = decodeAbiParameters([{ type: "uint256[]" }, { type: "uint256[]" }], log.data);
1946
- if (ids.length !== values.length) continue;
1947
- ids.forEach((id, i) => add(id, values[i]));
1948
- }
1949
- }
1950
- return [...out].map(([tokenId, amount]) => ({ contract, tokenId, amount }));
1951
- }
1952
-
1953
- // src/core/friendly-errors.ts
1954
- var GENERIC = "Transaction failed. Please try again. If it fails again, please contact support.";
1955
- var REVERTED = "Transaction reverted";
1956
- var record = (value) => value !== null && typeof value === "object" ? value : void 0;
1957
- var text = (value) => typeof value === "string" ? value.toLowerCase() : "";
1958
- function collect(error) {
1959
- const pending = [error];
1960
- const seen = /* @__PURE__ */ new Set();
1961
- const errors = [];
1962
- while (pending.length) {
1963
- const e = record(pending.pop());
1964
- if (!e || seen.has(e)) continue;
1965
- seen.add(e);
1966
- const data = record(e.data);
1967
- errors.push({
1968
- name: e.name,
1969
- code: e.code,
1970
- cancelled: e.cancelled,
1971
- replacement: e.replacement,
1972
- message: [e.message, e.shortMessage, isMintError(e) ? void 0 : e.reason, data?.message].map(text).join("\n")
1973
- });
1974
- pending.push(e.cause, data?.originalError);
1975
- }
1976
- return errors;
1977
- }
1978
- function fundsMessage(errors) {
1979
- const hasText = (phrase) => errors.some((e) => e.message.includes(phrase));
1980
- if (hasText("insufficient funds for gas")) {
1981
- 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.";
1982
- }
1983
- if (errors.some((e) => e.name === "InsufficientFundsError" || e.code === "INSUFFICIENT_FUNDS") || hasText("insufficient funds") || hasText("balance too low to proceed")) {
1984
- 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.";
1985
- }
1986
- return null;
1987
- }
1988
- function friendlyErrorMessage(error) {
1989
- if (isMintError(error)) {
1990
- if (error.reason === "INSUFFICIENT_FUNDS") return fundsMessage(collect(error.cause)) ?? error.message;
1991
- if (error.reason !== "RPC_ERROR" && error.reason !== "SIMULATION_REVERTED") return error.message;
1992
- if (error.reason === "SIMULATION_REVERTED" && error.domain === "relay") return error.message;
1993
- 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;
1994
- }
1995
- const errors = collect(error);
1996
- const hasText = (phrase) => errors.some((e) => e.message.includes(phrase));
1997
- const hasName = (name) => errors.some((e) => e.name === name);
1998
- const hasCode2 = (code2) => errors.some((e) => e.code === code2);
1999
- 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)) {
2000
- return "Transaction Rejected";
2001
- }
2002
- if (hasCode2(4902)) return "Network not available in wallet";
2003
- const replaced = errors.find((e) => e.name === "TransactionReplacedError" || e.code === "TRANSACTION_REPLACED");
2004
- if (replaced?.cancelled) return "Transaction was cancelled";
2005
- if (replaced?.replacement) return "Transaction was replaced with a new transaction (usually due to speed up)";
2006
- if (hasText("ledger")) return "Error with Ledger device. Please ensure device is connected and unlocked";
2007
- if (errors.some((e) => e.code === -32002 && e.message.includes("pending"))) {
2008
- return "Transaction already pending in wallet. Please check your wallet";
2009
- }
2010
- if (hasText("invalid amount")) return "Price calculation is incorrect, contact support!";
2011
- const funds = fundsMessage(errors);
2012
- if (funds) return funds;
2013
- if (hasName("NonceTooLowError") || hasName("NonceExhaustedError") || hasText("nonce too low")) {
2014
- return "Transaction nonce is too low. Please try again";
2015
- }
2016
- if (hasName("FeeCapTooLowError") || hasText("max fee per gas less than block base fee")) {
2017
- return "Gas price too low for current network conditions. Please try again";
2018
- }
2019
- if (hasName("TimeoutError") || hasCode2("TIMEOUT") || hasText("timeout")) {
2020
- return "Transaction timed out. Your wallet connection is having issues. Disconnect and reconnect your wallet, then please try again";
2021
- }
2022
- if (hasText("network disconnected")) return "Network connection lost. Please check your internet connection and try again";
2023
- if (hasName("ChainMismatchError") || hasText("wrong network")) return "Wrong network selected. Please switch to the correct network";
2024
- if (hasText("erc20: transfer amount exceeds balance")) {
2025
- return "You do not have the required amount of ERC20 tokens to complete this transaction.";
2026
- }
2027
- if (hasName("EstimateGasExecutionError") || hasCode2("UNPREDICTABLE_GAS_LIMIT") || hasText("cannot estimate gas")) {
2028
- return "Unable to estimate gas for transaction. The transaction may fail. Please try again.";
2029
- }
2030
- if (hasName("ContractFunctionExecutionError") || hasCode2("CALL_EXCEPTION")) {
2031
- return "Transaction failed due to contract execution error";
2032
- }
2033
- if (hasName("ContractFunctionRevertedError") || hasName("ExecutionRevertedError") || hasText("revert")) return REVERTED;
2034
- if (hasName("TransactionExecutionError")) return "Transaction execution failed";
2035
- if (hasCode2("NETWORK_ERROR") || hasName("HttpRequestError") || hasText("network")) return "Network error occurred";
2036
- return isMintError(error) && error.reason === "SIMULATION_REVERTED" ? REVERTED : GENERIC;
2037
- }
800
+ var contractAdapter = { readDrop, readWallet, buildPlan, simulate };
2038
801
 
2039
802
  // src/react/useMint.ts
2040
803
  var REFRESH_MS = 3e4;
@@ -2077,22 +840,6 @@ function eventAddressOf(config) {
2077
840
  return config.type === "manifold-claim" ? config.creatorContract : config.address;
2078
841
  }
2079
842
  var isUnsupported = (reason) => UNSUPPORTED_REASONS.includes(reason);
2080
- function isRejection(error) {
2081
- for (let e = error, depth = 0; e && depth < 8; depth++) {
2082
- if (e.code === 4001) return true;
2083
- e = e.cause;
2084
- }
2085
- return false;
2086
- }
2087
- function toReason(e) {
2088
- if (isMintError(e)) return { reason: e.reason, message: friendlyErrorMessage(e) };
2089
- if (isRejection(e)) return { reason: "USER_REJECTED", message: "You rejected the request." };
2090
- for (let cause = e, depth = 0; cause && depth < 8; depth++) {
2091
- if (cause.name === "ChainMismatchError") return { reason: "CHAIN_SWITCH_FAILED", message: "The wallet network changed before the transaction was sent." };
2092
- cause = cause.cause;
2093
- }
2094
- return { reason: "RPC_ERROR", message: friendlyErrorMessage(e) };
2095
- }
2096
843
  function errorReasonOf(e) {
2097
844
  const { reason, message } = toReason(e);
2098
845
  const ok = ["USER_REJECTED", "TX_REVERTED", "RATE_LIMITED", "RPC_ERROR", "CHAIN_SWITCH_FAILED", "ALLOWLIST_UNAVAILABLE"];
@@ -2273,7 +1020,7 @@ function useMint(options) {
2273
1020
  if (cancelled) throw new MintError("USER_REJECTED", "The transaction was cancelled or replaced with a different transaction.");
2274
1021
  if (await walletFor().getChainId() !== attempt.chainId) throw e;
2275
1022
  assertActive();
2276
- receipt2 = await walletFor().extend(publicActions2).waitForTransactionReceipt(params);
1023
+ receipt2 = await walletFor().extend(publicActions).waitForTransactionReceipt(params);
2277
1024
  }
2278
1025
  assertActive();
2279
1026
  if (cancelled) throw new MintError("USER_REJECTED", "The transaction was cancelled or replaced with a different transaction.");
@@ -2296,7 +1043,7 @@ function useMint(options) {
2296
1043
  }
2297
1044
  } catch (e) {
2298
1045
  if (isMintError(e)) throw e;
2299
- const reverted = e instanceof BaseError3 ? e.walk((cause) => cause instanceof ExecutionRevertedError) : null;
1046
+ const reverted = e instanceof BaseError2 ? e.walk((cause) => cause instanceof ExecutionRevertedError) : null;
2300
1047
  if (reverted instanceof ExecutionRevertedError) {
2301
1048
  throw new MintError("SIMULATION_REVERTED", reverted.shortMessage);
2302
1049
  }
@@ -2866,13 +1613,13 @@ function useMint(options) {
2866
1613
 
2867
1614
  // src/react/PayWithPicker.ts
2868
1615
  import { createElement, useCallback as useCallback2, useEffect as useEffect2, useState as useState2 } from "react";
2869
- import { formatUnits as formatUnits5 } from "viem";
1616
+ import { formatUnits as formatUnits3 } from "viem";
2870
1617
  var PICKER_REFRESH_MS = 2e4;
2871
1618
  var PICKER_DEBOUNCE_MS = 500;
2872
1619
  var RELAY_REASONS = /* @__PURE__ */ new Set(["BRIDGE_UNAVAILABLE", "BRIDGE_TIMEOUT", "BRIDGE_REFUNDED", "BRIDGE_FAILED"]);
2873
- var money4 = (value, chainId) => {
1620
+ var money2 = (value, chainId) => {
2874
1621
  const c = getChain(chainId).nativeCurrency;
2875
- return { value, decimals: c.decimals, symbol: c.symbol, formatted: formatUnits5(value, c.decimals) };
1622
+ return { value, decimals: c.decimals, symbol: c.symbol, formatted: formatUnits3(value, c.decimals) };
2876
1623
  };
2877
1624
  function usePayOptions(mint, onSelect) {
2878
1625
  const info = mint.crossChain;
@@ -2948,7 +1695,7 @@ function usePayOptions(mint, onSelect) {
2948
1695
  isDropChain,
2949
1696
  relayFee: isDropChain ? null : quoted?.relayFee ?? null,
2950
1697
  amountIn: isDropChain ? null : quoted?.amountIn ?? null,
2951
- balance: balance && balance.chainId === chainId && chainId === current ? money4(balance.value, chainId) : null,
1698
+ balance: balance && balance.chainId === chainId && chainId === current ? money2(balance.value, chainId) : null,
2952
1699
  loading: !isDropChain && q === void 0,
2953
1700
  select: () => select(chainId)
2954
1701
  };
@@ -3059,7 +1806,7 @@ function MintButton(props) {
3059
1806
  }
3060
1807
 
3061
1808
  // src/index.ts
3062
- var VERSION = "0.2.0";
1809
+ var VERSION = "0.3.0";
3063
1810
  export {
3064
1811
  CLICKABLE_STATES,
3065
1812
  MAX_QUANTITY,