@ar.io/sdk 3.10.2 → 3.11.0-alpha.10

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 (114) hide show
  1. package/README.md +52 -0
  2. package/bundles/web.bundle.min.js +140 -132
  3. package/lib/cjs/cli/cli.js +137 -122
  4. package/lib/cjs/cli/commands/readCommands.js +6 -0
  5. package/lib/cjs/cli/options.js +12 -0
  6. package/lib/cjs/cli/utils.js +40 -11
  7. package/lib/cjs/common/ant-versions.js +5 -5
  8. package/lib/cjs/common/ant.js +5 -5
  9. package/lib/cjs/common/index.js +2 -0
  10. package/lib/cjs/common/io.js +106 -1
  11. package/lib/cjs/common/turbo.js +208 -0
  12. package/lib/cjs/common/wayfinder/gateways/trusted-gateways.js +106 -0
  13. package/lib/cjs/common/wayfinder/gateways.js +86 -0
  14. package/lib/cjs/common/wayfinder/index.js +44 -0
  15. package/lib/cjs/common/wayfinder/routers/priority.js +29 -0
  16. package/lib/cjs/common/wayfinder/routers/priority.test.js +155 -0
  17. package/lib/cjs/common/wayfinder/routers/random.js +23 -0
  18. package/lib/cjs/common/wayfinder/routers/random.test.js +25 -0
  19. package/lib/cjs/common/wayfinder/routers/simple-cache.js +25 -0
  20. package/lib/cjs/common/wayfinder/routers/simple-cache.test.js +41 -0
  21. package/lib/cjs/common/wayfinder/routers/static.js +14 -0
  22. package/lib/cjs/common/wayfinder/routers/static.test.js +14 -0
  23. package/lib/cjs/common/wayfinder/verification/data-root-verifier.js +139 -0
  24. package/lib/cjs/common/wayfinder/verification/hash-verifier.js +50 -0
  25. package/lib/cjs/common/wayfinder/wayfinder.js +596 -0
  26. package/lib/cjs/common/wayfinder/wayfinder.test.js +500 -0
  27. package/lib/cjs/types/ant.js +12 -1
  28. package/lib/cjs/types/index.js +1 -0
  29. package/lib/cjs/types/io.js +1 -1
  30. package/lib/cjs/types/wayfinder.js +3 -0
  31. package/lib/cjs/utils/ao.js +42 -0
  32. package/lib/cjs/utils/hash.js +56 -0
  33. package/lib/cjs/utils/random.js +30 -0
  34. package/lib/cjs/utils/url.js +28 -0
  35. package/lib/cjs/utils/url.test.js +24 -0
  36. package/lib/cjs/utils/utils.test.js +8 -8
  37. package/lib/cjs/version.js +1 -1
  38. package/lib/cjs/web/index.js +3 -1
  39. package/lib/esm/cli/cli.js +138 -123
  40. package/lib/esm/cli/commands/readCommands.js +5 -0
  41. package/lib/esm/cli/options.js +12 -0
  42. package/lib/esm/cli/utils.js +39 -11
  43. package/lib/esm/common/ant-versions.js +5 -5
  44. package/lib/esm/common/ant.js +5 -5
  45. package/lib/esm/common/index.js +2 -0
  46. package/lib/esm/common/io.js +106 -1
  47. package/lib/esm/common/turbo.js +200 -0
  48. package/lib/esm/common/wayfinder/gateways/trusted-gateways.js +102 -0
  49. package/lib/esm/common/wayfinder/gateways.js +80 -0
  50. package/lib/esm/common/wayfinder/index.js +28 -0
  51. package/lib/esm/common/wayfinder/routers/priority.js +25 -0
  52. package/lib/esm/common/wayfinder/routers/priority.test.js +153 -0
  53. package/lib/esm/common/wayfinder/routers/random.js +19 -0
  54. package/lib/esm/common/wayfinder/routers/random.test.js +23 -0
  55. package/lib/esm/common/wayfinder/routers/simple-cache.js +21 -0
  56. package/lib/esm/common/wayfinder/routers/simple-cache.test.js +39 -0
  57. package/lib/esm/common/wayfinder/routers/static.js +10 -0
  58. package/lib/esm/common/wayfinder/routers/static.test.js +12 -0
  59. package/lib/esm/common/wayfinder/verification/data-root-verifier.js +130 -0
  60. package/lib/esm/common/wayfinder/verification/hash-verifier.js +46 -0
  61. package/lib/esm/common/wayfinder/wayfinder.js +584 -0
  62. package/lib/esm/common/wayfinder/wayfinder.test.js +495 -0
  63. package/lib/esm/types/ant.js +11 -0
  64. package/lib/esm/types/index.js +1 -0
  65. package/lib/esm/types/io.js +1 -1
  66. package/lib/esm/types/wayfinder.js +2 -0
  67. package/lib/esm/utils/ao.js +42 -0
  68. package/lib/esm/utils/hash.js +50 -0
  69. package/lib/esm/utils/random.js +26 -0
  70. package/lib/esm/utils/url.js +24 -0
  71. package/lib/esm/utils/url.test.js +19 -0
  72. package/lib/esm/utils/utils.test.js +1 -1
  73. package/lib/esm/version.js +1 -1
  74. package/lib/esm/web/index.js +1 -1
  75. package/lib/types/cli/commands/antCommands.d.ts +3 -3
  76. package/lib/types/cli/commands/arnsPurchaseCommands.d.ts +1 -1
  77. package/lib/types/cli/commands/gatewayWriteCommands.d.ts +9 -9
  78. package/lib/types/cli/commands/readCommands.d.ts +2 -0
  79. package/lib/types/cli/commands/transfer.d.ts +3 -3
  80. package/lib/types/cli/options.d.ts +9 -0
  81. package/lib/types/cli/types.d.ts +3 -0
  82. package/lib/types/cli/utils.d.ts +4 -0
  83. package/lib/types/common/ant-versions.d.ts +3 -6
  84. package/lib/types/common/index.d.ts +1 -0
  85. package/lib/types/common/io.d.ts +13 -8
  86. package/lib/types/common/turbo.d.ts +62 -0
  87. package/lib/types/common/wayfinder/gateways/trusted-gateways.d.ts +51 -0
  88. package/lib/types/common/wayfinder/gateways.d.ts +53 -0
  89. package/lib/types/common/wayfinder/index.d.ts +23 -0
  90. package/lib/types/common/wayfinder/routers/priority.d.ts +29 -0
  91. package/lib/types/common/wayfinder/routers/priority.test.d.ts +1 -0
  92. package/lib/types/common/wayfinder/routers/random.d.ts +27 -0
  93. package/lib/types/common/wayfinder/routers/random.test.d.ts +1 -0
  94. package/lib/types/common/wayfinder/routers/simple-cache.d.ts +28 -0
  95. package/lib/types/common/wayfinder/routers/simple-cache.test.d.ts +1 -0
  96. package/lib/types/common/wayfinder/routers/static.d.ts +24 -0
  97. package/lib/types/common/wayfinder/routers/static.test.d.ts +1 -0
  98. package/lib/types/common/wayfinder/verification/data-root-verifier.d.ts +31 -0
  99. package/lib/types/common/wayfinder/verification/hash-verifier.d.ts +27 -0
  100. package/lib/types/common/wayfinder/wayfinder.d.ts +265 -0
  101. package/lib/types/common/wayfinder/wayfinder.test.d.ts +1 -0
  102. package/lib/types/types/ant.d.ts +53 -1
  103. package/lib/types/types/common.d.ts +7 -2
  104. package/lib/types/types/index.d.ts +1 -0
  105. package/lib/types/types/io.d.ts +23 -6
  106. package/lib/types/types/wayfinder.d.ts +62 -0
  107. package/lib/types/utils/ao.d.ts +1 -12
  108. package/lib/types/utils/hash.d.ts +4 -0
  109. package/lib/types/utils/random.d.ts +7 -0
  110. package/lib/types/utils/url.d.ts +19 -0
  111. package/lib/types/utils/url.test.d.ts +1 -0
  112. package/lib/types/version.d.ts +1 -1
  113. package/lib/types/web/index.d.ts +1 -1
  114. package/package.json +5 -3
@@ -0,0 +1,500 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const axios_1 = __importDefault(require("axios"));
7
+ const got_1 = __importDefault(require("got"));
8
+ const node_assert_1 = __importDefault(require("node:assert"));
9
+ const node_events_1 = require("node:events");
10
+ const node_stream_1 = require("node:stream");
11
+ const consumers_1 = require("node:stream/consumers");
12
+ const node_test_1 = require("node:test");
13
+ const logger_js_1 = require("../../common/logger.js");
14
+ const random_js_1 = require("./routers/random.js");
15
+ const static_js_1 = require("./routers/static.js");
16
+ const wayfinder_js_1 = require("./wayfinder.js");
17
+ // TODO: replace with locally running gateway
18
+ const gatewayUrl = 'permagate.io';
19
+ const stubbedGatewaysProvider = {
20
+ getGateways: async () => [new URL(`http://${gatewayUrl}`)],
21
+ };
22
+ logger_js_1.Logger.default.setLogLevel('none');
23
+ (0, node_test_1.describe)('Wayfinder', () => {
24
+ node_test_1.describe.skip('http wrapper', () => {
25
+ (0, node_test_1.describe)('fetch', () => {
26
+ let wayfinder;
27
+ (0, node_test_1.before)(() => {
28
+ wayfinder = new wayfinder_js_1.Wayfinder({
29
+ httpClient: fetch,
30
+ router: new random_js_1.RandomGatewayRouter({
31
+ gatewaysProvider: stubbedGatewaysProvider,
32
+ }),
33
+ });
34
+ });
35
+ (0, node_test_1.it)('should fetch the data using the selected gateway', async () => {
36
+ const nativeFetch = await fetch(`https://ao.${gatewayUrl}`);
37
+ const response = await wayfinder.request('ar://ao');
38
+ node_assert_1.default.strictEqual(response.status, 200);
39
+ node_assert_1.default.strictEqual(response.status, nativeFetch.status);
40
+ // assert the arns headers are the same
41
+ const arnsHeaders = Array.from(response.headers.entries()).filter(([key]) => key.startsWith('x-arns-'));
42
+ const nativeFetchHeaders = Array.from(nativeFetch.headers.entries()).filter(([key]) => key.startsWith('x-arns-'));
43
+ node_assert_1.default.deepStrictEqual(arnsHeaders, nativeFetchHeaders);
44
+ });
45
+ (0, node_test_1.it)('should fetch a tx id using the selected gateway', async () => {
46
+ const nativeFetch = await fetch(`https://${gatewayUrl}/KKmRbIfrc7wiLcG0zvY1etlO0NBx1926dSCksxCIN3A`,
47
+ // follow redirects
48
+ { redirect: 'follow' });
49
+ const response = await wayfinder.request('ar://KKmRbIfrc7wiLcG0zvY1etlO0NBx1926dSCksxCIN3A', { redirect: 'follow' });
50
+ node_assert_1.default.strictEqual(response.status, 200);
51
+ node_assert_1.default.strictEqual(response.status, nativeFetch.status);
52
+ });
53
+ (0, node_test_1.it)('should route a non-ar:// url as a normal fetch', async () => {
54
+ const [nativeFetch, response] = await Promise.all([
55
+ fetch(`https://${gatewayUrl}/`, {
56
+ method: 'HEAD',
57
+ }),
58
+ wayfinder.request(`https://${gatewayUrl}/`, {
59
+ method: 'HEAD',
60
+ }),
61
+ ]);
62
+ node_assert_1.default.strictEqual(response.status, 200);
63
+ node_assert_1.default.strictEqual(response.status, nativeFetch.status);
64
+ // TODO: ensure the headers are the same excluding unique headers
65
+ });
66
+ for (const api of ['/info', '/block/current']) {
67
+ (0, node_test_1.it)(`supports native arweave node apis ${api}`, async () => {
68
+ const [nativeFetch, response] = await Promise.all([
69
+ fetch(`https://${gatewayUrl}${api}`),
70
+ wayfinder.request(`ar://${api}`),
71
+ ]);
72
+ node_assert_1.default.strictEqual(response.status, 200);
73
+ node_assert_1.default.strictEqual(response.status, nativeFetch.status);
74
+ // TODO: ensure the headers are the same excluding unique headers
75
+ });
76
+ }
77
+ for (const api of ['/ar-io/info']) {
78
+ (0, node_test_1.it)(`supports native ario node gateway apis ${api}`, async () => {
79
+ const [nativeFetch, response] = await Promise.all([
80
+ fetch(`https://${gatewayUrl}${api}`),
81
+ wayfinder.request(`ar:///${api}`),
82
+ ]);
83
+ node_assert_1.default.strictEqual(response.status, 200);
84
+ node_assert_1.default.strictEqual(response.status, nativeFetch.status);
85
+ // TODO: ensure the headers are the same excluding unique headers
86
+ });
87
+ }
88
+ (0, node_test_1.it)('supports a post request to graphql', async () => {
89
+ const response = await wayfinder.request('ar:///graphql', {
90
+ method: 'POST',
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ },
94
+ body: JSON.stringify({
95
+ query: `
96
+ query {
97
+ transactions(
98
+ ids: ["xf958qhCNGfDme1FtoiD6DtMfDENDbtxZpjOM_1tsMM"]
99
+ ) {
100
+ edges {
101
+ cursor
102
+ node {
103
+ id
104
+ tags {
105
+ name
106
+ value
107
+ }
108
+ block {
109
+ height
110
+ timestamp
111
+ }
112
+ }
113
+ }
114
+ pageInfo {
115
+ hasNextPage
116
+ }
117
+ }
118
+ }
119
+ `,
120
+ }),
121
+ });
122
+ node_assert_1.default.strictEqual(response.status, 200);
123
+ });
124
+ node_test_1.it.skip('returns the error from the target gateway if the route is not found', async () => {
125
+ const [nativeFetch, response] = await Promise.all([
126
+ fetch(`https://${gatewayUrl}/ar-io/not-found`),
127
+ wayfinder.request('ar:///not-found'),
128
+ ]);
129
+ node_assert_1.default.strictEqual(response.status, nativeFetch.status);
130
+ node_assert_1.default.strictEqual(response.statusText, nativeFetch.statusText);
131
+ });
132
+ });
133
+ (0, node_test_1.describe)('axios', () => {
134
+ let wayfinder;
135
+ (0, node_test_1.before)(() => {
136
+ wayfinder = new wayfinder_js_1.Wayfinder({
137
+ httpClient: axios_1.default,
138
+ router: new random_js_1.RandomGatewayRouter({
139
+ gatewaysProvider: stubbedGatewaysProvider,
140
+ }),
141
+ });
142
+ });
143
+ (0, node_test_1.it)('should fetch the data using axios default function against the target gateway', async () => {
144
+ const [nativeAxios, response] = await Promise.all([
145
+ (0, axios_1.default)(`https://ao.${gatewayUrl}`),
146
+ wayfinder.request('ar://ao'),
147
+ ]);
148
+ node_assert_1.default.strictEqual(response.status, 200);
149
+ node_assert_1.default.strictEqual(response.status, nativeAxios.status);
150
+ // assert the arns headers are the same
151
+ const arnsHeaders = Object.entries(response.headers)
152
+ .sort()
153
+ .filter(([key]) => key.startsWith('x-arns-'));
154
+ const nativeAxiosHeaders = Object.entries(nativeAxios.headers).filter(([key]) => key.startsWith('x-arns-'));
155
+ node_assert_1.default.deepStrictEqual(arnsHeaders.sort(), nativeAxiosHeaders.sort());
156
+ });
157
+ (0, node_test_1.it)('should fetch the data using the axios.get method against the target gateway', async () => {
158
+ const [nativeAxios, response] = await Promise.all([
159
+ axios_1.default.get(`https://ao.${gatewayUrl}`),
160
+ wayfinder.request.get('ar://ao'),
161
+ ]);
162
+ node_assert_1.default.strictEqual(response.status, 200);
163
+ node_assert_1.default.strictEqual(response.status, nativeAxios.status);
164
+ // assert the arns headers are the same
165
+ const arnsHeaders = Object.entries(response.headers)
166
+ .sort()
167
+ .filter(([key]) => key.startsWith('x-arns-'));
168
+ const nativeAxiosHeaders = Object.entries(nativeAxios.headers).filter(([key]) => key.startsWith('x-arns-'));
169
+ node_assert_1.default.deepStrictEqual(arnsHeaders.sort(), nativeAxiosHeaders.sort());
170
+ });
171
+ (0, node_test_1.it)('should route a non-ar:// url as a normal axios request', async () => {
172
+ const [nativeAxios, response] = await Promise.all([
173
+ (0, axios_1.default)(`https://${gatewayUrl}/`),
174
+ wayfinder.request(`https://${gatewayUrl}/`),
175
+ ]);
176
+ node_assert_1.default.strictEqual(response.status, 200);
177
+ node_assert_1.default.strictEqual(response.status, nativeAxios.status);
178
+ // TODO: ensure the headers are the same excluding unique headers
179
+ });
180
+ for (const api of ['/info', '/block/current']) {
181
+ (0, node_test_1.it)(`supports native arweave node apis ${api}`, async () => {
182
+ const [nativeAxios, response] = await Promise.all([
183
+ (0, axios_1.default)(`https://${gatewayUrl}${api}`),
184
+ wayfinder.request(`ar://${api}`),
185
+ ]);
186
+ node_assert_1.default.strictEqual(response.status, 200);
187
+ node_assert_1.default.strictEqual(response.status, nativeAxios.status);
188
+ // TODO: ensure the headers are the same excluding unique headers
189
+ });
190
+ }
191
+ for (const api of ['/ar-io/info', '/ar-io/__gateway_metrics']) {
192
+ (0, node_test_1.it)(`supports native ario node gateway apis ${api}`, async () => {
193
+ const [nativeAxios, response] = await Promise.all([
194
+ (0, axios_1.default)(`https://${gatewayUrl}${api}`),
195
+ wayfinder.request(`ar:///${api}`),
196
+ ]);
197
+ node_assert_1.default.strictEqual(response.status, 200);
198
+ node_assert_1.default.strictEqual(response.status, nativeAxios.status);
199
+ // TODO: ensure the headers are the same excluding unique headers
200
+ });
201
+ }
202
+ node_test_1.it.skip('should return the error from the target gateway if the route is not found', async () => {
203
+ const axiosInstance = axios_1.default.create({
204
+ validateStatus: () => true, // don't throw so we can compare axios result with wrapped axios result
205
+ });
206
+ const wayfinder = new wayfinder_js_1.Wayfinder({
207
+ httpClient: axiosInstance,
208
+ router: new random_js_1.RandomGatewayRouter({
209
+ gatewaysProvider: stubbedGatewaysProvider,
210
+ }),
211
+ });
212
+ const [nativeAxios, response] = await Promise.all([
213
+ axiosInstance(`https://${gatewayUrl}/ar-io/not-found`),
214
+ wayfinder.request('ar:///not-found'),
215
+ ]);
216
+ node_assert_1.default.strictEqual(response.status, nativeAxios.status);
217
+ });
218
+ });
219
+ (0, node_test_1.describe)('got', () => {
220
+ let wayfinder;
221
+ (0, node_test_1.before)(() => {
222
+ wayfinder = new wayfinder_js_1.Wayfinder({
223
+ httpClient: got_1.default,
224
+ router: new random_js_1.RandomGatewayRouter({
225
+ gatewaysProvider: stubbedGatewaysProvider,
226
+ }),
227
+ });
228
+ });
229
+ (0, node_test_1.it)('should fetch the data using the got default function against the target gateway', async () => {
230
+ const [nativeGot, response] = await Promise.all([
231
+ (0, got_1.default)(`https://ao.${gatewayUrl}`),
232
+ wayfinder.request('ar://ao'),
233
+ ]);
234
+ node_assert_1.default.strictEqual(response.statusCode, 200);
235
+ node_assert_1.default.strictEqual(response.statusCode, nativeGot.statusCode);
236
+ node_assert_1.default.deepStrictEqual(response.body, nativeGot.body);
237
+ });
238
+ (0, node_test_1.it)('should stream the data using got.stream against the selected target gateway', async () => {
239
+ const nativeBuffer = await (0, consumers_1.buffer)(await got_1.default.stream(`https://ao.${gatewayUrl}`, { decompress: false }));
240
+ const wayfinderBuffer = await (0, consumers_1.buffer)(await wayfinder.request.stream('ar://ao', { decompress: false }));
241
+ node_assert_1.default.deepStrictEqual(wayfinderBuffer, nativeBuffer);
242
+ });
243
+ });
244
+ });
245
+ (0, node_test_1.describe)('events', () => {
246
+ (0, node_test_1.it)('should emit events on the wayfinder event emitter', async () => {
247
+ const wayfinder = new wayfinder_js_1.Wayfinder({
248
+ httpClient: fetch,
249
+ router: new static_js_1.StaticGatewayRouter({
250
+ gateway: `http://${gatewayUrl}`,
251
+ }),
252
+ verifier: {
253
+ // @ts-expect-error
254
+ verifyData: async (params) => {
255
+ return;
256
+ },
257
+ },
258
+ });
259
+ const events = [];
260
+ wayfinder.emitter.on('verification-failed', (event) => {
261
+ events.push({ type: 'verification-failed', ...event });
262
+ });
263
+ wayfinder.emitter.on('verification-progress', (event) => {
264
+ events.push({ type: 'verification-progress', ...event });
265
+ });
266
+ wayfinder.emitter.on('verification-passed', (event) => {
267
+ events.push({ type: 'verification-passed', ...event });
268
+ });
269
+ // request data and assert the event is emitted
270
+ const response = await wayfinder.request('ar://c7wkwt6TKgcWJUfgvpJ5q5qi4DIZyJ1_TqhjXgURh0U', {
271
+ redirect: 'follow',
272
+ });
273
+ // read the full response body to ensure the stream is fully consumed
274
+ await response.text();
275
+ node_assert_1.default.strictEqual(response.status, 200);
276
+ node_assert_1.default.ok(events.find((e) => e.type === 'verification-passed'), 'Should emit at least one verification-passed');
277
+ });
278
+ (0, node_test_1.it)('should execute callbacks provided to the wayfinder constructor', async () => {
279
+ let verificationFailed = false;
280
+ let verificationProgress = false;
281
+ let verificationPassed = false;
282
+ const wayfinder = new wayfinder_js_1.Wayfinder({
283
+ httpClient: fetch,
284
+ router: new static_js_1.StaticGatewayRouter({
285
+ gateway: `http://${gatewayUrl}`,
286
+ }),
287
+ events: {
288
+ onVerificationFailed: () => {
289
+ verificationFailed = true;
290
+ },
291
+ onVerificationProgress: () => {
292
+ verificationProgress = true;
293
+ },
294
+ onVerificationPassed: () => {
295
+ verificationPassed = true;
296
+ },
297
+ },
298
+ });
299
+ const response = await wayfinder.request('ar://c7wkwt6TKgcWJUfgvpJ5q5qi4DIZyJ1_TqhjXgURh0U', {
300
+ redirect: 'follow',
301
+ });
302
+ // read the full response body to ensure the stream is fully consumed
303
+ await response.text();
304
+ node_assert_1.default.strictEqual(response.status, 200);
305
+ node_assert_1.default.ok(verificationFailed === false, 'Should not emit verification-failed');
306
+ node_assert_1.default.ok(verificationProgress, 'Should emit verification-progress');
307
+ node_assert_1.default.ok(verificationPassed, 'Should emit verification-passed');
308
+ });
309
+ });
310
+ node_test_1.describe.skip('tapAndVerifyRequest', () => {
311
+ (0, node_test_1.describe)('Readable', () => {
312
+ (0, node_test_1.it)('should duplicate the stream, verify the first and return the second if verification passes', async () => {
313
+ // create a simple readable
314
+ const chunks = [
315
+ Buffer.from('foo'),
316
+ Buffer.from('bar'),
317
+ Buffer.from('baz'),
318
+ ];
319
+ const contentLength = chunks.reduce((sum, c) => sum + c.length, 0);
320
+ // a stream that will emit chunks
321
+ const originalStream = node_stream_1.Readable.from(chunks);
322
+ let seen = Buffer.alloc(0);
323
+ const verifyData = async ({ data,
324
+ // @ts-expect-error
325
+ txId, }) => {
326
+ return new Promise((resolve, reject) => {
327
+ data.on('data', (chunk) => {
328
+ seen = Buffer.concat([seen, chunk]);
329
+ });
330
+ data.on('end', () => {
331
+ // Should have seen exactly the full payload
332
+ node_assert_1.default.strictEqual(seen.length, contentLength);
333
+ resolve();
334
+ });
335
+ data.on('error', reject);
336
+ });
337
+ };
338
+ const txId = 'test-tx-1';
339
+ const emitter = new node_events_1.EventEmitter();
340
+ const events = [];
341
+ emitter.on('verification-progress', (e) => {
342
+ console.log('verification-progress', e);
343
+ events.push({ type: 'verification-progress', ...e });
344
+ });
345
+ emitter.on('verification-passed', (e) => events.push({ type: 'verification-passed', ...e }));
346
+ // tap with verification
347
+ const tapped = (0, wayfinder_js_1.tapAndVerifyStream)({
348
+ originalStream,
349
+ contentLength,
350
+ verifyData,
351
+ txId,
352
+ emitter,
353
+ });
354
+ // read the stream
355
+ const out = [];
356
+ for await (const chunk of tapped) {
357
+ out.push(chunk);
358
+ }
359
+ // assert the stream is the same
360
+ node_assert_1.default.strictEqual(Buffer.concat(out).toString(), Buffer.concat(chunks).toString(), 'The tapped stream should emit exactly the original data');
361
+ node_assert_1.default.ok(events.find((e) => e.type === 'verification-progress'), 'Should emit at least one verification-progress');
362
+ node_assert_1.default.ok(events.find((e) => e.type === 'verification-passed' && e.txId === txId), 'Should emit at least one verification-passed');
363
+ });
364
+ (0, node_test_1.it)('should throw an error on the client stream if verification fails', async () => {
365
+ const chunks = [
366
+ Buffer.from('foo'),
367
+ Buffer.from('bar'),
368
+ Buffer.from('baz'),
369
+ ];
370
+ const contentLength = chunks.reduce((sum, c) => sum + c.length, 0);
371
+ // a stream that will emit chunks
372
+ const originalStream = node_stream_1.Readable.from(chunks);
373
+ const verifyData = async ({
374
+ // @ts-expect-error
375
+ data, txId, }) => {
376
+ throw new Error('Verification failed for txId: ' + txId);
377
+ };
378
+ const txId = 'test-tx-1';
379
+ const emitter = new node_events_1.EventEmitter();
380
+ const events = [];
381
+ emitter.on('verification-progress', (e) => events.push({ type: 'verification-progress', ...e }));
382
+ emitter.on('verification-failed', (e) => events.push({ type: 'verification-failed', ...e }));
383
+ // tap with verification
384
+ const tapped = (0, wayfinder_js_1.tapAndVerifyStream)({
385
+ originalStream,
386
+ contentLength,
387
+ verifyData,
388
+ txId,
389
+ emitter,
390
+ });
391
+ // read the stream
392
+ try {
393
+ const out = [];
394
+ for await (const chunk of tapped) {
395
+ out.push(chunk);
396
+ }
397
+ }
398
+ catch (error) {
399
+ node_assert_1.default.ok(events.find((e) => e.type === 'verification-failed' && e.txId === txId), 'Should emit at least one verification-failed');
400
+ // stream should be closed
401
+ node_assert_1.default.ok(tapped.closed);
402
+ }
403
+ });
404
+ });
405
+ (0, node_test_1.describe)('ReadableStream', () => {
406
+ (0, node_test_1.it)('should duplicate the ReadableStream, verify the first and return the second if verification passes', async () => {
407
+ // create a simple readable
408
+ const chunks = [
409
+ Buffer.from('foo'),
410
+ Buffer.from('bar'),
411
+ Buffer.from('baz'),
412
+ ];
413
+ const contentLength = chunks.reduce((sum, c) => sum + c.length, 0);
414
+ // a stream that will emit chunks
415
+ const originalStream = ReadableStream.from(chunks);
416
+ let seen = Buffer.alloc(0);
417
+ const verifyData = async ({ data,
418
+ // @ts-expect-error
419
+ txId, }) => {
420
+ return new Promise(async (resolve, reject) => {
421
+ const reader = data.getReader();
422
+ while (true) {
423
+ try {
424
+ const { done, value } = await reader.read();
425
+ if (done) {
426
+ resolve();
427
+ break;
428
+ }
429
+ seen = Buffer.concat([seen, value]);
430
+ }
431
+ catch (error) {
432
+ reject(error);
433
+ }
434
+ }
435
+ });
436
+ };
437
+ const txId = 'test-tx-1';
438
+ const emitter = new node_events_1.EventEmitter();
439
+ const events = [];
440
+ emitter.on('verification-progress', (e) => events.push({ type: 'verification-progress', ...e }));
441
+ emitter.on('verification-passed', (e) => events.push({ type: 'verification-passed', ...e }));
442
+ // tap with verification
443
+ const tapped = (0, wayfinder_js_1.tapAndVerifyStream)({
444
+ originalStream,
445
+ contentLength,
446
+ verifyData,
447
+ txId,
448
+ emitter,
449
+ });
450
+ // read the stream
451
+ const out = [];
452
+ for await (const chunk of tapped) {
453
+ out.push(chunk);
454
+ }
455
+ // assert the stream is the same
456
+ node_assert_1.default.strictEqual(Buffer.concat(out).toString(), Buffer.concat(chunks).toString(), 'The tapped stream should emit exactly the original data');
457
+ node_assert_1.default.ok(events.find((e) => e.type === 'verification-progress'), 'Should emit at least one verification-progress');
458
+ node_assert_1.default.ok(events.find((e) => e.type === 'verification-passed' && e.txId === txId), 'Should emit at least one verification-passed');
459
+ });
460
+ (0, node_test_1.it)('should throw an error on the client stream if verification fails', async () => {
461
+ const chunks = [
462
+ Buffer.from('foo'),
463
+ Buffer.from('bar'),
464
+ Buffer.from('baz'),
465
+ ];
466
+ const contentLength = chunks.reduce((sum, c) => sum + c.length, 0);
467
+ // a stream that will emit chunks
468
+ const originalStream = ReadableStream.from(chunks);
469
+ const verifyData = async ({
470
+ // @ts-expect-error
471
+ data, txId, }) => {
472
+ throw new Error('Verification failed for txId: ' + txId);
473
+ };
474
+ const txId = 'test-tx-1';
475
+ const emitter = new node_events_1.EventEmitter();
476
+ const events = [];
477
+ emitter.on('verification-progress', (e) => events.push({ type: 'verification-progress', ...e }));
478
+ emitter.on('verification-failed', (e) => events.push({ type: 'verification-failed', ...e }));
479
+ // tap with verification
480
+ const tapped = (0, wayfinder_js_1.tapAndVerifyStream)({
481
+ originalStream,
482
+ contentLength,
483
+ verifyData,
484
+ txId,
485
+ emitter,
486
+ });
487
+ // read the stream
488
+ try {
489
+ const out = [];
490
+ for await (const chunk of tapped) {
491
+ out.push(chunk);
492
+ }
493
+ }
494
+ catch (error) {
495
+ node_assert_1.default.ok(events.find((e) => e.type === 'verification-failed' && e.txId === txId), 'Should emit at least one verification-failed');
496
+ }
497
+ });
498
+ });
499
+ });
500
+ });
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AntInfoSchema = exports.AntHandlersSchema = exports.AntHandlerNames = exports.AntWriteHandlers = exports.AntReadHandlers = exports.AntStateSchema = exports.AntBalancesSchema = exports.AntControllersSchema = exports.AntRecordsSchema = exports.AntRecordSchema = exports.AntKeywordsSchema = exports.AntDescriptionSchema = exports.IntegerStringSchema = exports.AOAddressSchema = exports.ArweaveTxIdSchema = void 0;
3
+ exports.AntInfoSchema = exports.AntHandlersSchema = exports.AntHandlerNames = exports.AntWriteHandlers = exports.AntReadHandlers = exports.SpawnANTStateSchema = exports.AntStateSchema = exports.AntBalancesSchema = exports.AntControllersSchema = exports.AntRecordsSchema = exports.AntRecordSchema = exports.AntKeywordsSchema = exports.AntDescriptionSchema = exports.IntegerStringSchema = exports.AOAddressSchema = exports.ArweaveTxIdSchema = void 0;
4
4
  exports.isAoANTState = isAoANTState;
5
5
  /**
6
6
  * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
@@ -81,6 +81,17 @@ exports.AntStateSchema = zod_1.z.object({
81
81
  .boolean()
82
82
  .describe('Flag indicating whether the ANT has been initialized.'),
83
83
  });
84
+ exports.SpawnANTStateSchema = zod_1.z.object({
85
+ name: zod_1.z.string().describe('The name of the ANT.'),
86
+ ticker: zod_1.z.string().describe('The ticker symbol for the ANT.'),
87
+ description: zod_1.z.string().describe('The description for the ANT.'),
88
+ keywords: exports.AntKeywordsSchema.describe('The keywords for the ANT.'),
89
+ owner: exports.AOAddressSchema.describe('The Owners address.'),
90
+ controllers: exports.AntControllersSchema.describe('Controllers of the ANT who have administrative privileges.'),
91
+ records: exports.AntRecordsSchema.describe('Records associated with the ANT.'),
92
+ balances: exports.AntBalancesSchema.describe('Balance details for each address holding the ANT.'),
93
+ logo: exports.ArweaveTxIdSchema.describe('Transaction ID of the ANT logo.'),
94
+ });
84
95
  exports.AntReadHandlers = [
85
96
  'balance',
86
97
  'balances',
@@ -35,3 +35,4 @@ __exportStar(require("./common.js"), exports);
35
35
  __exportStar(require("./faucet.js"), exports);
36
36
  __exportStar(require("./io.js"), exports);
37
37
  __exportStar(require("./token.js"), exports);
38
+ __exportStar(require("./wayfinder.js"), exports);
@@ -31,7 +31,7 @@ const isValidIntent = (intent) => {
31
31
  return exports.validIntents.indexOf(intent) !== -1;
32
32
  };
33
33
  exports.isValidIntent = isValidIntent;
34
- exports.fundFromOptions = ['balance', 'stakes', 'any'];
34
+ exports.fundFromOptions = ['balance', 'stakes', 'any', 'turbo'];
35
35
  const isValidFundFrom = (fundFrom) => {
36
36
  return exports.fundFromOptions.indexOf(fundFrom) !== -1;
37
37
  };
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // TODO: add an offset provider that returns offsets for data items so we can use them to verify the signatures of a data item within a bundle
@@ -30,8 +30,13 @@ const zod_1 = require("zod");
30
30
  const arweave_js_1 = require("../common/arweave.js");
31
31
  const index_js_1 = require("../common/index.js");
32
32
  const constants_js_1 = require("../constants.js");
33
+ const ant_js_1 = require("../types/ant.js");
34
+ const schema_js_1 = require("./schema.js");
33
35
  async function spawnANT({ signer, module = constants_js_1.AOS_MODULE_ID, ao = (0, aoconnect_1.connect)(), scheduler = constants_js_1.DEFAULT_SCHEDULER_ID, state, antRegistryId = constants_js_1.ANT_REGISTRY_ID, logger = index_js_1.Logger.default, authority = constants_js_1.AO_AUTHORITY, }) {
34
36
  // TODO: use On-Boot data handler for bootstrapping state instead of initialize-state
37
+ if (state) {
38
+ (0, schema_js_1.parseSchemaResult)(ant_js_1.SpawnANTStateSchema, state);
39
+ }
35
40
  const processId = await ao.spawn({
36
41
  module,
37
42
  scheduler,
@@ -49,6 +54,43 @@ async function spawnANT({ signer, module = constants_js_1.AOS_MODULE_ID, ao = (0
49
54
  },
50
55
  ],
51
56
  });
57
+ let bootRes;
58
+ let attempts = 0;
59
+ while (attempts < 5 && bootRes === undefined) {
60
+ try {
61
+ bootRes = await ao.result({
62
+ process: processId,
63
+ message: processId,
64
+ });
65
+ break;
66
+ }
67
+ catch (error) {
68
+ logger.debug('Retrying ANT boot result fetch', {
69
+ processId,
70
+ module,
71
+ scheduler,
72
+ attempts,
73
+ error,
74
+ });
75
+ attempts++;
76
+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempts ** 2));
77
+ }
78
+ }
79
+ if (bootRes === undefined ||
80
+ bootRes.Messages.find((m) => m.Tags.find((t) => t.value === 'Invalid-Boot-Notice'))) {
81
+ if (bootRes === undefined) {
82
+ throw new Error('Failed to get boot result');
83
+ }
84
+ const bootError = errorMessageFromOutput(bootRes);
85
+ logger.error('ANT failed to boot correctly', {
86
+ processId,
87
+ module,
88
+ scheduler,
89
+ bootRes,
90
+ bootError,
91
+ });
92
+ throw new Error(`ANT failed to boot correctly: ${bootError}`);
93
+ }
52
94
  logger.debug(`Spawned ANT`, {
53
95
  processId,
54
96
  module,
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hashBufferToB64Url = exports.hashReadableStreamToB64Url = exports.hashReadableToB64Url = void 0;
4
+ /**
5
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * http://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ const crypto_1 = require("crypto");
20
+ const base64_js_1 = require("./base64.js");
21
+ const hashReadableToB64Url = (stream, algorithm = 'sha256') => {
22
+ return new Promise((resolve, reject) => {
23
+ const hash = (0, crypto_1.createHash)(algorithm);
24
+ stream.on('data', (chunk) => hash.update(chunk));
25
+ stream.on('end', () => resolve((0, base64_js_1.toB64Url)(hash.digest())));
26
+ stream.on('error', (err) => reject(err));
27
+ });
28
+ };
29
+ exports.hashReadableToB64Url = hashReadableToB64Url;
30
+ const hashReadableStreamToB64Url = (stream, algorithm = 'sha256') => {
31
+ return new Promise((resolve, reject) => {
32
+ const hash = (0, crypto_1.createHash)(algorithm);
33
+ const reader = stream.getReader();
34
+ const read = async () => {
35
+ try {
36
+ const { done, value } = await reader.read();
37
+ if (done) {
38
+ resolve((0, base64_js_1.toB64Url)(hash.digest()));
39
+ }
40
+ else {
41
+ hash.update(value);
42
+ read();
43
+ }
44
+ }
45
+ catch (err) {
46
+ reject(err);
47
+ }
48
+ };
49
+ read().catch(reject);
50
+ });
51
+ };
52
+ exports.hashReadableStreamToB64Url = hashReadableStreamToB64Url;
53
+ const hashBufferToB64Url = (buffer, algorithm = 'sha256') => {
54
+ return (0, base64_js_1.toB64Url)((0, crypto_1.createHash)(algorithm).update(buffer).digest());
55
+ };
56
+ exports.hashBufferToB64Url = hashBufferToB64Url;