@gearbox-protocol/sdk 18.2.0-next.4 → 18.2.0-next.6

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 (49) hide show
  1. package/dist/cjs/permissionless/api/oracles/PermissionlessOracles.js +3 -3
  2. package/dist/cjs/permissionless/api/oracles/schemas.js +44 -35
  3. package/dist/cjs/permissionless/api/schemas.js +0 -3
  4. package/dist/cjs/testnets/TestnetsAPI.js +179 -0
  5. package/dist/cjs/testnets/errors/TestnetNotFoundError.js +15 -0
  6. package/dist/cjs/testnets/errors/TestnetRequestFailedError.js +24 -0
  7. package/dist/cjs/testnets/errors/TestnetStatusError.js +19 -0
  8. package/dist/cjs/testnets/errors/TestnetValidationError.js +24 -0
  9. package/dist/cjs/testnets/errors/TestnetWaitTimeoutError.js +30 -0
  10. package/dist/cjs/testnets/errors/TestnetsError.js +34 -0
  11. package/dist/cjs/testnets/errors/index.js +13 -0
  12. package/dist/cjs/testnets/index.js +32 -0
  13. package/dist/cjs/testnets/package.json +1 -0
  14. package/dist/cjs/testnets/schemas.js +242 -0
  15. package/dist/cjs/testnets/types.js +1 -0
  16. package/dist/esm/permissionless/api/oracles/PermissionlessOracles.js +3 -3
  17. package/dist/esm/permissionless/api/oracles/schemas.js +44 -35
  18. package/dist/esm/permissionless/api/schemas.js +2 -4
  19. package/dist/esm/testnets/TestnetsAPI.js +178 -0
  20. package/dist/esm/testnets/errors/TestnetNotFoundError.js +14 -0
  21. package/dist/esm/testnets/errors/TestnetRequestFailedError.js +23 -0
  22. package/dist/esm/testnets/errors/TestnetStatusError.js +18 -0
  23. package/dist/esm/testnets/errors/TestnetValidationError.js +23 -0
  24. package/dist/esm/testnets/errors/TestnetWaitTimeoutError.js +29 -0
  25. package/dist/esm/testnets/errors/TestnetsError.js +33 -0
  26. package/dist/esm/testnets/errors/index.js +7 -0
  27. package/dist/esm/testnets/index.js +11 -0
  28. package/dist/esm/testnets/package.json +1 -0
  29. package/dist/esm/testnets/schemas.js +228 -0
  30. package/dist/esm/testnets/types.js +1 -0
  31. package/dist/types/permissionless/api/index.d.ts +2 -2
  32. package/dist/types/permissionless/api/oracles/PermissionlessOracles.d.ts +2 -4
  33. package/dist/types/permissionless/api/oracles/index.d.ts +2 -2
  34. package/dist/types/permissionless/api/oracles/schemas.d.ts +39 -24
  35. package/dist/types/permissionless/api/oracles/types.d.ts +47 -54
  36. package/dist/types/permissionless/api/schemas.d.ts +0 -2
  37. package/dist/types/permissionless/index.d.ts +2 -2
  38. package/dist/types/testnets/TestnetsAPI.d.ts +108 -0
  39. package/dist/types/testnets/errors/TestnetNotFoundError.d.ts +12 -0
  40. package/dist/types/testnets/errors/TestnetRequestFailedError.d.ts +11 -0
  41. package/dist/types/testnets/errors/TestnetStatusError.d.ts +15 -0
  42. package/dist/types/testnets/errors/TestnetValidationError.d.ts +16 -0
  43. package/dist/types/testnets/errors/TestnetWaitTimeoutError.d.ts +21 -0
  44. package/dist/types/testnets/errors/TestnetsError.d.ts +47 -0
  45. package/dist/types/testnets/errors/index.d.ts +7 -0
  46. package/dist/types/testnets/index.d.ts +11 -0
  47. package/dist/types/testnets/schemas.d.ts +554 -0
  48. package/dist/types/testnets/types.d.ts +717 -0
  49. package/package.json +6 -1
@@ -0,0 +1,242 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_onchain_chain_chains = require("../onchain/chain/chains.js");
3
+ const require_onchain_utils_zod = require("../onchain/utils/zod.js");
4
+ let zod_v4 = require("zod/v4");
5
+ //#region src/testnets/schemas.ts
6
+ /**
7
+ * Go marshals a nil slice as `null`; this reads it as an empty array.
8
+ **/
9
+ function nullableArray(item) {
10
+ return zod_v4.z.array(item).nullable().transform((value) => value ?? []);
11
+ }
12
+ /**
13
+ * Go marshals a nil map as `null`; this reads it as an empty record.
14
+ **/
15
+ function nullableRecord(value) {
16
+ return zod_v4.z.record(zod_v4.z.string(), value).nullable().transform((record) => record ?? {});
17
+ }
18
+ const timestamp = zod_v4.z.iso.datetime({ offset: true });
19
+ /**
20
+ * {@link TestnetStageStatus}
21
+ **/
22
+ const testnetStageStatusSchema = zod_v4.z.enum([
23
+ "queued",
24
+ "started",
25
+ "error",
26
+ "failed",
27
+ "success",
28
+ "terminated"
29
+ ]);
30
+ /**
31
+ * {@link TestnetBackendState}
32
+ **/
33
+ const testnetBackendStateSchema = zod_v4.z.enum([
34
+ "provisioning",
35
+ "starting",
36
+ "active",
37
+ "error"
38
+ ]);
39
+ /**
40
+ * {@link Testnet}
41
+ **/
42
+ const testnetSchema = zod_v4.z.object({
43
+ alias: zod_v4.z.string(),
44
+ executionId: zod_v4.z.string(),
45
+ isActive: zod_v4.z.boolean(),
46
+ description: zod_v4.z.string(),
47
+ persistent: zod_v4.z.boolean(),
48
+ paused: zod_v4.z.boolean(),
49
+ network: require_onchain_chain_chains.NetworkType,
50
+ createdAt: timestamp
51
+ });
52
+ /**
53
+ * {@link TestnetBackendOptions}
54
+ **/
55
+ const testnetBackendOptionsSchema = zod_v4.z.object({
56
+ version: zod_v4.z.string().optional(),
57
+ env: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.string()).optional(),
58
+ parentBranchId: zod_v4.z.string().optional()
59
+ });
60
+ /**
61
+ * {@link TestnetBackendStatus}
62
+ **/
63
+ const testnetBackendStatusSchema = zod_v4.z.object({
64
+ state: testnetBackendStateSchema,
65
+ error: zod_v4.z.string().optional(),
66
+ version: zod_v4.z.string().optional()
67
+ });
68
+ /**
69
+ * {@link TestnetBlock}
70
+ **/
71
+ const testnetBlockSchema = zod_v4.z.object({
72
+ number: zod_v4.z.number(),
73
+ time: timestamp
74
+ });
75
+ /**
76
+ * {@link TestnetScriptBlock}
77
+ **/
78
+ const testnetScriptBlockSchema = testnetBlockSchema.extend({
79
+ timeDrift: zod_v4.z.number(),
80
+ originDrift: zod_v4.z.string(),
81
+ automine: zod_v4.z.boolean(),
82
+ mineInterval: zod_v4.z.number()
83
+ });
84
+ /**
85
+ * {@link TestnetScriptOptions}
86
+ **/
87
+ const testnetScriptOptionsSchema = zod_v4.z.object({
88
+ id: zod_v4.z.string(),
89
+ description: zod_v4.z.string(),
90
+ npx: zod_v4.z.string().optional(),
91
+ docker: zod_v4.z.string().optional(),
92
+ args: nullableArray(zod_v4.z.string()),
93
+ env: nullableRecord(zod_v4.z.string()),
94
+ flags: nullableArray(zod_v4.z.string()),
95
+ timeout: zod_v4.z.string(),
96
+ packageManager: zod_v4.z.string().optional(),
97
+ input: zod_v4.z.unknown().optional()
98
+ });
99
+ /**
100
+ * {@link TestnetScript}
101
+ **/
102
+ const testnetScriptSchema = zod_v4.z.object({
103
+ script: testnetScriptOptionsSchema,
104
+ duration: zod_v4.z.string(),
105
+ blockBefore: testnetScriptBlockSchema.optional(),
106
+ blockAfter: testnetScriptBlockSchema.optional(),
107
+ status: testnetStageStatusSchema,
108
+ error: zod_v4.z.string().optional(),
109
+ exitCode: zod_v4.z.number(),
110
+ source: zod_v4.z.string().optional(),
111
+ revision: zod_v4.z.string().optional()
112
+ });
113
+ /**
114
+ * {@link TestnetTaskDefinition}
115
+ **/
116
+ const testnetTaskDefinitionSchema = zod_v4.z.object({
117
+ id: zod_v4.z.string().optional(),
118
+ family: zod_v4.z.string().optional(),
119
+ name: zod_v4.z.string().optional(),
120
+ description: zod_v4.z.string().optional(),
121
+ image: zod_v4.z.string(),
122
+ version: zod_v4.z.string().optional(),
123
+ entrypoint: zod_v4.z.array(zod_v4.z.string()).optional(),
124
+ command: zod_v4.z.array(zod_v4.z.string()).optional(),
125
+ env: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.string()).optional(),
126
+ secrets: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.string()).optional(),
127
+ input: zod_v4.z.unknown().optional(),
128
+ timeout: zod_v4.z.number().optional(),
129
+ concurrent: zod_v4.z.boolean(),
130
+ multicontainer: zod_v4.z.boolean(),
131
+ schemaVersion: zod_v4.z.number().optional()
132
+ });
133
+ /**
134
+ * {@link TestnetTaskProgress}
135
+ **/
136
+ const testnetTaskProgressSchema = zod_v4.z.object({
137
+ completed: zod_v4.z.number(),
138
+ total: zod_v4.z.number(),
139
+ details: zod_v4.z.unknown().optional()
140
+ });
141
+ /**
142
+ * {@link TestnetTask}
143
+ **/
144
+ const testnetTaskSchema = zod_v4.z.object({
145
+ id: zod_v4.z.string(),
146
+ definitionId: zod_v4.z.string(),
147
+ family: zod_v4.z.string(),
148
+ executionId: zod_v4.z.string(),
149
+ name: zod_v4.z.string().optional(),
150
+ description: zod_v4.z.string().optional(),
151
+ image: zod_v4.z.string(),
152
+ source: zod_v4.z.string().optional(),
153
+ revision: zod_v4.z.string().optional(),
154
+ entrypoint: zod_v4.z.array(zod_v4.z.string()).optional(),
155
+ command: zod_v4.z.array(zod_v4.z.string()).optional(),
156
+ env: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.string()).optional(),
157
+ secrets: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.string()).optional(),
158
+ input: zod_v4.z.unknown().optional(),
159
+ multicontainer: zod_v4.z.boolean(),
160
+ concurrent: zod_v4.z.boolean(),
161
+ outputDir: zod_v4.z.string().optional(),
162
+ status: testnetStageStatusSchema,
163
+ error: zod_v4.z.string().optional(),
164
+ createdAt: timestamp,
165
+ updatedAt: timestamp,
166
+ progress: testnetTaskProgressSchema
167
+ });
168
+ /**
169
+ * {@link TestnetOptions}
170
+ **/
171
+ const testnetOptionsSchema = zod_v4.z.object({
172
+ description: zod_v4.z.string().optional(),
173
+ chainId: zod_v4.z.number().optional(),
174
+ network: require_onchain_chain_chains.NetworkType,
175
+ cid: zod_v4.z.string().optional(),
176
+ anvilFlags: zod_v4.z.array(zod_v4.z.string()).optional(),
177
+ anvilImage: zod_v4.z.string().optional(),
178
+ rpcProvider: zod_v4.z.string().optional(),
179
+ addressProvider: require_onchain_utils_zod.ZodAddress().optional(),
180
+ marketConfigurators: zod_v4.z.array(require_onchain_utils_zod.ZodAddress()).optional(),
181
+ rwaFactories: zod_v4.z.array(require_onchain_utils_zod.ZodAddress()).optional(),
182
+ blockNumber: zod_v4.z.string(),
183
+ owner: zod_v4.z.string(),
184
+ timeout: zod_v4.z.string(),
185
+ synctronLogLevel: zod_v4.z.string().optional(),
186
+ scripts: nullableArray(testnetScriptOptionsSchema),
187
+ disableSync: zod_v4.z.boolean(),
188
+ disableIntervalMining: zod_v4.z.boolean(),
189
+ disableRPCProtection: zod_v4.z.boolean(),
190
+ debug: zod_v4.z.boolean().optional(),
191
+ webhooks: nullableArray(zod_v4.z.string()),
192
+ backend: testnetBackendOptionsSchema.optional(),
193
+ tasks: zod_v4.z.array(testnetTaskDefinitionSchema).optional()
194
+ });
195
+ /**
196
+ * {@link TestnetStatus}
197
+ **/
198
+ const testnetStatusSchema = zod_v4.z.object({
199
+ alias: zod_v4.z.string().optional(),
200
+ network: require_onchain_chain_chains.NetworkType,
201
+ nextRestart: timestamp.optional(),
202
+ isActive: zod_v4.z.boolean(),
203
+ ready: zod_v4.z.boolean(),
204
+ paused: zod_v4.z.boolean(),
205
+ rpcUrl: zod_v4.z.string().optional(),
206
+ url: zod_v4.z.string(),
207
+ logsUrl: zod_v4.z.string(),
208
+ persistent: zod_v4.z.boolean(),
209
+ latestBlock: testnetScriptBlockSchema.optional(),
210
+ tasks: zod_v4.z.array(testnetTaskSchema).optional(),
211
+ backend: testnetBackendStatusSchema.optional(),
212
+ executionId: zod_v4.z.string(),
213
+ options: testnetOptionsSchema,
214
+ forkBlock: testnetBlockSchema,
215
+ syncBlock: zod_v4.z.number(),
216
+ syncError: zod_v4.z.string().optional(),
217
+ originChainId: zod_v4.z.number(),
218
+ anvilChainId: zod_v4.z.number(),
219
+ createdAt: timestamp,
220
+ addressProvider: require_onchain_utils_zod.ZodAddress(),
221
+ marketConfigurators: zod_v4.z.array(require_onchain_utils_zod.ZodAddress()).optional(),
222
+ rwaFactories: zod_v4.z.array(require_onchain_utils_zod.ZodAddress()).optional(),
223
+ onchainExecutionId: require_onchain_utils_zod.ZodAddress(),
224
+ scripts: zod_v4.z.array(testnetScriptSchema).optional(),
225
+ cid: zod_v4.z.string().optional(),
226
+ files: zod_v4.z.array(zod_v4.z.string()).optional()
227
+ });
228
+ //#endregion
229
+ exports.testnetBackendOptionsSchema = testnetBackendOptionsSchema;
230
+ exports.testnetBackendStateSchema = testnetBackendStateSchema;
231
+ exports.testnetBackendStatusSchema = testnetBackendStatusSchema;
232
+ exports.testnetBlockSchema = testnetBlockSchema;
233
+ exports.testnetOptionsSchema = testnetOptionsSchema;
234
+ exports.testnetSchema = testnetSchema;
235
+ exports.testnetScriptBlockSchema = testnetScriptBlockSchema;
236
+ exports.testnetScriptOptionsSchema = testnetScriptOptionsSchema;
237
+ exports.testnetScriptSchema = testnetScriptSchema;
238
+ exports.testnetStageStatusSchema = testnetStageStatusSchema;
239
+ exports.testnetStatusSchema = testnetStatusSchema;
240
+ exports.testnetTaskDefinitionSchema = testnetTaskDefinitionSchema;
241
+ exports.testnetTaskProgressSchema = testnetTaskProgressSchema;
242
+ exports.testnetTaskSchema = testnetTaskSchema;
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
@@ -124,10 +124,10 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
124
124
  * const everywhere = await permissionless.oracles.assets();
125
125
  * ```
126
126
  **/
127
- async assets(args = {}) {
128
- const query = args.chainId === void 0 ? "" : `?chainId=${encodeURIComponent(args.chainId)}`;
127
+ async assets({ chainId } = {}) {
129
128
  return this.getData({
130
- path: `/pfs/assets${query}`,
129
+ path: "/pfs/assets",
130
+ query: { chainId: chainId?.toString() },
131
131
  schema: assetSummariesSchema
132
132
  });
133
133
  }
@@ -1,3 +1,4 @@
1
+ import { chainSchema } from "../chains/schemas.js";
1
2
  import { addressRecord, addressSchema } from "../schemas.js";
2
3
  import { z } from "zod/v4";
3
4
  //#region src/permissionless/api/oracles/schemas.ts
@@ -18,22 +19,29 @@ const priceFeedSchema = z.looseObject({
18
19
  stalenessPeriod: z.number(),
19
20
  name: z.string()
20
21
  });
21
- /** {@link PermissionlessAsset} */
22
- const assetSchema = z.looseObject({
22
+ /**
23
+ * {@link PermissionlessPriceFeedAsset}
24
+ *
25
+ * What identifies an asset, which is all a feed's own listing of one says.
26
+ **/
27
+ const priceFeedAssetSchema = z.looseObject({
23
28
  address: addressSchema,
24
29
  symbol: z.string(),
25
30
  name: z.string(),
26
- decimals: z.number(),
31
+ decimals: z.number()
32
+ });
33
+ /** {@link PermissionlessAsset} — identified as above, plus what prices it. */
34
+ const assetSchema = priceFeedAssetSchema.extend({
27
35
  owner: addressSchema,
28
36
  priceFeeds: z.array(priceFeedSchema)
29
37
  });
30
- /** {@link PermissionlessPriceFeedStore} */
31
- const priceFeedStoreSchema = z.looseObject({
32
- chainId: z.number(),
33
- name: z.string(),
34
- isPublic: z.boolean(),
35
- isActivated: z.boolean(),
36
- explorerUrl: z.string(),
38
+ /**
39
+ * {@link PermissionlessPriceFeedStore}
40
+ *
41
+ * A store is a chain's, and is described by the same five fields the chain
42
+ * list answers with, so those are extended rather than restated.
43
+ **/
44
+ const priceFeedStoreSchema = chainSchema.extend({
37
45
  assets: z.array(assetSchema),
38
46
  priceFeeds: z.array(priceFeedSchema)
39
47
  });
@@ -43,26 +51,29 @@ const pricesSchema = z.looseObject({
43
51
  marketCaps: addressRecord(addressRecord(z.string().nullable())),
44
52
  time: z.number()
45
53
  });
46
- /** {@link PermissionlessPriceFeedAsset} */
47
- const priceFeedAssetSchema = z.looseObject({
48
- address: addressSchema,
49
- symbol: z.string(),
50
- name: z.string(),
51
- decimals: z.number()
52
- });
53
- /** {@link PermissionlessPriceFeedMarket} */
54
- const priceFeedMarketSchema = z.looseObject({
54
+ /**
55
+ * What names a market, whichever side it is being listed from.
56
+ *
57
+ * A feed's markets and an asset's markets are different reads, but they
58
+ * answer with the same market: who curates it, what it is denominated in and
59
+ * how much of the quota is taken. Only what the read is about differs, which
60
+ * is what each of the two below adds.
61
+ **/
62
+ const marketSchema = z.looseObject({
55
63
  market: addressSchema,
56
64
  marketConfigurator: addressSchema,
57
65
  curatorName: z.string().nullable(),
58
66
  marketName: z.string().nullable(),
59
- token: addressSchema,
60
- tokenSymbol: z.string().nullable(),
61
67
  underlyingSymbol: z.string().nullable(),
62
- reserve: z.boolean(),
63
68
  isUnderlying: z.boolean(),
64
69
  quotaLimit: z.number().nullable(),
65
- quotaUsed: z.number().nullable(),
70
+ quotaUsed: z.number().nullable()
71
+ });
72
+ /** {@link PermissionlessPriceFeedMarket} — the market as the feed's slot in it. */
73
+ const priceFeedMarketSchema = marketSchema.extend({
74
+ token: addressSchema,
75
+ tokenSymbol: z.string().nullable(),
76
+ reserve: z.boolean(),
66
77
  marketStalenessPeriod: z.number().nullable()
67
78
  });
68
79
  /** {@link PermissionlessPriceFeedDetails} */
@@ -83,20 +94,12 @@ const assetMarketFeedSchema = z.looseObject({
83
94
  name: z.string().nullable(),
84
95
  inStore: z.boolean()
85
96
  });
86
- /** {@link PermissionlessAssetMarket} */
87
- const assetMarketSchema = z.looseObject({
88
- market: addressSchema,
89
- marketConfigurator: addressSchema,
90
- curatorName: z.string().nullable(),
91
- marketName: z.string().nullable(),
97
+ /** {@link PermissionlessAssetMarket} — the market as what prices the asset in it. */
98
+ const assetMarketSchema = marketSchema.extend({
92
99
  underlyingToken: addressSchema,
93
- underlyingSymbol: z.string().nullable(),
94
- isUnderlying: z.boolean(),
95
100
  isShutdown: z.boolean(),
96
101
  mainFeed: assetMarketFeedSchema.nullable(),
97
- reserveFeed: assetMarketFeedSchema.nullable(),
98
- quotaLimit: z.number().nullable(),
99
- quotaUsed: z.number().nullable()
102
+ reserveFeed: assetMarketFeedSchema.nullable()
100
103
  });
101
104
  /** {@link PermissionlessAssetDetails} */
102
105
  const assetDetailsSchema = z.looseObject({
@@ -107,7 +110,13 @@ const assetDetailsSchema = z.looseObject({
107
110
  quotaLimitUsd: z.number().nullable(),
108
111
  quotaUsedUsd: z.number().nullable()
109
112
  });
110
- /** {@link PermissionlessAssetPrices} */
113
+ /**
114
+ * {@link PermissionlessAssetPrices}
115
+ *
116
+ * The same shape as {@link priceFeedMarketCapsSchema} plus the prices, but not
117
+ * an extension of it: the caps there are keyed by asset and these are keyed by
118
+ * feed, so what the two have in common is a coincidence of form.
119
+ **/
111
120
  const assetPricesSchema = z.looseObject({
112
121
  prices: addressRecord(z.string().nullable()),
113
122
  marketCaps: addressRecord(z.string().nullable()),
@@ -1,4 +1,4 @@
1
- import { isAddress, isHex } from "viem";
1
+ import { isAddress } from "viem";
2
2
  import { z } from "zod/v4";
3
3
  //#region src/permissionless/api/schemas.ts
4
4
  /**
@@ -11,8 +11,6 @@ import { z } from "zod/v4";
11
11
  **/
12
12
  /** An address, in whatever case the backend serves it. */
13
13
  const addressSchema = z.custom((value) => typeof value === "string" && isAddress(value, { strict: false }), { message: "invalid address" });
14
- /** A `0x`-prefixed hex string, as viem's `Hex`. */
15
- const hexSchema = z.custom((value) => typeof value === "string" && isHex(value), { message: "invalid hex string" });
16
14
  /**
17
15
  * A record keyed by address. Spelled out here because zod types a record key
18
16
  * by the schema's output, which the branded `Address` is not inferred as.
@@ -22,4 +20,4 @@ function addressRecord(value) {
22
20
  return z.record(key, value);
23
21
  }
24
22
  //#endregion
25
- export { addressRecord, addressSchema, hexSchema };
23
+ export { addressRecord, addressSchema };
@@ -0,0 +1,178 @@
1
+ import { TestnetStatusError } from "./errors/TestnetStatusError.js";
2
+ import { TestnetNotFoundError } from "./errors/TestnetNotFoundError.js";
3
+ import { TestnetRequestFailedError } from "./errors/TestnetRequestFailedError.js";
4
+ import { TestnetValidationError } from "./errors/TestnetValidationError.js";
5
+ import { TestnetWaitTimeoutError } from "./errors/TestnetWaitTimeoutError.js";
6
+ import "./errors/index.js";
7
+ import { testnetSchema, testnetStatusSchema } from "./schemas.js";
8
+ import { z } from "zod/v4";
9
+ //#region src/testnets/TestnetsAPI.ts
10
+ const DEFAULT_BASE_URL = "https://anvil.gearbox.foundation";
11
+ const DEFAULT_TIMEOUT = 3e4;
12
+ const DEFAULT_WAIT_TIMEOUT = 6e5;
13
+ const DEFAULT_WAIT_INTERVAL = 5e3;
14
+ const errorBodySchema = z.object({ error: z.string() });
15
+ /**
16
+ * Client for anvil-manager, which runs the anvil forks Gearbox calls
17
+ * testnets. It manages non-persistent testnets only, addressed by their
18
+ * execution id.
19
+ *
20
+ * ```ts
21
+ * const testnets = new TestnetsAPI({ apiKey: process.env.ANVIL_MANAGER_API_KEY });
22
+ * const { executionId } = await testnets.create({ network: "Mainnet", timeout: "2h" });
23
+ * const status = await testnets.waitUntilReady(executionId);
24
+ * // ... use status.rpcUrl ...
25
+ * await testnets.kill(executionId);
26
+ * ```
27
+ *
28
+ * Every method throws a {@link TestnetsError} subclass when it fails, except
29
+ * when a response body is not JSON: then it rejects with the error of
30
+ * `response.json()`.
31
+ **/
32
+ var TestnetsAPI = class {
33
+ logger;
34
+ #baseUrl;
35
+ #apiKey;
36
+ #timeout;
37
+ constructor(options = {}) {
38
+ this.#baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
39
+ this.#apiKey = options.apiKey;
40
+ this.#timeout = options.timeout ?? DEFAULT_TIMEOUT;
41
+ this.logger = options.logger?.child?.({ name: "TestnetsAPI" }) ?? options.logger;
42
+ }
43
+ /**
44
+ * Base URL every request of this client is sent to.
45
+ **/
46
+ get baseUrl() {
47
+ return this.#baseUrl;
48
+ }
49
+ /**
50
+ * Every testnet anvil-manager knows of, persistent ones included.
51
+ **/
52
+ async list() {
53
+ const url = this.#url("/api/v1/forks");
54
+ const response = await this.#fetch(url, { method: "GET" });
55
+ return this.#decode(url, response, z.array(testnetSchema));
56
+ }
57
+ /**
58
+ * Status of one testnet.
59
+ *
60
+ * @param id - Execution id of the testnet.
61
+ * @throws {@link TestnetNotFoundError} when there is no such testnet.
62
+ **/
63
+ async get(id) {
64
+ const url = this.#forkUrl(id);
65
+ const response = await this.#fetch(url, { method: "GET" });
66
+ return this.#decode(url, response, testnetStatusSchema);
67
+ }
68
+ /**
69
+ * Starts a testnet. It answers as soon as the testnet is created, long
70
+ * before it is {@link TestnetStatus.ready}.
71
+ *
72
+ * @param files - Saved in the testnet's shared dir, where scripts and tasks
73
+ * can read them.
74
+ **/
75
+ async create(request, files) {
76
+ const url = this.#url("/api/v1/forks");
77
+ const response = await this.#fetch(url, {
78
+ method: "POST",
79
+ ...createBody(request, files)
80
+ });
81
+ return this.#decode(url, response, testnetStatusSchema);
82
+ }
83
+ /**
84
+ * Stops a testnet. Stopping one that is already stopped succeeds.
85
+ *
86
+ * @param id - Execution id of the testnet.
87
+ * @throws {@link TestnetNotFoundError} when there is no such testnet.
88
+ * @throws {@link TestnetStatusError} with status 400 when the testnet is
89
+ * persistent.
90
+ **/
91
+ async kill(id) {
92
+ await this.#fetch(this.#forkUrl(id), { method: "DELETE" });
93
+ }
94
+ /**
95
+ * Polls a testnet's status until it is {@link TestnetStatus.ready}.
96
+ *
97
+ * @param id - Execution id of the testnet.
98
+ * @returns The first status that is ready.
99
+ * @throws {@link TestnetWaitTimeoutError} when the testnet is not ready in
100
+ * time. Any error of a poll is thrown as is, without retrying.
101
+ **/
102
+ async waitUntilReady(id, options = {}) {
103
+ const { timeout = DEFAULT_WAIT_TIMEOUT, interval = DEFAULT_WAIT_INTERVAL } = options;
104
+ const deadline = Date.now() + timeout;
105
+ while (true) {
106
+ const status = await this.get(id);
107
+ if (status.ready) return status;
108
+ const remaining = deadline - Date.now();
109
+ if (remaining <= 0) throw new TestnetWaitTimeoutError(this.#forkUrl(id), id, timeout);
110
+ this.logger?.debug(`testnet ${id} is not ready yet`);
111
+ await new Promise((resolve) => setTimeout(resolve, Math.min(interval, remaining)));
112
+ }
113
+ }
114
+ #url(path) {
115
+ return `${this.#baseUrl}${path}`;
116
+ }
117
+ #forkUrl(id) {
118
+ return this.#url(`/api/v1/forks/${encodeURIComponent(id)}`);
119
+ }
120
+ /**
121
+ * Sends one request and returns its response once it is known to be 2xx.
122
+ **/
123
+ async #fetch(url, init) {
124
+ const headers = new Headers(init.headers);
125
+ headers.set("accept", "application/json");
126
+ if (this.#apiKey) headers.set("authorization", `Bearer ${this.#apiKey}`);
127
+ let response;
128
+ try {
129
+ response = await fetch(url, {
130
+ ...init,
131
+ headers,
132
+ signal: AbortSignal.timeout(this.#timeout)
133
+ });
134
+ } catch (error) {
135
+ throw new TestnetRequestFailedError(url, error);
136
+ }
137
+ if (!response.ok) {
138
+ const responseBody = await response.text();
139
+ const details = errorBodySchema.safeParse(responseBody).data?.error;
140
+ throw response.status === 404 ? new TestnetNotFoundError(url, details) : new TestnetStatusError(url, response.status, details);
141
+ }
142
+ return response;
143
+ }
144
+ /**
145
+ * Body of a 2xx response, decoded.
146
+ **/
147
+ async #decode(url, response, schema) {
148
+ const payload = await response.json();
149
+ const parsed = schema.safeParse(payload);
150
+ if (!parsed.success) {
151
+ const error = new TestnetValidationError(url, parsed.error);
152
+ this.logger?.error(error, "anvil-manager response does not match the testnet schemas");
153
+ throw error;
154
+ }
155
+ return parsed.data;
156
+ }
157
+ };
158
+ /**
159
+ * Body and content type of a create request: JSON alone, or a multipart form
160
+ * with the JSON in its `json` field when there are files to upload.
161
+ **/
162
+ function createBody(request, files) {
163
+ const json = JSON.stringify(request);
164
+ if (!files || Object.keys(files).length === 0) return {
165
+ body: json,
166
+ headers: { "content-type": "application/json" }
167
+ };
168
+ const form = new FormData();
169
+ form.append("json", json);
170
+ for (const [name, contents] of Object.entries(files)) form.append("file", toBlob(contents), name);
171
+ return { body: form };
172
+ }
173
+ function toBlob(contents) {
174
+ if (contents instanceof Blob) return contents;
175
+ return new Blob([typeof contents === "string" ? contents : new Uint8Array(contents)]);
176
+ }
177
+ //#endregion
178
+ export { TestnetsAPI };
@@ -0,0 +1,14 @@
1
+ import { TestnetStatusError } from "./TestnetStatusError.js";
2
+ //#region src/testnets/errors/TestnetNotFoundError.ts
3
+ /**
4
+ * Thrown when anvil-manager answered 404: there is no testnet with that
5
+ * execution id.
6
+ **/
7
+ var TestnetNotFoundError = class extends TestnetStatusError {
8
+ name = "TestnetNotFoundError";
9
+ constructor(url, details) {
10
+ super(url, 404, details);
11
+ }
12
+ };
13
+ //#endregion
14
+ export { TestnetNotFoundError };
@@ -0,0 +1,23 @@
1
+ import { TestnetsError } from "./TestnetsError.js";
2
+ //#region src/testnets/errors/TestnetRequestFailedError.ts
3
+ /**
4
+ * Thrown when a request to anvil-manager never completed: the network was
5
+ * down, or it took longer than the client's timeout.
6
+ **/
7
+ var TestnetRequestFailedError = class extends TestnetsError {
8
+ name = "TestnetRequestFailedError";
9
+ constructor(url, cause) {
10
+ super(timedOut(cause) ? "The request to anvil-manager timed out." : "The request to anvil-manager failed.", {
11
+ url,
12
+ cause
13
+ });
14
+ }
15
+ };
16
+ /**
17
+ * Whether a caught value is the rejection `AbortSignal.timeout` produces.
18
+ **/
19
+ function timedOut(error) {
20
+ return error instanceof Error && error.name === "TimeoutError";
21
+ }
22
+ //#endregion
23
+ export { TestnetRequestFailedError };
@@ -0,0 +1,18 @@
1
+ import { TestnetsError } from "./TestnetsError.js";
2
+ //#region src/testnets/errors/TestnetStatusError.ts
3
+ /**
4
+ * Thrown when anvil-manager answered with a status outside the 2xx range. What
5
+ * it said about it, when it said anything, is the `details` of the error.
6
+ **/
7
+ var TestnetStatusError = class extends TestnetsError {
8
+ name = "TestnetStatusError";
9
+ constructor(url, status, details) {
10
+ super(`anvil-manager answered ${status}.`, {
11
+ url,
12
+ status,
13
+ details
14
+ });
15
+ }
16
+ };
17
+ //#endregion
18
+ export { TestnetStatusError };
@@ -0,0 +1,23 @@
1
+ import { TestnetsError } from "./TestnetsError.js";
2
+ import { z } from "zod/v4";
3
+ //#region src/testnets/errors/TestnetValidationError.ts
4
+ /**
5
+ * Thrown when anvil-manager answered, but with a payload the testnet schemas
6
+ * do not describe, i.e. the two are of different versions.
7
+ **/
8
+ var TestnetValidationError = class extends TestnetsError {
9
+ name = "TestnetValidationError";
10
+ /**
11
+ * The zod failure itself, e.g. for `z.treeifyError(error.zodError)`.
12
+ **/
13
+ zodError;
14
+ constructor(url, zodError) {
15
+ super("The anvil-manager response does not match the testnet schemas.", {
16
+ url,
17
+ metaMessages: z.prettifyError(zodError).split("\n")
18
+ });
19
+ this.zodError = zodError;
20
+ }
21
+ };
22
+ //#endregion
23
+ export { TestnetValidationError };