### Install wagmi, viem, and react-query Source: https://docs.ens.domains/web/quickstart Installs the necessary packages for integrating wagmi, viem, and react-query into your project. These libraries are essential for interacting with Ethereum and ENS. ```bash npm install wagmi viem @tanstack/react-query ``` -------------------------------- ### Basic ENS Resolver Smart Contract Example (Solidity) Source: https://docs.ens.domains/resolvers/quickstart A simple example of an ENS resolver smart contract written in Solidity. This contract demonstrates the basic structure of a resolver, including the `addr` function to return an address and `supportsInterface` to indicate supported functionalities. It always returns the same address regardless of the input node. ```Solidity contract MyResolver { function addr(bytes32 node) external pure returns (address) { return 0x225f137127d9067788314bc7fcc1f36746a3c3B5; } function supportsInterface( bytes4 interfaceID ) external pure returns (bool) { return interfaceID == this.addr.selector || interfaceID == this.supportsInterface.selector; } } ``` -------------------------------- ### Namehash Algorithm Example (swarm) Source: https://docs.ens.domains/ensip/1 This example illustrates the step-by-step application of the namehash algorithm for the name 'mysite.swarm'. It shows how the node is iteratively updated by hashing the previous node with the hash of the current label. ```python node = '\0' * 32 node = sha3(node + sha3('swarm')) node = sha3(node + sha3('mysite')) ``` -------------------------------- ### Address Encoder Examples (JavaScript) Source: https://docs.ens.domains/ensip/11 Demonstrates the usage of the address-encoder library for converting between EVM chain IDs and coin types, and accessing format information. These examples showcase practical application of the ENSIP-11 standard in JavaScript. ```javascript const encoder = require('@ensdomains/address-encoder') > encoder.convertEVMChainIdToCoinType(61) 2147483709 > encoder.convertCoinTypeToEVMChainId(2147483709) 61 ``` ```javascript > encoder.formatsByName['XDAI'] { coinType: 2147483748, decoder: [Function (anonymous)], encoder: [Function (anonymous)], name: 'XDAI' } > encoder.formatsByCoinType[2147483748] { coinType: 2147483748, decoder: [Function (anonymous)], encoder: [Function (anonymous)], name: 'XDAI' } ``` -------------------------------- ### Start ENS Auctions and Submit Bid Source: https://docs.ens.domains/ensip/2 A convenience function that combines starting multiple ENS name auctions and submitting a new bid in a single transaction. Useful for streamlining the auction participation process. ```Solidity function startAuctionsAndBid(bytes32[] hashes, bytes32 sealedBid) ``` -------------------------------- ### Add Context7 MCP to Claude CodeCursor Source: https://docs.ens.domains/building-with-ai Installs the Context7 Model Context Protocol (MCP) server for Claude CodeCursor, enabling AI coding assistants to access up-to-date ENS documentation. This command uses npx to execute the installation script. ```bash claude mcp add context7 -- npx -y @upstash/context7-mcp ``` -------------------------------- ### Basic On-chain ENS Resolver Example (Solidity) Source: https://docs.ens.domains/resolvers/writing A simple Solidity contract demonstrating an on-chain ENS resolver. It uses a mapping to store addresses associated with ENS nodes and implements the `supportsInterface` method for EIP-165 compatibility. ```Solidity contract OnchainResolver { mapping(bytes32 node => address addr) public addr; function setAddr(bytes32 node, address _addr) external { addr[node] = _addr; } function supportsInterface( bytes4 interfaceID ) external pure returns (bool) { return interfaceID == OnchainResolver.supportsInterface.selector || // function addr(bytes32 node) external view returns (address) interfaceID == 0x3b3b57de; } } ``` -------------------------------- ### Interpreting Decoded Multicall Results in Solidity Source: https://docs.ens.domains/ensip/23 Provides examples of how to decode individual results from a multicall response in Solidity, including successfully decoding an address and a string, and identifying an `UnsupportedResolverProfile` error. ```solidity address ethAddress = abi.decode(results[0], (address)); string avatar = abi.decode(results[1], (string)); // results[2] == abi.encodeWithSelector(UnsupportedResolverProfile.selector, bytes4(0x00000000)); ``` -------------------------------- ### JavaScript Example for Setting and Retrieving Arbitrary ENS Data Source: https://docs.ens.domains/ensip/24 Illustrates how to interact with an ENS resolver contract to set and retrieve arbitrary data using pseudo-JavaScript. It shows an asynchronous transaction for setting data and then retrieving it using the `data` function. ```javascript // Pseudo javascript example // Store arbitrary data const tx = await resolver.setData(node, "agent-context", "0x0001ABCD..."); await tx.wait(); // Retrieve arbitrary data const result = await resolver.data(node, "agent-context"); ``` -------------------------------- ### Get ENS Primary Name using Wagmi (L1) Source: https://docs.ens.domains/web/reverse This Wagmi hook retrieves the primary ENS name associated with an EVM address on Ethereum Mainnet (L1). It uses the `useEnsName` hook and specifies the L1 chain ID. Resolution always starts from L1. ```javascript // https://wagmi.sh/react/hooks/useEnsName import { useEnsName } from 'wagmi' import { mainnet } from 'wagmi/chains' export const Name = () => { const { data: name } = useEnsName({ address: '0xb8c2C29ee19D8307cb7255e1Cd9CbDE883A267d5', chainId: mainnet.id, // resolution always starts from L1 }) return
Name: {name}
} ``` -------------------------------- ### Display User ENS Profile with wagmi hooks Source: https://docs.ens.domains/web/quickstart Demonstrates how to create a user profile component that displays the user's ENS name and avatar. It utilizes the `useAccount`, `useEnsName`, and `useEnsAvatar` hooks from wagmi. ENS resolution is performed on L1 by specifying `chainId: 1`. ```javascript import { useAccount, useEnsAvatar, useEnsName } from 'wagmi' export const EnsProfile = () => { const { address } = useAccount() const { data: name } = useEnsName({ address, chainId: 1 }) const { data: avatar } = useEnsAvatar({ name, chainId: 1 }) return (
{name} {address}
) } ``` -------------------------------- ### Encode String to Bytes (Solidity) Source: https://docs.ens.domains/ensip/13 This Solidity code snippet demonstrates how to encode a string into bytes, including its length and the '0x' prefix. It handles writing the string backwards and managing memory pointers efficiently. The function returns a pointer to the encoded string. ```solidity function string(uint256 ptr) internal pure returns (bytes memory) { // 32 bytes to store string length; address is 42 bytes long mstore(0x40, add(ptr, 96)) // Store (string length, '0', 'x') (42, 48, 120) // Single write by offsetting across 32 byte boundary ptr := add(ptr, 2) mstore(ptr, 0x2a3078) // Write string backwards for { // end is at 'x', ptr is at lsb char let end := add(ptr, 31) ptr := add(ptr, 71) } gt(ptr, end) { ptr := sub(ptr, 1) addr := shr(4, addr) } { let v := and(addr, 0xf) // if > 9, use ascii 'a-f' (no conditional required) v := add(v, mul(gt(v, 9), 39)) // Add ascii for '0' v := add(v, 48) mstore8(ptr, v) } // return ptr to point to length (32 + 2 for '0x' - 1) ptr := sub(ptr, 33) } return string(ptr); } } ``` -------------------------------- ### Get ENS Resolver Address (Solidity) Source: https://docs.ens.domains/resolution This Solidity code snippet demonstrates how to query the ENS Registry to get the address of the resolver contract responsible for a given name node. It utilizes the `resolver` function of the ENS contract. ```solidity ENS.resolver(bytes32 node) view returns (address) ``` -------------------------------- ### SHA3 Hashing for ENS Name Registration Source: https://docs.ens.domains/ensip/2 Demonstrates how to correctly hash a subdomain label for registration with the Initial Hash Registrar. The hash submitted should be the SHA3 of the label itself, not the full namehash. ```solidity pragma solidity ^0.4.24; contract Sha3Example { function getLabelHash(string label) public pure returns (bytes32) { return sha3(label); } // Example usage for registering 'abcdefg.eth' // The hash to submit would be sha3('abcdefg') } ``` -------------------------------- ### Configure L2 and Mainnet Clients (Viem) Source: https://docs.ens.domains/web/ensv2-readiness This Viem code snippet shows how to configure separate clients for an L2 chain (Base) and Ethereum Mainnet. It demonstrates fetching an address for an ENS name on the L2 chain by using the Mainnet client for ENS resolution. ```javascript import { createPublicClient, http, toCoinType } from 'viem' import { base, mainnet } from 'viem/chains' // Client for Base transactions const baseClient = createPublicClient({ chain: base, transport: http(), }) // Client for ENS resolution on Mainnet const mainnetClient = createPublicClient({ chain: mainnet, transport: http(), }) // Get the Base address for this ENS name const baseAddress = await mainnetClient.getEnsAddress({ name: 'test.ses.eth', coinType: toCoinType(base.id), }) ``` -------------------------------- ### Public Registration Function Example Source: https://docs.ens.domains/wrapper/creating-subname-registrar An example of a public-facing registration function in a smart contract. This function typically takes the parent node and subname label as input and internally calls `setSubnodeRecord` with default or derived parameters for owner, resolver, ttl, fuses, and expiry. ```Solidity register(bytes32 parentNode, string calldata label) // Under the hood, your contract will call setSubnodeRecord and fill in the rest of the parameters on behalf of the user: // * owner: Typically the caller account, msg.sender // * resolver: Typically the default public resolver, resolver.eth // * ttl: 0 // * fuses: Up to you and your goals. See the Use Cases section for a discussion on this. Typically 65536 for an enamcipated rental subname, or 327680 for an emancipated "forever" name. // * expiry: Up to you and your goals. If you are renting subnames for a particular length of time, this expiry would reflect that. If you are allowing registration of "forever" names, then you can just set the expiry equal to the parent name's current expiry. ``` -------------------------------- ### Smart Multicall Encoding in Solidity Source: https://docs.ens.domains/ensip/23 Demonstrates how to prepare multiple calls for different ENS resolver functions (like 'addr' and 'text') and package them into a single transaction using Solidity's `abi.encodeCall` and the `IMulticallable` interface. ```solidity bytes[] memory calls = new bytes[](3); calls[0] = abi.encodeCall(IAddrResolver.addr, (node)); calls[1] = abi.encodeCall(ITextResolver.text, (node, "avatar")); calls[2] = hex"00000000"; // invalid selector ``` -------------------------------- ### Get Default Resolver Source: https://docs.ens.domains/registry/reverse Retrieves the address of the default resolver contract used by the Reverse Registrar. ```APIDOC ## GET /defaultResolver ### Description Returns the address of the resolver contract that the `ReverseRegistrar` uses for `setName` operations. ### Method GET ### Endpoint /defaultResolver ### Response #### Success Response (200) - **resolverAddress** (address) - The address of the default resolver contract. ### Response Example ```json { "resolverAddress": "0xabc..." } ``` ``` -------------------------------- ### ENS Registry: Get Owner Address Source: https://docs.ens.domains/ensip/1 Retrieves the owner (registrar) address for a given ENS node. This is a constant function and does not modify the contract state. ```solidity function owner(bytes32 node) constant returns (address); ``` -------------------------------- ### ENS Registry: Get Resolver Address Source: https://docs.ens.domains/ensip/1 Retrieves the resolver contract address associated with a given ENS node. This function is constant and does not alter contract state. ```solidity function resolver(bytes32 node) constant returns (address); ``` -------------------------------- ### Set Subnode Record using NameWrapper Contract Source: https://docs.ens.domains/wrapper/usecases This example shows how to use the `setSubnodeRecord` method from the NameWrapper contract to set ownership and records for a subname. This method is useful for more complex configurations. ```Solidity // Assuming 'nameWrapper' is an instance of INameWrapper // Assuming 'subnodeOwner' is the address to assign ownership to // Assuming 'subnode' is the keccak256 hash of the subname // Assuming 'resolver' is the address of the resolver // Assuming 'owner' is the address of the owner of the parent name await nameWrapper.setSubnodeRecord(parentNameHash, subnode, subnodeOwner, resolver, owner, fuses, expiry); ``` -------------------------------- ### Implement ENS Registrar with Free Registration (Solidity) Source: https://docs.ens.domains/ensip/1 This Solidity contract implements a registrar for ENS (Ethereum Name Service) domains. It allows users to register a subdomain if it's not already owned or if the current owner is the message sender. The registration is free if the subdomain has not been previously claimed. ```Solidity contract FIFSRegistrar { ENS ens; bytes32 rootNode; function FIFSRegistrar(address ensAddr, bytes32 node) { ens = ENS(ensAddr); rootNode = node; } function register(bytes32 subnode, address owner) { var node = sha3(rootNode, subnode); var currentOwner = ens.owner(node); if(currentOwner != 0 && currentOwner != msg.sender) throw; ens.setSubnodeOwner(rootNode, subnode, owner); } } ``` -------------------------------- ### Set Subnode Owner using NameWrapper Contract Source: https://docs.ens.domains/wrapper/usecases This example demonstrates how to use the `setSubnodeOwner` method from the NameWrapper contract to assign ownership of a subname. This is typically used for bulk distribution of subnames. ```Solidity // Assuming 'nameWrapper' is an instance of INameWrapper // Assuming 'subnodeOwner' is the address to assign ownership to // Assuming 'subnode' is the keccak256 hash of the subname (e.g., keccak256(abi.encodePacked("subname", parentNameHash))) await nameWrapper.setSubnodeOwner(parentNameHash, subnode, subnodeOwner, fuses, expiry); ``` -------------------------------- ### Initiate Multiple ENS Name Auctions Source: https://docs.ens.domains/ensip/2 Starts auctions for multiple ENS names provided as an array of hashes. This is a strategy to increase the cost for attackers attempting to bid on many new auctions. Dummy auctions are automatically closed after a week if not bid upon. ```Solidity function startAuctions(bytes32[] _hashes); ``` -------------------------------- ### Get Default ENS Resolver Address Source: https://docs.ens.domains/registry/reverse This Solidity function returns the address of the default resolver contract used by the `ReverseRegistrar` for setting names. It is a view function, meaning it does not modify the blockchain state. ```solidity function defaultResolver() public view returns (address); ``` -------------------------------- ### Lookup ENS Address Records with wagmi Source: https://docs.ens.domains/web/quickstart Fetches and displays address records for various coin types associated with an ENS name, along with the user's avatar. This component utilizes `useEnsAvatar` and `useEnsAddresses` from wagmi. It requires a `Table` component and a custom `useEnsAddresses` hook. ```javascript import { useEnsAvatar } from 'wagmi' import { UseEnsAddressesProps, useEnsAddresses } from '../hooks/useEnsAddresses' import { Table } from './ui/Table' export const AddressRecords = ({ name, coinTypes }: UseEnsAddressesProps) => { const { data: avatar } = useEnsAvatar({ name, chainId: 1 }) const { data: addresses } = useEnsAddresses({ name, coinTypes }) return ( <>
{name}
[coinType, address]) || [] } /> ) } ``` -------------------------------- ### Accessing DNSRegistrar Properties and Functions Source: https://docs.ens.domains/registry/dns These examples show how to access properties like `suffixes` and `oracle` from the DNSRegistrar contract, and how to call its public functions for claiming DNS names. ```solidity // Get the list of suffixes DNSRegistrar.suffixes // Get Oracle DNSRegistrar.oracle ``` ```solidity DNSRegistrar.claim(bytes name, bytes proof) DNSRegistrar.proveAndClaim(bytes name, tuple[] input, bytes proof) DNSRegistrar.proveAndClaimWithResolver(bytes name, tuple[] input, bytes proof, address resolver, address addr) ``` -------------------------------- ### Register Subdomain Parameters - Solidity Source: https://docs.ens.domains/ensip/20 Defines the parameters required for registering a subdomain, including price, availability, token address, commit time, and extra data. This function supports flexible offchain registration. ```solidity struct RegisterParams { uint256 price; bool available; address token; uint256 commitTime; bytes extraData; } function registerParams( bytes memory name, uint256 duration ) external view returns (RegisterParams memory); ``` -------------------------------- ### Executing and Decoding Smart Multicalls in Solidity Source: https://docs.ens.domains/ensip/23 Illustrates how to encode a multicall request, execute it using the `UR.resolve` function, and then decode the array of results. It also shows how to interpret individual results, including potential errors. ```solidity bytes memory data = abi.encodeCall(IMulticallable.multicall, (calls)); (bytes memory result, address resolver) = UR.resolve(name, data); // note: could revert OffchainLookup bytes[] memory results = abi.decode(result, (bytes)); ```