Skip to content

feat(packages/ensnode-react): connection manager #893

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: resolution-client
Choose a base branch
from

Conversation

notrab
Copy link
Member

@notrab notrab commented Jul 30, 2025

This PR adds the connection management we discussed that can be added to ensnode-react (#886) so we can replace what's in ENSAdmin with this library.

function ConnectionSelector() {
  const {
    connections,
    currentUrl,
    setCurrentUrl,
    addConnection,
    removeConnection,
    isLoading,
  } = useConnections({
    defaultUrls: [
      "https://api.mainnet.ensnode.io",
      "https://api.testnet.ensnode.io",
    ],
  });

  const [newUrl, setNewUrl] = useState("");
  const [showAddForm, setShowAddForm] = useState(false);

  const handleAdd = async () => {
    if (!newUrl.trim()) return;

    try {
      await addConnection.mutateAsync({ url: newUrl.trim() });
      setNewUrl("");
      setShowAddForm(false);
    } catch (error) {
      console.error("Failed to add connection:", error);
    }
  };

  const handleRemove = async (url: string) => {
    try {
      await removeConnection.mutateAsync({ url });
    } catch (error) {
      console.error("Failed to remove connection:", error);
    }
  };

  if (isLoading) {
    return <div>Loading connections...</div>;
  }

  return (
    <div className="connection-selector">
      <h3>ENSNode Connections</h3>

      {/* Current Connection Display */}
      <div className="current-connection">
        <strong>Current:</strong> {currentUrl}
      </div>

      {/* Connection List */}
      <div className="connections-list">
        {connections.map(({ url, isDefault }) => (
          <div
            key={url}
            className={`connection-item ${url === currentUrl ? "active" : ""}`}
          >
            <button
              onClick={() => setCurrentUrl(url)}
              className="connection-button"
              disabled={url === currentUrl}
            >
              {url}
              {isDefault && <span className="badge">Default</span>}
            </button>

            {!isDefault && url !== currentUrl && (
              <button
                onClick={() => handleRemove(url)}
                disabled={removeConnection.isPending}
                className="remove-button"
              >
                {removeConnection.isPending ? "Removing..." : "Remove"}
              </button>
            )}
          </div>
        ))}
      </div>

      {/* Add Connection Form */}
      {showAddForm ? (
        <div className="add-connection-form">
          <input
            type="url"
            value={newUrl}
            onChange={(e) => setNewUrl(e.target.value)}
            placeholder="https://your-ensnode-endpoint.com"
            className="url-input"
          />
          <div className="form-actions">
            <button
              onClick={handleAdd}
              disabled={addConnection.isPending || !newUrl.trim()}
            >
              {addConnection.isPending ? "Adding..." : "Add"}
            </button>
            <button onClick={() => setShowAddForm(false)}>Cancel</button>
          </div>
          {addConnection.isError && (
            <div className="error">
              Error:{" "}
              {addConnection.error?.message || "Failed to add connection"}
            </div>
          )}
        </div>
      ) : (
        <button onClick={() => setShowAddForm(true)} className="add-button">
          Add Connection
        </button>
      )}
    </div>
  );
}

// Example: Data Display Component that uses current connection
function ENSDataDisplay() {
  const { url, config } = useCurrentConnection();
  const [address, setAddress] = useState(
    "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
  );
  const [name, setName] = useState("vitalik.eth");

  // These hooks will automatically use the current connection
  const addressResult = useResolveAddress({
    address,
    config, // Use current connection's config
  });

  const nameResult = useResolveName({
    name,
    selection: {
      name: true,
      addresses: [60], // ETH
      texts: ["avatar", "com.twitter"],
    },
    config, // Use current connection's config
  });

  return (
    <div className="ens-data-display">
      <h3>ENS Resolution Demo</h3>
      <div className="current-endpoint">
        <strong>Using endpoint:</strong> {url}
      </div>

      {/* Address to Name Resolution */}
      <div className="resolution-section">
        <h4>Address  Name</h4>
        <input
          type="text"
          value={address}
          onChange={(e) => setAddress(e.target.value)}
          placeholder="0x..."
        />
        <div className="result">
          {addressResult.isLoading && "Loading..."}
          {addressResult.error && `Error: ${addressResult.error.message}`}
          {addressResult.data && (
            <div>
              <strong>Primary Name:</strong>{" "}
              {addressResult.data.records.name || "None"}
            </div>
          )}
        </div>
      </div>

      {/* Name to Records Resolution */}
      <div className="resolution-section">
        <h4>Name  Records</h4>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="example.eth"
        />
        <div className="result">
          {nameResult.isLoading && "Loading..."}
          {nameResult.error && `Error: ${nameResult.error.message}`}
          {nameResult.data && (
            <div>
              <div>
                <strong>Name:</strong> {nameResult.data.records.name}
              </div>
              {nameResult.data.records.addresses?.["60"] && (
                <div>
                  <strong>ETH Address:</strong>{" "}
                  {nameResult.data.records.addresses["60"]}
                </div>
              )}
              {nameResult.data.records.texts?.avatar && (
                <div>
                  <strong>Avatar:</strong>{" "}
                  {nameResult.data.records.texts.avatar}
                </div>
              )}
              {nameResult.data.records.texts?.["com.twitter"] && (
                <div>
                  <strong>Twitter:</strong>{" "}
                  {nameResult.data.records.texts["com.twitter"]}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// Example: Multi-endpoint comparison
function MultiEndpointComparison() {
  const { createConfigWithUrl } = useCurrentConnection();
  const address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";

  // Create configs for different endpoints
  const mainnetConfig = createConfigWithUrl("https://api.mainnet.ensnode.io");
  const testnetConfig = createConfigWithUrl("https://api.testnet.ensnode.io");

  // Resolve on both networks
  const mainnetResult = useResolveAddress({ address, config: mainnetConfig });
  const testnetResult = useResolveAddress({ address, config: testnetConfig });

  return (
    <div className="multi-endpoint-comparison">
      <h3>Multi-Endpoint Comparison</h3>
      <div className="address">Address: {address}</div>

      <div className="comparison-grid">
        <div className="endpoint-result">
          <h4>Mainnet</h4>
          {mainnetResult.isLoading && "Loading..."}
          {mainnetResult.error && `Error: ${mainnetResult.error.message}`}
          {mainnetResult.data && (
            <div>Name: {mainnetResult.data.records.name || "None"}</div>
          )}
        </div>

        <div className="endpoint-result">
          <h4>Testnet</h4>
          {testnetResult.isLoading && "Loading..."}
          {testnetResult.error && `Error: ${testnetResult.error.message}`}
          {testnetResult.data && (
            <div>Name: {testnetResult.data.records.name || "None"}</div>
          )}
        </div>
      </div>
    </div>
  );
}

// Main App Component
function ConnectionManagementExample() {
  const config = createConfig({
    url: "https://api.mainnet.ensnode.io",
    debug: true,
  });

  return (
    <ENSNodeProvider config={config}>
      <div className="app">
        <h1>ENSNode React Connection Management</h1>

        <div className="layout">
          <div className="sidebar">
            <ConnectionSelector />
          </div>

          <div className="main-content">
            <ENSDataDisplay />
            <hr />
            <MultiEndpointComparison />
          </div>
        </div>

@notrab notrab requested a review from tk-o July 30, 2025 18:01
@notrab notrab requested a review from a team as a code owner July 30, 2025 18:01
Copy link

changeset-bot bot commented Jul 30, 2025

⚠️ No Changeset found

Latest commit: 79d74a3

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Jul 30, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
admin.ensnode.io ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 3, 2025 7:09pm
ensnode.io ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 3, 2025 7:09pm
ensrainbow.io ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 3, 2025 7:09pm

const addConnection = useMutation({
mutationFn: async ({ url }: AddConnectionVariables) => {
// Validate the URL
const validationResult = await defaultValidator.validate(url);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we took the validator object instance from the useConnections hook params. This way, the client app, such as ENSAdmin, could precisely manage the ENSNode connection validation strategy.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tk-o I'll have a look at modifying this so you can pass in a validator.

Copy link
Member

@lightwalker-eth lightwalker-eth left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@notrab Appreciate this. Reviewed and shared priority feedback.

* ENSIndexer Public Configuration
* Configuration data fetched from an ENSNode endpoint
*/
export interface ENSIndexerPublicConfig {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eeek! @tk-o @notrab Please several key issues here:

This type shouldn't be defined at a React-level (inside the ensnode-react package). It should be defined inside ensnode-sdk.

Appreciate your advice.

Also, @tk-o what's the status on getting everything ready with this interface and related validation logic?

*/
export interface ENSNodeValidator {
/**
* Validates an ENSNode endpoint URL and fetches its public configuration
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we "validating an ENSNode endpoint URL"?

What matters is:

  1. Getting the public config of the ENSIndexer instance.
  2. Deserializing the returned public config (into a "rich" / non-JSON object) and validating all of its invariants using Zod.

I don't like the idea that this is called a "Validator" or has a "validate" function.

The responsibility for serializing / deserializing (which includes validating!) belongs in ensnode-sdk and not at the react level.

/**
* Variables for adding a new connection
*/
export interface AddConnectionVariables {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're mixing up too many ideas and responsibilities here.

There should be just a single connection. The idea of managing a list of multiple possible connections doesn't belong anywhere in ensnode-react. It belongs only in an app like ensadmin.

/**
* Parameters for the useConnections hook
*/
export interface UseConnectionsParameters {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please see my other comment above.

We're putting ideas in the wrong place. It seems many of the ideas here belong only in ENSAdmin and not in ensnode-react.

@@ -0,0 +1,120 @@
import type { ENSIndexerPublicConfig, ENSNodeValidator } from "../types";

/**
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're mixing up ideas and putting them in the wrong places.

  1. All API calls to ENSNode need to be in ensnode-sdk, not here in ensnode-react.
  2. All validation / serialization / deserialization of an ens indexer public config need to be in ensnode-sdk.

It's critical to get these details right.

```

## Connection Management Modes
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Virtually no one (other than ourselves in ENSAdmin) will build "ENSNode connection picker" UX. We should focus on making it easy for the 99.999% who will want just a single connection for their app.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants