near-kit 0.4.3

A clean, ergonomic Rust client for NEAR Protocol
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
//! Non-fungible token client (NEP-171).

use std::sync::Arc;

use serde::Serialize;
use tokio::sync::OnceCell;

use crate::client::{CallBuilder, RpcClient, Signer, TransactionBuilder};
use crate::error::Error;
use crate::types::{AccountId, BlockReference, Finality, Gas, NearToken};

use super::types::{NftContractMetadata, NftToken};

// =============================================================================
// NonFungibleToken
// =============================================================================

/// Client for interacting with a NEP-171 Non-Fungible Token contract.
///
/// Create via [`Near::nft()`](crate::Near::nft).
///
/// # Caching
///
/// Contract metadata is lazily fetched and cached on first use.
///
/// # Example
///
/// ```rust,no_run
/// use near_kit::*;
///
/// # async fn example() -> Result<(), near_kit::Error> {
/// let near = Near::testnet().build();
/// let nft = near.nft("nft-contract.near")?;
///
/// // Get contract metadata
/// let meta = nft.metadata().await.map_err(Error::from)?;
/// println!("Collection: {}", meta.name);
///
/// // Get a specific token
/// if let Some(token) = nft.token("token-123").await? {
///     println!("Owner: {}", token.owner_id);
/// }
///
/// // List tokens owned by an account
/// let tokens = nft.tokens_for_owner("alice.near", None, Some(10)).await.map_err(Error::from)?;
/// # Ok(())
/// # }
/// ```
pub struct NonFungibleToken {
    rpc: Arc<RpcClient>,
    signer: Option<Arc<dyn Signer>>,
    contract_id: AccountId,
    metadata: OnceCell<NftContractMetadata>,
    max_nonce_retries: u32,
}

impl NonFungibleToken {
    /// Create a new NonFungibleToken client.
    pub(crate) fn new(
        rpc: Arc<RpcClient>,
        signer: Option<Arc<dyn Signer>>,
        contract_id: AccountId,
        max_nonce_retries: u32,
    ) -> Self {
        Self {
            rpc,
            signer,
            contract_id,
            metadata: OnceCell::new(),
            max_nonce_retries,
        }
    }

    /// Get the contract ID.
    pub fn contract_id(&self) -> &AccountId {
        &self.contract_id
    }

    /// Create a transaction builder for this contract.
    fn transaction(&self) -> TransactionBuilder {
        TransactionBuilder::new(
            self.rpc.clone(),
            self.signer.clone(),
            self.contract_id.clone(),
            self.max_nonce_retries,
        )
    }

    // =========================================================================
    // View Methods
    // =========================================================================

    /// Get contract metadata (nft_metadata).
    ///
    /// Metadata is cached after the first call.
    pub async fn metadata(&self) -> Result<&NftContractMetadata, Error> {
        self.metadata
            .get_or_try_init(|| async {
                let result = self
                    .rpc
                    .view_function(
                        &self.contract_id,
                        "nft_metadata",
                        &[],
                        BlockReference::Finality(Finality::Optimistic),
                    )
                    .await
                    .map_err(Error::from)?;
                result.json().map_err(Error::from)
            })
            .await
    }

    /// Get a specific token by ID (nft_token).
    ///
    /// Returns `None` if the token doesn't exist.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet().build();
    /// let nft = near.nft("nft-contract.near")?;
    ///
    /// if let Some(token) = nft.token("token-123").await? {
    ///     println!("Token {} owned by {}", token.token_id, token.owner_id);
    ///     if let Some(meta) = &token.metadata {
    ///         println!("Title: {:?}", meta.title);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn token(&self, token_id: impl AsRef<str>) -> Result<Option<NftToken>, Error> {
        #[derive(Serialize)]
        struct Args<'a> {
            token_id: &'a str,
        }

        let args = serde_json::to_vec(&Args {
            token_id: token_id.as_ref(),
        })?;

        let result = self
            .rpc
            .view_function(
                &self.contract_id,
                "nft_token",
                &args,
                BlockReference::Finality(Finality::Optimistic),
            )
            .await?;

        result.json().map_err(Error::from)
    }

    /// Get tokens owned by an account (nft_tokens_for_owner).
    ///
    /// Supports pagination via `from_index` and `limit`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet().build();
    /// let nft = near.nft("nft-contract.near")?;
    ///
    /// // Get first 10 tokens
    /// let tokens = nft.tokens_for_owner("alice.near", None, Some(10)).await?;
    /// for token in &tokens {
    ///     println!("Token: {}", token.token_id);
    /// }
    ///
    /// // Get next 10 tokens
    /// let more = nft.tokens_for_owner("alice.near", Some(10), Some(10)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn tokens_for_owner(
        &self,
        account_id: impl AsRef<str>,
        from_index: Option<u64>,
        limit: Option<u64>,
    ) -> Result<Vec<NftToken>, Error> {
        #[derive(Serialize)]
        struct Args<'a> {
            account_id: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            from_index: Option<String>,
            #[serde(skip_serializing_if = "Option::is_none")]
            limit: Option<u64>,
        }

        let args = serde_json::to_vec(&Args {
            account_id: account_id.as_ref(),
            from_index: from_index.map(|i| i.to_string()),
            limit,
        })?;

        let result = self
            .rpc
            .view_function(
                &self.contract_id,
                "nft_tokens_for_owner",
                &args,
                BlockReference::Finality(Finality::Optimistic),
            )
            .await?;

        result.json().map_err(Error::from)
    }

    /// Get total supply of tokens (nft_total_supply).
    pub async fn total_supply(&self) -> Result<u64, Error> {
        let result = self
            .rpc
            .view_function(
                &self.contract_id,
                "nft_total_supply",
                &[],
                BlockReference::Finality(Finality::Optimistic),
            )
            .await
            .map_err(Error::from)?;

        let supply_str: String = result.json()?;
        supply_str.parse().map_err(|_| {
            Error::Rpc(crate::error::RpcError::InvalidResponse(format!(
                "Invalid supply format: {}",
                supply_str
            )))
        })
    }

    /// Get token supply for an owner (nft_supply_for_owner).
    pub async fn supply_for_owner(&self, account_id: impl AsRef<str>) -> Result<u64, Error> {
        #[derive(Serialize)]
        struct Args<'a> {
            account_id: &'a str,
        }

        let args = serde_json::to_vec(&Args {
            account_id: account_id.as_ref(),
        })?;

        let result = self
            .rpc
            .view_function(
                &self.contract_id,
                "nft_supply_for_owner",
                &args,
                BlockReference::Finality(Finality::Optimistic),
            )
            .await
            .map_err(Error::from)?;

        let supply_str: String = result.json()?;
        supply_str.parse().map_err(|_| {
            Error::Rpc(crate::error::RpcError::InvalidResponse(format!(
                "Invalid supply format: {}",
                supply_str
            )))
        })
    }

    // =========================================================================
    // Transfer Methods
    // =========================================================================

    /// Transfer an NFT to a receiver (nft_transfer).
    ///
    /// # Security
    ///
    /// This automatically attaches 1 yoctoNEAR as required by NEP-171 for
    /// security (prevents function-call access key abuse).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///     .credentials("ed25519:...", "alice.near")?
    ///     .build();
    /// let nft = near.nft("nft-contract.near")?;
    ///
    /// nft.transfer("bob.near", "token-123").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn transfer(&self, receiver_id: impl AsRef<str>, token_id: impl AsRef<str>) -> CallBuilder {
        #[derive(Serialize)]
        struct TransferArgs {
            receiver_id: String,
            token_id: String,
        }

        self.transaction()
            .call("nft_transfer")
            .args(TransferArgs {
                receiver_id: receiver_id.as_ref().to_string(),
                token_id: token_id.as_ref().to_string(),
            })
            .deposit(NearToken::yocto(1))
            .gas(Gas::tgas(30))
    }

    /// Transfer an NFT with a memo (nft_transfer).
    ///
    /// Same as [`transfer`](Self::transfer) but with an optional memo field.
    pub fn transfer_with_memo(
        &self,
        receiver_id: impl AsRef<str>,
        token_id: impl AsRef<str>,
        memo: impl Into<String>,
    ) -> CallBuilder {
        #[derive(Serialize)]
        struct TransferArgs {
            receiver_id: String,
            token_id: String,
            memo: String,
        }

        self.transaction()
            .call("nft_transfer")
            .args(TransferArgs {
                receiver_id: receiver_id.as_ref().to_string(),
                token_id: token_id.as_ref().to_string(),
                memo: memo.into(),
            })
            .deposit(NearToken::yocto(1))
            .gas(Gas::tgas(30))
    }

    /// Transfer an NFT with approval ID (for approved transfers).
    pub fn transfer_with_approval(
        &self,
        receiver_id: impl AsRef<str>,
        token_id: impl AsRef<str>,
        approval_id: u64,
    ) -> CallBuilder {
        #[derive(Serialize)]
        struct TransferArgs {
            receiver_id: String,
            token_id: String,
            approval_id: u64,
        }

        self.transaction()
            .call("nft_transfer")
            .args(TransferArgs {
                receiver_id: receiver_id.as_ref().to_string(),
                token_id: token_id.as_ref().to_string(),
                approval_id,
            })
            .deposit(NearToken::yocto(1))
            .gas(Gas::tgas(30))
    }

    /// Transfer an NFT with a callback to the receiver (nft_transfer_call).
    ///
    /// This calls `nft_on_transfer` on the receiver contract.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///     .credentials("ed25519:...", "alice.near")?
    ///     .build();
    /// let nft = near.nft("nft-contract.near")?;
    ///
    /// nft.transfer_call("marketplace.near", "token-123", r#"{"action":"list","price":"10"}"#)
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn transfer_call(
        &self,
        receiver_id: impl AsRef<str>,
        token_id: impl AsRef<str>,
        msg: impl Into<String>,
    ) -> CallBuilder {
        #[derive(Serialize)]
        struct TransferCallArgs {
            receiver_id: String,
            token_id: String,
            msg: String,
        }

        self.transaction()
            .call("nft_transfer_call")
            .args(TransferCallArgs {
                receiver_id: receiver_id.as_ref().to_string(),
                token_id: token_id.as_ref().to_string(),
                msg: msg.into(),
            })
            .deposit(NearToken::yocto(1))
            .gas(Gas::tgas(100))
    }
}

impl Clone for NonFungibleToken {
    fn clone(&self) -> Self {
        Self {
            rpc: self.rpc.clone(),
            signer: self.signer.clone(),
            contract_id: self.contract_id.clone(),
            metadata: OnceCell::new(),
            max_nonce_retries: self.max_nonce_retries,
        }
    }
}

impl std::fmt::Debug for NonFungibleToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NonFungibleToken")
            .field("contract_id", &self.contract_id)
            .field("metadata_cached", &self.metadata.initialized())
            .finish()
    }
}