@ar.io/wayfinder-core

中文文档
2.0.2发布于 2026/08/14Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 3632

WayFinder core library for intelligently routing to optimal AR.IO gateways

原始使用文档
文档目录18 节
  1. Quick Start
  2. Installation
  3. Basic Usage
  4. Using with AR.IO Network
  5. Enable Verification
  6. createRoutingStrategy
  7. createVerificationStrategy
  8. ar:// Protocol
  9. Dynamic Routing
  10. Gateway Providers
  11. Routing Strategies
  12. Data Retrieval Strategies
  13. Verification Strategies
  14. x402 Payments
  15. Events and Monitoring
  16. Telemetry
  17. Resiliency
  18. Request Flow

Wayfinder Core

@ar.io/wayfinder-core is the core library for the Wayfinder project. It provides the core functionality for routing and verifying data through the ar.io network.

Quick Start

Installation

To install the latest version, run:

npm install @ar.io/wayfinder-core
# or
yarn add @ar.io/wayfinder-core

Basic Usage

import { createWayfinderClient } from '@ar.io/wayfinder-core';

// Creates a Wayfinder client with sensible defaults:
// - Trusted peers gateway provider with caching (5 minute TTL)
// - Random routing strategy
// - Verification disabled
const wayfinder = createWayfinderClient();

// Use Wayfinder to fetch data using ar:// protocol
const response = await wayfinder.request('ar://example-name');

Using with AR.IO Network

import {
  createWayfinderClient,
  FastestPingRoutingStrategy,
  NetworkGatewaysProvider,
} from '@ar.io/wayfinder-core';
import { ARIO } from '@ar.io/sdk';
import { createSolanaRpc } from '@solana/kit';

// AR.IO Solana mainnet — program-id overrides are not needed on mainnet
// (the SDK ships defaults). For devnet, pass explicit program IDs.
const ario = ARIO.init({
  rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'),
});

const wayfinder = createWayfinderClient({
  routingStrategy: new FastestPingRoutingStrategy({
    gatewaysProvider: new NetworkGatewaysProvider({
      ario,
      sortBy: 'operatorStake',
      sortOrder: 'desc',
      limit: 10,
    }),
  }),
});

Enable Verification

import {
  createWayfinderClient,
  HashVerificationStrategy,
} from '@ar.io/wayfinder-core';

const wayfinder = createWayfinderClient({
  verificationStrategy: new HashVerificationStrategy({
    trustedGateways: [new URL('https://turbo-gateway.com')],
  }),
  strict: true, // Fail requests on verification errors
});

Wayfinder Core provides helper functions to construct routing and verification strategies:

createRoutingStrategy

Create routing strategies with a simple string identifier:

import { createRoutingStrategy } from '@ar.io/wayfinder-core';

// Create a random routing strategy
const randomStrategy = createRoutingStrategy({
  strategy: 'random',
  gatewaysProvider: myGatewaysProvider,
  logger: myLogger,
});

// Available strategies: 'random', 'fastest', 'balanced', 'preferred'

createVerificationStrategy

Create verification strategies with a simple string identifier:

import { createVerificationStrategy } from '@ar.io/wayfinder-core';

// Create a hash verification strategy
const hashStrategy = createVerificationStrategy({
  strategy: 'hash',
  trustedGateways: [new URL('https://turbo-gateway.com')],
  logger: myLogger,
});

// Available strategies: 'hash', 'data-root', 'remote', 'disabled'

ar:// Protocol

Wayfinder supports several ar:// URL formats:

ar://TRANSACTION_ID              # Direct transaction ID
ar://NAME                        # ArNS name (paths supported)
ar:///info                       # Gateway endpoint (/info)

Dynamic Routing

Wayfinder supports a resolveUrl method which generates dynamic redirect URLs to a target gateway based on the provided routing strategy. This function can be used to directly replace any hard-coded gateway URLs, and instead use Wayfinder's routing logic to select a gateway for the request.

ArNS names

Given an ArNS name, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy.

const redirectUrl = await wayfinder.resolveUrl({
  arnsName: 'ardrive',
});
// results in https://ardrive.<selected-gateway>

Transaction Ids

Given a txId, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy.

const redirectUrl = await wayfinder.resolveUrl({
  txId: 'example-tx-id',
});
// results in https://<selected-gateway>/example-tx-id

Legacy URLs

Given a legacy arweave.net or arweave.dev URL, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy.

const redirectUrl = await wayfinder.resolveUrl({
  originalUrl: 'https://arweave.net/example-tx-id',
});
// results in https://<selected-gateway>/example-tx-id

ar:// URLs

Given an ar:// URL, the redirect URL will be the same as the original URL, but with the gateway selected by Wayfinder's routing strategy.

const redirectUrl = await wayfinder.resolveUrl({
  originalUrl: 'ar://example-name/subpath?query=value',
});
// results in https://<selected-gateway>/example-name/subpath?query=value

Gateway Providers

Gateway providers supply the list of gateways for routing. By default, createWayfinderClient and new Wayfinder() use a cached CompositeGatewaysProvider that tries TrustedPeersGatewaysProvider first and falls back to the trusted gateway itself. Peer discovery is a single point of failure — a gateway can answer /ar-io/peers with 200 and an empty list — and the fallback keeps requests working (routed through the one gateway already trusted) instead of failing outright. Call createDefaultGatewaysProvider() to build the same thing yourself.

ProviderDescriptionUse Case
NetworkGatewaysProviderReturns gateways from AR.IO NetworkLeverage AR.IO Network with quality filtering
TrustedPeersGatewaysProviderFetches from trusted gateway's peersDynamic gateway discovery (default)
StaticGatewaysProviderReturns a static list of gatewaysTesting or specific gateways
SimpleCacheGatewaysProviderIn-memory caching wrapperReduce API calls (used by default)
LocalStorageGatewaysProviderBrowser localStorage cachingPersistent caching (used by default in browsers)
CompositeGatewaysProviderChains multiple providers with fallbackMaximum resilience with multiple sources

NetworkGatewaysProvider

Returns a list of gateways from the ARIO Network based on on-chain Gateway Address Registry. You can specify on-chain metrics for gateways to prioritize the highest quality gateways. Requires @ar.io/sdk and @solana/kit.

import { NetworkGatewaysProvider } from '@ar.io/wayfinder-core';
import { ARIO } from '@ar.io/sdk';
import { createSolanaRpc } from '@solana/kit';

const ario = ARIO.init({
  rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'),
});

const gatewayProvider = new NetworkGatewaysProvider({
  ario,
  sortBy: 'operatorStake',
  sortOrder: 'desc',
  limit: 10,
  filter: (gateway) => gateway.status === 'joined',
});

Note on sorting. The Solana backend of @ar.io/sdk accepts sortBy and sortOrder but does not apply them — its pagination helper slices the account list in on-chain order. This provider therefore sorts client-side, which means it reads the whole registry before applying limit. That is what makes limit: 10 actually return the ten highest-staked gateways rather than ten arbitrary ones. sortBy also accepts dotted paths such as weights.stakeWeight; a gateway missing the field sorts as 0.

TrustedPeersGatewaysProvider

Fetches a dynamic list of trusted peer gateways from an AR.IO gateway's /ar-io/peers endpoint. This provider is useful for discovering available gateways from a trusted source.

import { TrustedPeersGatewaysProvider } from '@ar.io/wayfinder-core';

const gatewayProvider = new TrustedPeersGatewaysProvider({
  trustedGateway: 'https://turbo-gateway.com',
  retries: 3, // optional, defaults to 3
});

A gateway can answer /ar-io/peers with 200 and an empty gateways map — in practice this happens when an instance hasn't synced its view of the registry. The provider retries in that case and, if the list is still empty, throws an error naming the endpoint rather than returning [] (which would surface much later as an opaque "No gateways available" from whichever routing strategy consumed it). Both CompositeGatewaysProvider and SimpleCacheGatewaysProvider treat that throw as a signal to fall back, so wrapping this provider in either one gives you a clean degradation path.

CompositeGatewaysProvider

Chains multiple gateway providers together, trying each in sequence until one succeeds. This is useful for building resilient gateway discovery with fallbacks.

How it works:

  1. Tries each provider in the order they're provided
  2. If a provider returns a non-empty list of gateways, those gateways are used
  3. If a provider throws an error or returns an empty list, moves to the next provider
  4. If all providers fail, throws an error
import {
  CompositeGatewaysProvider,
  NetworkGatewaysProvider,
  StaticGatewaysProvider,
  TrustedPeersGatewaysProvider,
} from '@ar.io/wayfinder-core';
import { ARIO } from '@ar.io/sdk';
import { createSolanaRpc } from '@solana/kit';

const ario = ARIO.init({
  rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'),
});

// Example: Network-first with static fallback
const gatewayProvider = new CompositeGatewaysProvider({
  providers: [
    // Try fetching from AR.IO network first
    new NetworkGatewaysProvider({
      ario,
      sortBy: 'operatorStake',
      limit: 10,
    }),
    // Fallback to trusted peers if network fetch fails
    new TrustedPeersGatewaysProvider({
      trustedGateway: 'https://turbo-gateway.com',
    }),
    // Final fallback to static list
    new StaticGatewaysProvider({
      gateways: ['https://turbo-gateway.com', 'https://g8way.io'],
    }),
  ],
});

Routing Strategies

Wayfinder supports multiple routing strategies to select target gateways for your requests.

StrategyDescriptionUse Case
RandomRoutingStrategySelects a random gateway from a listGood for load balancing and resilience
StaticRoutingStrategyAlways uses a single gatewayWhen you need to use a specific gateway
RoundRobinRoutingStrategySelects gateways in round-robin orderGood for load balancing and resilience
FastestPingRoutingStrategySelects the fastest gateway based on ping timeGood for performance and latency
PingRoutingStrategyWraps another strategy and health-checks its choice, retrying with a different gateway on failureFiltering out unresponsive gateways. Used by default by new Wayfinder()
PreferredWithFallbackRoutingStrategyUses a preferred gateway, with a fallback strategy if the preferred gateway is not availableGood for performance and resilience. Ideal for builders who run their own gateways.
SimpleCacheRoutingStrategyCaches the gateway chosen by another strategy for a TTLAvoids re-running selection on every request
CompositeRoutingStrategyChains multiple routing strategies together, trying each sequentially until one succeedsGood for complex fallback scenarios and maximum resilience

RandomRoutingStrategy

Selects a random gateway from a list of gateways.

import { RandomRoutingStrategy } from '@ar.io/wayfinder-core';

const strategy = new RandomRoutingStrategy({
  gatewaysProvider: myGatewaysProvider,
});

FastestPingRoutingStrategy

Selects the fastest gateway based on ping time. This strategy pings all available gateways and selects the one with the lowest latency.

import { FastestPingRoutingStrategy } from '@ar.io/wayfinder-core';

const strategy = new FastestPingRoutingStrategy({
  timeoutMs: 1000,
  gatewaysProvider: myGatewaysProvider,
  probePath: '/', // optional, defaults to '/'
});

PingRoutingStrategy

Wraps another strategy, health-checks the gateway it picked, and retries with a different one if the check fails. This is the default strategy used by new Wayfinder() (wrapping a RandomRoutingStrategy).

import { PingRoutingStrategy, RandomRoutingStrategy } from '@ar.io/wayfinder-core';

const strategy = new PingRoutingStrategy({
  routingStrategy: new RandomRoutingStrategy({ gatewaysProvider: myGatewaysProvider }),
  retries: 5, // optional
  timeoutMs: 1000, // optional
  probePath: '/', // optional
});

What gets probed. Both ping strategies send a HEAD to probePath on the gateway's own host — not to the sandboxed URL of the request being routed. Probing the content URL makes the gateway resolve the data before it can answer, so a short timeout ends up measuring "is this object already cached here" rather than "is this gateway up". Against the live network with a 1s budget, a HEAD of the gateway root succeeded for ~85% of peers versus ~23% for the sandboxed content URL — and the difference is latency rather than breakage, since the sandboxed URL reaches ~78% once given 10s. Set probePath to /ar-io/healthcheck, or to any path you prefer, to override.

PreferredWithFallbackRoutingStrategy

Uses a preferred gateway, with a fallback strategy if the preferred gateway is not available. This is useful for builders who run their own gateways and want to use their own gateway as the preferred gateway, but also want to have a fallback strategy in case their gateway is not available.

[!INFO] This strategy is built using CompositeRoutingStrategy internally. It first attempts to ping the preferred gateway (using PingRoutingStrategy with StaticRoutingStrategy), and if that fails, it falls back to the specified fallback strategy.

import { PreferredWithFallbackRoutingStrategy, FastestPingRoutingStrategy } from '@ar.io/wayfinder-core';

const strategy = new PreferredWithFallbackRoutingStrategy({
  preferredGateway: 'https://my-gateway.com',
  fallbackStrategy: new FastestPingRoutingStrategy({ timeoutMs: 500 }),
});

CompositeRoutingStrategy

The CompositeRoutingStrategy allows you to chain multiple routing strategies together, providing maximum resilience by trying each strategy in sequence until one succeeds. This is ideal for complex fallback scenarios where you want to combine different routing approaches.

How it works:

  1. Tries each strategy in the order they're provided
  2. If a strategy successfully returns a gateway, that gateway is used (remaining strategies are skipped)
  3. If a strategy throws an error, moves to the next strategy
  4. If all strategies fail, throws an error

Common use cases:

  • Performance + Resilience: Try fastest ping first, fallback to random if ping fails
  • Preferred + Network: Use your own gateway first, fallback to AR.IO network selection
  • Multi-tier Fallback: Try premium gateways, then standard gateways, then any available gateway
import { 
  createWayfinderClient,
  CompositeRoutingStrategy, 
  FastestPingRoutingStrategy, 
  RandomRoutingStrategy,
  StaticRoutingStrategy,
  NetworkGatewaysProvider,
} from '@ar.io/wayfinder-core';
import { ARIO } from '@ar.io/sdk';
import { createSolanaRpc } from '@solana/kit';

const ario = ARIO.init({
  rpc: createSolanaRpc('https://api.mainnet-beta.solana.com'),
});

// Example 1: Performance-first with resilience fallback
const performanceWayfinder = createWayfinderClient({
  routingStrategy: new CompositeRoutingStrategy({
    strategies: [
      // Try fastest ping first (high performance, but may fail if all gateways are slow)
      new FastestPingRoutingStrategy({
        timeoutMs: 500,
        gatewaysProvider: new NetworkGatewaysProvider({
          ario,
          sortBy: 'operatorStake',
          limit: 10,
        }),
      }),
      // Fallback to random selection (guaranteed to work if gateways exist)
      new RandomRoutingStrategy({
        gatewaysProvider: new NetworkGatewaysProvider({
          ario,
          sortBy: 'operatorStake', 
          limit: 20, // Use more gateways for fallback
        }),
      }),
    ],
  }),
});

// Example 2: Preferred gateway with multi-tier fallback
const preferredWayfinder = createWayfinderClient({
  routingStrategy: new CompositeRoutingStrategy({
    strategies: [
      // First, try your preferred gateway
      new StaticRoutingStrategy({ 
        gateway: 'https://my-preferred-gateway.com' 
      }),
      // If that fails, try fastest ping from top-tier gateways
      new FastestPingRoutingStrategy({
        timeoutMs: 1000,
        gatewaysProvider: new NetworkGatewaysProvider({
          ario,
          sortBy: 'operatorStake',
          limit: 5, // Only top 5 gateways
        }),
      }),
      // Final fallback: any random gateway from a larger pool
      new RandomRoutingStrategy({
        gatewaysProvider: new NetworkGatewaysProvider({
          ario,
          limit: 50, // Larger pool for maximum availability
        }),
      }),
    ],
  }),
});

Data Retrieval Strategies

Wayfinder supports multiple data retrieval strategies to fetch transaction data from AR.IO gateways. These strategies determine how data is requested and assembled from the underlying storage layer.

StrategyUse CaseRequirements
ContiguousDataRetrievalStrategyStandard data fetching via direct GETGateway has the data cached or able to fetch from trusted peers
ChunkDataRetrievalStrategyChunk-based data assemblyGateway supports /chunk/<offset>/data endpoint (r58) and has requested transactions indexed

ContiguousDataRetrievalStrategy

The default strategy that fetches data using a direct GET request to the gateway. This is the most straightforward approach and works for most use cases.

import { Wayfinder, ContiguousDataRetrievalStrategy } from '@ar.io/wayfinder-core';

const wayfinder = new Wayfinder({
  dataRetrievalStrategy: new ContiguousDataRetrievalStrategy(),
});

ChunkDataRetrievalStrategy

An advanced strategy that provides the easiest way to load chunks stored on Arweave nodes via the robust chunk API provided by AR.IO gateways. This approach is particularly useful for:

  • Direct chunk access: Efficiently retrieves data directly from the underlying chunk storage layer
  • Bundled data items: Seamlessly fetches data items from within ANS-104 bundles using calculated offsets
  • x402 payment compatibility: Both strategies support custom fetch clients for payment-enabled requests
  • Large file handling: More reliable for large transactions that may time out with direct requests

Requirements:

  • Gateway must support the /chunk/<offset>/data endpoint (added in r58)
  • Gateway must have the requested transaction indexed (offsets are needed to fetch directly from chunks)
import { Wayfinder, ChunkDataRetrievalStrategy } from '@ar.io/wayfinder-core';

const wayfinder = new Wayfinder({
  dataRetrievalStrategy: new ChunkDataRetrievalStrategy(),
});

How it works:

  1. Makes a HEAD request to get transaction metadata (root transaction ID, data offset, content length)
  2. Queries /tx/{root-tx-id}/offset to get the root transaction's absolute offset in the weave
  3. Calculates the absolute offset for the requested data item
  4. Fetches data in chunks using /chunk/<offset>/data and assembles the complete data stream
  5. Validates that chunks belong to the expected root transaction for security

Sequence Diagram:

sequenceDiagram
    participant Client
    participant Wayfinder
    participant Gateway as AR.IO Gateway
    participant Arweave as Arweave Nodes

    Client->>Wayfinder: request('ar://data-item-id')
    activate Wayfinder

    Wayfinder->>Gateway: HEAD /tx/{data-item-id}
    Note over Gateway: Lookup data item metadata<br/>from indexed bundles
    Gateway-->>Wayfinder: Headers:<br/>- x-root-tx-id (bundle ID)<br/>- x-data-offset<br/>- content-length

    Wayfinder->>Gateway: GET /tx/{root-tx-id}/offset
    Gateway->>Arweave: GET /tx/{root-tx-id}/offset
    Note over Arweave: Lookup transaction offset<br/>in the weave
    Arweave-->>Gateway: Root transaction offset
    Gateway-->>Wayfinder: Root transaction offset in weave

    Note over Wayfinder: Calculate absolute offset:<br/>absolute = root_offset + data_offset

    loop For each chunk needed
        Wayfinder->>Gateway: GET /chunk/{absolute-offset}/data
        
        Note over Gateway: Serve chunk data from<br/>indexed storage using<br/>root transaction ID
        
        Gateway-->>Wayfinder: Chunk data + validation headers<br/>(x-root-tx-id for security)
        
        Note over Wayfinder: Validate chunk belongs<br/>to expected root TX
        
        Wayfinder-->>Client: Stream chunk data
    end

    Wayfinder-->>Client: Complete response
    deactivate Wayfinder

Example with createWayfinderClient:

import { createWayfinderClient, ChunkDataRetrievalStrategy } from '@ar.io/wayfinder-core';

const wayfinder = createWayfinderClient({
  dataRetrievalStrategy: new ChunkDataRetrievalStrategy(),
});

// Fetch a data item from within an ANS-104 bundle
const response = await wayfinder.request('ar://data-item-id');

x402 Support

Both data retrieval strategies support custom fetch implementations, allowing you to use x402-enabled fetch clients for paid gateway requests.

import { createWayfinderClient, ChunkDataRetrievalStrategy } from '@ar.io/wayfinder-core';
import { createX402Fetch } from '@ar.io/wayfinder-x402-fetch';

const x402Fetch = createX402Fetch({ /* payment config */ });

const wayfinder = createWayfinderClient({
  fetch: x402Fetch,
  dataRetrievalStrategy: new ChunkDataRetrievalStrategy({
    fetch: x402Fetch,
  }),
});

Verification Strategies

Wayfinder includes verification mechanisms to ensure the integrity of retrieved data. Verification strategies offer different trade-offs between complexity, performance, and security.

VerifierComplexityPerformanceSecurityDescription
RemoteVerificationStrategyLowLowLowChecks the x-ar-io-verified header from the gateway that returned the data. If true, the data is considered verified and trusted.
HashVerificationStrategyLowHighLowComputes the SHA-256 hash of the returned data and comparing it to the hash of a trusted gateway (recommended for most users).
DataRootVerificationStrategyMediumMediumLowComputes the data root for the transaction (most useful for L1 transactions) and compares it to the data root provided by a trusted gateway.
SignatureVerificationStrategyMediumMediumMedium- ANS-104 Data Items: Fetches signature components (owner, signature type, tags, etc.) from trusted gateways using range requests, then verifies signatures against the data payload using deep hash calculations following the ANS-104 standard.
- L1 Transactions: Retrieves transaction metadata from gateway /tx/ endpoints, computes the data root from the provided data stream, and verifies the signature using Arweave's cryptographic verification.

RemoteVerificationStrategy

This strategy is used to verify data by checking the x-ar-io-verified header from the gateway that returned the data. If the header is set to true, the data is considered verified and trusted.

[!IMPORTANT] This strategy is only recommended for users fetching data from their own gateways and want to avoid the overhead of the other verification strategies.

import { Wayfinder, RemoteVerificationStrategy } from '@ar.io/wayfinder-core';

const wayfinder = new Wayfinder({
  verificationSettings: {
    // no trusted gateways are required for this strategy
    enabled: true,
    strategy: new RemoteVerificationStrategy(),
  },
});

HashVerificationStrategy

Verifies data integrity using SHA-256 hash comparison. This is the default verification strategy and is recommended for most users looking for a balance between security and performance.

import { Wayfinder, HashVerificationStrategy } from '@ar.io/wayfinder-core';

const wayfinder = new Wayfinder({
  verificationSettings: {
    enabled: true,
    strategy: new HashVerificationStrategy({
      trustedGateways: [new URL('https://turbo-gateway.com')],
    }),
  },
});

DataRootVerificationStrategy

Verifies data integrity using Arweave by computing the data root for the transaction. This is useful for L1 transactions and is recommended for users who want to ensure the integrity of their data.

import { Wayfinder, DataRootVerificationStrategy } from '@ar.io/wayfinder-core';

const wayfinder = new Wayfinder({
  verificationSettings: {
    enabled: true,
    strategy: new DataRootVerificationStrategy({
      trustedGateways: [new URL('https://turbo-gateway.com')],
    }),
  },
});

SignatureVerificationStrategy

Verifies signatures of Arweave transactions and data items. Headers are retrieved from trusted gateways for use during verification. For a transaction, its data root is computed while streaming its data and then utilized alongside its headers for verification. For data items, the ANS-104 deep hash method of signature verification is used.

import { Wayfinder, SignatureVerificationStrategy } from '@ar.io/wayfinder-core';

const wayfinder = new Wayfinder({
  verificationSettings: {
    enabled: true,
    strategy: new SignatureVerificationStrategy({
      trustedGateways: [new URL('https://turbo-gateway.com')],
    }),
  },
});

x402 Payments

Wayfinder can be configured to work with the x402 payment protocol for paid gateway services and higher rate limits. This allows you to seamlessly make requests that may require payment without having to manually handle payment flows.

[!IMPORTANT] To get started, install the @ar.io/wayfinder-x402-fetch package.

The @ar.io/wayfinder-x402-fetch package is a simple wrapper of the x402-fetch library, which creates a fetch implementation to automatically handles x402 payment flows. You can use this fetch implementation with Wayfinder to enable x402 payments for your requests.

import { createWayfinderClient, StaticRoutingStrategy } from '@ar.io/wayfinder-core';
import { createX402Fetch } from '@ar.io/wayfinder-x402-fetch';
import { privateKeyToAccount } from 'viem/accounts';

// Set up your wallet for x402 payments
const privateKey = process.env.X402_PRIVATE_KEY; // Your private key
const account = privateKeyToAccount(privateKey);

// Create x402-enabled fetch implementation
const x402Fetch = createX402Fetch({
  walletClient: account,
});

// Create Wayfinder client with x402 fetch to handle payments
const wayfinder = createWayfinderClient({
  fetch: x402Fetch,
  routingSettings: {
    // Configure to use x402-enabled gateways
    strategy: new StaticRoutingStrategy({
      gateway: 'https://paid-gateway.example.com',
    }),
  },
});

// Requests will now automatically handle x402 payments
const response = await wayfinder.request('ar://transaction-id');

How it works:

  1. When a gateway returns a 402 Payment Required status
  2. The x402 fetch automatically handles the payment flow
  3. The request is retried with payment credentials
  4. You get access to premium gateway services

Use cases:

  • Higher rate limits on data requests
  • Access to premium gateway features
  • Supporting gateway operators through payments

To learn more about x402 payments, visit the x402 documentation.

Events and Monitoring

Global Events

const wayfinder = createWayfinderClient({
  routingSettings: {
    events: {
      onRoutingStarted: (event) => console.log('Routing started:', event),
      onRoutingSucceeded: (event) => console.log('Gateway selected:', event),
    },
  },
  verificationSettings: {
    events: {
      onVerificationProgress: (event) => {
        const percentage = (event.processedBytes / event.totalBytes) * 100;
        console.log(`Verification: ${percentage.toFixed(2)}%`);
      },
      onVerificationSucceeded: (event) => console.log('Verified:', event.txId),
    },
  },
});

Request-Specific Events

const response = await wayfinder.request('ar://example', {
  verificationSettings: {
    events: {
      onVerificationProgress: (event) => {
        console.log(`This request: ${event.txId}`);
      },
    },
  },
});

Telemetry

Wayfinder can optionally emit OpenTelemetry spans for every request. By default, telemetry is disabled. You can control this behavior with the telemetry option.

import { createWayfinderClient } from '@ar.io/wayfinder-core';

const wayfinder = createWayfinderClient({
  // other settings...
  telemetrySettings: {
    enabled: true,
    sampleRate: 0.1, // 10% sampling
    exporterUrl: 'https://your-otel-exporter',
    clientName: 'my-app',
    clientVersion: '1.0.0',
  },
});

Resiliency

Wayfinder includes built-in resiliency features:

  • Gateway retry: If a gateway returns a 5xx error or a network failure occurs, Wayfinder automatically re-selects a different gateway and retries (up to 3 attempts). Client errors (4xx) are returned immediately without retry.
  • Fetch timeouts: All outbound requests include configurable timeouts — 10s for metadata (HEAD, peer list), 30s for data retrieval — to prevent indefinite hangs on slow or dead gateways.
  • Gateway health checks: PingRoutingStrategy verifies the selected gateway responds before routing to it, and retries with a different one if not.
  • Peer list retries: TrustedPeersGatewaysProvider retries when a gateway returns an empty peer list, then fails loudly rather than silently yielding no gateways — and the default provider falls back to the trusted gateway so that failure degrades routing instead of stopping it.
  • Registry pagination failures are fatal: NetworkGatewaysProvider retries a failed page and throws once retries are exhausted, rather than returning a partial registry. Because limit is applied after sorting, a partial read would return the wrong gateways rather than merely fewer.
  • Full-registry pagination: NetworkGatewaysProvider reads the whole on-chain registry before applying limit, so limit selects the top-ranked gateways rather than whichever ones happened to come back first. It pages at the SDK maximum, so this is a single request for a registry of the current size.

Request Flow

sequenceDiagram
    participant Client
    participant Wayfinder
    participant Gateways Provider
    participant Routing Strategy
    participant Selected Gateway
    participant Verification Strategy
    participant Trusted Gateways

    Client->>Wayfinder: request('ar://example')
    activate Wayfinder

    Wayfinder->>+Gateways Provider: getGateways()
    Gateways Provider-->>-Wayfinder: List of gateway URLs

    Wayfinder->>+Routing Strategy: selectGateway()
    Routing Strategy-->>-Wayfinder: Selected gateway

    Wayfinder->>+Selected Gateway: HTTP request
    Selected Gateway-->>-Wayfinder: Response data

    opt Verification enabled
        Wayfinder->>+Verification Strategy: verifyData()
        Verification Strategy->>Trusted Gateways: Get verification data
        Trusted Gateways-->>Verification Strategy: Verification headers
        Verification Strategy-->>-Wayfinder: Verification result
    end

    Wayfinder-->>Client: Response or error
    deactivate Wayfinder

版本与发布记录

@ar.io/wayfinder-core 共发布 85 个版本,首次发布于 2025/06/13;过去 12 个月发布了 13 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.0.2latest2026/08/142 个月前
2.0.1alpha2026/06/224 个月前
2.0.02026/06/204 个月前
1.9.22026/03/058 个月前
1.9.12026/02/118 个月前
1.9.0-alpha.12026/02/088 个月前

其他发布通道:beta → 0.0.2-beta.0,alpha → 2.0.1。

关于 @ar.io/wayfinder-core 的常见问题

@ar.io/wayfinder-core 是什么?

WayFinder core library for intelligently routing to optimal AR.IO gateways

如何安装 @ar.io/wayfinder-core?

在项目目录运行 npm install @ar.io/wayfinder-core,或使用 pnpm add / yarn add / bun add。

@ar.io/wayfinder-core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ar.io/wayfinder-core 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ar.io/wayfinder-core 可以商用吗?

@ar.io/wayfinder-core 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@ar.io/wayfinder-core 的下载量有多少?

根据 npm 官方下载统计,@ar.io/wayfinder-core 在 2026/10/07 – 2026/11/05 这 30 天内被下载 3,632 次,日均约 121 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ar.io/wayfinder-core 还在维护吗?

最新版本 2.0.2 发布于 2026/08/14(2 个月前);至今共发布 85 个版本,其中过去 12 个月发布了 13 个;首次发布于 2025/06/13。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。