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
use anchor_lang::prelude::*;
use anchor_lang::ZeroCopy;
use arrayref::array_ref;
use std::cell::RefMut;
use std::{cell::Ref, mem};

/// Functions should prefer to work with AccountReader where possible, to abstract over
/// AccountInfo and AccountSharedData. That way the functions become usable in the program
/// and in client code.
// NOTE: would love to use solana's ReadableAccount, but that's in solana_sdk -- unavailable for programs
pub trait AccountReader {
    fn owner(&self) -> &Pubkey;
    fn data(&self) -> &[u8];
}

/// Like AccountReader, but can also get the account pubkey
pub trait KeyedAccountReader: AccountReader {
    fn key(&self) -> &Pubkey;
}

/// A Ref to an AccountInfo - makes AccountInfo compatible with AccountReader
pub struct AccountInfoRef<'a, 'info: 'a> {
    pub key: &'info Pubkey,
    pub owner: &'info Pubkey,
    pub data: Ref<'a, &'info mut [u8]>,
}

impl<'a, 'info: 'a> AccountInfoRef<'a, 'info> {
    pub fn borrow(account_info: &'a AccountInfo<'info>) -> Result<Self> {
        Ok(Self {
            key: account_info.key,
            owner: account_info.owner,
            data: account_info
                .data
                .try_borrow()
                .map_err(|_| ProgramError::AccountBorrowFailed)?,
            // Why is the following not acceptable?
            //data: account_info.try_borrow_data()?,
        })
    }

    pub fn borrow_slice(ais: &'a [AccountInfo<'info>]) -> Result<Vec<Self>> {
        ais.iter().map(Self::borrow).collect()
    }
}

pub struct AccountInfoRefMut<'a, 'info: 'a> {
    pub key: &'info Pubkey,
    pub owner: &'info Pubkey,
    pub data: RefMut<'a, &'info mut [u8]>,
}

impl<'a, 'info: 'a> AccountInfoRefMut<'a, 'info> {
    pub fn borrow(account_info: &'a AccountInfo<'info>) -> Result<Self> {
        Ok(Self {
            key: account_info.key,
            owner: account_info.owner,
            data: account_info
                .data
                .try_borrow_mut()
                .map_err(|_| ProgramError::AccountBorrowFailed)?,
        })
    }

    pub fn borrow_slice(ais: &'a [AccountInfo<'info>]) -> Result<Vec<Self>> {
        ais.iter().map(Self::borrow).collect()
    }
}

impl<'info, 'a> AccountReader for AccountInfoRef<'info, 'a> {
    fn owner(&self) -> &Pubkey {
        self.owner
    }

    fn data(&self) -> &[u8] {
        &self.data
    }
}

impl<'info, 'a> AccountReader for AccountInfoRefMut<'info, 'a> {
    fn owner(&self) -> &Pubkey {
        self.owner
    }

    fn data(&self) -> &[u8] {
        &self.data
    }
}

impl<'info, 'a> KeyedAccountReader for AccountInfoRef<'info, 'a> {
    fn key(&self) -> &Pubkey {
        self.key
    }
}

impl<'info, 'a> KeyedAccountReader for AccountInfoRefMut<'info, 'a> {
    fn key(&self) -> &Pubkey {
        self.key
    }
}

#[cfg(feature = "solana-sdk")]
impl<T: solana_sdk::account::ReadableAccount> AccountReader for T {
    fn owner(&self) -> &Pubkey {
        self.owner()
    }

    fn data(&self) -> &[u8] {
        self.data()
    }
}

#[cfg(feature = "solana-sdk")]
#[derive(Clone)]
pub struct KeyedAccount {
    pub key: Pubkey,
    pub account: solana_sdk::account::Account,
}

#[cfg(feature = "solana-sdk")]
impl AccountReader for KeyedAccount {
    fn owner(&self) -> &Pubkey {
        self.account.owner()
    }

    fn data(&self) -> &[u8] {
        self.account.data()
    }
}

#[cfg(feature = "solana-sdk")]
impl KeyedAccountReader for KeyedAccount {
    fn key(&self) -> &Pubkey {
        &self.key
    }
}

#[cfg(feature = "solana-sdk")]
#[derive(Clone)]
pub struct KeyedAccountSharedData {
    pub key: Pubkey,
    pub data: solana_sdk::account::AccountSharedData,
}

#[cfg(feature = "solana-sdk")]
impl KeyedAccountSharedData {
    pub fn new(key: Pubkey, data: solana_sdk::account::AccountSharedData) -> Self {
        Self { key, data }
    }
}

#[cfg(feature = "solana-sdk")]
impl AccountReader for KeyedAccountSharedData {
    fn owner(&self) -> &Pubkey {
        AccountReader::owner(&self.data)
    }

    fn data(&self) -> &[u8] {
        AccountReader::data(&self.data)
    }
}

#[cfg(feature = "solana-sdk")]
impl KeyedAccountReader for KeyedAccountSharedData {
    fn key(&self) -> &Pubkey {
        &self.key
    }
}

//
// Common traits for loading from account data.
//

pub trait LoadZeroCopy {
    /// Using AccountLoader forces a AccountInfo.clone() and then binds the loaded
    /// lifetime to the AccountLoader's lifetime. This function avoids both.
    /// It checks the account owner and discriminator, then casts the data.
    fn load<T: ZeroCopy + Owner>(&self) -> Result<&T>;

    /// Same as load(), but doesn't check the discriminator or owner.
    fn load_fully_unchecked<T: ZeroCopy + Owner>(&self) -> Result<&T>;
}

pub trait LoadMutZeroCopy {
    /// Same as load(), but mut
    fn load_mut<T: ZeroCopy + Owner>(&mut self) -> Result<&mut T>;

    /// Same as load_fully_unchecked(), but mut
    fn load_mut_fully_unchecked<T: ZeroCopy + Owner>(&mut self) -> Result<&mut T>;
}

pub trait LoadZeroCopyRef {
    /// Using AccountLoader forces a AccountInfo.clone() and then binds the loaded
    /// lifetime to the AccountLoader's lifetime. This function avoids both.
    /// It checks the account owner and discriminator, then casts the data.
    fn load<T: ZeroCopy + Owner>(&self) -> Result<Ref<T>>;

    /// Same as load(), but doesn't check the discriminator or owner.
    fn load_fully_unchecked<T: ZeroCopy + Owner>(&self) -> Result<Ref<T>>;
}

pub trait LoadMutZeroCopyRef {
    /// Same as load(), but mut
    fn load_mut<T: ZeroCopy + Owner>(&self) -> Result<RefMut<T>>;

    /// Same as load_fully_unchecked(), but mut
    fn load_mut_fully_unchecked<T: ZeroCopy + Owner>(&self) -> Result<RefMut<T>>;
}

impl<A: AccountReader> LoadZeroCopy for A {
    fn load<T: ZeroCopy + Owner>(&self) -> Result<&T> {
        if self.owner() != &T::owner() {
            return Err(ErrorCode::AccountOwnedByWrongProgram.into());
        }

        let data = self.data();
        if data.len() < 8 {
            return Err(ErrorCode::AccountDiscriminatorNotFound.into());
        }
        let disc_bytes = array_ref![data, 0, 8];
        if disc_bytes != &T::discriminator() {
            return Err(ErrorCode::AccountDiscriminatorMismatch.into());
        }

        Ok(bytemuck::from_bytes(&data[8..mem::size_of::<T>() + 8]))
    }

    fn load_fully_unchecked<T: ZeroCopy + Owner>(&self) -> Result<&T> {
        Ok(bytemuck::from_bytes(
            &self.data()[8..mem::size_of::<T>() + 8],
        ))
    }
}

impl<'info, 'a> LoadMutZeroCopy for AccountInfoRefMut<'info, 'a> {
    fn load_mut<T: ZeroCopy + Owner>(&mut self) -> Result<&mut T> {
        if self.owner != &T::owner() {
            return Err(ErrorCode::AccountOwnedByWrongProgram.into());
        }

        if self.data.len() < 8 {
            return Err(ErrorCode::AccountDiscriminatorNotFound.into());
        }
        let disc_bytes = array_ref![self.data, 0, 8];
        if disc_bytes != &T::discriminator() {
            return Err(ErrorCode::AccountDiscriminatorMismatch.into());
        }

        Ok(bytemuck::from_bytes_mut(
            &mut self.data[8..mem::size_of::<T>() + 8],
        ))
    }

    fn load_mut_fully_unchecked<T: ZeroCopy + Owner>(&mut self) -> Result<&mut T> {
        Ok(bytemuck::from_bytes_mut(
            &mut self.data[8..mem::size_of::<T>() + 8],
        ))
    }
}

impl<'info> LoadZeroCopyRef for AccountInfo<'info> {
    fn load<T: ZeroCopy + Owner>(&self) -> Result<Ref<T>> {
        if self.owner != &T::owner() {
            return Err(ErrorCode::AccountOwnedByWrongProgram.into());
        }

        let data = self.try_borrow_data()?;
        if data.len() < 8 {
            return Err(ErrorCode::AccountDiscriminatorNotFound.into());
        }

        let disc_bytes = array_ref![data, 0, 8];
        if disc_bytes != &T::discriminator() {
            return Err(ErrorCode::AccountDiscriminatorMismatch.into());
        }

        Ok(Ref::map(data, |data| {
            bytemuck::from_bytes(&data[8..mem::size_of::<T>() + 8])
        }))
    }

    fn load_fully_unchecked<T: ZeroCopy + Owner>(&self) -> Result<Ref<T>> {
        let data = self.try_borrow_data()?;
        Ok(Ref::map(data, |data| {
            bytemuck::from_bytes(&data[8..mem::size_of::<T>() + 8])
        }))
    }
}

impl<'info> LoadMutZeroCopyRef for AccountInfo<'info> {
    fn load_mut<T: ZeroCopy + Owner>(&self) -> Result<RefMut<T>> {
        if self.owner != &T::owner() {
            return Err(ErrorCode::AccountOwnedByWrongProgram.into());
        }

        let data = self.try_borrow_mut_data()?;
        if data.len() < 8 {
            return Err(ErrorCode::AccountDiscriminatorNotFound.into());
        }

        let disc_bytes = array_ref![data, 0, 8];
        if disc_bytes != &T::discriminator() {
            return Err(ErrorCode::AccountDiscriminatorMismatch.into());
        }

        Ok(RefMut::map(data, |data| {
            bytemuck::from_bytes_mut(&mut data[8..mem::size_of::<T>() + 8])
        }))
    }

    fn load_mut_fully_unchecked<T: ZeroCopy + Owner>(&self) -> Result<RefMut<T>> {
        let data = self.try_borrow_mut_data()?;
        Ok(RefMut::map(data, |data| {
            bytemuck::from_bytes_mut(&mut data[8..mem::size_of::<T>() + 8])
        }))
    }
}