near-kit 0.7.1

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
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
//! 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::from_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::fmt;
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::{Arc, OnceLock};

use tracing::Instrument;

use crate::error::{Error, RpcError};
use crate::types::{
    AccountId, Action, BlockReference, CryptoHash, DelegateAction, DeterministicAccountStateInit,
    FinalExecutionOutcome, Finality, Gas, GlobalContractIdentifier, GlobalContractRef, IntoGas,
    IntoNearToken, NearToken, NonDelegateAction, PublicKey, PublishMode, SignedDelegateAction,
    SignedTransaction, Transaction, TryIntoAccountId, 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::from_near(1))
///     .send()
///     .await?;
///
/// // Multiple actions (atomic)
/// let key: PublicKey = "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp".parse()?;
/// near.transaction("new.alice.testnet")
///     .create_account()
///     .transfer(NearToken::from_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 fmt::Debug for TransactionBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TransactionBuilder")
            .field(
                "signer_id",
                &self
                    .signer_override
                    .as_ref()
                    .or(self.signer.as_ref())
                    .map(|s| s.account_id()),
            )
            .field("receiver_id", &self.receiver_id)
            .field("action_count", &self.actions.len())
            .field("wait_until", &self.wait_until)
            .field("max_nonce_retries", &self.max_nonce_retries)
            .finish()
    }
}

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::from_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::from_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 TryIntoAccountId,
        method_names: Vec<String>,
        allowance: Option<NearToken>,
    ) -> Self {
        let receiver_id = receiver_id
            .try_into_account_id()
            .expect("invalid account 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 TryIntoAccountId) -> Self {
        let beneficiary_id = beneficiary_id
            .try_into_account_id()
            .expect("invalid account 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())
    ///     .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::from_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 via [`PublishMode`]:
    ///
    /// - [`PublishMode::Updatable`]: the contract is identified by the publisher's
    ///   account and can be updated by publishing new code from the same account.
    /// - [`PublishMode::Immutable`]: the contract is identified by its code hash and
    ///   cannot be updated once published.
    ///
    /// # 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(wasm_code.clone(), PublishMode::Updatable)
    ///     .send()
    ///     .await?;
    ///
    /// // Publish immutable contract (identified by its hash)
    /// near.transaction("alice.testnet")
    ///     .publish(wasm_code, PublishMode::Immutable)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn publish(mut self, code: impl Into<Vec<u8>>, mode: PublishMode) -> Self {
        self.actions.push(Action::publish(code.into(), mode));
        self
    }

    /// Deploy a contract from the global registry.
    ///
    /// Accepts any [`GlobalContractRef`] (such as a [`CryptoHash`] or an account ID
    /// string/[`AccountId`]) to reference a previously published 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(code_hash)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn deploy_from(mut self, contract_ref: impl GlobalContractRef) -> Self {
        let identifier = contract_ref.into_identifier();
        self.actions.push(match identifier {
            GlobalContractIdentifier::CodeHash(hash) => Action::deploy_from_hash(hash),
            GlobalContractIdentifier::AccountId(id) => Action::deploy_from_account(id),
        });
        self
    }

    /// Create a NEP-616 deterministic state init action.
    ///
    /// 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> {
    /// let si = DeterministicAccountStateInit::by_hash(code_hash, Default::default());
    /// let outcome = near.transaction("alice.testnet")
    ///     .state_init(si, NearToken::from_near(1))
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the deposit amount string cannot be parsed.
    pub fn state_init(
        mut self,
        state_init: DeterministicAccountStateInit,
        deposit: impl IntoNearToken,
    ) -> Self {
        let deposit = deposit
            .into_near_token()
            .expect("invalid deposit amount - use NearToken::from_str() for user input");

        self.receiver_id = state_init.derive_account_id();
        self.actions.push(Action::state_init(state_init, deposit));
        self
    }

    /// Add a pre-built action to the transaction.
    ///
    /// This is the most flexible way to add actions, since it accepts any
    /// [`Action`] variant directly. It's especially useful when you want to
    /// build function call actions independently and attach them later, or
    /// when working with action types that don't have dedicated builder
    /// methods.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// let action = Action::function_call(
    ///     "transfer",
    ///     serde_json::to_vec(&serde_json::json!({ "receiver": "bob.testnet" }))?,
    ///     Gas::from_tgas(30),
    ///     NearToken::ZERO,
    /// );
    ///
    /// near.transaction("contract.testnet")
    ///     .add_action(action)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_action(mut self, action: impl Into<Action>) -> Self {
        self.actions.push(action.into());
        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
    }

    /// Override the number of nonce retries for this transaction on `InvalidNonce`
    /// errors. `0` means no retries (send once), `1` means one retry, etc.
    pub fn max_nonce_retries(mut self, retries: u32) -> Self {
        self.max_nonce_retries = retries;
        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::from_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();
        let action_count = self.actions.len();

        let span = tracing::info_span!(
            "sign_transaction",
            sender = %signer_id,
            receiver = %self.receiver_id,
            action_count,
        );

        async move {
            // 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();

            // Single view_access_key call provides both nonce and block_hash.
            // Uses Finality::Final for block hash stability.
            let access_key = self
                .rpc
                .view_access_key(
                    &signer_id,
                    &public_key,
                    BlockReference::Finality(Finality::Final),
                )
                .await?;
            let block_hash = access_key.block_hash;

            let network = self.rpc.url().to_string();
            let nonce = nonce_manager().next(
                network,
                signer_id.clone(),
                public_key.clone(),
                access_key.nonce,
            );

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

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

            tracing::debug!(tx_hash = %tx_hash, nonce, "Transaction signed");

            Ok(SignedTransaction {
                transaction: tx,
                signature,
            })
        }
        .instrument(span)
        .await
    }

    /// 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::from_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 }
    }
}

// ============================================================================
// FunctionCall
// ============================================================================

/// A standalone function call configuration, decoupled from any transaction.
///
/// Use this when you need to pre-build calls and compose them into a transaction
/// later. This is especially useful for dynamic transaction composition (e.g. in
/// a loop) or for batching typed contract calls into a single transaction.
///
/// Note: `FunctionCall` does not capture a receiver/contract account. The call
/// will execute against whichever `receiver_id` is set on the transaction it's
/// added to.
///
/// # Examples
///
/// ```rust,no_run
/// # use near_kit::*;
/// # async fn example(near: Near) -> Result<(), near_kit::Error> {
/// // Pre-build calls independently
/// let init = FunctionCall::new("init")
///     .args(serde_json::json!({"owner": "alice.testnet"}))
///     .gas(Gas::from_tgas(50));
///
/// let notify = FunctionCall::new("notify")
///     .args(serde_json::json!({"msg": "done"}));
///
/// // Compose into a single atomic transaction
/// near.transaction("contract.testnet")
///     .add_action(init)
///     .add_action(notify)
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// ```rust,no_run
/// # use near_kit::*;
/// # async fn example(near: Near) -> Result<(), near_kit::Error> {
/// // Dynamic composition in a loop
/// let calls = vec![
///     FunctionCall::new("method_a").args(serde_json::json!({"x": 1})),
///     FunctionCall::new("method_b").args(serde_json::json!({"y": 2})),
/// ];
///
/// let mut tx = near.transaction("contract.testnet");
/// for call in calls {
///     tx = tx.add_action(call);
/// }
/// tx.send().await?;
/// # Ok(())
/// # }
/// ```
pub struct FunctionCall {
    method: String,
    args: Vec<u8>,
    gas: Gas,
    deposit: NearToken,
}

impl fmt::Debug for FunctionCall {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FunctionCall")
            .field("method", &self.method)
            .field("args_len", &self.args.len())
            .field("gas", &self.gas)
            .field("deposit", &self.deposit)
            .finish()
    }
}

impl FunctionCall {
    /// Create a new function call for the given method name.
    pub fn new(method: impl Into<String>) -> Self {
        Self {
            method: method.into(),
            args: Vec::new(),
            gas: Gas::from_tgas(30),
            deposit: NearToken::ZERO,
        }
    }

    /// Set JSON arguments.
    pub fn args(mut self, args: impl serde::Serialize) -> 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(mut self, args: impl borsh::BorshSerialize) -> Self {
        self.args = borsh::to_vec(&args).unwrap_or_default();
        self
    }

    /// Set gas limit.
    ///
    /// Defaults to 30 TGas if not set.
    ///
    /// # 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.
    ///
    /// Defaults to zero if not set.
    ///
    /// # 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
    }
}

impl From<FunctionCall> for Action {
    fn from(call: FunctionCall) -> Self {
        Action::function_call(call.method, call.args, call.gas, call.deposit)
    }
}

// ============================================================================
// 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,
    call: FunctionCall,
}

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

impl CallBuilder {
    fn new(builder: TransactionBuilder, method: String) -> Self {
        Self {
            builder,
            call: FunctionCall::new(method),
        }
    }

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

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

    /// Set Borsh-encoded arguments.
    pub fn args_borsh<A: borsh::BorshSerialize>(mut self, args: A) -> Self {
        self.call = self.call.args_borsh(args);
        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::from_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.call = self.call.gas(gas);
        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::from_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.call = self.call.deposit(amount);
        self
    }

    /// Convert this call into a standalone [`Action`], discarding the
    /// underlying transaction builder.
    ///
    /// This is useful for extracting a typed contract call so it can be
    /// composed into a different transaction.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use near_kit::*;
    /// # async fn example(near: Near) -> Result<(), near_kit::Error> {
    /// // Extract actions from the fluent builder
    /// let action = near.transaction("contract.testnet")
    ///     .call("method")
    ///     .args(serde_json::json!({"key": "value"}))
    ///     .gas(Gas::from_tgas(50))
    ///     .into_action();
    ///
    /// // Compose into a different transaction
    /// near.transaction("contract.testnet")
    ///     .add_action(action)
    ///     .send()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the underlying transaction builder already has accumulated
    /// actions, since those would be silently dropped. Use [`finish`](Self::finish)
    /// instead when chaining multiple actions on the same transaction.
    pub fn into_action(self) -> Action {
        assert!(
            self.builder.actions.is_empty(),
            "into_action() discards {} previously accumulated action(s) — \
             use .finish() to keep them in the transaction",
            self.builder.actions.len(),
        );
        self.call.into()
    }

    /// Finish this call and return to the transaction builder.
    ///
    /// This is useful when you need to conditionally add actions to a
    /// transaction, since it gives back the [`TransactionBuilder`] so you can
    /// branch on runtime state before starting the next action.
    pub fn finish(self) -> TransactionBuilder {
        self.builder.add_action(self.call)
    }

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

    /// Add a pre-built action to the transaction.
    ///
    /// Finishes this function call, then adds the given action.
    /// See [`TransactionBuilder::add_action`] for details.
    pub fn add_action(self, action: impl Into<Action>) -> TransactionBuilder {
        self.finish().add_action(action)
    }

    /// 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 TryIntoAccountId,
        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 TryIntoAccountId) -> 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(self, code: impl Into<Vec<u8>>, mode: PublishMode) -> TransactionBuilder {
        self.finish().publish(code, mode)
    }

    /// Deploy a contract from the global registry.
    pub fn deploy_from(self, contract_ref: impl GlobalContractRef) -> TransactionBuilder {
        self.finish().deploy_from(contract_ref)
    }

    /// Create a NEP-616 deterministic state init action.
    pub fn state_init(
        self,
        state_init: DeterministicAccountStateInit,
        deposit: impl IntoNearToken,
    ) -> TransactionBuilder {
        self.finish().state_init(state_init, 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)
    }

    /// Override the number of nonce retries for this transaction on `InvalidNonce`
    /// errors. `0` means no retries (send once), `1` means one retry, etc.
    pub fn max_nonce_retries(self, retries: u32) -> TransactionBuilder {
        self.finish().max_nonce_retries(retries)
    }

    /// 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
    }

    /// Override the number of nonce retries for this transaction on `InvalidNonce`
    /// errors. `0` means no retries (send once), `1` means one retry, etc.
    pub fn max_nonce_retries(mut self, retries: u32) -> Self {
        self.builder.max_nonce_retries = retries;
        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();

            let span = tracing::info_span!(
                "send_transaction",
                sender = %signer_id,
                receiver = %builder.receiver_id,
                action_count = builder.actions.len(),
            );

            async move {
                // Retry loop for transient InvalidTxErrors (nonce conflicts, expired block hash)
                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();

                    // Single view_access_key call provides both nonce and block_hash.
                    // Uses Finality::Final for block hash stability.
                    let access_key = builder
                        .rpc
                        .view_access_key(
                            &signer_id,
                            &public_key,
                            BlockReference::Finality(Finality::Final),
                        )
                        .await?;
                    let block_hash = access_key.block_hash;

                    // Resolve nonce: prefer ak_nonce from a prior InvalidNonce
                    // error (more recent than the view_access_key result), then
                    // fall back to the chain nonce. The nonce manager takes
                    // max(cached, provided) so stale values are harmless.
                    let nonce = nonce_manager().next(
                        network.clone(),
                        signer_id.clone(),
                        public_key.clone(),
                        last_ak_nonce.take().unwrap_or(access_key.nonce),
                    );

                    // Build transaction
                    let tx = Transaction::new(
                        signer_id.clone(),
                        public_key.clone(),
                        nonce,
                        builder.receiver_id.clone(),
                        block_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,
                                ))
                            })?;

                            // Inspect outcome status — only InvalidTxError becomes Err.
                            // ActionError means the tx executed (nonce incremented, gas consumed),
                            // so we return Ok(outcome) and let the caller inspect is_failure().
                            use crate::types::{FinalExecutionStatus, TxExecutionError};
                            match outcome.status {
                                FinalExecutionStatus::Failure(
                                    TxExecutionError::InvalidTxError(e),
                                ) => {
                                    return Err(Error::InvalidTx(Box::new(e)));
                                }
                                _ => return Ok(outcome),
                            }
                        }
                        Err(RpcError::InvalidTx(
                            crate::types::InvalidTxError::InvalidNonce { tx_nonce, ak_nonce },
                        )) if attempt < max_nonce_retries => {
                            tracing::warn!(
                                tx_nonce = tx_nonce,
                                ak_nonce = ak_nonce,
                                attempt = attempt + 1,
                                "Invalid nonce, retrying"
                            );
                            // Store ak_nonce for next iteration to avoid refetching
                            last_ak_nonce = Some(ak_nonce);
                            last_error = Some(Error::InvalidTx(Box::new(
                                crate::types::InvalidTxError::InvalidNonce { tx_nonce, ak_nonce },
                            )));
                            continue;
                        }
                        Err(RpcError::InvalidTx(crate::types::InvalidTxError::Expired))
                            if attempt + 1 < max_nonce_retries =>
                        {
                            tracing::warn!(
                                attempt = attempt + 1,
                                "Transaction expired (stale block hash), retrying with fresh block hash"
                            );
                            // Expired tx was rejected before nonce consumption.
                            // No cache invalidation needed: the next iteration calls
                            // view_access_key which provides a fresh nonce, and
                            // next() uses max(cached, chain) so stale cache is harmless.
                            last_error = Some(Error::InvalidTx(Box::new(
                                crate::types::InvalidTxError::Expired,
                            )));
                            continue;
                        }
                        Err(e) => {
                            tracing::error!(error = %e, "Transaction send failed");
                            return Err(e.into());
                        }
                    }
                }

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

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()
    }
}

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

    /// Create a TransactionBuilder for unit tests (no real network needed).
    fn test_builder() -> TransactionBuilder {
        let rpc = Arc::new(RpcClient::new("https://rpc.testnet.near.org"));
        let receiver: AccountId = "contract.testnet".parse().unwrap();
        TransactionBuilder::new(rpc, None, receiver, 0)
    }

    #[test]
    fn add_action_appends_to_transaction() {
        let action = Action::function_call(
            "do_something",
            serde_json::to_vec(&serde_json::json!({ "key": "value" })).unwrap(),
            Gas::from_tgas(30),
            NearToken::ZERO,
        );

        let builder = test_builder().add_action(action);
        assert_eq!(builder.actions.len(), 1);
    }

    #[test]
    fn add_action_chains_with_other_actions() {
        let call_action =
            Action::function_call("init", Vec::new(), Gas::from_tgas(10), NearToken::ZERO);

        let builder = test_builder()
            .create_account()
            .transfer(NearToken::from_near(5))
            .add_action(call_action);

        assert_eq!(builder.actions.len(), 3);
    }

    #[test]
    fn add_action_works_after_call_builder() {
        let extra_action = Action::transfer(NearToken::from_near(1));

        let builder = test_builder()
            .call("setup")
            .args(serde_json::json!({ "admin": "alice.testnet" }))
            .gas(Gas::from_tgas(50))
            .add_action(extra_action);

        // Should have two actions: the function call from CallBuilder + the transfer
        assert_eq!(builder.actions.len(), 2);
    }

    // FunctionCall tests

    #[test]
    fn function_call_into_action() {
        let call = FunctionCall::new("init")
            .args(serde_json::json!({"owner": "alice.testnet"}))
            .gas(Gas::from_tgas(50))
            .deposit(NearToken::from_near(1));

        let action: Action = call.into();
        match &action {
            Action::FunctionCall(fc) => {
                assert_eq!(fc.method_name, "init");
                assert_eq!(
                    fc.args,
                    serde_json::to_vec(&serde_json::json!({"owner": "alice.testnet"})).unwrap()
                );
                assert_eq!(fc.gas, Gas::from_tgas(50));
                assert_eq!(fc.deposit, NearToken::from_near(1));
            }
            other => panic!("expected FunctionCall, got {:?}", other),
        }
    }

    #[test]
    fn function_call_defaults() {
        let call = FunctionCall::new("method");
        let action: Action = call.into();
        match &action {
            Action::FunctionCall(fc) => {
                assert_eq!(fc.method_name, "method");
                assert!(fc.args.is_empty());
                assert_eq!(fc.gas, Gas::from_tgas(30));
                assert_eq!(fc.deposit, NearToken::ZERO);
            }
            other => panic!("expected FunctionCall, got {:?}", other),
        }
    }

    #[test]
    fn function_call_compose_into_transaction() {
        let init = FunctionCall::new("init")
            .args(serde_json::json!({"owner": "alice.testnet"}))
            .gas(Gas::from_tgas(50));

        let notify = FunctionCall::new("notify").args(serde_json::json!({"msg": "done"}));

        let builder = test_builder()
            .deploy(vec![0u8])
            .add_action(init)
            .add_action(notify);

        assert_eq!(builder.actions.len(), 3);
    }

    #[test]
    fn function_call_dynamic_loop_composition() {
        let methods = vec!["step1", "step2", "step3"];

        let mut tx = test_builder();
        for method in methods {
            tx = tx.add_action(FunctionCall::new(method));
        }

        assert_eq!(tx.actions.len(), 3);
    }

    #[test]
    fn call_builder_into_action() {
        let action = test_builder()
            .call("setup")
            .args(serde_json::json!({"admin": "alice.testnet"}))
            .gas(Gas::from_tgas(50))
            .deposit(NearToken::from_near(1))
            .into_action();

        match &action {
            Action::FunctionCall(fc) => {
                assert_eq!(fc.method_name, "setup");
                assert_eq!(fc.gas, Gas::from_tgas(50));
                assert_eq!(fc.deposit, NearToken::from_near(1));
            }
            other => panic!("expected FunctionCall, got {:?}", other),
        }
    }

    #[test]
    fn call_builder_into_action_compose() {
        let action1 = test_builder()
            .call("method_a")
            .gas(Gas::from_tgas(50))
            .into_action();

        let action2 = test_builder()
            .call("method_b")
            .deposit(NearToken::from_near(1))
            .into_action();

        let builder = test_builder().add_action(action1).add_action(action2);

        assert_eq!(builder.actions.len(), 2);
    }
}