/
Zns.ts
226 lines (202 loc) · 6.2 KB
/
Zns.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import sha256 from './utils/sha256';
import {
fromBech32Address,
toBech32Address,
toChecksumAddress,
} from './zns/utils';
import { invert, set } from './utils';
import {
Dictionary,
ResolutionResponse,
SourceDefinition,
UnclaimedDomainResponse,
ZnsResolution,
NamingServiceName,
isNullAddress,
nodeHash,
} from './types';
import { ResolutionError, ResolutionErrorCode } from './index';
import NamingService from './NamingService';
const DefaultSource = 'https://api.zilliqa.com';
const NetworkIdMap = {
mainnet: 1,
testnet: 333,
localnet: 111,
};
const RegistryMap = {
1: 'zil1jcgu2wlx6xejqk9jw3aaankw6lsjzeunx2j0jz',
};
const UrlMap = {
1: 'https://api.zilliqa.com',
333: 'https://dev-api.zilliqa.com',
111: 'http://localhost:4201',
};
const UrlNetworkMap = (url: string) => invert(UrlMap)[url];
/** @internal */
export default class Zns extends NamingService {
constructor(source: SourceDefinition = {}) {
super(source, NamingServiceName.ZNS);
}
async resolve(domain: string): Promise<ResolutionResponse | null> {
const recordAddresses = await this.getRecordsAddresses(domain);
if (!recordAddresses) return UnclaimedDomainResponse;
const [ownerAddress, resolverAddress] = recordAddresses;
const resolution = this.structureResolverRecords(
await this.getResolverRecords(resolverAddress),
);
const addresses: Record<string, string> = {};
if (resolution.crypto) {
Object.entries(resolution.crypto).forEach(
([key, v]) => v.address && (addresses[key] = v.address),
);
}
return {
addresses,
meta: {
owner: ownerAddress || null,
type: this.name,
ttl: parseInt(resolution.ttl as string) || 0,
},
records: resolution.records,
};
}
async owner(domain: string): Promise<string | null> {
const data = await this.resolve(domain);
return data ? data.meta.owner : null;
}
async record(domain: string, field: string) {
return await this.getRecordOrThrow(domain, field);
}
async allRecords(domain: string): Promise<Record<string, string>> {
const resolverAddress = await this.resolver(domain);
return await this.getResolverRecords(resolverAddress);
}
isSupportedDomain(domain: string): boolean {
const tokens = domain.split('.');
return (
!!tokens.length &&
tokens[tokens.length - 1] === 'zil' &&
tokens.every(v => !!v.length)
);
}
isSupportedNetwork(): boolean {
return this.registryAddress != null;
}
childhash(
parent: nodeHash,
label: string,
options: { prefix: boolean } = { prefix: true },
): nodeHash {
parent = parent.replace(/^0x/, '');
return sha256(parent + sha256(label, { hexPrefix: false }), {
hexPrefix: options.prefix,
inputEnc: 'hex',
});
}
async resolver(domain: string): Promise<string> {
const recordsAddresses = await this.getRecordsAddresses(domain);
if (!recordsAddresses || !recordsAddresses[0]) {
throw new ResolutionError(ResolutionErrorCode.UnregisteredDomain, {
domain: domain,
});
}
const [_, resolverAddress] = recordsAddresses;
if (isNullAddress(resolverAddress)) {
throw new ResolutionError(ResolutionErrorCode.UnspecifiedResolver, {
domain: domain,
});
}
return resolverAddress;
}
protected normalizeSource(
source: SourceDefinition | undefined,
): SourceDefinition {
source = { ...source };
source.network =
typeof source.network == 'string'
? NetworkIdMap[source.network]
: source.network || (source.url && UrlNetworkMap[source.url]) || 1;
if (!source.provider && !source.url) {
source.url =
typeof source.network === 'number' ? UrlMap[source.network] : undefined;
}
source.registry = source.registry || RegistryMap[source.network!];
if (source.registry?.startsWith('0x')) {
source.registry = toBech32Address(source.registry);
}
return source;
}
private async getRecordOrThrow(
domain: string,
field: string,
): Promise<string> {
const records = await this.allRecords(domain);
return this.ensureRecordPresence(domain, field, records[field]);
}
private async getRecordsAddresses(
domain: string,
): Promise<[string, string] | undefined> {
if (!this.isSupportedDomain(domain) || !this.isSupportedNetwork()) {
return undefined;
}
const registryRecord = await this.getContractMapValue(
this.registryAddress!,
'records',
this.namehash(domain),
);
if (!registryRecord) return undefined;
let [ownerAddress, resolverAddress] = registryRecord.arguments as [
string,
string,
];
if (ownerAddress.startsWith('0x')) {
ownerAddress = toBech32Address(ownerAddress);
}
return [ownerAddress, resolverAddress];
}
private async getResolverRecords(
resolverAddress: string,
): Promise<ZnsResolution> {
if (isNullAddress(resolverAddress)) {
return {};
}
const resolver = toChecksumAddress(resolverAddress);
return ((await this.getContractField(resolver, 'records')) ||
{}) as Dictionary<string>;
}
private structureResolverRecords(records: Dictionary<string>): ZnsResolution {
const result = {};
for (const [key, value] of Object.entries(records)) {
set(result, key, value);
}
return result;
}
private async fetchSubState(
contractAddress: string,
field: string,
keys: string[] = [],
): Promise<any> {
const params = [contractAddress.replace('0x', ''), field, keys];
const method = 'GetSmartContractSubState';
return await this.provider.request({ method, params });
}
private async getContractField(
contractAddress: string,
field: string,
keys: string[] = [],
): Promise<any> {
const contractAddr = contractAddress.startsWith('zil1')
? fromBech32Address(contractAddress)
: contractAddress;
const result = (await this.fetchSubState(contractAddr, field, keys)) || {};
return result[field];
}
private async getContractMapValue(
contractAddress: string,
field: string,
key: string,
): Promise<any> {
const record = await this.getContractField(contractAddress, field, [key]);
return (record && record[key]) || null;
}
}