Error Initializing Legacy Anchor IDL
Solana Explorer, a popular platform for accessing and managing the Anchor blockchain, has encountered issues with initializing legacy IDLs in the TypeScript SDK. One specific error reported is the message “undefined is not an object (evaluating ‘s.split’)”.
This issue occurs when attempting to convert the domain name explorer.solana.com
to camelCase, which is required by some older IDLs. The issue is with how TypeScript handles the split()
method of strings in some cases.
The issue:
When converting the domain name to camelCase, TypeScript attempts to use the split()
method with an empty string as the separator. However, when explorer.solana.com
is not a valid string (for example, it does not contain any spaces), s.split()
returns an array containing only one element: the entire input string. In this case, undefined
is returned instead of an object.
The solution:
To solve this problem, you can use a different approach to convert the domain name to camelCase. One way to do this is to use regular expressions (regex) in your TypeScript code.
Here is an updated example that uses regex to achieve the desired result:
;
import * as ts from 'typescript';
// Suppose we have the following IDL:
const explorerIdl =
// This is an example of an Anchor IDL.
// It should be converted to camelCase like this: "explorer.solana.com" -> "exPlOrer.solAnA.com"
function convertToCamelCase(idl: string): string {
const parser = ts.createParser(idl);
const sourceFile = ts.createSourceFile('idl.ts', idl, ts.ScriptTarget.ES2015);
let camelCaseIdl = '';
for (const token of parser.getTokens(sourceFile)) {
if (ts.isIdentifier(token) && !token.value.startsWith('_')) {
camelCaseIdl += token.name;
} else if (ts.isStringLiteral(token)) {
const regex = new RegExp(
${token.value.replace(/([A-Z])|([a-z])/g, '$1$1')}
, 'u');let match: RegExpExecArray | null;
while ((match = regex.exec(token.value)) !== null) {
camelCaseIdl += match[0][0].toLowerCase();
}
} else if (ts.isExpressionStatement(token)) {
camelCaseIdl += convertToCamelCase(token.expression);
}
}
return camelCaseIdl;
}
console.log(convertToCamelCase(explorerIdl));
In this updated example, the convertToCamelCase()
function uses a regex to check whether each token in the IDL is an identifier or a literal string. If it is an identifier, it simply appends its name to the camelCase IDL string. If it is a literal string, it converts the string using the same regex and then adds its first letter (in uppercase) to the camelCase IDL string.
Conclusion:
The problem with the original code can be solved by using regular expressions in TypeScript to convert the domain name to camelCase. This approach ensures that the correct objects are returned, eliminating the “undefined is not an object” error.