'use strict'; // Copyright (c) 2026 LWJ Digital LLC. MIT License (see LICENSE). // NameKey name resolution: reads a Freename name (e.g. owndot.usa) from the // FNS registry on Polygon, from at least 2 independent public RPC endpoints, // at the same FINALIZED block. The answer is accepted only if 2 endpoints agree // on the owner and on every record. Nothing is written, no key is needed. // Needs the npm package "ethers" (v6). const {id,solidityPackedKeccak256,FetchRequest,JsonRpcProvider,Contract}=require('ethers'); const REGISTRY='0x465ea4967479a96d4490d575b5a6cc2b4a4bee65'; // FNS registry proxy, Polygon const CHAIN_ID=137; // First two are always queried. The next ones are asked only if one fails or they disagree. const DEFAULT_RPCS=['https://polygon-bor-rpc.publicnode.com','https://polygon.drpc.org','https://polygon.gateway.tenderly.co']; const ABI=['function ownerOf(uint256) view returns(address)','function getAllKeys(uint256) view returns(string[])','function getManyRecords(string[],uint256) view returns(string[])']; const MAX_RECORDS=256, MAX_STALE_S=300; const IPV4=/^\d{1,3}(\.\d{1,3}){3}$/; const CID=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z2-7]{40,100})$/; // Token id of a name: only plain ASCII "label.tld" (or a bare tld) is accepted. function deriveFNS(name){ if(typeof name!=='string'||name.length>127)throw Error('unsupported_name'); const parts=name.split('.'); if(parts.length>2||!parts.every(x=>x.length>0&&x.length<=63&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(x)))throw Error('unsupported_name'); return parts.length===1?BigInt(id(parts[0])).toString():BigInt(solidityPackedKeccak256(['string','uint256'],[parts[1],id(parts[0])])).toString(); } async function readFrom(endpoint,name){ const request=new FetchRequest(endpoint);request.timeout=12000;request.setThrottleParams({maxAttempts:1,slotInterval:1000}); const p=new JsonRpcProvider(request,CHAIN_ID,{staticNetwork:true}); try{ if(await p.send('eth_chainId',[])!=='0x89')throw Error('chain_mismatch'); const b=await p.getBlock('finalized'); if(!b||Date.now()/1000-b.timestamp>MAX_STALE_S)throw Error('finalized_stale'); const c=new Contract(REGISTRY,ABI,p); const token=deriveFNS(name); const owner=await c.ownerOf(token,{blockTag:b.number}); const keys=Array.from(await c.getAllKeys(token,{blockTag:b.number})); if(keys.length>MAX_RECORDS)throw Error('record_bounds'); const values=Array.from(await c.getManyRecords(keys,token,{blockTag:b.number})); return {endpoint,blockNumber:b.number,blockHash:b.hash,owner,records:Object.fromEntries(keys.map((k,i)=>[k,values[i]]))}; }finally{p.destroy();} } // Returns {name, ip, cid, owner, blockNumber}. ip = "record.A.0" if it is an IPv4, cid = "token.IPFS.0" if valid. async function resolveName(name,rpcs){ rpcs=rpcs||DEFAULT_RPCS; const canon=r=>JSON.stringify([r.owner.toLowerCase(),Object.entries(r.records).sort()]); const ok=[];let lastErr=null; const first=await Promise.allSettled(rpcs.slice(0,2).map(e=>readFrom(e,name))); for(const r of first){if(r.status==='fulfilled')ok.push(r.value);else lastErr=r.reason;} let agree=ok.length===2&&canon(ok[0])===canon(ok[1])?ok[0]:null; if(!agree){ for(const ep of rpcs.slice(2)){try{ok.push(await readFrom(ep,name));break;}catch(e){lastErr=e;}} outer:for(let i=0;i=2)throw Error('rpc_disagreement');throw lastErr||Error('rpc_unavailable');} } const ip=(agree.records['record.A.0']||'').trim(); const cidRaw=String(agree.records['token.IPFS.0']||'').trim(); if(!IPV4.test(ip)&&!CID.test(cidRaw))throw Error('no_a_record'); return {name,ip:IPV4.test(ip)?ip:'',cid:CID.test(cidRaw)?cidRaw:'',owner:agree.owner,blockNumber:Math.max(...ok.map(x=>x.blockNumber))}; } module.exports={resolveName,deriveFNS,REGISTRY,DEFAULT_RPCS}; if(require.main===module){ resolveName(process.argv[2]||'owndot.usa').then(r=>console.log(JSON.stringify(r,null,2))).catch(e=>{console.error('ERR',e.message);process.exit(1);}); }