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
//! Signer trait and implementations.
//!
//! A `Signer` knows which account it signs for and provides keys for signing.
//! The `key()` method returns a `SigningKey` that bundles together the public key
//! and signing capability, ensuring atomic key claiming for rotating signers.
//!
//! # Implementations
//!
//! - [`InMemorySigner`] - Single key stored in memory
//! - [`FileSigner`] - Key loaded from ~/.near-credentials
//! - [`EnvSigner`] - Key loaded from environment variables
//! - [`RotatingSigner`] - Multiple keys with round-robin rotation
//!
//! # Example
//!
//! ```rust,no_run
//! use near_kit::{Near, InMemorySigner};
//!
//! # async fn example() -> Result<(), near_kit::Error> {
//! let signer = InMemorySigner::new(
//!     "alice.testnet",
//!     "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr"
//! )?;
//!
//! let near = Near::testnet()
//!     .signer(signer)
//!     .build();
//!
//! near.transfer("bob.testnet", "1 NEAR").await?;
//! # Ok(())
//! # }
//! ```

use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use crate::error::SignerError;
use crate::types::nep413::{self, SignMessageParams, SignedMessage};
use crate::types::{AccountId, PublicKey, SecretKey, Signature};

// ============================================================================
// Signer Trait
// ============================================================================

/// Trait for signing transactions.
///
/// A signer knows which account it signs for and provides keys for signing.
/// The `key()` method returns a [`SigningKey`] that bundles together the public
/// key and signing capability, ensuring atomic key claiming.
///
/// # Example Implementation
///
/// ```rust,ignore
/// use near_kit::{Signer, SigningKey, AccountId, SecretKey};
///
/// struct MyCustomSigner {
///     account_id: AccountId,
///     secret_key: SecretKey,
/// }
///
/// impl Signer for MyCustomSigner {
///     fn account_id(&self) -> &AccountId {
///         &self.account_id
///     }
///
///     fn key(&self) -> SigningKey {
///         SigningKey::new(self.secret_key.clone())
///     }
/// }
/// ```
pub trait Signer: Send + Sync {
    /// The account this signer signs for.
    fn account_id(&self) -> &AccountId;

    /// Get a key for signing.
    ///
    /// Returns a [`SigningKey`] that contains both the public key and the
    /// capability to sign with the corresponding private key.
    ///
    /// For single-key signers, this always returns the same key.
    /// For rotating signers, this atomically claims the next key in rotation.
    fn key(&self) -> SigningKey;
}

/// Implement `Signer` for `Arc<dyn Signer>` for convenience.
impl Signer for Arc<dyn Signer> {
    fn account_id(&self) -> &AccountId {
        (**self).account_id()
    }

    fn key(&self) -> SigningKey {
        (**self).key()
    }
}

// ============================================================================
// SigningKey
// ============================================================================

/// A key that can sign messages.
///
/// This bundles together a public key and the ability to sign with the
/// corresponding private key. For in-memory keys, signing is instant.
/// For hardware wallets or KMS, signing may involve async operations.
///
/// # Example
///
/// ```rust
/// use near_kit::{InMemorySigner, Signer};
///
/// # async fn example() -> Result<(), near_kit::Error> {
/// let signer = InMemorySigner::new("alice.testnet", "ed25519:...")?;
///
/// let key = signer.key();
/// println!("Public key: {}", key.public_key());
///
/// let signature = key.sign(b"message").await?;
/// # Ok(())
/// # }
/// ```
pub struct SigningKey {
    /// The public key.
    public_key: PublicKey,
    /// The signing backend.
    backend: Arc<dyn SigningBackend>,
}

impl SigningKey {
    /// Create a new signing key from a secret key.
    pub fn new(secret_key: SecretKey) -> Self {
        let public_key = secret_key.public_key();
        Self {
            public_key,
            backend: Arc::new(SecretKeyBackend { secret_key }),
        }
    }

    /// Get the public key.
    pub fn public_key(&self) -> &PublicKey {
        &self.public_key
    }

    /// Sign a message.
    ///
    /// For in-memory keys, this returns immediately.
    /// For hardware wallets or KMS, this may involve user confirmation or
    /// network requests.
    pub async fn sign(&self, message: &[u8]) -> Result<Signature, SignerError> {
        self.backend.sign(message).await
    }

    /// Sign a NEP-413 message for off-chain authentication.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use near_kit::{InMemorySigner, Signer, nep413};
    ///
    /// let signer = InMemorySigner::new("alice.testnet", "ed25519:...")?;
    /// let key = signer.key();
    ///
    /// let params = nep413::SignMessageParams {
    ///     message: "Login to MyApp".to_string(),
    ///     recipient: "myapp.com".to_string(),
    ///     nonce: nep413::generate_nonce(),
    ///     callback_url: None,
    ///     state: None,
    /// };
    ///
    /// let signed = key.sign_nep413(&signer.account_id(), &params).await?;
    /// ```
    pub async fn sign_nep413(
        &self,
        account_id: &AccountId,
        params: &SignMessageParams,
    ) -> Result<SignedMessage, SignerError> {
        let hash = nep413::serialize_message(params);
        let signature = self.sign(hash.as_bytes()).await?;

        Ok(SignedMessage {
            account_id: account_id.clone(),
            public_key: self.public_key.clone(),
            signature,
            state: params.state.clone(),
        })
    }
}

impl Clone for SigningKey {
    fn clone(&self) -> Self {
        Self {
            public_key: self.public_key.clone(),
            backend: self.backend.clone(),
        }
    }
}

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

// ============================================================================
// SigningBackend (internal)
// ============================================================================

/// Internal trait for signing backends.
///
/// This allows different implementations (in-memory, hardware wallet, KMS)
/// to provide signing capability.
trait SigningBackend: Send + Sync {
    fn sign(
        &self,
        message: &[u8],
    ) -> Pin<Box<dyn Future<Output = Result<Signature, SignerError>> + Send + '_>>;
}

/// In-memory signing backend using a secret key.
struct SecretKeyBackend {
    secret_key: SecretKey,
}

impl SigningBackend for SecretKeyBackend {
    fn sign(
        &self,
        message: &[u8],
    ) -> Pin<Box<dyn Future<Output = Result<Signature, SignerError>> + Send + '_>> {
        let sig = self.secret_key.sign(message);
        Box::pin(async move { Ok(sig) })
    }
}

// ============================================================================
// InMemorySigner
// ============================================================================

/// A signer with a single key stored in memory.
///
/// This is the simplest signer implementation, suitable for scripts,
/// bots, and testing.
///
/// # Example
///
/// ```rust
/// use near_kit::InMemorySigner;
///
/// let signer = InMemorySigner::new(
///     "alice.testnet",
///     "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr"
/// ).unwrap();
/// ```
#[derive(Clone)]
pub struct InMemorySigner {
    account_id: AccountId,
    secret_key: SecretKey,
    public_key: PublicKey,
}

impl InMemorySigner {
    /// Create a new signer with an account ID and secret key.
    ///
    /// # Arguments
    ///
    /// * `account_id` - The NEAR account ID (e.g., "alice.testnet")
    /// * `secret_key` - The secret key in string format (e.g., "ed25519:...")
    ///
    /// # Errors
    ///
    /// Returns an error if the account ID or secret key cannot be parsed.
    pub fn new(
        account_id: impl AsRef<str>,
        secret_key: impl AsRef<str>,
    ) -> Result<Self, crate::error::Error> {
        let account_id: AccountId = account_id.as_ref().parse()?;
        let secret_key: SecretKey = secret_key.as_ref().parse()?;
        let public_key = secret_key.public_key();

        Ok(Self {
            account_id,
            secret_key,
            public_key,
        })
    }

    /// Create a signer from a SecretKey directly.
    pub fn from_secret_key(account_id: AccountId, secret_key: SecretKey) -> Self {
        let public_key = secret_key.public_key();
        Self {
            account_id,
            secret_key,
            public_key,
        }
    }

    /// Create a signer from a BIP-39 seed phrase.
    ///
    /// Uses SLIP-10 derivation with the default NEAR HD path (`m/44'/397'/0'`).
    ///
    /// # Arguments
    ///
    /// * `account_id` - The NEAR account ID (e.g., "alice.testnet")
    /// * `phrase` - BIP-39 mnemonic phrase (12, 15, 18, 21, or 24 words)
    ///
    /// # Example
    ///
    /// ```rust
    /// use near_kit::InMemorySigner;
    ///
    /// let signer = InMemorySigner::from_seed_phrase(
    ///     "alice.testnet",
    ///     "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
    /// ).unwrap();
    /// ```
    pub fn from_seed_phrase(
        account_id: impl AsRef<str>,
        phrase: impl AsRef<str>,
    ) -> Result<Self, crate::error::Error> {
        let account_id: AccountId = account_id.as_ref().parse()?;
        let secret_key = SecretKey::from_seed_phrase(phrase)?;
        Ok(Self::from_secret_key(account_id, secret_key))
    }

    /// Create a signer from a BIP-39 seed phrase with custom HD path.
    ///
    /// # Arguments
    ///
    /// * `account_id` - The NEAR account ID
    /// * `phrase` - BIP-39 mnemonic phrase
    /// * `hd_path` - BIP-32 derivation path (e.g., `"m/44'/397'/0'"`)
    ///
    /// # Example
    ///
    /// ```rust
    /// use near_kit::InMemorySigner;
    ///
    /// let signer = InMemorySigner::from_seed_phrase_with_path(
    ///     "alice.testnet",
    ///     "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
    ///     "m/44'/397'/1'"
    /// ).unwrap();
    /// ```
    pub fn from_seed_phrase_with_path(
        account_id: impl AsRef<str>,
        phrase: impl AsRef<str>,
        hd_path: impl AsRef<str>,
    ) -> Result<Self, crate::error::Error> {
        let account_id: AccountId = account_id.as_ref().parse()?;
        let secret_key = SecretKey::from_seed_phrase_with_path(phrase, hd_path)?;
        Ok(Self::from_secret_key(account_id, secret_key))
    }

    /// Get the public key.
    pub fn public_key(&self) -> &PublicKey {
        &self.public_key
    }
}

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

impl Signer for InMemorySigner {
    fn account_id(&self) -> &AccountId {
        &self.account_id
    }

    fn key(&self) -> SigningKey {
        SigningKey::new(self.secret_key.clone())
    }
}

// ============================================================================
// FileSigner
// ============================================================================

/// A signer that loads its key from `~/.near-credentials/{network}/{account}.json`.
///
/// Compatible with credentials created by near-cli and near-cli-rs.
///
/// # Example
///
/// ```rust,no_run
/// use near_kit::FileSigner;
///
/// // Load from ~/.near-credentials/testnet/alice.testnet.json
/// let signer = FileSigner::new("testnet", "alice.testnet").unwrap();
/// ```
#[derive(Clone)]
pub struct FileSigner {
    inner: InMemorySigner,
}

/// Credential file format compatible with near-cli.
#[derive(serde::Deserialize)]
struct CredentialFile {
    #[serde(alias = "secret_key")]
    private_key: String,
}

impl FileSigner {
    /// Load credentials for an account from the standard NEAR credentials directory.
    ///
    /// Looks for the file at `~/.near-credentials/{network}/{account_id}.json`.
    ///
    /// # Arguments
    ///
    /// * `network` - Network name (e.g., "testnet", "mainnet")
    /// * `account_id` - The NEAR account ID
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The home directory cannot be determined
    /// - The credentials file doesn't exist
    /// - The file cannot be parsed
    pub fn new(
        network: impl AsRef<str>,
        account_id: impl AsRef<str>,
    ) -> Result<Self, crate::error::Error> {
        let home = dirs::home_dir().ok_or_else(|| {
            crate::error::Error::Config("Could not determine home directory".to_string())
        })?;
        let path = home
            .join(".near-credentials")
            .join(network.as_ref())
            .join(format!("{}.json", account_id.as_ref()));

        Self::from_file(&path, account_id)
    }

    /// Load credentials from a specific file path.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the credentials JSON file
    /// * `account_id` - The NEAR account ID
    pub fn from_file(
        path: impl AsRef<Path>,
        account_id: impl AsRef<str>,
    ) -> Result<Self, crate::error::Error> {
        let content = std::fs::read_to_string(path.as_ref()).map_err(|e| {
            crate::error::Error::Config(format!(
                "Failed to read credentials file {}: {}",
                path.as_ref().display(),
                e
            ))
        })?;

        let cred: CredentialFile = serde_json::from_str(&content).map_err(|e| {
            crate::error::Error::Config(format!(
                "Failed to parse credentials file {}: {}",
                path.as_ref().display(),
                e
            ))
        })?;

        let inner = InMemorySigner::new(account_id, &cred.private_key)?;
        Ok(Self { inner })
    }

    /// Get the public key.
    pub fn public_key(&self) -> &PublicKey {
        self.inner.public_key()
    }

    /// Unwrap into the underlying [`InMemorySigner`].
    pub fn into_inner(self) -> InMemorySigner {
        self.inner
    }
}

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

impl Signer for FileSigner {
    fn account_id(&self) -> &AccountId {
        self.inner.account_id()
    }

    fn key(&self) -> SigningKey {
        self.inner.key()
    }
}

// ============================================================================
// EnvSigner
// ============================================================================

/// A signer that loads credentials from environment variables.
///
/// By default, reads from:
/// - `NEAR_ACCOUNT_ID` - The account ID
/// - `NEAR_PRIVATE_KEY` - The private key
///
/// # Example
///
/// ```rust,no_run
/// use near_kit::EnvSigner;
///
/// // With NEAR_ACCOUNT_ID and NEAR_PRIVATE_KEY set:
/// let signer = EnvSigner::new().unwrap();
/// ```
#[derive(Clone)]
pub struct EnvSigner {
    inner: InMemorySigner,
}

impl EnvSigner {
    /// Load from `NEAR_ACCOUNT_ID` and `NEAR_PRIVATE_KEY` environment variables.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Either environment variable is not set
    /// - The values cannot be parsed
    pub fn new() -> Result<Self, crate::error::Error> {
        Self::from_env_vars("NEAR_ACCOUNT_ID", "NEAR_PRIVATE_KEY")
    }

    /// Load from custom environment variable names.
    ///
    /// # Arguments
    ///
    /// * `account_var` - Name of the environment variable containing the account ID
    /// * `key_var` - Name of the environment variable containing the private key
    pub fn from_env_vars(account_var: &str, key_var: &str) -> Result<Self, crate::error::Error> {
        let account_id = std::env::var(account_var).map_err(|_| {
            crate::error::Error::Config(format!("Environment variable {} not set", account_var))
        })?;

        let private_key = std::env::var(key_var).map_err(|_| {
            crate::error::Error::Config(format!("Environment variable {} not set", key_var))
        })?;

        let inner = InMemorySigner::new(&account_id, &private_key)?;
        Ok(Self { inner })
    }

    /// Get the public key.
    pub fn public_key(&self) -> &PublicKey {
        self.inner.public_key()
    }

    /// Unwrap into the underlying [`InMemorySigner`].
    pub fn into_inner(self) -> InMemorySigner {
        self.inner
    }
}

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

impl Signer for EnvSigner {
    fn account_id(&self) -> &AccountId {
        self.inner.account_id()
    }

    fn key(&self) -> SigningKey {
        self.inner.key()
    }
}

// ============================================================================
// RotatingSigner
// ============================================================================

/// A signer that rotates through multiple keys for the same account.
///
/// This solves the nonce collision problem for high-throughput applications.
/// Each call to `key()` atomically claims the next key in round-robin order.
///
/// # Use Case
///
/// NEAR uses per-key nonces. When sending concurrent transactions with a single key,
/// they can collide on nonce values. By rotating through multiple keys, each
/// concurrent transaction uses a different key with its own nonce sequence.
///
/// # Loading Keys from Other Sources
///
/// Keys can be loaded from any storage backend (file, keyring, env) via
/// [`from_signers()`](Self::from_signers):
///
/// ```rust,no_run
/// # use near_kit::*;
/// let rotating = RotatingSigner::from_signers(vec![
///     FileSigner::from_file("keys/bot-key-0.json", "bot.testnet")?.into_inner(),
///     FileSigner::from_file("keys/bot-key-1.json", "bot.testnet")?.into_inner(),
/// ])?;
/// # Ok::<(), near_kit::Error>(())
/// ```
///
/// # Sequential Sends
///
/// Use [`into_per_key_signers()`](Self::into_per_key_signers) to split into
/// per-key [`InMemorySigner`] instances for building sequential send queues.
/// See the `sequential_sends` example.
///
/// # Example
///
/// ```rust
/// use near_kit::{RotatingSigner, SecretKey, Signer};
///
/// let keys = vec![
///     SecretKey::generate_ed25519(),
///     SecretKey::generate_ed25519(),
///     SecretKey::generate_ed25519(),
/// ];
///
/// let signer = RotatingSigner::new("bot.testnet", keys).unwrap();
///
/// // Each key() call atomically claims the next key in sequence
/// let key1 = signer.key();
/// let key2 = signer.key();
/// let key3 = signer.key();
/// // key4 wraps back to the first key
/// let key4 = signer.key();
/// ```
pub struct RotatingSigner {
    account_id: AccountId,
    keys: Vec<SecretKey>,
    counter: AtomicUsize,
}

impl RotatingSigner {
    /// Create a rotating signer with multiple keys.
    ///
    /// # Arguments
    ///
    /// * `account_id` - The NEAR account ID
    /// * `keys` - Vector of secret keys (must not be empty)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The account ID cannot be parsed
    /// - The keys vector is empty
    pub fn new(
        account_id: impl AsRef<str>,
        keys: Vec<SecretKey>,
    ) -> Result<Self, crate::error::Error> {
        if keys.is_empty() {
            return Err(crate::error::Error::Config(
                "RotatingSigner requires at least one key".to_string(),
            ));
        }

        let account_id: AccountId = account_id.as_ref().parse()?;

        Ok(Self {
            account_id,
            keys,
            counter: AtomicUsize::new(0),
        })
    }

    /// Create a rotating signer from [`InMemorySigner`] instances.
    ///
    /// This accepts signers loaded from any source (keyring, file, env, etc.)
    /// via their `into_inner()` method. All signers must share the same account ID.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use near_kit::{RotatingSigner, FileSigner};
    ///
    /// // Load keys from separate credential files for the same account
    /// let signers = vec![
    ///     FileSigner::from_file("keys/bot-key-0.json", "bot.testnet")?.into_inner(),
    ///     FileSigner::from_file("keys/bot-key-1.json", "bot.testnet")?.into_inner(),
    /// ];
    /// let rotating = RotatingSigner::from_signers(signers)?;
    /// # Ok::<(), near_kit::Error>(())
    /// ```
    pub fn from_signers(signers: Vec<InMemorySigner>) -> Result<Self, crate::error::Error> {
        if signers.is_empty() {
            return Err(crate::error::Error::Config(
                "RotatingSigner requires at least one signer".to_string(),
            ));
        }

        let account_id = signers[0].account_id().clone();
        for signer in &signers[1..] {
            if signer.account_id() != &account_id {
                return Err(crate::error::Error::Config(format!(
                    "All signers must share the same account ID, got {} and {}",
                    account_id,
                    signer.account_id()
                )));
            }
        }

        let keys = signers.into_iter().map(|s| s.secret_key).collect();
        Ok(Self {
            account_id,
            keys,
            counter: AtomicUsize::new(0),
        })
    }

    /// Create a rotating signer from key strings.
    ///
    /// # Arguments
    ///
    /// * `account_id` - The NEAR account ID
    /// * `keys` - Slice of secret keys in string format (e.g., "ed25519:...")
    pub fn from_key_strings(
        account_id: impl AsRef<str>,
        keys: &[impl AsRef<str>],
    ) -> Result<Self, crate::error::Error> {
        let parsed_keys: Result<Vec<SecretKey>, _> =
            keys.iter().map(|k| k.as_ref().parse()).collect();
        Self::new(account_id, parsed_keys?)
    }

    /// Get the number of keys in rotation.
    pub fn key_count(&self) -> usize {
        self.keys.len()
    }

    /// Get all public keys.
    pub fn public_keys(&self) -> Vec<PublicKey> {
        self.keys.iter().map(|sk| sk.public_key()).collect()
    }

    /// Get all signing keys without advancing the rotation counter.
    ///
    /// Useful for building per-key data structures like sequential send queues.
    /// Unlike [`key()`](Signer::key), calling this does not affect the rotation.
    pub fn signing_keys(&self) -> Vec<SigningKey> {
        self.keys
            .iter()
            .map(|sk| SigningKey::new(sk.clone()))
            .collect()
    }

    /// Split into per-key [`InMemorySigner`] instances.
    ///
    /// Each signer uses a single key from the rotation pool, allowing
    /// independent send ordering per key. The global nonce manager
    /// automatically tracks nonces per `(account_id, public_key)`,
    /// so per-key signers coordinate correctly without extra setup.
    ///
    /// # Example
    ///
    /// ```rust
    /// use near_kit::{RotatingSigner, SecretKey};
    ///
    /// let keys = vec![SecretKey::generate_ed25519(), SecretKey::generate_ed25519()];
    /// let rotating = RotatingSigner::new("bot.testnet", keys).unwrap();
    ///
    /// // Create per-key signers for sequential queue workers
    /// let per_key: Vec<_> = rotating.into_per_key_signers();
    /// assert_eq!(per_key.len(), 2);
    /// ```
    pub fn into_per_key_signers(self) -> Vec<InMemorySigner> {
        let account_id = self.account_id;
        self.keys
            .into_iter()
            .map(|sk| InMemorySigner::from_secret_key(account_id.clone(), sk))
            .collect()
    }
}

impl std::fmt::Debug for RotatingSigner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RotatingSigner")
            .field("account_id", &self.account_id)
            .field("key_count", &self.keys.len())
            .field("counter", &self.counter.load(Ordering::Relaxed))
            .finish()
    }
}

impl Signer for RotatingSigner {
    fn account_id(&self) -> &AccountId {
        &self.account_id
    }

    fn key(&self) -> SigningKey {
        // Atomically claim the next key in rotation
        let idx = self.counter.fetch_add(1, Ordering::Relaxed) % self.keys.len();
        SigningKey::new(self.keys[idx].clone())
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Action, CryptoHash, NearToken, Transaction};

    #[tokio::test]
    async fn test_in_memory_signer() {
        let signer = InMemorySigner::new(
            "alice.testnet",
            "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr",
        )
        .unwrap();

        assert_eq!(signer.account_id().as_str(), "alice.testnet");

        let key = signer.key();
        let message = b"test message";
        let signature = key.sign(message).await.unwrap();

        // Verify the key matches
        assert_eq!(key.public_key(), signer.public_key());
        assert!(!signature.as_bytes().is_empty());
    }

    #[tokio::test]
    async fn test_signature_consistency() {
        // Same message should produce the same signature (Ed25519 is deterministic)
        let signer = InMemorySigner::new(
            "alice.testnet",
            "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr",
        )
        .unwrap();

        let key = signer.key();
        let message = b"test message";
        let sig1 = key.sign(message).await.unwrap();
        let sig2 = key.sign(message).await.unwrap();

        assert_eq!(sig1.as_bytes(), sig2.as_bytes());
    }

    #[tokio::test]
    async fn test_different_messages_different_signatures() {
        let signer = InMemorySigner::new(
            "alice.testnet",
            "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr",
        )
        .unwrap();

        let key = signer.key();
        let sig1 = key.sign(b"message 1").await.unwrap();
        let sig2 = key.sign(b"message 2").await.unwrap();

        assert_ne!(sig1.as_bytes(), sig2.as_bytes());
    }

    #[tokio::test]
    async fn test_transaction_signing_with_signer_trait() {
        let secret_key = SecretKey::generate_ed25519();
        let signer = InMemorySigner::from_secret_key("alice.testnet".parse().unwrap(), secret_key);

        // Get a key for signing
        let key = signer.key();

        // Build a transaction
        let tx = Transaction::new(
            signer.account_id().clone(),
            key.public_key().clone(),
            1,
            "bob.testnet".parse().unwrap(),
            CryptoHash::ZERO,
            vec![Action::transfer(NearToken::from_near(1))],
        );

        // Sign using the key
        let tx_hash = tx.get_hash();
        let signature = key.sign(tx_hash.as_bytes()).await.unwrap();

        // Verify signature is 64 bytes (Ed25519)
        assert_eq!(signature.as_bytes().len(), 64);

        // Create signed transaction
        let signed_tx = crate::types::SignedTransaction {
            transaction: tx,
            signature,
        };

        // Verify serialization works
        let bytes = signed_tx.to_bytes();
        assert!(!bytes.is_empty());

        // Verify base64 encoding works
        let base64 = signed_tx.to_base64();
        assert!(!base64.is_empty());
    }

    #[tokio::test]
    async fn test_rotating_signer() {
        let keys = vec![
            SecretKey::generate_ed25519(),
            SecretKey::generate_ed25519(),
            SecretKey::generate_ed25519(),
        ];
        let expected_public_keys: Vec<_> = keys.iter().map(|k| k.public_key()).collect();

        let signer = RotatingSigner::new("bot.testnet", keys).unwrap();

        // Verify round-robin rotation
        let key1 = signer.key();
        assert_eq!(key1.public_key(), &expected_public_keys[0]);

        let key2 = signer.key();
        assert_eq!(key2.public_key(), &expected_public_keys[1]);

        let key3 = signer.key();
        assert_eq!(key3.public_key(), &expected_public_keys[2]);

        // Wraps around
        let key4 = signer.key();
        assert_eq!(key4.public_key(), &expected_public_keys[0]);
    }

    #[tokio::test]
    async fn test_rotating_signer_atomic_key_claiming() {
        // Verify that key() atomically claims a key that can be used for signing
        let keys = vec![SecretKey::generate_ed25519(), SecretKey::generate_ed25519()];
        let expected_pks: Vec<_> = keys.iter().map(|k| k.public_key()).collect();

        let signer = RotatingSigner::new("bot.testnet", keys.clone()).unwrap();
        let message = b"test";

        // Claim first key and sign
        let key1 = signer.key();
        assert_eq!(key1.public_key(), &expected_pks[0]);
        let sig1 = key1.sign(message).await.unwrap();
        // Verify signature matches what the raw key would produce
        let expected_sig1 = keys[0].sign(message);
        assert_eq!(sig1.as_bytes(), expected_sig1.as_bytes());

        // Claim second key and sign
        let key2 = signer.key();
        assert_eq!(key2.public_key(), &expected_pks[1]);
        let sig2 = key2.sign(message).await.unwrap();
        let expected_sig2 = keys[1].sign(message);
        assert_eq!(sig2.as_bytes(), expected_sig2.as_bytes());

        // Different keys produce different signatures
        assert_ne!(sig1.as_bytes(), sig2.as_bytes());
    }

    #[test]
    fn test_rotating_signer_empty_keys() {
        let result = RotatingSigner::new("bot.testnet", vec![]);
        assert!(result.is_err());
    }

    #[test]
    fn test_env_signer_missing_vars() {
        // This should fail because the env vars aren't set
        let result = EnvSigner::from_env_vars("NONEXISTENT_VAR_1", "NONEXISTENT_VAR_2");
        assert!(result.is_err());
    }

    #[test]
    fn test_signer_from_secret_key() {
        let secret = SecretKey::generate_ed25519();
        let expected_pk = secret.public_key();

        let signer = InMemorySigner::from_secret_key("alice.testnet".parse().unwrap(), secret);

        assert_eq!(signer.account_id().as_str(), "alice.testnet");
        assert_eq!(signer.public_key(), &expected_pk);
    }

    #[test]
    fn test_rotating_signer_key_count() {
        let keys = vec![
            SecretKey::generate_ed25519(),
            SecretKey::generate_ed25519(),
            SecretKey::generate_ed25519(),
        ];

        let signer = RotatingSigner::new("bot.testnet", keys).unwrap();

        assert_eq!(signer.key_count(), 3);
        assert_eq!(signer.public_keys().len(), 3);
    }

    #[test]
    fn test_rotating_signer_from_key_strings() {
        let keys = [
            "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr",
            "ed25519:4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi5kL6YJt9Z6iLqMBkVfqDH2Zj8bxqXTdMkNmvPcAD8LqCZ",
        ];

        let signer = RotatingSigner::from_key_strings("bot.testnet", &keys).unwrap();

        assert_eq!(signer.key_count(), 2);
        assert_eq!(signer.account_id().as_str(), "bot.testnet");
    }

    #[test]
    fn test_in_memory_signer_debug_hides_secret() {
        let signer = InMemorySigner::new(
            "alice.testnet",
            "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr",
        )
        .unwrap();

        let debug_str = format!("{:?}", signer);

        // Should show account_id and public_key but NOT the secret key
        assert!(debug_str.contains("alice.testnet"));
        assert!(debug_str.contains("public_key"));
        assert!(!debug_str.contains("secret_key"));
        assert!(!debug_str.contains("3D4YudUahN1nawWogh"));
    }

    #[test]
    fn test_rotating_signer_from_signers() {
        let keys = vec![SecretKey::generate_ed25519(), SecretKey::generate_ed25519()];
        let expected_public_keys: Vec<_> = keys.iter().map(|k| k.public_key()).collect();

        let signers: Vec<InMemorySigner> = keys
            .into_iter()
            .map(|sk| InMemorySigner::from_secret_key("bot.testnet".parse().unwrap(), sk))
            .collect();

        let rotating = RotatingSigner::from_signers(signers).unwrap();
        assert_eq!(rotating.key_count(), 2);
        assert_eq!(rotating.public_keys(), expected_public_keys);
    }

    #[test]
    fn test_rotating_signer_from_signers_mismatched_accounts() {
        let signers = vec![
            InMemorySigner::from_secret_key(
                "alice.testnet".parse().unwrap(),
                SecretKey::generate_ed25519(),
            ),
            InMemorySigner::from_secret_key(
                "bob.testnet".parse().unwrap(),
                SecretKey::generate_ed25519(),
            ),
        ];

        let result = RotatingSigner::from_signers(signers);
        assert!(result.is_err());
    }

    #[test]
    fn test_rotating_signer_signing_keys() {
        let keys = vec![
            SecretKey::generate_ed25519(),
            SecretKey::generate_ed25519(),
            SecretKey::generate_ed25519(),
        ];
        let expected_public_keys: Vec<_> = keys.iter().map(|k| k.public_key()).collect();

        let signer = RotatingSigner::new("bot.testnet", keys).unwrap();

        // signing_keys() should not advance the counter
        let counter_before = signer.counter.load(Ordering::Relaxed);
        let signing_keys = signer.signing_keys();
        let counter_after = signer.counter.load(Ordering::Relaxed);
        assert_eq!(counter_before, counter_after);

        // Should return all keys with matching public keys
        assert_eq!(signing_keys.len(), 3);
        for (sk, expected_pk) in signing_keys.iter().zip(&expected_public_keys) {
            assert_eq!(sk.public_key(), expected_pk);
        }
    }

    #[test]
    fn test_rotating_signer_into_per_key_signers() {
        let keys = vec![SecretKey::generate_ed25519(), SecretKey::generate_ed25519()];
        let expected_public_keys: Vec<_> = keys.iter().map(|k| k.public_key()).collect();

        let signer = RotatingSigner::new("bot.testnet", keys).unwrap();
        let per_key = signer.into_per_key_signers();

        assert_eq!(per_key.len(), 2);
        for (ims, expected_pk) in per_key.iter().zip(&expected_public_keys) {
            assert_eq!(ims.account_id().as_str(), "bot.testnet");
            assert_eq!(ims.public_key(), expected_pk);
        }
    }

    #[test]
    fn test_signing_key_is_clone() {
        let signer = InMemorySigner::new(
            "alice.testnet",
            "ed25519:3D4YudUahN1nawWogh8pAKSj92sUNMdbZGjn7kERKzYoTy8tnFQuwoGUC51DowKqorvkr2pytJSnwuSbsNVfqygr",
        )
        .unwrap();

        let key = signer.key();
        let key_clone = key.clone();

        assert_eq!(key.public_key(), key_clone.public_key());
    }
}