near-api 0.8.6

Rust library to interact with NEAR Protocol via RPC API
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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use near_api_types::{
    AccountId, Action, Data, NearToken, Reference,
    ft::FungibleTokenMetadata,
    json::U128,
    nft::{NFTContractMetadata, Token},
    tokens::{FTBalance, STORAGE_COST_PER_BYTE, UserBalance},
    transaction::PrepopulateTransaction,
    transaction::actions::TransferAction,
};
use serde_json::json;

use crate::{
    NetworkConfig, StorageDeposit,
    advanced::{query_request::QueryRequest, query_rpc::SimpleQueryRpc},
    common::{
        query::{
            AccountViewHandler, CallResultHandler, MultiQueryHandler, MultiRequestBuilder,
            PostprocessHandler, RequestBuilder,
        },
        send::Transactionable,
    },
    contract::Contract,
    errors::{ArgumentValidationError, FTValidatorError, ValidationError},
    transactions::{ConstructTransaction, TransactionWithSign},
};

// This is not too long as most of the size is a links to the docs
#[allow(clippy::too_long_first_doc_paragraph)]
/// A wrapper struct that simplifies interactions with
/// [NEAR](https://docs.near.org/concepts/basics/tokens),
/// [FT](https://docs.near.org/build/primitives/ft),
/// [NFT](https://docs.near.org/build/primitives/nft)
///
/// This struct provides convenient methods to interact with different types of tokens on NEAR Protocol:
/// - [Native NEAR](https://docs.near.org/concepts/basics/tokens) token operations
/// - Fungible Token - [Documentation and examples](https://docs.near.org/build/primitives/ft), [NEP-141](https://github.com/near/NEPs/blob/master/neps/nep-0141.md)    
/// - Non-Fungible Token - [Documentation and examples](https://docs.near.org/build/primitives/nft), [NEP-171](https://github.com/near/NEPs/blob/master/neps/nep-0171.md)
///
/// ## Examples
///
/// ### Fungible Token Operations
/// ```
/// use near_api::*;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let bob_tokens = Tokens::account("bob.testnet".parse()?);
///
/// // Check FT balance
/// let balance = bob_tokens.ft_balance("usdt.tether-token.near".parse()?).fetch_from_mainnet().await?;
/// println!("Bob balance: {}", balance);
///
/// // Transfer FT tokens
/// bob_tokens.send_to("alice.testnet".parse()?)
///     .ft(
///         "usdt.tether-token.near".parse()?,
///         USDT_BALANCE.with_whole_amount(100)
///     )
///     .with_signer(Signer::from_ledger()?)
///     .send_to_mainnet()
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// ### NFT Operations
/// ```
/// use near_api::*;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let alice_tokens = Tokens::account("alice.testnet".parse()?);
///
/// // Check NFT assets
/// let tokens = alice_tokens.nft_assets("nft-contract.testnet".parse()?).fetch_from_testnet().await?;
/// println!("NFT count: {}", tokens.data.len());
///
/// // Transfer NFT
/// alice_tokens.send_to("bob.testnet".parse()?)
///     .nft("nft-contract.testnet".parse()?, "token-id".to_string())
///     .with_signer(Signer::from_ledger()?)
///     .send_to_testnet()
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// ### NEAR Token Operations
/// ```
/// use near_api::*;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let alice_account = Tokens::account("alice.testnet".parse()?);
///
/// // Check NEAR balance
/// let balance = alice_account.near_balance().fetch_from_testnet().await?;
/// println!("NEAR balance: {}", balance.total);
///
/// // Send NEAR
/// alice_account.send_to("bob.testnet".parse()?)
///     .near(NearToken::from_near(1))
///     .with_signer(Signer::from_ledger()?)
///     .send_to_testnet()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Tokens {
    account_id: AccountId,
}

impl Tokens {
    pub const fn account(account_id: AccountId) -> Self {
        Self { account_id }
    }

    /// Returns the underlying account ID for this tokens wrapper.
    ///
    /// # Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let tokens = Tokens::account("alice.testnet".parse()?);
    /// let account_id = tokens.account_id();
    /// println!("Account ID: {}", account_id);
    /// # Ok(())
    /// # }
    /// ```
    pub const fn account_id(&self) -> &AccountId {
        &self.account_id
    }

    /// Converts this tokens wrapper to an Account for account-related operations.
    ///
    /// # Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let tokens = Tokens::account("alice.testnet".parse()?);
    /// let account = tokens.as_account();
    /// let account_info = account.view().fetch_from_testnet().await?;
    /// println!("Account info: {:?}", account_info);
    /// # Ok(())
    /// # }
    /// ```
    pub fn as_account(&self) -> crate::account::Account {
        crate::account::Account(self.account_id.clone())
    }

    /// Fetches the total NEAR balance ([UserBalance]) of the account.
    ///
    /// ## Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_tokens = Tokens::account("alice.testnet".parse()?);
    /// let balance = alice_tokens.near_balance().fetch_from_testnet().await?;
    /// println!("Alice's NEAR balance: {:?}", balance);
    /// # Ok(())
    /// # }
    /// ```
    pub fn near_balance(
        &self,
    ) -> RequestBuilder<PostprocessHandler<UserBalance, AccountViewHandler>> {
        let request = QueryRequest::ViewAccount {
            account_id: self.account_id.clone(),
        };

        RequestBuilder::new(
            SimpleQueryRpc { request },
            Reference::Optimistic,
            AccountViewHandler,
        )
        .map(|account| {
            let account = account.data;
            let storage_locked = NearToken::from_yoctonear(
                account.storage_usage as u128 * STORAGE_COST_PER_BYTE.as_yoctonear(),
            );
            UserBalance {
                total: account.amount,
                storage_locked,
                storage_usage: account.storage_usage,
                locked: account.locked,
            }
        })
    }

    /// Prepares a new contract query (`nft_metadata`) for fetching the NFT metadata ([NFTContractMetadata]).
    ///
    /// The function depends that the contract implements [`NEP-171`](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core#nep-171)
    ///
    /// ## Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let metadata = Tokens::nft_metadata("nft-contract.testnet".parse()?)
    ///     .fetch_from_testnet()
    ///     .await?;
    /// println!("NFT metadata: {:?}", metadata);
    /// # Ok(())
    /// # }
    /// ```
    pub fn nft_metadata(
        contract_id: AccountId,
    ) -> RequestBuilder<CallResultHandler<NFTContractMetadata>> {
        Contract(contract_id)
            .call_function("nft_metadata", ())
            .read_only()
    }

    /// Prepares a new contract query (`nft_tokens_for_owner`) for fetching the NFT assets of the account ([Vec]<[Token]>).
    ///
    /// The function depends that the contract implements [`NEP-171`](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core#nep-171)
    ///
    /// ## Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_tokens = Tokens::account("alice.testnet".parse()?);
    /// let alice_assets = alice_tokens.nft_assets("nft-contract.testnet".parse()?)
    ///     .fetch_from_testnet()
    ///     .await?;
    /// println!("Alice's NFT assets: {:?}", alice_assets);
    /// # Ok(())
    /// # }
    /// ```
    pub fn nft_assets(
        &self,
        nft_contract: AccountId,
    ) -> RequestBuilder<CallResultHandler<Vec<Token>>> {
        Contract(nft_contract)
            .call_function(
                "nft_tokens_for_owner",
                json!({
                    "account_id": self.account_id.to_string(),
                }),
            )
            .read_only()
    }

    /// Prepares a new contract query (`ft_metadata`) for fetching the FT metadata ([FungibleTokenMetadata]).
    ///
    /// The function depends that the contract implements [`NEP-141`](https://nomicon.io/Standards/Tokens/FungibleToken/Core#nep-141)
    ///
    /// ## Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let metadata = Tokens::ft_metadata("usdt.tether-token.near".parse()?)
    ///     .fetch_from_testnet()
    ///     .await?
    ///     .data;
    /// println!("FT metadata: {} {}", metadata.name, metadata.symbol);
    /// # Ok(())
    /// # }
    /// ```
    pub fn ft_metadata(
        contract_id: AccountId,
    ) -> RequestBuilder<CallResultHandler<FungibleTokenMetadata>> {
        Contract(contract_id)
            .call_function("ft_metadata", ())
            .read_only()
    }

    /// Prepares a new contract query (`ft_balance_of`, `ft_metadata`) for fetching the [FTBalance] of the account.
    ///
    /// This query is a multi-query, meaning it will fetch the FT metadata and the FT balance of the account.
    /// The result is then postprocessed to create a `FTBalance` instance.
    ///
    /// The function depends that the contract implements [`NEP-141`](https://nomicon.io/Standards/Tokens/FungibleToken/Core#nep-141)
    ///
    /// # Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_usdt_balance = Tokens::account("alice.near".parse()?)
    ///     .ft_balance("usdt.tether-token.near".parse()?)
    ///     .fetch_from_mainnet()
    ///     .await?;
    /// println!("Alice's USDT balance: {}", alice_usdt_balance);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::type_complexity)]
    pub fn ft_balance(
        &self,
        ft_contract: AccountId,
    ) -> MultiRequestBuilder<
        PostprocessHandler<
            FTBalance,
            MultiQueryHandler<(
                CallResultHandler<FungibleTokenMetadata>,
                CallResultHandler<U128>,
            )>,
        >,
    > {
        let handler = MultiQueryHandler::new((
            CallResultHandler::<FungibleTokenMetadata>::new(),
            CallResultHandler::<U128>::new(),
        ));

        MultiRequestBuilder::new(handler, Reference::Optimistic)
            .add_query_builder(Self::ft_metadata(ft_contract.clone()))
            .add_query_builder(
                Contract(ft_contract)
                    .call_function(
                        "ft_balance_of",
                        json!({
                            "account_id": self.account_id.clone()
                        }),
                    )
                    .read_only::<()>(),
            )
            .map(
                |(metadata, amount): (Data<FungibleTokenMetadata>, Data<U128>)| {
                    FTBalance::with_decimals(metadata.data.decimals).with_amount(amount.data.0)
                },
            )
    }

    /// Prepares a new transaction builder for sending tokens to another account.
    ///
    /// This builder is used to construct transactions for sending NEAR, FT, and NFT tokens.
    ///
    /// ## Sending NEAR
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_tokens = Tokens::account("alice.near".parse()?);
    ///
    /// let result = alice_tokens.send_to("bob.near".parse()?)
    ///     .near(NearToken::from_near(1))
    ///     .with_signer(Signer::from_ledger()?)
    ///     .send_to_mainnet()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Sending FT
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_tokens = Tokens::account("alice.near".parse()?);
    ///
    /// let result = alice_tokens.send_to("bob.near".parse()?)
    ///     .ft("usdt.tether-token.near".parse()?, USDT_BALANCE.with_whole_amount(100))
    ///     .with_signer(Signer::from_ledger()?)
    ///     .send_to_mainnet()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Sending NFT
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_tokens = Tokens::account("alice.near".parse()?);
    ///
    /// let result = alice_tokens.send_to("bob.near".parse()?)
    ///     .nft("nft-contract.testnet".parse()?, "token-id".to_string())
    ///     .with_signer(Signer::from_ledger()?)
    ///     .send_to_testnet()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn send_to(&self, receiver_id: AccountId) -> SendToBuilder {
        SendToBuilder {
            from: self.account_id.clone(),
            receiver_id,
        }
    }
}

#[derive(Debug, Clone)]
pub struct SendToBuilder {
    from: AccountId,
    receiver_id: AccountId,
}

impl SendToBuilder {
    /// Prepares a new transaction for sending NEAR tokens to another account.
    pub fn near(self, amount: NearToken) -> ConstructTransaction {
        ConstructTransaction::new(self.from, self.receiver_id)
            .add_action(Action::Transfer(TransferAction { deposit: amount }))
    }

    /// Prepares a new transaction contract call (`ft_transfer`, `ft_metadata`, `storage_balance_of`, `storage_deposit`) for sending FT tokens to another account.
    ///
    /// Please note that if the receiver does not have enough storage, we will automatically deposit 100 milliNEAR for storage from
    /// the sender.
    ///
    /// The provided function depends that the contract implements [`NEP-141`](https://nomicon.io/Standards/Tokens/FungibleToken/Core#nep-141)
    ///
    /// For transferring tokens and calling a receiver contract method in a single transaction, see [`ft_call`](Self::ft_call).
    pub fn ft(
        self,
        ft_contract: AccountId,
        amount: FTBalance,
    ) -> TransactionWithSign<FTTransactionable> {
        let transaction = Contract(ft_contract)
            .call_function(
                "ft_transfer",
                json!({
                    "receiver_id": self.receiver_id,
                    "amount": amount.amount().to_string(),
                }),
            )
            .transaction()
            .deposit(NearToken::from_yoctonear(1))
            .with_signer_account(self.from);

        TransactionWithSign {
            tx: FTTransactionable {
                receiver: self.receiver_id,
                transaction: transaction.transaction,
                decimals: amount.decimals(),
            },
        }
    }

    /// Prepares a new transaction contract call (`nft_transfer`) for sending NFT tokens to another account.
    ///
    /// The provided function depends that the contract implements [`NEP-171`](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core#nep-171)
    ///
    /// For transferring an NFT and calling a receiver contract method in a single transaction, see [`nft_call`](Self::nft_call).
    pub fn nft(self, nft_contract: AccountId, token_id: String) -> ConstructTransaction {
        Contract(nft_contract)
            .call_function(
                "nft_transfer",
                json!({
                    "receiver_id": self.receiver_id,
                    "token_id": token_id
                }),
            )
            .transaction()
            .deposit(NearToken::from_yoctonear(1))
            .with_signer_account(self.from)
    }

    /// Prepares a new transaction contract call (`ft_transfer_call`, `ft_metadata`, `storage_balance_of`, `storage_deposit`) for transferring FT tokens and calling a receiver contract method.
    ///
    /// This method enables transferring tokens and invoking a receiver contract method in a single transaction.
    /// The receiver contract must implement `ft_on_transfer` according to NEP-141.
    ///
    /// Please note that if the receiver does not have enough storage, we will automatically deposit 100 milliNEAR for storage from
    /// the sender.
    ///
    /// The provided function depends that the contract implements [`NEP-141`](https://nomicon.io/Standards/Tokens/FungibleToken/Core#nep-141)
    ///
    /// ## Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_tokens = Tokens::account("alice.near".parse()?);
    ///
    /// let result = alice_tokens.send_to("contract.near".parse()?)
    ///     .ft_call(
    ///         "usdt.tether-token.near".parse()?,
    ///         USDT_BALANCE.with_whole_amount(100),
    ///         "deposit".to_string(),
    ///     )
    ///     .with_signer(Signer::from_ledger()?)
    ///     .send_to_mainnet()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn ft_call(
        self,
        ft_contract: AccountId,
        amount: FTBalance,
        msg: String,
    ) -> TransactionWithSign<FTTransactionable> {
        let transaction = Contract(ft_contract)
            .call_function(
                "ft_transfer_call",
                json!({
                    "receiver_id": self.receiver_id,
                    "amount": amount.amount().to_string(),
                    "msg": msg,
                }),
            )
            .transaction()
            .deposit(NearToken::from_yoctonear(1))
            .with_signer_account(self.from);

        TransactionWithSign {
            tx: FTTransactionable {
                receiver: self.receiver_id,
                transaction: transaction.transaction,
                decimals: amount.decimals(),
            },
        }
    }

    /// Prepares a new transaction contract call (`nft_transfer_call`) for transferring an NFT and calling a receiver contract method.
    ///
    /// This method enables "transfer and call" functionality, allowing a user to attach an NFT to a function call
    /// on a separate contract in a single transaction. The receiver contract must implement `nft_on_transfer` according to NEP-171.
    ///
    /// The provided function depends that the contract implements [`NEP-171`](https://nomicon.io/Standards/Tokens/NonFungibleToken/Core#nep-171)
    ///
    /// ## Example
    /// ```rust,no_run
    /// use near_api::*;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let alice_tokens = Tokens::account("alice.near".parse()?);
    ///
    /// let result = alice_tokens.send_to("marketplace.near".parse()?)
    ///     .nft_call(
    ///         "nft-contract.testnet".parse()?,
    ///         "token-123".to_string(),
    ///         "list_for_sale".to_string(),
    ///     )
    ///     .with_signer(Signer::from_ledger()?)
    ///     .send_to_testnet()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn nft_call(
        self,
        nft_contract: AccountId,
        token_id: String,
        msg: String,
    ) -> ConstructTransaction {
        Contract(nft_contract)
            .call_function(
                "nft_transfer_call",
                json!({
                    "receiver_id": self.receiver_id,
                    "token_id": token_id,
                    "msg": msg,
                }),
            )
            .transaction()
            .deposit(NearToken::from_yoctonear(1))
            .with_signer_account(self.from)
    }
}

/// The structs validates the decimals correctness on runtime level before
/// sending the ft tokens as well as deposits 100 milliNear of the deposit if
/// the receiver doesn't have any allocated storage in the provided FT contract
#[derive(Clone, Debug)]
pub struct FTTransactionable {
    transaction: Result<PrepopulateTransaction, ArgumentValidationError>,
    receiver: AccountId,
    decimals: u8,
}

impl FTTransactionable {
    pub async fn check_decimals(&self, network: &NetworkConfig) -> Result<(), ValidationError> {
        let transaction = match &self.transaction {
            Ok(transaction) => transaction,
            Err(e) => return Err(e.to_owned().into()),
        };

        let metadata = Tokens::ft_metadata(transaction.receiver_id.clone());

        let Ok(metadata) = metadata.fetch_from(network).await else {
            // If there is no metadata, than we can't check it
            return Ok(());
        };

        if metadata.data.decimals != self.decimals {
            Err(FTValidatorError::DecimalsMismatch {
                expected: metadata.data.decimals,
                got: self.decimals,
            })?;
        }
        Ok(())
    }
}

#[async_trait::async_trait]
impl Transactionable for FTTransactionable {
    fn prepopulated(&self) -> Result<PrepopulateTransaction, ArgumentValidationError> {
        self.transaction.clone()
    }

    async fn validate_with_network(
        &self,
        network: &NetworkConfig,
    ) -> core::result::Result<(), ValidationError> {
        self.check_decimals(network).await?;

        let transaction = match &self.transaction {
            Ok(transaction) => transaction,
            Err(_) => return Ok(()),
        };

        let storage_balance = StorageDeposit::on_contract(transaction.receiver_id.clone())
            .view_account_storage(self.receiver.clone())
            .fetch_from(network)
            .await
            .map_err(ValidationError::QueryError)?;

        if storage_balance.data.is_none() {
            Err(FTValidatorError::StorageDepositNeeded)?;
        }

        Ok(())
    }

    async fn edit_with_network(
        &mut self,
        network: &NetworkConfig,
    ) -> core::result::Result<(), ValidationError> {
        self.check_decimals(network).await?;

        let transaction = match &mut self.transaction {
            Ok(transaction) => transaction,
            Err(_) => return Ok(()),
        };

        let storage_balance = StorageDeposit::on_contract(transaction.receiver_id.clone())
            .view_account_storage(self.receiver.clone())
            .fetch_from(network)
            .await
            .map_err(ValidationError::QueryError)?;

        if storage_balance.data.is_none() {
            let mut action = StorageDeposit::on_contract(transaction.receiver_id.clone())
                .deposit(self.receiver.clone(), NearToken::from_millinear(100))
                .into_transaction()
                .with_signer_account(transaction.signer_id.clone())
                .prepopulated()?
                .actions;
            action.append(&mut transaction.actions);
            transaction.actions = action;
        }
        Ok(())
    }
}