diff --git a/CLAUDE.md b/CLAUDE.md
index 3c75d9b..7c96b06 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,6 +1,6 @@
# XClawRouter
-Smart LLM router for autonomous agents. 55+ models. Wallet-based auth. USDC micropayments via x402.
+Smart LLM router for autonomous agents. 60+ models. Wallet-based auth. USDC micropayments via x402.
## Commands
diff --git a/README.md b/README.md
index 544d04e..e729385 100644
--- a/README.md
+++ b/README.md
@@ -34,7 +34,7 @@ Agents can only sign transactions.
-> **ClawRouter** is an open-source smart LLM router that reduces AI API costs by up to 92%. It analyzes each request across 15 dimensions and routes to the cheapest capable model in under 1ms, entirely locally. ClawRouter is the only LLM router built for autonomous AI agents — it uses wallet signatures for authentication (no API keys) and USDC micropayments via the x402 protocol (no credit cards). 55+ models from OpenAI, Anthropic, Google, xAI, DeepSeek, and more. MIT licensed.
+> **ClawRouter** is an open-source smart LLM router that reduces AI API costs by up to 92%. It analyzes each request across 15 dimensions and routes to the cheapest capable model in under 1ms, entirely locally. ClawRouter is the only LLM router built for autonomous AI agents — it uses wallet signatures for authentication (no API keys) and USDC micropayments via the x402 protocol (no credit cards). 60+ models from OpenAI, Anthropic, Google, xAI, DeepSeek, and more. MIT licensed.
---
@@ -59,16 +59,16 @@ This is the stack that lets agents operate autonomously: **x402 + USDC + local r
## How it compares
-| | OpenRouter | LiteLLM | Martian | Portkey | **ClawRouter** |
-| ---------------- | ----------------- | ---------------- | ----------------- | ----------------- | ----------------------- |
-| **Models** | 200+ | 100+ | Smart routing | Gateway | **55+** |
-| **Free tier** | Rate-limited | BYO keys | No | No | **8 models, no signup** |
-| **Routing** | Manual selection | Manual selection | Smart (closed) | Observability | **Smart (open source)** |
-| **Auth** | Account + API key | Your API keys | Account + API key | Account + API key | **Wallet signature** |
-| **Payment** | Credit card | BYO keys | Credit card | $49-499/mo | **USDC per-request** |
-| **Runs locally** | No | Yes | No | No | **Yes** |
-| **Open source** | No | Yes | No | Partial | **Yes** |
-| **Agent-ready** | No | No | No | No | **Yes** |
+| | OpenRouter | LiteLLM | Martian | Portkey | **ClawRouter** |
+| ---------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ |
+| **Models** | 200+ | 100+ | Smart routing | Gateway | **60+** |
+| **Free tier** | Rate-limited | BYO keys | No | No | **10 models, no signup** |
+| **Routing** | Manual selection | Manual selection | Smart (closed) | Observability | **Smart (open source)** |
+| **Auth** | Account + API key | Your API keys | Account + API key | Account + API key | **Wallet signature** |
+| **Payment** | Credit card | BYO keys | Credit card | $49-499/mo | **USDC per-request** |
+| **Runs locally** | No | Yes | No | No | **Yes** |
+| **Open source** | No | Yes | No | Partial | **Yes** |
+| **Agent-ready** | No | No | No | No | **Yes** |
✓ Open source · ✓ Smart routing · ✓ Runs locally · ✓ Crypto native · ✓ Agent ready
@@ -78,7 +78,7 @@ This is the stack that lets agents operate autonomously: **x402 + USDC + local r
## Quick Start
-> **No wallet? 10 models work free out of the box.** Install, run, and pin `nvidia/gpt-oss-120b` (or any of the 10) — no crypto, no signup, no balance required. Add USDC later when you want paid models.
+> **No wallet? 10 models work free out of the box.** Install, run, and pin `free/gpt-oss-120b` (or any of the 10) — no crypto, no signup, no balance required. Add USDC later when you want paid models.
### Option A — OpenClaw Agent
@@ -127,7 +127,7 @@ npx @blockrun/xclawrouter
```
**2. Fund your wallet** — optional, skip for free tier
-Your wallet address is printed on first run. For paid models, send a few USDC on Base or Solana — $5 covers thousands of requests. To stay at $0, pin any of the 10 free models (e.g. `nvidia/gpt-oss-120b`) or use `/model free` inside OpenClaw.
+Your wallet address is printed on first run. For paid models, send a few USDC on Base or Solana — $5 covers thousands of requests. To stay at $0, pin any of the 10 free models (e.g. `free/gpt-oss-120b`) or use `/model free` inside OpenClaw.
**3. Point your client at `http://localhost:8402`**
@@ -218,7 +218,7 @@ Request → Weighted Scorer (15 dimensions) → Tier → Best Model → Response
| Tier | ECO Model | AUTO Model | PREMIUM Model |
| --------- | ----------------------------------- | ------------------------------------- | ---------------------------- |
-| SIMPLE | nvidia/gpt-oss-120b (**FREE**) | gemini-2.5-flash ($0.30/$2.50) | kimi-k2.6 |
+| SIMPLE | free/gpt-oss-120b (**FREE**) | gemini-2.5-flash ($0.30/$2.50) | kimi-k2.6 |
| MEDIUM | gemini-3.1-flash-lite ($0.25/$1.50) | kimi-k2.5 ($0.60/$3.00) | gpt-5.3-codex ($1.75/$14.00) |
| COMPLEX | gemini-3.1-flash-lite ($0.25/$1.50) | gemini-3.1-pro ($2/$12) | claude-opus-4.6 ($5/$25) |
| REASONING | grok-4-1-fast ($0.20/$0.50) | grok-4-1-fast-reasoning ($0.20/$0.50) | claude-sonnet-4.6 ($3/$15) |
@@ -297,49 +297,53 @@ Edit existing images with `/img2img`:
## Models & Pricing
-55+ models across 9 providers, one wallet. **Starting at $0.0002/request.**
+60+ models across 9 providers, one wallet. **Starting at $0.0002/request.**
> **💡 "Cost per request"** = estimated cost for a typical chat message (~500 input + 500 output tokens).
### Budget Models (under $0.001/request)
-| Model | Input $/M | Output $/M | ~$/request | Context | Features |
-| --------------------------------------------- | --------: | ---------: | ---------: | ------- | -------------------------------------------- |
-| nvidia/gpt-oss-120b | **FREE** | **FREE** | **$0** | 128K | default free model |
-| nvidia/gpt-oss-20b | **FREE** | **FREE** | **$0** | 128K | smaller, faster |
-| nvidia/mistral-small-4-119b | **FREE** | **FREE** | **$0** | 131K | fastest free chat (114 tok/s) |
-| nvidia/deepseek-v4-pro | **FREE** | **FREE** | **$0** | 1M | reasoning, MMLU-Pro 87.5 |
-| nvidia/deepseek-v4-flash | **FREE** | **FREE** | **$0** | 1M | reasoning, ~5x faster than v4-pro |
-| nvidia/qwen3-next-80b-a3b-thinking | **FREE** | **FREE** | **$0** | 131K | reasoning |
-| nvidia/qwen3-coder-480b | **FREE** | **FREE** | **$0** | 131K | coding |
-| nvidia/glm-4.7 | **FREE** | **FREE** | **$0** | 131K | reasoning |
-| nvidia/llama-4-maverick | **FREE** | **FREE** | **$0** | 131K | reasoning |
-| nvidia/nemotron-3-nano-omni-30b-a3b-reasoning | **FREE** | **FREE** | **$0** | 256K | reasoning, **vision** (text+img+video+audio) |
-| openai/gpt-5-nano | $0.05 | $0.40 | $0.0002 | 128K | tools |
-| openai/gpt-4.1-nano | $0.10 | $0.40 | $0.0003 | 128K | tools |
-| google/gemini-2.5-flash-lite | $0.10 | $0.40 | $0.0003 | 1M | tools |
-| openai/gpt-4o-mini | $0.15 | $0.60 | $0.0004 | 128K | tools |
-| xai/grok-4-fast | $0.20 | $0.50 | $0.0004 | 131K | tools |
-| xai/grok-4-fast-reasoning | $0.20 | $0.50 | $0.0004 | 131K | reasoning, tools |
-| xai/grok-4-1-fast | $0.20 | $0.50 | $0.0004 | 131K | tools |
-| xai/grok-4-1-fast-reasoning | $0.20 | $0.50 | $0.0004 | 131K | reasoning, tools |
-| xai/grok-4-0709 | $0.20 | $1.50 | $0.0009 | 131K | reasoning, tools |
-| openai/gpt-5-mini | $0.25 | $2.00 | $0.0011 | 200K | tools |
-| deepseek/deepseek-chat | $0.28 | $0.42 | $0.0004 | 128K | tools |
-| deepseek/deepseek-reasoner | $0.28 | $0.42 | $0.0004 | 128K | reasoning, tools |
-| xai/grok-3-mini | $0.30 | $0.50 | $0.0004 | 131K | tools |
-| minimax/minimax-m2.7 | $0.30 | $1.20 | $0.0008 | 205K | reasoning, agentic, tools |
-| minimax/minimax-m2.5 | $0.30 | $1.20 | $0.0008 | 205K | reasoning, agentic, tools |
-| google/gemini-2.5-flash | $0.30 | $2.50 | $0.0014 | 1M | vision, tools |
-| openai/gpt-4.1-mini | $0.40 | $1.60 | $0.0010 | 128K | tools |
-| google/gemini-3-flash-preview | $0.50 | $3.00 | $0.0018 | 1M | vision |
-| moonshot/kimi-k2.5 | $0.60 | $3.00 | $0.0018 | 262K | reasoning, vision, agentic, tools |
-| moonshot/kimi-k2.6 | $0.95 | $4.00 | $0.0025 | 262K | reasoning, vision, agentic, tools |
+| Model | Input $/M | Output $/M | ~$/request | Context | Features |
+| ------------------------------------------- | --------: | ---------: | ---------: | ------- | -------------------------------------------- |
+| free/gpt-oss-120b | **FREE** | **FREE** | **$0** | 128K | default free model |
+| free/gpt-oss-20b | **FREE** | **FREE** | **$0** | 128K | smaller, faster |
+| free/mistral-small-4-119b | **FREE** | **FREE** | **$0** | 131K | fastest free chat (114 tok/s) |
+| free/deepseek-v4-pro | **FREE** | **FREE** | **$0** | 1M | reasoning, MMLU-Pro 87.5 |
+| free/deepseek-v4-flash | **FREE** | **FREE** | **$0** | 1M | reasoning, ~5x faster than v4-pro |
+| free/qwen3-next-80b-a3b-thinking | **FREE** | **FREE** | **$0** | 131K | reasoning |
+| free/qwen3-coder-480b | **FREE** | **FREE** | **$0** | 131K | coding |
+| free/glm-4.7 | **FREE** | **FREE** | **$0** | 131K | reasoning |
+| free/llama-4-maverick | **FREE** | **FREE** | **$0** | 131K | reasoning |
+| free/nemotron-3-nano-omni-30b-a3b-reasoning | **FREE** | **FREE** | **$0** | 256K | reasoning, **vision** (text+img+video+audio) |
+| openai/gpt-5-nano | $0.05 | $0.40 | $0.0002 | 128K | tools |
+| openai/gpt-4.1-nano | $0.10 | $0.40 | $0.0003 | 128K | tools |
+| google/gemini-2.5-flash-lite | $0.10 | $0.40 | $0.0003 | 1M | tools |
+| openai/gpt-4o-mini | $0.15 | $0.60 | $0.0004 | 128K | tools |
+| xai/grok-4-fast | $0.20 | $0.50 | $0.0004 | 131K | tools |
+| xai/grok-4-fast-reasoning | $0.20 | $0.50 | $0.0004 | 131K | reasoning, tools |
+| xai/grok-4-fast-non-reasoning | $0.20 | $0.50 | $0.0003 | 131K | tools |
+| xai/grok-4-1-fast | $0.20 | $0.50 | $0.0004 | 131K | tools |
+| xai/grok-4-1-fast-reasoning | $0.20 | $0.50 | $0.0004 | 131K | reasoning, tools |
+| xai/grok-4-1-fast-non-reasoning | $0.20 | $0.50 | $0.0003 | 131K | tools |
+| openai/gpt-5.4-nano | $0.20 | $1.25 | $0.0007 | 1M | tools |
+| openai/gpt-5-mini | $0.25 | $2.00 | $0.0011 | 200K | tools |
+| google/gemini-3.1-flash-lite | $0.25 | $1.50 | $0.0009 | 1M | tools |
+| deepseek/deepseek-chat | $0.28 | $0.42 | $0.0004 | 128K | tools |
+| deepseek/deepseek-reasoner | $0.28 | $0.42 | $0.0004 | 128K | reasoning, tools |
+| xai/grok-3-mini | $0.30 | $0.50 | $0.0004 | 131K | tools |
+| minimax/minimax-m2.7 | $0.30 | $1.20 | $0.0008 | 205K | reasoning, agentic, tools |
+| minimax/minimax-m2.5 | $0.30 | $1.20 | $0.0008 | 205K | reasoning, agentic, tools |
+| google/gemini-2.5-flash | $0.30 | $2.50 | $0.0014 | 1M | vision, tools |
+| openai/gpt-4.1-mini | $0.40 | $1.60 | $0.0010 | 128K | tools |
+| google/gemini-3-flash-preview | $0.50 | $3.00 | $0.0018 | 1M | vision |
+| moonshot/kimi-k2.5 | $0.60 | $3.00 | $0.0018 | 262K | reasoning, vision, agentic, tools |
+| moonshot/kimi-k2.6 | $0.95 | $4.00 | $0.0025 | 262K | reasoning, vision, agentic, tools |
### Mid-Range Models ($0.001–$0.01/request)
| Model | Input $/M | Output $/M | ~$/request | Context | Features |
| --------------------------- | --------: | ---------: | ---------: | ------- | --------------------------------- |
+| openai/gpt-5.4-mini | $0.75 | $4.50 | $0.0026 | 400K | vision, agentic, tools |
| anthropic/claude-haiku-4.5 | $1.00 | $5.00 | $0.0030 | 200K | vision, agentic, tools |
| zai/glm-5 | $1.00 | $3.20 | $0.0021 | 200K | tools |
| openai/o1-mini | $1.10 | $4.40 | $0.0028 | 128K | reasoning, tools |
@@ -355,6 +359,9 @@ Edit existing images with `/img2img`:
| google/gemini-3-pro-preview | $2.00 | $12.00 | $0.0070 | 1M | reasoning, vision, tools |
| google/gemini-3.1-pro | $2.00 | $12.00 | $0.0070 | 1M | reasoning, vision, tools |
| xai/grok-2-vision | $2.00 | $10.00 | $0.0060 | 131K | vision, tools |
+| xai/grok-4.20-reasoning | $2.00 | $6.00 | $0.0040 | 2M | reasoning, tools |
+| xai/grok-4.20-non-reasoning | $2.00 | $6.00 | $0.0040 | 2M | tools |
+| xai/grok-4.20-multi-agent | $2.00 | $6.00 | $0.0040 | 2M | reasoning, tools |
| openai/gpt-4o | $2.50 | $10.00 | $0.0063 | 128K | vision, agentic, tools |
| openai/gpt-5.4 | $2.50 | $15.00 | $0.0088 | 400K | reasoning, vision, agentic, tools |
@@ -364,6 +371,7 @@ Edit existing images with `/img2img`:
| --------------------------- | --------: | ---------: | ---------: | ------- | --------------------------------- |
| anthropic/claude-sonnet-4.6 | $3.00 | $15.00 | $0.0090 | 200K | reasoning, vision, agentic, tools |
| xai/grok-3 | $3.00 | $15.00 | $0.0090 | 131K | reasoning, tools |
+| xai/grok-4-0709 | $3.00 | $15.00 | $0.0090 | 131K | reasoning, tools |
| anthropic/claude-opus-4.6 | $5.00 | $25.00 | $0.0150 | 200K | reasoning, vision, agentic, tools |
| openai/gpt-5.5 | $5.00 | $30.00 | $0.0175 | 1M | reasoning, vision, agentic, tools |
| openai/o1 | $15.00 | $60.00 | $0.0375 | 200K | reasoning, tools |
@@ -446,7 +454,7 @@ For basic usage, no configuration needed. For advanced options:
Block specific models from being routed to. Useful if a model doesn't follow your agent instructions or you want to control costs.
```bash
-/exclude add nvidia/gpt-oss-120b # Block the default free model
+/exclude add free/gpt-oss-120b # Block the default free model
/exclude add grok-4 # Aliases work — blocks all grok-4 variants
/exclude add gpt-5.4 # Skip expensive models
/exclude # Show current exclusions
@@ -540,7 +548,7 @@ npm test
**The LLM router built for autonomous agents**
-You're here. 55+ models, local smart routing, x402 USDC payments — the only stack that lets agents operate independently.
+You're here. 60+ models, local smart routing, x402 USDC payments — the only stack that lets agents operate independently.
`curl -fsSL https://blockrun.ai/XClawRouter-update | bash`
@@ -551,7 +559,7 @@ You're here. 55+ models, local smart routing, x402 USDC payments — the only st
**BlockRun for Claude Code**
-Run Claude Code with 50+ models, no rate limits, no Anthropic account, no phone verification. Pay per request with USDC — your wallet is your identity.
+Run Claude Code with 60+ models, no rate limits, no Anthropic account, no phone verification. Pay per request with USDC — your wallet is your identity.
`curl -fsSL https://blockrun.ai/brcc-install | bash`
diff --git a/dist/cli.js b/dist/cli.js
index 6f58d30..acbf513 100755
--- a/dist/cli.js
+++ b/dist/cli.js
@@ -985,6 +985,22 @@ var init_exports = __esm({
}
});
+// node_modules/viem/_esm/utils/getAction.js
+function getAction(client, actionFn, name) {
+ const action_implicit = client[actionFn.name];
+ if (typeof action_implicit === "function")
+ return action_implicit;
+ const action_explicit = client[name];
+ if (typeof action_explicit === "function")
+ return action_explicit;
+ return (params) => actionFn(client, params);
+}
+var init_getAction = __esm({
+ "node_modules/viem/_esm/utils/getAction.js"() {
+ "use strict";
+ }
+});
+
// node_modules/viem/_esm/utils/abi/formatAbiItem.js
function formatAbiItem2(abiItem, { includeName = false } = {}) {
if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error")
@@ -1448,6 +1464,22 @@ var init_abi = __esm({
}
});
+// node_modules/viem/_esm/errors/log.js
+var FilterTypeNotSupportedError;
+var init_log = __esm({
+ "node_modules/viem/_esm/errors/log.js"() {
+ "use strict";
+ init_base();
+ FilterTypeNotSupportedError = class extends BaseError2 {
+ constructor(type) {
+ super(`Filter type "${type}" is not supported.`, {
+ name: "FilterTypeNotSupportedError"
+ });
+ }
+ };
+ }
+});
+
// node_modules/viem/_esm/errors/data.js
var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError, InvalidBytesLengthError;
var init_data = __esm({
@@ -2845,6 +2877,114 @@ var init_getAbiItem = __esm({
}
});
+// node_modules/viem/_esm/utils/abi/encodeEventTopics.js
+function encodeEventTopics(parameters) {
+ const { abi: abi2, eventName, args } = parameters;
+ let abiItem = abi2[0];
+ if (eventName) {
+ const item = getAbiItem({ abi: abi2, name: eventName });
+ if (!item)
+ throw new AbiEventNotFoundError(eventName, { docsPath });
+ abiItem = item;
+ }
+ if (abiItem.type !== "event")
+ throw new AbiEventNotFoundError(void 0, { docsPath });
+ const definition = formatAbiItem2(abiItem);
+ const signature2 = toEventSelector(definition);
+ let topics = [];
+ if (args && "inputs" in abiItem) {
+ const indexedInputs = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed);
+ const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x) => args[x.name]) ?? [] : [];
+ if (args_.length > 0) {
+ topics = indexedInputs?.map((param, i) => {
+ if (Array.isArray(args_[i]))
+ return args_[i].map((_, j) => encodeArg({ param, value: args_[i][j] }));
+ return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null;
+ }) ?? [];
+ }
+ }
+ return [signature2, ...topics];
+}
+function encodeArg({ param, value }) {
+ if (param.type === "string" || param.type === "bytes")
+ return keccak256(toBytes(value));
+ if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
+ throw new FilterTypeNotSupportedError(param.type);
+ return encodeAbiParameters([param], [value]);
+}
+var docsPath;
+var init_encodeEventTopics = __esm({
+ "node_modules/viem/_esm/utils/abi/encodeEventTopics.js"() {
+ "use strict";
+ init_abi();
+ init_log();
+ init_toBytes();
+ init_keccak256();
+ init_toEventSelector();
+ init_encodeAbiParameters();
+ init_formatAbiItem2();
+ init_getAbiItem();
+ docsPath = "/docs/contract/encodeEventTopics";
+ }
+});
+
+// node_modules/viem/_esm/utils/filters/createFilterRequestScope.js
+function createFilterRequestScope(client, { method }) {
+ const requestMap = {};
+ if (client.transport.type === "fallback")
+ client.transport.onResponse?.(({ method: method_, response: id, status, transport }) => {
+ if (status === "success" && method === method_)
+ requestMap[id] = transport.request;
+ });
+ return ((id) => requestMap[id] || client.request);
+}
+var init_createFilterRequestScope = __esm({
+ "node_modules/viem/_esm/utils/filters/createFilterRequestScope.js"() {
+ "use strict";
+ }
+});
+
+// node_modules/viem/_esm/actions/public/createContractEventFilter.js
+async function createContractEventFilter(client, parameters) {
+ const { address: address2, abi: abi2, args, eventName, fromBlock, strict, toBlock } = parameters;
+ const getRequest = createFilterRequestScope(client, {
+ method: "eth_newFilter"
+ });
+ const topics = eventName ? encodeEventTopics({
+ abi: abi2,
+ args,
+ eventName
+ }) : void 0;
+ const id = await client.request({
+ method: "eth_newFilter",
+ params: [
+ {
+ address: address2,
+ fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
+ toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock,
+ topics
+ }
+ ]
+ });
+ return {
+ abi: abi2,
+ args,
+ eventName,
+ id,
+ request: getRequest(id),
+ strict: Boolean(strict),
+ type: "event"
+ };
+}
+var init_createContractEventFilter = __esm({
+ "node_modules/viem/_esm/actions/public/createContractEventFilter.js"() {
+ "use strict";
+ init_encodeEventTopics();
+ init_toHex();
+ init_createFilterRequestScope();
+ }
+});
+
// node_modules/viem/_esm/accounts/utils/parseAccount.js
function parseAccount(account) {
if (typeof account === "string")
@@ -4524,6 +4664,46 @@ var init_rpc = __esm({
}
});
+// node_modules/viem/_esm/utils/errors/getContractError.js
+function getContractError(err, { abi: abi2, address: address2, args, docsPath: docsPath8, functionName, sender }) {
+ const error = err instanceof RawContractError ? err : err instanceof BaseError2 ? err.walk((err2) => "data" in err2) || err.walk() : {};
+ const { code, data, details, message, shortMessage } = error;
+ const cause = (() => {
+ if (err instanceof AbiDecodingZeroDataError)
+ return new ContractFunctionZeroDataError({ functionName, cause: err });
+ if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage) || code === InvalidInputRpcError.code && details === "execution reverted" && data) {
+ return new ContractFunctionRevertedError({
+ abi: abi2,
+ data: typeof data === "object" ? data.data : data,
+ functionName,
+ message: error instanceof RpcRequestError ? details : shortMessage ?? message,
+ cause: err
+ });
+ }
+ return err;
+ })();
+ return new ContractFunctionExecutionError(cause, {
+ abi: abi2,
+ args,
+ contractAddress: address2,
+ docsPath: docsPath8,
+ functionName,
+ sender
+ });
+}
+var EXECUTION_REVERTED_ERROR_CODE;
+var init_getContractError = __esm({
+ "node_modules/viem/_esm/utils/errors/getContractError.js"() {
+ "use strict";
+ init_abi();
+ init_base();
+ init_contract();
+ init_request();
+ init_rpc();
+ EXECUTION_REVERTED_ERROR_CODE = 3;
+ }
+});
+
// node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
function publicKeyToAddress(publicKey) {
const address2 = keccak256(`0x${publicKey.substring(4)}`).substring(26);
@@ -7262,6 +7442,58 @@ var init_secp256k1 = __esm({
}
});
+// node_modules/viem/_esm/utils/signature/recoverPublicKey.js
+async function recoverPublicKey({ hash: hash3, signature: signature2 }) {
+ const hashHex = isHex(hash3) ? hash3 : toHex(hash3);
+ const { secp256k1: secp256k14 } = await Promise.resolve().then(() => (init_secp256k1(), secp256k1_exports));
+ const signature_ = (() => {
+ if (typeof signature2 === "object" && "r" in signature2 && "s" in signature2) {
+ const { r, s: s3, v, yParity } = signature2;
+ const yParityOrV2 = Number(yParity ?? v);
+ const recoveryBit2 = toRecoveryBit(yParityOrV2);
+ return new secp256k14.Signature(hexToBigInt(r), hexToBigInt(s3)).addRecoveryBit(recoveryBit2);
+ }
+ const signatureHex = isHex(signature2) ? signature2 : toHex(signature2);
+ if (size(signatureHex) !== 65)
+ throw new Error("invalid signature length");
+ const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`);
+ const recoveryBit = toRecoveryBit(yParityOrV);
+ return secp256k14.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit);
+ })();
+ const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false);
+ return `0x${publicKey}`;
+}
+function toRecoveryBit(yParityOrV) {
+ if (yParityOrV === 0 || yParityOrV === 1)
+ return yParityOrV;
+ if (yParityOrV === 27)
+ return 0;
+ if (yParityOrV === 28)
+ return 1;
+ throw new Error("Invalid yParityOrV value");
+}
+var init_recoverPublicKey = __esm({
+ "node_modules/viem/_esm/utils/signature/recoverPublicKey.js"() {
+ "use strict";
+ init_isHex();
+ init_size();
+ init_fromHex();
+ init_toHex();
+ }
+});
+
+// node_modules/viem/_esm/utils/signature/recoverAddress.js
+async function recoverAddress({ hash: hash3, signature: signature2 }) {
+ return publicKeyToAddress(await recoverPublicKey({ hash: hash3, signature: signature2 }));
+}
+var init_recoverAddress = __esm({
+ "node_modules/viem/_esm/utils/signature/recoverAddress.js"() {
+ "use strict";
+ init_publicKeyToAddress();
+ init_recoverPublicKey();
+ }
+});
+
// node_modules/viem/_esm/utils/encoding/toRlp.js
function toRlp(bytes, to = "hex") {
const encodable = getEncodable(bytes);
@@ -7387,6 +7619,66 @@ var init_hashAuthorization = __esm({
}
});
+// node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js
+async function recoverAuthorizationAddress(parameters) {
+ const { authorization, signature: signature2 } = parameters;
+ return recoverAddress({
+ hash: hashAuthorization(authorization),
+ signature: signature2 ?? authorization
+ });
+}
+var init_recoverAuthorizationAddress = __esm({
+ "node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js"() {
+ "use strict";
+ init_recoverAddress();
+ init_hashAuthorization();
+ }
+});
+
+// node_modules/viem/_esm/errors/estimateGas.js
+var EstimateGasExecutionError;
+var init_estimateGas = __esm({
+ "node_modules/viem/_esm/errors/estimateGas.js"() {
+ "use strict";
+ init_formatEther();
+ init_formatGwei();
+ init_base();
+ init_transaction();
+ EstimateGasExecutionError = class extends BaseError2 {
+ constructor(cause, { account, docsPath: docsPath8, chain: chain3, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) {
+ const prettyArgs = prettyPrint({
+ from: account?.address,
+ to,
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain3?.nativeCurrency?.symbol || "ETH"}`,
+ data,
+ gas,
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
+ nonce
+ });
+ super(cause.shortMessage, {
+ cause,
+ docsPath: docsPath8,
+ metaMessages: [
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
+ "Estimate Gas Arguments:",
+ prettyArgs
+ ].filter(Boolean),
+ name: "EstimateGasExecutionError"
+ });
+ Object.defineProperty(this, "cause", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: void 0
+ });
+ this.cause = cause;
+ }
+ };
+ }
+});
+
// node_modules/viem/_esm/errors/node.js
var ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, NonceTooHighError, NonceTooLowError, NonceMaxValueError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, TransactionTypeNotSupportedError, TipAboveFeeCapError, UnknownNodeError;
var init_node = __esm({
@@ -7630,6 +7922,28 @@ var init_getNodeError = __esm({
}
});
+// node_modules/viem/_esm/utils/errors/getEstimateGasError.js
+function getEstimateGasError(err, { docsPath: docsPath8, ...args }) {
+ const cause = (() => {
+ const cause2 = getNodeError(err, args);
+ if (cause2 instanceof UnknownNodeError)
+ return err;
+ return cause2;
+ })();
+ return new EstimateGasExecutionError(cause, {
+ docsPath: docsPath8,
+ ...args
+ });
+}
+var init_getEstimateGasError = __esm({
+ "node_modules/viem/_esm/utils/errors/getEstimateGasError.js"() {
+ "use strict";
+ init_estimateGas();
+ init_node();
+ init_getNodeError();
+ }
+});
+
// node_modules/viem/_esm/utils/formatters/extract.js
function extract(value_, { format }) {
if (!format)
@@ -7939,6 +8253,322 @@ var init_assertRequest = __esm({
}
});
+// node_modules/viem/_esm/errors/fee.js
+var BaseFeeScalarError, Eip1559FeesNotSupportedError, MaxFeePerGasTooLowError;
+var init_fee = __esm({
+ "node_modules/viem/_esm/errors/fee.js"() {
+ "use strict";
+ init_formatGwei();
+ init_base();
+ BaseFeeScalarError = class extends BaseError2 {
+ constructor() {
+ super("`baseFeeMultiplier` must be greater than 1.", {
+ name: "BaseFeeScalarError"
+ });
+ }
+ };
+ Eip1559FeesNotSupportedError = class extends BaseError2 {
+ constructor() {
+ super("Chain does not support EIP-1559 fees.", {
+ name: "Eip1559FeesNotSupportedError"
+ });
+ }
+ };
+ MaxFeePerGasTooLowError = class extends BaseError2 {
+ constructor({ maxPriorityFeePerGas }) {
+ super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" });
+ }
+ };
+ }
+});
+
+// node_modules/viem/_esm/errors/block.js
+var BlockNotFoundError;
+var init_block = __esm({
+ "node_modules/viem/_esm/errors/block.js"() {
+ "use strict";
+ init_base();
+ BlockNotFoundError = class extends BaseError2 {
+ constructor({ blockHash, blockNumber }) {
+ let identifier = "Block";
+ if (blockHash)
+ identifier = `Block at hash "${blockHash}"`;
+ if (blockNumber)
+ identifier = `Block at number "${blockNumber}"`;
+ super(`${identifier} could not be found.`, { name: "BlockNotFoundError" });
+ }
+ };
+ }
+});
+
+// node_modules/viem/_esm/utils/formatters/transaction.js
+function formatTransaction(transaction, _) {
+ const transaction_ = {
+ ...transaction,
+ blockHash: transaction.blockHash ? transaction.blockHash : null,
+ blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
+ chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0,
+ gas: transaction.gas ? BigInt(transaction.gas) : void 0,
+ gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
+ maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0,
+ maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
+ maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0,
+ nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0,
+ to: transaction.to ? transaction.to : null,
+ transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null,
+ type: transaction.type ? transactionType[transaction.type] : void 0,
+ typeHex: transaction.type ? transaction.type : void 0,
+ value: transaction.value ? BigInt(transaction.value) : void 0,
+ v: transaction.v ? BigInt(transaction.v) : void 0
+ };
+ if (transaction.authorizationList)
+ transaction_.authorizationList = formatAuthorizationList2(transaction.authorizationList);
+ transaction_.yParity = (() => {
+ if (transaction.yParity)
+ return Number(transaction.yParity);
+ if (typeof transaction_.v === "bigint") {
+ if (transaction_.v === 0n || transaction_.v === 27n)
+ return 0;
+ if (transaction_.v === 1n || transaction_.v === 28n)
+ return 1;
+ if (transaction_.v >= 35n)
+ return transaction_.v % 2n === 0n ? 1 : 0;
+ }
+ return void 0;
+ })();
+ if (transaction_.type === "legacy") {
+ delete transaction_.accessList;
+ delete transaction_.maxFeePerBlobGas;
+ delete transaction_.maxFeePerGas;
+ delete transaction_.maxPriorityFeePerGas;
+ delete transaction_.yParity;
+ }
+ if (transaction_.type === "eip2930") {
+ delete transaction_.maxFeePerBlobGas;
+ delete transaction_.maxFeePerGas;
+ delete transaction_.maxPriorityFeePerGas;
+ }
+ if (transaction_.type === "eip1559")
+ delete transaction_.maxFeePerBlobGas;
+ return transaction_;
+}
+function formatAuthorizationList2(authorizationList) {
+ return authorizationList.map((authorization) => ({
+ address: authorization.address,
+ chainId: Number(authorization.chainId),
+ nonce: Number(authorization.nonce),
+ r: authorization.r,
+ s: authorization.s,
+ yParity: Number(authorization.yParity)
+ }));
+}
+var transactionType, defineTransaction;
+var init_transaction2 = __esm({
+ "node_modules/viem/_esm/utils/formatters/transaction.js"() {
+ "use strict";
+ init_fromHex();
+ init_formatter();
+ transactionType = {
+ "0x0": "legacy",
+ "0x1": "eip2930",
+ "0x2": "eip1559",
+ "0x3": "eip4844",
+ "0x4": "eip7702"
+ };
+ defineTransaction = /* @__PURE__ */ defineFormatter("transaction", formatTransaction);
+ }
+});
+
+// node_modules/viem/_esm/utils/formatters/block.js
+function formatBlock(block, _) {
+ const transactions = (block.transactions ?? []).map((transaction) => {
+ if (typeof transaction === "string")
+ return transaction;
+ return formatTransaction(transaction);
+ });
+ return {
+ ...block,
+ baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
+ blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0,
+ difficulty: block.difficulty ? BigInt(block.difficulty) : void 0,
+ excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0,
+ gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0,
+ gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0,
+ hash: block.hash ? block.hash : null,
+ logsBloom: block.logsBloom ? block.logsBloom : null,
+ nonce: block.nonce ? block.nonce : null,
+ number: block.number ? BigInt(block.number) : null,
+ size: block.size ? BigInt(block.size) : void 0,
+ timestamp: block.timestamp ? BigInt(block.timestamp) : void 0,
+ transactions,
+ totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null
+ };
+}
+var defineBlock;
+var init_block2 = __esm({
+ "node_modules/viem/_esm/utils/formatters/block.js"() {
+ "use strict";
+ init_formatter();
+ init_transaction2();
+ defineBlock = /* @__PURE__ */ defineFormatter("block", formatBlock);
+ }
+});
+
+// node_modules/viem/_esm/actions/public/getBlock.js
+async function getBlock(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", includeTransactions: includeTransactions_ } = {}) {
+ const includeTransactions = includeTransactions_ ?? false;
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
+ let block = null;
+ if (blockHash) {
+ block = await client.request({
+ method: "eth_getBlockByHash",
+ params: [blockHash, includeTransactions]
+ }, { dedupe: true });
+ } else {
+ block = await client.request({
+ method: "eth_getBlockByNumber",
+ params: [blockNumberHex || blockTag, includeTransactions]
+ }, { dedupe: Boolean(blockNumberHex) });
+ }
+ if (!block)
+ throw new BlockNotFoundError({ blockHash, blockNumber });
+ const format = client.chain?.formatters?.block?.format || formatBlock;
+ return format(block, "getBlock");
+}
+var init_getBlock = __esm({
+ "node_modules/viem/_esm/actions/public/getBlock.js"() {
+ "use strict";
+ init_block();
+ init_toHex();
+ init_block2();
+ }
+});
+
+// node_modules/viem/_esm/actions/public/getGasPrice.js
+async function getGasPrice(client) {
+ const gasPrice = await client.request({
+ method: "eth_gasPrice"
+ });
+ return BigInt(gasPrice);
+}
+var init_getGasPrice = __esm({
+ "node_modules/viem/_esm/actions/public/getGasPrice.js"() {
+ "use strict";
+ }
+});
+
+// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js
+async function estimateMaxPriorityFeePerGas(client, args) {
+ return internal_estimateMaxPriorityFeePerGas(client, args);
+}
+async function internal_estimateMaxPriorityFeePerGas(client, args) {
+ const { block: block_, chain: chain3 = client.chain, request } = args || {};
+ try {
+ const maxPriorityFeePerGas = chain3?.fees?.maxPriorityFeePerGas ?? chain3?.fees?.defaultPriorityFee;
+ if (typeof maxPriorityFeePerGas === "function") {
+ const block = block_ || await getAction(client, getBlock, "getBlock")({});
+ const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({
+ block,
+ client,
+ request
+ });
+ if (maxPriorityFeePerGas_ === null)
+ throw new Error();
+ return maxPriorityFeePerGas_;
+ }
+ if (typeof maxPriorityFeePerGas !== "undefined")
+ return maxPriorityFeePerGas;
+ const maxPriorityFeePerGasHex = await client.request({
+ method: "eth_maxPriorityFeePerGas"
+ });
+ return hexToBigInt(maxPriorityFeePerGasHex);
+ } catch {
+ const [block, gasPrice] = await Promise.all([
+ block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}),
+ getAction(client, getGasPrice, "getGasPrice")({})
+ ]);
+ if (typeof block.baseFeePerGas !== "bigint")
+ throw new Eip1559FeesNotSupportedError();
+ const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas;
+ if (maxPriorityFeePerGas < 0n)
+ return 0n;
+ return maxPriorityFeePerGas;
+ }
+}
+var init_estimateMaxPriorityFeePerGas = __esm({
+ "node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js"() {
+ "use strict";
+ init_fee();
+ init_fromHex();
+ init_getAction();
+ init_getBlock();
+ init_getGasPrice();
+ }
+});
+
+// node_modules/viem/_esm/actions/public/estimateFeesPerGas.js
+async function estimateFeesPerGas(client, args) {
+ return internal_estimateFeesPerGas(client, args);
+}
+async function internal_estimateFeesPerGas(client, args) {
+ const { block: block_, chain: chain3 = client.chain, request, type = "eip1559" } = args || {};
+ const baseFeeMultiplier = await (async () => {
+ if (typeof chain3?.fees?.baseFeeMultiplier === "function")
+ return chain3.fees.baseFeeMultiplier({
+ block: block_,
+ client,
+ request
+ });
+ return chain3?.fees?.baseFeeMultiplier ?? 1.2;
+ })();
+ if (baseFeeMultiplier < 1)
+ throw new BaseFeeScalarError();
+ const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0;
+ const denominator = 10 ** decimals;
+ const multiply = (base2) => base2 * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator);
+ const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({});
+ if (typeof chain3?.fees?.estimateFeesPerGas === "function") {
+ const fees = await chain3.fees.estimateFeesPerGas({
+ block: block_,
+ client,
+ multiply,
+ request,
+ type
+ });
+ if (fees !== null)
+ return fees;
+ }
+ if (type === "eip1559") {
+ if (typeof block.baseFeePerGas !== "bigint")
+ throw new Eip1559FeesNotSupportedError();
+ const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, {
+ block,
+ chain: chain3,
+ request
+ });
+ const baseFeePerGas = multiply(block.baseFeePerGas);
+ const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas;
+ return {
+ maxFeePerGas,
+ maxPriorityFeePerGas
+ };
+ }
+ const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({}));
+ return {
+ gasPrice
+ };
+}
+var init_estimateFeesPerGas = __esm({
+ "node_modules/viem/_esm/actions/public/estimateFeesPerGas.js"() {
+ "use strict";
+ init_fee();
+ init_getAction();
+ init_estimateMaxPriorityFeePerGas();
+ init_getBlock();
+ init_getGasPrice();
+ }
+});
+
// node_modules/viem/_esm/actions/public/getTransactionCount.js
async function getTransactionCount(client, { address: address2, blockTag = "latest", blockNumber }) {
const count = await client.request({
@@ -8226,812 +8856,1638 @@ var init_getTransactionType = __esm({
}
});
-// node_modules/viem/_esm/utils/address/isAddressEqual.js
-function isAddressEqual(a, b) {
- if (!isAddress(a, { strict: false }))
- throw new InvalidAddressError({ address: a });
- if (!isAddress(b, { strict: false }))
- throw new InvalidAddressError({ address: b });
- return a.toLowerCase() === b.toLowerCase();
+// node_modules/viem/_esm/utils/errors/getTransactionError.js
+function getTransactionError(err, { docsPath: docsPath8, ...args }) {
+ const cause = (() => {
+ const cause2 = getNodeError(err, args);
+ if (cause2 instanceof UnknownNodeError)
+ return err;
+ return cause2;
+ })();
+ return new TransactionExecutionError(cause, {
+ docsPath: docsPath8,
+ ...args
+ });
}
-var init_isAddressEqual = __esm({
- "node_modules/viem/_esm/utils/address/isAddressEqual.js"() {
+var init_getTransactionError = __esm({
+ "node_modules/viem/_esm/utils/errors/getTransactionError.js"() {
"use strict";
- init_address();
- init_isAddress();
+ init_node();
+ init_transaction();
+ init_getNodeError();
}
});
-// node_modules/viem/_esm/utils/abi/decodeFunctionResult.js
-function decodeFunctionResult(parameters) {
- const { abi: abi2, args, functionName, data } = parameters;
- let abiItem = abi2[0];
- if (functionName) {
- const item = getAbiItem({ abi: abi2, args, name: functionName });
- if (!item)
- throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 });
- abiItem = item;
- }
- if (abiItem.type !== "function")
- throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath4 });
- if (!abiItem.outputs)
- throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 });
- const values = decodeAbiParameters(abiItem.outputs, data);
- if (values && values.length > 1)
- return values;
- if (values && values.length === 1)
- return values[0];
- return void 0;
+// node_modules/viem/_esm/actions/public/getChainId.js
+async function getChainId(client) {
+ const chainIdHex = await client.request({
+ method: "eth_chainId"
+ }, { dedupe: true });
+ return hexToNumber(chainIdHex);
}
-var docsPath4;
-var init_decodeFunctionResult = __esm({
- "node_modules/viem/_esm/utils/abi/decodeFunctionResult.js"() {
+var init_getChainId = __esm({
+ "node_modules/viem/_esm/actions/public/getChainId.js"() {
"use strict";
- init_abi();
- init_decodeAbiParameters();
- init_getAbiItem();
- docsPath4 = "/docs/contract/decodeFunctionResult";
+ init_fromHex();
}
});
-// node_modules/ox/node_modules/@noble/curves/esm/abstract/utils.js
-function isBytes3(a) {
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
-}
-function abytes3(item) {
- if (!isBytes3(item))
- throw new Error("Uint8Array expected");
-}
-function abool2(title, value) {
- if (typeof value !== "boolean")
- throw new Error(title + " boolean expected, got " + value);
-}
-function numberToHexUnpadded2(num2) {
- const hex = num2.toString(16);
- return hex.length & 1 ? "0" + hex : hex;
-}
-function hexToNumber3(hex) {
- if (typeof hex !== "string")
- throw new Error("hex string expected, got " + typeof hex);
- return hex === "" ? _0n7 : BigInt("0x" + hex);
-}
-function bytesToHex3(bytes) {
- abytes3(bytes);
- if (hasHexBuiltin2)
- return bytes.toHex();
- let hex = "";
- for (let i = 0; i < bytes.length; i++) {
- hex += hexes3[bytes[i]];
- }
- return hex;
-}
-function asciiToBase162(ch) {
- if (ch >= asciis2._0 && ch <= asciis2._9)
- return ch - asciis2._0;
- if (ch >= asciis2.A && ch <= asciis2.F)
- return ch - (asciis2.A - 10);
- if (ch >= asciis2.a && ch <= asciis2.f)
- return ch - (asciis2.a - 10);
- return;
-}
-function hexToBytes3(hex) {
- if (typeof hex !== "string")
- throw new Error("hex string expected, got " + typeof hex);
- if (hasHexBuiltin2)
- return Uint8Array.fromHex(hex);
- const hl = hex.length;
- const al = hl / 2;
- if (hl % 2)
- throw new Error("hex string expected, got unpadded hex of length " + hl);
- const array = new Uint8Array(al);
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
- const n1 = asciiToBase162(hex.charCodeAt(hi));
- const n2 = asciiToBase162(hex.charCodeAt(hi + 1));
- if (n1 === void 0 || n2 === void 0) {
- const char = hex[hi] + hex[hi + 1];
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
- }
- array[ai] = n1 * 16 + n2;
+// node_modules/viem/_esm/actions/public/fillTransaction.js
+async function fillTransaction(client, parameters) {
+ const { account = client.account, accessList, authorizationList, chain: chain3 = client.chain, blobVersionedHashes, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce: nonce_, nonceManager, to, type, value, ...rest } = parameters;
+ const nonce = await (async () => {
+ if (!account)
+ return nonce_;
+ if (!nonceManager)
+ return nonce_;
+ if (typeof nonce_ !== "undefined")
+ return nonce_;
+ const account_ = parseAccount(account);
+ const chainId = chain3 ? chain3.id : await getAction(client, getChainId, "getChainId")({});
+ return await nonceManager.consume({
+ address: account_.address,
+ chainId,
+ client
+ });
+ })();
+ assertRequest(parameters);
+ const chainFormat = chain3?.formatters?.transactionRequest?.format;
+ const format = chainFormat || formatTransactionRequest;
+ const request = format({
+ // Pick out extra data that might exist on the chain's transaction request type.
+ ...extract(rest, { format: chainFormat }),
+ account: account ? parseAccount(account) : void 0,
+ accessList,
+ authorizationList,
+ blobs,
+ blobVersionedHashes,
+ data,
+ gas,
+ gasPrice,
+ maxFeePerBlobGas,
+ maxFeePerGas,
+ maxPriorityFeePerGas,
+ nonce,
+ to,
+ type,
+ value
+ }, "fillTransaction");
+ try {
+ const response = await client.request({
+ method: "eth_fillTransaction",
+ params: [request]
+ });
+ const format2 = chain3?.formatters?.transaction?.format || formatTransaction;
+ const transaction = format2(response.tx);
+ delete transaction.blockHash;
+ delete transaction.blockNumber;
+ delete transaction.r;
+ delete transaction.s;
+ delete transaction.transactionIndex;
+ delete transaction.v;
+ delete transaction.yParity;
+ transaction.data = transaction.input;
+ if (transaction.gas)
+ transaction.gas = parameters.gas ?? transaction.gas;
+ if (transaction.gasPrice)
+ transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice;
+ if (transaction.maxFeePerBlobGas)
+ transaction.maxFeePerBlobGas = parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas;
+ if (transaction.maxFeePerGas)
+ transaction.maxFeePerGas = parameters.maxFeePerGas ?? transaction.maxFeePerGas;
+ if (transaction.maxPriorityFeePerGas)
+ transaction.maxPriorityFeePerGas = parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas;
+ if (transaction.nonce)
+ transaction.nonce = parameters.nonce ?? transaction.nonce;
+ const feeMultiplier = await (async () => {
+ if (typeof chain3?.fees?.baseFeeMultiplier === "function") {
+ const block = await getAction(client, getBlock, "getBlock")({});
+ return chain3.fees.baseFeeMultiplier({
+ block,
+ client,
+ request: parameters
+ });
+ }
+ return chain3?.fees?.baseFeeMultiplier ?? 1.2;
+ })();
+ if (feeMultiplier < 1)
+ throw new BaseFeeScalarError();
+ const decimals = feeMultiplier.toString().split(".")[1]?.length ?? 0;
+ const denominator = 10 ** decimals;
+ const multiplyFee = (base2) => base2 * BigInt(Math.ceil(feeMultiplier * denominator)) / BigInt(denominator);
+ if (transaction.maxFeePerGas && !parameters.maxFeePerGas)
+ transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas);
+ if (transaction.gasPrice && !parameters.gasPrice)
+ transaction.gasPrice = multiplyFee(transaction.gasPrice);
+ return {
+ raw: response.raw,
+ transaction: {
+ from: request.from,
+ ...transaction
+ }
+ };
+ } catch (err) {
+ throw getTransactionError(err, {
+ ...parameters,
+ chain: client.chain
+ });
}
- return array;
-}
-function bytesToNumberBE2(bytes) {
- return hexToNumber3(bytesToHex3(bytes));
-}
-function bytesToNumberLE2(bytes) {
- abytes3(bytes);
- return hexToNumber3(bytesToHex3(Uint8Array.from(bytes).reverse()));
-}
-function numberToBytesBE2(n, len) {
- return hexToBytes3(n.toString(16).padStart(len * 2, "0"));
-}
-function numberToBytesLE2(n, len) {
- return numberToBytesBE2(n, len).reverse();
}
-function ensureBytes2(title, hex, expectedLength) {
- let res;
- if (typeof hex === "string") {
- try {
- res = hexToBytes3(hex);
- } catch (e7) {
- throw new Error(title + " must be hex string or Uint8Array, cause: " + e7);
- }
- } else if (isBytes3(hex)) {
- res = Uint8Array.from(hex);
- } else {
- throw new Error(title + " must be hex string or Uint8Array");
+var init_fillTransaction = __esm({
+ "node_modules/viem/_esm/actions/public/fillTransaction.js"() {
+ "use strict";
+ init_parseAccount();
+ init_fee();
+ init_getTransactionError();
+ init_extract();
+ init_transaction2();
+ init_transactionRequest();
+ init_getAction();
+ init_assertRequest();
+ init_getBlock();
+ init_getChainId();
}
- const len = res.length;
- if (typeof expectedLength === "number" && len !== expectedLength)
- throw new Error(title + " of length " + expectedLength + " expected, got " + len);
- return res;
-}
-function concatBytes4(...arrays) {
- let sum = 0;
- for (let i = 0; i < arrays.length; i++) {
- const a = arrays[i];
- abytes3(a);
- sum += a.length;
+});
+
+// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js
+async function prepareTransactionRequest(client, args) {
+ let request = args;
+ request.account ??= client.account;
+ request.parameters ??= defaultParameters;
+ const { account: account_, chain: chain3 = client.chain, nonceManager, parameters } = request;
+ const prepareTransactionRequest2 = (() => {
+ if (typeof chain3?.prepareTransactionRequest === "function")
+ return {
+ fn: chain3.prepareTransactionRequest,
+ runAt: ["beforeFillTransaction"]
+ };
+ if (Array.isArray(chain3?.prepareTransactionRequest))
+ return {
+ fn: chain3.prepareTransactionRequest[0],
+ runAt: chain3.prepareTransactionRequest[1].runAt
+ };
+ return void 0;
+ })();
+ let chainId;
+ async function getChainId2() {
+ if (chainId)
+ return chainId;
+ if (typeof request.chainId !== "undefined")
+ return request.chainId;
+ if (chain3)
+ return chain3.id;
+ const chainId_ = await getAction(client, getChainId, "getChainId")({});
+ chainId = chainId_;
+ return chainId;
}
- const res = new Uint8Array(sum);
- for (let i = 0, pad4 = 0; i < arrays.length; i++) {
- const a = arrays[i];
- res.set(a, pad4);
- pad4 += a.length;
+ const account = account_ ? parseAccount(account_) : account_;
+ let nonce = request.nonce;
+ if (parameters.includes("nonce") && typeof nonce === "undefined" && account && nonceManager) {
+ const chainId2 = await getChainId2();
+ nonce = await nonceManager.consume({
+ address: account.address,
+ chainId: chainId2,
+ client
+ });
}
- return res;
-}
-function inRange2(n, min, max) {
- return isPosBig2(n) && isPosBig2(min) && isPosBig2(max) && min <= n && n < max;
-}
-function aInRange2(title, n, min, max) {
- if (!inRange2(n, min, max))
- throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
-}
-function bitLen2(n) {
- let len;
- for (len = 0; n > _0n7; n >>= _1n7, len += 1)
- ;
- return len;
-}
-function createHmacDrbg2(hashLen, qByteLen, hmacFn) {
- if (typeof hashLen !== "number" || hashLen < 2)
- throw new Error("hashLen must be a number");
- if (typeof qByteLen !== "number" || qByteLen < 2)
- throw new Error("qByteLen must be a number");
- if (typeof hmacFn !== "function")
- throw new Error("hmacFn must be a function");
- let v = u8n2(hashLen);
- let k = u8n2(hashLen);
- let i = 0;
- const reset = () => {
- v.fill(1);
- k.fill(0);
- i = 0;
- };
- const h = (...b) => hmacFn(k, v, ...b);
- const reseed = (seed = u8n2(0)) => {
- k = h(u8fr2([0]), seed);
- v = h();
- if (seed.length === 0)
- return;
- k = h(u8fr2([1]), seed);
- v = h();
+ if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillTransaction")) {
+ request = await prepareTransactionRequest2.fn({ ...request, chain: chain3 }, {
+ phase: "beforeFillTransaction"
+ });
+ nonce ??= request.nonce;
+ }
+ const attemptFill = (() => {
+ if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && request.kzg && request.blobs)
+ return false;
+ if (supportsFillTransaction.get(client.uid) === false)
+ return false;
+ const shouldAttempt = ["fees", "gas"].some((parameter) => parameters.includes(parameter));
+ if (!shouldAttempt)
+ return false;
+ if (parameters.includes("chainId") && typeof request.chainId !== "number")
+ return true;
+ if (parameters.includes("nonce") && typeof nonce !== "number")
+ return true;
+ if (parameters.includes("fees") && typeof request.gasPrice !== "bigint" && (typeof request.maxFeePerGas !== "bigint" || typeof request.maxPriorityFeePerGas !== "bigint"))
+ return true;
+ if (parameters.includes("gas") && typeof request.gas !== "bigint")
+ return true;
+ return false;
+ })();
+ const fillResult = attemptFill ? await getAction(client, fillTransaction, "fillTransaction")({ ...request, nonce }).then((result) => {
+ const { chainId: chainId2, from: from14, gas: gas2, gasPrice, nonce: nonce2, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, type: type2, ...rest } = result.transaction;
+ supportsFillTransaction.set(client.uid, true);
+ return {
+ ...request,
+ ...from14 ? { from: from14 } : {},
+ ...type2 && !request.type ? { type: type2 } : {},
+ ...typeof chainId2 !== "undefined" ? { chainId: chainId2 } : {},
+ ...typeof gas2 !== "undefined" ? { gas: gas2 } : {},
+ ...typeof gasPrice !== "undefined" ? { gasPrice } : {},
+ ...typeof nonce2 !== "undefined" ? { nonce: nonce2 } : {},
+ ...typeof maxFeePerBlobGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerBlobGas } : {},
+ ...typeof maxFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerGas } : {},
+ ...typeof maxPriorityFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxPriorityFeePerGas } : {},
+ ..."nonceKey" in rest && typeof rest.nonceKey !== "undefined" ? { nonceKey: rest.nonceKey } : {},
+ ..."keyAuthorization" in rest && typeof rest.keyAuthorization !== "undefined" && rest.keyAuthorization !== null && !("keyAuthorization" in request) ? { keyAuthorization: rest.keyAuthorization } : {}
+ };
+ }).catch((e7) => {
+ const error = e7;
+ if (error.name !== "TransactionExecutionError")
+ return request;
+ const executionReverted = error.walk?.((e8) => {
+ const error2 = e8;
+ return error2.name === "ExecutionRevertedError";
+ });
+ if (executionReverted)
+ throw e7;
+ const unsupported = error.walk?.((e8) => {
+ const error2 = e8;
+ return error2.name === "MethodNotFoundRpcError" || error2.name === "MethodNotSupportedRpcError" || error2.message?.includes("eth_fillTransaction is not available");
+ });
+ if (unsupported)
+ supportsFillTransaction.set(client.uid, false);
+ return request;
+ }) : request;
+ nonce ??= fillResult.nonce;
+ request = {
+ ...fillResult,
+ ...account ? { from: account?.address } : {},
+ ...nonce ? { nonce } : {}
};
- const gen2 = () => {
- if (i++ >= 1e3)
- throw new Error("drbg: tried 1000 values");
- let len = 0;
- const out = [];
- while (len < qByteLen) {
- v = h();
- const sl = v.slice();
- out.push(sl);
- len += v.length;
+ const { blobs, gas, kzg, type } = request;
+ if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillParameters")) {
+ request = await prepareTransactionRequest2.fn({ ...request, chain: chain3 }, {
+ phase: "beforeFillParameters"
+ });
+ }
+ let block;
+ async function getBlock2() {
+ if (block)
+ return block;
+ block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" });
+ return block;
+ }
+ if (parameters.includes("nonce") && typeof nonce === "undefined" && account && !nonceManager)
+ request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
+ address: account.address,
+ blockTag: "pending"
+ });
+ if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) {
+ const commitments = blobsToCommitments({ blobs, kzg });
+ if (parameters.includes("blobVersionedHashes")) {
+ const versionedHashes = commitmentsToVersionedHashes({
+ commitments,
+ to: "hex"
+ });
+ request.blobVersionedHashes = versionedHashes;
}
- return concatBytes4(...out);
- };
- const genUntil = (seed, pred) => {
- reset();
- reseed(seed);
- let res = void 0;
- while (!(res = pred(gen2())))
- reseed();
- reset();
- return res;
- };
- return genUntil;
-}
-function validateObject2(object, validators, optValidators = {}) {
- const checkField = (fieldName, type, isOptional) => {
- const checkVal = validatorFns2[type];
- if (typeof checkVal !== "function")
- throw new Error("invalid validator function");
- const val = object[fieldName];
- if (isOptional && val === void 0)
- return;
- if (!checkVal(val, object)) {
- throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
+ if (parameters.includes("sidecars")) {
+ const proofs = blobsToProofs({ blobs, commitments, kzg });
+ const sidecars = toBlobSidecars({
+ blobs,
+ commitments,
+ proofs,
+ to: "hex"
+ });
+ request.sidecars = sidecars;
}
- };
- for (const [fieldName, type] of Object.entries(validators))
- checkField(fieldName, type, false);
- for (const [fieldName, type] of Object.entries(optValidators))
- checkField(fieldName, type, true);
- return object;
+ }
+ if (parameters.includes("chainId"))
+ request.chainId = await getChainId2();
+ if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") {
+ try {
+ request.type = getTransactionType(request);
+ } catch {
+ let isEip1559Network = eip1559NetworkCache.get(client.uid);
+ if (typeof isEip1559Network === "undefined") {
+ const block2 = await getBlock2();
+ isEip1559Network = typeof block2?.baseFeePerGas === "bigint";
+ eip1559NetworkCache.set(client.uid, isEip1559Network);
+ }
+ request.type = isEip1559Network ? "eip1559" : "legacy";
+ }
+ }
+ if (parameters.includes("fees")) {
+ if (request.type !== "legacy" && request.type !== "eip2930") {
+ if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") {
+ const block2 = await getBlock2();
+ const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, {
+ block: block2,
+ chain: chain3,
+ request
+ });
+ if (typeof request.maxPriorityFeePerGas === "undefined" && request.maxFeePerGas && request.maxFeePerGas < maxPriorityFeePerGas)
+ throw new MaxFeePerGasTooLowError({
+ maxPriorityFeePerGas
+ });
+ request.maxPriorityFeePerGas = maxPriorityFeePerGas;
+ request.maxFeePerGas = maxFeePerGas;
+ }
+ } else {
+ if (typeof request.maxFeePerGas !== "undefined" || typeof request.maxPriorityFeePerGas !== "undefined")
+ throw new Eip1559FeesNotSupportedError();
+ if (typeof request.gasPrice === "undefined") {
+ const block2 = await getBlock2();
+ const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, {
+ block: block2,
+ chain: chain3,
+ request,
+ type: "legacy"
+ });
+ request.gasPrice = gasPrice_;
+ }
+ }
+ }
+ if (parameters.includes("gas") && typeof gas === "undefined")
+ request.gas = await getAction(client, estimateGas, "estimateGas")({
+ ...request,
+ account,
+ prepare: account?.type === "local" ? [] : ["blobVersionedHashes"]
+ });
+ if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("afterFillParameters"))
+ request = await prepareTransactionRequest2.fn({ ...request, chain: chain3 }, {
+ phase: "afterFillParameters"
+ });
+ assertRequest(request);
+ delete request.parameters;
+ return request;
}
-function memoized2(fn) {
- const map = /* @__PURE__ */ new WeakMap();
- return (arg, ...args) => {
- const val = map.get(arg);
- if (val !== void 0)
- return val;
- const computed = fn(arg, ...args);
- map.set(arg, computed);
- return computed;
- };
+var defaultParameters, eip1559NetworkCache, supportsFillTransaction;
+var init_prepareTransactionRequest = __esm({
+ "node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js"() {
+ "use strict";
+ init_parseAccount();
+ init_estimateFeesPerGas();
+ init_estimateGas2();
+ init_getBlock();
+ init_getTransactionCount();
+ init_fee();
+ init_blobsToCommitments();
+ init_blobsToProofs();
+ init_commitmentsToVersionedHashes();
+ init_toBlobSidecars();
+ init_getAction();
+ init_lru();
+ init_assertRequest();
+ init_getTransactionType();
+ init_fillTransaction();
+ init_getChainId();
+ defaultParameters = [
+ "blobVersionedHashes",
+ "chainId",
+ "fees",
+ "gas",
+ "nonce",
+ "type"
+ ];
+ eip1559NetworkCache = /* @__PURE__ */ new Map();
+ supportsFillTransaction = /* @__PURE__ */ new LruMap(128);
+ }
+});
+
+// node_modules/viem/_esm/actions/public/estimateGas.js
+async function estimateGas(client, args) {
+ const { account: account_ = client.account, prepare = true } = args;
+ const account = account_ ? parseAccount(account_) : void 0;
+ const parameters = (() => {
+ if (Array.isArray(prepare))
+ return prepare;
+ if (account?.type !== "local")
+ return ["blobVersionedHashes"];
+ return void 0;
+ })();
+ try {
+ const to = await (async () => {
+ if (args.to)
+ return args.to;
+ if (args.authorizationList && args.authorizationList.length > 0)
+ return await recoverAuthorizationAddress({
+ authorization: args.authorizationList[0]
+ }).catch(() => {
+ throw new BaseError2("`to` is required. Could not infer from `authorizationList`");
+ });
+ return void 0;
+ })();
+ const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = prepare ? await prepareTransactionRequest(client, {
+ ...args,
+ parameters,
+ to
+ }) : args;
+ if (gas && args.gas !== gas)
+ return gas;
+ const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
+ const block = blockNumberHex || blockTag;
+ const rpcStateOverride = serializeStateOverride(stateOverride);
+ assertRequest(args);
+ const chainFormat = client.chain?.formatters?.transactionRequest?.format;
+ const format = chainFormat || formatTransactionRequest;
+ const request = format({
+ // Pick out extra data that might exist on the chain's transaction request type.
+ ...extract(rest, { format: chainFormat }),
+ account,
+ accessList,
+ authorizationList,
+ blobs,
+ blobVersionedHashes,
+ data,
+ gasPrice,
+ maxFeePerBlobGas,
+ maxFeePerGas,
+ maxPriorityFeePerGas,
+ nonce,
+ to,
+ value
+ }, "estimateGas");
+ return BigInt(await client.request({
+ method: "eth_estimateGas",
+ params: rpcStateOverride ? [
+ request,
+ block ?? client.experimental_blockTag ?? "latest",
+ rpcStateOverride
+ ] : block ? [request, block] : [request]
+ }));
+ } catch (err) {
+ throw getEstimateGasError(err, {
+ ...args,
+ account,
+ chain: client.chain
+ });
+ }
}
-var _0n7, _1n7, hasHexBuiltin2, hexes3, asciis2, isPosBig2, bitMask2, u8n2, u8fr2, validatorFns2;
-var init_utils5 = __esm({
- "node_modules/ox/node_modules/@noble/curves/esm/abstract/utils.js"() {
+var init_estimateGas2 = __esm({
+ "node_modules/viem/_esm/actions/public/estimateGas.js"() {
"use strict";
- _0n7 = /* @__PURE__ */ BigInt(0);
- _1n7 = /* @__PURE__ */ BigInt(1);
- hasHexBuiltin2 = // @ts-ignore
- typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
- hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
- asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
- isPosBig2 = (n) => typeof n === "bigint" && _0n7 <= n;
- bitMask2 = (n) => (_1n7 << BigInt(n)) - _1n7;
- u8n2 = (len) => new Uint8Array(len);
- u8fr2 = (arr) => Uint8Array.from(arr);
- validatorFns2 = {
- bigint: (val) => typeof val === "bigint",
- function: (val) => typeof val === "function",
- boolean: (val) => typeof val === "boolean",
- string: (val) => typeof val === "string",
- stringOrUint8Array: (val) => typeof val === "string" || isBytes3(val),
- isSafeInteger: (val) => Number.isSafeInteger(val),
- array: (val) => Array.isArray(val),
- field: (val, object) => object.Fp.isValid(val),
- hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
- };
+ init_parseAccount();
+ init_base();
+ init_recoverAuthorizationAddress();
+ init_toHex();
+ init_getEstimateGasError();
+ init_extract();
+ init_transactionRequest();
+ init_stateOverride2();
+ init_assertRequest();
+ init_prepareTransactionRequest();
}
});
-// node_modules/ox/_esm/core/version.js
-var version3;
-var init_version3 = __esm({
- "node_modules/ox/_esm/core/version.js"() {
+// node_modules/viem/_esm/actions/public/estimateContractGas.js
+async function estimateContractGas(client, parameters) {
+ const { abi: abi2, address: address2, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...request } = parameters;
+ const data = encodeFunctionData({
+ abi: abi2,
+ args,
+ functionName
+ });
+ try {
+ const gas = await getAction(client, estimateGas, "estimateGas")({
+ data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
+ to: address2,
+ ...request
+ });
+ return gas;
+ } catch (error) {
+ const account = request.account ? parseAccount(request.account) : void 0;
+ throw getContractError(error, {
+ abi: abi2,
+ address: address2,
+ args,
+ docsPath: "/docs/contract/estimateContractGas",
+ functionName,
+ sender: account?.address
+ });
+ }
+}
+var init_estimateContractGas = __esm({
+ "node_modules/viem/_esm/actions/public/estimateContractGas.js"() {
"use strict";
- version3 = "0.1.1";
+ init_parseAccount();
+ init_encodeFunctionData();
+ init_getContractError();
+ init_getAction();
+ init_estimateGas2();
}
});
-// node_modules/ox/_esm/core/internal/errors.js
-function getVersion() {
- return version3;
+// node_modules/viem/_esm/utils/address/isAddressEqual.js
+function isAddressEqual(a, b) {
+ if (!isAddress(a, { strict: false }))
+ throw new InvalidAddressError({ address: a });
+ if (!isAddress(b, { strict: false }))
+ throw new InvalidAddressError({ address: b });
+ return a.toLowerCase() === b.toLowerCase();
}
-var init_errors2 = __esm({
- "node_modules/ox/_esm/core/internal/errors.js"() {
+var init_isAddressEqual = __esm({
+ "node_modules/viem/_esm/utils/address/isAddressEqual.js"() {
"use strict";
- init_version3();
+ init_address();
+ init_isAddress();
}
});
-// node_modules/ox/_esm/core/Errors.js
-function walk2(err, fn) {
- if (fn?.(err))
- return err;
- if (err && typeof err === "object" && "cause" in err && err.cause)
- return walk2(err.cause, fn);
- return fn ? null : err;
+// node_modules/viem/_esm/utils/formatters/log.js
+function formatLog(log, { args, eventName } = {}) {
+ return {
+ ...log,
+ blockHash: log.blockHash ? log.blockHash : null,
+ blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
+ blockTimestamp: log.blockTimestamp ? BigInt(log.blockTimestamp) : log.blockTimestamp === null ? null : void 0,
+ logIndex: log.logIndex ? Number(log.logIndex) : null,
+ transactionHash: log.transactionHash ? log.transactionHash : null,
+ transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null,
+ ...eventName ? { args, eventName } : {}
+ };
}
-var BaseError3;
-var init_Errors = __esm({
- "node_modules/ox/_esm/core/Errors.js"() {
+var init_log2 = __esm({
+ "node_modules/viem/_esm/utils/formatters/log.js"() {
"use strict";
- init_errors2();
- BaseError3 = class _BaseError extends Error {
- static setStaticOptions(options) {
- _BaseError.prototype.docsOrigin = options.docsOrigin;
- _BaseError.prototype.showVersion = options.showVersion;
- _BaseError.prototype.version = options.version;
- }
- constructor(shortMessage, options = {}) {
- const details = (() => {
- if (options.cause instanceof _BaseError) {
- if (options.cause.details)
- return options.cause.details;
- if (options.cause.shortMessage)
- return options.cause.shortMessage;
- }
- if (options.cause && "details" in options.cause && typeof options.cause.details === "string")
- return options.cause.details;
- if (options.cause?.message)
- return options.cause.message;
- return options.details;
- })();
- const docsPath8 = (() => {
- if (options.cause instanceof _BaseError)
- return options.cause.docsPath || options.docsPath;
- return options.docsPath;
- })();
- const docsBaseUrl = options.docsOrigin ?? _BaseError.prototype.docsOrigin;
- const docs = `${docsBaseUrl}${docsPath8 ?? ""}`;
- const showVersion = Boolean(options.version ?? _BaseError.prototype.showVersion);
- const version4 = options.version ?? _BaseError.prototype.version;
- const message = [
- shortMessage || "An error occurred.",
- ...options.metaMessages ? ["", ...options.metaMessages] : [],
- ...details || docsPath8 || showVersion ? [
- "",
- details ? `Details: ${details}` : void 0,
- docsPath8 ? `See: ${docs}` : void 0,
- showVersion ? `Version: ${version4}` : void 0
- ] : []
- ].filter((x) => typeof x === "string").join("\n");
- super(message, options.cause ? { cause: options.cause } : void 0);
- Object.defineProperty(this, "details", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "docs", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "docsOrigin", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "docsPath", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "shortMessage", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "showVersion", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "version", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "cause", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: void 0
- });
- Object.defineProperty(this, "name", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: "BaseError"
- });
- this.cause = options.cause;
- this.details = details;
- this.docs = docs;
- this.docsOrigin = docsBaseUrl;
- this.docsPath = docsPath8;
- this.shortMessage = shortMessage;
- this.showVersion = showVersion;
- this.version = version4;
- }
- walk(fn) {
- return walk2(this, fn);
- }
- };
- Object.defineProperty(BaseError3, "defaultStaticOptions", {
- enumerable: true,
- configurable: true,
- writable: true,
- value: {
- docsOrigin: "https://oxlib.sh",
- showVersion: false,
- version: `ox@${getVersion()}`
- }
- });
- (() => {
- BaseError3.setStaticOptions(BaseError3.defaultStaticOptions);
- })();
}
});
-// node_modules/ox/_esm/core/internal/bytes.js
-function assertSize2(bytes, size_) {
- if (size2(bytes) > size_)
- throw new SizeOverflowError2({
- givenSize: size2(bytes),
- maxSize: size_
- });
-}
-function assertStartOffset2(value, start) {
- if (typeof start === "number" && start > 0 && start > size2(value) - 1)
- throw new SliceOffsetOutOfBoundsError2({
- offset: start,
- position: "start",
- size: size2(value)
- });
-}
-function assertEndOffset2(value, start, end) {
- if (typeof start === "number" && typeof end === "number" && size2(value) !== end - start) {
- throw new SliceOffsetOutOfBoundsError2({
- offset: end,
- position: "end",
- size: size2(value)
+// node_modules/viem/_esm/utils/abi/decodeEventLog.js
+function decodeEventLog(parameters) {
+ const { abi: abi2, data, strict: strict_, topics } = parameters;
+ const strict = strict_ ?? true;
+ const [signature2, ...argTopics] = topics;
+ if (!signature2)
+ throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath3 });
+ const abiItem = abi2.find((x) => x.type === "event" && signature2 === toEventSelector(formatAbiItem2(x)));
+ if (!(abiItem && "name" in abiItem) || abiItem.type !== "event")
+ throw new AbiEventSignatureNotFoundError(signature2, { docsPath: docsPath3 });
+ const { name, inputs } = abiItem;
+ const isUnnamed = inputs?.some((x) => !("name" in x && x.name));
+ const args = isUnnamed ? [] : {};
+ const indexedInputs = inputs.map((x, i) => [x, i]).filter(([x]) => "indexed" in x && x.indexed);
+ const missingIndexedInputs = [];
+ for (let i = 0; i < indexedInputs.length; i++) {
+ const [param, argIndex] = indexedInputs[i];
+ const topic = argTopics[i];
+ if (!topic) {
+ if (strict)
+ throw new DecodeLogTopicsMismatch({
+ abiItem,
+ param
+ });
+ missingIndexedInputs.push([param, argIndex]);
+ continue;
+ }
+ args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({
+ param,
+ value: topic
});
}
+ const nonIndexedInputs = inputs.filter((x) => !("indexed" in x && x.indexed));
+ const inputsToDecode = strict ? nonIndexedInputs : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs];
+ if (inputsToDecode.length > 0) {
+ if (data && data !== "0x") {
+ try {
+ const decodedData = decodeAbiParameters(inputsToDecode, data);
+ if (decodedData) {
+ let dataIndex = 0;
+ if (!strict) {
+ for (const [param, argIndex] of missingIndexedInputs) {
+ args[isUnnamed ? argIndex : param.name || argIndex] = decodedData[dataIndex++];
+ }
+ }
+ if (isUnnamed) {
+ for (let i = 0; i < inputs.length; i++)
+ if (args[i] === void 0 && dataIndex < decodedData.length)
+ args[i] = decodedData[dataIndex++];
+ } else
+ for (let i = 0; i < nonIndexedInputs.length; i++)
+ args[nonIndexedInputs[i].name] = decodedData[dataIndex++];
+ }
+ } catch (err) {
+ if (strict) {
+ if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError)
+ throw new DecodeLogDataMismatch({
+ abiItem,
+ data,
+ params: inputsToDecode,
+ size: size(data)
+ });
+ throw err;
+ }
+ }
+ } else if (strict) {
+ throw new DecodeLogDataMismatch({
+ abiItem,
+ data: "0x",
+ params: inputsToDecode,
+ size: 0
+ });
+ }
+ }
+ return {
+ eventName: name,
+ args: Object.values(args).length > 0 ? args : void 0
+ };
}
-function charCodeToBase162(char) {
- if (char >= charCodeMap2.zero && char <= charCodeMap2.nine)
- return char - charCodeMap2.zero;
- if (char >= charCodeMap2.A && char <= charCodeMap2.F)
- return char - (charCodeMap2.A - 10);
- if (char >= charCodeMap2.a && char <= charCodeMap2.f)
- return char - (charCodeMap2.a - 10);
- return void 0;
+function decodeTopic({ param, value }) {
+ if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
+ return value;
+ const decodedArg = decodeAbiParameters([param], value) || [];
+ return decodedArg[0];
}
-function pad2(bytes, options = {}) {
- const { dir, size: size5 = 32 } = options;
- if (size5 === 0)
- return bytes;
- if (bytes.length > size5)
- throw new SizeExceedsPaddingSizeError2({
- size: bytes.length,
- targetSize: size5,
- type: "Bytes"
- });
- const paddedBytes = new Uint8Array(size5);
- for (let i = 0; i < size5; i++) {
- const padEnd = dir === "right";
- paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
+var docsPath3;
+var init_decodeEventLog = __esm({
+ "node_modules/viem/_esm/utils/abi/decodeEventLog.js"() {
+ "use strict";
+ init_abi();
+ init_cursor();
+ init_size();
+ init_toEventSelector();
+ init_decodeAbiParameters();
+ init_formatAbiItem2();
+ docsPath3 = "/docs/contract/decodeEventLog";
}
- return paddedBytes;
+});
+
+// node_modules/viem/_esm/utils/abi/parseEventLogs.js
+function parseEventLogs(parameters) {
+ const { abi: abi2, args, logs, strict = true } = parameters;
+ const eventName = (() => {
+ if (!parameters.eventName)
+ return void 0;
+ if (Array.isArray(parameters.eventName))
+ return parameters.eventName;
+ return [parameters.eventName];
+ })();
+ const abiTopics = abi2.filter((abiItem) => abiItem.type === "event").map((abiItem) => ({
+ abi: abiItem,
+ selector: toEventSelector(abiItem)
+ }));
+ return logs.map((log) => {
+ const formattedLog = typeof log.blockNumber === "string" ? formatLog(log) : log;
+ const abiItems = abiTopics.filter((abiTopic) => formattedLog.topics[0] === abiTopic.selector);
+ if (abiItems.length === 0)
+ return null;
+ let event;
+ let abiItem;
+ for (const item of abiItems) {
+ try {
+ event = decodeEventLog({
+ ...formattedLog,
+ abi: [item.abi],
+ strict: true
+ });
+ abiItem = item;
+ break;
+ } catch {
+ }
+ }
+ if (!event && !strict) {
+ abiItem = abiItems[0];
+ try {
+ event = decodeEventLog({
+ data: formattedLog.data,
+ topics: formattedLog.topics,
+ abi: [abiItem.abi],
+ strict: false
+ });
+ } catch {
+ const isUnnamed = abiItem.abi.inputs?.some((x) => !("name" in x && x.name));
+ return {
+ ...formattedLog,
+ args: isUnnamed ? [] : {},
+ eventName: abiItem.abi.name
+ };
+ }
+ }
+ if (!event || !abiItem)
+ return null;
+ if (eventName && !eventName.includes(event.eventName))
+ return null;
+ if (!includesArgs({
+ args: event.args,
+ inputs: abiItem.abi.inputs,
+ matchArgs: args
+ }))
+ return null;
+ return { ...event, ...formattedLog };
+ }).filter(Boolean);
}
-function trim2(value, options = {}) {
- const { dir = "left" } = options;
- let data = value;
- let sliceLength = 0;
- for (let i = 0; i < data.length - 1; i++) {
- if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
- sliceLength++;
- else
- break;
+function includesArgs(parameters) {
+ const { args, inputs, matchArgs } = parameters;
+ if (!matchArgs)
+ return true;
+ if (!args)
+ return false;
+ function isEqual2(input, value, arg) {
+ try {
+ if (input.type === "address")
+ return isAddressEqual(value, arg);
+ if (input.type === "string" || input.type === "bytes")
+ return keccak256(toBytes(value)) === arg;
+ return value === arg;
+ } catch {
+ return false;
+ }
}
- data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
- return data;
+ if (Array.isArray(args) && Array.isArray(matchArgs)) {
+ return matchArgs.every((value, index2) => {
+ if (value === null || value === void 0)
+ return true;
+ const input = inputs[index2];
+ if (!input)
+ return false;
+ const value_ = Array.isArray(value) ? value : [value];
+ return value_.some((value2) => isEqual2(input, value2, args[index2]));
+ });
+ }
+ if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs))
+ return Object.entries(matchArgs).every(([key, value]) => {
+ if (value === null || value === void 0)
+ return true;
+ const input = inputs.find((input2) => input2.name === key);
+ if (!input)
+ return false;
+ const value_ = Array.isArray(value) ? value : [value];
+ return value_.some((value2) => isEqual2(input, value2, args[key]));
+ });
+ return false;
}
-var charCodeMap2;
-var init_bytes = __esm({
- "node_modules/ox/_esm/core/internal/bytes.js"() {
+var init_parseEventLogs = __esm({
+ "node_modules/viem/_esm/utils/abi/parseEventLogs.js"() {
"use strict";
- init_Bytes();
- charCodeMap2 = {
- zero: 48,
- nine: 57,
- A: 65,
- F: 70,
- a: 97,
- f: 102
- };
+ init_isAddressEqual();
+ init_toBytes();
+ init_log2();
+ init_keccak256();
+ init_toEventSelector();
+ init_decodeEventLog();
}
});
-// node_modules/ox/_esm/core/internal/hex.js
-function assertSize3(hex, size_) {
- if (size3(hex) > size_)
- throw new SizeOverflowError3({
- givenSize: size3(hex),
- maxSize: size_
- });
-}
-function assertStartOffset3(value, start) {
- if (typeof start === "number" && start > 0 && start > size3(value) - 1)
- throw new SliceOffsetOutOfBoundsError3({
- offset: start,
- position: "start",
- size: size3(value)
+// node_modules/viem/_esm/actions/public/getLogs.js
+async function getLogs(client, { address: address2, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) {
+ const strict = strict_ ?? false;
+ const events = events_ ?? (event ? [event] : void 0);
+ let topics = [];
+ if (events) {
+ const encoded = events.flatMap((event2) => encodeEventTopics({
+ abi: [event2],
+ eventName: event2.name,
+ args: events_ ? void 0 : args
+ }));
+ topics = [encoded];
+ if (event)
+ topics = topics[0];
+ }
+ let logs;
+ if (blockHash) {
+ logs = await client.request({
+ method: "eth_getLogs",
+ params: [{ address: address2, topics, blockHash }]
});
-}
-function assertEndOffset3(value, start, end) {
- if (typeof start === "number" && typeof end === "number" && size3(value) !== end - start) {
- throw new SliceOffsetOutOfBoundsError3({
- offset: end,
- position: "end",
- size: size3(value)
+ } else {
+ logs = await client.request({
+ method: "eth_getLogs",
+ params: [
+ {
+ address: address2,
+ topics,
+ fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
+ toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock
+ }
+ ]
});
}
+ const formattedLogs = logs.map((log) => formatLog(log));
+ if (!events)
+ return formattedLogs;
+ return parseEventLogs({
+ abi: events,
+ args,
+ logs: formattedLogs,
+ strict
+ });
}
-function pad3(hex_, options = {}) {
- const { dir, size: size5 = 32 } = options;
- if (size5 === 0)
- return hex_;
- const hex = hex_.replace("0x", "");
- if (hex.length > size5 * 2)
- throw new SizeExceedsPaddingSizeError3({
- size: Math.ceil(hex.length / 2),
- targetSize: size5,
- type: "Hex"
- });
- return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`;
-}
-function trim3(value, options = {}) {
- const { dir = "left" } = options;
- let data = value.replace("0x", "");
- let sliceLength = 0;
- for (let i = 0; i < data.length - 1; i++) {
- if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
- sliceLength++;
- else
- break;
+var init_getLogs = __esm({
+ "node_modules/viem/_esm/actions/public/getLogs.js"() {
+ "use strict";
+ init_encodeEventTopics();
+ init_parseEventLogs();
+ init_toHex();
+ init_log2();
}
- data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
- if (data === "0")
- return "0x";
- if (dir === "right" && data.length % 2 === 1)
- return `0x${data}0`;
- return `0x${data}`;
+});
+
+// node_modules/viem/_esm/actions/public/getContractEvents.js
+async function getContractEvents(client, parameters) {
+ const { abi: abi2, address: address2, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters;
+ const event = eventName ? getAbiItem({ abi: abi2, name: eventName }) : void 0;
+ const events = !event ? abi2.filter((x) => x.type === "event") : void 0;
+ return getAction(client, getLogs, "getLogs")({
+ address: address2,
+ args,
+ blockHash,
+ event,
+ events,
+ fromBlock,
+ toBlock,
+ strict
+ });
}
-var init_hex = __esm({
- "node_modules/ox/_esm/core/internal/hex.js"() {
+var init_getContractEvents = __esm({
+ "node_modules/viem/_esm/actions/public/getContractEvents.js"() {
"use strict";
- init_Hex();
+ init_getAbiItem();
+ init_getAction();
+ init_getLogs();
}
});
-// node_modules/ox/_esm/core/Json.js
-function stringify2(value, replacer, space) {
- return JSON.stringify(value, (key, value2) => {
- if (typeof replacer === "function")
- return replacer(key, value2);
- if (typeof value2 === "bigint")
- return value2.toString() + bigIntSuffix;
- return value2;
- }, space);
+// node_modules/viem/_esm/utils/abi/decodeFunctionResult.js
+function decodeFunctionResult(parameters) {
+ const { abi: abi2, args, functionName, data } = parameters;
+ let abiItem = abi2[0];
+ if (functionName) {
+ const item = getAbiItem({ abi: abi2, args, name: functionName });
+ if (!item)
+ throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 });
+ abiItem = item;
+ }
+ if (abiItem.type !== "function")
+ throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath4 });
+ if (!abiItem.outputs)
+ throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 });
+ const values = decodeAbiParameters(abiItem.outputs, data);
+ if (values && values.length > 1)
+ return values;
+ if (values && values.length === 1)
+ return values[0];
+ return void 0;
}
-var bigIntSuffix;
-var init_Json = __esm({
- "node_modules/ox/_esm/core/Json.js"() {
+var docsPath4;
+var init_decodeFunctionResult = __esm({
+ "node_modules/viem/_esm/utils/abi/decodeFunctionResult.js"() {
"use strict";
- bigIntSuffix = "#__bigint";
+ init_abi();
+ init_decodeAbiParameters();
+ init_getAbiItem();
+ docsPath4 = "/docs/contract/decodeFunctionResult";
}
});
-// node_modules/ox/_esm/core/Bytes.js
-function assert(value) {
- if (value instanceof Uint8Array)
- return;
- if (!value)
- throw new InvalidBytesTypeError(value);
- if (typeof value !== "object")
- throw new InvalidBytesTypeError(value);
- if (!("BYTES_PER_ELEMENT" in value))
- throw new InvalidBytesTypeError(value);
- if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== "Uint8Array")
- throw new InvalidBytesTypeError(value);
+// node_modules/ox/node_modules/@noble/curves/esm/abstract/utils.js
+function isBytes3(a) {
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
-function from(value) {
- if (value instanceof Uint8Array)
- return value;
- if (typeof value === "string")
- return fromHex(value);
- return fromArray(value);
+function abytes3(item) {
+ if (!isBytes3(item))
+ throw new Error("Uint8Array expected");
}
-function fromArray(value) {
- return value instanceof Uint8Array ? value : new Uint8Array(value);
+function abool2(title, value) {
+ if (typeof value !== "boolean")
+ throw new Error(title + " boolean expected, got " + value);
}
-function fromHex(value, options = {}) {
- const { size: size5 } = options;
- let hex = value;
- if (size5) {
- assertSize3(value, size5);
- hex = padRight(value, size5);
+function numberToHexUnpadded2(num2) {
+ const hex = num2.toString(16);
+ return hex.length & 1 ? "0" + hex : hex;
+}
+function hexToNumber3(hex) {
+ if (typeof hex !== "string")
+ throw new Error("hex string expected, got " + typeof hex);
+ return hex === "" ? _0n7 : BigInt("0x" + hex);
+}
+function bytesToHex3(bytes) {
+ abytes3(bytes);
+ if (hasHexBuiltin2)
+ return bytes.toHex();
+ let hex = "";
+ for (let i = 0; i < bytes.length; i++) {
+ hex += hexes3[bytes[i]];
}
- let hexString = hex.slice(2);
- if (hexString.length % 2)
- hexString = `0${hexString}`;
- const length = hexString.length / 2;
- const bytes = new Uint8Array(length);
- for (let index2 = 0, j = 0; index2 < length; index2++) {
- const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j++));
- const nibbleRight = charCodeToBase162(hexString.charCodeAt(j++));
- if (nibbleLeft === void 0 || nibbleRight === void 0) {
- throw new BaseError3(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
+ return hex;
+}
+function asciiToBase162(ch) {
+ if (ch >= asciis2._0 && ch <= asciis2._9)
+ return ch - asciis2._0;
+ if (ch >= asciis2.A && ch <= asciis2.F)
+ return ch - (asciis2.A - 10);
+ if (ch >= asciis2.a && ch <= asciis2.f)
+ return ch - (asciis2.a - 10);
+ return;
+}
+function hexToBytes3(hex) {
+ if (typeof hex !== "string")
+ throw new Error("hex string expected, got " + typeof hex);
+ if (hasHexBuiltin2)
+ return Uint8Array.fromHex(hex);
+ const hl = hex.length;
+ const al = hl / 2;
+ if (hl % 2)
+ throw new Error("hex string expected, got unpadded hex of length " + hl);
+ const array = new Uint8Array(al);
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
+ const n1 = asciiToBase162(hex.charCodeAt(hi));
+ const n2 = asciiToBase162(hex.charCodeAt(hi + 1));
+ if (n1 === void 0 || n2 === void 0) {
+ const char = hex[hi] + hex[hi + 1];
+ throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
}
- bytes[index2] = nibbleLeft << 4 | nibbleRight;
+ array[ai] = n1 * 16 + n2;
}
- return bytes;
+ return array;
}
-function fromString(value, options = {}) {
- const { size: size5 } = options;
- const bytes = encoder3.encode(value);
- if (typeof size5 === "number") {
- assertSize2(bytes, size5);
- return padRight2(bytes, size5);
- }
- return bytes;
+function bytesToNumberBE2(bytes) {
+ return hexToNumber3(bytesToHex3(bytes));
}
-function padRight2(value, size5) {
- return pad2(value, { dir: "right", size: size5 });
+function bytesToNumberLE2(bytes) {
+ abytes3(bytes);
+ return hexToNumber3(bytesToHex3(Uint8Array.from(bytes).reverse()));
}
-function size2(value) {
- return value.length;
+function numberToBytesBE2(n, len) {
+ return hexToBytes3(n.toString(16).padStart(len * 2, "0"));
}
-function slice2(value, start, end, options = {}) {
- const { strict } = options;
- assertStartOffset2(value, start);
- const value_ = value.slice(start, end);
- if (strict)
- assertEndOffset2(value_, start, end);
- return value_;
+function numberToBytesLE2(n, len) {
+ return numberToBytesBE2(n, len).reverse();
}
-function toBigInt2(bytes, options = {}) {
- const { size: size5 } = options;
- if (typeof size5 !== "undefined")
- assertSize2(bytes, size5);
- const hex = fromBytes(bytes, options);
- return toBigInt(hex, options);
+function ensureBytes2(title, hex, expectedLength) {
+ let res;
+ if (typeof hex === "string") {
+ try {
+ res = hexToBytes3(hex);
+ } catch (e7) {
+ throw new Error(title + " must be hex string or Uint8Array, cause: " + e7);
+ }
+ } else if (isBytes3(hex)) {
+ res = Uint8Array.from(hex);
+ } else {
+ throw new Error(title + " must be hex string or Uint8Array");
+ }
+ const len = res.length;
+ if (typeof expectedLength === "number" && len !== expectedLength)
+ throw new Error(title + " of length " + expectedLength + " expected, got " + len);
+ return res;
}
-function toBoolean(bytes, options = {}) {
- const { size: size5 } = options;
- let bytes_ = bytes;
- if (typeof size5 !== "undefined") {
- assertSize2(bytes_, size5);
- bytes_ = trimLeft(bytes_);
+function concatBytes4(...arrays) {
+ let sum = 0;
+ for (let i = 0; i < arrays.length; i++) {
+ const a = arrays[i];
+ abytes3(a);
+ sum += a.length;
}
- if (bytes_.length > 1 || bytes_[0] > 1)
- throw new InvalidBytesBooleanError2(bytes_);
- return Boolean(bytes_[0]);
+ const res = new Uint8Array(sum);
+ for (let i = 0, pad4 = 0; i < arrays.length; i++) {
+ const a = arrays[i];
+ res.set(a, pad4);
+ pad4 += a.length;
+ }
+ return res;
}
-function toNumber2(bytes, options = {}) {
- const { size: size5 } = options;
- if (typeof size5 !== "undefined")
- assertSize2(bytes, size5);
- const hex = fromBytes(bytes, options);
- return toNumber(hex, options);
+function inRange2(n, min, max) {
+ return isPosBig2(n) && isPosBig2(min) && isPosBig2(max) && min <= n && n < max;
}
-function toString(bytes, options = {}) {
- const { size: size5 } = options;
- let bytes_ = bytes;
- if (typeof size5 !== "undefined") {
- assertSize2(bytes_, size5);
- bytes_ = trimRight(bytes_);
- }
- return decoder.decode(bytes_);
+function aInRange2(title, n, min, max) {
+ if (!inRange2(n, min, max))
+ throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
-function trimLeft(value) {
- return trim2(value, { dir: "left" });
+function bitLen2(n) {
+ let len;
+ for (len = 0; n > _0n7; n >>= _1n7, len += 1)
+ ;
+ return len;
}
-function trimRight(value) {
- return trim2(value, { dir: "right" });
+function createHmacDrbg2(hashLen, qByteLen, hmacFn) {
+ if (typeof hashLen !== "number" || hashLen < 2)
+ throw new Error("hashLen must be a number");
+ if (typeof qByteLen !== "number" || qByteLen < 2)
+ throw new Error("qByteLen must be a number");
+ if (typeof hmacFn !== "function")
+ throw new Error("hmacFn must be a function");
+ let v = u8n2(hashLen);
+ let k = u8n2(hashLen);
+ let i = 0;
+ const reset = () => {
+ v.fill(1);
+ k.fill(0);
+ i = 0;
+ };
+ const h = (...b) => hmacFn(k, v, ...b);
+ const reseed = (seed = u8n2(0)) => {
+ k = h(u8fr2([0]), seed);
+ v = h();
+ if (seed.length === 0)
+ return;
+ k = h(u8fr2([1]), seed);
+ v = h();
+ };
+ const gen2 = () => {
+ if (i++ >= 1e3)
+ throw new Error("drbg: tried 1000 values");
+ let len = 0;
+ const out = [];
+ while (len < qByteLen) {
+ v = h();
+ const sl = v.slice();
+ out.push(sl);
+ len += v.length;
+ }
+ return concatBytes4(...out);
+ };
+ const genUntil = (seed, pred) => {
+ reset();
+ reseed(seed);
+ let res = void 0;
+ while (!(res = pred(gen2())))
+ reseed();
+ reset();
+ return res;
+ };
+ return genUntil;
}
-function validate(value) {
- try {
- assert(value);
- return true;
- } catch {
- return false;
+function validateObject2(object, validators, optValidators = {}) {
+ const checkField = (fieldName, type, isOptional) => {
+ const checkVal = validatorFns2[type];
+ if (typeof checkVal !== "function")
+ throw new Error("invalid validator function");
+ const val = object[fieldName];
+ if (isOptional && val === void 0)
+ return;
+ if (!checkVal(val, object)) {
+ throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
+ }
+ };
+ for (const [fieldName, type] of Object.entries(validators))
+ checkField(fieldName, type, false);
+ for (const [fieldName, type] of Object.entries(optValidators))
+ checkField(fieldName, type, true);
+ return object;
+}
+function memoized2(fn) {
+ const map = /* @__PURE__ */ new WeakMap();
+ return (arg, ...args) => {
+ const val = map.get(arg);
+ if (val !== void 0)
+ return val;
+ const computed = fn(arg, ...args);
+ map.set(arg, computed);
+ return computed;
+ };
+}
+var _0n7, _1n7, hasHexBuiltin2, hexes3, asciis2, isPosBig2, bitMask2, u8n2, u8fr2, validatorFns2;
+var init_utils5 = __esm({
+ "node_modules/ox/node_modules/@noble/curves/esm/abstract/utils.js"() {
+ "use strict";
+ _0n7 = /* @__PURE__ */ BigInt(0);
+ _1n7 = /* @__PURE__ */ BigInt(1);
+ hasHexBuiltin2 = // @ts-ignore
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
+ hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
+ asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
+ isPosBig2 = (n) => typeof n === "bigint" && _0n7 <= n;
+ bitMask2 = (n) => (_1n7 << BigInt(n)) - _1n7;
+ u8n2 = (len) => new Uint8Array(len);
+ u8fr2 = (arr) => Uint8Array.from(arr);
+ validatorFns2 = {
+ bigint: (val) => typeof val === "bigint",
+ function: (val) => typeof val === "function",
+ boolean: (val) => typeof val === "boolean",
+ string: (val) => typeof val === "string",
+ stringOrUint8Array: (val) => typeof val === "string" || isBytes3(val),
+ isSafeInteger: (val) => Number.isSafeInteger(val),
+ array: (val) => Array.isArray(val),
+ field: (val, object) => object.Fp.isValid(val),
+ hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
+ };
+ }
+});
+
+// node_modules/ox/_esm/core/version.js
+var version3;
+var init_version3 = __esm({
+ "node_modules/ox/_esm/core/version.js"() {
+ "use strict";
+ version3 = "0.1.1";
}
+});
+
+// node_modules/ox/_esm/core/internal/errors.js
+function getVersion() {
+ return version3;
}
-var decoder, encoder3, InvalidBytesBooleanError2, InvalidBytesTypeError, SizeOverflowError2, SliceOffsetOutOfBoundsError2, SizeExceedsPaddingSizeError2;
-var init_Bytes = __esm({
- "node_modules/ox/_esm/core/Bytes.js"() {
+var init_errors2 = __esm({
+ "node_modules/ox/_esm/core/internal/errors.js"() {
"use strict";
- init_Errors();
- init_Hex();
- init_bytes();
- init_hex();
- init_Json();
- decoder = /* @__PURE__ */ new TextDecoder();
- encoder3 = /* @__PURE__ */ new TextEncoder();
- InvalidBytesBooleanError2 = class extends BaseError3 {
- constructor(bytes) {
- super(`Bytes value \`${bytes}\` is not a valid boolean.`, {
- metaMessages: [
- "The bytes array must contain a single byte of either a `0` or `1` value."
- ]
+ init_version3();
+ }
+});
+
+// node_modules/ox/_esm/core/Errors.js
+function walk2(err, fn) {
+ if (fn?.(err))
+ return err;
+ if (err && typeof err === "object" && "cause" in err && err.cause)
+ return walk2(err.cause, fn);
+ return fn ? null : err;
+}
+var BaseError3;
+var init_Errors = __esm({
+ "node_modules/ox/_esm/core/Errors.js"() {
+ "use strict";
+ init_errors2();
+ BaseError3 = class _BaseError extends Error {
+ static setStaticOptions(options) {
+ _BaseError.prototype.docsOrigin = options.docsOrigin;
+ _BaseError.prototype.showVersion = options.showVersion;
+ _BaseError.prototype.version = options.version;
+ }
+ constructor(shortMessage, options = {}) {
+ const details = (() => {
+ if (options.cause instanceof _BaseError) {
+ if (options.cause.details)
+ return options.cause.details;
+ if (options.cause.shortMessage)
+ return options.cause.shortMessage;
+ }
+ if (options.cause && "details" in options.cause && typeof options.cause.details === "string")
+ return options.cause.details;
+ if (options.cause?.message)
+ return options.cause.message;
+ return options.details;
+ })();
+ const docsPath8 = (() => {
+ if (options.cause instanceof _BaseError)
+ return options.cause.docsPath || options.docsPath;
+ return options.docsPath;
+ })();
+ const docsBaseUrl = options.docsOrigin ?? _BaseError.prototype.docsOrigin;
+ const docs = `${docsBaseUrl}${docsPath8 ?? ""}`;
+ const showVersion = Boolean(options.version ?? _BaseError.prototype.showVersion);
+ const version4 = options.version ?? _BaseError.prototype.version;
+ const message = [
+ shortMessage || "An error occurred.",
+ ...options.metaMessages ? ["", ...options.metaMessages] : [],
+ ...details || docsPath8 || showVersion ? [
+ "",
+ details ? `Details: ${details}` : void 0,
+ docsPath8 ? `See: ${docs}` : void 0,
+ showVersion ? `Version: ${version4}` : void 0
+ ] : []
+ ].filter((x) => typeof x === "string").join("\n");
+ super(message, options.cause ? { cause: options.cause } : void 0);
+ Object.defineProperty(this, "details", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: void 0
});
- Object.defineProperty(this, "name", {
+ Object.defineProperty(this, "docs", {
enumerable: true,
configurable: true,
writable: true,
- value: "Bytes.InvalidBytesBooleanError"
+ value: void 0
});
- }
- };
- InvalidBytesTypeError = class extends BaseError3 {
- constructor(value) {
- super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid Bytes value.`, {
- metaMessages: ["Bytes values must be of type `Bytes`."]
+ Object.defineProperty(this, "docsOrigin", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: void 0
});
- Object.defineProperty(this, "name", {
+ Object.defineProperty(this, "docsPath", {
enumerable: true,
configurable: true,
writable: true,
- value: "Bytes.InvalidBytesTypeError"
+ value: void 0
});
- }
- };
- SizeOverflowError2 = class extends BaseError3 {
- constructor({ givenSize, maxSize }) {
- super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`);
- Object.defineProperty(this, "name", {
+ Object.defineProperty(this, "shortMessage", {
enumerable: true,
configurable: true,
writable: true,
- value: "Bytes.SizeOverflowError"
+ value: void 0
});
- }
- };
- SliceOffsetOutOfBoundsError2 = class extends BaseError3 {
- constructor({ offset, position, size: size5 }) {
- super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`);
- Object.defineProperty(this, "name", {
+ Object.defineProperty(this, "showVersion", {
enumerable: true,
configurable: true,
writable: true,
- value: "Bytes.SliceOffsetOutOfBoundsError"
+ value: void 0
+ });
+ Object.defineProperty(this, "version", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: void 0
+ });
+ Object.defineProperty(this, "cause", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: void 0
});
- }
- };
- SizeExceedsPaddingSizeError2 = class extends BaseError3 {
- constructor({ size: size5, targetSize, type }) {
- super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`);
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
- value: "Bytes.SizeExceedsPaddingSizeError"
+ value: "BaseError"
});
+ this.cause = options.cause;
+ this.details = details;
+ this.docs = docs;
+ this.docsOrigin = docsBaseUrl;
+ this.docsPath = docsPath8;
+ this.shortMessage = shortMessage;
+ this.showVersion = showVersion;
+ this.version = version4;
+ }
+ walk(fn) {
+ return walk2(this, fn);
}
};
+ Object.defineProperty(BaseError3, "defaultStaticOptions", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: {
+ docsOrigin: "https://oxlib.sh",
+ showVersion: false,
+ version: `ox@${getVersion()}`
+ }
+ });
+ (() => {
+ BaseError3.setStaticOptions(BaseError3.defaultStaticOptions);
+ })();
}
});
-// node_modules/ox/_esm/core/Hex.js
-function assert2(value, options = {}) {
- const { strict = false } = options;
- if (!value)
- throw new InvalidHexTypeError(value);
- if (typeof value !== "string")
- throw new InvalidHexTypeError(value);
- if (strict) {
- if (!/^0x[0-9a-fA-F]*$/.test(value))
- throw new InvalidHexValueError(value);
- }
- if (!value.startsWith("0x"))
- throw new InvalidHexValueError(value);
+// node_modules/ox/_esm/core/internal/bytes.js
+function assertSize2(bytes, size_) {
+ if (size2(bytes) > size_)
+ throw new SizeOverflowError2({
+ givenSize: size2(bytes),
+ maxSize: size_
+ });
}
-function concat2(...values) {
- return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
+function assertStartOffset2(value, start) {
+ if (typeof start === "number" && start > 0 && start > size2(value) - 1)
+ throw new SliceOffsetOutOfBoundsError2({
+ offset: start,
+ position: "start",
+ size: size2(value)
+ });
}
-function from2(value) {
- if (value instanceof Uint8Array)
- return fromBytes(value);
- if (Array.isArray(value))
- return fromBytes(new Uint8Array(value));
- return value;
+function assertEndOffset2(value, start, end) {
+ if (typeof start === "number" && typeof end === "number" && size2(value) !== end - start) {
+ throw new SliceOffsetOutOfBoundsError2({
+ offset: end,
+ position: "end",
+ size: size2(value)
+ });
+ }
}
-function fromBoolean(value, options = {}) {
- const hex = `0x${Number(value)}`;
+function charCodeToBase162(char) {
+ if (char >= charCodeMap2.zero && char <= charCodeMap2.nine)
+ return char - charCodeMap2.zero;
+ if (char >= charCodeMap2.A && char <= charCodeMap2.F)
+ return char - (charCodeMap2.A - 10);
+ if (char >= charCodeMap2.a && char <= charCodeMap2.f)
+ return char - (charCodeMap2.a - 10);
+ return void 0;
+}
+function pad2(bytes, options = {}) {
+ const { dir, size: size5 = 32 } = options;
+ if (size5 === 0)
+ return bytes;
+ if (bytes.length > size5)
+ throw new SizeExceedsPaddingSizeError2({
+ size: bytes.length,
+ targetSize: size5,
+ type: "Bytes"
+ });
+ const paddedBytes = new Uint8Array(size5);
+ for (let i = 0; i < size5; i++) {
+ const padEnd = dir === "right";
+ paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
+ }
+ return paddedBytes;
+}
+function trim2(value, options = {}) {
+ const { dir = "left" } = options;
+ let data = value;
+ let sliceLength = 0;
+ for (let i = 0; i < data.length - 1; i++) {
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
+ sliceLength++;
+ else
+ break;
+ }
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
+ return data;
+}
+var charCodeMap2;
+var init_bytes = __esm({
+ "node_modules/ox/_esm/core/internal/bytes.js"() {
+ "use strict";
+ init_Bytes();
+ charCodeMap2 = {
+ zero: 48,
+ nine: 57,
+ A: 65,
+ F: 70,
+ a: 97,
+ f: 102
+ };
+ }
+});
+
+// node_modules/ox/_esm/core/internal/hex.js
+function assertSize3(hex, size_) {
+ if (size3(hex) > size_)
+ throw new SizeOverflowError3({
+ givenSize: size3(hex),
+ maxSize: size_
+ });
+}
+function assertStartOffset3(value, start) {
+ if (typeof start === "number" && start > 0 && start > size3(value) - 1)
+ throw new SliceOffsetOutOfBoundsError3({
+ offset: start,
+ position: "start",
+ size: size3(value)
+ });
+}
+function assertEndOffset3(value, start, end) {
+ if (typeof start === "number" && typeof end === "number" && size3(value) !== end - start) {
+ throw new SliceOffsetOutOfBoundsError3({
+ offset: end,
+ position: "end",
+ size: size3(value)
+ });
+ }
+}
+function pad3(hex_, options = {}) {
+ const { dir, size: size5 = 32 } = options;
+ if (size5 === 0)
+ return hex_;
+ const hex = hex_.replace("0x", "");
+ if (hex.length > size5 * 2)
+ throw new SizeExceedsPaddingSizeError3({
+ size: Math.ceil(hex.length / 2),
+ targetSize: size5,
+ type: "Hex"
+ });
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`;
+}
+function trim3(value, options = {}) {
+ const { dir = "left" } = options;
+ let data = value.replace("0x", "");
+ let sliceLength = 0;
+ for (let i = 0; i < data.length - 1; i++) {
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
+ sliceLength++;
+ else
+ break;
+ }
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
+ if (data === "0")
+ return "0x";
+ if (dir === "right" && data.length % 2 === 1)
+ return `0x${data}0`;
+ return `0x${data}`;
+}
+var init_hex = __esm({
+ "node_modules/ox/_esm/core/internal/hex.js"() {
+ "use strict";
+ init_Hex();
+ }
+});
+
+// node_modules/ox/_esm/core/Json.js
+function stringify2(value, replacer, space) {
+ return JSON.stringify(value, (key, value2) => {
+ if (typeof replacer === "function")
+ return replacer(key, value2);
+ if (typeof value2 === "bigint")
+ return value2.toString() + bigIntSuffix;
+ return value2;
+ }, space);
+}
+var bigIntSuffix;
+var init_Json = __esm({
+ "node_modules/ox/_esm/core/Json.js"() {
+ "use strict";
+ bigIntSuffix = "#__bigint";
+ }
+});
+
+// node_modules/ox/_esm/core/Bytes.js
+function assert(value) {
+ if (value instanceof Uint8Array)
+ return;
+ if (!value)
+ throw new InvalidBytesTypeError(value);
+ if (typeof value !== "object")
+ throw new InvalidBytesTypeError(value);
+ if (!("BYTES_PER_ELEMENT" in value))
+ throw new InvalidBytesTypeError(value);
+ if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== "Uint8Array")
+ throw new InvalidBytesTypeError(value);
+}
+function from(value) {
+ if (value instanceof Uint8Array)
+ return value;
+ if (typeof value === "string")
+ return fromHex(value);
+ return fromArray(value);
+}
+function fromArray(value) {
+ return value instanceof Uint8Array ? value : new Uint8Array(value);
+}
+function fromHex(value, options = {}) {
+ const { size: size5 } = options;
+ let hex = value;
+ if (size5) {
+ assertSize3(value, size5);
+ hex = padRight(value, size5);
+ }
+ let hexString = hex.slice(2);
+ if (hexString.length % 2)
+ hexString = `0${hexString}`;
+ const length = hexString.length / 2;
+ const bytes = new Uint8Array(length);
+ for (let index2 = 0, j = 0; index2 < length; index2++) {
+ const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j++));
+ const nibbleRight = charCodeToBase162(hexString.charCodeAt(j++));
+ if (nibbleLeft === void 0 || nibbleRight === void 0) {
+ throw new BaseError3(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
+ }
+ bytes[index2] = nibbleLeft << 4 | nibbleRight;
+ }
+ return bytes;
+}
+function fromString(value, options = {}) {
+ const { size: size5 } = options;
+ const bytes = encoder3.encode(value);
+ if (typeof size5 === "number") {
+ assertSize2(bytes, size5);
+ return padRight2(bytes, size5);
+ }
+ return bytes;
+}
+function padRight2(value, size5) {
+ return pad2(value, { dir: "right", size: size5 });
+}
+function size2(value) {
+ return value.length;
+}
+function slice2(value, start, end, options = {}) {
+ const { strict } = options;
+ assertStartOffset2(value, start);
+ const value_ = value.slice(start, end);
+ if (strict)
+ assertEndOffset2(value_, start, end);
+ return value_;
+}
+function toBigInt2(bytes, options = {}) {
+ const { size: size5 } = options;
+ if (typeof size5 !== "undefined")
+ assertSize2(bytes, size5);
+ const hex = fromBytes(bytes, options);
+ return toBigInt(hex, options);
+}
+function toBoolean(bytes, options = {}) {
+ const { size: size5 } = options;
+ let bytes_ = bytes;
+ if (typeof size5 !== "undefined") {
+ assertSize2(bytes_, size5);
+ bytes_ = trimLeft(bytes_);
+ }
+ if (bytes_.length > 1 || bytes_[0] > 1)
+ throw new InvalidBytesBooleanError2(bytes_);
+ return Boolean(bytes_[0]);
+}
+function toNumber2(bytes, options = {}) {
+ const { size: size5 } = options;
+ if (typeof size5 !== "undefined")
+ assertSize2(bytes, size5);
+ const hex = fromBytes(bytes, options);
+ return toNumber(hex, options);
+}
+function toString(bytes, options = {}) {
+ const { size: size5 } = options;
+ let bytes_ = bytes;
+ if (typeof size5 !== "undefined") {
+ assertSize2(bytes_, size5);
+ bytes_ = trimRight(bytes_);
+ }
+ return decoder.decode(bytes_);
+}
+function trimLeft(value) {
+ return trim2(value, { dir: "left" });
+}
+function trimRight(value) {
+ return trim2(value, { dir: "right" });
+}
+function validate(value) {
+ try {
+ assert(value);
+ return true;
+ } catch {
+ return false;
+ }
+}
+var decoder, encoder3, InvalidBytesBooleanError2, InvalidBytesTypeError, SizeOverflowError2, SliceOffsetOutOfBoundsError2, SizeExceedsPaddingSizeError2;
+var init_Bytes = __esm({
+ "node_modules/ox/_esm/core/Bytes.js"() {
+ "use strict";
+ init_Errors();
+ init_Hex();
+ init_bytes();
+ init_hex();
+ init_Json();
+ decoder = /* @__PURE__ */ new TextDecoder();
+ encoder3 = /* @__PURE__ */ new TextEncoder();
+ InvalidBytesBooleanError2 = class extends BaseError3 {
+ constructor(bytes) {
+ super(`Bytes value \`${bytes}\` is not a valid boolean.`, {
+ metaMessages: [
+ "The bytes array must contain a single byte of either a `0` or `1` value."
+ ]
+ });
+ Object.defineProperty(this, "name", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: "Bytes.InvalidBytesBooleanError"
+ });
+ }
+ };
+ InvalidBytesTypeError = class extends BaseError3 {
+ constructor(value) {
+ super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid Bytes value.`, {
+ metaMessages: ["Bytes values must be of type `Bytes`."]
+ });
+ Object.defineProperty(this, "name", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: "Bytes.InvalidBytesTypeError"
+ });
+ }
+ };
+ SizeOverflowError2 = class extends BaseError3 {
+ constructor({ givenSize, maxSize }) {
+ super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`);
+ Object.defineProperty(this, "name", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: "Bytes.SizeOverflowError"
+ });
+ }
+ };
+ SliceOffsetOutOfBoundsError2 = class extends BaseError3 {
+ constructor({ offset, position, size: size5 }) {
+ super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`);
+ Object.defineProperty(this, "name", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: "Bytes.SliceOffsetOutOfBoundsError"
+ });
+ }
+ };
+ SizeExceedsPaddingSizeError2 = class extends BaseError3 {
+ constructor({ size: size5, targetSize, type }) {
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`);
+ Object.defineProperty(this, "name", {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value: "Bytes.SizeExceedsPaddingSizeError"
+ });
+ }
+ };
+ }
+});
+
+// node_modules/ox/_esm/core/Hex.js
+function assert2(value, options = {}) {
+ const { strict = false } = options;
+ if (!value)
+ throw new InvalidHexTypeError(value);
+ if (typeof value !== "string")
+ throw new InvalidHexTypeError(value);
+ if (strict) {
+ if (!/^0x[0-9a-fA-F]*$/.test(value))
+ throw new InvalidHexValueError(value);
+ }
+ if (!value.startsWith("0x"))
+ throw new InvalidHexValueError(value);
+}
+function concat2(...values) {
+ return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
+}
+function from2(value) {
+ if (value instanceof Uint8Array)
+ return fromBytes(value);
+ if (Array.isArray(value))
+ return fromBytes(new Uint8Array(value));
+ return value;
+}
+function fromBoolean(value, options = {}) {
+ const hex = `0x${Number(value)}`;
if (typeof options.size === "number") {
assertSize3(hex, options.size);
return padLeft(hex, options.size);
@@ -10570,56119 +12026,55771 @@ var init_call = __esm({
}
});
-// node_modules/viem/_esm/utils/transaction/assertTransaction.js
-function assertTransactionEIP7702(transaction) {
- const { authorizationList } = transaction;
- if (authorizationList) {
- for (const authorization of authorizationList) {
- const { chainId } = authorization;
- const address2 = authorization.address;
- if (!isAddress(address2))
- throw new InvalidAddressError({ address: address2 });
- if (chainId < 0)
- throw new InvalidChainIdError({ chainId });
- }
- }
- assertTransactionEIP1559(transaction);
-}
-function assertTransactionEIP4844(transaction) {
- const { blobVersionedHashes } = transaction;
- if (blobVersionedHashes) {
- if (blobVersionedHashes.length === 0)
- throw new EmptyBlobError();
- for (const hash3 of blobVersionedHashes) {
- const size_ = size(hash3);
- const version4 = hexToNumber(slice(hash3, 0, 1));
- if (size_ !== 32)
- throw new InvalidVersionedHashSizeError({ hash: hash3, size: size_ });
- if (version4 !== versionedHashVersionKzg)
- throw new InvalidVersionedHashVersionError({
- hash: hash3,
- version: version4
- });
- }
+// node_modules/viem/_esm/actions/public/readContract.js
+async function readContract(client, parameters) {
+ const { abi: abi2, address: address2, args, functionName, ...rest } = parameters;
+ const calldata = encodeFunctionData({
+ abi: abi2,
+ args,
+ functionName
+ });
+ try {
+ const { data } = await getAction(client, call, "call")({
+ ...rest,
+ data: calldata,
+ to: address2
+ });
+ return decodeFunctionResult({
+ abi: abi2,
+ args,
+ functionName,
+ data: data || "0x"
+ });
+ } catch (error) {
+ throw getContractError(error, {
+ abi: abi2,
+ address: address2,
+ args,
+ docsPath: "/docs/contract/readContract",
+ functionName
+ });
}
- assertTransactionEIP1559(transaction);
-}
-function assertTransactionEIP1559(transaction) {
- const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;
- if (chainId <= 0)
- throw new InvalidChainIdError({ chainId });
- if (to && !isAddress(to))
- throw new InvalidAddressError({ address: to });
- if (maxFeePerGas && maxFeePerGas > maxUint256)
- throw new FeeCapTooHighError({ maxFeePerGas });
- if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
- throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
-}
-function assertTransactionEIP2930(transaction) {
- const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
- if (chainId <= 0)
- throw new InvalidChainIdError({ chainId });
- if (to && !isAddress(to))
- throw new InvalidAddressError({ address: to });
- if (maxPriorityFeePerGas || maxFeePerGas)
- throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");
- if (gasPrice && gasPrice > maxUint256)
- throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
-}
-function assertTransactionLegacy(transaction) {
- const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
- if (to && !isAddress(to))
- throw new InvalidAddressError({ address: to });
- if (typeof chainId !== "undefined" && chainId <= 0)
- throw new InvalidChainIdError({ chainId });
- if (maxPriorityFeePerGas || maxFeePerGas)
- throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");
- if (gasPrice && gasPrice > maxUint256)
- throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
}
-var init_assertTransaction = __esm({
- "node_modules/viem/_esm/utils/transaction/assertTransaction.js"() {
+var init_readContract = __esm({
+ "node_modules/viem/_esm/actions/public/readContract.js"() {
"use strict";
- init_kzg();
- init_number();
- init_address();
- init_base();
- init_blob2();
- init_chain();
- init_node();
- init_isAddress();
- init_size();
- init_slice();
- init_fromHex();
+ init_decodeFunctionResult();
+ init_encodeFunctionData();
+ init_getContractError();
+ init_getAction();
+ init_call();
}
});
-// node_modules/viem/_esm/utils/transaction/serializeAccessList.js
-function serializeAccessList(accessList) {
- if (!accessList || accessList.length === 0)
- return [];
- const serializedAccessList = [];
- for (let i = 0; i < accessList.length; i++) {
- const { address: address2, storageKeys } = accessList[i];
- for (let j = 0; j < storageKeys.length; j++) {
- if (storageKeys[j].length - 2 !== 64) {
- throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });
+// node_modules/viem/_esm/actions/public/simulateContract.js
+async function simulateContract(client, parameters) {
+ const { abi: abi2, address: address2, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...callRequest } = parameters;
+ const account = callRequest.account ? parseAccount(callRequest.account) : client.account;
+ const calldata = encodeFunctionData({ abi: abi2, args, functionName });
+ try {
+ const { data } = await getAction(client, call, "call")({
+ batch: false,
+ data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
+ to: address2,
+ ...callRequest,
+ account
+ });
+ const result = decodeFunctionResult({
+ abi: abi2,
+ args,
+ functionName,
+ data: data || "0x"
+ });
+ const minimizedAbi = abi2.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName);
+ return {
+ result,
+ request: {
+ abi: minimizedAbi,
+ address: address2,
+ args,
+ dataSuffix,
+ functionName,
+ ...callRequest,
+ account
}
- }
- if (!isAddress(address2, { strict: false })) {
- throw new InvalidAddressError({ address: address2 });
- }
- serializedAccessList.push([address2, storageKeys]);
+ };
+ } catch (error) {
+ throw getContractError(error, {
+ abi: abi2,
+ address: address2,
+ args,
+ docsPath: "/docs/contract/simulateContract",
+ functionName,
+ sender: account?.address
+ });
}
- return serializedAccessList;
}
-var init_serializeAccessList = __esm({
- "node_modules/viem/_esm/utils/transaction/serializeAccessList.js"() {
+var init_simulateContract = __esm({
+ "node_modules/viem/_esm/actions/public/simulateContract.js"() {
"use strict";
- init_address();
- init_transaction();
- init_isAddress();
+ init_parseAccount();
+ init_decodeFunctionResult();
+ init_encodeFunctionData();
+ init_getContractError();
+ init_getAction();
+ init_call();
}
});
-// node_modules/viem/_esm/utils/transaction/serializeTransaction.js
-function serializeTransaction(transaction, signature2) {
- const type = getTransactionType(transaction);
- if (type === "eip1559")
- return serializeTransactionEIP1559(transaction, signature2);
- if (type === "eip2930")
- return serializeTransactionEIP2930(transaction, signature2);
- if (type === "eip4844")
- return serializeTransactionEIP4844(transaction, signature2);
- if (type === "eip7702")
- return serializeTransactionEIP7702(transaction, signature2);
- return serializeTransactionLegacy(transaction, signature2);
-}
-function serializeTransactionEIP7702(transaction, signature2) {
- const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
- assertTransactionEIP7702(transaction);
- const serializedAccessList = serializeAccessList(accessList);
- const serializedAuthorizationList = serializeAuthorizationList(authorizationList);
- return concatHex([
- "0x04",
- toRlp([
- numberToHex(chainId),
- nonce ? numberToHex(nonce) : "0x",
- maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
- maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
- gas ? numberToHex(gas) : "0x",
- to ?? "0x",
- value ? numberToHex(value) : "0x",
- data ?? "0x",
- serializedAccessList,
- serializedAuthorizationList,
- ...toYParitySignatureArray(transaction, signature2)
- ])
+// node_modules/viem/_esm/utils/observe.js
+function observe(observerId, callbacks, fn) {
+ const callbackId = ++callbackCount;
+ const getListeners = () => listenersCache.get(observerId) || [];
+ const unsubscribe = () => {
+ const listeners2 = getListeners();
+ listenersCache.set(observerId, listeners2.filter((cb) => cb.id !== callbackId));
+ };
+ const unwatch = () => {
+ const listeners2 = getListeners();
+ if (!listeners2.some((cb) => cb.id === callbackId))
+ return;
+ const cleanup2 = cleanupCache.get(observerId);
+ if (listeners2.length === 1 && cleanup2) {
+ const p = cleanup2();
+ if (p instanceof Promise)
+ p.catch(() => {
+ });
+ }
+ unsubscribe();
+ };
+ const listeners = getListeners();
+ listenersCache.set(observerId, [
+ ...listeners,
+ { id: callbackId, fns: callbacks }
]);
-}
-function serializeTransactionEIP4844(transaction, signature2) {
- const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
- assertTransactionEIP4844(transaction);
- let blobVersionedHashes = transaction.blobVersionedHashes;
- let sidecars = transaction.sidecars;
- if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) {
- const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x));
- const kzg = transaction.kzg;
- const commitments2 = blobsToCommitments({
- blobs: blobs2,
- kzg
+ if (listeners && listeners.length > 0)
+ return unwatch;
+ const emit = {};
+ for (const key in callbacks) {
+ emit[key] = ((...args) => {
+ const listeners2 = getListeners();
+ if (listeners2.length === 0)
+ return;
+ for (const listener of listeners2)
+ listener.fns[key]?.(...args);
});
- if (typeof blobVersionedHashes === "undefined")
- blobVersionedHashes = commitmentsToVersionedHashes({
- commitments: commitments2
- });
- if (typeof sidecars === "undefined") {
- const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg });
- sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 });
- }
}
- const serializedAccessList = serializeAccessList(accessList);
- const serializedTransaction = [
- numberToHex(chainId),
- nonce ? numberToHex(nonce) : "0x",
- maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
- maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
- gas ? numberToHex(gas) : "0x",
- to ?? "0x",
- value ? numberToHex(value) : "0x",
- data ?? "0x",
- serializedAccessList,
- maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : "0x",
- blobVersionedHashes ?? [],
- ...toYParitySignatureArray(transaction, signature2)
- ];
- const blobs = [];
- const commitments = [];
- const proofs = [];
- if (sidecars)
- for (let i = 0; i < sidecars.length; i++) {
- const { blob, commitment, proof } = sidecars[i];
- blobs.push(blob);
- commitments.push(commitment);
- proofs.push(proof);
- }
- return concatHex([
- "0x03",
- sidecars ? (
- // If sidecars are enabled, envelope turns into a "wrapper":
- toRlp([serializedTransaction, blobs, commitments, proofs])
- ) : (
- // If sidecars are disabled, standard envelope is used:
- toRlp(serializedTransaction)
- )
- ]);
-}
-function serializeTransactionEIP1559(transaction, signature2) {
- const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
- assertTransactionEIP1559(transaction);
- const serializedAccessList = serializeAccessList(accessList);
- const serializedTransaction = [
- numberToHex(chainId),
- nonce ? numberToHex(nonce) : "0x",
- maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
- maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
- gas ? numberToHex(gas) : "0x",
- to ?? "0x",
- value ? numberToHex(value) : "0x",
- data ?? "0x",
- serializedAccessList,
- ...toYParitySignatureArray(transaction, signature2)
- ];
- return concatHex([
- "0x02",
- toRlp(serializedTransaction)
- ]);
-}
-function serializeTransactionEIP2930(transaction, signature2) {
- const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;
- assertTransactionEIP2930(transaction);
- const serializedAccessList = serializeAccessList(accessList);
- const serializedTransaction = [
- numberToHex(chainId),
- nonce ? numberToHex(nonce) : "0x",
- gasPrice ? numberToHex(gasPrice) : "0x",
- gas ? numberToHex(gas) : "0x",
- to ?? "0x",
- value ? numberToHex(value) : "0x",
- data ?? "0x",
- serializedAccessList,
- ...toYParitySignatureArray(transaction, signature2)
- ];
- return concatHex([
- "0x01",
- toRlp(serializedTransaction)
- ]);
+ const cleanup = fn(emit);
+ if (typeof cleanup === "function")
+ cleanupCache.set(observerId, cleanup);
+ return unwatch;
}
-function serializeTransactionLegacy(transaction, signature2) {
- const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;
- assertTransactionLegacy(transaction);
- let serializedTransaction = [
- nonce ? numberToHex(nonce) : "0x",
- gasPrice ? numberToHex(gasPrice) : "0x",
- gas ? numberToHex(gas) : "0x",
- to ?? "0x",
- value ? numberToHex(value) : "0x",
- data ?? "0x"
- ];
- if (signature2) {
- const v = (() => {
- if (signature2.v >= 35n) {
- const inferredChainId = (signature2.v - 35n) / 2n;
- if (inferredChainId > 0)
- return signature2.v;
- return 27n + (signature2.v === 35n ? 0n : 1n);
- }
- if (chainId > 0)
- return BigInt(chainId * 2) + BigInt(35n + signature2.v - 27n);
- const v2 = 27n + (signature2.v === 27n ? 0n : 1n);
- if (signature2.v !== v2)
- throw new InvalidLegacyVError({ v: signature2.v });
- return v2;
- })();
- const r = trim(signature2.r);
- const s3 = trim(signature2.s);
- serializedTransaction = [
- ...serializedTransaction,
- numberToHex(v),
- r === "0x00" ? "0x" : r,
- s3 === "0x00" ? "0x" : s3
- ];
- } else if (chainId > 0) {
- serializedTransaction = [
- ...serializedTransaction,
- numberToHex(chainId),
- "0x",
- "0x"
- ];
+var listenersCache, cleanupCache, callbackCount;
+var init_observe = __esm({
+ "node_modules/viem/_esm/utils/observe.js"() {
+ "use strict";
+ listenersCache = /* @__PURE__ */ new Map();
+ cleanupCache = /* @__PURE__ */ new Map();
+ callbackCount = 0;
}
- return toRlp(serializedTransaction);
-}
-function toYParitySignatureArray(transaction, signature_) {
- const signature2 = signature_ ?? transaction;
- const { v, yParity } = signature2;
- if (typeof signature2.r === "undefined")
- return [];
- if (typeof signature2.s === "undefined")
- return [];
- if (typeof v === "undefined" && typeof yParity === "undefined")
- return [];
- const r = trim(signature2.r);
- const s3 = trim(signature2.s);
- const yParity_ = (() => {
- if (typeof yParity === "number")
- return yParity ? numberToHex(1) : "0x";
- if (v === 0n)
- return "0x";
- if (v === 1n)
- return numberToHex(1);
- return v === 27n ? "0x" : numberToHex(1);
- })();
- return [yParity_, r === "0x00" ? "0x" : r, s3 === "0x00" ? "0x" : s3];
+});
+
+// node_modules/viem/_esm/utils/wait.js
+async function wait(time) {
+ return new Promise((res) => setTimeout(res, time));
}
-var init_serializeTransaction = __esm({
- "node_modules/viem/_esm/utils/transaction/serializeTransaction.js"() {
+var init_wait = __esm({
+ "node_modules/viem/_esm/utils/wait.js"() {
"use strict";
- init_transaction();
- init_serializeAuthorizationList();
- init_blobsToCommitments();
- init_blobsToProofs();
- init_commitmentsToVersionedHashes();
- init_toBlobSidecars();
- init_concat();
- init_trim();
- init_toHex();
- init_toRlp();
- init_assertTransaction();
- init_getTransactionType();
- init_serializeAccessList();
}
});
-// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js
-function serializeAuthorizationList(authorizationList) {
- if (!authorizationList || authorizationList.length === 0)
- return [];
- const serializedAuthorizationList = [];
- for (const authorization of authorizationList) {
- const { chainId, nonce, ...signature2 } = authorization;
- const contractAddress = authorization.address;
- serializedAuthorizationList.push([
- chainId ? toHex(chainId) : "0x",
- contractAddress,
- nonce ? toHex(nonce) : "0x",
- ...toYParitySignatureArray({}, signature2)
- ]);
- }
- return serializedAuthorizationList;
+// node_modules/viem/_esm/utils/poll.js
+function poll(fn, { emitOnBegin, initialWaitTime, interval }) {
+ let active = true;
+ const unwatch = () => active = false;
+ const watch = async () => {
+ let data;
+ if (emitOnBegin)
+ data = await fn({ unpoll: unwatch });
+ const initialWait = await initialWaitTime?.(data) ?? interval;
+ await wait(initialWait);
+ const poll2 = async () => {
+ if (!active)
+ return;
+ await fn({ unpoll: unwatch });
+ await wait(interval);
+ poll2();
+ };
+ poll2();
+ };
+ watch();
+ return unwatch;
}
-var init_serializeAuthorizationList = __esm({
- "node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js"() {
+var init_poll = __esm({
+ "node_modules/viem/_esm/utils/poll.js"() {
"use strict";
- init_toHex();
- init_serializeTransaction();
+ init_wait();
}
});
-// node_modules/viem/_esm/constants/strings.js
-var presignMessagePrefix;
-var init_strings = __esm({
- "node_modules/viem/_esm/constants/strings.js"() {
+// node_modules/viem/_esm/utils/promise/withCache.js
+function getCache(cacheKey2) {
+ const buildCache = (cacheKey3, cache2) => ({
+ clear: () => cache2.delete(cacheKey3),
+ get: () => cache2.get(cacheKey3),
+ set: (data) => cache2.set(cacheKey3, data)
+ });
+ const promise = buildCache(cacheKey2, promiseCache);
+ const response = buildCache(cacheKey2, responseCache);
+ return {
+ clear: () => {
+ promise.clear();
+ response.clear();
+ },
+ promise,
+ response
+ };
+}
+async function withCache(fn, { cacheKey: cacheKey2, cacheTime = Number.POSITIVE_INFINITY }) {
+ const cache2 = getCache(cacheKey2);
+ const response = cache2.response.get();
+ if (response && cacheTime > 0) {
+ const age = Date.now() - response.created.getTime();
+ if (age < cacheTime)
+ return response.data;
+ }
+ let promise = cache2.promise.get();
+ if (!promise) {
+ promise = fn();
+ cache2.promise.set(promise);
+ }
+ try {
+ const data = await promise;
+ cache2.response.set({ created: /* @__PURE__ */ new Date(), data });
+ return data;
+ } finally {
+ cache2.promise.clear();
+ }
+}
+var promiseCache, responseCache;
+var init_withCache = __esm({
+ "node_modules/viem/_esm/utils/promise/withCache.js"() {
"use strict";
- presignMessagePrefix = "Ethereum Signed Message:\n";
+ promiseCache = /* @__PURE__ */ new Map();
+ responseCache = /* @__PURE__ */ new Map();
}
});
-// node_modules/viem/_esm/utils/signature/toPrefixedMessage.js
-function toPrefixedMessage(message_) {
- const message = (() => {
- if (typeof message_ === "string")
- return stringToHex(message_);
- if (typeof message_.raw === "string")
- return message_.raw;
- return bytesToHex(message_.raw);
- })();
- const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`);
- return concat([prefix, message]);
+// node_modules/viem/_esm/actions/public/getBlockNumber.js
+async function getBlockNumber(client, { cacheTime = client.cacheTime } = {}) {
+ const blockNumberHex = await withCache(() => client.request({
+ method: "eth_blockNumber"
+ }), { cacheKey: cacheKey(client.uid), cacheTime });
+ return BigInt(blockNumberHex);
}
-var init_toPrefixedMessage = __esm({
- "node_modules/viem/_esm/utils/signature/toPrefixedMessage.js"() {
+var cacheKey;
+var init_getBlockNumber = __esm({
+ "node_modules/viem/_esm/actions/public/getBlockNumber.js"() {
"use strict";
- init_strings();
- init_concat();
- init_size();
- init_toHex();
+ init_withCache();
+ cacheKey = (id) => `blockNumber.${id}`;
}
});
-// node_modules/viem/_esm/utils/signature/hashMessage.js
-function hashMessage(message, to_) {
- return keccak256(toPrefixedMessage(message), to_);
+// node_modules/viem/_esm/actions/public/getFilterChanges.js
+async function getFilterChanges(_client, { filter }) {
+ const strict = "strict" in filter && filter.strict;
+ const logs = await filter.request({
+ method: "eth_getFilterChanges",
+ params: [filter.id]
+ });
+ if (typeof logs[0] === "string")
+ return logs;
+ const formattedLogs = logs.map((log) => formatLog(log));
+ if (!("abi" in filter) || !filter.abi)
+ return formattedLogs;
+ return parseEventLogs({
+ abi: filter.abi,
+ logs: formattedLogs,
+ strict
+ });
}
-var init_hashMessage = __esm({
- "node_modules/viem/_esm/utils/signature/hashMessage.js"() {
+var init_getFilterChanges = __esm({
+ "node_modules/viem/_esm/actions/public/getFilterChanges.js"() {
"use strict";
- init_keccak256();
- init_toPrefixedMessage();
+ init_parseEventLogs();
+ init_log2();
}
});
-// node_modules/viem/_esm/errors/typedData.js
-var InvalidDomainError, InvalidPrimaryTypeError, InvalidStructTypeError;
-var init_typedData = __esm({
- "node_modules/viem/_esm/errors/typedData.js"() {
+// node_modules/viem/_esm/actions/public/uninstallFilter.js
+async function uninstallFilter(_client, { filter }) {
+ return filter.request({
+ method: "eth_uninstallFilter",
+ params: [filter.id]
+ });
+}
+var init_uninstallFilter = __esm({
+ "node_modules/viem/_esm/actions/public/uninstallFilter.js"() {
"use strict";
- init_stringify();
- init_base();
- InvalidDomainError = class extends BaseError2 {
- constructor({ domain }) {
- super(`Invalid domain "${stringify(domain)}".`, {
- metaMessages: ["Must be a valid EIP-712 domain."]
- });
- }
- };
- InvalidPrimaryTypeError = class extends BaseError2 {
- constructor({ primaryType, types }) {
- super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
- docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
- metaMessages: ["Check that the primary type is a key in `types`."]
- });
- }
- };
- InvalidStructTypeError = class extends BaseError2 {
- constructor({ type }) {
- super(`Struct type "${type}" is invalid.`, {
- metaMessages: ["Struct type must not be a Solidity type."],
- name: "InvalidStructTypeError"
- });
- }
- };
}
});
-// node_modules/viem/_esm/utils/typedData.js
-function validateTypedData(parameters) {
- const { domain, message, primaryType, types } = parameters;
- const validateData = (struct, data) => {
- for (const param of struct) {
- const { name, type } = param;
- const value = data[name];
- const integerMatch = type.match(integerRegex2);
- if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
- const [_type, base2, size_] = integerMatch;
- numberToHex(value, {
- signed: base2 === "int",
- size: Number.parseInt(size_, 10) / 8
- });
- }
- if (type === "address" && typeof value === "string" && !isAddress(value))
- throw new InvalidAddressError({ address: value });
- const bytesMatch = type.match(bytesRegex2);
- if (bytesMatch) {
- const [_type, size_] = bytesMatch;
- if (size_ && size(value) !== Number.parseInt(size_, 10))
- throw new BytesSizeMismatchError({
- expectedSize: Number.parseInt(size_, 10),
- givenSize: size(value)
+// node_modules/viem/_esm/actions/public/watchContractEvent.js
+function watchContractEvent(client, parameters) {
+ const { abi: abi2, address: address2, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ } = parameters;
+ const enablePolling = (() => {
+ if (typeof poll_ !== "undefined")
+ return poll_;
+ if (typeof fromBlock === "bigint")
+ return true;
+ if (client.transport.type === "webSocket" || client.transport.type === "ipc")
+ return false;
+ if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc"))
+ return false;
+ return true;
+ })();
+ const pollContractEvent = () => {
+ const strict = strict_ ?? false;
+ const observerId = stringify([
+ "watchContractEvent",
+ address2,
+ args,
+ batch,
+ client.uid,
+ eventName,
+ pollingInterval,
+ strict,
+ fromBlock
+ ]);
+ return observe(observerId, { onLogs, onError }, (emit) => {
+ let previousBlockNumber;
+ if (fromBlock !== void 0)
+ previousBlockNumber = fromBlock - 1n;
+ let filter;
+ let initialized = false;
+ const unwatch = poll(async () => {
+ if (!initialized) {
+ try {
+ filter = await getAction(client, createContractEventFilter, "createContractEventFilter")({
+ abi: abi2,
+ address: address2,
+ args,
+ eventName,
+ strict,
+ fromBlock
+ });
+ } catch {
+ }
+ initialized = true;
+ return;
+ }
+ try {
+ let logs;
+ if (filter) {
+ logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter });
+ } else {
+ const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({});
+ if (previousBlockNumber && previousBlockNumber < blockNumber) {
+ logs = await getAction(client, getContractEvents, "getContractEvents")({
+ abi: abi2,
+ address: address2,
+ args,
+ eventName,
+ fromBlock: previousBlockNumber + 1n,
+ toBlock: blockNumber,
+ strict
+ });
+ } else {
+ logs = [];
+ }
+ previousBlockNumber = blockNumber;
+ }
+ if (logs.length === 0)
+ return;
+ if (batch)
+ emit.onLogs(logs);
+ else
+ for (const log of logs)
+ emit.onLogs([log]);
+ } catch (err) {
+ if (filter && err instanceof InvalidInputRpcError)
+ initialized = false;
+ emit.onError?.(err);
+ }
+ }, {
+ emitOnBegin: true,
+ interval: pollingInterval
+ });
+ return async () => {
+ if (filter)
+ await getAction(client, uninstallFilter, "uninstallFilter")({ filter });
+ unwatch();
+ };
+ });
+ };
+ const subscribeContractEvent = () => {
+ const strict = strict_ ?? false;
+ const observerId = stringify([
+ "watchContractEvent",
+ address2,
+ args,
+ batch,
+ client.uid,
+ eventName,
+ pollingInterval,
+ strict
+ ]);
+ let active = true;
+ let unsubscribe = () => active = false;
+ return observe(observerId, { onLogs, onError }, (emit) => {
+ ;
+ (async () => {
+ try {
+ const transport = (() => {
+ if (client.transport.type === "fallback") {
+ const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc");
+ if (!transport2)
+ return client.transport;
+ return transport2.value;
+ }
+ return client.transport;
+ })();
+ const topics = eventName ? encodeEventTopics({
+ abi: abi2,
+ eventName,
+ args
+ }) : [];
+ const { unsubscribe: unsubscribe_ } = await transport.subscribe({
+ params: ["logs", { address: address2, topics }],
+ onData(data) {
+ if (!active)
+ return;
+ const log = data.result;
+ try {
+ const { eventName: eventName2, args: args2 } = decodeEventLog({
+ abi: abi2,
+ data: log.data,
+ topics: log.topics,
+ strict: strict_
+ });
+ const formatted = formatLog(log, {
+ args: args2,
+ eventName: eventName2
+ });
+ emit.onLogs([formatted]);
+ } catch (err) {
+ let eventName2;
+ let isUnnamed;
+ if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) {
+ if (strict_)
+ return;
+ eventName2 = err.abiItem.name;
+ isUnnamed = err.abiItem.inputs?.some((x) => !("name" in x && x.name));
+ }
+ const formatted = formatLog(log, {
+ args: isUnnamed ? [] : {},
+ eventName: eventName2
+ });
+ emit.onLogs([formatted]);
+ }
+ },
+ onError(error) {
+ emit.onError?.(error);
+ }
});
- }
- const struct2 = types[type];
- if (struct2) {
- validateReference(type);
- validateData(struct2, value);
- }
- }
+ unsubscribe = unsubscribe_;
+ if (!active)
+ unsubscribe();
+ } catch (err) {
+ onError?.(err);
+ }
+ })();
+ return () => unsubscribe();
+ });
};
- if (types.EIP712Domain && domain) {
- if (typeof domain !== "object")
- throw new InvalidDomainError({ domain });
- validateData(types.EIP712Domain, domain);
- }
- if (primaryType !== "EIP712Domain") {
- if (types[primaryType])
- validateData(types[primaryType], message);
- else
- throw new InvalidPrimaryTypeError({ primaryType, types });
- }
-}
-function getTypesForEIP712Domain({ domain }) {
- return [
- typeof domain?.name === "string" && { name: "name", type: "string" },
- domain?.version && { name: "version", type: "string" },
- (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && {
- name: "chainId",
- type: "uint256"
- },
- domain?.verifyingContract && {
- name: "verifyingContract",
- type: "address"
- },
- domain?.salt && { name: "salt", type: "bytes32" }
- ].filter(Boolean);
-}
-function validateReference(type) {
- if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int"))
- throw new InvalidStructTypeError({ type });
+ return enablePolling ? pollContractEvent() : subscribeContractEvent();
}
-var init_typedData2 = __esm({
- "node_modules/viem/_esm/utils/typedData.js"() {
+var init_watchContractEvent = __esm({
+ "node_modules/viem/_esm/actions/public/watchContractEvent.js"() {
"use strict";
init_abi();
- init_address();
- init_typedData();
- init_isAddress();
- init_size();
- init_toHex();
- init_regex2();
+ init_rpc();
+ init_decodeEventLog();
+ init_encodeEventTopics();
+ init_log2();
+ init_getAction();
+ init_observe();
+ init_poll();
+ init_stringify();
+ init_createContractEventFilter();
+ init_getBlockNumber();
+ init_getContractEvents();
+ init_getFilterChanges();
+ init_uninstallFilter();
}
});
-// node_modules/viem/_esm/utils/signature/hashTypedData.js
-function hashTypedData(parameters) {
- const { domain = {}, message, primaryType } = parameters;
- const types = {
- EIP712Domain: getTypesForEIP712Domain({ domain }),
- ...parameters.types
- };
- validateTypedData({
- domain,
- message,
- primaryType,
- types
- });
- const parts = ["0x1901"];
- if (domain)
- parts.push(hashDomain({
- domain,
- types
- }));
- if (primaryType !== "EIP712Domain")
- parts.push(hashStruct({
- data: message,
- primaryType,
- types
- }));
- return keccak256(concat(parts));
-}
-function hashDomain({ domain, types }) {
- return hashStruct({
- data: domain,
- primaryType: "EIP712Domain",
- types
- });
-}
-function hashStruct({ data, primaryType, types }) {
- const encoded = encodeData({
- data,
- primaryType,
- types
- });
- return keccak256(encoded);
-}
-function encodeData({ data, primaryType, types }) {
- const encodedTypes = [{ type: "bytes32" }];
- const encodedValues = [hashType({ primaryType, types })];
- for (const field of types[primaryType]) {
- const [type, value] = encodeField({
- types,
- name: field.name,
- type: field.type,
- value: data[field.name]
- });
- encodedTypes.push(type);
- encodedValues.push(value);
- }
- return encodeAbiParameters(encodedTypes, encodedValues);
-}
-function hashType({ primaryType, types }) {
- const encodedHashType = toHex(encodeType({ primaryType, types }));
- return keccak256(encodedHashType);
-}
-function encodeType({ primaryType, types }) {
- let result = "";
- const unsortedDeps = findTypeDependencies({ primaryType, types });
- unsortedDeps.delete(primaryType);
- const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
- for (const type of deps) {
- result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
- }
- return result;
-}
-function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
- const match = primaryType_.match(/^\w*/u);
- const primaryType = match?.[0];
- if (results.has(primaryType) || types[primaryType] === void 0) {
- return results;
- }
- results.add(primaryType);
- for (const field of types[primaryType]) {
- findTypeDependencies({ primaryType: field.type, types }, results);
- }
- return results;
+// node_modules/viem/_esm/actions/wallet/sendRawTransaction.js
+async function sendRawTransaction(client, { serializedTransaction }) {
+ return client.request({
+ method: "eth_sendRawTransaction",
+ params: [serializedTransaction]
+ }, { retryCount: 0 });
}
-function encodeField({ types, name, type, value }) {
- if (types[type] !== void 0) {
- return [
- { type: "bytes32" },
- keccak256(encodeData({ data: value, primaryType: type, types }))
- ];
- }
- if (type === "bytes")
- return [{ type: "bytes32" }, keccak256(value)];
- if (type === "string")
- return [{ type: "bytes32" }, keccak256(toHex(value))];
- if (type.lastIndexOf("]") === type.length - 1) {
- const parsedType = type.slice(0, type.lastIndexOf("["));
- const typeValuePairs = value.map((item) => encodeField({
- name,
- type: parsedType,
- types,
- value: item
- }));
- return [
- { type: "bytes32" },
- keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))
- ];
+var init_sendRawTransaction = __esm({
+ "node_modules/viem/_esm/actions/wallet/sendRawTransaction.js"() {
+ "use strict";
}
- return [{ type }, value];
+});
+
+// node_modules/viem/_esm/utils/promise/withRetry.js
+function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) {
+ return new Promise((resolve, reject) => {
+ const attemptRetry = async ({ count = 0 } = {}) => {
+ const retry = async ({ error }) => {
+ const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_;
+ if (delay)
+ await wait(delay);
+ attemptRetry({ count: count + 1 });
+ };
+ try {
+ const data = await fn();
+ resolve(data);
+ } catch (err) {
+ if (count < retryCount && await shouldRetry2({ count, error: err }))
+ return retry({ error: err });
+ reject(err);
+ }
+ };
+ attemptRetry();
+ });
}
-var init_hashTypedData = __esm({
- "node_modules/viem/_esm/utils/signature/hashTypedData.js"() {
+var init_withRetry = __esm({
+ "node_modules/viem/_esm/utils/promise/withRetry.js"() {
"use strict";
- init_encodeAbiParameters();
- init_concat();
- init_toHex();
- init_keccak256();
- init_typedData2();
+ init_wait();
}
});
-// node_modules/viem/_esm/utils/signature/serializeSignature.js
-function serializeSignature({ r, s: s3, to = "hex", v, yParity }) {
- const yParity_ = (() => {
- if (yParity === 0 || yParity === 1)
- return yParity;
- if (v && (v === 27n || v === 28n || v >= 35n))
- return v % 2n === 0n ? 1 : 0;
- throw new Error("Invalid `v` or `yParity` value");
- })();
- const signature2 = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s3)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`;
- if (to === "hex")
- return signature2;
- return hexToBytes(signature2);
+// node_modules/viem/_esm/utils/formatters/transactionReceipt.js
+function formatTransactionReceipt(transactionReceipt, _) {
+ const receipt = {
+ ...transactionReceipt,
+ blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null,
+ contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null,
+ cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null,
+ effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null,
+ gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null,
+ logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null,
+ to: transactionReceipt.to ? transactionReceipt.to : null,
+ transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null,
+ status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null,
+ type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null
+ };
+ if (transactionReceipt.blobGasPrice)
+ receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice);
+ if (transactionReceipt.blobGasUsed)
+ receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed);
+ return receipt;
}
-var init_serializeSignature = __esm({
- "node_modules/viem/_esm/utils/signature/serializeSignature.js"() {
+var receiptStatuses, defineTransactionReceipt;
+var init_transactionReceipt = __esm({
+ "node_modules/viem/_esm/utils/formatters/transactionReceipt.js"() {
"use strict";
- init_secp256k1();
init_fromHex();
- init_toBytes();
+ init_formatter();
+ init_log2();
+ init_transaction2();
+ receiptStatuses = {
+ "0x0": "reverted",
+ "0x1": "success"
+ };
+ defineTransactionReceipt = /* @__PURE__ */ defineFormatter("transactionReceipt", formatTransactionReceipt);
}
});
-// node_modules/@scure/base/lib/esm/index.js
-function isBytes4(a) {
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
-}
-function isArrayOf(isString, arr) {
- if (!Array.isArray(arr))
- return false;
- if (arr.length === 0)
- return true;
- if (isString) {
- return arr.every((item) => typeof item === "string");
- } else {
- return arr.every((item) => Number.isSafeInteger(item));
- }
-}
-function afn(input) {
- if (typeof input !== "function")
- throw new Error("function expected");
- return true;
-}
-function astr(label, input) {
- if (typeof input !== "string")
- throw new Error(`${label}: string expected`);
- return true;
-}
-function anumber2(n) {
- if (!Number.isSafeInteger(n))
- throw new Error(`invalid integer: ${n}`);
-}
-function aArr(input) {
- if (!Array.isArray(input))
- throw new Error("array expected");
-}
-function astrArr(label, input) {
- if (!isArrayOf(true, input))
- throw new Error(`${label}: array of strings expected`);
-}
-function anumArr(label, input) {
- if (!isArrayOf(false, input))
- throw new Error(`${label}: array of numbers expected`);
-}
-// @__NO_SIDE_EFFECTS__
-function chain(...args) {
- const id = (a) => a;
- const wrap3 = (a, b) => (c2) => a(b(c2));
- const encode4 = args.map((x) => x.encode).reduceRight(wrap3, id);
- const decode2 = args.map((x) => x.decode).reduce(wrap3, id);
- return { encode: encode4, decode: decode2 };
-}
-// @__NO_SIDE_EFFECTS__
-function alphabet(letters) {
- const lettersA = typeof letters === "string" ? letters.split("") : letters;
- const len = lettersA.length;
- astrArr("alphabet", lettersA);
- const indexes = new Map(lettersA.map((l2, i) => [l2, i]));
- return {
- encode: (digits) => {
- aArr(digits);
- return digits.map((i) => {
- if (!Number.isSafeInteger(i) || i < 0 || i >= len)
- throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
- return lettersA[i];
- });
- },
- decode: (input) => {
- aArr(input);
- return input.map((letter) => {
- astr("alphabet.decode", letter);
- const i = indexes.get(letter);
- if (i === void 0)
- throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
- return i;
- });
- }
- };
-}
-// @__NO_SIDE_EFFECTS__
-function join(separator = "") {
- astr("join", separator);
- return {
- encode: (from14) => {
- astrArr("join.decode", from14);
- return from14.join(separator);
- },
- decode: (to) => {
- astr("join.decode", to);
- return to.split(separator);
- }
- };
-}
-// @__NO_SIDE_EFFECTS__
-function padding(bits, chr = "=") {
- anumber2(bits);
- astr("padding", chr);
- return {
- encode(data) {
- astrArr("padding.encode", data);
- while (data.length * bits % 8)
- data.push(chr);
- return data;
- },
- decode(input) {
- astrArr("padding.decode", input);
- let end = input.length;
- if (end * bits % 8)
- throw new Error("padding: invalid, string should have whole number of bytes");
- for (; end > 0 && input[end - 1] === chr; end--) {
- const last = end - 1;
- const byte = last * bits;
- if (byte % 8 === 0)
- throw new Error("padding: invalid, string has too much padding");
- }
- return input.slice(0, end);
- }
- };
-}
-function convertRadix(data, from14, to) {
- if (from14 < 2)
- throw new Error(`convertRadix: invalid from=${from14}, base cannot be less than 2`);
- if (to < 2)
- throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
- aArr(data);
- if (!data.length)
- return [];
- let pos = 0;
- const res = [];
- const digits = Array.from(data, (d) => {
- anumber2(d);
- if (d < 0 || d >= from14)
- throw new Error(`invalid integer: ${d}`);
- return d;
- });
- const dlen = digits.length;
- while (true) {
- let carry = 0;
- let done = true;
- for (let i = pos; i < dlen; i++) {
- const digit = digits[i];
- const fromCarry = from14 * carry;
- const digitBase = fromCarry + digit;
- if (!Number.isSafeInteger(digitBase) || fromCarry / from14 !== carry || digitBase - digit !== fromCarry) {
- throw new Error("convertRadix: carry overflow");
- }
- const div = digitBase / to;
- carry = digitBase % to;
- const rounded = Math.floor(div);
- digits[i] = rounded;
- if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
- throw new Error("convertRadix: carry overflow");
- if (!done)
- continue;
- else if (!rounded)
- pos = i;
- else
- done = false;
+// node_modules/viem/_esm/utils/uid.js
+function uid(length = 11) {
+ if (!buffer || index + length > size4 * 2) {
+ buffer = "";
+ index = 0;
+ for (let i = 0; i < size4; i++) {
+ buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1);
}
- res.push(carry);
- if (done)
- break;
}
- for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
- res.push(0);
- return res.reverse();
+ return buffer.substring(index, index++ + length);
}
-function convertRadix2(data, from14, to, padding2) {
- aArr(data);
- if (from14 <= 0 || from14 > 32)
- throw new Error(`convertRadix2: wrong from=${from14}`);
- if (to <= 0 || to > 32)
- throw new Error(`convertRadix2: wrong to=${to}`);
- if (/* @__PURE__ */ radix2carry(from14, to) > 32) {
- throw new Error(`convertRadix2: carry overflow from=${from14} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from14, to)}`);
- }
- let carry = 0;
- let pos = 0;
- const max = powers[from14];
- const mask = powers[to] - 1;
- const res = [];
- for (const n of data) {
- anumber2(n);
- if (n >= max)
- throw new Error(`convertRadix2: invalid data word=${n} from=${from14}`);
- carry = carry << from14 | n;
- if (pos + from14 > 32)
- throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from14}`);
- pos += from14;
- for (; pos >= to; pos -= to)
- res.push((carry >> pos - to & mask) >>> 0);
- const pow = powers[pos];
- if (pow === void 0)
- throw new Error("invalid carry");
- carry &= pow - 1;
+var size4, index, buffer;
+var init_uid = __esm({
+ "node_modules/viem/_esm/utils/uid.js"() {
+ "use strict";
+ size4 = 256;
+ index = size4;
}
- carry = carry << to - pos & mask;
- if (!padding2 && pos >= from14)
- throw new Error("Excess padding");
- if (!padding2 && carry > 0)
- throw new Error(`Non-zero padding: ${carry}`);
- if (padding2 && pos > 0)
- res.push(carry >>> 0);
- return res;
-}
-// @__NO_SIDE_EFFECTS__
-function radix(num2) {
- anumber2(num2);
- const _256 = 2 ** 8;
- return {
- encode: (bytes) => {
- if (!isBytes4(bytes))
- throw new Error("radix.encode input should be Uint8Array");
- return convertRadix(Array.from(bytes), _256, num2);
- },
- decode: (digits) => {
- anumArr("radix.decode", digits);
- return Uint8Array.from(convertRadix(digits, num2, _256));
- }
- };
-}
-// @__NO_SIDE_EFFECTS__
-function radix2(bits, revPadding = false) {
- anumber2(bits);
- if (bits <= 0 || bits > 32)
- throw new Error("radix2: bits should be in (0..32]");
- if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32)
- throw new Error("radix2: carry overflow");
- return {
- encode: (bytes) => {
- if (!isBytes4(bytes))
- throw new Error("radix2.encode input should be Uint8Array");
- return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
- },
- decode: (digits) => {
- anumArr("radix2.decode", digits);
- return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
- }
- };
-}
-function checksum3(len, fn) {
- anumber2(len);
- afn(fn);
- return {
- encode(data) {
- if (!isBytes4(data))
- throw new Error("checksum.encode: input should be Uint8Array");
- const sum = fn(data).slice(0, len);
- const res = new Uint8Array(data.length + len);
- res.set(data);
- res.set(sum, data.length);
- return res;
- },
- decode(data) {
- if (!isBytes4(data))
- throw new Error("checksum.decode: input should be Uint8Array");
- const payload = data.slice(0, -len);
- const oldChecksum = data.slice(-len);
- const newChecksum = fn(payload).slice(0, len);
- for (let i = 0; i < len; i++)
- if (newChecksum[i] !== oldChecksum[i])
- throw new Error("Invalid checksum");
- return payload;
- }
+});
+
+// node_modules/viem/_esm/clients/createClient.js
+function createClient(parameters) {
+ const { batch, chain: chain3, ccipRead, dataSuffix, key = "base", name = "Base Client", type = "base" } = parameters;
+ const experimental_blockTag = parameters.experimental_blockTag ?? (typeof chain3?.experimental_preconfirmationTime === "number" ? "pending" : void 0);
+ const blockTime = chain3?.blockTime ?? 12e3;
+ const defaultPollingInterval = Math.min(Math.max(Math.floor(blockTime / 2), 500), 4e3);
+ const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval;
+ const cacheTime = parameters.cacheTime ?? pollingInterval;
+ const account = parameters.account ? parseAccount(parameters.account) : void 0;
+ const { config, request, value } = parameters.transport({
+ account,
+ chain: chain3,
+ pollingInterval
+ });
+ const transport = { ...config, ...value };
+ const client = {
+ account,
+ batch,
+ cacheTime,
+ ccipRead,
+ chain: chain3,
+ dataSuffix,
+ key,
+ name,
+ pollingInterval,
+ request,
+ transport,
+ type,
+ uid: uid(),
+ ...experimental_blockTag ? { experimental_blockTag } : {}
};
+ function extend(base2) {
+ return (extendFn) => {
+ const extended = extendFn(base2);
+ for (const key2 in client)
+ delete extended[key2];
+ const combined = { ...base2, ...extended };
+ return Object.assign(combined, { extend: extend(combined) });
+ };
+ }
+ return Object.assign(client, { extend: extend(client) });
}
-var gcd, radix2carry, powers, utils;
-var init_esm = __esm({
- "node_modules/@scure/base/lib/esm/index.js"() {
+var init_createClient = __esm({
+ "node_modules/viem/_esm/clients/createClient.js"() {
"use strict";
- gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
- radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from14, to) => from14 + (to - gcd(from14, to));
- powers = /* @__PURE__ */ (() => {
- let res = [];
- for (let i = 0; i < 40; i++)
- res.push(2 ** i);
- return res;
- })();
- utils = {
- alphabet,
- chain,
- checksum: checksum3,
- convertRadix,
- convertRadix2,
- radix,
- radix2,
- join,
- padding
- };
+ init_parseAccount();
+ init_uid();
}
});
-// node_modules/@noble/hashes/esm/pbkdf2.js
-function pbkdf2Init(hash3, _password, _salt, _opts) {
- ahash(hash3);
- const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
- const { c: c2, dkLen, asyncTick } = opts;
- anumber(c2);
- anumber(dkLen);
- anumber(asyncTick);
- if (c2 < 1)
- throw new Error("iterations (c) should be >= 1");
- const password = kdfInputToBytes(_password);
- const salt = kdfInputToBytes(_salt);
- const DK = new Uint8Array(dkLen);
- const PRF = hmac.create(hash3, password);
- const PRFSalt = PRF._cloneInto().update(salt);
- return { c: c2, dkLen, asyncTick, DK, PRF, PRFSalt };
-}
-function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
- PRF.destroy();
- PRFSalt.destroy();
- if (prfW)
- prfW.destroy();
- clean(u);
- return DK;
+// node_modules/viem/_esm/utils/ens/errors.js
+function isNullUniversalResolverError(err) {
+ if (!(err instanceof BaseError2))
+ return false;
+ const cause = err.walk((e7) => e7 instanceof ContractFunctionRevertedError);
+ if (!(cause instanceof ContractFunctionRevertedError))
+ return false;
+ if (cause.data?.errorName === "HttpError")
+ return true;
+ if (cause.data?.errorName === "ResolverError")
+ return true;
+ if (cause.data?.errorName === "ResolverNotContract")
+ return true;
+ if (cause.data?.errorName === "ResolverNotFound")
+ return true;
+ if (cause.data?.errorName === "ReverseAddressMismatch")
+ return true;
+ if (cause.data?.errorName === "UnsupportedResolverProfile")
+ return true;
+ return false;
}
-function pbkdf2(hash3, password, salt, opts) {
- const { c: c2, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash3, password, salt, opts);
- let prfW;
- const arr = new Uint8Array(4);
- const view = createView(arr);
- const u = new Uint8Array(PRF.outputLen);
- for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
- const Ti = DK.subarray(pos, pos + PRF.outputLen);
- view.setInt32(0, ti, false);
- (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
- Ti.set(u.subarray(0, Ti.length));
- for (let ui = 1; ui < c2; ui++) {
- PRF._cloneInto(prfW).update(u).digestInto(u);
- for (let i = 0; i < Ti.length; i++)
- Ti[i] ^= u[i];
- }
+var init_errors3 = __esm({
+ "node_modules/viem/_esm/utils/ens/errors.js"() {
+ "use strict";
+ init_base();
+ init_contract();
}
- return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
+});
+
+// node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js
+function encodedLabelToLabelhash(label) {
+ if (label.length !== 66)
+ return null;
+ if (label.indexOf("[") !== 0)
+ return null;
+ if (label.indexOf("]") !== 65)
+ return null;
+ const hash3 = `0x${label.slice(1, 65)}`;
+ if (!isHex(hash3))
+ return null;
+ return hash3;
}
-var init_pbkdf2 = __esm({
- "node_modules/@noble/hashes/esm/pbkdf2.js"() {
+var init_encodedLabelToLabelhash = __esm({
+ "node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js"() {
"use strict";
- init_hmac();
- init_utils2();
+ init_isHex();
}
});
-// node_modules/@scure/bip39/esm/index.js
-function nfkd(str) {
- if (typeof str !== "string")
- throw new TypeError("invalid mnemonic type: " + typeof str);
- return str.normalize("NFKD");
-}
-function normalize(str) {
- const norm = nfkd(str);
- const words = norm.split(" ");
- if (![12, 15, 18, 21, 24].includes(words.length))
- throw new Error("Invalid mnemonic");
- return { nfkd: norm, words };
-}
-function aentropy(ent) {
- abytes(ent, 16, 20, 24, 28, 32);
-}
-function generateMnemonic(wordlist2, strength = 128) {
- anumber(strength);
- if (strength % 32 !== 0 || strength > 256)
- throw new TypeError("Invalid entropy");
- return entropyToMnemonic(randomBytes(strength / 8), wordlist2);
-}
-function getCoder(wordlist2) {
- if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string")
- throw new Error("Wordlist: expected array of 2048 strings");
- wordlist2.forEach((i) => {
- if (typeof i !== "string")
- throw new Error("wordlist: non-string element: " + i);
- });
- return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist2));
-}
-function mnemonicToEntropy(mnemonic, wordlist2) {
- const { words } = normalize(mnemonic);
- const entropy = getCoder(wordlist2).decode(words);
- aentropy(entropy);
- return entropy;
-}
-function entropyToMnemonic(entropy, wordlist2) {
- aentropy(entropy);
- const words = getCoder(wordlist2).encode(entropy);
- return words.join(isJapanese(wordlist2) ? "\u3000" : " ");
+// node_modules/viem/_esm/utils/ens/namehash.js
+function namehash(name) {
+ let result = new Uint8Array(32).fill(0);
+ if (!name)
+ return bytesToHex(result);
+ const labels = name.split(".");
+ for (let i = labels.length - 1; i >= 0; i -= 1) {
+ const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]);
+ const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes");
+ result = keccak256(concat([result, hashed]), "bytes");
+ }
+ return bytesToHex(result);
}
-function validateMnemonic(mnemonic, wordlist2) {
- try {
- mnemonicToEntropy(mnemonic, wordlist2);
- } catch (e7) {
- return false;
+var init_namehash = __esm({
+ "node_modules/viem/_esm/utils/ens/namehash.js"() {
+ "use strict";
+ init_concat();
+ init_toBytes();
+ init_toHex();
+ init_keccak256();
+ init_encodedLabelToLabelhash();
}
- return true;
+});
+
+// node_modules/viem/_esm/utils/ens/encodeLabelhash.js
+function encodeLabelhash(hash3) {
+ return `[${hash3.slice(2)}]`;
}
-function mnemonicToSeedSync(mnemonic, passphrase = "") {
- return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
+var init_encodeLabelhash = __esm({
+ "node_modules/viem/_esm/utils/ens/encodeLabelhash.js"() {
+ "use strict";
+ }
+});
+
+// node_modules/viem/_esm/utils/ens/labelhash.js
+function labelhash(label) {
+ const result = new Uint8Array(32).fill(0);
+ if (!label)
+ return bytesToHex(result);
+ return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label));
}
-var isJapanese, calcChecksum, psalt;
-var init_esm2 = __esm({
- "node_modules/@scure/bip39/esm/index.js"() {
+var init_labelhash = __esm({
+ "node_modules/viem/_esm/utils/ens/labelhash.js"() {
"use strict";
- init_pbkdf2();
- init_sha2();
- init_utils2();
- init_esm();
- isJapanese = (wordlist2) => wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093";
- calcChecksum = (entropy) => {
- const bitsLeft = 8 - entropy.length / 4;
- return new Uint8Array([sha256(entropy)[0] >> bitsLeft << bitsLeft]);
- };
- psalt = (passphrase) => nfkd("mnemonic" + passphrase);
+ init_toBytes();
+ init_toHex();
+ init_keccak256();
+ init_encodedLabelToLabelhash();
}
});
-// node_modules/viem/_esm/accounts/toAccount.js
-function toAccount(source) {
- if (typeof source === "string") {
- if (!isAddress(source, { strict: false }))
- throw new InvalidAddressError({ address: source });
- return {
- address: source,
- type: "json-rpc"
- };
+// node_modules/viem/_esm/utils/ens/packetToBytes.js
+function packetToBytes(packet) {
+ const value = packet.replace(/^\.|\.$/gm, "");
+ if (value.length === 0)
+ return new Uint8Array(1);
+ const bytes = new Uint8Array(stringToBytes(value).byteLength + 2);
+ let offset = 0;
+ const list = value.split(".");
+ for (let i = 0; i < list.length; i++) {
+ let encoded = stringToBytes(list[i]);
+ if (encoded.byteLength > 255)
+ encoded = stringToBytes(encodeLabelhash(labelhash(list[i])));
+ bytes[offset] = encoded.length;
+ bytes.set(encoded, offset + 1);
+ offset += encoded.length + 1;
}
- if (!isAddress(source.address, { strict: false }))
- throw new InvalidAddressError({ address: source.address });
- return {
- address: source.address,
- nonceManager: source.nonceManager,
- sign: source.sign,
- signAuthorization: source.signAuthorization,
- signMessage: source.signMessage,
- signTransaction: source.signTransaction,
- signTypedData: source.signTypedData,
- source: "custom",
- type: "local"
- };
+ if (bytes.byteLength !== offset + 1)
+ return bytes.slice(0, offset + 1);
+ return bytes;
}
-var init_toAccount = __esm({
- "node_modules/viem/_esm/accounts/toAccount.js"() {
+var init_packetToBytes = __esm({
+ "node_modules/viem/_esm/utils/ens/packetToBytes.js"() {
"use strict";
- init_address();
- init_isAddress();
+ init_toBytes();
+ init_encodeLabelhash();
+ init_labelhash();
}
});
-// node_modules/viem/_esm/accounts/utils/sign.js
-async function sign({ hash: hash3, privateKey, to = "object" }) {
- const { r, s: s3, recovery } = secp256k1.sign(hash3.slice(2), privateKey.slice(2), {
- lowS: true,
- extraEntropy: isHex(extraEntropy, { strict: false }) ? hexToBytes(extraEntropy) : extraEntropy
- });
- const signature2 = {
- r: numberToHex(r, { size: 32 }),
- s: numberToHex(s3, { size: 32 }),
- v: recovery ? 28n : 27n,
- yParity: recovery
- };
- return (() => {
- if (to === "bytes" || to === "hex")
- return serializeSignature({ ...signature2, to });
- return signature2;
+// node_modules/viem/_esm/actions/ens/getEnsAddress.js
+async function getEnsAddress(client, parameters) {
+ const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } = parameters;
+ const { chain: chain3 } = client;
+ const universalResolverAddress = (() => {
+ if (parameters.universalResolverAddress)
+ return parameters.universalResolverAddress;
+ if (!chain3)
+ throw new Error("client chain not configured. universalResolverAddress is required.");
+ return getChainContractAddress({
+ blockNumber,
+ chain: chain3,
+ contract: "ensUniversalResolver"
+ });
+ })();
+ const tlds = chain3?.ensTlds;
+ if (tlds && !tlds.some((tld) => name.endsWith(tld)))
+ return null;
+ const args = (() => {
+ if (coinType != null)
+ return [namehash(name), BigInt(coinType)];
+ return [namehash(name)];
})();
+ try {
+ const functionData = encodeFunctionData({
+ abi: addressResolverAbi,
+ functionName: "addr",
+ args
+ });
+ const readContractParameters = {
+ address: universalResolverAddress,
+ abi: universalResolverResolveAbi,
+ functionName: "resolveWithGateways",
+ args: [
+ toHex(packetToBytes(name)),
+ functionData,
+ gatewayUrls ?? [localBatchGatewayUrl]
+ ],
+ blockNumber,
+ blockTag
+ };
+ const readContractAction = getAction(client, readContract, "readContract");
+ const res = await readContractAction(readContractParameters);
+ if (res[0] === "0x")
+ return null;
+ const address2 = decodeFunctionResult({
+ abi: addressResolverAbi,
+ args,
+ functionName: "addr",
+ data: res[0]
+ });
+ if (address2 === "0x")
+ return null;
+ if (trim(address2) === "0x00")
+ return null;
+ return address2;
+ } catch (err) {
+ if (strict)
+ throw err;
+ if (isNullUniversalResolverError(err))
+ return null;
+ throw err;
+ }
}
-var extraEntropy;
-var init_sign = __esm({
- "node_modules/viem/_esm/accounts/utils/sign.js"() {
+var init_getEnsAddress = __esm({
+ "node_modules/viem/_esm/actions/ens/getEnsAddress.js"() {
"use strict";
- init_secp256k1();
- init_isHex();
- init_toBytes();
+ init_abis();
+ init_decodeFunctionResult();
+ init_encodeFunctionData();
+ init_getChainContractAddress();
+ init_trim();
init_toHex();
- init_serializeSignature();
- extraEntropy = false;
+ init_errors3();
+ init_localBatchGatewayRequest();
+ init_namehash();
+ init_packetToBytes();
+ init_getAction();
+ init_readContract();
}
});
-// node_modules/viem/_esm/accounts/utils/signAuthorization.js
-async function signAuthorization(parameters) {
- const { chainId, nonce, privateKey, to = "object" } = parameters;
- const address2 = parameters.contractAddress ?? parameters.address;
- const signature2 = await sign({
- hash: hashAuthorization({ address: address2, chainId, nonce }),
- privateKey,
- to
- });
- if (to === "object")
+// node_modules/viem/_esm/errors/ens.js
+var EnsAvatarInvalidMetadataError, EnsAvatarInvalidNftUriError, EnsAvatarUriResolutionError, EnsAvatarUnsupportedNamespaceError;
+var init_ens = __esm({
+ "node_modules/viem/_esm/errors/ens.js"() {
+ "use strict";
+ init_base();
+ EnsAvatarInvalidMetadataError = class extends BaseError2 {
+ constructor({ data }) {
+ super("Unable to extract image from metadata. The metadata may be malformed or invalid.", {
+ metaMessages: [
+ "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.",
+ "",
+ `Provided data: ${JSON.stringify(data)}`
+ ],
+ name: "EnsAvatarInvalidMetadataError"
+ });
+ }
+ };
+ EnsAvatarInvalidNftUriError = class extends BaseError2 {
+ constructor({ reason }) {
+ super(`ENS NFT avatar URI is invalid. ${reason}`, {
+ name: "EnsAvatarInvalidNftUriError"
+ });
+ }
+ };
+ EnsAvatarUriResolutionError = class extends BaseError2 {
+ constructor({ uri }) {
+ super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" });
+ }
+ };
+ EnsAvatarUnsupportedNamespaceError = class extends BaseError2 {
+ constructor({ namespace }) {
+ super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" });
+ }
+ };
+ }
+});
+
+// node_modules/viem/_esm/utils/ens/avatar/utils.js
+async function isImageUri(uri) {
+ try {
+ const res = await fetch(uri, { method: "HEAD" });
+ if (res.status === 200) {
+ const contentType = res.headers.get("content-type");
+ return contentType?.startsWith("image/");
+ }
+ return false;
+ } catch (error) {
+ if (typeof error === "object" && typeof error.response !== "undefined") {
+ return false;
+ }
+ if (!Object.hasOwn(globalThis, "Image"))
+ return false;
+ return new Promise((resolve) => {
+ const img = new Image();
+ img.onload = () => {
+ resolve(true);
+ };
+ img.onerror = () => {
+ resolve(false);
+ };
+ img.src = uri;
+ });
+ }
+}
+function getGateway(custom2, defaultGateway) {
+ if (!custom2)
+ return defaultGateway;
+ if (custom2.endsWith("/"))
+ return custom2.slice(0, -1);
+ return custom2;
+}
+function resolveAvatarUri({ uri, gatewayUrls }) {
+ const isEncoded = base64Regex.test(uri);
+ if (isEncoded)
+ return { uri, isOnChain: true, isEncoded };
+ const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io");
+ const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net");
+ const networkRegexMatch = uri.match(networkRegex);
+ const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {};
+ const isIPNS = protocol === "ipns:/" || subpath === "ipns/";
+ const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri);
+ if (uri.startsWith("http") && !isIPNS && !isIPFS) {
+ let replacedUri = uri;
+ if (gatewayUrls?.arweave)
+ replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave);
+ return { uri: replacedUri, isOnChain: false, isEncoded: false };
+ }
+ if ((isIPNS || isIPFS) && target) {
return {
- address: address2,
- chainId,
- nonce,
- ...signature2
+ uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`,
+ isOnChain: false,
+ isEncoded: false
};
- return signature2;
+ }
+ if (protocol === "ar:/" && target) {
+ return {
+ uri: `${arweaveGateway}/${target}${subtarget || ""}`,
+ isOnChain: false,
+ isEncoded: false
+ };
+ }
+ let parsedUri = uri.replace(dataURIRegex, "");
+ if (parsedUri.startsWith("