@asi-names/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,662 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ASI_CONTRACTS: () => ASI_CONTRACTS,
24
+ ASI_NODE: () => ASI_NODE,
25
+ ASI_TOKENS: () => ASI_TOKENS,
26
+ AsiNameError: () => AsiNameError,
27
+ COIN_TYPE_DEFAULT: () => COIN_TYPE_DEFAULT,
28
+ COIN_TYPE_ETH: () => COIN_TYPE_ETH,
29
+ MIN_REGISTRATION_SECONDS: () => MIN_REGISTRATION_SECONDS,
30
+ SECONDS_PER_YEAR: () => SECONDS_PER_YEAR,
31
+ abis: () => abis_exports,
32
+ createAsiClient: () => createAsiClient,
33
+ decodeContenthash: () => decodeContenthash,
34
+ dnsEncode: () => dnsEncode,
35
+ encodeContenthash: () => encodeContenthash,
36
+ evmCoinType: () => evmCoinType,
37
+ labelLength: () => labelLength,
38
+ labelhash: () => labelhash,
39
+ namehash: () => namehash,
40
+ normalizeAsiName: () => normalizeAsiName,
41
+ randomSecret: () => randomSecret,
42
+ recordCalls: () => recordCalls,
43
+ registerName: () => registerName,
44
+ secondLevelLabel: () => secondLevelLabel,
45
+ yearsToSeconds: () => yearsToSeconds
46
+ });
47
+ module.exports = __toCommonJS(index_exports);
48
+
49
+ // src/client.ts
50
+ var import_viem3 = require("viem");
51
+ var import_chains = require("viem/chains");
52
+
53
+ // src/abis.ts
54
+ var abis_exports = {};
55
+ __export(abis_exports, {
56
+ baseRegistrarAbi: () => baseRegistrarAbi,
57
+ controllerAbi: () => controllerAbi,
58
+ erc1155ReceiverAbi: () => erc1155ReceiverAbi,
59
+ erc20Abi: () => erc20Abi,
60
+ nameWrapperAbi: () => nameWrapperAbi,
61
+ registryAbi: () => registryAbi,
62
+ resolverAbi: () => resolverAbi,
63
+ reverseAbi: () => reverseAbi,
64
+ universalResolverAbi: () => universalResolverAbi,
65
+ wrappedRegistrarAbi: () => wrappedRegistrarAbi
66
+ });
67
+ var import_viem = require("viem");
68
+ var universalResolverAbi = (0, import_viem.parseAbi)([
69
+ "function resolve(bytes name, bytes data) view returns (bytes result, address resolver)",
70
+ "function reverse(bytes lookupAddress, uint256 coinType) view returns (string primary, address resolver, address reverseResolver)",
71
+ "function findResolver(bytes name) view returns (address resolver, bytes32 node, uint256 offset)",
72
+ "error ResolverNotFound(bytes name)",
73
+ "error ResolverNotContract(bytes name, address resolver)",
74
+ "error UnsupportedResolverProfile(bytes4 selector)",
75
+ "error ResolverError(bytes errorData)",
76
+ "error ReverseAddressMismatch(string primary, bytes primaryAddress)",
77
+ "error HttpError(uint16 status, string message)"
78
+ ]);
79
+ var resolverAbi = (0, import_viem.parseAbi)([
80
+ "function addr(bytes32 node) view returns (address)",
81
+ "function addr(bytes32 node, uint256 coinType) view returns (bytes)",
82
+ "function text(bytes32 node, string key) view returns (string)",
83
+ "function contenthash(bytes32 node) view returns (bytes)",
84
+ "function setAddr(bytes32 node, uint256 coinType, bytes a)",
85
+ "function setText(bytes32 node, string key, string value)",
86
+ "function setContenthash(bytes32 node, bytes hash)",
87
+ "function multicall(bytes[] data) returns (bytes[] results)"
88
+ ]);
89
+ var controllerAbi = (0, import_viem.parseAbi)([
90
+ "function available(string label) view returns (bool)",
91
+ "function valid(string label) pure returns (bool)",
92
+ "function rentPrice(string label, uint256 duration) view returns ((uint256 base, uint256 premium) price)",
93
+ "function rentPriceInToken(string label, uint256 duration, address token) view returns (uint256 baseAmount, uint256 premiumAmount)",
94
+ "function commit(bytes32 commitment)",
95
+ "function commitments(bytes32) view returns (uint256)",
96
+ "function minCommitmentAge() view returns (uint256)",
97
+ "function maxCommitmentAge() view returns (uint256)"
98
+ ]);
99
+ var registerArgs = "(string label, address wrappedOwner, uint256 duration, bytes32 userSecret, address resolver, bytes[] data, uint16 ownerControlledFuses, bytes32 referrer)";
100
+ var wrappedRegistrarAbi = (0, import_viem.parseAbi)([
101
+ `function makeCommitment(${registerArgs} a) view returns (bytes32)`,
102
+ `function register(${registerArgs} a) payable returns (uint256 expires)`,
103
+ `function registerWithToken(${registerArgs} a, address token) returns (uint256 expires)`,
104
+ "function renew(string label, uint256 duration) payable returns (uint256 expires)",
105
+ "function renewWithToken(string label, uint256 duration, address token) returns (uint256 expires)",
106
+ "function sync(string label) returns (uint256 expires)"
107
+ ]);
108
+ var baseRegistrarAbi = (0, import_viem.parseAbi)([
109
+ "function nameExpires(uint256 id) view returns (uint256)",
110
+ "function ownerOf(uint256 id) view returns (address)",
111
+ "function available(uint256 id) view returns (bool)"
112
+ ]);
113
+ var nameWrapperAbi = (0, import_viem.parseAbi)([
114
+ "function getData(uint256 id) view returns (address owner, uint32 fuses, uint64 expiry)",
115
+ "function uri(uint256 id) view returns (string)"
116
+ ]);
117
+ var registryAbi = (0, import_viem.parseAbi)([
118
+ "function owner(bytes32 node) view returns (address)",
119
+ "function resolver(bytes32 node) view returns (address)"
120
+ ]);
121
+ var reverseAbi = (0, import_viem.parseAbi)(["function setName(string name)"]);
122
+ var erc20Abi = (0, import_viem.parseAbi)([
123
+ "function approve(address spender, uint256 amount) returns (bool)",
124
+ "function allowance(address owner, address spender) view returns (uint256)",
125
+ "function balanceOf(address owner) view returns (uint256)"
126
+ ]);
127
+ var erc1155ReceiverAbi = (0, import_viem.parseAbi)([
128
+ "function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes data) returns (bytes4)"
129
+ ]);
130
+
131
+ // src/constants.ts
132
+ var ASI_CONTRACTS = {
133
+ registry: "0x0B37f0F4f16d495449a1B276d0e49a7b47778a61",
134
+ baseRegistrar: "0x961a030ED67F52Ab0589C6E0F41c9B50D16e3e12",
135
+ nameWrapper: "0xDbD333d657a56fA884Df3661B14460C8d9165b5E",
136
+ controller: "0xeFd488CaD139eAb30d63C7e16A286f6Afe2F26EB",
137
+ wrappedRegistrar: "0xc8280A388469E1f619cef154bDba6E67465f30d8",
138
+ priceOracle: "0x7cA636391B8cC4da9c5a93308Bc60fe09af8cfe7",
139
+ publicResolver: "0xf8583956Da77F2f69162056DE9c029D264dC761E",
140
+ universalResolver: "0x862F5eca96515B9F53768800f03509987bf0caCA",
141
+ reverseRegistrar: "0xD5776A1E861723a43f6C85048E159D7C14Ee9F5E",
142
+ defaultReverseRegistrar: "0xBEa7cD170314A6a22FEda3547cE8FE9C57E15bf9",
143
+ dnsClaim: "0xe78eC9D71AB25A62821Ae2f6473f4F628ED3afC0",
144
+ metadataService: "0x5591A2B89769aEE3B2bA481830A54a393E02A2c8"
145
+ };
146
+ var ASI_TOKENS = {
147
+ USDC: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
148
+ USDT: "0xdAC17F958D2ee523a2206206994597C13D831ec7"
149
+ };
150
+ var ASI_NODE = "0xbc2f332e8aea2d6fa479b875008d7cae2a833e44b2bd61f1335c3f923ce88a1e";
151
+ var COIN_TYPE_DEFAULT = 0x80000000n;
152
+ var COIN_TYPE_ETH = 60n;
153
+ var SECONDS_PER_YEAR = 365n * 24n * 60n * 60n;
154
+ var MIN_REGISTRATION_SECONDS = 28n * 24n * 60n * 60n;
155
+
156
+ // src/utils.ts
157
+ var import_viem2 = require("viem");
158
+ var import_ens = require("viem/ens");
159
+ var AsiNameError = class extends Error {
160
+ name = "AsiNameError";
161
+ };
162
+ function normalizeAsiName(input) {
163
+ const trimmed = input.trim();
164
+ const withTld = trimmed.toLowerCase().endsWith(".asi") ? trimmed : `${trimmed}.asi`;
165
+ let name;
166
+ try {
167
+ name = (0, import_ens.normalize)(withTld);
168
+ } catch (e) {
169
+ throw new AsiNameError(`Invalid name "${input}": ${e.message}`);
170
+ }
171
+ const labels = name.split(".");
172
+ if (labels.length < 2 || labels.some((l) => l.length === 0)) throw new AsiNameError(`Invalid name "${input}"`);
173
+ return name;
174
+ }
175
+ function secondLevelLabel(name) {
176
+ const labels = normalizeAsiName(name).split(".");
177
+ return labels[labels.length - 2];
178
+ }
179
+ var namehash = (name) => (0, import_ens.namehash)(name);
180
+ var labelhash = (label) => (0, import_ens.labelhash)(label);
181
+ function dnsEncode(name) {
182
+ const out = [];
183
+ for (const label of name.split(".")) {
184
+ const b = (0, import_viem2.stringToBytes)(label);
185
+ if (b.length > 255) throw new AsiNameError(`Label too long: ${label}`);
186
+ out.push(b.length, ...b);
187
+ }
188
+ out.push(0);
189
+ return (0, import_viem2.bytesToHex)(Uint8Array.from(out));
190
+ }
191
+ function evmCoinType(chainId) {
192
+ const id = BigInt(chainId);
193
+ if (id === 1n) return COIN_TYPE_ETH;
194
+ if (id <= 0n || id >= 0x80000000n) throw new AsiNameError(`Invalid EVM chain id ${chainId}`);
195
+ return COIN_TYPE_DEFAULT | id;
196
+ }
197
+ function yearsToSeconds(years) {
198
+ if (!(years > 0)) throw new AsiNameError("years must be > 0");
199
+ return BigInt(Math.round(years * 365 * 24 * 60 * 60));
200
+ }
201
+ function randomSecret() {
202
+ const b = new Uint8Array(32);
203
+ globalThis.crypto.getRandomValues(b);
204
+ return (0, import_viem2.bytesToHex)(b);
205
+ }
206
+ function labelLength(label) {
207
+ return [...label].length;
208
+ }
209
+ var B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
210
+ var B32 = "abcdefghijklmnopqrstuvwxyz234567";
211
+ function base58Decode(s) {
212
+ let n = 0n;
213
+ for (const c of s) {
214
+ const v = B58.indexOf(c);
215
+ if (v < 0) throw new AsiNameError(`Invalid base58 character "${c}"`);
216
+ n = n * 58n + BigInt(v);
217
+ }
218
+ const hex = n === 0n ? "" : n.toString(16);
219
+ const body = (0, import_viem2.hexToBytes)(`0x${hex.length % 2 ? "0" + hex : hex}`);
220
+ let zeros = 0;
221
+ while (s[zeros] === "1") zeros++;
222
+ return Uint8Array.from([...new Uint8Array(zeros), ...body]);
223
+ }
224
+ function base58Encode(b) {
225
+ let n = BigInt((0, import_viem2.bytesToHex)(b) === "0x" ? 0 : (0, import_viem2.bytesToHex)(b));
226
+ let out = "";
227
+ while (n > 0n) {
228
+ out = B58[Number(n % 58n)] + out;
229
+ n /= 58n;
230
+ }
231
+ for (const x of b) {
232
+ if (x !== 0) break;
233
+ out = "1" + out;
234
+ }
235
+ return out;
236
+ }
237
+ function base32Encode(b) {
238
+ let bits = 0, value = 0, out = "";
239
+ for (const x of b) {
240
+ value = value << 8 | x;
241
+ bits += 8;
242
+ while (bits >= 5) {
243
+ out += B32[value >>> bits - 5 & 31];
244
+ bits -= 5;
245
+ }
246
+ }
247
+ if (bits > 0) out += B32[value << 5 - bits & 31];
248
+ return out;
249
+ }
250
+ function base32Decode(s) {
251
+ let bits = 0, value = 0;
252
+ const out = [];
253
+ for (const c of s.toLowerCase()) {
254
+ const v = B32.indexOf(c);
255
+ if (v < 0) throw new AsiNameError(`Invalid base32 character "${c}"`);
256
+ value = value << 5 | v;
257
+ bits += 5;
258
+ if (bits >= 8) {
259
+ out.push(value >>> bits - 8 & 255);
260
+ bits -= 8;
261
+ }
262
+ }
263
+ return Uint8Array.from(out);
264
+ }
265
+ function cidToBytes(cid) {
266
+ if (cid.startsWith("Qm")) return Uint8Array.from([1, 112, ...base58Decode(cid)]);
267
+ if (cid.startsWith("b")) return base32Decode(cid.slice(1));
268
+ throw new AsiNameError(`Unsupported CID "${cid}" (use Qm... or bafy...)`);
269
+ }
270
+ function encodeContenthash(uri) {
271
+ const m = /^(ipfs|ipns):\/\/(.+)$/.exec(uri.trim());
272
+ const [proto, cid] = m ? [m[1], m[2]] : ["ipfs", uri.trim()];
273
+ const prefix = proto === "ipfs" ? [227, 1] : [229, 1];
274
+ return (0, import_viem2.bytesToHex)(Uint8Array.from([...prefix, ...cidToBytes(cid.replace(/\/$/, ""))]));
275
+ }
276
+ function decodeContenthash(hash) {
277
+ const b = (0, import_viem2.hexToBytes)(hash);
278
+ if (b.length < 4) return null;
279
+ const cid = b.slice(2);
280
+ if (b[0] === 227 && b[1] === 1) return `ipfs://${cid[0] === 18 ? base58Encode(cid) : "b" + base32Encode(cid)}`;
281
+ if (b[0] === 229 && b[1] === 1) return `ipns://${"b" + base32Encode(cid)}`;
282
+ return null;
283
+ }
284
+
285
+ // src/client.ts
286
+ function isRevert(e) {
287
+ return e instanceof import_viem3.BaseError && e.walk((x) => x instanceof import_viem3.ContractFunctionRevertedError) !== null;
288
+ }
289
+ function createAsiClient(opts = {}) {
290
+ const client = opts.publicClient ?? (0, import_viem3.createPublicClient)({ chain: import_chains.mainnet, transport: (0, import_viem3.http)(opts.rpcUrl ?? "https://ethereum-rpc.publicnode.com") });
291
+ const C = ASI_CONTRACTS;
292
+ async function urResolve(name, data) {
293
+ try {
294
+ const [result] = await client.readContract({
295
+ address: C.universalResolver,
296
+ abi: universalResolverAbi,
297
+ functionName: "resolve",
298
+ args: [dnsEncode(name), data]
299
+ });
300
+ return result;
301
+ } catch (e) {
302
+ if (isRevert(e)) return null;
303
+ throw e;
304
+ }
305
+ }
306
+ function argsFor(p, secret) {
307
+ const name = normalizeAsiName(p.name);
308
+ const parts = name.split(".");
309
+ if (parts.length !== 2) throw new AsiNameError(`Register second-level names only (got "${name}")`);
310
+ return {
311
+ label: parts[0],
312
+ wrappedOwner: (0, import_viem3.getAddress)(p.owner),
313
+ duration: yearsToSeconds(p.years ?? 1),
314
+ userSecret: secret,
315
+ resolver: C.publicResolver,
316
+ data: recordCalls(name, p.records ?? {}),
317
+ ownerControlledFuses: p.fuses ?? 0,
318
+ referrer: p.referrer ?? "0x" + "00".repeat(32)
319
+ };
320
+ }
321
+ const api = {
322
+ client,
323
+ contracts: C,
324
+ // ------------------------------------------------------------ resolution
325
+ /** The address `name` points to on `chainId` (default 1). Falls back to the all-EVM record. */
326
+ async getAddress(name, opts2 = {}) {
327
+ const n = normalizeAsiName(name);
328
+ const node = namehash(n);
329
+ const coinType = evmCoinType(opts2.chainId ?? 1);
330
+ const data = (0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "addr", args: [node, coinType] });
331
+ const res = await urResolve(n, data);
332
+ if (!res) return null;
333
+ const bytes = (0, import_viem3.decodeFunctionResult)({ abi: resolverAbi, functionName: "addr", args: [node, coinType], data: res });
334
+ return bytes && bytes.length === 42 ? (0, import_viem3.getAddress)(bytes) : null;
335
+ },
336
+ async getText(name, key) {
337
+ const n = normalizeAsiName(name);
338
+ const data = (0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "text", args: [namehash(n), key] });
339
+ const res = await urResolve(n, data);
340
+ if (!res) return null;
341
+ const v = (0, import_viem3.decodeFunctionResult)({ abi: resolverAbi, functionName: "text", data: res });
342
+ return v === "" ? null : v;
343
+ },
344
+ /** The website: `ipfs://...` / `ipns://...` (or the raw hex for other codecs). */
345
+ async getContenthash(name) {
346
+ const n = normalizeAsiName(name);
347
+ const data = (0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "contenthash", args: [namehash(n)] });
348
+ const res = await urResolve(n, data);
349
+ if (!res) return null;
350
+ const h = (0, import_viem3.decodeFunctionResult)({ abi: resolverAbi, functionName: "contenthash", data: res });
351
+ if (h === "0x") return null;
352
+ return decodeContenthash(h) ?? h;
353
+ },
354
+ /** Verified primary name for `address` on `chainId` (default 1), or null. */
355
+ async getName(address, opts2 = {}) {
356
+ try {
357
+ const [primary] = await client.readContract({
358
+ address: C.universalResolver,
359
+ abi: universalResolverAbi,
360
+ functionName: "reverse",
361
+ args: [(0, import_viem3.getAddress)(address), evmCoinType(opts2.chainId ?? 1)]
362
+ });
363
+ return primary === "" ? null : primary;
364
+ } catch (e) {
365
+ if (isRevert(e)) return null;
366
+ throw e;
367
+ }
368
+ },
369
+ // ------------------------------------------------------------ registry state
370
+ async isAvailable(name) {
371
+ return client.readContract({ address: C.controller, abi: controllerAbi, functionName: "available", args: [secondLevelLabel(name)] });
372
+ },
373
+ /** Price for `years` (default 1), in ETH wei or a stablecoin's units. */
374
+ async getPrice(name, opts2 = {}) {
375
+ const label = secondLevelLabel(name);
376
+ const duration = yearsToSeconds(opts2.years ?? 1);
377
+ if (opts2.token) {
378
+ const [base, premium] = await client.readContract({
379
+ address: C.controller,
380
+ abi: controllerAbi,
381
+ functionName: "rentPriceInToken",
382
+ args: [label, duration, ASI_TOKENS[opts2.token]]
383
+ });
384
+ return { base, premium, total: base + premium, currency: opts2.token };
385
+ }
386
+ const p = await client.readContract({ address: C.controller, abi: controllerAbi, functionName: "rentPrice", args: [label, duration] });
387
+ return { base: p.base, premium: p.premium, total: p.base + p.premium, currency: "ETH" };
388
+ },
389
+ /** Registration expiry (unix seconds), or null if never registered. */
390
+ async getExpiry(name) {
391
+ const id = BigInt(labelhash(secondLevelLabel(name)));
392
+ const e = await client.readContract({ address: C.baseRegistrar, abi: baseRegistrarAbi, functionName: "nameExpires", args: [id] });
393
+ return e === 0n ? null : e;
394
+ },
395
+ /** Who controls `name`: the NameWrapper token owner if wrapped, otherwise the registry owner. */
396
+ async getOwner(name) {
397
+ const n = normalizeAsiName(name);
398
+ const node = namehash(n);
399
+ const regOwner = await client.readContract({ address: C.registry, abi: registryAbi, functionName: "owner", args: [node] });
400
+ if ((0, import_viem3.getAddress)(regOwner) === (0, import_viem3.getAddress)(C.nameWrapper)) {
401
+ const [owner] = await client.readContract({ address: C.nameWrapper, abi: nameWrapperAbi, functionName: "getData", args: [BigInt(node)] });
402
+ return { owner: owner === import_viem3.zeroAddress ? null : owner, wrapped: true };
403
+ }
404
+ return { owner: regOwner === import_viem3.zeroAddress ? null : regOwner, wrapped: false };
405
+ },
406
+ // ------------------------------------------------------------ transactions
407
+ /**
408
+ * Step 1 of 2. Returns the commit tx and the `secret` you must keep for step 2.
409
+ * Wait `minCommitmentAge` (60s) after it is mined, and no longer than 24h.
410
+ */
411
+ async prepareCommit(p) {
412
+ const secret = p.secret ?? randomSecret();
413
+ const a = argsFor(p, secret);
414
+ const commitment = await client.readContract({
415
+ address: C.wrappedRegistrar,
416
+ abi: wrappedRegistrarAbi,
417
+ functionName: "makeCommitment",
418
+ args: [a]
419
+ });
420
+ return {
421
+ secret,
422
+ commitment,
423
+ tx: {
424
+ to: C.controller,
425
+ value: 0n,
426
+ chainId: 1,
427
+ data: (0, import_viem3.encodeFunctionData)({ abi: controllerAbi, functionName: "commit", args: [commitment] }),
428
+ description: `Commit to register ${a.label}.asi`
429
+ }
430
+ };
431
+ },
432
+ /**
433
+ * Step 2 of 2. Returns the txs to send in order: an ERC-20 approval when paying with a
434
+ * stablecoin and the allowance is short, then the register tx. ETH payments include a 3%
435
+ * buffer for price movement; the excess is refunded in the same tx.
436
+ */
437
+ async prepareRegister(p) {
438
+ const a = argsFor(p, p.secret);
439
+ const price = await api.getPrice(p.name, { years: p.years, token: p.token });
440
+ const label = `${a.label}.asi`;
441
+ if (p.token) {
442
+ const token = ASI_TOKENS[p.token];
443
+ const txs = [];
444
+ const allowance = await client.readContract({
445
+ address: token,
446
+ abi: erc20Abi,
447
+ functionName: "allowance",
448
+ args: [(0, import_viem3.getAddress)(p.payer ?? p.owner), C.wrappedRegistrar]
449
+ });
450
+ if (allowance < price.total) {
451
+ txs.push({
452
+ to: token,
453
+ value: 0n,
454
+ chainId: 1,
455
+ data: (0, import_viem3.encodeFunctionData)({ abi: erc20Abi, functionName: "approve", args: [C.wrappedRegistrar, price.total] }),
456
+ description: `Approve ${Number(price.total) / 1e6} ${p.token} for ${label}`
457
+ });
458
+ }
459
+ txs.push({
460
+ to: C.wrappedRegistrar,
461
+ value: 0n,
462
+ chainId: 1,
463
+ data: (0, import_viem3.encodeFunctionData)({ abi: wrappedRegistrarAbi, functionName: "registerWithToken", args: [a, token] }),
464
+ description: `Register ${label} (${p.years ?? 1}y, ${Number(price.total) / 1e6} ${p.token})`
465
+ });
466
+ return txs;
467
+ }
468
+ const value = price.total * 103n / 100n;
469
+ return [{
470
+ to: C.wrappedRegistrar,
471
+ value,
472
+ chainId: 1,
473
+ data: (0, import_viem3.encodeFunctionData)({ abi: wrappedRegistrarAbi, functionName: "register", args: [a] }),
474
+ description: `Register ${label} (${p.years ?? 1}y, ~${Number(price.total) / 1e18} ETH)`
475
+ }];
476
+ },
477
+ /** Renew (anyone can renew any name). Goes through the NameWrapper so wrapped names stay in sync. */
478
+ async prepareRenew(p) {
479
+ const label = secondLevelLabel(p.name);
480
+ const duration = yearsToSeconds(p.years ?? 1);
481
+ const price = await api.getPrice(p.name, { years: p.years, token: p.token });
482
+ if (p.token) {
483
+ const token = ASI_TOKENS[p.token];
484
+ const txs = [];
485
+ if (!p.payer) throw new AsiNameError("payer is required to check the token allowance");
486
+ const allowance = await client.readContract({ address: token, abi: erc20Abi, functionName: "allowance", args: [(0, import_viem3.getAddress)(p.payer), C.wrappedRegistrar] });
487
+ if (allowance < price.base) {
488
+ txs.push({
489
+ to: token,
490
+ value: 0n,
491
+ chainId: 1,
492
+ description: `Approve ${Number(price.base) / 1e6} ${p.token}`,
493
+ data: (0, import_viem3.encodeFunctionData)({ abi: erc20Abi, functionName: "approve", args: [C.wrappedRegistrar, price.base] })
494
+ });
495
+ }
496
+ txs.push({
497
+ to: C.wrappedRegistrar,
498
+ value: 0n,
499
+ chainId: 1,
500
+ description: `Renew ${label}.asi`,
501
+ data: (0, import_viem3.encodeFunctionData)({ abi: wrappedRegistrarAbi, functionName: "renewWithToken", args: [label, duration, token] })
502
+ });
503
+ return txs;
504
+ }
505
+ return [{
506
+ to: C.wrappedRegistrar,
507
+ value: price.base * 103n / 100n,
508
+ chainId: 1,
509
+ description: `Renew ${label}.asi`,
510
+ data: (0, import_viem3.encodeFunctionData)({ abi: wrappedRegistrarAbi, functionName: "renew", args: [label, duration] })
511
+ }];
512
+ },
513
+ /** Write records in one tx (the caller must own/manage the name). */
514
+ prepareSetRecords(name, records) {
515
+ const n = normalizeAsiName(name);
516
+ const calls = recordCalls(n, records);
517
+ if (calls.length === 0) throw new AsiNameError("No records given");
518
+ return {
519
+ to: C.publicResolver,
520
+ value: 0n,
521
+ chainId: 1,
522
+ description: `Set ${calls.length} record(s) on ${n}`,
523
+ data: calls.length === 1 ? calls[0] : (0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "multicall", args: [calls] })
524
+ };
525
+ },
526
+ /**
527
+ * Make `name` the primary name of the sending wallet on every EVM chain (default.reverse).
528
+ * The name must resolve back to the wallet (set `address` first) or lookups ignore it.
529
+ */
530
+ prepareSetPrimaryName(name) {
531
+ const n = normalizeAsiName(name);
532
+ return {
533
+ to: C.defaultReverseRegistrar,
534
+ value: 0n,
535
+ chainId: 1,
536
+ description: `Set ${n} as primary name on all EVM chains`,
537
+ data: (0, import_viem3.encodeFunctionData)({ abi: reverseAbi, functionName: "setName", args: [n] })
538
+ };
539
+ },
540
+ /** Free repair for a wrapped name renewed directly on the controller. */
541
+ prepareSync(name) {
542
+ const label = secondLevelLabel(name);
543
+ return {
544
+ to: C.wrappedRegistrar,
545
+ value: 0n,
546
+ chainId: 1,
547
+ description: `Sync ${label}.asi expiry into the NameWrapper`,
548
+ data: (0, import_viem3.encodeFunctionData)({ abi: wrappedRegistrarAbi, functionName: "sync", args: [label] })
549
+ };
550
+ },
551
+ /**
552
+ * Wrapped names arrive as ERC-1155 tokens. A contract or EIP-7702 account that does not accept
553
+ * them would make the register step revert after the commit was paid for, so check first.
554
+ */
555
+ async canReceiveWrapped(owner) {
556
+ const code = await client.getCode({ address: (0, import_viem3.getAddress)(owner) });
557
+ if (!code || code === "0x") return true;
558
+ try {
559
+ const ret = await client.call({
560
+ account: C.nameWrapper,
561
+ to: (0, import_viem3.getAddress)(owner),
562
+ data: (0, import_viem3.encodeFunctionData)({
563
+ abi: erc1155ReceiverAbi,
564
+ functionName: "onERC1155Received",
565
+ args: [C.wrappedRegistrar, import_viem3.zeroAddress, 1n, 1n, "0x"]
566
+ })
567
+ });
568
+ return (ret.data ?? "0x").slice(0, 10).toLowerCase() === "0xf23a6e61";
569
+ } catch (e) {
570
+ if (isRevert(e) || e instanceof import_viem3.BaseError && /revert/i.test(e.message)) return false;
571
+ throw e;
572
+ }
573
+ },
574
+ /** Seconds to wait between commit and register, and the max age. */
575
+ async commitWindow() {
576
+ const [min, max] = await Promise.all([
577
+ client.readContract({ address: C.controller, abi: controllerAbi, functionName: "minCommitmentAge" }),
578
+ client.readContract({ address: C.controller, abi: controllerAbi, functionName: "maxCommitmentAge" })
579
+ ]);
580
+ return { min, max };
581
+ }
582
+ };
583
+ return api;
584
+ }
585
+ function recordCalls(name, r) {
586
+ const node = namehash(normalizeAsiName(name));
587
+ const calls = [];
588
+ if (r.address) {
589
+ calls.push((0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "setAddr", args: [node, COIN_TYPE_DEFAULT, (0, import_viem3.getAddress)(r.address)] }));
590
+ }
591
+ for (const [chainId, a] of Object.entries(r.chainAddresses ?? {})) {
592
+ calls.push((0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "setAddr", args: [node, evmCoinType(Number(chainId)), (0, import_viem3.getAddress)(a)] }));
593
+ }
594
+ for (const [k, v] of Object.entries(r.texts ?? {})) {
595
+ calls.push((0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "setText", args: [node, k, v] }));
596
+ }
597
+ if (r.contenthash) {
598
+ calls.push((0, import_viem3.encodeFunctionData)({ abi: resolverAbi, functionName: "setContenthash", args: [node, encodeContenthash(r.contenthash)] }));
599
+ }
600
+ return calls;
601
+ }
602
+
603
+ // src/register.ts
604
+ async function registerName(asi, wallet, params, onProgress) {
605
+ const owner = params.owner ?? wallet.account.address;
606
+ const p = { ...params, owner };
607
+ const pub = asi.client;
608
+ const hashes = [];
609
+ const send = async (tx) => {
610
+ const hash = await wallet.sendTransaction({ to: tx.to, data: tx.data, value: tx.value, chain: wallet.chain, account: wallet.account });
611
+ hashes.push(hash);
612
+ onProgress?.({ step: "tx-sent", hash, description: tx.description });
613
+ const rc = await pub.waitForTransactionReceipt({ hash });
614
+ if (rc.status !== "success") throw new AsiNameError(`Transaction reverted: ${tx.description} (${hash})`);
615
+ onProgress?.({ step: "tx-mined", hash, description: tx.description });
616
+ return rc;
617
+ };
618
+ if (!await asi.isAvailable(p.name)) throw new AsiNameError(`${p.name} is not available`);
619
+ if (!await asi.canReceiveWrapped(owner)) {
620
+ throw new AsiNameError(`${owner} is a contract/7702 account that does not accept ERC-1155 tokens; register to a different owner`);
621
+ }
622
+ const { tx: commitTx, secret } = await asi.prepareCommit(p);
623
+ const commitRc = await send(commitTx);
624
+ const commitBlock = await pub.getBlock({ blockNumber: commitRc.blockNumber });
625
+ const { min } = await asi.commitWindow();
626
+ const readyAt = commitBlock.timestamp + min + 1n;
627
+ for (; ; ) {
628
+ const now = (await pub.getBlock()).timestamp;
629
+ if (now >= readyAt) break;
630
+ const left = Number(readyAt - now);
631
+ onProgress?.({ step: "waiting", secondsLeft: left });
632
+ await new Promise((r) => setTimeout(r, Math.min(left, 12) * 1e3));
633
+ }
634
+ for (const tx of await asi.prepareRegister({ ...p, secret, payer: wallet.account.address })) await send(tx);
635
+ return { name: p.name, secret, hashes };
636
+ }
637
+ // Annotate the CommonJS export names for ESM import in node:
638
+ 0 && (module.exports = {
639
+ ASI_CONTRACTS,
640
+ ASI_NODE,
641
+ ASI_TOKENS,
642
+ AsiNameError,
643
+ COIN_TYPE_DEFAULT,
644
+ COIN_TYPE_ETH,
645
+ MIN_REGISTRATION_SECONDS,
646
+ SECONDS_PER_YEAR,
647
+ abis,
648
+ createAsiClient,
649
+ decodeContenthash,
650
+ dnsEncode,
651
+ encodeContenthash,
652
+ evmCoinType,
653
+ labelLength,
654
+ labelhash,
655
+ namehash,
656
+ normalizeAsiName,
657
+ randomSecret,
658
+ recordCalls,
659
+ registerName,
660
+ secondLevelLabel,
661
+ yearsToSeconds
662
+ });