tensor_toolbox/
common.rs

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#![allow(clippy::result_large_err)]
use anchor_lang::{
    prelude::*,
    solana_program::{program::invoke, pubkey::Pubkey, system_instruction, system_program},
};
use anchor_spl::{associated_token::AssociatedToken, token_interface::TokenInterface};
use mpl_token_metadata::types::TokenStandard;
use std::slice::Iter;
use tensor_vipers::prelude::*;

use crate::token_2022::transfer::transfer_checked as token_2022_transfer_checked;
use crate::TensorError;

pub const HUNDRED_PCT_BPS: u64 = 10000;
pub const HUNDRED_PCT: u64 = 100;
pub const BROKER_FEE_PCT: u64 = 50;
pub const TNSR_DISCOUNT_BPS: u64 = 2500;
pub const TAKER_FEE_BPS: u64 = 200;
pub const MAKER_BROKER_PCT: u64 = 80; // Out of 100

pub const fn pubkey(base58str: &str) -> Pubkey {
    Pubkey::new_from_array(five8_const::decode_32_const(base58str))
}

pub mod escrow {
    use super::*;
    declare_id!("TSWAPaqyCSx2KABk68Shruf4rp7CxcNi8hAsbdwmHbN");

    pub const TSWAP_SINGLETON: Pubkey = pubkey("4zdNGgAtFsW1cQgHqkiWyRsxaAgxrSRRynnuunxzjxue");
}

pub mod fees {
    use super::*;
    declare_id!("TFEEgwDP6nn1s8mMX2tTNPPz8j2VomkphLUmyxKm17A");
}

pub mod marketplace {
    use super::*;
    declare_id!("TCMPhJdwDryooaGtiocG1u3xcYbRpiJzb283XfCZsDp");

    pub const TCOMP_SINGLETON: Pubkey = pubkey("q4s8z5dRAt2fKC2tLthBPatakZRXPMx1LfacckSXd4f");
}

pub mod mpl_token_auth_rules {
    use super::*;
    declare_id!("auth9SigNpDKz4sJJ1DfCTuZrZNSAgh9sFD3rboVmgg");
}

pub mod price_lock {
    use super::*;
    declare_id!("TLoCKic2wGJm7VhZKumih4Lc35fUhYqVMgA4j389Buk");

    pub const TLOCK_SINGLETON: Pubkey = pubkey("CdXA5Vpg4hqvsmLSKC2cygnJVvsQTrDrrn428nAZQaKz");
}

/// Calculates fee vault shard from a given AccountInfo or Pubkey. Relies on the Anchor `Key` trait.
#[macro_export]
macro_rules! shard_num {
    ($value:expr) => {
        &$value.key().as_ref()[31].to_le_bytes()
    };
}

pub struct CalcFeesArgs {
    pub amount: u64,
    pub total_fee_bps: u64,
    pub broker_fee_pct: u64,
    pub maker_broker_pct: u64,
    pub tnsr_discount: bool,
}

/// Fees struct that holds the calculated fees.
pub struct Fees {
    /// Taker fee is the total fee sans royalties: protocol fee + broker fees.
    pub taker_fee: u64,
    /// Protocol fee is the fee that goes to the protocol, a percentage of the total fee determined by 1 - broker_fee_pct.
    pub protocol_fee: u64,
    /// Maker broker fee is the fee that goes to the maker broker: a percentage of the total broker fee.
    pub maker_broker_fee: u64,
    /// Taker broker fee is the fee that goes to the taker broker: the remainder of the total broker fee.
    pub taker_broker_fee: u64,
}

// Calculate fees for a given amount.
pub fn calc_fees(args: CalcFeesArgs) -> Result<Fees> {
    let CalcFeesArgs {
        amount,
        total_fee_bps,
        broker_fee_pct,
        maker_broker_pct,
        tnsr_discount,
    } = args;

    // Apply the TNSR discount if enabled.
    let total_fee_bps = if tnsr_discount {
        unwrap_checked!({
            total_fee_bps
                .checked_mul(HUNDRED_PCT_BPS - TNSR_DISCOUNT_BPS)?
                .checked_div(HUNDRED_PCT_BPS)
        })
    } else {
        total_fee_bps
    };

    // Total fee is calculated from the passed in total_fee_bps and is protocol fee + broker fees.
    let total_fee = unwrap_checked!({
        (amount)
            .checked_mul(total_fee_bps)?
            .checked_div(HUNDRED_PCT_BPS)
    });

    // Broker fees are a percentage of the total fee.
    let broker_fees = unwrap_checked!({
        total_fee
            .checked_mul(broker_fee_pct)?
            .checked_div(HUNDRED_PCT)
    });

    // Protocol fee is the remainder.
    let protocol_fee = unwrap_checked!({ total_fee.checked_sub(broker_fees) });

    // Maker broker is a percentage of the total brokers fee.
    let maker_broker_fee = unwrap_checked!({
        broker_fees
            .checked_mul(maker_broker_pct)?
            .checked_div(HUNDRED_PCT)
    });

    // Remaining broker fee is the taker broker fee.
    let taker_broker_fee = unwrap_int!(broker_fees.checked_sub(maker_broker_fee));

    Ok(Fees {
        taker_fee: total_fee,
        protocol_fee,
        maker_broker_fee,
        taker_broker_fee,
    })
}

pub fn is_royalty_enforced(token_standard: Option<TokenStandard>) -> bool {
    matches!(
        token_standard,
        Some(TokenStandard::ProgrammableNonFungible)
            | Some(TokenStandard::ProgrammableNonFungibleEdition)
    )
}

pub fn calc_creators_fee(
    seller_fee_basis_points: u16,
    amount: u64,
    royalty_pct: Option<u16>,
) -> Result<u64> {
    let creator_fee_bps = if let Some(royalty_pct) = royalty_pct {
        require!(royalty_pct <= 100, TensorError::BadRoyaltiesPct);

        // If optional passed, pay optional royalties
        unwrap_checked!({
            (seller_fee_basis_points as u64)
                .checked_mul(royalty_pct as u64)?
                .checked_div(100_u64)
        })
    } else {
        // Else pay 0
        0_u64
    };
    let fee = unwrap_checked!({
        creator_fee_bps
            .checked_mul(amount)?
            .checked_div(HUNDRED_PCT_BPS)
    });

    Ok(fee)
}

/// Transfers all lamports from a PDA (except for rent) to a destination account.
pub fn transfer_all_lamports_from_pda<'info>(
    from_pda: &AccountInfo<'info>,
    to: &AccountInfo<'info>,
) -> Result<()> {
    let rent = Rent::get()?.minimum_balance(from_pda.data_len());
    let to_move = unwrap_int!(from_pda.lamports().checked_sub(rent));

    transfer_lamports_from_pda(from_pda, to, to_move)
}

/// Transfers specified lamports from a PDA to a destination account.
/// Throws an error if less than rent remains in the PDA.
pub fn transfer_lamports_from_pda<'info>(
    from_pda: &AccountInfo<'info>,
    to: &AccountInfo<'info>,
    lamports: u64,
) -> Result<()> {
    let remaining_pda_lamports = unwrap_int!(from_pda.lamports().checked_sub(lamports));
    // Check we are not withdrawing into our rent.
    let rent = Rent::get()?.minimum_balance(from_pda.data_len());
    require!(
        remaining_pda_lamports >= rent,
        TensorError::InsufficientBalance
    );

    **from_pda.try_borrow_mut_lamports()? = remaining_pda_lamports;

    let new_to = unwrap_int!(to.lamports.borrow().checked_add(lamports));
    **to.lamports.borrow_mut() = new_to;

    Ok(())
}

pub struct FromExternal<'b, 'info> {
    pub from: &'b AccountInfo<'info>,
    pub sys_prog: &'b AccountInfo<'info>,
}

pub enum FromAcc<'a, 'info> {
    Pda(&'a AccountInfo<'info>),
    External(&'a FromExternal<'a, 'info>),
}

#[derive(AnchorSerialize, AnchorDeserialize, PartialEq, Eq, Debug, Clone)]
pub struct TCreator {
    pub address: Pubkey,
    pub verified: bool,
    // In percentages, NOT basis points ;) Watch out!
    pub share: u8,
}

//into token meta
impl From<TCreator> for mpl_token_metadata::types::Creator {
    fn from(creator: TCreator) -> Self {
        mpl_token_metadata::types::Creator {
            address: creator.address,
            verified: creator.verified,
            share: creator.share,
        }
    }
}

//from token meta
impl From<mpl_token_metadata::types::Creator> for TCreator {
    fn from(creator: mpl_token_metadata::types::Creator) -> Self {
        TCreator {
            address: creator.address,
            verified: creator.verified,
            share: creator.share,
        }
    }
}

#[cfg(feature = "mpl-core")]
//from token meta
impl From<mpl_core::types::Creator> for TCreator {
    fn from(creator: mpl_core::types::Creator) -> Self {
        TCreator {
            address: creator.address,
            share: creator.percentage,
            // mpl-core does not have a concept of "verified" creator
            verified: false,
        }
    }
}

#[repr(u8)]
pub enum CreatorFeeMode<'a, 'info> {
    Sol {
        from: &'a FromAcc<'a, 'info>,
    },
    Spl {
        associated_token_program: &'a Program<'info, AssociatedToken>,
        token_program: &'a Interface<'info, TokenInterface>,
        system_program: &'a Program<'info, System>,
        currency: &'a AccountInfo<'info>,
        from: &'a AccountInfo<'info>,
        from_token_acc: &'a AccountInfo<'info>,
        rent_payer: &'a AccountInfo<'info>,
    },
}

pub fn transfer_creators_fee<'a, 'info>(
    //using TCreator here so that this fn is agnostic to normal NFTs and cNFTs
    creators: &'a Vec<TCreator>,
    creator_accounts: &mut Iter<AccountInfo<'info>>,
    creator_fee: u64,
    // put not-in-common args in an enum so the invoker doesn't require it
    mode: &'a CreatorFeeMode<'a, 'info>,
) -> Result<u64> {
    // Send royalties: taken from AH's calculation:
    // https://github.com/metaplex-foundation/metaplex-program-library/blob/2320b30ec91b729b153f0c0fe719f96d325b2358/auction-house/program/src/utils.rs#L366-L471
    let mut remaining_fee = creator_fee;
    for creator in creators {
        let current_creator_info = next_account_info(creator_accounts)?;

        require!(
            creator.address.eq(current_creator_info.key),
            TensorError::CreatorMismatch
        );

        let pct = creator.share as u64;
        let creator_fee = unwrap_checked!({ pct.checked_mul(creator_fee)?.checked_div(100) });

        let current_creator_ata_info = match mode {
            CreatorFeeMode::Sol { from: _ } => {
                // Prevents InsufficientFundsForRent, where creator acc doesn't have enough fee
                // https://explorer.solana.com/tx/vY5nYA95ELVrs9SU5u7sfU2ucHj4CRd3dMCi1gWrY7MSCBYQLiPqzABj9m8VuvTLGHb9vmhGaGY7mkqPa1NLAFE
                let rent = Rent::get()?.minimum_balance(current_creator_info.data_len());
                if unwrap_int!(current_creator_info.lamports().checked_add(creator_fee)) < rent {
                    //skip current creator, we can't pay them
                    continue;
                }
                None
            }
            CreatorFeeMode::Spl {
                associated_token_program: _,
                token_program: _,
                system_program: _,
                currency: _,
                from: _,
                from_token_acc: _,
                rent_payer: _,
            } => {
                // ATA validated on transfer CPI.
                Some(next_account_info(creator_accounts)?)
            }
        };

        remaining_fee = unwrap_int!(remaining_fee.checked_sub(creator_fee));
        if creator_fee > 0 {
            match mode {
                CreatorFeeMode::Sol { from } => match from {
                    FromAcc::Pda(from_pda) => {
                        transfer_lamports_from_pda(from_pda, current_creator_info, creator_fee)?;
                    }
                    FromAcc::External(from_ext) => {
                        let FromExternal { from, sys_prog } = from_ext;
                        invoke(
                            &system_instruction::transfer(
                                from.key,
                                current_creator_info.key,
                                creator_fee,
                            ),
                            &[
                                (*from).clone(),
                                current_creator_info.clone(),
                                (*sys_prog).clone(),
                            ],
                        )?;
                    }
                },

                CreatorFeeMode::Spl {
                    associated_token_program,
                    token_program,
                    system_program,
                    currency,
                    from,
                    from_token_acc: from_ata,
                    rent_payer,
                } => {
                    let creator_ata_info =
                        unwrap_opt!(current_creator_ata_info, "missing creator ata");

                    anchor_spl::associated_token::create_idempotent(CpiContext::new(
                        associated_token_program.to_account_info(),
                        anchor_spl::associated_token::Create {
                            payer: rent_payer.to_account_info(),
                            associated_token: creator_ata_info.to_account_info(),
                            authority: current_creator_info.to_account_info(),
                            mint: currency.to_account_info(),
                            system_program: system_program.to_account_info(),
                            token_program: token_program.to_account_info(),
                        },
                    ))?;

                    match token_program.key() {
                        anchor_spl::token::ID => {
                            anchor_spl::token::transfer(
                                CpiContext::new(
                                    token_program.to_account_info(),
                                    anchor_spl::token::Transfer {
                                        from: from_ata.to_account_info(),
                                        to: creator_ata_info.to_account_info(),
                                        authority: from.to_account_info(),
                                    },
                                ),
                                creator_fee,
                            )?;
                        }
                        anchor_spl::token_interface::ID => {
                            let mint = anchor_spl::token_interface::Mint::try_deserialize(
                                &mut &currency.data.borrow()[..],
                            )?;
                            token_2022_transfer_checked(
                                CpiContext::new(
                                    token_program.to_account_info(),
                                    anchor_spl::token_interface::TransferChecked {
                                        from: from_ata.to_account_info(),
                                        mint: currency.to_account_info(),
                                        to: creator_ata_info.to_account_info(),
                                        authority: from.to_account_info(),
                                    },
                                ),
                                creator_fee,
                                mint.decimals,
                            )?;
                        }
                        _ => return Err(ErrorCode::InvalidProgramId.into()),
                    }
                }
            }
        }
    }

    // Return the amount that was sent (minus any dust).
    Ok(unwrap_int!(creator_fee.checked_sub(remaining_fee)))
}

// NOT: https://github.com/coral-xyz/sealevel-attacks/blob/master/programs/9-closing-accounts/secure/src/lib.rs
// Instead: https://github.com/coral-xyz/anchor/blob/b7bada148cead931bc3bdae7e9a641e9be66e6a6/lang/src/common.rs#L6
pub fn close_account(
    pda_to_close: &mut AccountInfo,
    sol_destination: &mut AccountInfo,
) -> Result<()> {
    // Transfer tokens from the account to the sol_destination.
    let dest_starting_lamports = sol_destination.lamports();
    **sol_destination.lamports.borrow_mut() =
        unwrap_int!(dest_starting_lamports.checked_add(pda_to_close.lamports()));
    **pda_to_close.lamports.borrow_mut() = 0;

    pda_to_close.assign(&system_program::ID);
    pda_to_close.realloc(0, false).map_err(Into::into)
}

/// Transfers lamports from one account to another, handling the cases where the account
/// is either a PDA or a system account.
pub fn transfer_lamports<'info>(
    from: &AccountInfo<'info>,
    to: &AccountInfo<'info>,
    lamports: u64,
) -> Result<()> {
    // if the from account is empty, we can use the system program to transfer
    if from.data_is_empty() && from.owner == &system_program::ID {
        invoke(
            &system_instruction::transfer(from.key, to.key, lamports),
            &[from.clone(), to.clone()],
        )
        .map_err(Into::into)
    } else {
        transfer_lamports_from_pda(from, to, lamports)
    }
}

/// Transfers lamports, skipping the transfer if the `to` account would not be rent exempt.
///
/// This is useful when transferring lamports to a new account that may not have been created yet
/// and the transfer amount is less than the rent exemption.
pub fn transfer_lamports_checked<'info, 'b>(
    from: &'b AccountInfo<'info>,
    to: &'b AccountInfo<'info>,
    lamports: u64,
) -> Result<()> {
    let rent = Rent::get()?.minimum_balance(to.data_len());
    if unwrap_int!(to.lamports().checked_add(lamports)) < rent {
        // skip the transfer if the account as the account would not be rent exempt
        msg!(
            "Skipping transfer of {} lamports to {}: account would not be rent exempt",
            lamports,
            to.key
        );
        Ok(())
    } else {
        transfer_lamports(from, to, lamports)
    }
}

/// Asserts that the account is a valid fee account: either one of the program singletons or the fee vault.
pub fn assert_fee_account(fee_vault_info: &AccountInfo, state_info: &AccountInfo) -> Result<()> {
    let expected_fee_vault = Pubkey::find_program_address(
        &[
            b"fee_vault",
            // Use the last byte of the mint as the fee shard number
            shard_num!(state_info),
        ],
        &fees::ID,
    )
    .0;

    require!(
        fee_vault_info.key == &expected_fee_vault
            || &marketplace::TCOMP_SINGLETON == fee_vault_info.key,
        TensorError::InvalidFeeAccount
    );

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pubkey_constant() {
        let default_pubkey = pubkey("11111111111111111111111111111111");
        assert_eq!(default_pubkey, Pubkey::default());

        let p = pubkey("4zdNGgAtFsW1cQgHqkiWyRsxaAgxrSRRynnuunxzjxue");
        assert_eq!(
            p.to_bytes(),
            [
                59, 86, 73, 113, 118, 186, 131, 166, 77, 161, 204, 243, 144, 62, 8, 138, 52, 116,
                86, 213, 41, 159, 32, 94, 252, 208, 28, 78, 220, 101, 76, 105
            ]
        );
    }

    #[test]
    #[should_panic]
    fn pubkey_constant_base58_too_short() {
        let _p = pubkey("abc");
    }

    #[test]
    #[should_panic]
    fn pubkey_constant_base58_too_long() {
        let _p = pubkey("abc123456789012345678901234567890123456789012345678901234567890123");
    }

    #[test]
    #[should_panic]
    fn pubkey_constant_base58_empty() {
        let _p = pubkey("");
    }
}