near-api-types 0.8.4

Rust types library to interact with NEAR Protocol via RPC API
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
use std::collections::BTreeMap;
use std::str::FromStr;

use crate::AccountId;
use base64::Engine;
use base64::prelude::BASE64_STANDARD;
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};
use serde_with::{base64::Base64, serde_as};

use crate::errors::DataConversionError;
use crate::json::U64;
use crate::transaction::delegate_action::SignedDelegateAction;
use crate::utils::near_gas_as_u64;
use crate::{CryptoHash, NearGas, NearToken, PublicKey, Signature};

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub enum Action {
    /// Create an (sub)account using a transaction `receiver_id` as an ID for
    /// a new account ID must pass validation rules described here
    /// <http://nomicon.io/Primitives/Account.html>.
    CreateAccount(CreateAccountAction),
    /// Sets a Wasm code to a receiver_id
    DeployContract(DeployContractAction),
    /// Call a function on a contract
    FunctionCall(Box<FunctionCallAction>),
    /// Transfer tokens to an account
    Transfer(TransferAction),
    /// Stake tokens from an account to a validator
    /// As a not a developer of staking pool, you should consider using a staking pool contract instead
    Stake(Box<StakeAction>),
    /// Add a key to an account
    AddKey(Box<AddKeyAction>),
    /// Delete a key from an account
    DeleteKey(Box<DeleteKeyAction>),
    /// Delete an account and transfer all tokens to a beneficiary account
    DeleteAccount(DeleteAccountAction),
    /// Delegate your action submission to some relayer that will cover the cost of the transaction
    Delegate(Box<SignedDelegateAction>),
    /// Deploy a global contract
    DeployGlobalContract(DeployGlobalContractAction),
    /// Use a global contract to link code to an account
    UseGlobalContract(Box<UseGlobalContractAction>),
    /// Deploy a deterministic account with global contract and state.
    ///
    /// See [NEP-616](https://github.com/near/NEPs/blob/master/neps/nep-0616.md) for more details
    DeterministicStateInit(Box<DeterministicStateInitAction>),

    /// Creates a gas key for an account to be used for gas payments
    ///
    /// See [NEP-611](https://github.com/near/NEPs/blob/master/neps/nep-0611.md) for more details
    AddGasKey(Box<AddGasKeyAction>),
    /// Deletes a gas key for an account
    ///
    /// See [NEP-611](https://github.com/near/NEPs/blob/master/neps/nep-0611.md) for more details
    DeleteGasKey(Box<DeleteGasKeyAction>),
    /// Transfers tokens to a gas key
    ///
    /// See [NEP-611](https://github.com/near/NEPs/blob/master/neps/nep-0611.md) for more details
    TransferToGasKey(Box<TransferToGasKeyAction>),
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct DeterministicStateInitAction {
    pub state_init: DeterministicAccountStateInit,
    pub deposit: NearToken,
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
#[borsh(use_discriminant = true)]
#[repr(u8)]
pub enum DeterministicAccountStateInit {
    V1(DeterministicAccountStateInitV1),
}

#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct DeterministicAccountStateInitV1 {
    pub code: GlobalContractIdentifier,
    #[serde_as(as = "BTreeMap<Base64, Base64>")]
    pub data: BTreeMap<Vec<u8>, Vec<u8>>,
}

impl TryFrom<near_openapi_types::DeterministicStateInitAction> for DeterministicStateInitAction {
    type Error = DataConversionError;
    fn try_from(
        val: near_openapi_types::DeterministicStateInitAction,
    ) -> Result<Self, Self::Error> {
        let near_openapi_types::DeterministicStateInitAction {
            state_init,
            deposit,
        } = val;

        match state_init {
            near_openapi_types::DeterministicAccountStateInit::V1(v1) => Ok(Self {
                state_init: DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
                    code: v1.code.into(),
                    data: v1
                        .data
                        .into_iter()
                        .map(|(k, v)| {
                            Ok::<(Vec<u8>, Vec<u8>), DataConversionError>((
                                BASE64_STANDARD.decode(k)?,
                                BASE64_STANDARD.decode(v)?,
                            ))
                        })
                        .collect::<Result<BTreeMap<Vec<u8>, Vec<u8>>, _>>()?,
                }),
                deposit,
            }),
        }
    }
}

#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct DeployGlobalContractAction {
    #[serde_as(as = "Base64")]
    pub code: Vec<u8>,
    pub deploy_mode: GlobalContractDeployMode,
}

impl TryFrom<near_openapi_types::DeployGlobalContractAction> for DeployGlobalContractAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::DeployGlobalContractAction) -> Result<Self, Self::Error> {
        let near_openapi_types::DeployGlobalContractAction { code, deploy_mode } = val;
        Ok(Self {
            code: BASE64_STANDARD.decode(code)?,
            deploy_mode: deploy_mode.into(),
        })
    }
}
#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct UseGlobalContractAction {
    pub contract_identifier: GlobalContractIdentifier,
}

impl From<near_openapi_types::UseGlobalContractAction> for UseGlobalContractAction {
    fn from(val: near_openapi_types::UseGlobalContractAction) -> Self {
        let near_openapi_types::UseGlobalContractAction {
            contract_identifier,
        } = val;
        Self {
            contract_identifier: contract_identifier.into(),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct CreateAccountAction {}

impl From<near_openapi_types::CreateAccountAction> for CreateAccountAction {
    fn from(_: near_openapi_types::CreateAccountAction) -> Self {
        Self {}
    }
}

#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct DeployContractAction {
    #[serde_as(as = "Base64")]
    pub code: Vec<u8>,
}

impl TryFrom<near_openapi_types::DeployContractAction> for DeployContractAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::DeployContractAction) -> Result<Self, Self::Error> {
        let near_openapi_types::DeployContractAction { code } = val;
        Ok(Self {
            code: BASE64_STANDARD.decode(code)?,
        })
    }
}

#[serde_as]
#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct FunctionCallAction {
    pub method_name: String,
    #[serde_as(as = "Base64")]
    pub args: Vec<u8>,
    #[serde(serialize_with = "near_gas_as_u64::serialize")]
    pub gas: NearGas,
    pub deposit: NearToken,
}

impl TryFrom<near_openapi_types::FunctionCallAction> for FunctionCallAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::FunctionCallAction) -> Result<Self, Self::Error> {
        let near_openapi_types::FunctionCallAction {
            method_name,
            args,
            gas,
            deposit,
        } = val;
        Ok(Self {
            method_name,
            args: BASE64_STANDARD.decode(args)?,
            gas,
            deposit,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct TransferAction {
    pub deposit: NearToken,
}

impl TryFrom<near_openapi_types::TransferAction> for TransferAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::TransferAction) -> Result<Self, Self::Error> {
        let near_openapi_types::TransferAction { deposit } = val;
        Ok(Self { deposit })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct StakeAction {
    /// Amount of tokens to stake.
    pub stake: NearToken,
    /// Validator key which will be used to sign transactions on behalf of signer_id
    pub public_key: PublicKey,
}

impl TryFrom<near_openapi_types::StakeAction> for StakeAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::StakeAction) -> Result<Self, Self::Error> {
        let near_openapi_types::StakeAction { public_key, stake } = val;
        Ok(Self {
            public_key: public_key.try_into()?,
            stake,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct AddGasKeyAction {
    pub public_key: PublicKey,
    pub num_nonces: u32,
    pub permission: AccessKeyPermission,
}

impl TryFrom<near_openapi_types::AddGasKeyAction> for AddGasKeyAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::AddGasKeyAction) -> Result<Self, Self::Error> {
        let near_openapi_types::AddGasKeyAction {
            public_key,
            num_nonces,
            permission,
        } = val;
        Ok(Self {
            public_key: public_key.try_into()?,
            num_nonces,
            permission: permission.try_into()?,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct DeleteGasKeyAction {
    pub public_key: PublicKey,
}

impl TryFrom<near_openapi_types::DeleteGasKeyAction> for DeleteGasKeyAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::DeleteGasKeyAction) -> Result<Self, Self::Error> {
        let near_openapi_types::DeleteGasKeyAction { public_key } = val;
        Ok(Self {
            public_key: public_key.try_into()?,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct TransferToGasKeyAction {
    pub public_key: PublicKey,
    pub deposit: NearToken,
}

impl TryFrom<near_openapi_types::TransferToGasKeyAction> for TransferToGasKeyAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::TransferToGasKeyAction) -> Result<Self, Self::Error> {
        let near_openapi_types::TransferToGasKeyAction {
            public_key,
            deposit,
        } = val;
        Ok(Self {
            public_key: public_key.try_into()?,
            deposit,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct AddKeyAction {
    /// A public key which will be associated with an access_key
    pub public_key: PublicKey,
    /// An access key with the permission
    pub access_key: AccessKey,
}

impl TryFrom<near_openapi_types::AddKeyAction> for AddKeyAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::AddKeyAction) -> Result<Self, Self::Error> {
        let near_openapi_types::AddKeyAction {
            public_key,
            access_key,
        } = val;
        Ok(Self {
            public_key: public_key.try_into()?,
            access_key: access_key.try_into()?,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct AccessKey {
    /// Nonce for this access key, used for tx nonce generation. When access key is created, nonce
    /// is set to `(block_height - 1) * 1e6` to avoid tx hash collision on access key re-creation.
    /// See <https://github.com/near/nearcore/issues/3779> for more details.
    pub nonce: U64,
    /// Defines permissions for this access key.
    pub permission: AccessKeyPermission,
}

impl TryFrom<near_openapi_types::AccessKeyView> for AccessKey {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::AccessKeyView) -> Result<Self, Self::Error> {
        let near_openapi_types::AccessKeyView { nonce, permission } = val;
        Ok(Self {
            nonce: U64(nonce),
            permission: permission.try_into()?,
        })
    }
}

impl TryFrom<near_openapi_types::AccessKey> for AccessKey {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::AccessKey) -> Result<Self, Self::Error> {
        let near_openapi_types::AccessKey { nonce, permission } = val;
        Ok(Self {
            nonce: U64(nonce),
            permission: permission.try_into()?,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub enum AccessKeyPermission {
    FunctionCall(FunctionCallPermission),
    /// Grants full access to the account.
    /// NOTE: It's used to replace account-level public keys.
    FullAccess,
}

impl TryFrom<near_openapi_types::AccessKeyPermissionView> for AccessKeyPermission {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::AccessKeyPermissionView) -> Result<Self, Self::Error> {
        match val {
            near_openapi_types::AccessKeyPermissionView::FunctionCall {
                allowance,
                method_names,
                receiver_id,
            } => Ok(Self::FunctionCall(FunctionCallPermission {
                allowance,
                receiver_id,
                method_names,
            })),
            near_openapi_types::AccessKeyPermissionView::FullAccess => Ok(Self::FullAccess),
        }
    }
}

impl TryFrom<near_openapi_types::AccessKeyPermission> for AccessKeyPermission {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::AccessKeyPermission) -> Result<Self, Self::Error> {
        match val {
            near_openapi_types::AccessKeyPermission::FunctionCall(function_call_permission) => {
                Ok(Self::FunctionCall(function_call_permission.try_into()?))
            }
            near_openapi_types::AccessKeyPermission::FullAccess => Ok(Self::FullAccess),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct FunctionCallPermission {
    pub allowance: Option<NearToken>,
    pub receiver_id: String,
    pub method_names: Vec<String>,
}

impl TryFrom<near_openapi_types::FunctionCallPermission> for FunctionCallPermission {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::FunctionCallPermission) -> Result<Self, Self::Error> {
        let near_openapi_types::FunctionCallPermission {
            allowance,
            receiver_id,
            method_names,
        } = val;
        Ok(Self {
            allowance,
            receiver_id,
            method_names,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct DeleteKeyAction {
    /// A public key associated with the access_key to be deleted.
    pub public_key: PublicKey,
}

impl TryFrom<near_openapi_types::DeleteKeyAction> for DeleteKeyAction {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::DeleteKeyAction) -> Result<Self, Self::Error> {
        let near_openapi_types::DeleteKeyAction { public_key } = val;
        Ok(Self {
            public_key: public_key.try_into()?,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub struct DeleteAccountAction {
    pub beneficiary_id: AccountId,
}

impl From<near_openapi_types::DeleteAccountAction> for DeleteAccountAction {
    fn from(val: near_openapi_types::DeleteAccountAction) -> Self {
        let near_openapi_types::DeleteAccountAction { beneficiary_id } = val;
        Self { beneficiary_id }
    }
}

#[derive(
    BorshSerialize,
    BorshDeserialize,
    serde::Serialize,
    serde::Deserialize,
    PartialEq,
    Eq,
    Clone,
    Debug,
)]
#[repr(u8)]
pub enum GlobalContractDeployMode {
    /// Contract is deployed under its code hash.
    /// Users will be able reference it by that hash.
    /// This effectively makes the contract immutable.
    CodeHash,
    /// Contract is deployed under the owner account id.
    /// Users will be able reference it by that account id.
    /// This allows the owner to update the contract for all its users.
    AccountId,
}

impl From<near_openapi_types::GlobalContractDeployMode> for GlobalContractDeployMode {
    fn from(val: near_openapi_types::GlobalContractDeployMode) -> Self {
        match val {
            near_openapi_types::GlobalContractDeployMode::CodeHash => Self::CodeHash,
            near_openapi_types::GlobalContractDeployMode::AccountId => Self::AccountId,
        }
    }
}
#[derive(Serialize, Deserialize, Debug, Clone, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub enum GlobalContractIdentifier {
    CodeHash(CryptoHash),
    AccountId(AccountId),
}

impl From<near_openapi_types::GlobalContractIdentifier> for GlobalContractIdentifier {
    fn from(val: near_openapi_types::GlobalContractIdentifier) -> Self {
        match val {
            near_openapi_types::GlobalContractIdentifier::CodeHash(code_hash) => {
                Self::CodeHash(code_hash.into())
            }
            near_openapi_types::GlobalContractIdentifier::AccountId(account_id) => {
                Self::AccountId(account_id)
            }
        }
    }
}

impl From<near_openapi_types::GlobalContractIdentifierView> for GlobalContractIdentifier {
    fn from(val: near_openapi_types::GlobalContractIdentifierView) -> Self {
        match val {
            near_openapi_types::GlobalContractIdentifierView::CryptoHash(code_hash) => {
                Self::CodeHash(code_hash.into())
            }
            near_openapi_types::GlobalContractIdentifierView::AccountId(account_id) => {
                Self::AccountId(account_id)
            }
        }
    }
}

impl TryFrom<near_openapi_types::ActionView> for Action {
    type Error = DataConversionError;
    fn try_from(val: near_openapi_types::ActionView) -> Result<Self, Self::Error> {
        match val {
            near_openapi_types::ActionView::DeterministicStateInit {
                code,
                data,
                deposit,
            } => Ok(Self::DeterministicStateInit(Box::new(
                DeterministicStateInitAction {
                    state_init: DeterministicAccountStateInit::V1(
                        DeterministicAccountStateInitV1 {
                            code: code.into(),
                            data: data
                                .into_iter()
                                .map(|(k, v)| {
                                    Ok::<(Vec<u8>, Vec<u8>), DataConversionError>((
                                        BASE64_STANDARD.decode(k)?,
                                        BASE64_STANDARD.decode(v)?,
                                    ))
                                })
                                .collect::<Result<BTreeMap<Vec<u8>, Vec<u8>>, _>>()?,
                        },
                    ),
                    deposit,
                },
            ))),
            near_openapi_types::ActionView::CreateAccount => {
                Ok(Self::CreateAccount(CreateAccountAction {}))
            }
            near_openapi_types::ActionView::DeployContract { code } => {
                Ok(Self::DeployContract(DeployContractAction {
                    code: BASE64_STANDARD.decode(code)?,
                }))
            }
            near_openapi_types::ActionView::FunctionCall {
                method_name,
                args,
                gas,
                deposit,
            } => Ok(Self::FunctionCall(Box::new(FunctionCallAction {
                method_name,
                args: BASE64_STANDARD.decode(args.0)?,
                gas,
                deposit,
            }))),
            near_openapi_types::ActionView::Transfer { deposit } => {
                Ok(Self::Transfer(TransferAction { deposit }))
            }
            near_openapi_types::ActionView::Stake { public_key, stake } => {
                Ok(Self::Stake(Box::new(StakeAction {
                    public_key: public_key.try_into()?,
                    stake,
                })))
            }
            near_openapi_types::ActionView::AddKey {
                access_key,
                public_key,
            } => Ok(Self::AddKey(Box::new(AddKeyAction {
                public_key: public_key.try_into()?,
                access_key: access_key.try_into()?,
            }))),
            near_openapi_types::ActionView::DeleteKey { public_key } => {
                Ok(Self::DeleteKey(Box::new(DeleteKeyAction {
                    public_key: public_key.try_into()?,
                })))
            }
            near_openapi_types::ActionView::DeleteAccount { beneficiary_id } => {
                Ok(Self::DeleteAccount(DeleteAccountAction { beneficiary_id }))
            }
            near_openapi_types::ActionView::Delegate {
                delegate_action,
                signature,
            } => Ok(Self::Delegate(Box::new(SignedDelegateAction {
                delegate_action: delegate_action.try_into()?,
                signature: Signature::from_str(&signature)?,
            }))),
            near_openapi_types::ActionView::DeployGlobalContract { code } => {
                Ok(Self::DeployGlobalContract(DeployGlobalContractAction {
                    code: BASE64_STANDARD.decode(code)?,
                    deploy_mode: GlobalContractDeployMode::CodeHash,
                }))
            }
            near_openapi_types::ActionView::DeployGlobalContractByAccountId { code } => {
                Ok(Self::DeployGlobalContract(DeployGlobalContractAction {
                    code: BASE64_STANDARD.decode(code)?,
                    deploy_mode: GlobalContractDeployMode::AccountId,
                }))
            }
            near_openapi_types::ActionView::UseGlobalContract { code_hash } => {
                Ok(Self::UseGlobalContract(Box::new(UseGlobalContractAction {
                    contract_identifier: GlobalContractIdentifier::CodeHash(code_hash.into()),
                })))
            }
            near_openapi_types::ActionView::UseGlobalContractByAccountId { account_id } => {
                Ok(Self::UseGlobalContract(Box::new(UseGlobalContractAction {
                    contract_identifier: GlobalContractIdentifier::AccountId(account_id),
                })))
            }
            near_openapi_types::ActionView::AddGasKey {
                num_nonces,
                permission,
                public_key,
            } => Ok(Self::AddGasKey(Box::new(AddGasKeyAction {
                public_key: public_key.try_into()?,
                num_nonces,
                permission: permission.try_into()?,
            }))),
            near_openapi_types::ActionView::DeleteGasKey { public_key } => {
                Ok(Self::DeleteGasKey(Box::new(DeleteGasKeyAction {
                    public_key: public_key.try_into()?,
                })))
            }
            near_openapi_types::ActionView::TransferToGasKey {
                amount: deposit,
                public_key,
            } => Ok(Self::TransferToGasKey(Box::new(TransferToGasKeyAction {
                public_key: public_key.try_into()?,
                deposit,
            }))),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::sync::Arc;

    use super::*;
    use crate::crypto::{ED25519_PUBLIC_KEY_LENGTH, public_key::ED25519PublicKey};
    use crate::transaction::delegate_action::{DelegateAction, NonDelegateAction};
    use near_primitives::action as npa;
    use near_primitives::deterministic_account_id::{
        DeterministicAccountStateInit as npaDeterministicAccountStateInit,
        DeterministicAccountStateInitV1 as npaDeterministicAccountStateInitV1,
    };
    use near_primitives::gas::Gas;
    use near_primitives::global_contract::GlobalContractIdentifier as npaGlobalContractIdentifier;
    use serde_json;

    fn get_actions() -> (Vec<Action>, Vec<npa::Action>) {
        let btreemap = BTreeMap::from([(b"key".to_vec(), b"value".to_vec())]);

        let local_actions = vec![
            Action::CreateAccount(CreateAccountAction {}),
            Action::DeployContract(DeployContractAction {
                code: vec![1, 2, 3],
            }),
            Action::FunctionCall(Box::new(FunctionCallAction {
                method_name: "test".to_string(),
                args: vec![4, 5, 6],
                gas: NearGas::from_gas(1000000),
                deposit: NearToken::from_yoctonear(0),
            })),
            Action::Transfer(TransferAction {
                deposit: NearToken::from_yoctonear(1000000000),
            }),
            Action::Stake(Box::new(StakeAction {
                stake: NearToken::from_yoctonear(100000000),
                public_key: PublicKey::ED25519(ED25519PublicKey([0; ED25519_PUBLIC_KEY_LENGTH])),
            })),
            Action::AddKey(Box::new(AddKeyAction {
                public_key: PublicKey::ED25519(ED25519PublicKey([0; ED25519_PUBLIC_KEY_LENGTH])),
                access_key: AccessKey {
                    nonce: U64(0),
                    permission: AccessKeyPermission::FullAccess,
                },
            })),
            Action::DeleteKey(Box::new(DeleteKeyAction {
                public_key: PublicKey::ED25519(ED25519PublicKey([0; ED25519_PUBLIC_KEY_LENGTH])),
            })),
            Action::DeleteAccount(DeleteAccountAction {
                beneficiary_id: "alice.near".parse().unwrap(),
            }),
            Action::DeployGlobalContract(DeployGlobalContractAction {
                code: vec![7, 8, 9],
                deploy_mode: GlobalContractDeployMode::CodeHash,
            }),
            Action::UseGlobalContract(Box::new(UseGlobalContractAction {
                contract_identifier: GlobalContractIdentifier::AccountId(
                    "global.near".parse().unwrap(),
                ),
            })),
            Action::Delegate(Box::new(SignedDelegateAction {
                delegate_action: DelegateAction {
                    sender_id: "sender.near".parse().unwrap(),
                    receiver_id: "receiver.near".parse().unwrap(),
                    actions: vec![
                        NonDelegateAction::try_from(Action::Transfer(TransferAction {
                            deposit: NearToken::from_yoctonear(1000),
                        }))
                        .unwrap(),
                    ],
                    nonce: 1,
                    max_block_height: 1000,
                    public_key: PublicKey::ED25519(ED25519PublicKey(
                        [0; ED25519_PUBLIC_KEY_LENGTH],
                    )),
                },
                signature: Signature::from_parts(crate::crypto::KeyType::ED25519, &[0u8; 64])
                    .unwrap(),
            })),
            Action::DeterministicStateInit(Box::new(DeterministicStateInitAction {
                state_init: DeterministicAccountStateInit::V1(DeterministicAccountStateInitV1 {
                    code: GlobalContractIdentifier::AccountId("init.near".parse().unwrap()),
                    data: btreemap.clone(),
                }),
                deposit: NearToken::from_yoctonear(5000000000),
            })),
        ];

        let near_primitives_actions = vec![
            npa::Action::CreateAccount(npa::CreateAccountAction {}),
            npa::Action::DeployContract(npa::DeployContractAction {
                code: vec![1, 2, 3],
            }),
            npa::Action::FunctionCall(Box::new(npa::FunctionCallAction {
                method_name: "test".to_string(),
                args: vec![4, 5, 6],
                gas: Gas::from_gas(1000000),
                deposit: NearToken::ZERO,
            })),
            npa::Action::Transfer(npa::TransferAction {
                deposit: NearToken::from_yoctonear(1000000000),
            }),
            npa::Action::Stake(Box::new(npa::StakeAction {
                stake: NearToken::from_yoctonear(100000000),
                public_key: near_crypto::PublicKey::empty(near_crypto::KeyType::ED25519),
            })),
            npa::Action::AddKey(Box::new(npa::AddKeyAction {
                public_key: near_crypto::PublicKey::empty(near_crypto::KeyType::ED25519),
                access_key: near_primitives::account::AccessKey {
                    nonce: 0,
                    permission: near_primitives::account::AccessKeyPermission::FullAccess,
                },
            })),
            npa::Action::DeleteKey(Box::new(npa::DeleteKeyAction {
                public_key: near_crypto::PublicKey::empty(near_crypto::KeyType::ED25519),
            })),
            npa::Action::DeleteAccount(npa::DeleteAccountAction {
                beneficiary_id: "alice.near".parse().unwrap(),
            }),
            npa::Action::DeployGlobalContract(npa::DeployGlobalContractAction {
                code: Arc::new([7, 8, 9]),
                deploy_mode: npa::GlobalContractDeployMode::CodeHash,
            }),
            npa::Action::UseGlobalContract(Box::new(npa::UseGlobalContractAction {
                contract_identifier: npa::GlobalContractIdentifier::AccountId(
                    "global.near".parse().unwrap(),
                ),
            })),
            npa::Action::Delegate(Box::new(npa::delegate::SignedDelegateAction {
                delegate_action: npa::delegate::DelegateAction {
                    sender_id: "sender.near".parse().unwrap(),
                    receiver_id: "receiver.near".parse().unwrap(),
                    actions: vec![
                        npa::delegate::NonDelegateAction::try_from(npa::Action::Transfer(
                            npa::TransferAction {
                                deposit: NearToken::from_yoctonear(1000),
                            },
                        ))
                        .unwrap(),
                    ],
                    nonce: 1,
                    max_block_height: 1000,
                    public_key: near_crypto::PublicKey::empty(near_crypto::KeyType::ED25519),
                },
                signature: near_crypto::Signature::from_parts(
                    near_crypto::KeyType::ED25519,
                    &[0u8; 64],
                )
                .unwrap(),
            })),
            npa::Action::DeterministicStateInit(Box::new(npa::DeterministicStateInitAction {
                state_init: npaDeterministicAccountStateInit::V1(
                    npaDeterministicAccountStateInitV1 {
                        code: npaGlobalContractIdentifier::AccountId("init.near".parse().unwrap()),
                        data: btreemap,
                    },
                ),
                deposit: NearToken::from_yoctonear(5000000000),
            })),
        ];

        (local_actions, near_primitives_actions)
    }

    #[test]
    fn test_action_serialization() {
        let (local_actions, _) = get_actions();

        for action in local_actions {
            let serialized =
                serde_json::to_string(&action).expect("Failed to serialize action to JSON");

            let deserialized: Action =
                serde_json::from_str(&serialized).expect("Failed to deserialize action from JSON");

            assert_eq!(
                action, deserialized,
                "Serialization/Deserialization mismatch: original action: {action:?}, deserialized action: {deserialized:?}"
            );
        }
    }

    #[test]
    fn test_action_borsh_serialization() {
        let (local_actions, _) = get_actions();

        for action in local_actions {
            let serialized = borsh::to_vec(&action).expect("Failed to serialize action to borsh");

            let deserialized: Action = Action::try_from_slice(&serialized)
                .expect("Failed to deserialize action from borsh");

            assert_eq!(
                action, deserialized,
                "Serialization/Deserialization mismatch: original action: {action:?}, deserialized action: {deserialized:?}"
            );
        }
    }

    #[test]
    fn serialization_comparison_with_near_primitives() {
        let (local_actions, near_primitives_actions) = get_actions();

        assert_eq!(
            local_actions.len(),
            near_primitives_actions.len(),
            "Action lists should have the same length"
        );

        for (local_action, np_action) in local_actions.iter().zip(near_primitives_actions.iter()) {
            // Compare borsh serialization - this is what matters for on-chain compatibility
            let local_borsh =
                borsh::to_vec(local_action).expect("Failed to serialize local action to borsh");
            let np_borsh = borsh::to_vec(np_action)
                .expect("Failed to serialize near_primitives action to borsh");

            assert_eq!(local_borsh, np_borsh, "Borsh serialization mismatch");

            // Note: We intentionally diverge from near_primitives JSON serialization format.
            // Our U64 and U128 types serialize as strings for JavaScript compatibility,
            // while near_primitives uses numbers. This is by design - JSON is for API/RPC
            // communication where JavaScript compatibility matters, while Borsh is for
            // on-chain data where binary compatibility is what counts.
        }
    }
}