anchor-spl 2.0.0-rc.1

Anchor v2 SPL account types and constraint markers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Interface account types that accept both Token and Token-2022 programs.
//!
//! Provides `TokenAccount` and `Mint` aliases for use with
//! `anchor_lang::prelude::InterfaceAccount`, accepting either
//! `TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA` (Token) or
//! `TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb` (Token-2022).
//!
//! # Usage
//!
//! ```ignore
//! use anchor_lang::prelude::InterfaceAccount;
//! use anchor_spl::token_interface::{Mint, TokenAccount};
//!
//! #[derive(Accounts)]
//! pub struct MyAccounts {
//!     #[account(token::mint = mint, token::authority = owner)]
//!     pub token_account: InterfaceAccount<TokenAccount>,
//!     pub mint: InterfaceAccount<Mint>,
//! }
//! ```

pub use crate::{
    token_2022::{PermanentDelegateInitialize, *},
    token_2022_extensions::*,
};
use {
    anchor_lang::{
        accounts::{InterfaceAccount, SlabInit, SlabSchema},
        programs::{Token, Token2022 as Token2022Program},
        require, require_eq, AccountConstraint, AnchorAccount, Id, Ids,
    },
    bytemuck::{Pod, Zeroable},
    core::ops::Deref,
    pinocchio::account::AccountView,
    solana_address::Address,
    solana_program_error::ProgramError,
    spl_token_2022_interface::{
        extension::{
            BaseStateWithExtensions, ExtensionType as Token2022ExtensionType,
            PodStateWithExtensions,
        },
        pod::{PodAccount, PodMint},
    },
};

// ---------------------------------------------------------------------------
// Interface<T> — transparent wrapper that changes validation to accept both
// Token and Token-2022 program ownership.
// ---------------------------------------------------------------------------

/// Transparent wrapper around an SPL type `T` that relaxes ownership
/// validation to accept both the Token and Token-2022 programs.
///
/// Users should not reference this type directly — use `InterfaceAccount<T>`.
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct Interface<T>(T);

// SAFETY: Interface<T> is #[repr(transparent)] over T.
// If T is Pod+Zeroable, so is Interface<T>.
unsafe impl<T: Pod> Pod for Interface<T> {}
unsafe impl<T: Zeroable> Zeroable for Interface<T> {}

impl<T> Deref for Interface<T> {
    type Target = T;
    #[inline(always)]
    fn deref(&self) -> &T {
        &self.0
    }
}

/// SPL token account data used with `InterfaceAccount<TokenAccount>`.
pub type TokenAccount = Interface<crate::TokenAccount>;

/// SPL mint account data used with `InterfaceAccount<Mint>`.
pub type Mint = Interface<crate::Mint>;

/// Extension reader for Token-2022 interface mint and token accounts.
///
/// This keeps TLV parsing on the account wrapper, where the underlying
/// [`AccountView`] is available, while preserving Token-2022 owner and
/// extension-family checks.
pub trait TokenInterfaceAccountExtensions {
    fn get_extension<T: crate::extensions::ExtensionType>(&self) -> Result<&T, ProgramError>;
}

impl TokenInterfaceAccountExtensions for InterfaceAccount<Mint> {
    #[inline(always)]
    fn get_extension<T: crate::extensions::ExtensionType>(&self) -> Result<&T, ProgramError> {
        let account = self.account();
        require!(
            account.owned_by(&Token2022Program::id()),
            ProgramError::IllegalOwner
        );

        let data = unsafe { account.borrow_unchecked() };
        let state = PodStateWithExtensions::<PodMint>::unpack(data)?;
        let extension = state.get_extension::<T>()?;
        let extension_ptr = extension as *const T;

        // SAFETY: `PodStateWithExtensions` stores only references into `data`,
        // and `extension_ptr` points into that account data, not into the
        // temporary wrapper value. `data` is borrowed from `account`, which
        // outlives the returned reference.
        Ok(unsafe { &*extension_ptr })
    }
}

impl TokenInterfaceAccountExtensions for InterfaceAccount<TokenAccount> {
    #[inline(always)]
    fn get_extension<T: crate::extensions::ExtensionType>(&self) -> Result<&T, ProgramError> {
        let account = self.account();
        require!(
            account.owned_by(&Token2022Program::id()),
            ProgramError::IllegalOwner
        );

        let data = unsafe { account.borrow_unchecked() };
        let state = PodStateWithExtensions::<PodAccount>::unpack(data)?;
        let extension = state.get_extension::<T>()?;
        let extension_ptr = extension as *const T;

        // SAFETY: `PodStateWithExtensions` stores only references into `data`,
        // and `extension_ptr` points into that account data, not into the
        // temporary wrapper value. `data` is borrowed from `account`, which
        // outlives the returned reference.
        Ok(unsafe { &*extension_ptr })
    }
}

/// Program marker that accepts both Token and Token-2022 executable accounts.
pub struct TokenInterface;

impl Ids for TokenInterface {
    #[inline(always)]
    fn ids() -> &'static [Address] {
        static IDS: [Address; 2] = [
            anchor_lang::address!("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
            anchor_lang::address!("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"),
        ];
        &IDS
    }
}

// ---------------------------------------------------------------------------
// SlabSchema — Interface<TokenAccount>
// ---------------------------------------------------------------------------

impl SlabSchema for Interface<crate::TokenAccount> {
    const DATA_OFFSET: usize = 0;
    const MIN_DATA_LEN: usize = core::mem::size_of::<Self>();

    #[inline(always)]
    fn validate(view: &AccountView, data: &[u8]) -> Result<(), ProgramError> {
        require!(
            view.owned_by(&Token::id()) || view.owned_by(&Token2022Program::id()),
            ProgramError::IllegalOwner
        );
        PodStateWithExtensions::<PodAccount>::unpack(data)?;
        crate::token::validate_token_account_initialized(data)?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// SlabSchema — Interface<Mint>
// ---------------------------------------------------------------------------

impl SlabSchema for Interface<crate::Mint> {
    const DATA_OFFSET: usize = 0;
    const MIN_DATA_LEN: usize = core::mem::size_of::<Self>();

    #[inline(always)]
    fn validate(view: &AccountView, data: &[u8]) -> Result<(), ProgramError> {
        require!(
            view.owned_by(&Token::id()) || view.owned_by(&Token2022Program::id()),
            ProgramError::IllegalOwner
        );
        PodStateWithExtensions::<PodMint>::unpack(data)?;
        crate::mint::validate_mint_initialized(data)?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Space
// ---------------------------------------------------------------------------

impl anchor_lang::Space for Interface<crate::TokenAccount> {
    const INIT_SPACE: usize = core::mem::size_of::<crate::TokenAccount>();
}

impl anchor_lang::Space for Interface<crate::Mint> {
    const INIT_SPACE: usize = core::mem::size_of::<crate::Mint>();
}

// ---------------------------------------------------------------------------
// IDL — keep interface types out of the user's types[] array
// ---------------------------------------------------------------------------

#[doc(hidden)]
impl anchor_lang::IdlAccountType for Interface<crate::TokenAccount> {}

#[doc(hidden)]
impl anchor_lang::IdlAccountType for Interface<crate::Mint> {}

// ---------------------------------------------------------------------------
// SlabInit — Interface<TokenAccount>
// ---------------------------------------------------------------------------

/// Init params for `InterfaceAccount<TokenAccount>`. Requires `token_program`
/// to know which program to create the account through.
#[derive(Default)]
pub struct InterfaceTokenAccountInitParams<'a> {
    pub mint: Option<&'a AccountView>,
    pub authority: Option<&'a AccountView>,
    pub token_program: Option<&'a AccountView>,
}

impl SlabInit for Interface<crate::TokenAccount> {
    type Params<'a> = InterfaceTokenAccountInitParams<'a>;

    #[cold]
    fn create_and_initialize<'a>(
        payer: &AccountView,
        account: &AccountView,
        _space: usize,
        params: &Self::Params<'a>,
        signer_seeds: Option<&[&[u8]]>,
        payer_signer_seeds: Option<&[&[u8]]>,
    ) -> Result<(), ProgramError> {
        let mint = params.mint.ok_or(ProgramError::InvalidArgument)?;
        let authority = params.authority.ok_or(ProgramError::InvalidArgument)?;
        let token_program = params.token_program.ok_or(ProgramError::InvalidArgument)?;
        let program_id = token_program.address();
        crate::token_shared::validate_token_interface_program(program_id)?;

        let space = token_account_init_space(mint, program_id)?;
        anchor_lang::create_account_with_signers(
            payer,
            account,
            space,
            program_id,
            signer_seeds,
            payer_signer_seeds,
        )?;

        pinocchio_token_2022::instructions::InitializeAccount3 {
            account,
            mint,
            owner: authority.address(),
            token_program: program_id,
        }
        .invoke()
    }
}

#[inline(always)]
fn token_account_init_space(
    mint: &AccountView,
    token_program: &Address,
) -> Result<usize, ProgramError> {
    if !anchor_lang::address_eq(token_program, &Token2022Program::id()) {
        return Ok(core::mem::size_of::<crate::TokenAccount>());
    }

    let mint_data = unsafe { mint.borrow_unchecked() };
    let mint_state = PodStateWithExtensions::<PodMint>::unpack(mint_data)?;
    let mint_extensions = mint_state.get_extension_types()?;
    let required_extensions =
        Token2022ExtensionType::get_required_init_account_extensions(&mint_extensions);

    Token2022ExtensionType::try_calculate_account_len::<PodAccount>(&required_extensions)
}

// ---------------------------------------------------------------------------
// SlabInit — Interface<Mint>
// ---------------------------------------------------------------------------

/// Init params for `InterfaceAccount<Mint>`.
#[derive(Default)]
pub struct InterfaceMintInitParams<'a> {
    pub decimals: Option<u8>,
    pub authority: Option<&'a AccountView>,
    pub freeze_authority: Option<&'a AccountView>,
    pub token_program: Option<&'a AccountView>,
}

impl SlabInit for Interface<crate::Mint> {
    type Params<'a> = InterfaceMintInitParams<'a>;

    #[cold]
    fn create_and_initialize<'a>(
        payer: &AccountView,
        account: &AccountView,
        _space: usize,
        params: &Self::Params<'a>,
        signer_seeds: Option<&[&[u8]]>,
        payer_signer_seeds: Option<&[&[u8]]>,
    ) -> Result<(), ProgramError> {
        let decimals = params.decimals.ok_or(ProgramError::InvalidArgument)?;
        let authority = params.authority.ok_or(ProgramError::InvalidArgument)?;
        let token_program = params.token_program.ok_or(ProgramError::InvalidArgument)?;
        let program_id = token_program.address();
        crate::token_shared::validate_token_interface_program(program_id)?;

        let space = core::mem::size_of::<crate::Mint>();
        anchor_lang::create_account_with_signers(
            payer,
            account,
            space,
            program_id,
            signer_seeds,
            payer_signer_seeds,
        )?;

        pinocchio_token_2022::instructions::InitializeMint2 {
            mint: account,
            decimals,
            mint_authority: authority.address(),
            freeze_authority: params.freeze_authority.map(|v| v.address()),
            token_program: program_id,
        }
        .invoke()
    }
}

// ---------------------------------------------------------------------------
// Constraint impls — token::* on InterfaceAccount<TokenAccount>
// ---------------------------------------------------------------------------

impl AccountConstraint<InterfaceAccount<TokenAccount>> for crate::token::MintConstraint {
    type Value = Address;
    #[inline(always)]
    fn check(
        account: &InterfaceAccount<TokenAccount>,
        expected: &Address,
    ) -> Result<(), ProgramError> {
        require!(
            anchor_lang::address_eq(account.mint(), expected),
            ProgramError::InvalidAccountData
        );
        Ok(())
    }
}

impl AccountConstraint<InterfaceAccount<TokenAccount>> for crate::token::AuthorityConstraint {
    type Value = Address;
    #[inline(always)]
    fn check(
        account: &InterfaceAccount<TokenAccount>,
        expected: &Address,
    ) -> Result<(), ProgramError> {
        require!(
            anchor_lang::address_eq(account.owner(), expected),
            ProgramError::InvalidAccountData
        );
        Ok(())
    }
}

impl AccountConstraint<InterfaceAccount<TokenAccount>> for crate::token::TokenProgramConstraint {
    type Value = Address;
    #[inline(always)]
    fn check(
        account: &InterfaceAccount<TokenAccount>,
        expected: &Address,
    ) -> Result<(), ProgramError> {
        require!(
            AsRef::<AccountView>::as_ref(account).owned_by(expected),
            ProgramError::IllegalOwner
        );
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Constraint impls — mint::* on InterfaceAccount<Mint>
// ---------------------------------------------------------------------------

impl AccountConstraint<InterfaceAccount<Mint>> for crate::mint::AuthorityConstraint {
    type Value = Address;
    #[inline(always)]
    fn check(account: &InterfaceAccount<Mint>, expected: &Address) -> Result<(), ProgramError> {
        require_eq!(
            account.mint_authority(),
            Some(expected),
            ProgramError::InvalidAccountData
        );
        Ok(())
    }
}

impl AccountConstraint<InterfaceAccount<Mint>> for crate::mint::FreezeAuthorityConstraint {
    type Value = Address;
    #[inline(always)]
    fn check(account: &InterfaceAccount<Mint>, expected: &Address) -> Result<(), ProgramError> {
        require_eq!(
            account.freeze_authority(),
            Some(expected),
            ProgramError::InvalidAccountData
        );
        Ok(())
    }
}

impl AccountConstraint<InterfaceAccount<Mint>> for crate::mint::DecimalsConstraint {
    type Value = u8;
    #[inline(always)]
    fn check(account: &InterfaceAccount<Mint>, expected: &u8) -> Result<(), ProgramError> {
        require_eq!(
            account.decimals(),
            *expected,
            ProgramError::InvalidAccountData
        );
        Ok(())
    }
}

impl AccountConstraint<InterfaceAccount<Mint>> for crate::mint::TokenProgramConstraint {
    type Value = Address;
    #[inline(always)]
    fn check(account: &InterfaceAccount<Mint>, expected: &Address) -> Result<(), ProgramError> {
        require!(
            AsRef::<AccountView>::as_ref(account).owned_by(expected),
            ProgramError::IllegalOwner
        );
        Ok(())
    }
}