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
//! Transaction builder for fluent multi-action transactions.
//!
//! 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()?;
//! let wasm_code = std::fs::read("contract.wasm").expect("failed to read wasm");
//! near.transaction("new.alice.testnet")
//!     .create_account()
//!     .transfer(NearToken::near(5))
//!     .add_full_access_key(new_public_key)
//!     .deploy(wasm_code)
//!     .call("init")
//!         .args(serde_json::json!({ "owner": "alice.testnet" }))
//!     .send()
//!     .await?;
//! # Ok(())
//! # }
//! ```

use std::collections::BTreeMap;
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::{Arc, OnceLock};

use crate::error::{Error, RpcError};
use crate::types::{
    AccountId, Action, BlockReference, CryptoHash, DelegateAction, DeterministicAccountStateInit,
    DeterministicAccountStateInitV1, FinalExecutionOutcome, Finality, Gas,
    GlobalContractIdentifier, IntoGas, IntoNearToken, NearToken, NonDelegateAction, PublicKey,
    SignedDelegateAction, SignedTransaction, Transaction, TxExecutionStatus,
};

use super::nonce_manager::NonceManager;
use super::rpc::RpcClient;
use super::signer::Signer;

/// Global nonce manager shared across all TransactionBuilder instances.
/// This is an implementation detail - not exposed to users.
fn nonce_manager() -> &'static NonceManager {
    static NONCE_MANAGER: OnceLock<NonceManager> = OnceLock::new();
    NONCE_MANAGER.get_or_init(NonceManager::new)
}

// ============================================================================
// Delegate Action Types
// ============================================================================

/// Options for creating a delegate action (meta-transaction).
#[derive(Clone, Debug, Default)]
pub struct DelegateOptions {
    /// Explicit block height at which the delegate action expires.
    /// If omitted, uses the current block height plus `block_height_offset`.
    pub max_block_height: Option<u64>,

    /// Number of blocks after the current height when the delegate action should expire.
    /// Defaults to 200 blocks if neither this nor `max_block_height` is provided.
    pub block_height_offset: Option<u64>,

    /// Override nonce to use for the delegate action. If omitted, fetches
    /// from the access key and uses nonce + 1.
    pub nonce: Option<u64>,
}

impl DelegateOptions {
    /// Create options with a specific block height offset.
    pub fn with_offset(offset: u64) -> Self {
        Self {
            block_height_offset: Some(offset),
            ..Default::default()
        }
    }

    /// Create options with a specific max block height.
    pub fn with_max_height(height: u64) -> Self {
        Self {
            max_block_height: Some(height),
            ..Default::default()
        }
    }
}

/// Result of creating a delegate action.
///
/// Contains the signed delegate action plus a pre-encoded payload for transport.
#[derive(Clone, Debug)]
pub struct DelegateResult {
    /// The fully signed delegate action.
    pub signed_delegate_action: SignedDelegateAction,
    /// Base64-encoded payload for HTTP/JSON transport.
    pub payload: String,
}

impl DelegateResult {
    /// Get the raw bytes of the signed delegate action.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.signed_delegate_action.to_bytes()
    }

    /// Get the sender account ID.
    pub fn sender_id(&self) -> &AccountId {
        self.signed_delegate_action.sender_id()
    }

    /// Get the receiver account ID.
    pub fn receiver_id(&self) -> &AccountId {
        self.signed_delegate_action.receiver_id()
    }
}

// ============================================================================
// TransactionBuilder
// ============================================================================

/// Builder for constructing multi-action transactions.
///
/// Created via [`crate::Near::transaction`]. Supports chaining multiple actions
/// into a single atomic transaction.
///
/// # Example
///
/// ```rust,no_run
/// # use near_kit::*;
/// # async fn example() -> Result<(), near_kit::Error> {
/// let near = Near::testnet()
///     .credentials("ed25519:...", "alice.testnet")?
///     .build();
///
/// // Single action
/// near.transaction("bob.testnet")
///     .transfer(NearToken::near(1))
///     .send()
///     .await?;
///
/// // Multiple actions (atomic)
/// let key: PublicKey = "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp".parse()?;
/// near.transaction("new.alice.testnet")
///     .create_account()
///     .transfer(NearToken::near(5))
///     .add_full_access_key(key)
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct TransactionBuilder {
    rpc: Arc<RpcClient>,
    signer: Option<Arc<dyn Signer>>,
    receiver_id: AccountId,
    actions: Vec<Action>,
    signer_override: Option<Arc<dyn Signer>>,
    wait_until: TxExecutionStatus,
    max_nonce_retries: u32,
}

impl TransactionBuilder {
    pub(crate) fn new(
        rpc: Arc<RpcClient>,
        signer: Option<Arc<dyn Signer>>,
        receiver_id: AccountId,
        max_nonce_retries: u32,
    ) -> Self {
        Self {
            rpc,
            signer,
            receiver_id,
            actions: Vec::new(),
            signer_override: None,
            wait_until: TxExecutionStatus::ExecutedOptimistic,
            max_nonce_retries,
        }
    }

    // ========================================================================
    // Action methods
    // ========================================================================

    /// Add a create account action.
    ///
    /// Creates a new sub-account. Must be followed by `transfer` and `add_key`
    /// to properly initialize the account.
    pub fn create_account(mut self) -> Self {
        self.actions.push(Action::create_account());
        self
    }

    /// Add a transfer action.
    ///
    /// Transfers NEAR tokens to the receiver account.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// near.transaction("bob.testnet")
    ///     .transfer(NearToken::near(1))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the amount string cannot be parsed.
    pub fn transfer(mut self, amount: impl IntoNearToken) -> Self {
        let amount = amount
            .into_near_token()
            .expect("invalid transfer amount - use NearToken::from_str() for user input");
        self.actions.push(Action::transfer(amount));
        self
    }

    /// Add a deploy contract action.
    ///
    /// Deploys WASM code to the receiver account.
    pub fn deploy(mut self, code: impl Into<Vec<u8>>) -> Self {
        self.actions.push(Action::deploy_contract(code.into()));
        self
    }

    /// Add a function call action.
    ///
    /// Returns a [`CallBuilder`] for configuring the call with args, gas, and deposit.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// near.transaction("contract.testnet")
    ///     .call("set_greeting")
    ///         .args(serde_json::json!({ "greeting": "Hello" }))
    ///         .gas(Gas::tgas(10))
    ///         .deposit(NearToken::ZERO)
    ///     .call("another_method")
    ///         .args(serde_json::json!({ "value": 42 }))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn call(self, method: &str) -> CallBuilder {
        CallBuilder::new(self, method.to_string())
    }

    /// Add a full access key to the account.
    pub fn add_full_access_key(mut self, public_key: PublicKey) -> Self {
        self.actions.push(Action::add_full_access_key(public_key));
        self
    }

    /// Add a function call access key to the account.
    ///
    /// # Arguments
    ///
    /// * `public_key` - The public key to add
    /// * `receiver_id` - The contract this key can call
    /// * `method_names` - Methods this key can call (empty = all methods)
    /// * `allowance` - Maximum amount this key can spend (None = unlimited)
    pub fn add_function_call_key(
        mut self,
        public_key: PublicKey,
        receiver_id: impl AsRef<str>,
        method_names: Vec<String>,
        allowance: Option<NearToken>,
    ) -> Self {
        let receiver_id = AccountId::parse_lenient(receiver_id);
        self.actions.push(Action::add_function_call_key(
            public_key,
            receiver_id,
            method_names,
            allowance,
        ));
        self
    }

    /// Delete an access key from the account.
    pub fn delete_key(mut self, public_key: PublicKey) -> Self {
        self.actions.push(Action::delete_key(public_key));
        self
    }

    /// Delete the account and transfer remaining balance to beneficiary.
    pub fn delete_account(mut self, beneficiary_id: impl AsRef<str>) -> Self {
        let beneficiary_id = AccountId::parse_lenient(beneficiary_id);
        self.actions.push(Action::delete_account(beneficiary_id));
        self
    }

    /// Add a stake action.
    ///
    /// # Panics
    ///
    /// Panics if the amount string cannot be parsed.
    pub fn stake(mut self, amount: impl IntoNearToken, public_key: PublicKey) -> Self {
        let amount = amount
            .into_near_token()
            .expect("invalid stake amount - use NearToken::from_str() for user input");
        self.actions.push(Action::stake(amount, public_key));
        self
    }

    /// Add a signed delegate action to this transaction (for relayers).
    ///
    /// This is used by relayers to wrap a user's signed delegate action
    /// and submit it to the blockchain, paying for the gas on behalf of the user.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(relayer: Near, payload: &str) -> Result<(), near_kit::Error> {
    /// // Relayer receives base64 payload from user
    /// let signed_delegate = SignedDelegateAction::from_base64(payload)?;
    ///
    /// // Relayer submits it, paying the gas
    /// let result = relayer
    ///     .transaction(signed_delegate.sender_id().as_str())
    ///     .signed_delegate_action(signed_delegate)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn signed_delegate_action(mut self, signed_delegate: SignedDelegateAction) -> Self {
        // Set receiver_id to the sender of the delegate action (the original user)
        self.receiver_id = signed_delegate.sender_id().clone();
        self.actions.push(Action::delegate(signed_delegate));
        self
    }

    // ========================================================================
    // Meta-transactions (Delegate Actions)
    // ========================================================================

    /// Build and sign a delegate action for meta-transactions (NEP-366).
    ///
    /// This allows the user to sign a set of actions off-chain, which can then
    /// be submitted by a relayer who pays the gas fees. The user's signature
    /// authorizes the actions, but they don't need to hold NEAR for gas.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// // User builds and signs a delegate action
    /// let result = near
    ///     .transaction("contract.testnet")
    ///     .call("add_message")
    ///         .args(serde_json::json!({ "text": "Hello!" }))
    ///         .gas(Gas::tgas(30))
    ///     .delegate(Default::default())
    ///     .await?;
    ///
    /// // Send payload to relayer via HTTP
    /// println!("Payload to send: {}", result.payload);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn delegate(self, options: DelegateOptions) -> Result<DelegateResult, Error> {
        if self.actions.is_empty() {
            return Err(Error::InvalidTransaction(
                "Delegate action requires at least one action".to_string(),
            ));
        }

        // Verify no nested delegates
        for action in &self.actions {
            if matches!(action, Action::Delegate(_)) {
                return Err(Error::InvalidTransaction(
                    "Delegate actions cannot contain nested signed delegate actions".to_string(),
                ));
            }
        }

        // Get the signer
        let signer = self
            .signer_override
            .as_ref()
            .or(self.signer.as_ref())
            .ok_or(Error::NoSigner)?;

        let sender_id = signer.account_id().clone();

        // Get a signing key atomically
        let key = signer.key();
        let public_key = key.public_key().clone();

        // Get nonce
        let nonce = if let Some(n) = options.nonce {
            n
        } else {
            let access_key = self
                .rpc
                .view_access_key(
                    &sender_id,
                    &public_key,
                    BlockReference::Finality(Finality::Optimistic),
                )
                .await?;
            access_key.nonce + 1
        };

        // Get max block height
        let max_block_height = if let Some(h) = options.max_block_height {
            h
        } else {
            let status = self.rpc.status().await?;
            let offset = options.block_height_offset.unwrap_or(200);
            status.sync_info.latest_block_height + offset
        };

        // Convert actions to NonDelegateAction
        let delegate_actions: Vec<NonDelegateAction> = self
            .actions
            .into_iter()
            .filter_map(NonDelegateAction::from_action)
            .collect();

        // Create delegate action
        let delegate_action = DelegateAction {
            sender_id,
            receiver_id: self.receiver_id,
            actions: delegate_actions,
            nonce,
            max_block_height,
            public_key: public_key.clone(),
        };

        // Sign the delegate action
        let hash = delegate_action.get_hash();
        let signature = key.sign(hash.as_bytes()).await?;

        // Create signed delegate action
        let signed_delegate_action = delegate_action.sign(signature);
        let payload = signed_delegate_action.to_base64();

        Ok(DelegateResult {
            signed_delegate_action,
            payload,
        })
    }

    // ========================================================================
    // Global Contract Actions
    // ========================================================================

    /// Publish a contract to the global registry.
    ///
    /// Global contracts are deployed once and can be referenced by multiple accounts,
    /// saving storage costs. Two modes are available:
    ///
    /// - `by_hash = false` (default): Contract is identified by the signer's account ID.
    ///   The signer can update the contract later, and all users will automatically
    ///   use the updated version.
    ///
    /// - `by_hash = true`: Contract is identified by its code hash. This creates
    ///   an immutable contract that cannot be updated.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), Box<dyn std::error::Error>> {
    /// let wasm_code = std::fs::read("contract.wasm")?;
    ///
    /// // Publish updatable contract (identified by your account)
    /// near.transaction("alice.testnet")
    ///     .publish_contract(wasm_code.clone(), false)
    ///     .send()
    ///     .await?;
    ///
    /// // Publish immutable contract (identified by its hash)
    /// near.transaction("alice.testnet")
    ///     .publish_contract(wasm_code, true)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn publish_contract(mut self, code: impl Into<Vec<u8>>, by_hash: bool) -> Self {
        self.actions
            .push(Action::publish_contract(code.into(), by_hash));
        self
    }

    /// Deploy a contract from the global registry by code hash.
    ///
    /// References a previously published immutable contract.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near, code_hash: CryptoHash) -> Result<(), near_kit::Error> {
    /// near.transaction("alice.testnet")
    ///     .deploy_from_hash(code_hash)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn deploy_from_hash(mut self, code_hash: CryptoHash) -> Self {
        self.actions.push(Action::deploy_from_hash(code_hash));
        self
    }

    /// Deploy a contract from the global registry by publisher account.
    ///
    /// References a contract published by the given account.
    /// The contract can be updated by the publisher.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// near.transaction("alice.testnet")
    ///     .deploy_from_publisher("contract-publisher.near")
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn deploy_from_publisher(mut self, publisher_id: impl AsRef<str>) -> Self {
        let publisher_id = AccountId::parse_lenient(publisher_id);
        self.actions.push(Action::deploy_from_account(publisher_id));
        self
    }

    /// Create a NEP-616 deterministic state init action with code hash reference.
    ///
    /// The receiver_id is automatically set to the deterministically derived account ID:
    /// `"0s" + hex(keccak256(borsh(state_init))[12..32])`
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near, code_hash: CryptoHash) -> Result<(), near_kit::Error> {
    /// // Note: the receiver_id passed to transaction() is ignored for state_init -
    /// // it will be replaced with the derived deterministic account ID
    /// let outcome = near.transaction("alice.testnet")
    ///     .state_init_by_hash(code_hash, Default::default(), NearToken::near(1))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the deposit amount string cannot be parsed.
    pub fn state_init_by_hash(
        mut self,
        code_hash: CryptoHash,
        data: BTreeMap<Vec<u8>, Vec<u8>>,
        deposit: impl IntoNearToken,
    ) -> Self {
        let deposit = deposit
            .into_near_token()
            .expect("invalid deposit amount - use NearToken::from_str() for user input");

        // Build the state init to derive the account ID
        let state_init = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::CodeHash(code_hash),
            data: data.clone(),
        });

        // Set receiver_id to the derived deterministic account ID
        self.receiver_id = state_init.derive_account_id();

        self.actions
            .push(Action::state_init_by_hash(code_hash, data, deposit));
        self
    }

    /// Create a NEP-616 deterministic state init action with publisher account reference.
    ///
    /// The receiver_id is automatically set to the deterministically derived account ID.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// // Note: the receiver_id passed to transaction() is ignored for state_init -
    /// // it will be replaced with the derived deterministic account ID
    /// let outcome = near.transaction("alice.testnet")
    ///     .state_init_by_publisher("contract-publisher.near", Default::default(), NearToken::near(1))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the deposit amount string cannot be parsed.
    pub fn state_init_by_publisher(
        mut self,
        publisher_id: impl AsRef<str>,
        data: BTreeMap<Vec<u8>, Vec<u8>>,
        deposit: impl IntoNearToken,
    ) -> Self {
        let publisher_id = AccountId::parse_lenient(publisher_id);
        let deposit = deposit
            .into_near_token()
            .expect("invalid deposit amount - use NearToken::from_str() for user input");

        // Build the state init to derive the account ID
        let state_init = DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
            code: GlobalContractIdentifier::AccountId(publisher_id.clone()),
            data: data.clone(),
        });

        // Set receiver_id to the derived deterministic account ID
        self.receiver_id = state_init.derive_account_id();

        self.actions
            .push(Action::state_init_by_account(publisher_id, data, deposit));
        self
    }

    // ========================================================================
    // Configuration methods
    // ========================================================================

    /// Override the signer for this transaction.
    pub fn sign_with(mut self, signer: impl Signer + 'static) -> Self {
        self.signer_override = Some(Arc::new(signer));
        self
    }

    /// Set the execution wait level.
    pub fn wait_until(mut self, status: TxExecutionStatus) -> Self {
        self.wait_until = status;
        self
    }

    // ========================================================================
    // Execution
    // ========================================================================

    /// Sign the transaction without sending it.
    ///
    /// Returns a `SignedTransaction` that can be inspected or sent later.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// let signed = near.transaction("bob.testnet")
    ///     .transfer(NearToken::near(1))
    ///     .sign()
    ///     .await?;
    ///
    /// // Inspect the transaction
    /// println!("Hash: {}", signed.transaction.get_hash());
    /// println!("Actions: {:?}", signed.transaction.actions);
    ///
    /// // Send it later
    /// let outcome = near.send(&signed).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn sign(self) -> Result<SignedTransaction, Error> {
        if self.actions.is_empty() {
            return Err(Error::InvalidTransaction(
                "Transaction must have at least one action".to_string(),
            ));
        }

        let signer = self
            .signer_override
            .or(self.signer)
            .ok_or(Error::NoSigner)?;

        let signer_id = signer.account_id().clone();

        // Get a signing key atomically. For RotatingSigner, this claims the next
        // key in rotation. The key contains both the public key and signing capability.
        let key = signer.key();
        let public_key = key.public_key().clone();
        let public_key_str = public_key.to_string();

        // Get nonce for the key
        let rpc = self.rpc.clone();
        let network = rpc.url().to_string();
        let signer_id_clone = signer_id.clone();
        let public_key_clone = public_key.clone();

        let nonce = nonce_manager()
            .get_next_nonce(&network, signer_id.as_ref(), &public_key_str, || async {
                let access_key = rpc
                    .view_access_key(
                        &signer_id_clone,
                        &public_key_clone,
                        BlockReference::Finality(Finality::Optimistic),
                    )
                    .await?;
                Ok(access_key.nonce)
            })
            .await?;

        // Get recent block hash
        let block = self
            .rpc
            .block(BlockReference::Finality(Finality::Final))
            .await?;

        // Build transaction
        let tx = Transaction::new(
            signer_id,
            public_key,
            nonce,
            self.receiver_id,
            block.header.hash,
            self.actions,
        );

        // Sign with the key
        let signature = key.sign(tx.get_hash().as_bytes()).await?;

        Ok(SignedTransaction {
            transaction: tx,
            signature,
        })
    }

    /// Sign the transaction offline without network access.
    ///
    /// This is useful for air-gapped signing workflows where you need to
    /// provide the block hash and nonce manually (obtained from a separate
    /// online machine).
    ///
    /// # Arguments
    ///
    /// * `block_hash` - A recent block hash (transaction expires ~24h after this block)
    /// * `nonce` - The next nonce for the signing key (current nonce + 1)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// # use near_kit::*;
    /// // On online machine: get block hash and nonce
    /// // let block = near.rpc().block(BlockReference::latest()).await?;
    /// // let access_key = near.rpc().view_access_key(...).await?;
    ///
    /// // On offline machine: sign with pre-fetched values
    /// let block_hash: CryptoHash = "11111111111111111111111111111111".parse().unwrap();
    /// let nonce = 12345u64;
    ///
    /// let signed = near.transaction("bob.testnet")
    ///     .transfer(NearToken::near(1))
    ///     .sign_offline(block_hash, nonce)
    ///     .await?;
    ///
    /// // Transport signed_tx.to_base64() back to online machine
    /// ```
    pub async fn sign_offline(
        self,
        block_hash: CryptoHash,
        nonce: u64,
    ) -> Result<SignedTransaction, Error> {
        if self.actions.is_empty() {
            return Err(Error::InvalidTransaction(
                "Transaction must have at least one action".to_string(),
            ));
        }

        let signer = self
            .signer_override
            .or(self.signer)
            .ok_or(Error::NoSigner)?;

        let signer_id = signer.account_id().clone();

        // Get a signing key atomically
        let key = signer.key();
        let public_key = key.public_key().clone();

        // Build transaction with provided block_hash and nonce
        let tx = Transaction::new(
            signer_id,
            public_key,
            nonce,
            self.receiver_id,
            block_hash,
            self.actions,
        );

        // Sign
        let signature = key.sign(tx.get_hash().as_bytes()).await?;

        Ok(SignedTransaction {
            transaction: tx,
            signature,
        })
    }

    /// Send the transaction.
    ///
    /// This is equivalent to awaiting the builder directly.
    pub fn send(self) -> TransactionSend {
        TransactionSend { builder: self }
    }

    /// Internal method to add an action (used by CallBuilder).
    fn push_action(&mut self, action: Action) {
        self.actions.push(action);
    }
}

// ============================================================================
// CallBuilder
// ============================================================================

/// Builder for configuring a function call within a transaction.
///
/// Created via [`TransactionBuilder::call`]. Allows setting args, gas, and deposit
/// before continuing to chain more actions or sending.
pub struct CallBuilder {
    builder: TransactionBuilder,
    method: String,
    args: Vec<u8>,
    gas: Gas,
    deposit: NearToken,
}

impl CallBuilder {
    fn new(builder: TransactionBuilder, method: String) -> Self {
        Self {
            builder,
            method,
            args: Vec::new(),
            gas: Gas::DEFAULT,
            deposit: NearToken::ZERO,
        }
    }

    /// Set JSON arguments.
    pub fn args<A: serde::Serialize>(mut self, args: A) -> Self {
        self.args = serde_json::to_vec(&args).unwrap_or_default();
        self
    }

    /// Set raw byte arguments.
    pub fn args_raw(mut self, args: Vec<u8>) -> Self {
        self.args = args;
        self
    }

    /// Set Borsh-encoded arguments.
    pub fn args_borsh<A: borsh::BorshSerialize>(mut self, args: A) -> Self {
        self.args = borsh::to_vec(&args).unwrap_or_default();
        self
    }

    /// Set gas limit.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// near.transaction("contract.testnet")
    ///     .call("method")
    ///         .gas(Gas::tgas(50))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the gas string cannot be parsed. Use [`Gas`]'s `FromStr` impl
    /// for fallible parsing of user input.
    pub fn gas(mut self, gas: impl IntoGas) -> Self {
        self.gas = gas
            .into_gas()
            .expect("invalid gas format - use Gas::from_str() for user input");
        self
    }

    /// Set attached deposit.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// near.transaction("contract.testnet")
    ///     .call("method")
    ///         .deposit(NearToken::near(1))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the amount string cannot be parsed. Use [`NearToken`]'s `FromStr`
    /// impl for fallible parsing of user input.
    pub fn deposit(mut self, amount: impl IntoNearToken) -> Self {
        self.deposit = amount
            .into_near_token()
            .expect("invalid deposit amount - use NearToken::from_str() for user input");
        self
    }

    /// Finish this call and return to the transaction builder.
    fn finish(self) -> TransactionBuilder {
        let mut builder = self.builder;
        builder.push_action(Action::function_call(
            self.method,
            self.args,
            self.gas,
            self.deposit,
        ));
        builder
    }

    // ========================================================================
    // Chaining methods (delegate to TransactionBuilder after finishing)
    // ========================================================================

    /// Add another function call.
    pub fn call(self, method: &str) -> CallBuilder {
        self.finish().call(method)
    }

    /// Add a create account action.
    pub fn create_account(self) -> TransactionBuilder {
        self.finish().create_account()
    }

    /// Add a transfer action.
    pub fn transfer(self, amount: impl IntoNearToken) -> TransactionBuilder {
        self.finish().transfer(amount)
    }

    /// Add a deploy contract action.
    pub fn deploy(self, code: impl Into<Vec<u8>>) -> TransactionBuilder {
        self.finish().deploy(code)
    }

    /// Add a full access key.
    pub fn add_full_access_key(self, public_key: PublicKey) -> TransactionBuilder {
        self.finish().add_full_access_key(public_key)
    }

    /// Add a function call access key.
    pub fn add_function_call_key(
        self,
        public_key: PublicKey,
        receiver_id: impl AsRef<str>,
        method_names: Vec<String>,
        allowance: Option<NearToken>,
    ) -> TransactionBuilder {
        self.finish()
            .add_function_call_key(public_key, receiver_id, method_names, allowance)
    }

    /// Delete an access key.
    pub fn delete_key(self, public_key: PublicKey) -> TransactionBuilder {
        self.finish().delete_key(public_key)
    }

    /// Delete the account.
    pub fn delete_account(self, beneficiary_id: impl AsRef<str>) -> TransactionBuilder {
        self.finish().delete_account(beneficiary_id)
    }

    /// Add a stake action.
    pub fn stake(self, amount: impl IntoNearToken, public_key: PublicKey) -> TransactionBuilder {
        self.finish().stake(amount, public_key)
    }

    /// Publish a contract to the global registry.
    pub fn publish_contract(self, code: impl Into<Vec<u8>>, by_hash: bool) -> TransactionBuilder {
        self.finish().publish_contract(code, by_hash)
    }

    /// Deploy a contract from the global registry by code hash.
    pub fn deploy_from_hash(self, code_hash: CryptoHash) -> TransactionBuilder {
        self.finish().deploy_from_hash(code_hash)
    }

    /// Deploy a contract from the global registry by publisher account.
    pub fn deploy_from_publisher(self, publisher_id: impl AsRef<str>) -> TransactionBuilder {
        self.finish().deploy_from_publisher(publisher_id)
    }

    /// Create a NEP-616 deterministic state init action with code hash reference.
    pub fn state_init_by_hash(
        self,
        code_hash: CryptoHash,
        data: BTreeMap<Vec<u8>, Vec<u8>>,
        deposit: impl IntoNearToken,
    ) -> TransactionBuilder {
        self.finish().state_init_by_hash(code_hash, data, deposit)
    }

    /// Create a NEP-616 deterministic state init action with publisher account reference.
    pub fn state_init_by_publisher(
        self,
        publisher_id: impl AsRef<str>,
        data: BTreeMap<Vec<u8>, Vec<u8>>,
        deposit: impl IntoNearToken,
    ) -> TransactionBuilder {
        self.finish()
            .state_init_by_publisher(publisher_id, data, deposit)
    }

    /// Override the signer.
    pub fn sign_with(self, signer: impl Signer + 'static) -> TransactionBuilder {
        self.finish().sign_with(signer)
    }

    /// Set the execution wait level.
    pub fn wait_until(self, status: TxExecutionStatus) -> TransactionBuilder {
        self.finish().wait_until(status)
    }

    /// Build and sign a delegate action for meta-transactions (NEP-366).
    ///
    /// This finishes the current function call and then creates a delegate action.
    pub async fn delegate(self, options: DelegateOptions) -> Result<DelegateResult, crate::Error> {
        self.finish().delegate(options).await
    }

    /// Sign the transaction offline without network access.
    ///
    /// See [`TransactionBuilder::sign_offline`] for details.
    pub async fn sign_offline(
        self,
        block_hash: CryptoHash,
        nonce: u64,
    ) -> Result<SignedTransaction, Error> {
        self.finish().sign_offline(block_hash, nonce).await
    }

    /// Sign the transaction without sending it.
    ///
    /// See [`TransactionBuilder::sign`] for details.
    pub async fn sign(self) -> Result<SignedTransaction, Error> {
        self.finish().sign().await
    }

    /// Send the transaction.
    pub fn send(self) -> TransactionSend {
        self.finish().send()
    }
}

impl IntoFuture for CallBuilder {
    type Output = Result<FinalExecutionOutcome, Error>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        self.send().into_future()
    }
}

// ============================================================================
// TransactionSend
// ============================================================================

/// Future for sending a transaction.
pub struct TransactionSend {
    builder: TransactionBuilder,
}

impl TransactionSend {
    /// Set the execution wait level.
    pub fn wait_until(mut self, status: TxExecutionStatus) -> Self {
        self.builder.wait_until = status;
        self
    }
}

impl IntoFuture for TransactionSend {
    type Output = Result<FinalExecutionOutcome, Error>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let builder = self.builder;

            if builder.actions.is_empty() {
                return Err(Error::InvalidTransaction(
                    "Transaction must have at least one action".to_string(),
                ));
            }

            let signer = builder
                .signer_override
                .as_ref()
                .or(builder.signer.as_ref())
                .ok_or(Error::NoSigner)?;

            let signer_id = signer.account_id().clone();

            // Retry loop for InvalidNonceError
            let max_nonce_retries = builder.max_nonce_retries;
            let network = builder.rpc.url().to_string();
            let mut last_error: Option<Error> = None;
            let mut last_ak_nonce: Option<u64> = None;

            for attempt in 0..max_nonce_retries {
                // Get a signing key atomically for this attempt
                let key = signer.key();
                let public_key = key.public_key().clone();
                let public_key_str = public_key.to_string();

                // Get nonce from manager (fetches from blockchain on first call, then increments locally)
                let rpc = builder.rpc.clone();
                let signer_id_clone = signer_id.clone();
                let public_key_clone = public_key.clone();

                let nonce = if let Some(ak_nonce) = last_ak_nonce.take() {
                    // Use the ak_nonce from the error directly - avoids refetching
                    nonce_manager().update_and_get_next(
                        &network,
                        signer_id.as_ref(),
                        &public_key_str,
                        ak_nonce,
                    )
                } else {
                    nonce_manager()
                        .get_next_nonce(&network, signer_id.as_ref(), &public_key_str, || async {
                            let access_key = rpc
                                .view_access_key(
                                    &signer_id_clone,
                                    &public_key_clone,
                                    BlockReference::Finality(Finality::Optimistic),
                                )
                                .await?;
                            Ok(access_key.nonce)
                        })
                        .await?
                };

                // Get recent block hash (use finalized for stability)
                let block = builder
                    .rpc
                    .block(BlockReference::Finality(Finality::Final))
                    .await?;

                // Build transaction
                let tx = Transaction::new(
                    signer_id.clone(),
                    public_key.clone(),
                    nonce,
                    builder.receiver_id.clone(),
                    block.header.hash,
                    builder.actions.clone(),
                );

                // Sign with the key
                let signature = match key.sign(tx.get_hash().as_bytes()).await {
                    Ok(sig) => sig,
                    Err(e) => return Err(Error::Signing(e)),
                };
                let signed_tx = crate::types::SignedTransaction {
                    transaction: tx,
                    signature,
                };

                // Send
                match builder.rpc.send_tx(&signed_tx, builder.wait_until).await {
                    Ok(response) => {
                        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, builder.wait_until,
                            ))
                        })?;
                        if outcome.is_failure() {
                            return Err(Error::TransactionFailed(
                                outcome.failure_message().unwrap_or_default(),
                            ));
                        }
                        return Ok(outcome);
                    }
                    Err(RpcError::InvalidNonce { tx_nonce, ak_nonce })
                        if attempt < max_nonce_retries - 1 =>
                    {
                        // Store ak_nonce for next iteration to avoid refetching
                        last_ak_nonce = Some(ak_nonce);
                        last_error =
                            Some(Error::Rpc(RpcError::InvalidNonce { tx_nonce, ak_nonce }));
                        continue;
                    }
                    Err(e) => return Err(Error::Rpc(e)),
                }
            }

            Err(last_error.unwrap_or_else(|| {
                Error::InvalidTransaction("Unknown error during transaction send".to_string())
            }))
        })
    }
}

impl IntoFuture for TransactionBuilder {
    type Output = Result<FinalExecutionOutcome, Error>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        self.send().into_future()
    }
}