bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 25쪽
me from registration, so this call needs no extra setup:
```typescript
import { keccak256, toHex, parseAbi } from 'viem'
const permissionedRegistryAbi = parseAbi([
'function setSubregistry(uint256 anyId, address subregistry)',
])
// Point the parent name at the UserRegistry
// (here: nick.eth, so this runs on the .eth registry)
await wallet.writeContract({
address: ethRegistryAddress,
abi: permissionedRegistryAbi,
functionName: 'setSubregistry',
args: [BigInt(keccak256(toHex('nick'))), userRegistryAddress],
})
```
The `wallet` object in the TypeScript snippets on this page is a viem wallet client; its setup is shown in [Client Integration](#client-integration) below. The protocol contract addresses (like `ethRegistryAddress`) are listed in the [Deployments](/learn/deployments#sepolia-ensv2) table.
#### Deploy the Registrar
The registrar is a plain contract (not a proxy), so deployment is straightforward. You need:
* The address of your UserRegistry (from the previous step)
* An ERC20 payment token address (on a testnet, deploy your own mintable mock ERC20; any token implementing `transferFrom`/`approve` works)
* A beneficiary address for receiving payments
* The annual price in the token's smallest unit
* A minimum registration duration in seconds
```solidity
SimpleSubnameRegistrar registrar = new SimpleSubnameRegistrar(
IPermissionedRegistry(userRegistryAddress),
IERC20(usdcAddress),
beneficiaryAddress,
5_000_000, // 5 USDC per year (6 decimals)
30 days // minimum 30-day registration
);
```
For example, deploying with Foundry:
```bash
forge create src/SimpleSubnameRegistrar.sol:SimpleSubnameRegistrar \
--rpc-url $RPC_URL --private-key $PRIVATE_KEY --broadcast \
--constructor-args $USER_REGISTRY $PAYMENT_TOKEN $BENEFICIARY 5000000 2592000
```
The last two arguments are the price (5 USDC with 6 decimals) and the minimum duration (30 days in seconds). Passing a raw private key is acceptable for testnet experiments; in general, follow Foundry's [key management best practices](https://getfoundry.sh/guides/best-practices/key-management/) (encrypted keystores via `cast wallet import`, hardware wallets for production).
#### Grant Roles to the Registrar
After deployment, the registry owner must grant the registrar `ROLE_REGISTRAR` and `ROLE_RENEW` on `ROOT_RESOURCE`. Without these roles, calls to `registry.register()` and `registry.renew()` will revert.
In Solidity:
```solidity
registry.grantRootRoles(
RegistryRolesLib.ROLE_REGISTRAR | RegistryRolesLib.ROLE_RENEW,
address(registrar)
);
```
Or via viem:
```typescript
const ROLE_REGISTRAR = 1n << 0n
const ROLE_RENEW = 1n << 16n
await wallet.writeContract({
address: userRegistryAddress,
abi: [{
name: 'grantRootRoles',
type: 'function',
stateMutability: 'nonpayable',
inputs: [
{ name: 'roleBitmap', type: 'uint256' },
{ name: 'account', type: 'address' },
],
outputs: [{ name: '', type: 'bool' }],
}],
functionName: 'grantRootRoles',
args: [ROLE_REGISTRAR | ROLE_RENEW, registrarAddress],
})
```
<FrenCallout fren="kuzco" variant="warning" title="Watch out!">
`ROLE_REGISTRAR` authorizes the registrar to register **any** name under your registry, and `ROLE_RENEW` lets it extend **any** name's expiry. Only grant these roles to contracts you trust and have audited.
</FrenCallout>
Trust works in both directions: the roles that remain on `ROOT_RESOURCE` define how much subname owners must trust *you*. See [Configuration Patterns](/ensv2/registry-template#configuration-patterns) for the managed versus emancipated trade-off, and [Emancipation](/ensv2/permissioned-registry#emancipation) for how owners can verify your registry's setup.
### Client Integration
Once the registrar is deployed and authorized, users interact with it via standard `writeContract` calls. Here is a complete example using viem. ENSv2 is currently deployed on Sepolia, so the clients target that chain; in a browser app you would create the wallet client with `custom(window.ethereum)` instead of a private key account.
```typescript
import { createPublicClient, createWalletClient, http } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { sepolia } from 'viem/chains'
const registrarAddress = '0x...' // your deployed SimpleSubnameRegistrar
const paymentTokenAddress = '0x...' // ERC20 payment token (e.g., USDC)
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)
const client = createPublicClient({ chain: sepolia, transport: http() })
const wallet = createWalletClient({ account, chain: sepolia, transport: http() })
const simpleRegistrarAbi = [
{
name: 'isAvailable', type: 'function', stateMutability: 'view',
inputs: [{ name: 'label', type: 'string' }],
outputs: [{ name: '', type: 'bool' }],
},
{
name: 'getPrice', type: 'function', stateMutability: 'view',
inputs: [{ name: 'duration', type: 'uint64' }],
outputs: [{ name: '', type: 'uint256' }],
},
{
name: 'register', type: 'function', stateMutability: 'nonpayable',
inputs: [
{ name: 'label', type: 'string' },
{ name: 'owner', type: 'address' },
{ name: 'resolver', type: 'address' },
{ name: 'duration', type: 'uint64' },
],
outputs: [{ name: 'tokenId', type: 'uint256' }],
},
{
name: 'renew', type: 'function', stateMutability: 'nonpayable',
inputs: [
{ name: 'label', type: 'string' },
{ name: 'duration', type: 'uint64' },
],
outputs: [],
},
] as const
```
#### Check Availability and Price
```typescript
const available = await client.readContract({
address: registrarAddress,
abi: simpleRegistrarAbi,
functionName: 'isAvailable',
args: ['sub'],
})
const oneYear = BigInt(365 * 24 * 60 * 60)
const price = await client.readContract({
address: registrarAddress,
abi: simpleRegistrarAbi,
functionName: 'getPrice',
args: [oneYear],
})
```
#### Register a Subname
Before calling `register()`, the caller must approve the registrar to spend the payment token:
```typescript
import { erc20Abi } from 'viem'
// Approve the registrar to spend the payment token
await wallet.writeContract({
address: paymentTokenAddress,
abi: erc20Abi,
functionName: 'approve',
args: [registrarAddress, price],
})
// Register sub.nick.eth
const hash = await wallet.writeContract({
address: registrarAddress,
abi: simpleRegistrarAbi,
functionName: 'register',
args: ['sub', ownerAddress, resolverAddress, oneYear],
})
```
To confirm the registration worked, check availability again; it should now return `false`:
```typescript
const stillAvailable = await client.readContract({
address: registrarAddress,
abi: simpleRegistrarAbi,
functionName: 'isAvailable',
args: ['sub'],
})
console.log(stillAvailable) // false
```
Once the owner sets records on the resolver, the name resolves like any other ENS name (e.g., via viem's `getEnsAddress`).
#### Renew a Subname
```typescript
// Approve payment for renewal
await wallet.writeContract({
address: paymentTokenAddress,
abi: erc20Abi,
functionName: 'approve',
args: [registrarAddress, price],
})
// Extend sub.nick.eth by one year
await wallet.writeContract({
address: registrarAddress,
abi: simpleRegistrarAbi,
functionName: 'renew',
args: ['sub', oneYear],
})
```
### Events and Indexing
A single `register()` call triggers events from **two contracts**: the registrar and the underlying registry. If you are building an indexer, you need to listen to both.
**From the registrar:**
| Event | Fields |
| ---------------- | ---------------------------------------------------- |
| `NameRegistered` | `tokenId`, `label`, `owner`, `duration`, `price` |
| `NameRenewed` | `tokenId`, `label`, `duration`, `newExpiry`, `price` |
**From the registry** (emitted inside `REGISTRY.register()`):
| Event | Purpose |
| ----------------- | ----------------------------------------------------- |
| `LabelRegistered` | Records the label, owner, expiry, and sender |
| `TokenResource` | Associates the ERC1155 token ID with the EAC resource |
| `TransferSingle` | ERC1155 mint (from `address(0)` to owner) |
| `ResolverUpdated` | Records the resolver address (if not `address(0)`) |
Renewals follow the same pattern: `renew()` emits the registrar's `NameRenewed` and the registry's `ExpiryUpdated`. Indexing only the registrar's events would miss renewals performed by other `ROLE_RENEW` holders directly on the registry.
<FrenCallout fren="kuzco" variant="warning" title="Watch out!">
Both custom events index the token ID, but token IDs in ENSv2 are **mutable**: they change whenever roles are granted or revoked on a name, and on re-registration after expiry. Key your index on the labelhash and follow `TokenRegenerated` events to track ID changes. See [Mutable Token IDs](/ensv2/mutable-token-ids#dont-cache-token-ids).
</FrenCallout>
For the full event reference, parameter details, and indexing patterns, see [Indexing ENSv2](/ensv2/indexing).
### Troubleshooting
| Symptom | Likely cause |
| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `register()` or `renew()` reverts with `EACUnauthorizedAccountRoles` | The registrar was not granted `ROLE_REGISTRAR` (or `ROLE_RENEW`) on the registry's `ROOT_RESOURCE` |
| `grantRootRoles()` reverts with `EACCannotGrantRoles` | The caller does not hold the `_ADMIN` variants of the roles being granted; check the `roleBitmap` passed to the UserRegistry's `initialize()` |
| `register()` reverts with an ERC20 allowance error | The caller did not `approve()` the registrar for the payment token, or approved less than `getPrice(duration)` |
| Registration succeeds but the name does not resolve | The parent name does not point at the UserRegistry; call `setSubregistry()` (see [Set Up the UserRegistry](#set-up-the-userregistry)), and make sure the name's resolver has records set |
### Next Steps
The `SimpleSubnameRegistrar` covers the core registration pattern. Here are common extensions you might add:
* **Commit-reveal**: prevent front-running by requiring a commitment before registration. See how the [ETH Registrar](/ensv2/eth-registrar#commit-reveal) implements this.
* **Allowlists or NFT-gating**: restrict who can register by checking token balances or merkle proofs in `register()`.
* **Custom role bitmaps**: use different `REGISTRATION_ROLE_BITMAP` values for different registration tiers (e.g., premium names get fewer restrictions).
* **Infinite-duration claims**: for permanent subnames, pass `type(uint64).max` as the expiry instead of computing it from a duration. `renew()` and the `ROLE_RENEW` grant become unnecessary, but abandoned names never return to the available pool; removing one then requires the operator to hold `ROLE_UNREGISTER`, a trust tradeoff expiry-based recycling avoids.
* **Grace periods**: keep expired names renewable for a window before they become available to others.
* **Custom registries**: for deeper customization, build your own registry by extending `PermissionedRegistry` directly. See [Registry Template](/ensv2/registry-template#building-your-own-registry).
import { FrenCallout } from '../../components/ensv2/FrenCallout'
import { ContractReference } from '../../components/ensv2/ContractReference'
import { MonoDiagram } from '../../components/ensv2/MonoDiagram'
## Universal Resolver V2
The Universal Resolver V2 is the primary public entry point for ENS name resolution. It resolves names by traversing the [hierarchical registry tree](/ensv2/registry-hierarchy), walking from the root registry down through subregistries to locate the correct resolver for any name. Its companion contract [UniversalHelper](#universalhelper) provides functions for navigating and verifying the registry hierarchy itself.
### Architecture
Both Universal Resolver versions share a base contract that implements all resolution logic: forward resolution, reverse resolution, [CCIP-Read](/resolvers/ccip-read) gateway batching, and callback chaining. The only function the base leaves abstract is `findResolver()`, which each version overrides with its own registry traversal strategy:
* **URv1** walks a flat ENS registry
* **URv2** walks the hierarchical registry tree via `getSubregistry()` at each level
Because the walk passes through each parent registry, if a parent name expires or its subregistry is removed, the registry returns `address(0)` and all subnames stop resolving automatically.
`resolve()`, `reverse()`, and all CCIP-Read infrastructure work identically across both versions.
Functions for inspecting the registry hierarchy itself live on the separate [UniversalHelper](#universalhelper) contract, keeping the Universal Resolver focused on resolution.
### Resolution
The Universal Resolver resolves names by walking down the registry tree from the root, looking for the **deepest resolver** along the path. At each level, it calls `getResolver(label)` on the current registry. If a resolver exists, it's remembered. Then it calls `getSubregistry(label)` to descend to the next level. The resolver that covers the longest matching suffix of the name wins.
`resolve()` and `reverse()` both call `findResolver` internally via `requireResolver`, which reverts if no suitable resolver is found.
Using the structure from the [registry hierarchy diagrams](/ensv2/registry-hierarchy#from-flat-to-hierarchical), here are two examples showing how `findResolver()` walks the tree:
#### Example 1
Resolving `inigo.montoya.eth`: the walk descends from root, checking for resolvers at each level:
```mermaid
flowchart LR
subgraph s1 [" "]
direction TB
r1@{label: "<b><root></b>"}
e1@{label: "<b>eth</b>"}
m1@{label: "<b>montoya.eth</b>"}
i1@{label: "<b>Resolver 2</b>", shape: notch-rect}
d1@{label: "<b>domingo.montoya.eth</b>"}
mr1@{label: "<b>Resolver 1</b>", shape: notch-rect}
r1-- eth --> e1
e1-- montoya --> m1
e1-- montoya --> mr1
m1-- inigo --> i1
m1-- domingo --> d1
style r1 fill:#0080BC,stroke:#011A25,color:#fff
style e1 fill:#CEE1E8,stroke:#0080BC,color:#011A25
style m1 fill:#CEE1E8,stroke:#0080BC,color:#011A25
style i1 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style d1 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style mr1 fill:#CEE1E8,stroke:#CEE1E8,color:#999
end
subgraph s2 [" "]
direction TB
r2@{label: "<b><root></b>"}
e2@{label: "<b>eth</b>"}
m2@{label: "<b>montoya.eth</b>"}
i2@{label: "<b>Resolver 2</b>", shape: notch-rect}
d2@{label: "<b>domingo.montoya.eth</b>"}
mr2@{label: "<b>Resolver 1</b>", shape: notch-rect}
r2-- eth --> e2
e2-- montoya --> m2
e2-- montoya --> mr2
m2-- inigo --> i2
m2-- domingo --> d2
style r2 fill:#0080BC,stroke:#011A25,color:#fff
style e2 fill:#0080BC,stroke:#011A25,color:#fff
style m2 fill:#CEE1E8,stroke:#0080BC,color:#011A25
style i2 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style d2 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style mr2 fill:#CEE1E8,stroke:#0080BC,color:#011A25
end
subgraph s3 [" "]
direction TB
r3@{label: "<b><root></b>"}
e3@{label: "<b>eth</b>"}
m3@{label: "<b>montoya.eth</b>"}
i3@{label: "<b>Resolver 2</b>", shape: notch-rect}
d3@{label: "<b>domingo.montoya.eth</b>"}
mr3@{label: "<b>Resolver 1</b>", shape: notch-rect}
r3-- eth --> e3
e3-- montoya --> m3
e3-- montoya --> mr3
m3-- inigo --> i3
m3-- domingo --> d3
style r3 fill:#0080BC,stroke:#011A25,color:#fff
style e3 fill:#0080BC,stroke:#011A25,color:#fff
style m3 fill:#0080BC,stroke:#011A25,color:#fff
style i3 fill:#011A25,stroke:#0080BC,color:#fff
style d3 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style mr3 fill:#CEE1E8,stroke:#0080BC,color:#011A25
end
style s1 fill:none,stroke:none
style s2 fill:none,stroke:none
style s3 fill:none,stroke:none
s1 ~~~ s2 ~~~ s3
```
Resolver 1 is found at the .eth level, but Resolver 2 is found one level deeper at montoya.eth. **Resolver 2 wins** because it covers the longest matching suffix, in this case the full name `inigo.montoya.eth`.
#### Example 2
Resolving `domingo.montoya.eth`: the walk follows the same path, but `domingo` has no resolver:
```mermaid
flowchart LR
subgraph s1 [" "]
direction TB
r1@{label: "<b><root></b>"}
e1@{label: "<b>eth</b>"}
m1@{label: "<b>montoya.eth</b>"}
i1@{label: "<b>Resolver 2</b>", shape: notch-rect}
d1@{label: "<b>domingo.montoya.eth</b>"}
mr1@{label: "<b>Resolver 1</b>", shape: notch-rect}
r1-- eth --> e1
e1-- montoya --> m1
e1-- montoya --> mr1
m1-- inigo --> i1
m1-- domingo --> d1
style r1 fill:#0080BC,stroke:#011A25,color:#fff
style e1 fill:#CEE1E8,stroke:#0080BC,color:#011A25
style m1 fill:#CEE1E8,stroke:#0080BC,color:#011A25
style i1 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style d1 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style mr1 fill:#CEE1E8,stroke:#CEE1E8,color:#999
end
subgraph s2 [" "]
direction TB
r2@{label: "<b><root></b>"}
e2@{label: "<b>eth</b>"}
m2@{label: "<b>montoya.eth</b>"}
i2@{label: "<b>Resolver 2</b>", shape: notch-rect}
d2@{label: "<b>domingo.montoya.eth</b>"}
mr2@{label: "<b>Resolver 1</b>", shape: notch-rect}
r2-- eth --> e2
e2-- montoya --> m2
e2-- montoya --> mr2
m2-- inigo --> i2
m2-- domingo --> d2
style r2 fill:#0080BC,stroke:#011A25,color:#fff
style e2 fill:#0080BC,stroke:#011A25,color:#fff
style m2 fill:#CEE1E8,stroke:#0080BC,color:#011A25
style i2 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style d2 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style mr2 fill:#CEE1E8,stroke:#0080BC,color:#011A25
end
subgraph s3 [" "]
direction TB
r3@{label: "<b><root></b>"}
e3@{label: "<b>eth</b>"}
m3@{label: "<b>montoya.eth</b>"}
i3@{label: "<b>Resolver 2</b>", shape: notch-rect}
d3@{label: "<b>domingo.montoya.eth</b>"}
mr3@{label: "<b>Resolver 1</b>", shape: notch-rect}
r3-- eth --> e3
e3-- montoya --> m3
e3-- montoya --> mr3
m3-- inigo --> i3
m3-- domingo --> d3
style r3 fill:#0080BC,stroke:#011A25,color:#fff
style e3 fill:#0080BC,stroke:#011A25,color:#fff
style m3 fill:#0080BC,stroke:#011A25,color:#fff
style i3 fill:#CEE1E8,stroke:#CEE1E8,color:#999
style d3 fill:#CEE1E8,stroke:#0080BC,color:#011A25
style mr3 fill:#011A25,stroke:#0080BC,color:#fff
end
style s1 fill:none,stroke:none
style s2 fill:none,stroke:none
style s3 fill:none,stroke:none
s1 ~~~ s2 ~~~ s3
```
Resolver 1 is found at the .eth level, but `domingo` has no resolver set. **Resolver 1 wins** as the longest-suffix match, covering `montoya.eth`. Any subname of `montoya.eth` without its own resolver will fall back to Resolver 1 the same way.
#### The Algorithm
`findResolver()` implements this longest-suffix match. It recursively descends from the root, and at each level:
1. Calls `getResolver(label)`. If non-zero, overwrites the previously remembered resolver.
2. Calls `getSubregistry(label)`. If non-zero, continues descending into the subregistry.
The final remembered resolver is the one used for the actual record query.
### UniversalHelper
ENSv2 provides functions for locating registries within the hierarchy and verifying their position. All functions described here are exposed on the **UniversalHelper** contract, a companion to the Universal Resolver deployed alongside it (see [Deployments](/learn/deployments#sepolia-ensv2)).
All navigation functions walk **down** from the root registry except `findCanonicalName`, which walks **up** via `getParent()`, and `findCanonicalRegistry`, which does both.
The `findNearest*` functions return a byte **offset** alongside their result. It marks the label boundary in the DNS-encoded input where the returned result was found: cutting the input bytes at that position (`name[offset:]` in pseudocode, where `name` is the DNS-encoded byte array) yields the ancestor's own DNS-encoded name, because every suffix of a DNS-encoded name that starts at a label boundary is itself a valid DNS-encoded name. The cut result can be passed directly to any other function that takes a name (onchain via 프로젝트로 돌아가기