-
Notifications
You must be signed in to change notification settings - Fork 66
/
config.ts
492 lines (432 loc) · 16.6 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import { ethers } from 'ethers';
import { SuperRefinement, z } from 'zod';
import forEach from 'lodash/forEach';
import includes from 'lodash/includes';
import size from 'lodash/size';
import { goSync } from '@api3/promise-utils';
import { version as packageVersion } from '../../package.json';
import { OIS, oisSchema, RELAY_METADATA_TYPES } from '../ois';
import { SchemaType } from '../types';
export const evmAddressSchema = z.string().regex(/^0x[a-fA-F0-9]{40}$/);
export const evmIdSchema = z.string().regex(/^0x[a-fA-F0-9]{64}$/);
// We use a convention for deriving endpoint ID from OIS title and endpoint name,
// but we are not enforcing the convention in docs:
// https://docs.api3.org/airnode/latest/concepts/endpoint.html#endpointid
export const endpointIdSchema = z.string();
export const triggerSchema = z
.object({
endpointId: endpointIdSchema,
endpointName: z.string(),
oisTitle: z.string(),
})
.strict();
export const rrpTriggerSchema = triggerSchema
.merge(
z.object({
cacheResponses: z.boolean(),
})
)
.strict();
export const triggersSchema = z
.object({
rrp: z.array(rrpTriggerSchema),
http: z.array(triggerSchema),
httpSignedData: z.array(triggerSchema),
})
.strict();
export const templateSchema = z
.object({
templateId: evmIdSchema,
endpointId: endpointIdSchema,
encodedParameters: z.string(),
})
.strict();
export const logLevelSchema = z.union([z.literal('DEBUG'), z.literal('INFO'), z.literal('WARN'), z.literal('ERROR')]);
export const logFormatSchema = z.union([z.literal('json'), z.literal('plain')]);
export const chainTypeSchema = z.literal('evm');
export const chainContractsSchema = z
.object({
AirnodeRrp: evmAddressSchema,
})
.strict();
export const providerSchema = z
.object({
url: z.string().url(),
})
.strict();
export const providersSchema = z.record(z.string(), providerSchema);
export const amountSchema = z
.object({
value: z.number().lte(9007199254740991), // 2**53 - 1
unit: z.union([
z.literal('wei'),
z.literal('kwei'),
z.literal('mwei'),
z.literal('gwei'),
z.literal('szabo'),
z.literal('finney'),
z.literal('ether'),
]),
})
.strict();
export const latestBlockPercentileGasPriceStrategySchema = z
.object({
gasPriceStrategy: z.literal('latestBlockPercentileGasPrice'),
percentile: z.number().int(),
minTransactionCount: z.number().int(),
pastToCompareInBlocks: z.number().int(),
maxDeviationMultiplier: z.number(),
})
.strict();
export const providerRecommendedGasPriceStrategySchema = z
.object({
gasPriceStrategy: z.literal('providerRecommendedGasPrice'),
recommendedGasPriceMultiplier: z.number().positive(),
})
.strict();
export const providerRecommendedEip1559GasPriceStrategySchema = z
.object({
gasPriceStrategy: z.literal('providerRecommendedEip1559GasPrice'),
baseFeeMultiplier: z.number().int(),
priorityFee: amountSchema,
})
.strict();
export const constantGasPriceStrategySchema = z
.object({
gasPriceStrategy: z.literal('constantGasPrice'),
gasPrice: amountSchema,
})
.strict();
export const gasPriceOracleStrategySchema = z.discriminatedUnion('gasPriceStrategy', [
latestBlockPercentileGasPriceStrategySchema,
providerRecommendedGasPriceStrategySchema,
providerRecommendedEip1559GasPriceStrategySchema,
constantGasPriceStrategySchema,
]);
export const gasPriceOracleSchema = z
.array(gasPriceOracleStrategySchema)
.nonempty()
.superRefine((strategies, ctx) => {
const constantGasPriceStrategy = strategies.find((strategy) => strategy.gasPriceStrategy === 'constantGasPrice');
if (!constantGasPriceStrategy) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Missing required constantGasPrice strategy`,
path: ['gasPriceOracle'],
});
}
if (strategies[strategies.length - 1]?.gasPriceStrategy !== 'constantGasPrice') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `ConstantGasPrice strategy must be set as the last strategy in the array.`,
path: ['gasPriceOracle'],
});
}
});
export const chainOptionsSchema = z
.object({
fulfillmentGasLimit: z.number().int(),
withdrawalRemainder: amountSchema.optional(),
gasPriceOracle: gasPriceOracleSchema,
})
.strict();
export const chainAuthorizationsSchema = z.object({
requesterEndpointAuthorizations: z.record(endpointIdSchema, z.array(evmAddressSchema)),
});
export const requesterEndpointAuthorizersSchema = z.array(evmAddressSchema);
export const crossChainRequesterAuthorizerSchema = z.object({
requesterEndpointAuthorizers: requesterEndpointAuthorizersSchema,
chainType: chainTypeSchema,
chainId: z.string(),
contracts: chainContractsSchema,
chainProvider: providerSchema,
});
export const chainAuthorizersSchema = z.object({
requesterEndpointAuthorizers: requesterEndpointAuthorizersSchema,
crossChainRequesterAuthorizers: z.array(crossChainRequesterAuthorizerSchema),
});
export const maxConcurrencySchema = z.number().int().positive();
const validateMaxConcurrency: SuperRefinement<{ providers: Providers; maxConcurrency: MaxConcurrency }> = (
chainConfig,
ctx
) => {
if (chainConfig.maxConcurrency < size(chainConfig.providers)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Concurrency limit can't be lower than the number of providers for given chain`,
path: ['maxConcurrency'],
});
}
};
export const chainConfigSchema = z
.object({
authorizers: chainAuthorizersSchema,
authorizations: chainAuthorizationsSchema,
blockHistoryLimit: z.number().int().optional(), // Defaults to BLOCK_COUNT_HISTORY_LIMIT defined in airnode-node
contracts: chainContractsSchema,
id: z.string(),
// Defaults to BLOCK_MIN_CONFIRMATIONS defined in airnode-node but may be overridden
// by a requester if the _minConfirmations reserved parameter is configured
minConfirmations: z.number().int().optional(),
type: chainTypeSchema,
options: chainOptionsSchema,
providers: providersSchema,
maxConcurrency: maxConcurrencySchema,
})
.strict()
.superRefine(validateMaxConcurrency);
export const apiKeySchema = z.string().min(30).max(120);
export const corsOriginsSchema = z.array(z.string());
export const enabledGatewaySchema = z
.object({
enabled: z.literal(true),
maxConcurrency: z.number().int().positive(),
corsOrigins: corsOriginsSchema,
})
.strict();
export const disabledGatewaySchema = z
.object({
enabled: z.literal(false),
})
.strict();
export const gatewaySchema = z.discriminatedUnion('enabled', [enabledGatewaySchema, disabledGatewaySchema]);
export const enabledHeartbeatSchema = z
.object({
enabled: z.literal(true),
apiKey: apiKeySchema,
url: z.string(),
})
.strict();
export const disabledHeartbeatSchema = z
.object({
enabled: z.literal(false),
})
.strict();
export const heartbeatSchema = z.discriminatedUnion('enabled', [enabledHeartbeatSchema, disabledHeartbeatSchema]);
export const localProviderSchema = z
.object({
type: z.literal('local'),
// Gateway server port is optional, because docker ports need to be published when starting the Airnode client
// container. Users can bind (publish) the default port to any port they want. This property is useful if the
// container is run in "network host" mode, where the container uses the host network natively (and no port
// publishing is needed).
gatewayServerPort: z.number().optional(),
})
.strict();
export const awsCloudProviderSchema = z
.object({
type: z.literal('aws'),
region: z.string(),
disableConcurrencyReservations: z.boolean(),
})
.strict();
export const gcpCloudProviderSchema = z
.object({
type: z.literal('gcp'),
region: z.string(),
projectId: z.string(),
disableConcurrencyReservations: z.boolean(),
})
.strict();
export const cloudProviderSchema = z.discriminatedUnion('type', [awsCloudProviderSchema, gcpCloudProviderSchema]);
export const localOrCloudProviderSchema = z.discriminatedUnion('type', [
localProviderSchema,
// AWS and GCP schemas used in favor of cloudProviderSchema as
// discriminatedUnion methods cannot be nested
awsCloudProviderSchema,
gcpCloudProviderSchema,
]);
const validateMnemonic: SuperRefinement<string> = (mnemonic, ctx) => {
const goWallet = goSync(() => ethers.Wallet.fromMnemonic(mnemonic));
if (!goWallet.success) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Airnode wallet mnemonic is not a valid mnemonic',
path: [],
});
}
};
export const nodeSettingsSchema = z
.object({
airnodeWalletMnemonic: z.string().superRefine(validateMnemonic),
heartbeat: heartbeatSchema,
httpGateway: gatewaySchema,
httpSignedDataGateway: gatewaySchema,
stage: z.string().regex(/^[a-z0-9-]{1,16}$/),
cloudProvider: localOrCloudProviderSchema,
logFormat: logFormatSchema,
logLevel: logLevelSchema,
nodeVersion: z.string().superRefine((version, ctx) => {
if (version === packageVersion) return;
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `The "nodeVersion" must be ${packageVersion}`,
path: [],
});
}),
})
.strict();
export const baseApiCredentialsSchema = z
.object({
securitySchemeName: z.string(),
securitySchemeValue: z.string(),
})
.strict();
export const apiCredentialsSchema = baseApiCredentialsSchema
.extend({
oisTitle: z.string(),
})
.strict();
const validateSecuritySchemesReferences: SuperRefinement<{
ois: OIS[];
apiCredentials: ApiCredentials[];
}> = (config, ctx) => {
config.ois.forEach((ois, index) => {
Object.keys(ois.apiSpecifications.security).forEach((enabledSecuritySchemeName) => {
const enabledSecurityScheme = ois.apiSpecifications.components.securitySchemes[enabledSecuritySchemeName];
if (enabledSecurityScheme && ['apiKey', 'http'].includes(enabledSecurityScheme.type)) {
const securitySchemeApiCredentials = config.apiCredentials.find(
(apiCredentials) => apiCredentials.securitySchemeName === enabledSecuritySchemeName
);
if (!securitySchemeApiCredentials) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `The security scheme is enabled but no credentials are provided in "apiCredentials"`,
path: ['ois', index, 'apiSpecifications', 'security', enabledSecuritySchemeName],
});
}
}
});
});
};
const validateTemplateSchemes: SuperRefinement<{
nodeSettings: NodeSettings;
templates: Template[];
}> = (config, ctx) => {
if (config.templates) {
config.templates.forEach((template: any) => {
// Verify that a V0/RRP templates are valid by hashing the airnodeAddress,
// endpointId and encodedParameters
const airnodeAddress = ethers.Wallet.fromMnemonic(config.nodeSettings.airnodeWalletMnemonic).address;
const derivedTemplateId = ethers.utils.solidityKeccak256(
['address', 'bytes32', 'bytes'],
[airnodeAddress, template.endpointId, template.encodedParameters]
);
if (derivedTemplateId !== template.templateId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Template is invalid`,
path: [template.templateId],
});
}
});
}
};
const validateTriggersReferences: SuperRefinement<{
ois: OIS[];
triggers: Triggers;
}> = (config, ctx) => {
forEach(config.triggers, (triggers, triggerSection) => {
forEach(triggers, (trigger, index) => {
const { oisTitle, endpointName } = trigger;
// Check that the OIS with the "oisTitle" from the trigger exists
const ois = config.ois.find((ois) => ois.title === oisTitle);
if (!ois) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `No matching OIS for trigger with OIS title "${oisTitle}"`,
path: ['triggers', triggerSection, index, 'oisTitle'],
});
return;
}
// Check that the OIS contains an endpoint from the trigger
const endpoint = ois.endpoints.find((endpoint) => endpoint.name === endpointName);
if (!endpoint) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `No matching endpoint for trigger with endpoint name "${endpointName}"`,
path: ['triggers', triggerSection, index, 'endpointName'],
});
}
});
});
};
const ensureRelayedMetadataAreNotUsedWithGateways: SuperRefinement<{
ois: OIS[];
triggers: Triggers;
}> = (config, ctx) => {
// Check whether we have `http` or `httpSignedData` trigger defined
const httpGatewaysUsed = config.triggers.http.length !== 0;
const httpSignedDataGatewaysUsed = config.triggers.httpSignedData.length !== 0;
// If we don't use a gateway there's no need to check relayed metadata
if (!httpGatewaysUsed && !httpSignedDataGatewaysUsed) return;
forEach(config.ois, (ois) => {
forEach(ois.apiSpecifications.security, (_emptyArray, securitySchemaName) => {
const securitySchema = ois.apiSpecifications.components.securitySchemes[securitySchemaName];
if (securitySchema && includes(RELAY_METADATA_TYPES, securitySchema.type)) {
if (httpGatewaysUsed) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Relayed metadata authentication can't be used with an HTTP gateway`,
path: ['ois', 'apiSpecifications', 'components', 'securitySchemes', securitySchemaName, 'type'],
});
}
if (httpSignedDataGatewaysUsed) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Relayed metadata authentication can't be used with an HTTP signed data gateway`,
path: ['ois', 'apiSpecifications', 'components', 'securitySchemes', securitySchemaName, 'type'],
});
}
}
});
});
};
export const configSchema = z
.object({
chains: z.array(chainConfigSchema),
nodeSettings: nodeSettingsSchema,
ois: z.array(oisSchema),
triggers: triggersSchema,
templates: z.array(templateSchema),
apiCredentials: z.array(apiCredentialsSchema),
})
.strict()
.superRefine(validateSecuritySchemesReferences)
.superRefine(validateTemplateSchemes)
.superRefine(validateTriggersReferences)
.superRefine(ensureRelayedMetadataAreNotUsedWithGateways);
export type Config = SchemaType<typeof configSchema>;
export type ApiCredentials = SchemaType<typeof apiCredentialsSchema>;
export type NodeSettings = SchemaType<typeof nodeSettingsSchema>;
export type Template = SchemaType<typeof templateSchema>;
export type CloudProvider = SchemaType<typeof cloudProviderSchema>;
export type LocalProvider = SchemaType<typeof localProviderSchema>;
export type AwsCloudProvider = SchemaType<typeof awsCloudProviderSchema>;
export type GcpCloudProvider = SchemaType<typeof gcpCloudProviderSchema>;
export type LocalOrCloudProvider = SchemaType<typeof localOrCloudProviderSchema>;
export type Providers = SchemaType<typeof providersSchema>;
export type Gateway = SchemaType<typeof gatewaySchema>;
export type ChainAuthorizers = SchemaType<typeof chainAuthorizersSchema>;
export type CrossChainAuthorizer = SchemaType<typeof crossChainRequesterAuthorizerSchema>;
export type RequesterEndpointAuthorizers = SchemaType<typeof requesterEndpointAuthorizersSchema>;
export type ChainAuthorizations = SchemaType<typeof chainAuthorizationsSchema>;
export type ChainOptions = SchemaType<typeof chainOptionsSchema>;
export type ChainType = SchemaType<typeof chainTypeSchema>;
export type ChainConfig = SchemaType<typeof chainConfigSchema>;
export type LatestBlockPercentileGasPriceStrategy = z.infer<typeof latestBlockPercentileGasPriceStrategySchema>;
export type ProviderRecommendedGasPriceStrategy = z.infer<typeof providerRecommendedGasPriceStrategySchema>;
export type ProviderRecommendedEip1559GasPriceStrategy = z.infer<
typeof providerRecommendedEip1559GasPriceStrategySchema
>;
export type ConstantGasPriceStrategy = z.infer<typeof constantGasPriceStrategySchema>;
export type GasPriceOracleStrategy = z.infer<typeof gasPriceOracleStrategySchema>;
export type GasPriceOracleConfig = z.infer<typeof gasPriceOracleSchema>;
export type Trigger = SchemaType<typeof triggerSchema>;
export type RrpTrigger = SchemaType<typeof rrpTriggerSchema>;
export type Triggers = SchemaType<typeof triggersSchema>;
export type Heartbeat = SchemaType<typeof heartbeatSchema>;
export type Amount = SchemaType<typeof amountSchema>;
export type EnabledGateway = SchemaType<typeof enabledGatewaySchema>;
export type MaxConcurrency = SchemaType<typeof maxConcurrencySchema>;
export const availableCloudProviders = Array.from(cloudProviderSchema.optionsMap.keys()) as CloudProvider['type'][];