-
Notifications
You must be signed in to change notification settings - Fork 239
/
feature-detection.ts
711 lines (672 loc) · 18.5 KB
/
feature-detection.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
import {
Feature,
FeatureName,
FeatureWithEnabled,
SUPPORTED_FEATURES,
} from "../constants/contract-features";
import { ContractWrapper } from "../core/classes/contract-wrapper";
import { DetectableFeature } from "../core/interfaces/DetectableFeature";
import { decode } from "../lib/cbor-decode.js";
import {
Abi,
AbiEvent,
AbiFunction,
AbiSchema,
AbiTypeSchema,
ContractInfoSchema,
ContractSource,
FullPublishMetadata,
FullPublishMetadataSchemaOutput,
PreDeployMetadata,
PreDeployMetadataFetched,
PreDeployMetadataFetchedSchema,
PublishedMetadata,
} from "../schema/contracts/custom";
import { ExtensionNotImplementedError } from "./error";
import { ThirdwebStorage } from "@thirdweb-dev/storage";
import bs58 from "bs58";
import { BaseContract, BigNumber, ethers } from "ethers";
import { z } from "zod";
/**
* @internal
* @param abi
* @param feature
*/
function matchesAbiInterface(abi: Abi, feature: Feature): boolean {
// returns true if all the functions in `interfaceToMatch` are found in `contract` (removing any duplicates)
return hasMatchingAbi(abi, feature.abis);
}
/**
* @internal
* @param contractWrapper
* @param abi
* @returns
*/
export function matchesPrebuiltAbi<T extends BaseContract>(
contractWrapper: ContractWrapper<BaseContract>,
abi: Abi,
): contractWrapper is ContractWrapper<T> {
return hasMatchingAbi(contractWrapper.abi as Abi, [abi]);
}
/**
* @internal
* @param contractAbi
* @param featureAbis
* @returns
*/
export function hasMatchingAbi(contractAbi: Abi, featureAbis: readonly Abi[]) {
const contractFn = extractFunctionsFromAbi(contractAbi);
const interfaceFn = featureAbis.flatMap((i: any) =>
extractFunctionsFromAbi(i),
);
// match every function and their arguments
const intersection = contractFn.filter((fn) => {
const match = interfaceFn.find(
(iFn) =>
iFn.name === fn.name &&
iFn.inputs.length === fn.inputs.length &&
iFn.inputs.every((i, index) => {
if (i.type === "tuple" || i.type === "tuple[]") {
// check that all properties in the tuple are the same type
return (
i.type === fn.inputs[index].type &&
i.components?.every((c, cIndex) => {
return c.type === fn.inputs[index].components?.[cIndex]?.type;
})
);
}
return i.type === fn.inputs[index].type;
}),
);
return match !== undefined;
});
return intersection.length === interfaceFn.length;
}
/**
* @internal
*/
export async function extractConstructorParams(
predeployMetadataUri: string,
storage: ThirdwebStorage,
) {
const meta = await fetchPreDeployMetadata(predeployMetadataUri, storage);
return extractConstructorParamsFromAbi(meta.abi);
}
/**
* @internal
* @param predeployMetadataUri
* @param storage
*/
export async function extractFunctions(
predeployMetadataUri: string,
storage: ThirdwebStorage,
): Promise<AbiFunction[]> {
const metadata = await fetchPreDeployMetadata(predeployMetadataUri, storage);
return extractFunctionsFromAbi(metadata.abi, metadata.metadata);
}
/**
* @internal
* @param name
* @param metadata
* @param type
*/
function extractCommentFromMetadata(
name: string | undefined,
metadata: Record<string, any> | undefined,
type: "methods" | "events",
) {
return (
metadata?.output?.userdoc?.[type]?.[
Object.keys(metadata?.output?.userdoc[type] || {}).find((fn) =>
fn.includes(name || "unknown"),
) || ""
]?.notice ||
metadata?.output?.devdoc?.[type]?.[
Object.keys(metadata?.output?.devdoc[type] || {}).find((fn) =>
fn.includes(name || "unknown"),
) || ""
]?.details
);
}
/**
*
* @param abi
* @returns
* @internal
*/
export function extractConstructorParamsFromAbi(
abi: z.input<typeof AbiSchema>,
) {
for (const input of abi) {
if (input.type === "constructor") {
return input.inputs || [];
}
}
return [];
}
/**
*
* @param abi
* @param functionName
* @returns
* @internal
*/
export function extractFunctionParamsFromAbi(
abi: z.input<typeof AbiSchema>,
functionName: string,
) {
for (const input of abi) {
if (input.type === "function" && input.name === functionName) {
return input.inputs || [];
}
}
return [];
}
/**
* @internal
* @param abi
* @param metadata
*/
export function extractFunctionsFromAbi(
abi: Abi,
metadata?: Record<string, any>,
): AbiFunction[] {
const functions = (abi || []).filter((el) => el.type === "function");
const parsed: AbiFunction[] = [];
for (const f of functions) {
const doc = extractCommentFromMetadata(f.name, metadata, "methods");
const args =
f.inputs?.map((i) => `${i.name || "key"}: ${toJSType(i)}`)?.join(", ") ||
"";
const fargs = args ? `, ${args}` : "";
const out = f.outputs?.map((o) => toJSType(o, true))?.join(", ");
const promise = out ? `: Promise<${out}>` : `: Promise<TransactionResult>`;
const signature = `contract.call("${f.name}"${fargs})${promise}`;
parsed.push({
inputs: f.inputs || [],
outputs: f.outputs || [],
name: f.name || "unknown",
signature,
stateMutability: f.stateMutability || "",
comment: doc,
});
}
return parsed;
}
/**
* @internal
* @param abi
* @param metadata
*/
export function extractEventsFromAbi(
abi: Abi,
metadata?: Record<string, any>,
): AbiEvent[] {
const events = (abi || []).filter((el) => el.type === "event");
const parsed: AbiEvent[] = [];
for (const e of events) {
const doc = extractCommentFromMetadata(e.name, metadata, "events");
parsed.push({
inputs: e.inputs || [],
outputs: e.outputs || [],
name: e.name || "unknown",
comment: doc,
});
}
return parsed;
}
function toJSType(
contractType: z.input<typeof AbiTypeSchema>,
isReturnType = false,
withName = false,
): string {
let jsType = contractType.type;
let isArray = false;
if (jsType.endsWith("[]")) {
isArray = true;
jsType = jsType.slice(0, -2);
}
if (jsType.startsWith("bytes")) {
jsType = "BytesLike";
}
if (jsType.startsWith("uint") || jsType.startsWith("int")) {
jsType = isReturnType ? "BigNumber" : "BigNumberish";
}
if (jsType.startsWith("bool")) {
jsType = "boolean";
}
if (jsType === "address") {
jsType = "string";
}
if (jsType === "tuple") {
if (contractType.components) {
jsType = `{ ${contractType.components
.map((a) => toJSType(a, false, true))
.join(", ")} }`;
}
}
if (isArray) {
jsType += "[]";
}
if (withName) {
jsType = `${contractType.name}: ${jsType}`;
}
return jsType;
}
/**
* @internal
* @param bytecode
*/
export function extractMinimalProxyImplementationAddress(
bytecode: string,
): string | undefined {
// EIP-1167 clone minimal proxy - https://eips.ethereum.org/EIPS/eip-1167
if (bytecode.startsWith("0x363d3d373d3d3d363d73")) {
const implementationAddress = bytecode.slice(22, 62);
return `0x${implementationAddress}`;
}
// Minimal Proxy with receive() from 0xSplits - https://github.com/0xSplits/splits-contracts/blob/c7b741926ec9746182d0d1e2c4c2046102e5d337/contracts/libraries/Clones.sol
if (bytecode.startsWith("0x36603057343d5230")) {
// +40 = size of addr
const implementationAddress = bytecode.slice(122, 122 + 40);
return `0x${implementationAddress}`;
}
// 0age's minimal proxy - https://medium.com/coinmonks/the-more-minimal-proxy-5756ae08ee48
if (bytecode.startsWith("0x3d3d3d3d363d3d37363d73")) {
// +40 = size of addr
const implementationAddress = bytecode.slice(24, 24 + 40);
return `0x${implementationAddress}`;
}
// vyper's minimal proxy (uniswap v1) - https://etherscan.io/address/0x09cabec1ead1c0ba254b09efb3ee13841712be14#code
if (bytecode.startsWith("0x366000600037611000600036600073")) {
const implementationAddress = bytecode.slice(32, 32 + 40);
return `0x${implementationAddress}`;
}
return undefined;
}
/**
* @internal
* @param address
* @param provider
*/
export async function resolveContractUriFromAddress(
address: string,
provider: ethers.providers.Provider,
): Promise<string | undefined> {
const bytecode = await provider.getCode(address);
if (bytecode === "0x") {
const chain = await provider.getNetwork();
throw new Error(
`Contract at ${address} does not exist on chain '${chain.name}' (chainId: ${chain.chainId})`,
);
}
try {
const implementationAddress =
extractMinimalProxyImplementationAddress(bytecode);
if (implementationAddress) {
return await resolveContractUriFromAddress(
`0x${implementationAddress}`,
provider,
);
}
} catch (e) {
// ignore
}
// EIP-1967 proxy storage slots - https://eips.ethereum.org/EIPS/eip-1967
try {
const proxyStorage = await provider.getStorageAt(
address,
BigNumber.from(
"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
),
);
const implementationAddress = ethers.utils.hexStripZeros(proxyStorage);
if (implementationAddress !== "0x") {
return await resolveContractUriFromAddress(
implementationAddress,
provider,
);
}
} catch (e) {
// ignore
}
// TODO support other types of proxies
return await extractIPFSHashFromBytecode(bytecode);
}
/**
* @internal
* @param bytecode
*/
export function extractIPFSHashFromBytecode(
bytecode: string,
): string | undefined {
const numericBytecode = hexToBytes(bytecode);
const cborLength: number =
numericBytecode[numericBytecode.length - 2] * 0x100 +
numericBytecode[numericBytecode.length - 1];
const bytecodeBuffer = Uint8Array.from(
numericBytecode.slice(numericBytecode.length - 2 - cborLength, -2),
);
const cborData = decode(bytecodeBuffer);
if ("ipfs" in cborData && cborData["ipfs"]) {
try {
return `ipfs://${bs58.encode(cborData["ipfs"])}`;
} catch (e) {
console.warn("feature-detection ipfs cbor failed", e);
}
}
return undefined;
}
/**
* @internal
* @param hex
*/
function hexToBytes(hex: string | number) {
hex = hex.toString(16);
if (!hex.startsWith("0x")) {
hex = `0x${hex}`;
}
if (!isHexStrict(hex)) {
throw new Error(`Given value "${hex}" is not a valid hex string.`);
}
hex = hex.replace(/^0x/i, "");
const bytes: number[] = [];
for (let c = 0; c < hex.length; c += 2) {
bytes.push(parseInt(hex.slice(c, c + 2), 16));
}
return bytes;
}
/**
* @internal
* @param hex
*/
function isHexStrict(hex: string | number) {
return (
(typeof hex === "string" || typeof hex === "number") &&
/^(-)?0x[0-9a-f]*$/i.test(hex.toString())
);
}
/**
* @internal
* @param address
* @param provider
* @param storage
*/
export async function fetchContractMetadataFromAddress(
address: string,
provider: ethers.providers.Provider,
storage: ThirdwebStorage,
) {
const compilerMetadataUri = await resolveContractUriFromAddress(
address,
provider,
);
if (!compilerMetadataUri) {
throw new Error(`Could not resolve metadata for contract at ${address}`);
}
return await fetchContractMetadata(compilerMetadataUri, storage);
}
/**
* @internal
* @param compilerMetadataUri
* @param storage
*/
export async function fetchContractMetadata(
compilerMetadataUri: string,
storage: ThirdwebStorage,
): Promise<PublishedMetadata> {
const metadata = await storage.downloadJSON(compilerMetadataUri);
const abi = AbiSchema.parse(metadata.output.abi);
const compilationTarget = metadata.settings.compilationTarget;
const targets = Object.keys(compilationTarget);
const name = compilationTarget[targets[0]];
const info = ContractInfoSchema.parse({
title: metadata.output.devdoc.title,
author: metadata.output.devdoc.author,
details: metadata.output.devdoc.detail,
notice: metadata.output.userdoc.notice,
});
const licenses: string[] = [
...new Set(
Object.entries(metadata.sources).map(([, src]) => (src as any).license),
),
];
return {
name,
abi,
metadata,
info,
licenses,
};
}
/**
* @internal
* @param publishedMetadata
* @param storage
*/
export async function fetchSourceFilesFromMetadata(
publishedMetadata: PublishedMetadata,
storage: ThirdwebStorage,
): Promise<ContractSource[]> {
return await Promise.all(
Object.entries(publishedMetadata.metadata.sources).map(
async ([path, info]) => {
const urls = (info as any).urls as string[];
const ipfsLink = urls
? urls.find((url) => url.includes("ipfs"))
: undefined;
if (ipfsLink) {
const ipfsHash = ipfsLink.split("ipfs/")[1];
// 5 sec timeout for sources that haven't been uploaded to ipfs
const timeout = new Promise<string>((_r, rej) =>
setTimeout(() => rej("timeout"), 5000),
);
const source = await Promise.race([
(await storage.download(`ipfs://${ipfsHash}`)).text(),
timeout,
]);
return {
filename: path,
source,
};
} else {
return {
filename: path,
source:
(info as any).content ||
"Could not find source for this contract",
};
}
},
),
);
}
/**
* @internal
* @param publishMetadataUri
* @param storage
*/
export async function fetchRawPredeployMetadata(
publishMetadataUri: string,
storage: ThirdwebStorage,
) {
return PreDeployMetadata.parse(
JSON.parse(await (await storage.download(publishMetadataUri)).text()),
);
}
/**
* Fetch the metadata coming from CLI, this is before deploying or releasing the contract.
* @internal
* @param publishMetadataUri
* @param storage
*/
export async function fetchPreDeployMetadata(
publishMetadataUri: string,
storage: ThirdwebStorage,
): Promise<PreDeployMetadataFetched> {
const rawMeta = await fetchRawPredeployMetadata(publishMetadataUri, storage);
const deployBytecode = await (
await storage.download(rawMeta.bytecodeUri)
).text();
const parsedMeta = await fetchContractMetadata(rawMeta.metadataUri, storage);
return PreDeployMetadataFetchedSchema.parse({
...rawMeta,
...parsedMeta,
bytecode: deployBytecode,
});
}
/**
* Fetch and parse the full metadata AFTER creating a release, with all the extra information (version, readme, etc)
* @internal
* @param publishMetadataUri
* @param storage
*/
export async function fetchExtendedReleaseMetadata(
publishMetadataUri: string,
storage: ThirdwebStorage,
): Promise<FullPublishMetadata> {
const meta = await (await storage.download(publishMetadataUri)).text();
return FullPublishMetadataSchemaOutput.parse(JSON.parse(meta));
}
/**
* Processes ALL supported features and sets whether the passed in abi supports each individual feature
* @internal
* @param abi
* @param features
* @returns the nested struct of all features and whether they're detected in the abi
*/
export function detectFeatures(
abi: Abi,
features: Record<string, Feature> = SUPPORTED_FEATURES,
): Record<string, FeatureWithEnabled> {
const results: Record<string, FeatureWithEnabled> = {};
for (const featureKey in features) {
const feature = features[featureKey];
const enabled = matchesAbiInterface(abi, feature);
const childResults = detectFeatures(abi, feature.features);
results[featureKey] = {
...feature,
features: childResults,
enabled,
} as FeatureWithEnabled;
}
return results;
}
function extractFeatures(
input: Record<string, FeatureWithEnabled>,
enabledExtensions: FeatureWithEnabled[],
) {
if (!input) {
return;
}
for (const extensionKey in input) {
const extension = input[extensionKey];
// if extension is enabled, then add it to enabledFeatures
if (extension.enabled) {
enabledExtensions.push(extension);
}
// recurse
extractFeatures(extension.features, enabledExtensions);
}
}
/**
* Return all the detected features in the abi
* @param abi - parsed array of abi entries
* @returns array of all detected extensions with full information on each feature
* @public
*/
export function getAllDetectedFeatures(abi: Abi): FeatureWithEnabled[] {
const features: FeatureWithEnabled[] = [];
extractFeatures(detectFeatures(abi), features);
return features;
}
/**
* Return all the detected features names in the abi
* @param abi - parsed array of abi entries
* @returns array of all detected features names
* @public
*/
export function getAllDetectedFeatureNames(abi: Abi): string[] {
const features: FeatureWithEnabled[] = [];
extractFeatures(detectFeatures(abi), features);
return features.map((f) => f.name);
}
/**
* Checks whether the given ABI supports a given feature
* @internal
* @param abi
* @param featureName
*/
export function isFeatureEnabled(
abi: z.input<typeof AbiSchema>,
featureName: FeatureName,
): boolean {
const features = detectFeatures(abi);
return _featureEnabled(features, featureName);
}
/**
* Checks whether the given DetectableFeature is defined
* @internal
* @param namespace The namespace to check
* @param feature The corresponding feature
*/
export function assertEnabled<T extends DetectableFeature>(
namespace: T | undefined,
feature: Feature,
) {
if (!namespace) {
throw new ExtensionNotImplementedError(feature);
}
return namespace as T;
}
/**
* Type guard for contractWrappers depending on passed feature name
* @internal
* @param contractWrapper
* @param featureName
*/
export function detectContractFeature<T extends BaseContract>(
contractWrapper: ContractWrapper<BaseContract>,
featureName: FeatureName,
): contractWrapper is ContractWrapper<T> {
return isFeatureEnabled(AbiSchema.parse(contractWrapper.abi), featureName);
}
/**
* Searches the feature map for featureName and returns whether its enabled
* @internal
* @param features
* @param featureName
*/
function _featureEnabled(
features: Record<string, FeatureWithEnabled>,
featureName: FeatureName,
): boolean {
const keys = Object.keys(features);
if (!keys.includes(featureName)) {
let found = false;
for (const key of keys) {
const f = features[key];
found = _featureEnabled(
f.features as Record<string, FeatureWithEnabled>,
featureName,
);
if (found) {
break;
}
}
return found;
}
const feature = features[featureName];
return feature.enabled;
}
/**
* @internal
* @param contractWrapper
* @param functionName
*/
export function hasFunction<TContract extends BaseContract>(
functionName: string,
contractWrapper: ContractWrapper<any>,
): contractWrapper is ContractWrapper<TContract> {
return functionName in contractWrapper.readContract.functions;
}