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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
//! The main Near client.

use std::sync::Arc;

use serde::de::DeserializeOwned;

use crate::contract::ContractClient;
use crate::error::Error;
use crate::types::{AccountId, Gas, IntoNearToken, NearToken, Network, PublicKey, SecretKey};

use super::query::{AccessKeysQuery, AccountExistsQuery, AccountQuery, BalanceQuery, ViewCall};
use super::rpc::{MAINNET, RetryConfig, RpcClient, TESTNET};
use super::signer::{InMemorySigner, Signer};
use super::transaction::{CallBuilder, TransactionBuilder};
use crate::types::TxExecutionStatus;

/// Trait for sandbox network configuration.
///
/// Implement this trait for your sandbox type to enable ergonomic
/// integration with the `Near` client via [`Near::sandbox()`].
///
/// # Example
///
/// ```rust,ignore
/// use near_sandbox::Sandbox;
///
/// let sandbox = Sandbox::start_sandbox().await?;
/// let near = Near::sandbox(&sandbox).build();
///
/// // The root account credentials are automatically configured
/// near.transfer("alice.sandbox", "10 NEAR").await?;
/// ```
pub trait SandboxNetwork {
    /// The RPC URL for the sandbox (e.g., `http://127.0.0.1:3030`).
    fn rpc_url(&self) -> &str;

    /// The root account ID (e.g., `"sandbox"`).
    fn root_account_id(&self) -> &str;

    /// The root account's secret key.
    fn root_secret_key(&self) -> &str;
}

/// The main client for interacting with NEAR Protocol.
///
/// The `Near` client is the single entry point for all NEAR operations.
/// It can be configured with a signer for write operations, or used
/// without a signer for read-only operations.
///
/// Transport (RPC connection) and signing are separate concerns — the client
/// holds a shared `Arc<RpcClient>` and an optional signer. Use [`with_signer`](Near::with_signer)
/// to derive new clients that share the same connection but sign as different accounts.
///
/// # Example
///
/// ```rust,no_run
/// use near_kit::*;
///
/// #[tokio::main]
/// async fn main() -> Result<(), near_kit::Error> {
///     // Read-only client (no signer)
///     let near = Near::testnet().build();
///     let balance = near.balance("alice.testnet").await?;
///     println!("Balance: {}", balance);
///
///     // Client with signer for transactions
///     let near = Near::testnet()
///         .credentials("ed25519:...", "alice.testnet")?
///         .build();
///     near.transfer("bob.testnet", "1 NEAR").await?;
///
///     Ok(())
/// }
/// ```
///
/// # Multiple Accounts
///
/// For production apps that manage multiple accounts, set up the connection once
/// and derive signing contexts with [`with_signer`](Near::with_signer):
///
/// ```rust,no_run
/// # use near_kit::*;
/// # fn example() -> Result<(), Error> {
/// let near = Near::testnet().build();
///
/// let alice = near.with_signer(InMemorySigner::new("alice.testnet", "ed25519:...")?);
/// let bob = near.with_signer(InMemorySigner::new("bob.testnet", "ed25519:...")?);
///
/// // Both share the same RPC connection, sign as different accounts
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Near {
    rpc: Arc<RpcClient>,
    signer: Option<Arc<dyn Signer>>,
    network: Network,
    max_nonce_retries: u32,
}

impl Near {
    /// Create a builder for mainnet.
    pub fn mainnet() -> NearBuilder {
        NearBuilder::new(MAINNET.rpc_url, Network::Mainnet)
    }

    /// Create a builder for testnet.
    pub fn testnet() -> NearBuilder {
        NearBuilder::new(TESTNET.rpc_url, Network::Testnet)
    }

    /// Create a builder with a custom RPC URL.
    pub fn custom(rpc_url: impl Into<String>) -> NearBuilder {
        NearBuilder::new(rpc_url, Network::Custom)
    }

    /// Create a configured client from environment variables.
    ///
    /// Reads the following environment variables:
    /// - `NEAR_NETWORK` (optional): `"mainnet"`, `"testnet"`, or a custom RPC URL.
    ///   Defaults to `"testnet"` if not set.
    /// - `NEAR_ACCOUNT_ID` (optional): Account ID for signing transactions.
    /// - `NEAR_PRIVATE_KEY` (optional): Private key for signing (e.g., `"ed25519:..."`).
    ///
    /// If `NEAR_ACCOUNT_ID` and `NEAR_PRIVATE_KEY` are both set, the client will
    /// be configured with signing capability. Otherwise, it will be read-only.
    ///
    /// # Example
    ///
    /// ```bash
    /// # Environment variables
    /// export NEAR_NETWORK=testnet
    /// export NEAR_ACCOUNT_ID=alice.testnet
    /// export NEAR_PRIVATE_KEY=ed25519:...
    /// ```
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// // Auto-configures from environment
    /// let near = Near::from_env()?;
    ///
    /// // If credentials are set, transactions work
    /// near.transfer("bob.testnet", "1 NEAR").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `NEAR_ACCOUNT_ID` is set without `NEAR_PRIVATE_KEY` (or vice versa)
    /// - `NEAR_PRIVATE_KEY` contains an invalid key format
    pub fn from_env() -> Result<Near, Error> {
        let network = std::env::var("NEAR_NETWORK").ok();
        let account_id = std::env::var("NEAR_ACCOUNT_ID").ok();
        let private_key = std::env::var("NEAR_PRIVATE_KEY").ok();

        // Determine builder based on network
        let mut builder = match network.as_deref() {
            Some("mainnet") => Near::mainnet(),
            Some("testnet") | None => Near::testnet(),
            Some(url) => Near::custom(url),
        };

        // Configure signer if both account and key are provided
        match (account_id, private_key) {
            (Some(account), Some(key)) => {
                builder = builder.credentials(&key, &account)?;
            }
            (Some(_), None) => {
                return Err(Error::Config(
                    "NEAR_ACCOUNT_ID is set but NEAR_PRIVATE_KEY is missing".into(),
                ));
            }
            (None, Some(_)) => {
                return Err(Error::Config(
                    "NEAR_PRIVATE_KEY is set but NEAR_ACCOUNT_ID is missing".into(),
                ));
            }
            (None, None) => {
                // Read-only client, no credentials
            }
        }

        Ok(builder.build())
    }

    /// Create a builder configured for a sandbox network.
    ///
    /// This automatically configures the client with the sandbox's RPC URL
    /// and root account credentials, making it ready for transactions.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use near_sandbox::Sandbox;
    /// use near_kit::*;
    ///
    /// let sandbox = Sandbox::start_sandbox().await?;
    /// let near = Near::sandbox(&sandbox);
    ///
    /// // Root account credentials are auto-configured - ready for transactions!
    /// near.transfer("alice.sandbox", "10 NEAR").await?;
    /// ```
    pub fn sandbox(network: &impl SandboxNetwork) -> Near {
        let secret_key: SecretKey = network
            .root_secret_key()
            .parse()
            .expect("sandbox should provide valid secret key");
        let account_id: AccountId = network
            .root_account_id()
            .parse()
            .expect("sandbox should provide valid account id");

        let signer = InMemorySigner::from_secret_key(account_id, secret_key);

        Near {
            rpc: Arc::new(RpcClient::new(network.rpc_url())),
            signer: Some(Arc::new(signer)),
            network: Network::Sandbox,
            max_nonce_retries: 3,
        }
    }

    /// Get the underlying RPC client.
    pub fn rpc(&self) -> &RpcClient {
        &self.rpc
    }

    /// Get the RPC URL.
    pub fn rpc_url(&self) -> &str {
        self.rpc.url()
    }

    /// Get the signer's account ID, if a signer is configured.
    pub fn account_id(&self) -> Option<&AccountId> {
        self.signer.as_ref().map(|s| s.account_id())
    }

    /// Get the network this client is connected to.
    pub fn network(&self) -> Network {
        self.network
    }

    /// Create a new client that shares this client's transport but uses a different signer.
    ///
    /// This is the recommended way to manage multiple accounts. The RPC connection
    /// is shared (via `Arc`), so there's no overhead from creating multiple clients.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # fn example() -> Result<(), Error> {
    /// // Set up a shared connection
    /// let near = Near::testnet().build();
    ///
    /// // Derive signing contexts for different accounts
    /// let alice = near.with_signer(InMemorySigner::new("alice.testnet", "ed25519:...")?);
    /// let bob = near.with_signer(InMemorySigner::new("bob.testnet", "ed25519:...")?);
    ///
    /// // Both share the same RPC connection
    /// // alice.transfer("carol.testnet", NearToken::near(1)).await?;
    /// // bob.transfer("carol.testnet", NearToken::near(2)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_signer(&self, signer: impl Signer + 'static) -> Near {
        Near {
            rpc: self.rpc.clone(),
            signer: Some(Arc::new(signer)),
            network: self.network,
            max_nonce_retries: self.max_nonce_retries,
        }
    }

    // ========================================================================
    // Read Operations (Query Builders)
    // ========================================================================

    /// Get account balance.
    ///
    /// Returns a query builder that can be customized with block reference
    /// options before awaiting.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet().build();
    ///
    /// // Simple query
    /// let balance = near.balance("alice.testnet").await?;
    /// println!("Available: {}", balance.available);
    ///
    /// // Query at specific block height
    /// let balance = near.balance("alice.testnet")
    ///     .at_block(100_000_000)
    ///     .await?;
    ///
    /// // Query with specific finality
    /// let balance = near.balance("alice.testnet")
    ///     .finality(Finality::Optimistic)
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn balance(&self, account_id: impl AsRef<str>) -> BalanceQuery {
        let account_id = AccountId::parse_lenient(account_id);
        BalanceQuery::new(self.rpc.clone(), account_id)
    }

    /// Get full account information.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet().build();
    /// let account = near.account("alice.testnet").await?;
    /// println!("Storage used: {} bytes", account.storage_usage);
    /// # Ok(())
    /// # }
    /// ```
    pub fn account(&self, account_id: impl AsRef<str>) -> AccountQuery {
        let account_id = AccountId::parse_lenient(account_id);
        AccountQuery::new(self.rpc.clone(), account_id)
    }

    /// Check if an account exists.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet().build();
    /// if near.account_exists("alice.testnet").await? {
    ///     println!("Account exists!");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn account_exists(&self, account_id: impl AsRef<str>) -> AccountExistsQuery {
        let account_id = AccountId::parse_lenient(account_id);
        AccountExistsQuery::new(self.rpc.clone(), account_id)
    }

    /// Call a view function on a contract.
    ///
    /// Returns a query builder that can be customized with arguments
    /// and block reference options before awaiting.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet().build();
    ///
    /// // Simple view call
    /// let count: u64 = near.view("counter.testnet", "get_count").await?;
    ///
    /// // View call with arguments
    /// let messages: Vec<String> = near.view("guestbook.testnet", "get_messages")
    ///     .args(serde_json::json!({ "limit": 10 }))
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn view<T>(&self, contract_id: impl AsRef<str>, method: &str) -> ViewCall<T> {
        let contract_id = AccountId::parse_lenient(contract_id);
        ViewCall::new(self.rpc.clone(), contract_id, method.to_string())
    }

    /// Get all access keys for an account.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet().build();
    /// let keys = near.access_keys("alice.testnet").await?;
    /// for key_info in keys.keys {
    ///     println!("Key: {}", key_info.public_key);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn access_keys(&self, account_id: impl AsRef<str>) -> AccessKeysQuery {
        let account_id = AccountId::parse_lenient(account_id);
        AccessKeysQuery::new(self.rpc.clone(), account_id)
    }

    // ========================================================================
    // Off-Chain Signing (NEP-413)
    // ========================================================================

    /// Sign a message for off-chain authentication (NEP-413).
    ///
    /// This enables users to prove account ownership without gas fees
    /// or blockchain transactions. Commonly used for:
    /// - Web3 authentication/login
    /// - Off-chain message signing
    /// - Proof of account ownership
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///     .credentials("ed25519:...", "alice.testnet")?
    ///     .build();
    ///
    /// let signed = near.sign_message(nep413::SignMessageParams {
    ///     message: "Login to MyApp".to_string(),
    ///     recipient: "myapp.com".to_string(),
    ///     nonce: nep413::generate_nonce(),
    ///     callback_url: None,
    ///     state: None,
    /// }).await?;
    ///
    /// println!("Signed by: {}", signed.account_id);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// @see <https://github.com/near/NEPs/blob/master/neps/nep-0413.md>
    pub async fn sign_message(
        &self,
        params: crate::types::nep413::SignMessageParams,
    ) -> Result<crate::types::nep413::SignedMessage, Error> {
        let signer = self.signer.as_ref().ok_or(Error::NoSigner)?;
        let key = signer.key();
        key.sign_nep413(signer.account_id(), &params)
            .await
            .map_err(Error::Signing)
    }

    // ========================================================================
    // Write Operations (Transaction Builders)
    // ========================================================================

    /// Transfer NEAR tokens.
    ///
    /// Returns a transaction builder that can be customized with
    /// wait options before awaiting.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///         .credentials("ed25519:...", "alice.testnet")?
    ///     .build();
    ///
    /// // Preferred: typed constructor
    /// near.transfer("bob.testnet", NearToken::near(1)).await?;
    ///
    /// // Transfer with wait for finality
    /// near.transfer("bob.testnet", NearToken::near(1000))
    ///     .wait_until(TxExecutionStatus::Final)
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn transfer(
        &self,
        receiver: impl AsRef<str>,
        amount: impl IntoNearToken,
    ) -> TransactionBuilder {
        self.transaction(receiver).transfer(amount)
    }

    /// Call a function on a contract.
    ///
    /// Returns a transaction builder that can be customized with
    /// arguments, gas, deposit, and other options before awaiting.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///         .credentials("ed25519:...", "alice.testnet")?
    ///     .build();
    ///
    /// // Simple call
    /// near.call("counter.testnet", "increment").await?;
    ///
    /// // Call with args, gas, and deposit
    /// near.call("nft.testnet", "nft_mint")
    ///     .args(serde_json::json!({ "token_id": "1" }))
    ///     .gas("100 Tgas")
    ///     .deposit("0.1 NEAR")
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn call(&self, contract_id: impl AsRef<str>, method: &str) -> CallBuilder {
        self.transaction(contract_id).call(method)
    }

    /// Deploy a contract.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///         .credentials("ed25519:...", "alice.testnet")?
    ///     .build();
    ///
    /// let wasm_code = std::fs::read("contract.wasm").unwrap();
    /// near.deploy("alice.testnet", wasm_code).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn deploy(
        &self,
        account_id: impl AsRef<str>,
        code: impl Into<Vec<u8>>,
    ) -> TransactionBuilder {
        self.transaction(account_id).deploy(code)
    }

    /// Add a full access key to an account.
    pub fn add_full_access_key(
        &self,
        account_id: impl AsRef<str>,
        public_key: PublicKey,
    ) -> TransactionBuilder {
        self.transaction(account_id).add_full_access_key(public_key)
    }

    /// Delete an access key from an account.
    pub fn delete_key(
        &self,
        account_id: impl AsRef<str>,
        public_key: PublicKey,
    ) -> TransactionBuilder {
        self.transaction(account_id).delete_key(public_key)
    }

    // ========================================================================
    // Multi-Action Transactions
    // ========================================================================

    /// Create a transaction builder for multi-action transactions.
    ///
    /// This allows chaining multiple actions (transfers, function calls, account creation, etc.)
    /// into a single atomic transaction. All actions either succeed together or fail together.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///     .credentials("ed25519:...", "alice.testnet")?
    ///     .build();
    ///
    /// // Create a new sub-account with funding and a key
    /// let new_public_key: PublicKey = "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp".parse()?;
    /// near.transaction("new.alice.testnet")
    ///     .create_account()
    ///     .transfer("5 NEAR")
    ///     .add_full_access_key(new_public_key)
    ///     .send()
    ///     .await?;
    ///
    /// // Multiple function calls in one transaction
    /// near.transaction("contract.testnet")
    ///     .call("method1")
    ///         .args(serde_json::json!({ "value": 1 }))
    ///     .call("method2")
    ///         .args(serde_json::json!({ "value": 2 }))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn transaction(&self, receiver_id: impl AsRef<str>) -> TransactionBuilder {
        let receiver_id = AccountId::parse_lenient(receiver_id);
        TransactionBuilder::new(
            self.rpc.clone(),
            self.signer.clone(),
            receiver_id,
            self.max_nonce_retries,
        )
    }

    /// Send a pre-signed transaction.
    ///
    /// Use this with transactions signed via `.sign()` for offline signing
    /// or inspection before sending.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::testnet()
    ///     .credentials("ed25519:...", "alice.testnet")?
    ///     .build();
    ///
    /// // Sign offline
    /// let signed = near.transfer("bob.testnet", NearToken::near(1))
    ///     .sign()
    ///     .await?;
    ///
    /// // Send later
    /// let outcome = near.send(&signed).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send(
        &self,
        signed_tx: &crate::types::SignedTransaction,
    ) -> Result<crate::types::FinalExecutionOutcome, Error> {
        self.send_with_options(signed_tx, TxExecutionStatus::ExecutedOptimistic)
            .await
    }

    /// Send a pre-signed transaction with custom wait options.
    pub async fn send_with_options(
        &self,
        signed_tx: &crate::types::SignedTransaction,
        wait_until: TxExecutionStatus,
    ) -> Result<crate::types::FinalExecutionOutcome, Error> {
        let response = self.rpc.send_tx(signed_tx, wait_until).await?;
        let outcome = response.outcome.ok_or_else(|| {
            Error::InvalidTransaction(format!(
                "Transaction {} submitted with wait_until={:?} but no execution outcome \
                 was returned. Use rpc().send_tx() for fire-and-forget submission.",
                response.transaction_hash, wait_until,
            ))
        })?;

        if outcome.is_failure() {
            return Err(Error::TransactionFailed(
                outcome.failure_message().unwrap_or_default(),
            ));
        }

        Ok(outcome)
    }

    // ========================================================================
    // Convenience methods
    // ========================================================================

    /// Call a view function with arguments (convenience method).
    pub async fn view_with_args<T: DeserializeOwned + Send + 'static, A: serde::Serialize>(
        &self,
        contract_id: impl AsRef<str>,
        method: &str,
        args: &A,
    ) -> Result<T, Error> {
        let contract_id = AccountId::parse_lenient(contract_id);
        ViewCall::new(self.rpc.clone(), contract_id, method.to_string())
            .args(args)
            .await
    }

    /// Call a function with arguments (convenience method).
    pub async fn call_with_args<A: serde::Serialize>(
        &self,
        contract_id: impl AsRef<str>,
        method: &str,
        args: &A,
    ) -> Result<crate::types::FinalExecutionOutcome, Error> {
        self.call(contract_id, method).args(args).await
    }

    /// Call a function with full options (convenience method).
    pub async fn call_with_options<A: serde::Serialize>(
        &self,
        contract_id: impl AsRef<str>,
        method: &str,
        args: &A,
        gas: Gas,
        deposit: NearToken,
    ) -> Result<crate::types::FinalExecutionOutcome, Error> {
        self.call(contract_id, method)
            .args(args)
            .gas(gas)
            .deposit(deposit)
            .await
    }

    // ========================================================================
    // Typed Contract Interfaces
    // ========================================================================

    /// Create a typed contract client.
    ///
    /// This method creates a type-safe client for interacting with a contract,
    /// using the interface defined via the `#[near_kit::contract]` macro.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use near_kit::*;
    /// use serde::Serialize;
    ///
    /// #[near_kit::contract]
    /// pub trait Counter {
    ///     fn get_count(&self) -> u64;
    ///     
    ///     #[call]
    ///     fn increment(&mut self);
    ///     
    ///     #[call]
    ///     fn add(&mut self, args: AddArgs);
    /// }
    ///
    /// #[derive(Serialize)]
    /// pub struct AddArgs {
    ///     pub value: u64,
    /// }
    ///
    /// async fn example(near: &Near) -> Result<(), near_kit::Error> {
    ///     let counter = near.contract::<Counter>("counter.testnet");
    ///     
    ///     // View call - type-safe!
    ///     let count = counter.get_count().await?;
    ///     
    ///     // Change call - type-safe!
    ///     counter.increment().await?;
    ///     counter.add(AddArgs { value: 5 }).await?;
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub fn contract<T: crate::Contract + ?Sized>(
        &self,
        contract_id: impl AsRef<str>,
    ) -> T::Client<'_> {
        let contract_id = AccountId::parse_lenient(contract_id);
        T::Client::new(self, contract_id)
    }

    // ========================================================================
    // Token Helpers
    // ========================================================================

    /// Get a fungible token client for a NEP-141 contract.
    ///
    /// Accepts either a string/`AccountId` for raw addresses, or a [`KnownToken`]
    /// constant (like [`tokens::USDC`]) which auto-resolves based on the network.
    ///
    /// [`KnownToken`]: crate::tokens::KnownToken
    /// [`tokens::USDC`]: crate::tokens::USDC
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example() -> Result<(), near_kit::Error> {
    /// let near = Near::mainnet().build();
    ///
    /// // Use a known token - auto-resolves based on network
    /// let usdc = near.ft(tokens::USDC)?;
    ///
    /// // Or use a raw address
    /// let custom = near.ft("custom-token.near")?;
    ///
    /// // Get metadata
    /// let meta = usdc.metadata().await?;
    /// println!("{} ({})", meta.name, meta.symbol);
    ///
    /// // Get balance - returns FtAmount for nice formatting
    /// let balance = usdc.balance_of("alice.near").await?;
    /// println!("Balance: {}", balance);  // e.g., "1.5 USDC"
    /// # Ok(())
    /// # }
    /// ```
    pub fn ft(
        &self,
        contract: impl crate::tokens::IntoContractId,
    ) -> Result<crate::tokens::FungibleToken, Error> {
        let contract_id = contract.into_contract_id(self.network)?;
        Ok(crate::tokens::FungibleToken::new(
            self.rpc.clone(),
            self.signer.clone(),
            contract_id,
            self.max_nonce_retries,
        ))
    }

    /// Get a non-fungible token client for a NEP-171 contract.
    ///
    /// Accepts either a string/`AccountId` for raw addresses, or a contract
    /// identifier that implements [`IntoContractId`].
    ///
    /// [`IntoContractId`]: crate::tokens::IntoContractId
    ///
    /// # 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 a specific token
    /// if let Some(token) = nft.token("token-123").await? {
    ///     println!("Owner: {}", token.owner_id);
    /// }
    ///
    /// // List tokens for an owner
    /// let tokens = nft.tokens_for_owner("alice.near", None, Some(10)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn nft(
        &self,
        contract: impl crate::tokens::IntoContractId,
    ) -> Result<crate::tokens::NonFungibleToken, Error> {
        let contract_id = contract.into_contract_id(self.network)?;
        Ok(crate::tokens::NonFungibleToken::new(
            self.rpc.clone(),
            self.signer.clone(),
            contract_id,
            self.max_nonce_retries,
        ))
    }
}

impl std::fmt::Debug for Near {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Near")
            .field("rpc", &self.rpc)
            .field("account_id", &self.account_id())
            .finish()
    }
}

/// Builder for creating a [`Near`] client.
///
/// # Example
///
/// ```rust,ignore
/// use near_kit::*;
///
/// // Read-only client
/// let near = Near::testnet().build();
///
/// // Client with credentials (secret key + account)
/// let near = Near::testnet()
///     .credentials("ed25519:...", "alice.testnet")?
///     .build();
///
/// // Client with keystore
/// let keystore = std::sync::Arc::new(InMemoryKeyStore::new());
/// // ... add keys to keystore ...
/// let near = Near::testnet()
///     .keystore(keystore, "alice.testnet")?
///     .build();
/// ```
pub struct NearBuilder {
    rpc_url: String,
    signer: Option<Arc<dyn Signer>>,
    retry_config: RetryConfig,
    network: Network,
    max_nonce_retries: u32,
}

impl NearBuilder {
    /// Create a new builder with the given RPC URL.
    fn new(rpc_url: impl Into<String>, network: Network) -> Self {
        Self {
            rpc_url: rpc_url.into(),
            signer: None,
            retry_config: RetryConfig::default(),
            network,
            max_nonce_retries: 3,
        }
    }

    /// Set the signer for transactions.
    ///
    /// The signer determines which account will sign transactions.
    pub fn signer(mut self, signer: impl Signer + 'static) -> Self {
        self.signer = Some(Arc::new(signer));
        self
    }

    /// Set up signing using a private key string and account ID.
    ///
    /// This is a convenience method that creates an `InMemorySigner` for you.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use near_kit::Near;
    ///
    /// let near = Near::testnet()
    ///     .credentials("ed25519:...", "alice.testnet")?
    ///     .build();
    /// ```
    pub fn credentials(
        mut self,
        private_key: impl AsRef<str>,
        account_id: impl AsRef<str>,
    ) -> Result<Self, Error> {
        let signer = InMemorySigner::new(account_id, private_key)?;
        self.signer = Some(Arc::new(signer));
        Ok(self)
    }

    /// Set the retry configuration.
    pub fn retry_config(mut self, config: RetryConfig) -> Self {
        self.retry_config = config;
        self
    }

    /// Set the maximum number of transaction send attempts on `InvalidNonce` errors.
    ///
    /// When a transaction fails with `InvalidNonce`, the client automatically
    /// retries with the corrected nonce from the error response. This controls
    /// the total number of send attempts (including the initial one) before
    /// giving up. A value of `1` means no retries (only the initial attempt).
    ///
    /// Defaults to `3`. For high-contention relayer scenarios, consider setting
    /// this higher (e.g., `u32::MAX`) and wrapping sends in `tokio::timeout`.
    ///
    /// # Panics
    ///
    /// Panics if `attempts` is `0`.
    pub fn max_nonce_retries(mut self, attempts: u32) -> Self {
        assert!(attempts > 0, "max_nonce_retries must be at least 1");
        self.max_nonce_retries = attempts;
        self
    }

    /// Build the client.
    pub fn build(self) -> Near {
        Near {
            rpc: Arc::new(RpcClient::with_retry_config(
                self.rpc_url,
                self.retry_config,
            )),
            signer: self.signer,
            network: self.network,
            max_nonce_retries: self.max_nonce_retries,
        }
    }
}

impl From<NearBuilder> for Near {
    fn from(builder: NearBuilder) -> Self {
        builder.build()
    }
}

// ============================================================================
// near-sandbox integration (behind feature flag or for dev dependencies)
// ============================================================================

/// Default sandbox root account ID.
pub const SANDBOX_ROOT_ACCOUNT: &str = "sandbox";

/// Default sandbox root account private key.
pub const SANDBOX_ROOT_PRIVATE_KEY: &str = "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB";

#[cfg(feature = "sandbox")]
impl SandboxNetwork for near_sandbox::Sandbox {
    fn rpc_url(&self) -> &str {
        &self.rpc_addr
    }

    fn root_account_id(&self) -> &str {
        SANDBOX_ROOT_ACCOUNT
    }

    fn root_secret_key(&self) -> &str {
        SANDBOX_ROOT_PRIVATE_KEY
    }
}

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

    // ========================================================================
    // Near client tests
    // ========================================================================

    #[test]
    fn test_near_mainnet_builder() {
        let near = Near::mainnet().build();
        assert!(near.rpc_url().contains("fastnear") || near.rpc_url().contains("near"));
        assert!(near.account_id().is_none()); // No signer configured
    }

    #[test]
    fn test_near_testnet_builder() {
        let near = Near::testnet().build();
        assert!(near.rpc_url().contains("fastnear") || near.rpc_url().contains("test"));
        assert!(near.account_id().is_none());
    }

    #[test]
    fn test_near_custom_builder() {
        let near = Near::custom("https://custom-rpc.example.com").build();
        assert_eq!(near.rpc_url(), "https://custom-rpc.example.com");
    }

    #[test]
    fn test_near_with_credentials() {
        let near = Near::testnet()
            .credentials(
                "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
                "alice.testnet",
            )
            .unwrap()
            .build();

        assert!(near.account_id().is_some());
        assert_eq!(near.account_id().unwrap().as_str(), "alice.testnet");
    }

    #[test]
    fn test_near_with_signer() {
        let signer = InMemorySigner::new(
            "bob.testnet",
            "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
        ).unwrap();

        let near = Near::testnet().signer(signer).build();

        assert!(near.account_id().is_some());
        assert_eq!(near.account_id().unwrap().as_str(), "bob.testnet");
    }

    #[test]
    fn test_near_debug() {
        let near = Near::testnet().build();
        let debug = format!("{:?}", near);
        assert!(debug.contains("Near"));
        assert!(debug.contains("rpc"));
    }

    #[test]
    fn test_near_rpc_accessor() {
        let near = Near::testnet().build();
        let rpc = near.rpc();
        assert!(!rpc.url().is_empty());
    }

    // ========================================================================
    // NearBuilder tests
    // ========================================================================

    #[test]
    fn test_near_builder_new() {
        let builder = NearBuilder::new("https://example.com", Network::Custom);
        let near = builder.build();
        assert_eq!(near.rpc_url(), "https://example.com");
    }

    #[test]
    fn test_near_builder_retry_config() {
        let config = RetryConfig {
            max_retries: 10,
            initial_delay_ms: 200,
            max_delay_ms: 10000,
        };
        let near = Near::testnet().retry_config(config).build();
        // Can't directly test retry config, but we can verify it builds
        assert!(!near.rpc_url().is_empty());
    }

    #[test]
    fn test_near_builder_from_trait() {
        let builder = Near::testnet();
        let near: Near = builder.into();
        assert!(!near.rpc_url().is_empty());
    }

    #[test]
    fn test_near_builder_credentials_invalid_key() {
        let result = Near::testnet().credentials("invalid-key", "alice.testnet");
        assert!(result.is_err());
    }

    #[test]
    fn test_near_builder_credentials_invalid_account() {
        // Empty account ID is invalid
        let result = Near::testnet().credentials(
            "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
            "",
        );
        assert!(result.is_err());
    }

    // ========================================================================
    // SandboxNetwork trait tests
    // ========================================================================

    struct MockSandbox {
        rpc_url: String,
        root_account: String,
        root_key: String,
    }

    impl SandboxNetwork for MockSandbox {
        fn rpc_url(&self) -> &str {
            &self.rpc_url
        }

        fn root_account_id(&self) -> &str {
            &self.root_account
        }

        fn root_secret_key(&self) -> &str {
            &self.root_key
        }
    }

    #[test]
    fn test_sandbox_network_trait() {
        let mock = MockSandbox {
            rpc_url: "http://127.0.0.1:3030".to_string(),
            root_account: "sandbox".to_string(),
            root_key: SANDBOX_ROOT_PRIVATE_KEY.to_string(),
        };

        let near = Near::sandbox(&mock);
        assert_eq!(near.rpc_url(), "http://127.0.0.1:3030");
        assert!(near.account_id().is_some());
        assert_eq!(near.account_id().unwrap().as_str(), "sandbox");
    }

    // ========================================================================
    // Constant tests
    // ========================================================================

    #[test]
    fn test_sandbox_constants() {
        assert_eq!(SANDBOX_ROOT_ACCOUNT, "sandbox");
        assert!(SANDBOX_ROOT_PRIVATE_KEY.starts_with("ed25519:"));
    }

    // ========================================================================
    // Clone tests
    // ========================================================================

    #[test]
    fn test_near_clone() {
        let near1 = Near::testnet().build();
        let near2 = near1.clone();
        assert_eq!(near1.rpc_url(), near2.rpc_url());
    }

    #[test]
    fn test_near_with_signer_derived() {
        let near = Near::testnet().build();
        assert!(near.account_id().is_none());

        let signer = InMemorySigner::new(
            "alice.testnet",
            "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
        ).unwrap();

        let alice = near.with_signer(signer);
        assert_eq!(alice.account_id().unwrap().as_str(), "alice.testnet");
        assert_eq!(alice.rpc_url(), near.rpc_url()); // Same transport
        assert!(near.account_id().is_none()); // Original unchanged
    }

    #[test]
    fn test_near_with_signer_multiple_accounts() {
        let near = Near::testnet().build();

        let alice = near.with_signer(InMemorySigner::new(
            "alice.testnet",
            "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
        ).unwrap());

        let bob = near.with_signer(InMemorySigner::new(
            "bob.testnet",
            "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
        ).unwrap());

        assert_eq!(alice.account_id().unwrap().as_str(), "alice.testnet");
        assert_eq!(bob.account_id().unwrap().as_str(), "bob.testnet");
        assert_eq!(alice.rpc_url(), bob.rpc_url()); // Shared transport
    }

    // ========================================================================
    // from_env tests
    // ========================================================================

    // NOTE: Environment variable tests are consolidated into a single test
    // because they modify global state and would race with each other if
    // run in parallel. Each scenario is tested sequentially within this test.
    #[test]
    fn test_from_env_scenarios() {
        // Helper to clean up env vars
        fn clear_env() {
            // SAFETY: This is a test and we control the execution
            unsafe {
                std::env::remove_var("NEAR_NETWORK");
                std::env::remove_var("NEAR_ACCOUNT_ID");
                std::env::remove_var("NEAR_PRIVATE_KEY");
            }
        }

        // Scenario 1: No vars - defaults to testnet, read-only
        clear_env();
        {
            let near = Near::from_env().unwrap();
            assert!(
                near.rpc_url().contains("test") || near.rpc_url().contains("fastnear"),
                "Expected testnet URL, got: {}",
                near.rpc_url()
            );
            assert!(near.account_id().is_none());
        }

        // Scenario 2: Mainnet network
        clear_env();
        unsafe {
            std::env::set_var("NEAR_NETWORK", "mainnet");
        }
        {
            let near = Near::from_env().unwrap();
            assert!(
                near.rpc_url().contains("mainnet") || near.rpc_url().contains("fastnear"),
                "Expected mainnet URL, got: {}",
                near.rpc_url()
            );
            assert!(near.account_id().is_none());
        }

        // Scenario 3: Custom URL
        clear_env();
        unsafe {
            std::env::set_var("NEAR_NETWORK", "https://custom-rpc.example.com");
        }
        {
            let near = Near::from_env().unwrap();
            assert_eq!(near.rpc_url(), "https://custom-rpc.example.com");
        }

        // Scenario 4: Full credentials
        clear_env();
        unsafe {
            std::env::set_var("NEAR_NETWORK", "testnet");
            std::env::set_var("NEAR_ACCOUNT_ID", "alice.testnet");
            std::env::set_var(
                "NEAR_PRIVATE_KEY",
                "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
            );
        }
        {
            let near = Near::from_env().unwrap();
            assert!(near.account_id().is_some());
            assert_eq!(near.account_id().unwrap().as_str(), "alice.testnet");
        }

        // Scenario 5: Account without key - should error
        clear_env();
        unsafe {
            std::env::set_var("NEAR_ACCOUNT_ID", "alice.testnet");
        }
        {
            let result = Near::from_env();
            assert!(
                result.is_err(),
                "Expected error when account set without key"
            );
            let err = result.unwrap_err();
            assert!(
                err.to_string().contains("NEAR_PRIVATE_KEY"),
                "Error should mention NEAR_PRIVATE_KEY: {}",
                err
            );
        }

        // Scenario 6: Key without account - should error
        clear_env();
        unsafe {
            std::env::set_var(
                "NEAR_PRIVATE_KEY",
                "ed25519:3tgdk2wPraJzT4nsTuf86UX41xgPNk3MHnq8epARMdBNs29AFEztAuaQ7iHddDfXG9F2RzV1XNQYgJyAyoW51UBB",
            );
        }
        {
            let result = Near::from_env();
            assert!(
                result.is_err(),
                "Expected error when key set without account"
            );
            let err = result.unwrap_err();
            assert!(
                err.to_string().contains("NEAR_ACCOUNT_ID"),
                "Error should mention NEAR_ACCOUNT_ID: {}",
                err
            );
        }

        // Final cleanup
        clear_env();
    }
}