Skip to content

Commit

Permalink
Use receive name and contract name from concordium-contracts-common
Browse files Browse the repository at this point in the history
  • Loading branch information
limemloh committed Aug 8, 2022
1 parent e8e4d5d commit e59e497
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 122 deletions.
2 changes: 1 addition & 1 deletion concordium-base
37 changes: 13 additions & 24 deletions src/cis2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl From<concordium_contracts_common::NewReceiveNameError> for Cis2TransactionE
pub enum Cis2QueryError {
/// The smart contract receive name is invalid.
#[error("Invalid receive name: {0}")]
InvalidReceiveName(concordium_contracts_common::NewReceiveNameError),
InvalidReceiveName(#[from] concordium_contracts_common::NewReceiveNameError),

/// The parameter for `balanceOf` is invalid.
#[error("Invalid balanceOf parameter: {0}")]
Expand All @@ -84,28 +84,13 @@ pub enum Cis2QueryError {

/// The returned bytes from invoking the smart contract could not be parsed.
#[error("Failed parsing the response.")]
ResponseParseError(concordium_contracts_common::ParseError),
ResponseParseError(#[from] concordium_contracts_common::ParseError),

/// The node rejected the invocation.
#[error("Rejected by the node.")]
NodeRejected(sdk_types::RejectReason),
}

// This is implemented manually, since deriving it using thiserror requires
// `concordium_contracts_common::NewReceiveNameError` to implement
// std::error::Error.
impl From<concordium_contracts_common::NewReceiveNameError> for Cis2QueryError {
fn from(err: concordium_contracts_common::NewReceiveNameError) -> Self {
Self::InvalidReceiveName(err)
}
}

// This is implemented manually, since deriving it using thiserror requires
// `concordium_contracts_common::ParseError` to implement std::error::Error.
impl From<concordium_contracts_common::ParseError> for Cis2QueryError {
fn from(err: concordium_contracts_common::ParseError) -> Self { Self::ResponseParseError(err) }
}

// This is implemented manually, since deriving it using thiserror requires
// `RejectReason` to implement std::error::Error.
impl From<sdk_types::RejectReason> for Cis2QueryError {
Expand Down Expand Up @@ -169,7 +154,7 @@ impl Cis2Contract {
let bytes = concordium_contracts_common::to_bytes(&parameter);
let contract_name = self.contract_name.as_contract_name().contract_name();
let receive_name =
smart_contracts::ReceiveName::try_from(format!("{}.transfer", contract_name))?;
smart_contracts::OwnedReceiveName::try_from(format!("{}.transfer", contract_name))?;

let payload = transactions::Payload::Update {
payload: transactions::UpdateContractPayload {
Expand Down Expand Up @@ -214,8 +199,10 @@ impl Cis2Contract {
let bytes = concordium_contracts_common::to_bytes(&parameter);
let contract_name = self.contract_name.as_contract_name().contract_name();

let receive_name =
smart_contracts::ReceiveName::try_from(format!("{}.updateOperator", contract_name))?;
let receive_name = smart_contracts::OwnedReceiveName::try_from(format!(
"{}.updateOperator",
contract_name
))?;

let payload = transactions::Payload::Update {
payload: transactions::UpdateContractPayload {
Expand Down Expand Up @@ -257,7 +244,7 @@ impl Cis2Contract {
let bytes = concordium_contracts_common::to_bytes(&parameter);
let contract_name = self.contract_name.as_contract_name().contract_name();
let receive_name =
smart_contracts::ReceiveName::try_from(format!("{}.balanceOf", contract_name))?;
smart_contracts::OwnedReceiveName::try_from(format!("{}.balanceOf", contract_name))?;

let contract_context = smart_contracts::ContractContext {
invoker: None,
Expand Down Expand Up @@ -305,7 +292,7 @@ impl Cis2Contract {
let bytes = concordium_contracts_common::to_bytes(&parameter);
let contract_name = self.contract_name.as_contract_name().contract_name();
let receive_name =
smart_contracts::ReceiveName::try_from(format!("{}.operatorOf", contract_name))?;
smart_contracts::OwnedReceiveName::try_from(format!("{}.operatorOf", contract_name))?;

let contract_context = smart_contracts::ContractContext {
invoker: None,
Expand Down Expand Up @@ -352,8 +339,10 @@ impl Cis2Contract {
let parameter = TokenMetadataQueryParams::new(queries)?;
let bytes = concordium_contracts_common::to_bytes(&parameter);
let contract_name = self.contract_name.as_contract_name().contract_name();
let receive_name =
smart_contracts::ReceiveName::try_from(format!("{}.tokenMetadata", contract_name))?;
let receive_name = smart_contracts::OwnedReceiveName::try_from(format!(
"{}.tokenMetadata",
contract_name
))?;

let contract_context = smart_contracts::ContractContext {
invoker: None,
Expand Down
22 changes: 14 additions & 8 deletions src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,7 @@ mod block_summary_parser {
protocol_version: super::ProtocolVersion,
#[serde(flatten)]
// parse first into a value
data: super::BlockSummaryData<serde_json::Value>,
data: super::BlockSummaryData<serde_json::Value>,
}

impl std::convert::TryFrom<BlockSummaryRaw> for super::BlockSummary {
Expand Down Expand Up @@ -1519,7 +1519,7 @@ pub struct ContractInitializedEvent {
/// The amount the instance was initialized with.
pub amount: Amount,
/// The name of the contract.
pub init_name: smart_contracts::InitName,
pub init_name: smart_contracts::OwnedContractName,
/// Any contract events that might have been generated by the contract
/// initialization.
pub events: Vec<smart_contracts::ContractEvent>,
Expand All @@ -1543,7 +1543,7 @@ pub struct InstanceUpdatedEvent {
/// The message passed to method.
pub message: smart_contracts::Parameter,
/// The name of the method that was executed.
pub receive_name: smart_contracts::ReceiveName,
pub receive_name: smart_contracts::OwnedReceiveName,
/// Any contract events that might have been generated by the contract
/// execution.
pub events: Vec<smart_contracts::ContractEvent>,
Expand Down Expand Up @@ -1889,7 +1889,7 @@ pub struct HigherLevelAccessStructure<Kind> {
pub keys: Vec<UpdatePublicKey>,
pub threshold: UpdateKeysThreshold,
#[serde(skip)] // use default when deserializing
pub _phantom: PhantomData<Kind>,
pub _phantom: PhantomData<Kind>,
}

impl<Kind> Deserial for HigherLevelAccessStructure<Kind> {
Expand Down Expand Up @@ -2420,11 +2420,17 @@ pub enum RejectReason {
InvalidAccountReference { contents: AccountAddress },
/// Reference to a non-existing contract init method.
InvalidInitMethod {
contents: (smart_contracts::ModuleRef, smart_contracts::InitName),
contents: (
smart_contracts::ModuleRef,
smart_contracts::OwnedContractName,
),
},
/// Reference to a non-existing contract receive method.
InvalidReceiveMethod {
contents: (smart_contracts::ModuleRef, smart_contracts::ReceiveName),
contents: (
smart_contracts::ModuleRef,
smart_contracts::OwnedReceiveName,
),
},
/// Reference to a non-existing module.
InvalidModuleReference {
Expand All @@ -2450,10 +2456,10 @@ pub enum RejectReason {
RejectedReceive {
reject_reason: i32,
contract_address: ContractAddress,
receive_name: smart_contracts::ReceiveName,
receive_name: smart_contracts::OwnedReceiveName,
parameter: smart_contracts::Parameter,
},
/// Reward account desired by the baker does not exist.
/// Reward account desired by the baker does not exist.
NonExistentRewardAccount { contents: AccountAddress },
/// Proof that the baker owns relevant private keys is not valid.
InvalidProof,
Expand Down
100 changes: 14 additions & 86 deletions src/types/smart_contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use super::{hashes, Address, ContractAddress, ContractTraceElement, Energy, Reje
use crate::constants::*;
/// Re-export of common helper functionality for smart contract, such as types
/// and serialization specific for smart contracts.
pub use concordium_contracts_common;
pub use concordium_contracts_common::{
self, ContractName, OwnedContractName, OwnedReceiveName, ReceiveName,
};
use crypto_common::{
derive,
derive::{Serial, Serialize},
Expand Down Expand Up @@ -71,15 +73,15 @@ pub enum InstanceInfo {
model: Vec<u8>,
owner: AccountAddress,
amount: Amount,
methods: std::collections::BTreeSet<ReceiveName>,
name: InitName,
methods: std::collections::BTreeSet<OwnedReceiveName>,
name: OwnedContractName,
source_module: ModuleRef,
},
V1 {
owner: AccountAddress,
amount: Amount,
methods: std::collections::BTreeSet<ReceiveName>,
name: InitName,
methods: std::collections::BTreeSet<OwnedReceiveName>,
name: OwnedContractName,
source_module: ModuleRef,
},
}
Expand All @@ -103,7 +105,7 @@ impl InstanceInfo {

/// Entrypoints supported by the instance. This returns the full name of the
/// function that is suitable for inclusion in a transaction.
pub fn entrypoints(&self) -> &std::collections::BTreeSet<ReceiveName> {
pub fn entrypoints(&self) -> &std::collections::BTreeSet<OwnedReceiveName> {
match self {
InstanceInfo::V0 { methods, .. } => methods,
InstanceInfo::V1 { methods, .. } => methods,
Expand All @@ -112,7 +114,7 @@ impl InstanceInfo {

/// Get the name of the contract, i.e., the name of the init function that
/// was used to create the instance.
pub fn name(&self) -> &InitName {
pub fn name(&self) -> &OwnedContractName {
match self {
InstanceInfo::V0 { name, .. } => name,
InstanceInfo::V1 { name, .. } => name,
Expand All @@ -131,8 +133,8 @@ mod instance_parser {
model: Option<String>,
owner: AccountAddress,
amount: Amount,
methods: std::collections::BTreeSet<ReceiveName>,
name: InitName,
methods: std::collections::BTreeSet<OwnedReceiveName>,
name: OwnedContractName,
source_module: ModuleRef,
}

Expand Down Expand Up @@ -206,80 +208,6 @@ mod instance_parser {
}
}

#[derive(
SerdeSerialize, SerdeDeserialize, Serial, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Clone,
)]
#[serde(into = "String", try_from = "String")]
/// FIXME: Add structure.
pub struct ReceiveName {
#[string_size_length = 2]
pub name: String,
}

impl From<ReceiveName> for String {
fn from(n: ReceiveName) -> Self { n.name }
}

impl<'a> From<&'a ReceiveName> for &'a str {
fn from(n: &'a ReceiveName) -> Self { n.name.as_str() }
}

impl TryFrom<String> for ReceiveName {
type Error = concordium_contracts_common::NewReceiveNameError;

fn try_from(value: String) -> Result<Self, Self::Error> {
concordium_contracts_common::ReceiveName::is_valid_receive_name(value.as_str())?;
Ok(ReceiveName { name: value })
}
}

impl Deserial for ReceiveName {
fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
let len: u16 = source.get()?;
let name = crypto_common::deserial_string(source, len.into())?;
concordium_contracts_common::ReceiveName::is_valid_receive_name(name.as_str())
.map_err(|x| anyhow::anyhow!(x))?;
Ok(ReceiveName { name })
}
}

#[derive(
SerdeSerialize, SerdeDeserialize, Eq, PartialEq, Ord, PartialOrd, Hash, Serial, Debug, Clone,
)]
#[serde(into = "String", try_from = "String")]
/// FIXME: Add structure.
pub struct InitName {
#[string_size_length = 2]
name: String,
}

impl From<InitName> for String {
fn from(n: InitName) -> Self { n.name }
}

impl<'a> From<&'a InitName> for &'a str {
fn from(n: &'a InitName) -> Self { n.name.as_str() }
}

impl TryFrom<String> for InitName {
type Error = concordium_contracts_common::NewContractNameError;

fn try_from(value: String) -> Result<Self, Self::Error> {
concordium_contracts_common::ContractName::is_valid_contract_name(value.as_str())?;
Ok(InitName { name: value })
}
}

impl Deserial for InitName {
fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
let len: u16 = source.get()?;
let name = crypto_common::deserial_string(source, len.into())?;
concordium_contracts_common::ContractName::is_valid_contract_name(name.as_str())
.map_err(|x| anyhow::anyhow!(x))?;
Ok(InitName { name })
}
}

// FIXME: Move to Wasm, and check size also in JSON deserialization
#[derive(
SerdeSerialize, SerdeDeserialize, derive::Serial, Debug, Clone, AsRef, Into, From, Default,
Expand Down Expand Up @@ -380,7 +308,7 @@ pub struct ContractContext {
#[serde(default = "return_zero_amount")]
pub amount: Amount,
/// Which entrypoint to invoke.
pub method: ReceiveName,
pub method: OwnedReceiveName,
/// And with what parameter.
#[serde(default)]
pub parameter: Parameter,
Expand All @@ -407,11 +335,11 @@ impl ContractContext {
/// parameter
/// - the [`energy`](ContractContext::energy) is set to
/// [`DEFAULT_INVOKE_ENERGY`]
pub fn new(contract: ContractAddress, method: ReceiveName) -> Self {
pub fn new(contract: ContractAddress, method: OwnedReceiveName) -> Self {
Self {
invoker: None,
contract,
amount: Amount::from_micro_ccd(0),
amount: Amount::zero(),
method,
parameter: Parameter::default(),
energy: DEFAULT_INVOKE_ENERGY,
Expand Down
6 changes: 3 additions & 3 deletions src/types/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ pub enum ConfigureBakerKeysMarker {}
/// markers: `AddBakerKeysMarker` and `UpdateBakerKeysMarker`.
pub struct BakerKeysPayload<V> {
#[serde(skip)] // use default when deserializing
phantom: PhantomData<V>,
phantom: PhantomData<V>,
/// New public key for participating in the election lottery.
pub election_verify_key: BakerElectionVerifyKey,
/// New public key for verifying this baker's signatures.
Expand Down Expand Up @@ -333,7 +333,7 @@ pub struct InitContractPayload {
/// Reference to the module from which to initialize the instance.
pub mod_ref: smart_contracts::ModuleRef,
/// Name of the contract in the module.
pub init_name: smart_contracts::InitName,
pub init_name: smart_contracts::OwnedContractName,
/// Message to invoke the initialization method with.
pub param: smart_contracts::Parameter,
}
Expand All @@ -348,7 +348,7 @@ pub struct UpdateContractPayload {
/// Address of the contract instance to invoke.
pub address: ContractAddress,
/// Name of the method to invoke on the contract.
pub receive_name: smart_contracts::ReceiveName,
pub receive_name: smart_contracts::OwnedReceiveName,
/// Message to send to the contract instance.
pub message: smart_contracts::Parameter,
}
Expand Down

0 comments on commit e59e497

Please sign in to comment.