anchor
anchor copied to clipboard
Letter after number in functions and parameters name cause typescript to have undefined behavior
I have a function called a1b_receive.
When compiling, in IDL, it look like this: a1bReceive
In typescript, when doing this:
const program = anchor.workspace.MyProgram as Program<MyProgram>;
console.log(program.methods)
await program.methods.a1bReceive(...)
something interesting happen:
- console.log will output this:
{
a1BReceive: [Function (anonymous)], // notice the capital B here
}
- methods.a1bReceive will fail with the following error:
Error calling initialize function: TypeError: program.methods.a1bReceive is not a function
and, if I put program.methods.a1BReceive, typescript won't compile.
So, it look like somehow:
a1bReceive exist during compilation, but not during runtime
a1BReceive exist during runtime, but not during compilation
Another behavior, that is actually worst:
In my initialize function, I have a parameter like this:
my_a1b_param: Pubkey,
When in typescript I call this function, whatever the parameters are, my_a1b_param will ALWAYS by 11111111111111111111 (the system account public key, I guess also the default public key).
So the value is straight up changed between what is passed and what is received, and it's a very confusing issue that could potentially lead to security issue
This happens because we generate the types file in Rust using the heck library, and in the JS package, we use camelcase library, and unfortunately, they don't behave the same when there is a number in the input.
To solve this, we can add an edge case check for this exact discrepancy so that the generated types are always in sync, but generally, you'd have a better time if you avoid using numbers in your identifiers.
Reiterating here that avoiding numbers in var names is a better strategy.