@ar.io/sdk 3.10.0 → 3.11.0-alpha.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 (96) hide show
  1. package/README.md +66 -125
  2. package/bundles/web.bundle.min.js +130 -125
  3. package/lib/cjs/cli/options.js +12 -0
  4. package/lib/cjs/cli/utils.js +32 -10
  5. package/lib/cjs/common/ant-versions.js +5 -5
  6. package/lib/cjs/common/index.js +2 -0
  7. package/lib/cjs/common/io.js +64 -1
  8. package/lib/cjs/common/turbo.js +208 -0
  9. package/lib/cjs/common/wayfinder/gateways.js +75 -0
  10. package/lib/cjs/common/wayfinder/index.js +36 -0
  11. package/lib/cjs/common/wayfinder/routers/fixed.js +14 -0
  12. package/lib/cjs/common/wayfinder/routers/fixed.test.js +14 -0
  13. package/lib/cjs/common/wayfinder/routers/priority.js +38 -0
  14. package/lib/cjs/common/wayfinder/routers/priority.test.js +155 -0
  15. package/lib/cjs/common/wayfinder/routers/random.js +23 -0
  16. package/lib/cjs/common/wayfinder/routers/random.test.js +104 -0
  17. package/lib/cjs/common/wayfinder/routers/simple-cache.js +25 -0
  18. package/lib/cjs/common/wayfinder/routers/simple-cache.test.js +41 -0
  19. package/lib/cjs/common/wayfinder/wayfinder.js +167 -0
  20. package/lib/cjs/common/wayfinder/wayfinder.test.js +253 -0
  21. package/lib/cjs/types/ant.js +12 -1
  22. package/lib/cjs/types/index.js +1 -0
  23. package/lib/cjs/types/io.js +1 -1
  24. package/lib/cjs/types/wayfinder.js +2 -0
  25. package/lib/cjs/utils/ao.js +5 -0
  26. package/lib/cjs/utils/random.js +30 -0
  27. package/lib/cjs/utils/url.js +28 -0
  28. package/lib/cjs/utils/url.test.js +24 -0
  29. package/lib/cjs/utils/utils.test.js +8 -8
  30. package/lib/cjs/version.js +1 -1
  31. package/lib/cjs/web/index.js +3 -1
  32. package/lib/esm/cli/options.js +12 -0
  33. package/lib/esm/cli/utils.js +31 -10
  34. package/lib/esm/common/ant-versions.js +5 -5
  35. package/lib/esm/common/index.js +2 -0
  36. package/lib/esm/common/io.js +64 -1
  37. package/lib/esm/common/turbo.js +200 -0
  38. package/lib/esm/common/wayfinder/gateways.js +69 -0
  39. package/lib/esm/common/wayfinder/index.js +20 -0
  40. package/lib/esm/common/wayfinder/routers/fixed.js +10 -0
  41. package/lib/esm/common/wayfinder/routers/fixed.test.js +12 -0
  42. package/lib/esm/common/wayfinder/routers/priority.js +34 -0
  43. package/lib/esm/common/wayfinder/routers/priority.test.js +153 -0
  44. package/lib/esm/common/wayfinder/routers/random.js +19 -0
  45. package/lib/esm/common/wayfinder/routers/random.test.js +102 -0
  46. package/lib/esm/common/wayfinder/routers/simple-cache.js +21 -0
  47. package/lib/esm/common/wayfinder/routers/simple-cache.test.js +39 -0
  48. package/lib/esm/common/wayfinder/wayfinder.js +161 -0
  49. package/lib/esm/common/wayfinder/wayfinder.test.js +248 -0
  50. package/lib/esm/types/ant.js +11 -0
  51. package/lib/esm/types/index.js +1 -0
  52. package/lib/esm/types/io.js +1 -1
  53. package/lib/esm/types/wayfinder.js +1 -0
  54. package/lib/esm/utils/ao.js +5 -0
  55. package/lib/esm/utils/random.js +26 -0
  56. package/lib/esm/utils/url.js +24 -0
  57. package/lib/esm/utils/url.test.js +19 -0
  58. package/lib/esm/utils/utils.test.js +1 -1
  59. package/lib/esm/version.js +1 -1
  60. package/lib/esm/web/index.js +1 -1
  61. package/lib/types/cli/commands/antCommands.d.ts +3 -3
  62. package/lib/types/cli/commands/arnsPurchaseCommands.d.ts +1 -1
  63. package/lib/types/cli/commands/gatewayWriteCommands.d.ts +9 -9
  64. package/lib/types/cli/commands/readCommands.d.ts +1 -0
  65. package/lib/types/cli/commands/transfer.d.ts +3 -3
  66. package/lib/types/cli/options.d.ts +9 -0
  67. package/lib/types/cli/types.d.ts +3 -0
  68. package/lib/types/cli/utils.d.ts +4 -0
  69. package/lib/types/common/ant-versions.d.ts +3 -6
  70. package/lib/types/common/index.d.ts +1 -0
  71. package/lib/types/common/io.d.ts +9 -7
  72. package/lib/types/common/turbo.d.ts +62 -0
  73. package/lib/types/common/wayfinder/gateways.d.ts +44 -0
  74. package/lib/types/common/wayfinder/index.d.ts +19 -0
  75. package/lib/types/common/wayfinder/routers/fixed.d.ts +24 -0
  76. package/lib/types/common/wayfinder/routers/fixed.test.d.ts +1 -0
  77. package/lib/types/common/wayfinder/routers/priority.d.ts +33 -0
  78. package/lib/types/common/wayfinder/routers/priority.test.d.ts +1 -0
  79. package/lib/types/common/wayfinder/routers/random.d.ts +27 -0
  80. package/lib/types/common/wayfinder/routers/random.test.d.ts +1 -0
  81. package/lib/types/common/wayfinder/routers/simple-cache.d.ts +28 -0
  82. package/lib/types/common/wayfinder/routers/simple-cache.test.d.ts +1 -0
  83. package/lib/types/common/wayfinder/wayfinder.d.ts +113 -0
  84. package/lib/types/common/wayfinder/wayfinder.test.d.ts +1 -0
  85. package/lib/types/types/ant.d.ts +53 -1
  86. package/lib/types/types/common.d.ts +7 -2
  87. package/lib/types/types/index.d.ts +1 -0
  88. package/lib/types/types/io.d.ts +7 -5
  89. package/lib/types/types/wayfinder.d.ts +19 -0
  90. package/lib/types/utils/ao.d.ts +1 -12
  91. package/lib/types/utils/random.d.ts +7 -0
  92. package/lib/types/utils/url.d.ts +19 -0
  93. package/lib/types/utils/url.test.d.ts +1 -0
  94. package/lib/types/version.d.ts +1 -1
  95. package/lib/types/web/index.d.ts +1 -1
  96. package/package.json +5 -3
@@ -0,0 +1,102 @@
1
+ import { strict as assert } from 'node:assert';
2
+ import { describe, it } from 'node:test';
3
+ import { RandomGatewayRouter } from './random.js';
4
+ describe('RandomRouter', () => {
5
+ const mockGateways = [
6
+ {
7
+ settings: {
8
+ fqdn: 'gateway1.net',
9
+ port: 443,
10
+ protocol: 'https',
11
+ allowDelegatedStaking: false,
12
+ delegateRewardShareRatio: 0.5,
13
+ allowedDelegates: [],
14
+ minDelegatedStake: 0,
15
+ autoStake: false,
16
+ properties: '',
17
+ label: '',
18
+ note: '',
19
+ },
20
+ gatewayAddress: 'addr1',
21
+ observerAddress: 'addr1',
22
+ totalDelegatedStake: 1000,
23
+ startTimestamp: 0,
24
+ endTimestamp: 0,
25
+ operatorStake: 100,
26
+ status: 'joined',
27
+ weights: {
28
+ normalizedCompositeWeight: 0.5,
29
+ stakeWeight: 0.5,
30
+ tenureWeight: 0.5,
31
+ gatewayPerformanceRatio: 0.5,
32
+ observerPerformanceRatio: 0.5,
33
+ compositeWeight: 0.5,
34
+ gatewayRewardRatioWeight: 0.5,
35
+ observerRewardRatioWeight: 0.5,
36
+ },
37
+ stats: {
38
+ passedConsecutiveEpochs: 10,
39
+ failedConsecutiveEpochs: 5,
40
+ totalEpochCount: 15,
41
+ passedEpochCount: 10,
42
+ failedEpochCount: 5,
43
+ observedEpochCount: 15,
44
+ prescribedEpochCount: 20,
45
+ },
46
+ },
47
+ {
48
+ settings: {
49
+ fqdn: 'gateway2.net',
50
+ port: 443,
51
+ protocol: 'https',
52
+ allowDelegatedStaking: false,
53
+ delegateRewardShareRatio: 0.5,
54
+ allowedDelegates: [],
55
+ minDelegatedStake: 0,
56
+ autoStake: false,
57
+ properties: '',
58
+ label: '',
59
+ note: '',
60
+ },
61
+ gatewayAddress: 'addr2',
62
+ observerAddress: 'addr2',
63
+ totalDelegatedStake: 0,
64
+ startTimestamp: 0,
65
+ endTimestamp: 0,
66
+ operatorStake: 0,
67
+ status: 'leaving',
68
+ weights: {
69
+ normalizedCompositeWeight: 0.5,
70
+ stakeWeight: 0.5,
71
+ tenureWeight: 0.5,
72
+ gatewayPerformanceRatio: 0.5,
73
+ observerPerformanceRatio: 0.5,
74
+ compositeWeight: 0.5,
75
+ gatewayRewardRatioWeight: 0.5,
76
+ observerRewardRatioWeight: 0.5,
77
+ },
78
+ stats: {
79
+ passedConsecutiveEpochs: 10,
80
+ failedConsecutiveEpochs: 5,
81
+ totalEpochCount: 15,
82
+ passedEpochCount: 10,
83
+ failedEpochCount: 5,
84
+ observedEpochCount: 15,
85
+ prescribedEpochCount: 20,
86
+ },
87
+ },
88
+ ];
89
+ const mockGatewaysProvider = {
90
+ getGateways: async () => mockGateways,
91
+ };
92
+ it('should only return joined gateways', async () => {
93
+ const router = new RandomGatewayRouter({
94
+ gatewaysProvider: mockGatewaysProvider,
95
+ });
96
+ // Run multiple times to ensure we only get joined gateways
97
+ for (let i = 0; i < 10; i++) {
98
+ const result = await router.getTargetGateway();
99
+ assert.deepStrictEqual(result, new URL('https://gateway1.net'));
100
+ }
101
+ });
102
+ });
@@ -0,0 +1,21 @@
1
+ export class SimpleCacheRouter {
2
+ name;
3
+ lastUpdatedTimestamp;
4
+ ttlSeconds;
5
+ targetGateway;
6
+ router;
7
+ constructor({ router, ttlSeconds = 5 * 60, // 5 minutes
8
+ }) {
9
+ this.router = router;
10
+ this.ttlSeconds = ttlSeconds;
11
+ }
12
+ async getTargetGateway() {
13
+ if (this.targetGateway === undefined ||
14
+ this.lastUpdatedTimestamp + this.ttlSeconds * 1000 < Date.now()) {
15
+ this.targetGateway = await this.router.getTargetGateway();
16
+ this.lastUpdatedTimestamp = Date.now();
17
+ }
18
+ return this.targetGateway;
19
+ }
20
+ }
21
+ // TODO: a router that accepts ario and a router, and adds read through promise cache to ario.getGateways to avoid calling the ARIO contract on every request
@@ -0,0 +1,39 @@
1
+ import { strict as assert } from 'node:assert';
2
+ import { describe, it } from 'node:test';
3
+ import { SimpleCacheRouter } from './simple-cache.js';
4
+ describe('SimpleCacheRouter', () => {
5
+ it('should cache gateway for TTL period even if underlying gateway changes', async () => {
6
+ const gateway1 = new URL('https://gateway1.net');
7
+ const gateway2 = new URL('https://gateway2.net');
8
+ let currentGateway = gateway1;
9
+ const mockRouter = {
10
+ name: 'mock',
11
+ getTargetGateway: async () => currentGateway,
12
+ };
13
+ const router = new SimpleCacheRouter({
14
+ router: mockRouter,
15
+ ttlSeconds: 300, // 5 minutes
16
+ });
17
+ // Get initial gateway which should be cached
18
+ const initial = await router.getTargetGateway();
19
+ assert.deepStrictEqual(initial, gateway1);
20
+ // Change the underlying gateway
21
+ currentGateway = gateway2;
22
+ // Should still return cached gateway1 for multiple calls
23
+ for (let i = 0; i < 5; i++) {
24
+ const result = await router.getTargetGateway();
25
+ assert.deepStrictEqual(result, gateway1);
26
+ }
27
+ // Advance time past TTL
28
+ const originalNow = Date.now;
29
+ try {
30
+ Date.now = () => originalNow() + 300 * 1000 + 1;
31
+ // Should now return the new gateway2
32
+ const result = await router.getTargetGateway();
33
+ assert.deepStrictEqual(result, gateway2);
34
+ }
35
+ finally {
36
+ Date.now = originalNow;
37
+ }
38
+ });
39
+ });
@@ -0,0 +1,161 @@
1
+ import { ARIO } from '../io.js';
2
+ import { ARIOGatewaysProvider } from './gateways.js';
3
+ import { RandomGatewayRouter } from './routers/random.js';
4
+ // known regexes for wayfinder urls
5
+ export const arnsRegex = /^[a-z0-9_-]{1,51}$/;
6
+ export const txIdRegex = /^[a-z0-9]{43}$/;
7
+ /**
8
+ * Core function to resolve a wayfinder url against a target gateway
9
+ * @param originalUrl - the wayfinder url to resolve
10
+ * @param targetGateway - the target gateway to resolve the url against
11
+ * @returns the resolved url that can be used to make a request
12
+ */
13
+ export const resolveWayfinderUrl = ({ originalUrl, targetGateway, }) => {
14
+ if (originalUrl.toString().startsWith('ar://')) {
15
+ const [, path] = originalUrl.toString().split('ar://');
16
+ // e.g. ar:///info should route to the info endpoint of the target gateway
17
+ if (path.startsWith('/')) {
18
+ return new URL(path.slice(1), targetGateway);
19
+ }
20
+ // TODO: this breaks 43 character named arns names - we should check a a local name cache list before resolving raw transaction ids
21
+ if (txIdRegex.test(path)) {
22
+ const [txId, ...rest] = path.split('/');
23
+ return new URL(`${txId}${rest.join('/')}`, targetGateway);
24
+ }
25
+ if (arnsRegex.test(path)) {
26
+ // TODO: tests to ensure arns names support query params and paths
27
+ const [name, ...rest] = path.split('/');
28
+ const targetGatewayUrl = new URL(targetGateway);
29
+ const arnsUrl = `${targetGatewayUrl.protocol}//${name}.${targetGatewayUrl.hostname}${targetGatewayUrl.port ? `:${targetGatewayUrl.port}` : ''}`;
30
+ return new URL(rest.join('/'), arnsUrl);
31
+ }
32
+ // TODO: support .eth addresses
33
+ // TODO: "gasless" routing via DNS TXT records (e.g. ar://gatewaypie.com -> TXT record lookup for TX ID and redirect to that gateway)
34
+ }
35
+ // return the original url if it's not a wayfinder url (allows you to use the wayfinder client with non-wayfinder urls)
36
+ return new URL(originalUrl);
37
+ };
38
+ /**
39
+ * Creates a wrapped http client that supports ar:// protocol
40
+ *
41
+ * This function leverages a Proxy to intercept calls to the http client
42
+ * and redirects them to the target gateway using the resolveUrl function url.
43
+ * It also supports the http client methods like get(), post(), put(), delete(), etc.
44
+ *
45
+ * Any URLs provided that are not wayfinder urls will be returned as is.
46
+ *
47
+ * @param httpClient - the http client to wrap (e.g. axios, fetch, got, etc.)
48
+ * @param resolveUrl - the function to construct the redirect url for ar:// requests
49
+ * @returns a wrapped http client that supports ar:// protocol
50
+ */
51
+ export const createWayfinderClient = ({ httpClient, resolveUrl, }) => {
52
+ const wayfinderRedirect = async (fn, rawArgs) => {
53
+ // TODO: handle if first arg is not a string (i.e. just return the result of the function call)
54
+ const [originalUrl, ...rest] = rawArgs;
55
+ // route the request to the target gateway
56
+ const redirectUrl = await resolveUrl({
57
+ originalUrl,
58
+ });
59
+ // make the request to the target gateway using the redirect url and http client
60
+ const response = await fn(redirectUrl.toString(), ...rest);
61
+ // TODO: if verifyDataHash is provided, verify the data hash before returning
62
+ return response;
63
+ };
64
+ return new Proxy(httpClient, {
65
+ // support direct calls: fetch('ar://…', options)
66
+ // axios() or got()
67
+ apply: (_target, _thisArg, argArray) => wayfinderRedirect(httpClient, argArray),
68
+ // support http clients that use methods like `got.get`, `got.post`, `axios.get`, etc. while still using the wayfinder redirect function
69
+ get: (target, prop, receiver) => {
70
+ const value = Reflect.get(target, prop, receiver);
71
+ if (typeof value === 'function') {
72
+ return (...inner) => wayfinderRedirect(value.bind(target), inner);
73
+ }
74
+ return value; // numbers, objects, symbols pass through untouched
75
+ },
76
+ });
77
+ };
78
+ /**
79
+ * The main class for the wayfinder
80
+ * @param router - the router to use for requests
81
+ * @param httpClient - the http client to use for requests
82
+ * @param blocklist - the blocklist of gateways to avoid
83
+ */
84
+ export class Wayfinder {
85
+ /**
86
+ * The router to use for requests
87
+ *
88
+ * @example
89
+ * const wayfinder = new Wayfinder({
90
+ * router: new RandomGatewayRouter({ ario: ARIO.mainnet() }),
91
+ * });
92
+ */
93
+ router;
94
+ /**
95
+ * The http client to use for requests
96
+ *
97
+ * @example
98
+ * const wayfinder = new Wayfinder({
99
+ * router: new RandomGatewayRouter({ ario: ARIO.mainnet() }),
100
+ * httpClient: axios,
101
+ * });
102
+ */
103
+ httpClient;
104
+ /**
105
+ * The function that resolves the redirect url for ar:// requests to a target gateway
106
+ *
107
+ * @example
108
+ * const wayfinder = new Wayfinder({
109
+ * router: new RandomGatewayRouter({ ario: ARIO.mainnet() }),
110
+ * httpClient: axios,
111
+ * });
112
+ *
113
+ * const redirectUrl = await wayfinder.resolveUrl({ originalUrl: 'ar://example' });
114
+ */
115
+ resolveUrl;
116
+ /**
117
+ * A wrapped http client that supports ar:// protocol
118
+ *
119
+ * @example
120
+ * const { request: wayfind } = new Wayfinder({
121
+ * router: new RandomGatewayRouter({ ario: ARIO.mainnet() }),
122
+ * httpClient: axios,
123
+ * });;
124
+ *
125
+ * TODO: consider a top level function that supports wayfinder routing under the hood
126
+ * const response = await wayfind('ar://', {
127
+ * method: 'POST',
128
+ * data: {
129
+ * name: 'John Doe',
130
+ * },
131
+ * })
132
+ */
133
+ request;
134
+ // TODO: stats provider
135
+ // TODO: metricsProvider for otel/prom support
136
+ // TODO: private verificationSettings: {
137
+ // trustedGateways: URL[];
138
+ // method: 'local' | 'remote';
139
+ // };
140
+ constructor({
141
+ // TODO: consider changing router to routingStrategy or strategy
142
+ router = new RandomGatewayRouter({
143
+ // optionally use a cache gateways provider to reduce the number of requests to the contract
144
+ gatewaysProvider: new ARIOGatewaysProvider({ ario: ARIO.mainnet() }),
145
+ }), httpClient,
146
+ // TODO: add verifier interface that provides a verifyDataHash function
147
+ // TODO: stats provider
148
+ }) {
149
+ this.router = router;
150
+ this.httpClient = httpClient;
151
+ this.resolveUrl = async ({ originalUrl }) => resolveWayfinderUrl({
152
+ originalUrl,
153
+ targetGateway: await this.router.getTargetGateway(),
154
+ });
155
+ this.request = createWayfinderClient({
156
+ httpClient,
157
+ resolveUrl: this.resolveUrl,
158
+ // TODO: provide the verifyDataHash function from the verifier to the wayfinder client along with verificationSettings
159
+ });
160
+ }
161
+ }
@@ -0,0 +1,248 @@
1
+ import axios from 'axios';
2
+ import got from 'got';
3
+ import assert from 'node:assert';
4
+ import { buffer } from 'node:stream/consumers';
5
+ import { before, describe, it } from 'node:test';
6
+ import { RandomGatewayRouter } from './routers/random.js';
7
+ import { Wayfinder } from './wayfinder.js';
8
+ const stubbedGateway = {
9
+ status: 'joined',
10
+ gatewayAddress: 'arweave',
11
+ operatorStake: 1000,
12
+ totalDelegatedStake: 1000,
13
+ startTimestamp: 1000,
14
+ settings: {
15
+ protocol: 'https',
16
+ fqdn: 'arweave.net',
17
+ port: 443,
18
+ },
19
+ };
20
+ const stubbedGatewaysProvider = {
21
+ getGateways: async () => [stubbedGateway],
22
+ };
23
+ describe('Wayfinder', () => {
24
+ describe('http wrapper', () => {
25
+ describe('fetch', () => {
26
+ let wayfinder;
27
+ before(() => {
28
+ wayfinder = new Wayfinder({
29
+ httpClient: fetch,
30
+ router: new RandomGatewayRouter({
31
+ gatewaysProvider: stubbedGatewaysProvider,
32
+ }),
33
+ });
34
+ });
35
+ it('should fetch the data using the selected gateway', async () => {
36
+ const nativeFetch = await fetch('https://ao.arweave.net');
37
+ const response = await wayfinder.request('ar://ao');
38
+ assert.strictEqual(response.status, 200);
39
+ assert.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
+ assert.deepStrictEqual(arnsHeaders, nativeFetchHeaders);
44
+ assert.deepStrictEqual(await response.text(), await nativeFetch.text());
45
+ });
46
+ it('should route a non-ar:// url as a normal fetch', async () => {
47
+ const [nativeFetch, response] = await Promise.all([
48
+ fetch('https://arweave.net/', {
49
+ method: 'HEAD',
50
+ }),
51
+ wayfinder.request('https://arweave.net/', {
52
+ method: 'HEAD',
53
+ }),
54
+ ]);
55
+ assert.strictEqual(response.status, 200);
56
+ assert.strictEqual(response.status, nativeFetch.status);
57
+ // TODO: ensure the headers are the same excluding unique headers
58
+ assert.deepStrictEqual(await response.text(), await nativeFetch.text());
59
+ });
60
+ for (const api of ['/info', '/metrics', '/block/current']) {
61
+ it(`supports native arweave node apis ${api}`, async () => {
62
+ const [nativeFetch, response] = await Promise.all([
63
+ fetch(`https://arweave.net${api}`),
64
+ wayfinder.request(`ar:///${api}`),
65
+ ]);
66
+ assert.strictEqual(response.status, 200);
67
+ assert.strictEqual(response.status, nativeFetch.status);
68
+ // TODO: ensure the headers are the same excluding unique headers
69
+ assert.deepStrictEqual(await response.text(), await nativeFetch.text());
70
+ });
71
+ }
72
+ for (const api of ['/ar-io/info', '/ar-io/__gateway_metrics']) {
73
+ it(`supports native ario node gateway apis ${api}`, async () => {
74
+ const [nativeFetch, response] = await Promise.all([
75
+ fetch(`https://arweave.net${api}`),
76
+ wayfinder.request(`ar:///${api}`),
77
+ ]);
78
+ assert.strictEqual(response.status, 200);
79
+ assert.strictEqual(response.status, nativeFetch.status);
80
+ // TODO: ensure the headers are the same excluding unique headers
81
+ assert.deepStrictEqual(await response.text(), await nativeFetch.text());
82
+ });
83
+ }
84
+ it('supports a post request to graphql', async () => {
85
+ const response = await wayfinder.request('ar:///graphql', {
86
+ method: 'POST',
87
+ headers: {
88
+ 'Content-Type': 'application/json',
89
+ },
90
+ body: JSON.stringify({
91
+ query: `
92
+ query {
93
+ transactions(
94
+ ids: ["xf958qhCNGfDme1FtoiD6DtMfDENDbtxZpjOM_1tsMM"]
95
+ ) {
96
+ edges {
97
+ cursor
98
+ node {
99
+ id
100
+ tags {
101
+ name
102
+ value
103
+ }
104
+ block {
105
+ height
106
+ timestamp
107
+ }
108
+ }
109
+ }
110
+ pageInfo {
111
+ hasNextPage
112
+ }
113
+ }
114
+ }
115
+ `,
116
+ }),
117
+ });
118
+ assert.strictEqual(response.status, 200);
119
+ });
120
+ it('returns the error from the target gateway if the route is not found', async () => {
121
+ const [nativeFetch, response] = await Promise.all([
122
+ fetch('https://arweave.net/not-found'),
123
+ wayfinder.request('https://arweave.net/not-found'),
124
+ ]);
125
+ assert.strictEqual(response.status, nativeFetch.status);
126
+ assert.strictEqual(response.statusText, nativeFetch.statusText);
127
+ assert.deepStrictEqual(await response.text(), await nativeFetch.text());
128
+ });
129
+ });
130
+ describe('axios', () => {
131
+ let wayfinder;
132
+ before(() => {
133
+ wayfinder = new Wayfinder({
134
+ httpClient: axios,
135
+ router: new RandomGatewayRouter({
136
+ gatewaysProvider: stubbedGatewaysProvider,
137
+ }),
138
+ });
139
+ });
140
+ it('should fetch the data using axios default function against the target gateway', async () => {
141
+ const [nativeAxios, response] = await Promise.all([
142
+ axios('https://ao.arweave.net'),
143
+ wayfinder.request('ar://ao'),
144
+ ]);
145
+ assert.strictEqual(response.status, 200);
146
+ assert.strictEqual(response.status, nativeAxios.status);
147
+ // assert the arns headers are the same
148
+ const arnsHeaders = Object.entries(response.headers)
149
+ .sort()
150
+ .filter(([key]) => key.startsWith('x-arns-'));
151
+ const nativeAxiosHeaders = Object.entries(nativeAxios.headers).filter(([key]) => key.startsWith('x-arns-'));
152
+ assert.deepStrictEqual(arnsHeaders.sort(), nativeAxiosHeaders.sort());
153
+ assert.deepStrictEqual(response.data, nativeAxios.data);
154
+ });
155
+ it('should fetch the data using the axios.get method against the target gateway', async () => {
156
+ const [nativeAxios, response] = await Promise.all([
157
+ axios.get('https://ao.arweave.net'),
158
+ wayfinder.request.get('ar://ao'),
159
+ ]);
160
+ assert.strictEqual(response.status, 200);
161
+ assert.strictEqual(response.status, nativeAxios.status);
162
+ // assert the arns headers are the same
163
+ const arnsHeaders = Object.entries(response.headers)
164
+ .sort()
165
+ .filter(([key]) => key.startsWith('x-arns-'));
166
+ const nativeAxiosHeaders = Object.entries(nativeAxios.headers).filter(([key]) => key.startsWith('x-arns-'));
167
+ assert.deepStrictEqual(arnsHeaders.sort(), nativeAxiosHeaders.sort());
168
+ assert.deepStrictEqual(response.data, nativeAxios.data);
169
+ });
170
+ it('should route a non-ar:// url as a normal axios request', async () => {
171
+ const [nativeAxios, response] = await Promise.all([
172
+ axios('https://arweave.net/'),
173
+ wayfinder.request('https://arweave.net/'),
174
+ ]);
175
+ assert.strictEqual(response.status, 200);
176
+ assert.strictEqual(response.status, nativeAxios.status);
177
+ assert.deepStrictEqual(response.data, nativeAxios.data);
178
+ // TODO: ensure the headers are the same excluding unique headers
179
+ });
180
+ for (const api of ['/info', '/metrics', '/block/current']) {
181
+ it(`supports native arweave node apis ${api}`, async () => {
182
+ const [nativeAxios, response] = await Promise.all([
183
+ axios(`https://arweave.net${api}`),
184
+ wayfinder.request(`ar:///${api}`),
185
+ ]);
186
+ assert.strictEqual(response.status, 200);
187
+ assert.strictEqual(response.status, nativeAxios.status);
188
+ // TODO: ensure the headers are the same excluding unique headers
189
+ assert.deepStrictEqual(response.data, nativeAxios.data);
190
+ });
191
+ }
192
+ for (const api of ['/ar-io/info', '/ar-io/__gateway_metrics']) {
193
+ it(`supports native ario node gateway apis ${api}`, async () => {
194
+ const [nativeAxios, response] = await Promise.all([
195
+ axios(`https://arweave.net${api}`),
196
+ wayfinder.request(`ar:///${api}`),
197
+ ]);
198
+ assert.strictEqual(response.status, 200);
199
+ assert.strictEqual(response.status, nativeAxios.status);
200
+ // TODO: ensure the headers are the same excluding unique headers
201
+ assert.deepStrictEqual(response.data, nativeAxios.data);
202
+ });
203
+ }
204
+ it('should return the error from the target gateway if the route is not found', async () => {
205
+ const axiosInstance = axios.create({
206
+ validateStatus: () => true, // don't throw so we can compare axios result with wrapped axios result
207
+ });
208
+ const wayfinder = new Wayfinder({
209
+ httpClient: axiosInstance,
210
+ router: new RandomGatewayRouter({
211
+ gatewaysProvider: stubbedGatewaysProvider,
212
+ }),
213
+ });
214
+ const [nativeAxios, response] = await Promise.all([
215
+ axiosInstance('https://arweave.net/not-found'),
216
+ wayfinder.request('https://arweave.net/not-found'),
217
+ ]);
218
+ assert.strictEqual(response.status, nativeAxios.status);
219
+ assert.strictEqual(response.data, nativeAxios.data);
220
+ });
221
+ });
222
+ describe('got', () => {
223
+ let wayfinder;
224
+ before(() => {
225
+ wayfinder = new Wayfinder({
226
+ httpClient: got,
227
+ router: new RandomGatewayRouter({
228
+ gatewaysProvider: stubbedGatewaysProvider,
229
+ }),
230
+ });
231
+ });
232
+ it('should fetch the data using the got default function against the target gateway', async () => {
233
+ const [nativeGot, response] = await Promise.all([
234
+ got('https://ao.arweave.net'),
235
+ wayfinder.request('ar://ao'),
236
+ ]);
237
+ assert.strictEqual(response.statusCode, 200);
238
+ assert.strictEqual(response.statusCode, nativeGot.statusCode);
239
+ assert.deepStrictEqual(response.body, nativeGot.body);
240
+ });
241
+ it('should stream the data using got.stream against the selected target gateway', async () => {
242
+ const nativeBuffer = await buffer(await got.stream('https://ao.arweave.net', { decompress: false }));
243
+ const wayfinderBuffer = await buffer(await wayfinder.request.stream('ar://ao', { decompress: false }));
244
+ assert.deepStrictEqual(wayfinderBuffer, nativeBuffer);
245
+ });
246
+ });
247
+ });
248
+ });
@@ -77,6 +77,17 @@ export const AntStateSchema = z.object({
77
77
  .boolean()
78
78
  .describe('Flag indicating whether the ANT has been initialized.'),
79
79
  });
80
+ export const SpawnANTStateSchema = z.object({
81
+ name: z.string().describe('The name of the ANT.'),
82
+ ticker: z.string().describe('The ticker symbol for the ANT.'),
83
+ description: z.string().describe('The description for the ANT.'),
84
+ keywords: AntKeywordsSchema.describe('The keywords for the ANT.'),
85
+ owner: AOAddressSchema.describe('The Owners address.'),
86
+ controllers: AntControllersSchema.describe('Controllers of the ANT who have administrative privileges.'),
87
+ records: AntRecordsSchema.describe('Records associated with the ANT.'),
88
+ balances: AntBalancesSchema.describe('Balance details for each address holding the ANT.'),
89
+ logo: ArweaveTxIdSchema.describe('Transaction ID of the ANT logo.'),
90
+ });
80
91
  export const AntReadHandlers = [
81
92
  'balance',
82
93
  'balances',
@@ -19,3 +19,4 @@ export * from './common.js';
19
19
  export * from './faucet.js';
20
20
  export * from './io.js';
21
21
  export * from './token.js';
22
+ export * from './wayfinder.js';
@@ -22,7 +22,7 @@ export const intentsUsingYears = [
22
22
  export const isValidIntent = (intent) => {
23
23
  return validIntents.indexOf(intent) !== -1;
24
24
  };
25
- export const fundFromOptions = ['balance', 'stakes', 'any'];
25
+ export const fundFromOptions = ['balance', 'stakes', 'any', 'turbo'];
26
26
  export const isValidFundFrom = (fundFrom) => {
27
27
  return fundFromOptions.indexOf(fundFrom) !== -1;
28
28
  };
@@ -0,0 +1 @@
1
+ export {};
@@ -19,8 +19,13 @@ import { z } from 'zod';
19
19
  import { defaultArweave } from '../common/arweave.js';
20
20
  import { AOProcess, Logger } from '../common/index.js';
21
21
  import { ANT_LUA_ID, ANT_REGISTRY_ID, AOS_MODULE_ID, AO_AUTHORITY, DEFAULT_SCHEDULER_ID, } from '../constants.js';
22
+ import { SpawnANTStateSchema } from '../types/ant.js';
23
+ import { parseSchemaResult } from './schema.js';
22
24
  export async function spawnANT({ signer, module = AOS_MODULE_ID, ao = connect(), scheduler = DEFAULT_SCHEDULER_ID, state, antRegistryId = ANT_REGISTRY_ID, logger = Logger.default, authority = AO_AUTHORITY, }) {
23
25
  // TODO: use On-Boot data handler for bootstrapping state instead of initialize-state
26
+ if (state) {
27
+ parseSchemaResult(SpawnANTStateSchema, state);
28
+ }
24
29
  const processId = await ao.spawn({
25
30
  module,
26
31
  scheduler,
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { webcrypto } from 'crypto';
17
+ /**
18
+ * Cryptographically secure helper for randomness, does not support seeding
19
+ * @param min - the minimum value
20
+ * @param max - the maximum value
21
+ * @returns a random integer between min and max
22
+ */
23
+ export const randomInt = (min, max) => {
24
+ const [rand] = webcrypto.getRandomValues(new Uint32Array(1));
25
+ return min + (rand % (max - min));
26
+ };