coral-xyz / anchor

⚓ Solana Sealevel Framework
https://anchor-lang.com
Apache License 2.0
3.68k stars 1.34k forks source link

Translate CPI error codes to human readable string #126

Open armaniferrante opened 3 years ago

armaniferrante commented 3 years ago

Currently, only error codes from frontend programs (i.e. the one directly called from the client) are translated into human readable strings. This is because Solana programs immediately halt if a CPI instruction fails, and so the client can't know about/have the IDL + error codes of the entire call graph being invoked--especially since opaque #[interface] programs can be invoked.

One solution here might be to change the way clients handle errors all together by asking the program to do the translation of an error code, instead of the client (which currently just looks at an error code and tries to match it against the codes in the IDL). The flow might work as follows.

Client executes transaction. Program performs CPI. CPI errors, halting transaction. Client receives error code. Client uses program logs to deduce the program that returned the error code. Client then asks the program to translate the error into a human readable string (which can be done via simulate transaction + msg! log).

To achieve this, the codegen would add an additional translate_error instruction that takes an error code, and returns a 'static &str.

With this solution, error codes could also be removed from the IDL.

armaniferrante commented 3 years ago

Perhaps a more straightforward solution is to treat errors similar to events. We can log errors as msg! logs to the transaction, prefixing the logs with some magic string or 8 byte identifier. Anchor clients can parse the logs on error, and throw the error logged to the transaction.