Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lang: Use associated discriminator constants instead of hardcoding in #[account] #3144

Conversation

acheroncrypto
Copy link
Collaborator

Problem

The #[account] attribute generates uses hardcoded values for discriminators multiple times:

if buf.len() < #discriminator.len() {
return Err(anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into());
}
let given_disc = &buf[..#discriminator.len()];
if &#discriminator != given_disc {

This expands to:

if buf.len() < [200, 118, 9, 135, 8, 198, 62, 135].len() {
    return Err(
        anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into(),
    );
}
let given_disc = &buf[..[200, 118, 9, 135, 8, 198, 62, 135].len()];
if &[200, 118, 9, 135, 8, 198, 62, 135] != given_disc {

The discriminators were being hardcoded before, but getting the length dynamically (rather than hardcoding as 8) in #3101 made the problem more obvious.

Additionally, this makes overriding discriminators via argument e.g. discriminator = DISC or discriminator = &[1] unreliable because appending .len() to these expressions sometimes result in &usize type which causes compile errors.

Summary of changes

Use the associated discriminator constant instead of hardcoding the value. This is functionally idential as the same code now expands to:

if buf.len() < MyAccount::DISCRIMINATOR.len() {
    return Err(
        anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into(),
    );
}
let given_disc = &buf[..MyAccount::DISCRIMINATOR.len()];
if MyAccount::DISCRIMINATOR != given_disc {

Note: This PR is part of a greater effort explained in #3097.

Copy link

vercel bot commented Aug 2, 2024

@acheroncrypto is attempting to deploy a commit to the coral-xyz Team on Vercel.

A member of the Team first needs to authorize it.

@acheroncrypto acheroncrypto merged commit dc6ac2d into coral-xyz:master Aug 3, 2024
1 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant