spl-token-client 0.18.0

SPL-Token Rust Client
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
mod program_test;
use {
    program_test::{keypair_clone, TestContext, TokenContext},
    solana_program_test::{
        processor,
        tokio::{self, sync::Mutex},
        ProgramTest,
    },
    solana_sdk::{
        account_info::{next_account_info, AccountInfo},
        clock::Clock,
        entrypoint::ProgramResult,
        instruction::{AccountMeta, Instruction, InstructionError},
        msg,
        program::{get_return_data, invoke},
        program_error::ProgramError,
        pubkey::Pubkey,
        signature::Signer,
        signer::keypair::Keypair,
        transaction::{Transaction, TransactionError},
        transport::TransportError,
    },
    spl_token_2022_interface::{
        error::TokenError,
        extension::{scaled_ui_amount::ScaledUiAmountConfig, BaseStateWithExtensions},
        instruction::{amount_to_ui_amount, ui_amount_to_amount, AuthorityType},
    },
    spl_token_client::token::{ExtensionInitializationParams, TokenError as TokenClientError},
    std::{convert::TryInto, sync::Arc},
};

#[tokio::test]
async fn success_initialize() {
    for (multiplier, authority) in [
        (f64::MIN_POSITIVE, None),
        (f64::MAX, Some(Pubkey::new_unique())),
    ] {
        let mut context = TestContext::new().await;
        context
            .init_token_with_mint(vec![ExtensionInitializationParams::ScaledUiAmountConfig {
                authority,
                multiplier,
            }])
            .await
            .unwrap();
        let TokenContext { token, .. } = context.token_context.unwrap();

        let state = token.get_mint_info().await.unwrap();
        let extension = state.get_extension::<ScaledUiAmountConfig>().unwrap();
        assert_eq!(Option::<Pubkey>::from(extension.authority), authority,);
        assert_eq!(f64::from(extension.multiplier), multiplier);
        assert_eq!(f64::from(extension.new_multiplier), multiplier);
        assert_eq!(i64::from(extension.new_multiplier_effective_timestamp), 0);
    }
}

#[tokio::test]
async fn fail_initialize_with_interest_bearing() {
    let authority = None;
    let mut context = TestContext::new().await;
    let err = context
        .init_token_with_mint(vec![
            ExtensionInitializationParams::ScaledUiAmountConfig {
                authority,
                multiplier: 1.0,
            },
            ExtensionInitializationParams::InterestBearingConfig {
                rate_authority: None,
                rate: 0,
            },
        ])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        TokenClientError::Client(Box::new(TransportError::TransactionError(
            TransactionError::InstructionError(
                3,
                InstructionError::Custom(TokenError::InvalidExtensionCombination as u32)
            )
        )))
    );
}

#[tokio::test]
async fn fail_initialize_with_bad_multiplier() {
    let mut context = TestContext::new().await;
    let err = context
        .init_token_with_mint(vec![ExtensionInitializationParams::ScaledUiAmountConfig {
            authority: None,
            multiplier: 0.0,
        }])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        TokenClientError::Client(Box::new(TransportError::TransactionError(
            TransactionError::InstructionError(
                1,
                InstructionError::Custom(TokenError::InvalidScale as u32)
            )
        )))
    );
}

#[tokio::test]
async fn update_multiplier() {
    let authority = Keypair::new();
    let initial_multiplier = 5.0;
    let mut context = TestContext::new().await;
    context
        .init_token_with_mint(vec![ExtensionInitializationParams::ScaledUiAmountConfig {
            authority: Some(authority.pubkey()),
            multiplier: initial_multiplier,
        }])
        .await
        .unwrap();
    let TokenContext { token, .. } = context.token_context.take().unwrap();

    let state = token.get_mint_info().await.unwrap();
    let extension = state.get_extension::<ScaledUiAmountConfig>().unwrap();
    assert_eq!(f64::from(extension.multiplier), initial_multiplier);
    assert_eq!(f64::from(extension.new_multiplier), initial_multiplier);

    // correct
    let new_multiplier = 10.0;
    token
        .update_multiplier(&authority.pubkey(), new_multiplier, 0, &[&authority])
        .await
        .unwrap();
    let state = token.get_mint_info().await.unwrap();
    let extension = state.get_extension::<ScaledUiAmountConfig>().unwrap();
    assert_eq!(f64::from(extension.multiplier), new_multiplier);
    assert_eq!(f64::from(extension.new_multiplier), new_multiplier);
    assert_eq!(i64::from(extension.new_multiplier_effective_timestamp), 0);

    // fail, bad number
    let err = token
        .update_multiplier(&authority.pubkey(), f64::INFINITY, 0, &[&authority])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        TokenClientError::Client(Box::new(TransportError::TransactionError(
            TransactionError::InstructionError(
                0,
                InstructionError::Custom(TokenError::InvalidScale as u32)
            )
        )))
    );

    // correct in the future
    let newest_multiplier = 100.0;
    token
        .update_multiplier(
            &authority.pubkey(),
            newest_multiplier,
            i64::MAX,
            &[&authority],
        )
        .await
        .unwrap();
    let state = token.get_mint_info().await.unwrap();
    let extension = state.get_extension::<ScaledUiAmountConfig>().unwrap();
    assert_eq!(f64::from(extension.multiplier), new_multiplier);
    assert_eq!(f64::from(extension.new_multiplier), newest_multiplier);
    assert_eq!(
        i64::from(extension.new_multiplier_effective_timestamp),
        i64::MAX
    );

    // wrong signer
    let wrong_signer = Keypair::new();
    let err = token
        .update_multiplier(&wrong_signer.pubkey(), 1.0, 0, &[&wrong_signer])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        TokenClientError::Client(Box::new(TransportError::TransactionError(
            TransactionError::InstructionError(
                0,
                InstructionError::Custom(TokenError::OwnerMismatch as u32)
            )
        )))
    );
}

#[tokio::test]
async fn update_old_multiplier_after_time_passed() {
    let authority = Keypair::new();
    let initial_multiplier = 5.0;
    let mut context = TestContext::new().await;
    context
        .init_token_with_mint(vec![ExtensionInitializationParams::ScaledUiAmountConfig {
            authority: Some(authority.pubkey()),
            multiplier: initial_multiplier,
        }])
        .await
        .unwrap();
    let TokenContext { token, .. } = context.token_context.take().unwrap();
    let context = context.context;
    let new_multiplier_timestamp = 1_000_000_000_000;

    let new_multiplier = 100.0;
    token
        .update_multiplier(
            &authority.pubkey(),
            new_multiplier,
            new_multiplier_timestamp,
            &[&authority],
        )
        .await
        .unwrap();

    {
        let context = context.lock().await;
        context.set_sysvar(&Clock {
            unix_timestamp: new_multiplier_timestamp,
            ..Default::default()
        });
    }

    let newest_multiplier = 101.0;
    let newest_multiplier_timestamp = new_multiplier_timestamp + 1;
    token
        .update_multiplier(
            &authority.pubkey(),
            newest_multiplier,
            newest_multiplier_timestamp,
            &[&authority],
        )
        .await
        .unwrap();

    let state = token.get_mint_info().await.unwrap();
    let extension = state.get_extension::<ScaledUiAmountConfig>().unwrap();
    assert_eq!(f64::from(extension.multiplier), new_multiplier);
    assert_eq!(f64::from(extension.new_multiplier), newest_multiplier);
    assert_eq!(
        i64::from(extension.new_multiplier_effective_timestamp),
        newest_multiplier_timestamp
    );
}

#[tokio::test]
async fn set_authority() {
    let authority = Keypair::new();
    let initial_multiplier = 500.0;
    let mut context = TestContext::new().await;
    context
        .init_token_with_mint(vec![ExtensionInitializationParams::ScaledUiAmountConfig {
            authority: Some(authority.pubkey()),
            multiplier: initial_multiplier,
        }])
        .await
        .unwrap();
    let TokenContext { token, .. } = context.token_context.take().unwrap();

    // success
    let new_authority = Keypair::new();
    token
        .set_authority(
            token.get_address(),
            &authority.pubkey(),
            Some(&new_authority.pubkey()),
            AuthorityType::ScaledUiAmount,
            &[&authority],
        )
        .await
        .unwrap();
    let state = token.get_mint_info().await.unwrap();
    let extension = state.get_extension::<ScaledUiAmountConfig>().unwrap();
    assert_eq!(
        extension.authority,
        Some(new_authority.pubkey()).try_into().unwrap(),
    );
    token
        .update_multiplier(&new_authority.pubkey(), 10.0, 0, &[&new_authority])
        .await
        .unwrap();
    let err = token
        .update_multiplier(&authority.pubkey(), 100.0, 0, &[&authority])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        TokenClientError::Client(Box::new(TransportError::TransactionError(
            TransactionError::InstructionError(
                0,
                InstructionError::Custom(TokenError::OwnerMismatch as u32)
            )
        )))
    );

    // set to none
    token
        .set_authority(
            token.get_address(),
            &new_authority.pubkey(),
            None,
            AuthorityType::ScaledUiAmount,
            &[&new_authority],
        )
        .await
        .unwrap();
    let state = token.get_mint_info().await.unwrap();
    let extension = state.get_extension::<ScaledUiAmountConfig>().unwrap();
    assert_eq!(extension.authority, None.try_into().unwrap(),);

    // now all fail
    let err = token
        .update_multiplier(&new_authority.pubkey(), 50.0, 0, &[&new_authority])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        TokenClientError::Client(Box::new(TransportError::TransactionError(
            TransactionError::InstructionError(
                0,
                InstructionError::Custom(TokenError::NoAuthorityExists as u32)
            )
        )))
    );
    let err = token
        .update_multiplier(&authority.pubkey(), 5.5, 0, &[&authority])
        .await
        .unwrap_err();
    assert_eq!(
        err,
        TokenClientError::Client(Box::new(TransportError::TransactionError(
            TransactionError::InstructionError(
                0,
                InstructionError::Custom(TokenError::NoAuthorityExists as u32)
            )
        )))
    );
}

// test program to CPI into token to get ui amounts
fn process_instruction(
    _program_id: &Pubkey,
    accounts: &[AccountInfo],
    _input: &[u8],
) -> ProgramResult {
    let account_info_iter = &mut accounts.iter();
    let mint_info = next_account_info(account_info_iter)?;
    let token_program = next_account_info(account_info_iter)?;
    // 10 tokens, with 9 decimal places
    let test_amount = 10_000_000_000;
    // "10" as an amount should be smaller than test_amount due to interest
    invoke(
        &ui_amount_to_amount(token_program.key, mint_info.key, "50")?,
        &[mint_info.clone(), token_program.clone()],
    )?;
    let (_, return_data) = get_return_data().unwrap();
    let amount = u64::from_le_bytes(return_data[0..8].try_into().unwrap());
    msg!("amount: {}", amount);
    if amount != test_amount {
        return Err(ProgramError::InvalidInstructionData);
    }

    // test_amount as a UI amount should be larger due to interest
    invoke(
        &amount_to_ui_amount(token_program.key, mint_info.key, test_amount)?,
        &[mint_info.clone(), token_program.clone()],
    )?;
    let (_, return_data) = get_return_data().unwrap();
    let ui_amount = String::from_utf8(return_data).unwrap();
    msg!("ui amount: {}", ui_amount);
    let float_ui_amount = ui_amount.parse::<f64>().unwrap();
    if float_ui_amount != 50.0 {
        return Err(ProgramError::InvalidInstructionData);
    }
    Ok(())
}

#[tokio::test]
async fn amount_conversions() {
    let authority = Keypair::new();
    let mut program_test = ProgramTest::default();
    program_test.add_program("spl_token_2022", spl_token_2022_interface::id(), None);
    program_test.prefer_bpf(false);
    let program_id = Pubkey::new_unique();
    program_test.add_program(
        "ui_amount_to_amount",
        program_id,
        processor!(process_instruction),
    );

    let context = program_test.start_with_context().await;
    let payer = keypair_clone(&context.payer);
    let last_blockhash = context.last_blockhash;
    let context = Arc::new(Mutex::new(context));
    let mut context = TestContext {
        context,
        token_context: None,
    };
    let initial_multiplier = 5.0;
    context
        .init_token_with_mint(vec![ExtensionInitializationParams::ScaledUiAmountConfig {
            authority: Some(authority.pubkey()),
            multiplier: initial_multiplier,
        }])
        .await
        .unwrap();
    let TokenContext { token, .. } = context.token_context.take().unwrap();

    let transaction = Transaction::new_signed_with_payer(
        &[Instruction {
            program_id,
            accounts: vec![
                AccountMeta::new_readonly(*token.get_address(), false),
                AccountMeta::new_readonly(spl_token_2022_interface::id(), false),
            ],
            data: vec![],
        }],
        Some(&payer.pubkey()),
        &[&payer],
        last_blockhash,
    );
    context
        .context
        .lock()
        .await
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();
}