near_primitives_core/
global_contract.rs

1use crate::account::AccountContract;
2use crate::hash::CryptoHash;
3use borsh::{BorshDeserialize, BorshSerialize};
4use near_account_id::AccountId;
5use near_schema_checker_lib::ProtocolSchema;
6use serde_with::serde_as;
7use std::fmt;
8
9#[serde_as]
10#[derive(
11    BorshSerialize,
12    BorshDeserialize,
13    serde::Serialize,
14    serde::Deserialize,
15    Hash,
16    PartialEq,
17    Eq,
18    Clone,
19    ProtocolSchema,
20    Debug,
21)]
22#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
23#[borsh(use_discriminant = true)]
24#[repr(u8)]
25pub enum GlobalContractIdentifier {
26    CodeHash(CryptoHash) = 0,
27    AccountId(AccountId) = 1,
28}
29
30impl GlobalContractIdentifier {
31    pub fn len(&self) -> usize {
32        match self {
33            GlobalContractIdentifier::CodeHash(_) => 32,
34            GlobalContractIdentifier::AccountId(account_id) => account_id.len(),
35        }
36    }
37}
38
39/// Extract [`GlobalContractIdentifier`] out of [`AccountContract`] if it represents a global
40/// contract.
41///
42/// If conversion is not possible, the conversion error can be inspected to obtain information
43/// about the local error.
44impl TryFrom<AccountContract> for GlobalContractIdentifier {
45    type Error = ContractIsLocalError;
46    fn try_from(value: AccountContract) -> Result<Self, Self::Error> {
47        match value {
48            AccountContract::None => Err(ContractIsLocalError::NotDeployed),
49            AccountContract::Local(h) => Err(ContractIsLocalError::Deployed(h)),
50            AccountContract::Global(h) => Ok(GlobalContractIdentifier::CodeHash(h)),
51            AccountContract::GlobalByAccount(a) => Ok(GlobalContractIdentifier::AccountId(a)),
52        }
53    }
54}
55
56#[derive(Debug)]
57pub enum ContractIsLocalError {
58    NotDeployed,
59    Deployed(CryptoHash),
60}
61
62impl std::error::Error for ContractIsLocalError {}
63
64impl fmt::Display for ContractIsLocalError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(match self {
67            ContractIsLocalError::NotDeployed => "contract is not deployed",
68            ContractIsLocalError::Deployed(_) => "a locally deployed contract is deployed",
69        })
70    }
71}