What are the best practices I can do to secure my Solana smart contracts if I can't afford an audit?
What are the best practices I can do to secure my Solana smart contracts if I can't afford an audit?
4 Answers
You can check out this github repo where some possible exploits and their recommended safety checks are given.
To list some important ones:
- Try to avoid
AccountInfo
account type wherever possible. This is becauseAccountInfo
can contain any random wrong data. Instead of something likepub mint: AccountInfo<'info>
, usepub mint: Account<'info, Mint>
- Make sure that in the instruction which takes an
authority
account,authority
is required to be aSigner
. - Use constraints to check for account ownership. For example, if an instruction takes in a
TokenAccount
, check for ownership by the token program#[account(constraint = authority.key == &token_account.owner)]
- Close an account and reclaim its rent when it is not needed anymore.
#[account(mut, close = authority)]
The creator of the Anchor framework, Armani, has put up a repo which contains some of the common exploits and how you can prevent those through best practices. I would also highly suggest going through audit reports of some of the Top Defi protocols on Solana. There is a Automatic Auditing Tool in Solana built by Sec3; check Sec3 blogs as well, they are helpful. There are a lot of Twitter threads on security as well. That's all I can find of as of now but there is a bunch of stuff if you do some research.
While these won't comprehensively secure your program, there are a few security checks you can keep in mind;
Ownership checks:
An ownership check verifies that an account is owned by the expected public key. In the case of PDAs, that the owner of the account is the executing program.
Signer checks:
Used to verify that an account has signed a transaction. It should verify that the right parties have signed a transaction. Any account that authorizes any state update in a transaction must sign that transaction.
General Account Validation:
It's important to ensure that the provided accounts are what your code expects them to be. For example, you would want to validate that a provided PDA account's address can be derived with the expected seeds. This ensures that it is the account you expect it to be.
Data Validation:
Used to verify the inputs provided by a user. This is more related to your program logic. Check logical constraints that your program has are adhered to before saving/writing data to an account.
Validating mint of SPL token account is very important when you are working on kind of collateralized asset managements.
There should be always a way to check if collateral token mint and underlying token mint addresses matches for token accounts.
Otherwise attackers may use arbitrary mint's token account as collateral and get unerlying assets drained.