@beclab/olaresid 0.1.13 → 0.2.1

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.
Files changed (182) hide show
  1. package/CLI-TREE.md +107 -0
  2. package/CLI.md +122 -1340
  3. package/README.md +30 -12
  4. package/SDK-TREE.md +151 -0
  5. package/TAG.md +95 -41
  6. package/config.json +6 -4
  7. package/dist/abi/TerminusDIDQueryABI.d.ts +397 -0
  8. package/dist/abi/TerminusDIDQueryABI.d.ts.map +1 -0
  9. package/dist/abi/TerminusDIDQueryABI.js +519 -0
  10. package/dist/abi/TerminusDIDQueryABI.js.map +1 -0
  11. package/dist/business/index.d.ts.map +1 -1
  12. package/dist/business/index.js +9 -23
  13. package/dist/business/index.js.map +1 -1
  14. package/dist/business/tag-context.d.ts +1 -0
  15. package/dist/business/tag-context.d.ts.map +1 -1
  16. package/dist/business/tag-context.js +13 -7
  17. package/dist/business/tag-context.js.map +1 -1
  18. package/dist/cli.js +177 -76
  19. package/dist/cli.js.map +1 -1
  20. package/dist/config/index.d.ts +16 -4
  21. package/dist/config/index.d.ts.map +1 -1
  22. package/dist/config/index.js +28 -14
  23. package/dist/config/index.js.map +1 -1
  24. package/dist/domain/core.d.ts +65 -0
  25. package/dist/domain/core.d.ts.map +1 -0
  26. package/dist/domain/core.js +317 -0
  27. package/dist/domain/core.js.map +1 -0
  28. package/dist/domain/index.d.ts +104 -57
  29. package/dist/domain/index.d.ts.map +1 -1
  30. package/dist/domain/index.js +188 -428
  31. package/dist/domain/index.js.map +1 -1
  32. package/dist/domain/types.d.ts +56 -0
  33. package/dist/domain/types.d.ts.map +1 -0
  34. package/dist/domain/types.js +3 -0
  35. package/dist/domain/types.js.map +1 -0
  36. package/dist/index.d.ts +81 -23
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +158 -143
  39. package/dist/index.js.map +1 -1
  40. package/dist/utils/crypto-utils.d.ts +110 -0
  41. package/dist/utils/crypto-utils.d.ts.map +1 -1
  42. package/dist/utils/crypto-utils.js +127 -8
  43. package/dist/utils/crypto-utils.js.map +1 -1
  44. package/dist/utils/error-parser.d.ts.map +1 -1
  45. package/dist/utils/error-parser.js +2 -1
  46. package/dist/utils/error-parser.js.map +1 -1
  47. package/dist/utils/event-parser.d.ts +161 -0
  48. package/dist/utils/event-parser.d.ts.map +1 -0
  49. package/dist/utils/event-parser.js +140 -0
  50. package/dist/utils/event-parser.js.map +1 -0
  51. package/dist/utils/tag-type-builder.d.ts +43 -0
  52. package/dist/utils/tag-type-builder.d.ts.map +1 -1
  53. package/dist/utils/tag-type-builder.js +122 -0
  54. package/dist/utils/tag-type-builder.js.map +1 -1
  55. package/dist/utils/tag-type-parser.d.ts +70 -0
  56. package/dist/utils/tag-type-parser.d.ts.map +1 -0
  57. package/dist/utils/tag-type-parser.js +190 -0
  58. package/dist/utils/tag-type-parser.js.map +1 -0
  59. package/examples/create-with-rpc-demo.ts +142 -0
  60. package/examples/fetch-all-flat-demo.ts +159 -0
  61. package/examples/fetch-by-indices-demo.ts +235 -0
  62. package/examples/fetch-domain-demo.ts +137 -0
  63. package/examples/fetch-domains-demo.ts +221 -0
  64. package/examples/frontend-demo/index.html +2 -2
  65. package/examples/frontend-demo/package-lock.json +4 -1
  66. package/examples/index.ts +3 -5
  67. package/jest.config.js +25 -0
  68. package/package.json +6 -2
  69. package/src/abi/TerminusDIDQueryABI.ts +516 -0
  70. package/src/business/index.ts +9 -33
  71. package/src/business/tag-context.ts +35 -7
  72. package/src/cli.ts +253 -90
  73. package/src/config/index.ts +34 -19
  74. package/src/domain/core.ts +382 -0
  75. package/src/domain/index.ts +271 -641
  76. package/src/domain/types.ts +59 -0
  77. package/src/index.ts +230 -207
  78. package/src/utils/crypto-utils.ts +205 -2
  79. package/src/utils/error-parser.ts +2 -1
  80. package/src/utils/event-parser.ts +353 -0
  81. package/src/utils/tag-type-builder.ts +138 -0
  82. package/src/utils/tag-type-parser.ts +246 -0
  83. package/tests/unit/crypto-utils.test.ts +338 -0
  84. package/tests/unit/ed25519-jwk.test.ts +201 -0
  85. package/tests/unit/event-parser.test.ts +690 -0
  86. package/tests/unit/generate-mnemonic.test.ts +268 -0
  87. package/tests/unit/olares-id-format.test.ts +321 -0
  88. package/tests/unit/tag-type-parser.test.ts +802 -0
  89. package/tests/unit/tag-types.test.ts +821 -0
  90. package/tests/unit/version.test.ts +14 -0
  91. package/tsconfig.json +3 -2
  92. package/dist/abi/ABITypeABI.d.ts +0 -88
  93. package/dist/abi/ABITypeABI.d.ts.map +0 -1
  94. package/dist/abi/ABITypeABI.js +0 -382
  95. package/dist/abi/ABITypeABI.js.map +0 -1
  96. package/dist/abi/RegistryABI.d.ts +0 -77
  97. package/dist/abi/RegistryABI.d.ts.map +0 -1
  98. package/dist/abi/RegistryABI.js +0 -462
  99. package/dist/abi/RegistryABI.js.map +0 -1
  100. package/dist/tag/address.d.ts +0 -11
  101. package/dist/tag/address.d.ts.map +0 -1
  102. package/dist/tag/address.js +0 -44
  103. package/dist/tag/address.js.map +0 -1
  104. package/dist/tag/array.d.ts +0 -14
  105. package/dist/tag/array.d.ts.map +0 -1
  106. package/dist/tag/array.js +0 -72
  107. package/dist/tag/array.js.map +0 -1
  108. package/dist/tag/bool.d.ts +0 -11
  109. package/dist/tag/bool.d.ts.map +0 -1
  110. package/dist/tag/bool.js +0 -43
  111. package/dist/tag/bool.js.map +0 -1
  112. package/dist/tag/bytes.d.ts +0 -11
  113. package/dist/tag/bytes.d.ts.map +0 -1
  114. package/dist/tag/bytes.js +0 -37
  115. package/dist/tag/bytes.js.map +0 -1
  116. package/dist/tag/flarray.d.ts +0 -15
  117. package/dist/tag/flarray.d.ts.map +0 -1
  118. package/dist/tag/flarray.js +0 -81
  119. package/dist/tag/flarray.js.map +0 -1
  120. package/dist/tag/flbytes.d.ts +0 -11
  121. package/dist/tag/flbytes.d.ts.map +0 -1
  122. package/dist/tag/flbytes.js +0 -47
  123. package/dist/tag/flbytes.js.map +0 -1
  124. package/dist/tag/index.d.ts +0 -32
  125. package/dist/tag/index.d.ts.map +0 -1
  126. package/dist/tag/index.js +0 -121
  127. package/dist/tag/index.js.map +0 -1
  128. package/dist/tag/int.d.ts +0 -12
  129. package/dist/tag/int.d.ts.map +0 -1
  130. package/dist/tag/int.js +0 -49
  131. package/dist/tag/int.js.map +0 -1
  132. package/dist/tag/string.d.ts +0 -11
  133. package/dist/tag/string.d.ts.map +0 -1
  134. package/dist/tag/string.js +0 -37
  135. package/dist/tag/string.js.map +0 -1
  136. package/dist/tag/tag.d.ts +0 -67
  137. package/dist/tag/tag.d.ts.map +0 -1
  138. package/dist/tag/tag.js +0 -157
  139. package/dist/tag/tag.js.map +0 -1
  140. package/dist/tag/tuple.d.ts +0 -17
  141. package/dist/tag/tuple.d.ts.map +0 -1
  142. package/dist/tag/tuple.js +0 -162
  143. package/dist/tag/tuple.js.map +0 -1
  144. package/dist/tag/uint.d.ts +0 -12
  145. package/dist/tag/uint.d.ts.map +0 -1
  146. package/dist/tag/uint.js +0 -49
  147. package/dist/tag/uint.js.map +0 -1
  148. package/dist/test/did.d.ts +0 -2
  149. package/dist/test/did.d.ts.map +0 -1
  150. package/dist/test/did.js +0 -177
  151. package/dist/test/did.js.map +0 -1
  152. package/dist/utils/tag-abi-codec.d.ts +0 -69
  153. package/dist/utils/tag-abi-codec.d.ts.map +0 -1
  154. package/dist/utils/tag-abi-codec.js +0 -144
  155. package/dist/utils/tag-abi-codec.js.map +0 -1
  156. package/examples/crypto-utilities.ts +0 -140
  157. package/examples/ed25519-jwk.ts +0 -73
  158. package/examples/generate-mnemonic.ts +0 -149
  159. package/examples/legacy.ts +0 -33
  160. package/examples/olares-id-format.ts +0 -197
  161. package/examples/tag-builder.ts +0 -235
  162. package/examples/tag-nested-tuple.ts +0 -190
  163. package/examples/tag-simple.ts +0 -149
  164. package/examples/tag-tagger.ts +0 -217
  165. package/examples/test-nested-tuple-conversion.ts +0 -143
  166. package/examples/test-type-bytes-parser.ts +0 -70
  167. package/src/abi/ABITypeABI.ts +0 -379
  168. package/src/abi/RegistryABI.ts +0 -459
  169. package/src/tag/address.ts +0 -48
  170. package/src/tag/array.ts +0 -80
  171. package/src/tag/bool.ts +0 -43
  172. package/src/tag/bytes.ts +0 -38
  173. package/src/tag/flarray.ts +0 -99
  174. package/src/tag/flbytes.ts +0 -48
  175. package/src/tag/index.ts +0 -170
  176. package/src/tag/int.ts +0 -51
  177. package/src/tag/string.ts +0 -38
  178. package/src/tag/tag.ts +0 -229
  179. package/src/tag/tuple.ts +0 -193
  180. package/src/tag/uint.ts +0 -51
  181. package/src/test/did.ts +0 -346
  182. package/src/utils/tag-abi-codec.ts +0 -158
@@ -1,436 +1,196 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ /**
3
+ * Domain fetching functions
4
+ *
5
+ * This module provides three main functions for fetching domain data:
6
+ * 1. fetchDomain - Fetch a single domain by name or tokenId
7
+ * 2. fetchDomains - Fetch multiple domains with pagination
8
+ * 3. fetchAllFlat - Fetch all domains with flat structure
9
+ */
5
10
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.PackageDomain = void 0;
7
- const ethers_1 = require("ethers");
8
- const index_1 = __importDefault(require("../tag/index"));
9
- const debug_1 = require("../debug");
10
- const getBase64 = (data) => {
11
- const hex = data;
12
- const arr = [];
13
- for (let i = 0; i < hex.length; i += 2) {
14
- const code = parseInt(hex.slice(i, i + 2), 16);
15
- arr.push(code);
11
+ exports.fetchDomain = fetchDomain;
12
+ exports.fetchDomains = fetchDomains;
13
+ exports.fetchDomainsByIndices = fetchDomainsByIndices;
14
+ exports.fetchAllFlat = fetchAllFlat;
15
+ const core_1 = require("./core");
16
+ /**
17
+ * Fetch a single domain by name or tokenId
18
+ *
19
+ * @param console - DIDConsole instance
20
+ * @param nameOrTokenId - Domain name (e.g., "alice.olares.com") or tokenId (hex string or bigint)
21
+ * @param options - Fetch options
22
+ * @returns Domain data or null if not found
23
+ *
24
+ * @example
25
+ * // Fetch by domain name
26
+ * const domain = await fetchDomain(console, "alice.olares.com", { queryContractAddress });
27
+ *
28
+ * // Fetch by tokenId
29
+ * const domain = await fetchDomain(console, "0x123...", { queryContractAddress });
30
+ */
31
+ async function fetchDomain(console, nameOrTokenId, options = {}) {
32
+ const { queryContractAddress } = options;
33
+ if (!queryContractAddress) {
34
+ throw new Error('queryContractAddress is required');
16
35
  }
17
- debug_1.debug.info(arr);
18
- let str = '';
19
- for (let i = 0; i < arr.length; i++) {
20
- const char = String.fromCharCode(arr[i]);
21
- str += char;
36
+ // Step 1: Create query helper
37
+ const helper = new core_1.QueryContractHelper(queryContractAddress, console.getProvider());
38
+ // Step 2: Fetch single domain (supports both name and tokenId)
39
+ const rawDomain = await helper.getDomain(nameOrTokenId);
40
+ if (!rawDomain) {
41
+ return null;
22
42
  }
23
- debug_1.debug.info(str);
24
- const base64 = btoa(str);
25
- debug_1.debug.info(base64);
26
- return base64;
27
- };
28
- const getHex = (data) => {
29
- let hex = '';
30
- for (let i = 0; i < data.length; i++) {
31
- const code = data.charCodeAt(i);
32
- let hexCode = code.toString(16);
33
- if (hexCode.length < 2) {
34
- hexCode = '0' + hexCode;
35
- }
36
- hex += hexCode;
43
+ // Step 3: Collect field name hashes from this domain's tags
44
+ const fieldNameHashes = (0, core_1.collectFieldNameHashes)([rawDomain]);
45
+ // Step 4: Batch fetch field names
46
+ const contract = console.getContractDID();
47
+ const fieldNamesMap = await (0, core_1.batchFetchFieldNames)(contract, fieldNameHashes);
48
+ // Step 5: Parse domain (no parentId calculation for single domain)
49
+ const domain = (0, core_1.parseDomain)(rawDomain, fieldNamesMap);
50
+ return domain;
51
+ }
52
+ /**
53
+ * Fetch multiple domains with pagination
54
+ * Allows you to fetch a specific range of domains with offset and limit
55
+ *
56
+ * @param console - DIDConsole instance
57
+ * @param options - Fetch options including offset and limit
58
+ * @returns Array of domains in the specified range
59
+ *
60
+ * @example
61
+ * // Fetch first 10 domains
62
+ * const domains = await fetchDomains(console, {
63
+ * queryContractAddress: "0x...",
64
+ * offset: 0,
65
+ * limit: 10
66
+ * });
67
+ *
68
+ * // Fetch next 10 domains
69
+ * const nextDomains = await fetchDomains(console, {
70
+ * queryContractAddress: "0x...",
71
+ * offset: 10,
72
+ * limit: 10
73
+ * });
74
+ */
75
+ async function fetchDomains(console, options) {
76
+ const { queryContractAddress, offset, limit } = options;
77
+ if (!queryContractAddress) {
78
+ throw new Error('queryContractAddress is required');
37
79
  }
38
- debug_1.debug.info(hex);
39
- return hex;
40
- };
41
- var PackageDomain;
42
- (function (PackageDomain) {
43
- class Domain {
44
- constructor(id, name, did, note, allowSubdomain, owner, subdomains, tags) {
45
- this.id = id;
46
- this.name = name;
47
- this.did = did;
48
- this.note = note;
49
- this.allowSubdomain = allowSubdomain;
50
- this.owner = owner;
51
- this.subdomains = subdomains;
52
- this.tags = tags;
53
- }
80
+ if (offset < 0) {
81
+ throw new Error('offset must be >= 0');
54
82
  }
55
- PackageDomain.Domain = Domain;
56
- PackageDomain.syncById = (tokenId, contract) => new Promise(async (resolve, reject) => {
57
- let meta = undefined;
58
- let owner = undefined;
59
- let times = 0;
60
- while (tokenId == undefined ||
61
- meta == undefined ||
62
- owner == undefined) {
63
- try {
64
- meta = await contract.getMetadata(tokenId);
65
- owner = await contract.ownerOf(tokenId);
66
- }
67
- catch (error) {
68
- times++;
69
- if (times >= 5) {
70
- throw new Error('network error');
71
- }
72
- }
73
- }
74
- // debug.info('meta', meta);
75
- const domain = {
76
- id: ethers_1.ethers.toBeHex(tokenId),
77
- name: meta['0'],
78
- did: meta['1'],
79
- note: meta['2'],
80
- allowSubdomain: meta['3'],
81
- subdomains: [],
82
- owner: owner,
83
- tags: []
84
- };
85
- const tags = await PackageDomain.fetchAllTagType(domain, contract);
86
- domain.tags = tags;
87
- await PackageDomain.fetchAllTagValue(domain, contract);
88
- resolve(domain);
89
- });
90
- PackageDomain.syncByName = (name, contract) => new Promise(async (resolve, reject) => {
91
- let tokenId = await contract.tokenIdOf(name);
92
- debug_1.debug.info('syncByName', name, tokenId);
93
- if (tokenId == undefined) {
94
- resolve(undefined);
95
- }
96
- else {
97
- resolve(await PackageDomain.syncById(tokenId, contract));
98
- }
99
- });
100
- PackageDomain.syncByIndex = (index, contract) => new Promise(async (resolve, reject) => {
101
- let tokenId = undefined;
102
- let times = 0;
103
- while (tokenId == undefined) {
104
- try {
105
- tokenId = await contract.tokenByIndex(index);
106
- }
107
- catch (error) {
108
- times++;
109
- if (times >= 5) {
110
- throw new Error('network error');
111
- }
112
- }
113
- }
114
- resolve(await PackageDomain.syncById(tokenId, contract));
115
- });
116
- PackageDomain.buildTree = (allDomains) => {
117
- allDomains.forEach((item) => {
118
- const domains = PackageDomain.findSubdomain(item, allDomains);
119
- item.subdomains = domains;
120
- });
121
- return allDomains.filter((item) => item.name.split('.').length == 1);
122
- };
123
- PackageDomain.findSubdomain = (domain, allDomains) => {
124
- const arr = [];
125
- allDomains.forEach((item) => {
126
- if (item.name.endsWith('.' + domain.name) &&
127
- domain.name.split('.').length + 1 == item.name.split('.').length) {
128
- const subdomains = PackageDomain.findSubdomain(item, allDomains);
129
- item.subdomains = subdomains;
130
- arr.push(item);
131
- }
132
- });
133
- return arr;
134
- };
135
- PackageDomain.findASubtree = (name, allDomains) => {
136
- for (const domain of allDomains) {
137
- if (domain.name == name) {
138
- return domain;
139
- }
140
- }
141
- return undefined;
142
- };
143
- PackageDomain.findSubtreesByOwner = (owner, allDomains) => {
144
- let arr = [];
145
- arr.push(...allDomains.filter((d) => d.owner.toLocaleLowerCase() == owner.toLocaleLowerCase()));
146
- for (const d of allDomains) {
147
- let subArr = PackageDomain.findSubtreesByOwner(owner, d.subdomains);
148
- arr.push(...subArr);
149
- }
150
- return arr;
151
- };
152
- PackageDomain.findSubtreesByDid = (did, allDomains) => {
153
- let arr = [];
154
- arr.push(...allDomains.filter((d) => d.did.startsWith(did)));
155
- for (const d of allDomains) {
156
- let subArr = PackageDomain.findSubtreesByDid(did, d.subdomains);
157
- arr.push(...subArr);
158
- }
159
- return arr;
160
- };
161
- PackageDomain.fetchAllTagType = (domain, contract) => new Promise(async (resolve, reject) => {
162
- // debug.info('fetchAllTagType', domain);
163
- let d = domain.name.split('.');
164
- let fromArr = [''];
165
- for (let index = 1; index <= d.length; index++) {
166
- fromArr.push(d.slice(d.length - index).join('.'));
167
- }
168
- debug_1.debug.info('fromArr', fromArr);
169
- let arr = [];
170
- for (const from of fromArr) {
171
- debug_1.debug.group(from);
172
- let count = await contract.getDefinedTagCount(from);
173
- debug_1.debug.info('count', count);
174
- for (let i = 0; i < count; i++) {
175
- let name = await contract.getDefinedTagNameByIndex(from, i);
176
- debug_1.debug.info('name', name);
177
- arr.push({
178
- from: from,
179
- to: domain.name,
180
- name: name,
181
- valueFormated: undefined,
182
- valueSource: undefined
183
- });
184
- }
185
- debug_1.debug.groupEnd();
186
- }
187
- domain.tags = arr;
188
- resolve(domain.tags);
189
- });
190
- PackageDomain.fetchTagStructure = (tag, contract) => new Promise(async (resolve, reject) => {
191
- debug_1.debug.info('fetchTagStructure', tag.from, tag.to, tag.name);
192
- const tagRawType = await contract.getTagABIType(tag.from, tag.name);
193
- // debug.info(`tag type raw bytes:`);
194
- // debug.info(tagRawType);
195
- const tagType = index_1.default.doFormatType(tagRawType);
196
- // debug.info(`tag type:`);
197
- // debug.info(tagType);
198
- if (tagType
199
- .getAbiTypeString()
200
- .includes('tuple')) {
201
- let [_, fieldNamesHashs] = await contract.getTagType(tag.from, tag.name);
202
- let fieldNames = [];
203
- for (let hash of fieldNamesHashs) {
204
- let blockNum = await contract.getFieldNamesEventBlock(hash);
205
- // debug.info(`field name hash: ${hash}`);
206
- // debug.info(`block num: ${blockNum}`);
207
- const events = await contract.queryFilter('OffchainStringArray', Number(blockNum), Number(blockNum));
208
- for (let event of events) {
209
- // debug.info('event', event);
210
- if (hash == event.args.hash) {
211
- fieldNames.push(event.args.value);
212
- }
213
- }
214
- }
215
- // debug.info(`found field names:`);
216
- // debug.info(fieldNames);
217
- tagType.setFieldNames(fieldNames, 0);
218
- }
219
- resolve(tagType);
220
- });
221
- PackageDomain.fetchTagValue = (tag, contract) => new Promise(async (resolve, reject) => {
222
- try {
223
- debug_1.debug.info('fetchTagValue', tag.from, tag.to, tag.name);
224
- const tagRawType = await contract.getTagABIType(tag.from, tag.name);
225
- // debug.info(`tag type raw bytes:`);
226
- // debug.info(tagRawType);
227
- const tagType = index_1.default.doFormatType(tagRawType);
228
- // debug.info(`tag type:`);
229
- // debug.info(tagType);
230
- const rawData = await contract.getTagElem(tag.from, tag.to, tag.name, []);
231
- // debug.info(`tag raw value:`);
232
- // debug.info(rawData);
233
- tag.valueSource = rawData;
234
- let data = tagType.parseValue(rawData);
235
- data = data[0];
236
- debug_1.debug.info('tag value:');
237
- debug_1.debug.info(data);
238
- if (tagType
239
- .getAbiTypeString()
240
- .includes('tuple')) {
241
- let [_, fieldNamesHashs] = await contract.getTagType(tag.from, tag.name);
242
- let fieldNames = [];
243
- for (let hash of fieldNamesHashs) {
244
- let blockNum = await contract.getFieldNamesEventBlock(hash);
245
- // debug.info(`field name hash: ${hash}`);
246
- // debug.info(`block num: ${blockNum}`);
247
- const events = await contract.queryFilter('OffchainStringArray', Number(blockNum), Number(blockNum));
248
- for (let event of events) {
249
- // debug.info('event', event);
250
- if (hash == event.args.hash) {
251
- fieldNames.push(event.args.value);
252
- }
253
- }
254
- }
255
- // debug.info(`found field names:`);
256
- // debug.info(fieldNames);
257
- tagType.setFieldNames(fieldNames, 0);
258
- data = tagType.hydration(rawData);
259
- // data = data[0];
260
- // debug.info('tag value with field names:');
261
- // console.dir(data, { depth: null });
262
- }
263
- let strData = data;
264
- if (data !== null && data !== undefined && typeof data !== 'string') {
265
- strData = JSON.stringify(data);
266
- }
267
- tag.valueFormated = strData;
268
- debug_1.debug.info(`✅ Successfully fetched value for tag: ${tag.name}`);
269
- debug_1.debug.info('✅ Updated tag data:', tag);
270
- resolve(tag);
271
- }
272
- catch (error) {
273
- debug_1.debug.error(`❌ Failed to fetch value for tag "${tag.name}" (${tag.from} -> ${tag.to}): ${error instanceof Error ? error.message : String(error)}`);
274
- tag.valueFormated = null;
275
- tag.valueSource = null;
276
- resolve(tag);
277
- }
278
- });
279
- PackageDomain.fetchAllTagValue = (domain, contract) => new Promise(async (resolve, reject) => {
280
- for (const tag of domain.tags) {
281
- await PackageDomain.fetchTagValue(tag, contract);
282
- }
283
- resolve(domain.tags);
284
- });
285
- PackageDomain.defineTag = async (domain, tagName, value, contract, providerHolder) => {
286
- debug_1.debug.info('abitype', await value.getAbiType(providerHolder));
287
- debug_1.debug.info('field', await value.getFieldNames());
288
- await contract.defineTag(domain?.name, tagName, await value.getAbiType(providerHolder), await value.getFieldNames());
289
- };
290
- PackageDomain.getAllSubdoamin = (domain) => {
291
- let arr = [];
292
- for (const d of domain.subdomains) {
293
- arr.push(...PackageDomain.getAllSubdoamin(d));
294
- }
295
- arr.push(...domain.subdomains);
296
- return arr;
297
- };
298
- PackageDomain.fetchOfficialExtendedInformation = (domain, contract) => new Promise(async (resolve, reject) => {
299
- let ip = undefined;
300
- let ipStr = '';
301
- try {
302
- ip = (await contract.getDnsARecord(domain.name));
303
- ipStr = `${parseInt(ip.substring(2, 4), 16)}.${parseInt(ip.substring(4, 6), 16)}.${parseInt(ip.substring(6, 8), 16)}.${parseInt(ip.substring(8, 10), 16)}`;
304
- }
305
- catch (error) {
306
- debug_1.debug.info(error instanceof Error ? error.message : String(error));
307
- }
308
- let rsaKey = undefined;
309
- try {
310
- rsaKey = (await contract.getRsaPubKey(domain.name));
311
- }
312
- catch (error) {
313
- debug_1.debug.info(error instanceof Error ? error.message : String(error));
314
- }
315
- let pubKey = '';
316
- try {
317
- if (rsaKey != '0x' && rsaKey != undefined) {
318
- // debug.info('rsaKey:');
319
- const str = String.fromCharCode(...rsaKey
320
- .match(/.{1,2}/g)
321
- .map((byte) => parseInt(byte, 16)));
322
- const encoded = btoa(str);
323
- const base64 = getBase64(rsaKey.replaceAll('0x', ''));
324
- // debug.info(encoded);
325
- // debug.info(base64);
326
- pubKey = `-----BEGIN RSA PUBLIC KEY-----
327
- ${base64}
328
- -----END RSA PUBLIC KEY-----`;
329
- }
330
- }
331
- catch (error) {
332
- debug_1.debug.error(error instanceof Error ? error.message : String(error));
333
- }
334
- let authenticatedAddress = [];
335
- try {
336
- authenticatedAddress =
337
- await contract.getAuthenticationAddresses(domain.name);
338
- }
339
- catch (error) {
340
- debug_1.debug.error(error instanceof Error ? error.message : String(error));
341
- }
342
- // debug.info('authenticatedAddress:');
343
- // debug.info(authenticatedAddress);
344
- let latestDID = '';
345
- try {
346
- latestDID = await contract.getLatestDID(domain.name);
347
- }
348
- catch (error) {
349
- debug_1.debug.info(error instanceof Error ? error.message : String(error));
350
- }
351
- // debug.info('latestDID:', latestDID);
352
- const officialExt = {
353
- ip: ipStr,
354
- rsaKey: pubKey,
355
- authenticateds: authenticatedAddress,
356
- latestDID: latestDID
357
- };
358
- debug_1.debug.info('officialExt: ', officialExt);
359
- resolve(officialExt);
360
- });
361
- PackageDomain.updateIp = (domain, ipStr, contract) => new Promise(async (resolve, reject) => {
362
- debug_1.debug.info('updateIp', ipStr);
363
- const v2 = '((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))';
364
- const v3 = '((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5])).((d{1,2})|(1d{2})|(2[0-4]d)|(25[0-5]))';
365
- const reg = new RegExp(v3, 'g');
366
- const reg2 = new RegExp(v2, 'g');
367
- const isIp = ipStr.match(reg);
368
- const isIp2 = ipStr.match(reg2);
369
- if (isIp != null || isIp2 != null) {
370
- const ipArr = ipStr.split('.');
371
- const add0 = (str) => str.length == 1 ? '0' + str : str;
372
- const ipBytes = `0x${add0(parseInt(ipArr[0]).toString(16))}${add0(parseInt(ipArr[1]).toString(16))}${add0(parseInt(ipArr[2]).toString(16))}${add0(parseInt(ipArr[3]).toString(16))}`;
373
- debug_1.debug.info(ethers_1.ethers.getBytes(ipBytes));
374
- debug_1.debug.info(ipBytes);
375
- debug_1.debug.info(domain.name);
376
- await contract
377
- .setDnsARecord(domain.name, ipBytes)
378
- .then((resp) => {
379
- resolve('sumbit succeed');
380
- })
381
- .catch((error) => {
382
- debug_1.debug.info('error1:');
383
- debug_1.debug.info(error);
384
- reject(error.message);
385
- });
386
- }
387
- else {
388
- reject('ip format error');
83
+ if (limit <= 0) {
84
+ throw new Error('limit must be > 0');
85
+ }
86
+ // Step 1: Create query helper
87
+ const helper = new core_1.QueryContractHelper(queryContractAddress, console.getProvider());
88
+ // Step 2: Fetch domains in the specified range
89
+ const rawDomains = await helper.getAllDomains(offset, limit);
90
+ // Return empty array if no domains found
91
+ if (rawDomains.length === 0) {
92
+ return [];
93
+ }
94
+ // Step 3: Collect field name hashes
95
+ const fieldNameHashes = (0, core_1.collectFieldNameHashes)(rawDomains);
96
+ // Step 4: Batch fetch field names
97
+ const contract = console.getContractDID();
98
+ const fieldNamesMap = await (0, core_1.batchFetchFieldNames)(contract, fieldNameHashes);
99
+ // Step 5: Parse domains (with parentId calculation)
100
+ const flatDomains = (0, core_1.parseAllDomains)(rawDomains, fieldNamesMap);
101
+ return flatDomains;
102
+ }
103
+ /**
104
+ * Fetch multiple domains by their indices
105
+ * Useful for fetching specific domains when you know their positions
106
+ *
107
+ * @param console - DIDConsole instance
108
+ * @param indices - Array of domain indices (e.g., [5, 6, 9, 10])
109
+ * @param options - Fetch options
110
+ * @returns Array of domains corresponding to the specified indices
111
+ *
112
+ * @example
113
+ * // Fetch domains at specific indices
114
+ * const domains = await fetchDomainsByIndices(console, [5, 6, 9, 10], {
115
+ * queryContractAddress: "0x..."
116
+ * });
117
+ *
118
+ * // Result will contain domains at positions 5, 6, 9, and 10
119
+ * // indices[0] -> domains[0], indices[1] -> domains[1], etc.
120
+ */
121
+ async function fetchDomainsByIndices(console, indices, options = {}) {
122
+ const { queryContractAddress } = options;
123
+ if (!queryContractAddress) {
124
+ throw new Error('queryContractAddress is required');
125
+ }
126
+ if (!Array.isArray(indices) || indices.length === 0) {
127
+ throw new Error('indices must be a non-empty array');
128
+ }
129
+ if (indices.length > 100) {
130
+ throw new Error(`Too many indices: ${indices.length}. Maximum is 100. Please split into multiple calls.`);
131
+ }
132
+ // Validate all indices are non-negative
133
+ for (const index of indices) {
134
+ if (index < 0 || !Number.isInteger(index)) {
135
+ throw new Error(`Invalid index: ${index}. All indices must be non-negative integers`);
389
136
  }
390
- });
391
- PackageDomain.updateRSAPublicKey = (domain, rsaPublicKey, contract) => new Promise(async (resolve, reject) => {
392
- const regex1 = new RegExp('-----BEGIN PUBLIC KEY-----', 'g');
393
- const regex2 = new RegExp('-----END PUBLIC KEY-----', 'g');
394
- const regex3 = new RegExp('\n', 'g');
395
- const keyBase64 = rsaPublicKey
396
- .replace(regex1, '')
397
- .replace(regex2, '')
398
- .replace(regex3, '');
399
- const keyHex = getHex(atob(rsaPublicKey));
400
- debug_1.debug.info('keyHex:');
401
- debug_1.debug.info(keyHex);
402
- debug_1.debug.info(keyBase64);
403
- debug_1.debug.info(rsaPublicKey);
404
- await contract
405
- .setRsaPubKey(domain.name, `0x${keyHex}`)
406
- .then((resp) => {
407
- resolve('sumbit succeed');
408
- })
409
- .catch((error) => {
410
- reject(error.message);
411
- });
412
- });
413
- PackageDomain.setValue = (tag, data, contract) => new Promise(async (resolve, reject) => {
414
- await contract
415
- .addTag(tag.from, tag.to, tag.name, data)
416
- .then((resp) => {
417
- debug_1.debug.info(resp);
418
- resolve('sumbit succeed');
419
- })
420
- .catch((error) => {
421
- reject(error.message);
422
- });
423
- });
424
- PackageDomain.setTagger = (tag, tagger, contract) => new Promise(async (resolve, reject) => {
425
- await contract
426
- .setTagger(tag.from, tag.name, tagger)
427
- .then((resp) => {
428
- debug_1.debug.info(resp);
429
- resolve('sumbit succeed');
430
- })
431
- .catch((error) => {
432
- reject(error.message);
433
- });
434
- });
435
- })(PackageDomain || (exports.PackageDomain = PackageDomain = {}));
137
+ }
138
+ // Step 1: Create query helper
139
+ const helper = new core_1.QueryContractHelper(queryContractAddress, console.getProvider());
140
+ // Step 2: Fetch domains by indices (single RPC call)
141
+ const rawDomains = await helper.getDomainsByIndices(indices);
142
+ if (rawDomains.length === 0) {
143
+ return [];
144
+ }
145
+ // Step 3: Collect field name hashes
146
+ const fieldNameHashes = (0, core_1.collectFieldNameHashes)(rawDomains);
147
+ // Step 4: Batch fetch field names
148
+ const contract = console.getContractDID();
149
+ const fieldNamesMap = await (0, core_1.batchFetchFieldNames)(contract, fieldNameHashes);
150
+ // Step 5: Parse all domains
151
+ const domains = (0, core_1.parseAllDomains)(rawDomains, fieldNamesMap);
152
+ return domains;
153
+ }
154
+ /**
155
+ * Fetch all domains with flat structure using query contract
156
+ * Much more efficient than the old fetchAll method
157
+ *
158
+ * @param console - DIDConsole instance
159
+ * @param options - Fetch options
160
+ * @returns Array of all domains in flat structure
161
+ *
162
+ * @example
163
+ * const domains = await fetchAllFlat(console, {
164
+ * queryContractAddress: "0x...",
165
+ * batchSize: 100,
166
+ * onProgress: (current, total) => console.log(`${current}/${total}`)
167
+ * });
168
+ */
169
+ async function fetchAllFlat(console, options = {}) {
170
+ const { queryContractAddress, batchSize = 100, onProgress } = options;
171
+ if (!queryContractAddress) {
172
+ throw new Error('queryContractAddress is required');
173
+ }
174
+ // Step 1: Create query helper
175
+ const helper = new core_1.QueryContractHelper(queryContractAddress, console.getProvider());
176
+ // Step 2: Get total supply
177
+ const totalSupply = await helper.getTotalSupply();
178
+ onProgress?.(0, totalSupply);
179
+ // Step 3: Fetch all domains in batches
180
+ const allRawDomains = [];
181
+ for (let offset = 0; offset < totalSupply; offset += batchSize) {
182
+ const limit = Math.min(batchSize, totalSupply - offset);
183
+ const batch = await helper.getAllDomains(offset, limit);
184
+ allRawDomains.push(...batch);
185
+ onProgress?.(Math.min(offset + batchSize, totalSupply), totalSupply);
186
+ }
187
+ // Step 4: Collect all field name hashes
188
+ const fieldNameHashes = (0, core_1.collectFieldNameHashes)(allRawDomains);
189
+ // Step 5: Batch fetch field names
190
+ const contract = console.getContractDID();
191
+ const fieldNamesMap = await (0, core_1.batchFetchFieldNames)(contract, fieldNameHashes);
192
+ // Step 6: Parse all domains (with parentId calculation)
193
+ const flatDomains = (0, core_1.parseAllDomains)(allRawDomains, fieldNamesMap);
194
+ return flatDomains;
195
+ }
436
196
  //# sourceMappingURL=index.js.map