Ethereum Name Service 백서

Ethereum Name Service

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 24쪽

ion path**: the [readiness page](/web/ensv2-readiness#universal-resolver) provides test names (like `ur.integration-tests.eth`) that verify your app reaches the correct Universal Resolver and handles CCIP-Read. * **End to end on Sepolia**: register a test name on the Sepolia deployment, set records with the snippets above, and confirm the resolution calls return them. The protocol contract addresses are in the [Deployments table](/learn/deployments#sepolia-ensv2). * **DNS names**: make sure your name detection does not assume `.eth`; see [name detection](/web/ensv2-readiness#dns-names-and-name-detection). #### Getting Test Funds Registering a name on the Sepolia deployment costs two things: Sepolia ETH for gas (any public faucet works) and the registration fee, which the [ETH Registrar](/ensv2/eth-registrar) collects in an ERC20 token. On Sepolia that token is `MockUSDC` (address in the [Deployments table](/learn/deployments#sepolia-ensv2)), and it is free: its `mint` function has no access control, so anyone can mint themselves a balance. ```typescript import { parseAbi } from 'viem' // MockUSDC, from the Deployments table await wallet.writeContract({ address: mockUsdcAddress, abi: parseAbi(['function mint(address to, uint256 amount)']), functionName: 'mint', args: [account, 100_000_000n], // 100 USDC (6 decimals) }) ``` Before registering, `approve` the ETH Registrar to spend the minted balance; the registration flow itself is described on the [ETH Registrar](/ensv2/eth-registrar) page. ### Troubleshooting | Symptom | Likely cause | | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Names that resolve in other apps return `null` in yours | Library version predates ENSv2 support; check the [readiness page](/web/ensv2-readiness) minimums | | A name your user just registered resolves to `null` | No address record set yet; registration and records are separate steps | | Record writes revert with `EACUnauthorizedAccountRoles` | The connected account holds no roles on that resolver, most commonly a subname owner writing to the parent's resolver (see [Who Can Write](#who-can-write)) | | Record writes succeed but reads return old values | The write went to a resolver the name no longer points at; look up the resolver again instead of caching it | | Resolution works in scripts but fails in the app | The app's environment blocks the HTTP requests CCIP-Read needs; see [CCIP Read](/web/ensv2-readiness#offchain-and-l2-resolution-with-ccip-read) | ### Next Steps * Track library support and test names on the [ENSv2 readiness page](/web/ensv2-readiness) * Understand the resolution machinery in [Universal Resolver V2](/ensv2/universal-resolver-v2) * Go deeper on record permissions and delegation in [Permissioned Resolver](/ensv2/permissioned-resolver) * Building a subname product on top of your integration? Continue with the [contract developers guide](/ensv2/tutorial-contract-developers) import { FrenCallout } from '../../components/ensv2/FrenCallout' ## For Contract Developers This guide walks through building a simplified subname registrar: a minimal smart contract that lets users register and renew subnames under a parent name you own. It demonstrates the core pattern that all ENSv2 registrars follow, including the production [ETH Registrar](/ensv2/eth-registrar). The registrar built here is based on the ETH Registrar, but heavily simplified: commit-reveal, oracle-based pricing, grace periods, and referral tracking are stripped away, leaving the essentials of availability checks, flat-fee ERC20 payments, registration, and renewal. By the end you will know how a registrar interfaces with an ENSv2 registry at the contract level, how the two are connected and authorized, how to interact with them through a client library like viem, and how to index the events they emit. <FrenCallout fren="bittu" variant="tip" title="Prerequisites"> You should understand the basics of the [Permissioned Registry](/ensv2/permissioned-registry) (where names are stored and permissions are enforced), [Enhanced Access Control](/ensv2/enhanced-access-control) (the role-based permission system), and the [Verifiable Factory](/ensv2/verifiable-factory) (how per-name registries are deployed). </FrenCallout> ### Architecture In ENSv2, registries and registrars have distinct responsibilities. The **registry** (a [Permissioned Registry](/ensv2/permissioned-registry) or [UserRegistry](/ensv2/registry-template#userregistry)) stores names, manages ERC1155 tokens, and enforces permissions. Since each registry is its own contract, the subnames it manages form their own NFT collection, distinct from `.eth` names and from every other subname project. The **registrar** is a separate contract that sits in front of the registry and handles business logic: pricing, payment collection, availability checks, and any registration constraints. The registrar calls `registry.register()` to create names and `registry.renew()` to extend them. For this to work, the registry owner must grant the registrar two roles on `ROOT_RESOURCE` (the registry-wide resource, whose roles apply to every name in the registry; see [Enhanced Access Control](/ensv2/enhanced-access-control)): | Role | Value | Purpose | | ---------------- | --------- | ----------------------------------------------- | | `ROLE_REGISTRAR` | `1 << 0` | Authorizes calling `register()` on the registry | | `ROLE_RENEW` | `1 << 16` | Authorizes calling `renew()` on the registry | The registrar itself does not store names or manage tokens. It is a thin gatekeeper that validates inputs, collects payment, and delegates to the registry. ```mermaid sequenceDiagram participant User participant Registrar as SimpleSubnameRegistrar participant Token as ERC20 Token participant Registry as UserRegistry User->>Registrar: register("sub", owner, resolver, duration) Registrar->>Registrar: validate availability and duration Registrar->>Token: safeTransferFrom(user, beneficiary, price) Registrar->>Registry: register("sub", owner, ..., expiry) Registry->>Registry: mint ERC1155 token to owner Registry-->>Registrar: tokenId Registrar-->>User: tokenId ``` ### Project Setup This tutorial uses [Foundry](https://getfoundry.sh/). Install the ENSv2 contracts directly from their GitHub repository: ```bash forge init simple-subname-registrar && cd simple-subname-registrar forge install ensdomains/contracts-v2 ``` The repository brings its own OpenZeppelin checkout along as a git submodule, so no separate OpenZeppelin install is needed. Add both remappings to `foundry.toml` so the import paths used below resolve: ```toml remappings = [ "@ensdomains/contracts-v2/=lib/contracts-v2/contracts/src/", "@openzeppelin/contracts/=lib/contracts-v2/contracts/lib/openzeppelin-contracts/contracts/", ] ``` You will build the contract in `src/SimpleSubnameRegistrar.sol`. ### Building the Contract #### Imports and Role Bitmap Start the file with the pragma and imports: ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IPermissionedRegistry} from "@ensdomains/contracts-v2/registry/interfaces/IPermissionedRegistry.sol"; import {IRegistry} from "@ensdomains/contracts-v2/registry/interfaces/IRegistry.sol"; import {RegistryRolesLib} from "@ensdomains/contracts-v2/registry/libraries/RegistryRolesLib.sol"; ``` Next, define `REGISTRATION_ROLE_BITMAP` as a file-level constant, between the imports and the contract declaration. It determines what permissions each name owner receives at registration. We use the same bitmap as the [ETH Registrar](/ensv2/eth-registrar#roles-granted-at-registration): ```solidity uint256 constant REGISTRATION_ROLE_BITMAP = RegistryRolesLib.ROLE_SET_SUBREGISTRY | RegistryRolesLib.ROLE_SET_SUBREGISTRY_ADMIN | RegistryRolesLib.ROLE_SET_RESOLVER | RegistryRolesLib.ROLE_SET_RESOLVER_ADMIN | RegistryRolesLib.ROLE_CAN_TRANSFER_ADMIN; ``` This grants name owners the ability to change their resolver, set up a child registry for sub-subnames, and transfer their name. The `_ADMIN` variants of the two setter roles let owners delegate those permissions to other accounts. `ROLE_CAN_TRANSFER_ADMIN` works differently: it is the transfer permission itself, an admin-only role with no non-admin counterpart. See [EAC roles](/ensv2/enhanced-access-control) for full details. <FrenCallout fren="earl" variant="note" title="Definition – Role Bitmap"> A role bitmap is a 256-bit integer where each role occupies one 4-bit slot (nybble); see [Bitmap Layout](/ensv2/enhanced-access-control#bitmap-layout). When `register()` is called on the registry, the bitmap determines which [EAC](/ensv2/enhanced-access-control) roles the new owner receives on their name's resource. Different registrars can use different bitmaps to create different trust models. </FrenCallout> #### Contract Shell The contract stores its configuration as immutable values set at deployment. All five parameters are fixed for the lifetime of the registrar: which registry it manages, which token it accepts, where payments go, the annual price, and the minimum registration duration. ```solidity contract SimpleSubnameRegistrar { using SafeERC20 for IERC20; error NameNotAvailable(string label); error NameNotRegistered(string label); error InvalidOwner(); error DurationTooShort(uint64 duration, uint64 minimum); event NameRegistered( uint256 indexed tokenId, string label, address owner, uint64 duration, uint256 price ); event NameRenewed( uint256 indexed tokenId, string label, uint64 duration, uint64 newExpiry, uint256 price ); IPermissionedRegistry public immutable REGISTRY; IERC20 public immutable PAYMENT_TOKEN; address public immutable BENEFICIARY; uint256 public immutable PRICE; uint64 public immutable MIN_DURATION; constructor( IPermissionedRegistry registry, IERC20 paymentToken, address beneficiary, uint256 price, uint64 minDuration ) { REGISTRY = registry; PAYMENT_TOKEN = paymentToken; BENEFICIARY = beneficiary; PRICE = price; MIN_DURATION = minDuration; } ``` `PRICE` is denominated in the payment token's smallest unit (e.g., for USDC with 6 decimals, a price of `5_000_000` means $5/year). `MIN_DURATION` is in seconds. All functions in the following sections go inside this contract body. #### Checking Availability To check whether a label is available for registration, query the registry's `getState()` function. It returns a [State struct](/ensv2/permissioned-registry#querying-name-state) containing the name's status, expiry, latest owner (`latestOwner`), token ID, and resource. A name is available if its status is `AVAILABLE` (either never registered or expired). The `getState()` function accepts an [anyId](/ensv2/mutable-token-ids#anyid-polymorphism): a labelhash, token ID, or resource. For a fresh lookup by label, use the labelhash (`keccak256(bytes(label))`). ```solidity function isAvailable(string calldata label) public view returns (bool) { IPermissionedRegistry.State memory state = REGISTRY.getState(uint256(keccak256(bytes(label)))); return state.status == IPermissionedRegistry.Status.AVAILABLE; } function getPrice(uint64 duration) public view returns (uint256) { return PRICE * duration / 365 days; } ``` `getPrice()` pro-rates the annual price by duration. For example, if `PRICE` is 5 USDC and `duration` is six months (15768000 seconds), the cost is \~2.5 USDC. Integer division truncates toward zero, so pick `PRICE` and `MIN_DURATION` such that the minimum charge (`PRICE * MIN_DURATION / 365 days`) stays well above zero; otherwise short registrations become free. #### Registering Names The `register()` function validates inputs, collects payment, and delegates to `REGISTRY.register()`. The registry handles all token minting and role assignment internally. ```solidity function register( string calldata label, address owner, address resolver, uint64 duration ) external returns (uint256 tokenId) { if (!isAvailable(label)) revert NameNotAvailable(label); if (owner == address(0)) revert InvalidOwner(); if (duration < MIN_DURATION) revert DurationTooShort(duration, MIN_DURATION); uint256 price = getPrice(duration); PAYMENT_TOKEN.safeTransferFrom(msg.sender, BENEFICIARY, price); tokenId = REGISTRY.register( label, owner, IRegistry(address(0)), resolver, REGISTRATION_ROLE_BITMAP, uint64(block.timestamp) + duration ); emit NameRegistered(tokenId, label, owner, duration, price); } ``` A few things to note about the `REGISTRY.register()` call: * `label` is the subname label only (e.g., `"sub"` for `sub.nick.eth`), not the full name * `IRegistry(address(0))` means no child registry is set; the owner can set one later via `setSubregistry()` if they want sub-subnames * `resolver` is the address of a [Permissioned Resolver](/ensv2/permissioned-resolver) proxy (or any contract implementing the resolver interface), typically [deployed per account via the Verifiable Factory](/ensv2/verifiable-factory#deploying-a-resolver-proxy); the owner can change it later with `setResolver()` since they hold `ROLE_SET_RESOLVER` * `expiry` is an **absolute Unix timestamp**, not a duration * The returned `tokenId` is the [ERC1155Singleton](/ensv2/erc1155-singleton) token minted to the owner <FrenCallout fren="bittu" variant="tip" title="Developer tip"> Unlike the ETH Registrar, this contract does not use commit-reveal. Commit-reveal prevents front-running by hiding registration parameters until after the commitment is recorded. For subnames this is typically unnecessary: the parent name owner controls the registry and can [reserve names](/ensv2/permissioned-registry#name-lifecycle) if needed. </FrenCallout> #### Renewing Names Renewal extends a name's expiry without changing ownership or permissions. Anyone can renew any name (not just the owner), which matches the ETH Registrar's behavior. ```solidity function renew(string calldata label, uint64 duration) external { if (duration < MIN_DURATION) revert DurationTooShort(duration, MIN_DURATION); uint256 labelId = uint256(keccak256(bytes(label))); IPermissionedRegistry.State memory state = REGISTRY.getState(labelId); if (state.status != IPermissionedRegistry.Status.REGISTERED) { revert NameNotRegistered(label); } uint256 price = getPrice(duration); PAYMENT_TOKEN.safeTransferFrom(msg.sender, BENEFICIARY, price); uint64 newExpiry = state.expiry + duration; REGISTRY.renew(labelId, newExpiry); emit NameRenewed(state.tokenId, label, duration, newExpiry, price); } } ``` The registry's `renew()` function accepts an [anyId](/ensv2/mutable-token-ids#anyid-polymorphism) (here we pass the labelhash) and an absolute `newExpiry` timestamp. The registry enforces that `newExpiry >= oldExpiry`, so the expiry can only increase. The closing brace after `renew()` completes the contract. The full file is below; `forge build` should compile it cleanly. <details> <summary>View the complete SimpleSubnameRegistrar.sol</summary> ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IPermissionedRegistry} from "@ensdomains/contracts-v2/registry/interfaces/IPermissionedRegistry.sol"; import {IRegistry} from "@ensdomains/contracts-v2/registry/interfaces/IRegistry.sol"; import {RegistryRolesLib} from "@ensdomains/contracts-v2/registry/libraries/RegistryRolesLib.sol"; uint256 constant REGISTRATION_ROLE_BITMAP = RegistryRolesLib.ROLE_SET_SUBREGISTRY | RegistryRolesLib.ROLE_SET_SUBREGISTRY_ADMIN | RegistryRolesLib.ROLE_SET_RESOLVER | RegistryRolesLib.ROLE_SET_RESOLVER_ADMIN | RegistryRolesLib.ROLE_CAN_TRANSFER_ADMIN; contract SimpleSubnameRegistrar { using SafeERC20 for IERC20; error NameNotAvailable(string label); error NameNotRegistered(string label); error InvalidOwner(); error DurationTooShort(uint64 duration, uint64 minimum); event NameRegistered( uint256 indexed tokenId, string label, address owner, uint64 duration, uint256 price ); event NameRenewed( uint256 indexed tokenId, string label, uint64 duration, uint64 newExpiry, uint256 price ); IPermissionedRegistry public immutable REGISTRY; IERC20 public immutable PAYMENT_TOKEN; address public immutable BENEFICIARY; uint256 public immutable PRICE; uint64 public immutable MIN_DURATION; constructor( IPermissionedRegistry registry, IERC20 paymentToken, address beneficiary, uint256 price, uint64 minDuration ) { REGISTRY = registry; PAYMENT_TOKEN = paymentToken; BENEFICIARY = beneficiary; PRICE = price; MIN_DURATION = minDuration; } function isAvailable(string calldata label) public view returns (bool) { IPermissionedRegistry.State memory state = REGISTRY.getState(uint256(keccak256(bytes(label)))); return state.status == IPermissionedRegistry.Status.AVAILABLE; } function getPrice(uint64 duration) public view returns (uint256) { return PRICE * duration / 365 days; } function register( string calldata label, address owner, address resolver, uint64 duration ) external returns (uint256 tokenId) { if (!isAvailable(label)) revert NameNotAvailable(label); if (owner == address(0)) revert InvalidOwner(); if (duration < MIN_DURATION) revert DurationTooShort(duration, MIN_DURATION); uint256 price = getPrice(duration); PAYMENT_TOKEN.safeTransferFrom(msg.sender, BENEFICIARY, price); tokenId = REGISTRY.register( label, owner, IRegistry(address(0)), resolver, REGISTRATION_ROLE_BITMAP, uint64(block.timestamp) + duration ); emit NameRegistered(tokenId, label, owner, duration, price); } function renew(string calldata label, uint64 duration) external { if (duration < MIN_DURATION) revert DurationTooShort(duration, MIN_DURATION); uint256 labelId = uint256(keccak256(bytes(label))); IPermissionedRegistry.State memory state = REGISTRY.getState(labelId); if (state.status != IPermissionedRegistry.Status.REGISTERED) { revert NameNotRegistered(label); } uint256 price = getPrice(duration); PAYMENT_TOKEN.safeTransferFrom(msg.sender, BENEFICIARY, price); uint64 newExpiry = state.expiry + duration; REGISTRY.renew(labelId, newExpiry); emit NameRenewed(state.tokenId, label, duration, newExpiry, price); } } ``` </details> <FrenCallout fren="kuzco" variant="warning" title="Watch out!"> This contract is provided for educational purposes only, not as a production-grade implementation. It is intentionally minimal and unaudited; review, test, and harden it before using it for anything real. </FrenCallout> ### Deploying and Authorizing #### Set Up the UserRegistry The registrar needs a registry to register into. If your parent name does not have one yet, two setup steps are required: deploy a UserRegistry proxy via the Verifiable Factory, then point your parent name at it with `setSubregistry()` on the parent registry. For the first step, follow [Deploying a Registry Proxy](/ensv2/verifiable-factory#deploying-a-registry-proxy); the `ProxyDeployed` event in the receipt gives you the proxy address (`userRegistryAddress` below). Choose the `roleBitmap` passed to `initialize()` carefully: granting a role later via `grantRootRoles()` requires holding that role's `_ADMIN` variant, so the bitmap must include at least `ROLE_REGISTRAR_ADMIN` and `ROLE_RENEW_ADMIN` for the authorization step below to succeed. The second step is what connects the new registry to the ENS hierarchy. The [Universal Resolver](/ensv2/universal-resolver-v2) finds subnames by walking `getSubregistry()` calls down from the root, so until your parent name points at the UserRegistry, names registered in it mint tokens but never resolve. You hold `ROLE_SET_SUBREGISTRY` on your na
프로젝트로 돌아가기