From f46f842c9af81ef613521919a6052748f41d1d56 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 20 Feb 2020 21:17:35 +0200 Subject: [PATCH 01/28] Extend transactions type --- src/external.rs | 47 +++++++++++++------- src/transactions.rs | 105 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 16 deletions(-) create mode 100644 src/transactions.rs diff --git a/src/external.rs b/src/external.rs index 84845b2..4017ccf 100644 --- a/src/external.rs +++ b/src/external.rs @@ -1,18 +1,33 @@ extern "C" { - pub fn __ping(number: usize) -> i64; - pub fn __write_log(msg: *const u8, len: usize) -> i64; - pub fn save_to_storage( - file_ptr: *const u8, - file_len: usize, - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn save_sc_result( - file_ptr: *const u8, - file_len: usize, - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn get_from_storage(file_ptr: *const u8, file_len: usize, data: *mut u8) -> i64; - pub fn get_http(url: *const u8, url_len: usize, body: *mut u8) -> i64; + pub fn __ping(number: usize) -> i64; + pub fn __write_log(msg: *const u8, len: usize) -> i64; + pub fn save_to_storage( + file_ptr: *const u8, + file_len: usize, + data_ptr: *const u8, + data_len: usize, + ) -> i64; + pub fn save_sc_result( + file_ptr: *const u8, + file_len: usize, + data_ptr: *const u8, + data_len: usize, + ) -> i64; + pub fn get_from_storage( + file_ptr: *const u8, + file_len: usize, + data: *mut u8, + ) -> i64; + pub fn get_http( + url: *const u8, + url_len: usize, + body: *mut u8, + ) -> i64; + + pub fn flush() -> i64; + pub fn mosaic_definition( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; } diff --git a/src/transactions.rs b/src/transactions.rs new file mode 100644 index 0000000..9c01e8b --- /dev/null +++ b/src/transactions.rs @@ -0,0 +1,105 @@ +//! Basic Blockchain functions and getters + +use serde::{Deserialize, Serialize}; + +pub type NetworkType = u8; +pub type EntityType = u16; +pub type EntityVersion = u32; +pub type Amount = i64; +pub type Deadline = i64; +pub type PublicAccount = [u8; 32]; +pub type Height = i64; +pub type Hash = [u8; 32]; +pub type Address = [u8; 25]; +pub type NamespaceId = i64; +pub type AliasActionType = u8; +pub type MosaicId = i64; +pub type PubKey = [u8; 32]; +pub type AssetId = u64; +pub type Duration = i64; +pub type MosaicSupplyType = u8; + +#[derive(Debug, Deserialize, Serialize)] +pub struct AbstractTransaction { + pub height: Height, + pub index: uint32, + pub transaction_hash: Option, + pub merkle_component_hash: Option, + pub aggregate_hash: Option, + pub unique_aggregate_hash: Option, + pub aggregate_id: [u8; 32], + + pub network_type: NetworkType, + pub deadline: Option, + pub entity_type: EntityType, + pub version: EntityVersion, + pub max_fee: Amount, + pub signature: [u8; 64], + pub signer: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicDefinition { + pub nonce: u32, + pub owner_public_key: [u32], + pub mosaic_props: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicProperties { + pub supply_mutable: bool, + pub transferable: bool, + pbb divisibility: u8, + pub optional_properties: []MosaicProperty, +} + +pub type MosaicPropertyId = u8; + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicProperty { + pub id: MosaicPropertyId, + pub value: i64, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct AddressAlias { + address: Option
, + namespace_id: Option, + action_type: AliasActionType, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicAlias { + mosaic_id: Option, + namespace_id: Option, + action_type: AliasActionType, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct AddExchangeOffer { + add_offers: Option< []AddOffer>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ExchangeOffer { + offer: Option<[]ExchangeConfirmation>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Transfer { + pub_key: PubKey, + asset_id: AssetId, + amount: i64, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct RemoveExchangeOffer { + remove_offers: Option<[]RemoveOffer>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicSupplyChange{ + asset_id: AssetId, + supply_type: MosaicSupplyType, + delta: Duration, +} From 4bff2ccbed0386e798c0f6085817d6b4990ecacd Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 20 Feb 2020 22:54:24 +0200 Subject: [PATCH 02/28] Extend for most recent transactions types --- Cargo.lock | 149 +++++++++++++-------------------- Cargo.toml | 2 +- src/transactions.rs | 200 ++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 242 insertions(+), 109 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 86bd775..4862237 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,94 +2,78 @@ # It is not intended for manual editing. [[package]] name = "backtrace" -version = "0.3.35" +version = "0.3.44" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "backtrace-sys 0.1.31 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "backtrace-sys 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "backtrace-sys" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "cc 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "cc" -version = "1.0.41" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "cfg-if" -version = "0.1.9" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "failure" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "backtrace 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)", - "failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "backtrace 0.3.44 (registry+https://github.com/rust-lang/crates.io-index)", + "failure_derive 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "failure_derive" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)", - "synstructure 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "synstructure 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "itoa" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libc" -version = "0.2.62" +version = "0.2.66" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "proc-macro2" -version = "0.4.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "proc-macro2" -version = "1.0.1" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "quote" -version = "0.6.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "quote" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -99,73 +83,58 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "ryu" -version = "1.0.0" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "serde" -version = "1.0.99" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde_derive" -version = "1.0.99" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde_json" -version = "1.0.40" +version = "1.0.48" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", - "ryu 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", + "itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "syn" -version = "0.15.44" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "syn" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "synstructure" -version = "0.10.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "unicode-xid" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "unicode-xid" version = "0.2.0" @@ -173,33 +142,29 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "xpx_supercontracts_sdk" -version = "0.1.0" +version = "0.2.0" dependencies = [ - "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)", + "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.48 (registry+https://github.com/rust-lang/crates.io-index)", ] [metadata] -"checksum backtrace 0.3.35 (registry+https://github.com/rust-lang/crates.io-index)" = "1371048253fa3bac6704bfd6bbfc922ee9bdcee8881330d40f308b81cc5adc55" -"checksum backtrace-sys 0.1.31 (registry+https://github.com/rust-lang/crates.io-index)" = "82a830b4ef2d1124a711c71d263c5abdc710ef8e907bd508c88be475cebc422b" -"checksum cc 1.0.41 (registry+https://github.com/rust-lang/crates.io-index)" = "8dae9c4b8fedcae85592ba623c4fd08cfdab3e3b72d6df780c6ead964a69bfff" -"checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" -"checksum failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "795bd83d3abeb9220f257e597aa0080a508b27533824adf336529648f6abf7e2" -"checksum failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1" -"checksum itoa 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "501266b7edd0174f8530248f87f99c88fbe60ca4ef3dd486835b8d8d53136f7f" -"checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba" -"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" -"checksum proc-macro2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4c5c2380ae88876faae57698be9e9775e3544decad214599c3a6266cca6ac802" -"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +"checksum backtrace 0.3.44 (registry+https://github.com/rust-lang/crates.io-index)" = "e4036b9bf40f3cf16aba72a3d65e8a520fc4bafcdc7079aea8f848c58c5b5536" +"checksum backtrace-sys 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "5d6575f128516de27e3ce99689419835fce9643a9b215a14d2b5b685be018491" +"checksum cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)" = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" +"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "f8273f13c977665c5db7eb2b99ae520952fe5ac831ae4cd09d80c4c7042b5ed9" +"checksum failure_derive 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0bc225b78e0391e4b8683440bf2e63c2deeeb2ce5189eab46e2b68c6d3725d08" +"checksum itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" +"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" +"checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" "checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" "checksum rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" -"checksum ryu 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c92464b447c0ee8c4fb3824ecc8383b81717b9f1e74ba2e72540aef7b9f82997" -"checksum serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)" = "fec2851eb56d010dc9a21b89ca53ee75e6528bab60c11e89d38390904982da9f" -"checksum serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)" = "cb4dc18c61206b08dc98216c98faa0232f4337e1e1b8574551d5bad29ea1b425" -"checksum serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)" = "051c49229f282f7c6f3813f8286cc1e3323e8051823fce42c7ea80fe13521704" -"checksum syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)" = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" -"checksum syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "66850e97125af79138385e9b88339cbcd037e3f28ceab8c5ad98e64f0f1f80bf" -"checksum synstructure 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)" = "02353edf96d6e4dc81aea2d8490a7e9db177bf8acb0e951c24940bf866cb313f" -"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8" +"checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" +"checksum serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" +"checksum serde_json 1.0.48 (registry+https://github.com/rust-lang/crates.io-index)" = "9371ade75d4c2d6cb154141b9752cf3781ec9c05e0e5cf35060e1e70ee7b9c25" +"checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" +"checksum synstructure 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "67656ea1dc1b41b1451851562ea232ec2e5a80242139f7e679ceccfb5d61f545" "checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/Cargo.toml b/Cargo.toml index bea5d97..539426f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "xpx_supercontracts_sdk" -version = "0.1.0" +version = "0.2.0" authors = ["ProxymaX Core Development Team"] description = "ProximaX Supercontracts Rust SDK" edition = "2018" diff --git a/src/transactions.rs b/src/transactions.rs index 9c01e8b..031c58a 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -1,6 +1,7 @@ //! Basic Blockchain functions and getters use serde::{Deserialize, Serialize}; +use std::collections::HashMap; pub type NetworkType = u8; pub type EntityType = u16; @@ -18,6 +19,11 @@ pub type PubKey = [u8; 32]; pub type AssetId = u64; pub type Duration = i64; pub type MosaicSupplyType = u8; +pub type MetadataModificationType = u8; +pub type HashType = u8; +pub type Message = [u8]; +pub type OfferType = u8; +pub type TransactionID = [u8; 32]; #[derive(Debug, Deserialize, Serialize)] pub struct AbstractTransaction { @@ -63,43 +69,205 @@ pub struct MosaicProperty { #[derive(Debug, Deserialize, Serialize)] pub struct AddressAlias { - address: Option
, - namespace_id: Option, - action_type: AliasActionType, + pub address: Option
, + pub namespace_id: Option, + pub action_type: AliasActionType, } #[derive(Debug, Deserialize, Serialize)] pub struct MosaicAlias { - mosaic_id: Option, - namespace_id: Option, - action_type: AliasActionType, + pub mosaic_id: Option, + pub namespace_id: Option, + pub action_type: AliasActionType, } #[derive(Debug, Deserialize, Serialize)] pub struct AddExchangeOffer { - add_offers: Option< []AddOffer>, + pub add_offers: Option< []AddOffer >, } #[derive(Debug, Deserialize, Serialize)] pub struct ExchangeOffer { - offer: Option<[]ExchangeConfirmation>, + pub offer: Option<[]ExchangeConfirmation >, } #[derive(Debug, Deserialize, Serialize)] pub struct Transfer { - pub_key: PubKey, - asset_id: AssetId, - amount: i64, + pub pub_key: PubKey, + pub asset_id: AssetId, + pub amount: i64, } #[derive(Debug, Deserialize, Serialize)] pub struct RemoveExchangeOffer { - remove_offers: Option<[]RemoveOffer>, + pub remove_offers: Option<[]RemoveOffer >, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicSupplyChange { + pub asset_id: AssetId, + pub supply_type: MosaicSupplyType, + pub delta: Duration, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct RegisterRootNamespace { + pub namespace_name: String, + pub duration: Duration, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct RegisterSubNamespace { + pub namespace_name: String, + pub parent_id: NamespaceId, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Mosaic { + pub asset_id: AssetId, + pub amount: Amount, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct SecretLock { + pub mosaic: Option, + pub duration: Duration, + pub secret: Option, + pub recipient: Option
, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Proof { + pub data: [u8], +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct SecretProof { + pub hash_type: HashType, + pub proof: Option, + pub recipient: Option
, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct TransferWithNamespace { + pub recipient: Option, + pub mosaics: Option<[]Mosaic >, + pub message: Message, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ModifyMetadataAddress { + pub address: Option
, + pub modifications: Option<[]MetadataModification >, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ModifyMetadataMosaic { + pub mosaic_id: Option, + pub modifications: Option<[]MetadataModification >, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MetadataModification { + modification_type: MetadataModificationType, + key: String, + value: String, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ModifyMetadataNamespace { + pub namespace_id: NamespaceId, + pub modifications: Option<[]MetadataModification >, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct OfferInfo { + pub offer_type: OfferType, + pub owner: Option, + pub mosaic: Option, + pub price_numerator: Amount, + pub price_denominator: Amount, + pub deadline: Height, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct UserExchangeInfo { + pub owner: Option, + pub offers: HashMap>>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetAccountExchangeInfo { + pub account: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetExchangeOfferByAssetId { + pub asset_id: AssetId, + pub offer_type: OfferType, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicInfo { + mosaic_id: Option, + supply: Amount, + height: Height, + owner: Option, + revision: u32, + properties: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetMosaicInfo { + pub mosaic_id: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetMosaicInfos { + pub msc_ids: Option<[]MosaicId >, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicName { + pub mosaic_id: Option, + pub names: [String], +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetMosaicsNames { + pub msc_ids: Option<[]MosaicId >, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransaction { + pub id: TransactionID, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransactions { + pub ids: []TransactionID, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct TransactionStatus { + deadline: Option, + group: String, + status: String, + hash: Option, + height: Height, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransactionStatus { + pub id: TransactionID, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransactionStatuses { + pub ids: []TransactionID, } #[derive(Debug, Deserialize, Serialize)] -pub struct MosaicSupplyChange{ - asset_id: AssetId, - supply_type: MosaicSupplyType, - delta: Duration, +pub struct GetTransactionEffectiveFee { + pub id: TransactionID, } From a1602fb2bfe60028872291ad69bcc0c902357a3f Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 21 Feb 2020 07:59:12 +0200 Subject: [PATCH 03/28] Fix bug for Errors.Enum. Fix transactions type --- src/lib.rs | 1 + src/statuses.rs | 1 + src/transactions.rs | 273 ----------------------------------- src/transactions_type.rs | 304 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 306 insertions(+), 273 deletions(-) create mode 100644 src/transactions_type.rs diff --git a/src/lib.rs b/src/lib.rs index 7980bb7..c6356f0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -67,3 +67,4 @@ pub mod http; pub mod statuses; pub mod storage; pub mod utils; +pub mod transactions; diff --git a/src/statuses.rs b/src/statuses.rs index ae2aa6f..6225d65 100644 --- a/src/statuses.rs +++ b/src/statuses.rs @@ -46,6 +46,7 @@ impl From for ExecutionError { } } +#[repr(i8)] #[derive(Debug, Fail)] pub enum Error { #[fail(display = "Failed serialize the given data structure as a JSON byte ")] diff --git a/src/transactions.rs b/src/transactions.rs index 031c58a..e69de29 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -1,273 +0,0 @@ -//! Basic Blockchain functions and getters - -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; - -pub type NetworkType = u8; -pub type EntityType = u16; -pub type EntityVersion = u32; -pub type Amount = i64; -pub type Deadline = i64; -pub type PublicAccount = [u8; 32]; -pub type Height = i64; -pub type Hash = [u8; 32]; -pub type Address = [u8; 25]; -pub type NamespaceId = i64; -pub type AliasActionType = u8; -pub type MosaicId = i64; -pub type PubKey = [u8; 32]; -pub type AssetId = u64; -pub type Duration = i64; -pub type MosaicSupplyType = u8; -pub type MetadataModificationType = u8; -pub type HashType = u8; -pub type Message = [u8]; -pub type OfferType = u8; -pub type TransactionID = [u8; 32]; - -#[derive(Debug, Deserialize, Serialize)] -pub struct AbstractTransaction { - pub height: Height, - pub index: uint32, - pub transaction_hash: Option, - pub merkle_component_hash: Option, - pub aggregate_hash: Option, - pub unique_aggregate_hash: Option, - pub aggregate_id: [u8; 32], - - pub network_type: NetworkType, - pub deadline: Option, - pub entity_type: EntityType, - pub version: EntityVersion, - pub max_fee: Amount, - pub signature: [u8; 64], - pub signer: Option, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicDefinition { - pub nonce: u32, - pub owner_public_key: [u32], - pub mosaic_props: Option, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicProperties { - pub supply_mutable: bool, - pub transferable: bool, - pbb divisibility: u8, - pub optional_properties: []MosaicProperty, -} - -pub type MosaicPropertyId = u8; - -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicProperty { - pub id: MosaicPropertyId, - pub value: i64, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct AddressAlias { - pub address: Option
, - pub namespace_id: Option, - pub action_type: AliasActionType, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicAlias { - pub mosaic_id: Option, - pub namespace_id: Option, - pub action_type: AliasActionType, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct AddExchangeOffer { - pub add_offers: Option< []AddOffer >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct ExchangeOffer { - pub offer: Option<[]ExchangeConfirmation >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct Transfer { - pub pub_key: PubKey, - pub asset_id: AssetId, - pub amount: i64, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct RemoveExchangeOffer { - pub remove_offers: Option<[]RemoveOffer >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicSupplyChange { - pub asset_id: AssetId, - pub supply_type: MosaicSupplyType, - pub delta: Duration, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct RegisterRootNamespace { - pub namespace_name: String, - pub duration: Duration, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct RegisterSubNamespace { - pub namespace_name: String, - pub parent_id: NamespaceId, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct Mosaic { - pub asset_id: AssetId, - pub amount: Amount, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct SecretLock { - pub mosaic: Option, - pub duration: Duration, - pub secret: Option, - pub recipient: Option
, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct Proof { - pub data: [u8], -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct SecretProof { - pub hash_type: HashType, - pub proof: Option, - pub recipient: Option
, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct TransferWithNamespace { - pub recipient: Option, - pub mosaics: Option<[]Mosaic >, - pub message: Message, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct ModifyMetadataAddress { - pub address: Option
, - pub modifications: Option<[]MetadataModification >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct ModifyMetadataMosaic { - pub mosaic_id: Option, - pub modifications: Option<[]MetadataModification >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct MetadataModification { - modification_type: MetadataModificationType, - key: String, - value: String, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct ModifyMetadataNamespace { - pub namespace_id: NamespaceId, - pub modifications: Option<[]MetadataModification >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct OfferInfo { - pub offer_type: OfferType, - pub owner: Option, - pub mosaic: Option, - pub price_numerator: Amount, - pub price_denominator: Amount, - pub deadline: Height, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct UserExchangeInfo { - pub owner: Option, - pub offers: HashMap>>, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetAccountExchangeInfo { - pub account: Option, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetExchangeOfferByAssetId { - pub asset_id: AssetId, - pub offer_type: OfferType, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicInfo { - mosaic_id: Option, - supply: Amount, - height: Height, - owner: Option, - revision: u32, - properties: Option, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetMosaicInfo { - pub mosaic_id: Option, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetMosaicInfos { - pub msc_ids: Option<[]MosaicId >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicName { - pub mosaic_id: Option, - pub names: [String], -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetMosaicsNames { - pub msc_ids: Option<[]MosaicId >, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetTransaction { - pub id: TransactionID, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetTransactions { - pub ids: []TransactionID, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct TransactionStatus { - deadline: Option, - group: String, - status: String, - hash: Option, - height: Height, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetTransactionStatus { - pub id: TransactionID, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetTransactionStatuses { - pub ids: []TransactionID, -} - -#[derive(Debug, Deserialize, Serialize)] -pub struct GetTransactionEffectiveFee { - pub id: TransactionID, -} diff --git a/src/transactions_type.rs b/src/transactions_type.rs new file mode 100644 index 0000000..f46e725 --- /dev/null +++ b/src/transactions_type.rs @@ -0,0 +1,304 @@ +//! Basic Blockchain functions and getters + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +pub type NetworkType = u8; +pub type EntityType = u16; +pub type EntityVersion = u32; +pub type Amount = i64; +pub type Deadline = i64; +pub type PublicAccount = [u8; 32]; +pub type Height = i64; +pub type Hash = [u8; 32]; +pub type Address = [u8; 25]; +pub type NamespaceId = i64; +pub type AliasActionType = u8; +pub type MosaicId = i64; +pub type PubKey = [u8; 32]; +pub type AssetId = u64; +pub type Duration = i64; +pub type MosaicSupplyType = u8; +pub type MetadataModificationType = u8; +pub type HashType = u8; +pub type Message = Vec; +pub type OfferType = u8; +pub type TransactionID = [u8; 32]; + +pub type Signature = [u8; 64]; + +#[derive(Debug, Deserialize, Serialize)] +pub struct AbstractTransaction { + pub height: Height, + pub index: u32, + pub transaction_hash: Option, + pub merkle_component_hash: Option, + pub aggregate_hash: Option, + pub unique_aggregate_hash: Option, + pub aggregate_id: Vec, + + pub network_type: NetworkType, + pub deadline: Option, + pub entity_type: EntityType, + pub version: EntityVersion, + pub max_fee: Amount, + pub signature: Vec, + pub signer: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicDefinition { + pub nonce: u32, + pub owner_public_key: Vec, + pub mosaic_props: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicProperties { + pub supply_mutable: bool, + pub transferable: bool, + pub divisibility: u8, + pub optional_properties: Vec, +} + +pub type MosaicPropertyId = u8; + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicProperty { + pub id: MosaicPropertyId, + pub value: i64, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct AddressAlias { + pub address: Option
, + pub namespace_id: Option, + pub action_type: AliasActionType, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicAlias { + pub mosaic_id: Option, + pub namespace_id: Option, + pub action_type: AliasActionType, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct AddExchangeOffer { + pub add_offers: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ExchangeConfirmation { + offer_type: OfferType, + mosaic: Option, + cost: Amount, + owner: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct AddOffer { + pub offer_type: OfferType, + pub mosaic: Option, + pub cost: Amount, + pub duration: Duration, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ExchangeOffer { + pub offer: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Transfer { + pub pub_key: PubKey, + pub asset_id: AssetId, + pub amount: i64, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct RemoveOffer { + offer_type: OfferType, + asset_id: AssetId, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct RemoveExchangeOffer { + pub remove_offers: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicSupplyChange { + pub asset_id: AssetId, + pub supply_type: MosaicSupplyType, + pub delta: Duration, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct RegisterRootNamespace { + pub namespace_name: String, + pub duration: Duration, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct RegisterSubNamespace { + pub namespace_name: String, + pub parent_id: NamespaceId, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Mosaic { + pub asset_id: AssetId, + pub amount: Amount, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Secret { + pub hash: Hash, + pub hash_type: HashType, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct SecretLock { + pub mosaic: Option, + pub duration: Duration, + pub secret: Option, + pub recipient: Option
, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Proof { + pub data: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct SecretProof { + pub hash_type: HashType, + pub proof: Option, + pub recipient: Option
, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct TransferWithNamespace { + pub recipient: Option, + pub mosaics: Option>, + pub message: Message, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ModifyMetadataAddress { + pub address: Option
, + pub modifications: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ModifyMetadataMosaic { + pub mosaic_id: Option, + pub modifications: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MetadataModification { + modification_type: MetadataModificationType, + key: String, + value: String, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct ModifyMetadataNamespace { + pub namespace_id: NamespaceId, + pub modifications: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct OfferInfo { + pub offer_type: OfferType, + pub owner: Option, + pub mosaic: Option, + pub price_numerator: Amount, + pub price_denominator: Amount, + pub deadline: Height, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct UserExchangeInfo { + pub owner: Option, + pub offers: HashMap>>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetAccountExchangeInfo { + pub account: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetExchangeOfferByAssetId { + pub asset_id: AssetId, + pub offer_type: OfferType, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicInfo { + mosaic_id: Option, + supply: Amount, + height: Height, + owner: Option, + revision: u32, + properties: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetMosaicInfo { + pub mosaic_id: Option, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetMosaicInfos { + pub msc_ids: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicName { + pub mosaic_id: Option, + pub names: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetMosaicsNames { + pub msc_ids: Option>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransaction { + pub id: TransactionID, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransactions { + pub ids: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct TransactionStatus { + deadline: Option, + group: String, + status: String, + hash: Option, + height: Height, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransactionStatus { + pub id: TransactionID, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransactionStatuses { + pub ids: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct GetTransactionEffectiveFee { + pub id: TransactionID, +} From 73af74ad99eeba515766b713c4fd18f088fc0198 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 21 Feb 2020 09:51:20 +0200 Subject: [PATCH 04/28] Added functions: flush mosaic_definition Fixed tests --- examples/debug.rs | 2 +- src/http.rs | 4 ++-- src/lib.rs | 3 ++- src/statuses.rs | 4 ++++ src/storage.rs | 8 ++++---- src/transactions.rs | 32 ++++++++++++++++++++++++++++++++ src/transactions_type.rs | 14 +++++++++++++- src/utils.rs | 4 ++-- 8 files changed, 60 insertions(+), 11 deletions(-) diff --git a/examples/debug.rs b/examples/debug.rs index f0de803..ef045cf 100644 --- a/examples/debug.rs +++ b/examples/debug.rs @@ -5,6 +5,6 @@ use xpx_supercontracts_sdk::utils::debug_message; #[no_mangle] pub extern "C" fn app_main() -> i64 { let msg = "Debug message".to_string(); - debug_message(msg); + debug_message(&msg); STATUS_SUCCESS } diff --git a/src/http.rs b/src/http.rs index 26ccaed..627794f 100644 --- a/src/http.rs +++ b/src/http.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; use crate::external; -use crate::statuses::{Error, Result}; +use crate::statuses::{Error, MultipleFunctionResult}; /// HTTP request data #[derive(Debug, Deserialize, Serialize)] @@ -30,7 +30,7 @@ struct HttpResponse { /// ```rust,no_run /// use xpx_supercontracts_sdk::http::http_get; /// ``` -pub fn http_get(request: &HttpRequest) -> Result> { +pub fn http_get(request: &HttpRequest) -> MultipleFunctionResult { let request_body = serde_json::to_vec(&request); if request_body.is_err() { return Err(Error::SerializeJson); diff --git a/src/lib.rs b/src/lib.rs index c6356f0..a0415e2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -52,7 +52,7 @@ //! let ping_number: usize = 99; //! let pong_result = ping(ping_number); //! let msg = format!("Supercontract Ping: {:?} and Pong: {:?}", ping_number, pong_result); -//! debug_message(msg); +//! debug_message(&msg); //! return 0; //! } //! ``` @@ -68,3 +68,4 @@ pub mod statuses; pub mod storage; pub mod utils; pub mod transactions; +pub mod transactions_type; diff --git a/src/statuses.rs b/src/statuses.rs index 6225d65..2e82105 100644 --- a/src/statuses.rs +++ b/src/statuses.rs @@ -2,6 +2,8 @@ use std::result; pub type Result = result::Result; +pub type FunctionResult = Result; +pub type MultipleFunctionResult = Result>; /// Success status of function execution /// when function don't has own result. @@ -51,4 +53,6 @@ impl From for ExecutionError { pub enum Error { #[fail(display = "Failed serialize the given data structure as a JSON byte ")] SerializeJson = -1, + #[fail(display = "Failed deserialize the given byte data to structure")] + DeserializeJson = -2, } diff --git a/src/storage.rs b/src/storage.rs index ded26f1..cc4ef33 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -4,7 +4,7 @@ //! So it should be relative path like: `path/to/my/file.json` use crate::external; -use crate::statuses::Result; +use crate::statuses::{FunctionResult, MultipleFunctionResult}; /// Save data to Storage. Return result status. /// File always located inside `/root/supercontracts/` directory. @@ -17,7 +17,7 @@ use crate::statuses::Result; /// let result_status = storage_save(&"some_file.json".to_string(), data); /// assert_eq!(result_status.unwrap(), 0); /// ``` -pub fn storage_save(file_name: &String, data: &[u8]) -> Result { +pub fn storage_save(file_name: &String, data: &[u8]) -> FunctionResult { let file_name = file_name.as_bytes(); return unsafe { let res = external::save_to_storage( @@ -41,7 +41,7 @@ pub fn storage_save(file_name: &String, data: &[u8]) -> Result { /// let file_data = storage_get(&"some_file.json".to_string()); /// assert_eq!(file_data.unwrap(), vec![0]); /// ``` -pub fn storage_get(file_name: &String) -> Result> { +pub fn storage_get(file_name: &String) -> MultipleFunctionResult { let file_name = file_name.as_bytes(); let data: &mut Vec = &mut vec![]; return unsafe { @@ -67,7 +67,7 @@ pub fn storage_get(file_name: &String) -> Result> { /// let result_status = save_result(&"some_file.json".to_string(), data); /// assert_eq!(result_status.unwrap(), 0); /// ``` -pub fn save_result(file_name: &String, data: &[u8]) -> Result { +pub fn save_result(file_name: &String, data: &[u8]) -> FunctionResult { let file_name = file_name.as_bytes(); return unsafe { let res = external::save_sc_result( diff --git a/src/transactions.rs b/src/transactions.rs index e69de29..f0b8f29 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -0,0 +1,32 @@ +//! Basic Blockchain functions and getters + +use crate::external; +use crate::statuses::{Error, FunctionResult, Result}; +use crate::transactions_type::{ + MosaicDefinition, + MosaicDefinitionTransaction, +}; + +pub fn flush() -> FunctionResult { + return unsafe { Ok(external::flush()) }; +} + +pub fn mosaic_definition(params: &MosaicDefinition) -> Result { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = external::mosaic_definition(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} diff --git a/src/transactions_type.rs b/src/transactions_type.rs index f46e725..3cb1a88 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -1,4 +1,4 @@ -//! Basic Blockchain functions and getters +//! Basic Transactions types for Blockchain functions and getters use std::collections::HashMap; @@ -302,3 +302,15 @@ pub struct GetTransactionStatuses { pub struct GetTransactionEffectiveFee { pub id: TransactionID, } + +//========================================== +// Transactions +//========================================== + +#[derive(Debug, Deserialize, Serialize)] +pub struct MosaicDefinitionTransaction { + pub basic_transction: AbstractTransaction, + pub mosaic_properties: Option, + pub mosaic_nonce: u32, + pub mosaic_id: Option, +} diff --git a/src/utils.rs b/src/utils.rs index b26dca5..8888108 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,7 +1,7 @@ //! Basic utils functions for communication with `WasmVM`. use crate::external; -use crate::statuses::Result; +use crate::statuses::FunctionResult; /// Send ping message to `WasmVM`. Successful result should be /// incremented value. Useful for most simple request/response @@ -13,7 +13,7 @@ use crate::statuses::Result; /// let respond = ping(10); /// assert_eq!(respond.unwrap(), 11); /// ``` -pub fn ping(msg: usize) -> Result { +pub fn ping(msg: usize) -> FunctionResult { return unsafe { Ok(external::__ping(msg)) }; } From 812f519dab1f0af2eb3cee69c369f5e300621f5a Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 21 Feb 2020 11:07:01 +0200 Subject: [PATCH 05/28] Added call_external_func complex logic --- src/external.rs | 25 +++++++++ src/transactions.rs | 124 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 144 insertions(+), 5 deletions(-) diff --git a/src/external.rs b/src/external.rs index 4017ccf..222fbfb 100644 --- a/src/external.rs +++ b/src/external.rs @@ -30,4 +30,29 @@ extern "C" { data_len: usize, transaction: *mut u8, ) -> i64; + pub fn get_account_exchange_info( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_exchange_offer_by_asset_id( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_mosaic_info( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_mosaic_infos( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_mosaics_names( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; } diff --git a/src/transactions.rs b/src/transactions.rs index f0b8f29..1fdaf2f 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -1,17 +1,131 @@ //! Basic Blockchain functions and getters +use serde::{de::DeserializeOwned, Serialize}; + use crate::external; use crate::statuses::{Error, FunctionResult, Result}; -use crate::transactions_type::{ - MosaicDefinition, - MosaicDefinitionTransaction, -}; +use crate::transactions_type::{GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, MosaicDefinition, MosaicDefinitionTransaction, MosaicInfo, MosaicName, OfferInfo, UserExchangeInfo}; + +/// Extrnral function type definition for call closure func +type ExternalFn = unsafe extern "C" fn( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, +) -> i64; + +/// External functions call wrapper. It serialize input data +/// and deserialize output data after raw call of external function +fn call_external_func(params: &T, extenral_fn: ExternalFn) -> Result + where T: Serialize, U: DeserializeOwned { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = extenral_fn(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} pub fn flush() -> FunctionResult { return unsafe { Ok(external::flush()) }; } pub fn mosaic_definition(params: &MosaicDefinition) -> Result { + call_external_func(params, external::mosaic_definition) +} + +pub fn get_account_exchange_info(params: &GetAccountExchangeInfo) -> Result { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = external::get_account_exchange_info(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} + +pub fn get_exchange_offer_by_asset_id(params: &GetExchangeOfferByAssetId) -> Result { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = external::get_exchange_offer_by_asset_id(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} + +pub fn get_mosaic_info(params: &GetMosaicInfo) -> Result> { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = external::get_mosaic_info(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} + +pub fn get_mosaic_infos(params: &GetMosaicInfos) -> Result>> { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = external::get_mosaic_infos(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} + +pub fn get_mosaics_names(params: &GetMosaicsNames) -> Result>> { let fn_param = serde_json::to_vec(¶ms); if fn_param.is_err() { return Err(Error::SerializeJson); @@ -20,7 +134,7 @@ pub fn mosaic_definition(params: &MosaicDefinition) -> Result = &mut vec![]; - let fn_result_len = external::mosaic_definition(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_result_len = external::get_mosaics_names(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); fn_data_bytes.to_vec() }; From 1fed79e6821380e0366fa2c22c8a5d07ec4095e4 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 21 Feb 2020 13:18:52 +0200 Subject: [PATCH 06/28] Extend functions with Getter transaction. Added Trait for SingTransactions --- src/external.rs | 25 +++++++ src/lib.rs | 1 + src/tools/call.rs | 33 +++++++++ src/tools/mod.rs | 1 + src/transactions.rs | 146 ++++++++------------------------------- src/transactions_type.rs | 11 ++- 6 files changed, 97 insertions(+), 120 deletions(-) create mode 100644 src/tools/call.rs create mode 100644 src/tools/mod.rs diff --git a/src/external.rs b/src/external.rs index 222fbfb..87095d3 100644 --- a/src/external.rs +++ b/src/external.rs @@ -55,4 +55,29 @@ extern "C" { data_len: usize, transaction: *mut u8, ) -> i64; + pub fn get_transaction( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_transactions( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_transaction_status( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_transaction_statuses( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn get_transaction_effective_fee( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; } diff --git a/src/lib.rs b/src/lib.rs index a0415e2..69eaaff 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,3 +69,4 @@ pub mod storage; pub mod utils; pub mod transactions; pub mod transactions_type; +mod tools; diff --git a/src/tools/call.rs b/src/tools/call.rs new file mode 100644 index 0000000..0a98fc8 --- /dev/null +++ b/src/tools/call.rs @@ -0,0 +1,33 @@ +use serde::{de::DeserializeOwned, Serialize}; +use crate::statuses::{Error, Result}; + +/// Extrnral function type definition for call closure func +type ExternalFn = unsafe extern "C" fn( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, +) -> i64; + +/// External functions call wrapper. It serialize input data +/// and deserialize output data after raw call of external function +pub fn call_external_func(params: &T, extenral_fn: ExternalFn) -> Result + where T: Serialize, U: DeserializeOwned { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = extenral_fn(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} diff --git a/src/tools/mod.rs b/src/tools/mod.rs new file mode 100644 index 0000000..002ad68 --- /dev/null +++ b/src/tools/mod.rs @@ -0,0 +1 @@ +pub mod call; \ No newline at end of file diff --git a/src/transactions.rs b/src/transactions.rs index 1fdaf2f..88c8d98 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -1,41 +1,11 @@ //! Basic Blockchain functions and getters -use serde::{de::DeserializeOwned, Serialize}; +use serde::de::DeserializeOwned; use crate::external; -use crate::statuses::{Error, FunctionResult, Result}; -use crate::transactions_type::{GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, MosaicDefinition, MosaicDefinitionTransaction, MosaicInfo, MosaicName, OfferInfo, UserExchangeInfo}; - -/// Extrnral function type definition for call closure func -type ExternalFn = unsafe extern "C" fn( - data_ptr: *const u8, - data_len: usize, - transaction: *mut u8, -) -> i64; - -/// External functions call wrapper. It serialize input data -/// and deserialize output data after raw call of external function -fn call_external_func(params: &T, extenral_fn: ExternalFn) -> Result - where T: Serialize, U: DeserializeOwned { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } - - let fn_params_body = fn_param.unwrap(); - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = extenral_fn(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; - - let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) -} +use crate::statuses::{FunctionResult, Result}; +use crate::tools::call::call_external_func; +use crate::transactions_type::*; pub fn flush() -> FunctionResult { return unsafe { Ok(external::flush()) }; @@ -46,101 +16,41 @@ pub fn mosaic_definition(params: &MosaicDefinition) -> Result Result { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } - - let fn_params_body = fn_param.unwrap(); - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = external::get_account_exchange_info(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; - let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) + call_external_func(params, external::get_account_exchange_info) } pub fn get_exchange_offer_by_asset_id(params: &GetExchangeOfferByAssetId) -> Result { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } - - let fn_params_body = fn_param.unwrap(); - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = external::get_exchange_offer_by_asset_id(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; - let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) + call_external_func(params, external::get_exchange_offer_by_asset_id) } pub fn get_mosaic_info(params: &GetMosaicInfo) -> Result> { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } - - let fn_params_body = fn_param.unwrap(); - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = external::get_mosaic_info(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; - let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) + call_external_func(params, external::get_mosaic_info) } pub fn get_mosaic_infos(params: &GetMosaicInfos) -> Result>> { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } - - let fn_params_body = fn_param.unwrap(); - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = external::get_mosaic_infos(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; - let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) + call_external_func(params, external::get_mosaic_infos) } pub fn get_mosaics_names(params: &GetMosaicsNames) -> Result>> { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } + call_external_func(params, external::get_mosaics_names) +} + +pub fn get_transaction(params: &GetTransaction) -> Result { + call_external_func(params, external::get_transaction) +} + +pub fn get_transactions(params: &GetTransactions) -> Result> { + call_external_func(params, external::get_transactions) +} + +pub fn get_transaction_status(params: &GetTransactionStatus) -> Result> { + call_external_func(params, external::get_transaction_status) +} + +pub fn get_transaction_statuses(params: &GetTransactionStatuses) -> Result>> { + call_external_func(params, external::get_transaction_statuses) +} - let fn_params_body = fn_param.unwrap(); - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = external::get_mosaics_names(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; - let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) +pub fn get_transaction_effective_fee(params: &GetTransactionEffectiveFee) -> Result { + call_external_func(params, external::get_transaction_effective_fee) } diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 3cb1a88..4e271f1 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -25,7 +25,7 @@ pub type HashType = u8; pub type Message = Vec; pub type OfferType = u8; pub type TransactionID = [u8; 32]; - +pub type TransactionType = u8; pub type Signature = [u8; 64]; #[derive(Debug, Deserialize, Serialize)] @@ -308,9 +308,16 @@ pub struct GetTransactionEffectiveFee { //========================================== #[derive(Debug, Deserialize, Serialize)] -pub struct MosaicDefinitionTransaction { +pub struct MosaicDefinitionTransaction { pub basic_transction: AbstractTransaction, pub mosaic_properties: Option, pub mosaic_nonce: u32, pub mosaic_id: Option, } + +pub trait SignedTransaction { + fn id(&self) -> TransactionID; + fn transaction_type() -> TransactionType; + fn signer() -> PubKey; + fn signature() -> Vec; +} From b2a6c64c7ca85bd9b34a2c33b6603c997c40a629 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 21 Feb 2020 15:27:12 +0200 Subject: [PATCH 07/28] Extend Transactions functions and external funcs --- src/external.rs | 75 ++++++++++++++++++++++++++++++++++++++++ src/transactions.rs | 62 ++++++++++++++++++++++++++++++++- src/transactions_type.rs | 8 ----- 3 files changed, 136 insertions(+), 9 deletions(-) diff --git a/src/external.rs b/src/external.rs index 87095d3..192fe9b 100644 --- a/src/external.rs +++ b/src/external.rs @@ -80,4 +80,79 @@ extern "C" { data_len: usize, transaction: *mut u8, ) -> i64; + pub fn address_alias( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn mosaic_alias( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn add_exchange_offer( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn exchange_offer( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn transfer( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn remove_exchange_offer( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn mosaic_supply_change( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn register_root_namespace( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn register_sub_namespace( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn secret_lock( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn secret_proof( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn transfer_with_namespace( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn modify_metadata_address( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn modify_metadata_mosaic( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; + pub fn modify_metadata_namespace( + data_ptr: *const u8, + data_len: usize, + transaction: *mut u8, + ) -> i64; } diff --git a/src/transactions.rs b/src/transactions.rs index 88c8d98..0eefe40 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -11,10 +11,70 @@ pub fn flush() -> FunctionResult { return unsafe { Ok(external::flush()) }; } -pub fn mosaic_definition(params: &MosaicDefinition) -> Result { +pub fn mosaic_definition(params: &MosaicDefinition) -> FunctionResult { call_external_func(params, external::mosaic_definition) } +pub fn address_alias(params: &AddressAlias) -> FunctionResult { + call_external_func(params, external::address_alias) +} + +pub fn mosaic_alias(params: &MosaicAlias) -> FunctionResult { + call_external_func(params, external::mosaic_alias) +} + +pub fn add_exchange_offer(params: &AddExchangeOffer) -> FunctionResult { + call_external_func(params, external::add_exchange_offer) +} + +pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { + call_external_func(params, external::exchange_offer) +} + +pub fn transfer(params: &Transfer) -> FunctionResult { + call_external_func(params, external::transfer) +} + +pub fn remove_exchange_offer(params: &RemoveExchangeOffer) -> FunctionResult { + call_external_func(params, external::remove_exchange_offer) +} + +pub fn mosaic_supply_change(params: &MosaicSupplyChange) -> FunctionResult { + call_external_func(params, external::mosaic_supply_change) +} + +pub fn register_root_namespace(params: &RegisterRootNamespace) -> FunctionResult { + call_external_func(params, external::register_root_namespace) +} + +pub fn register_sub_namespace(params: &RegisterSubNamespace) -> FunctionResult { + call_external_func(params, external::register_sub_namespace) +} + +pub fn secret_lock(params: &SecretLock) -> FunctionResult { + call_external_func(params, external::secret_lock) +} + +pub fn secret_proof(params: &SecretProof) -> FunctionResult { + call_external_func(params, external::secret_proof) +} + +pub fn transfer_with_namespace(params: &TransferWithNamespace) -> FunctionResult { + call_external_func(params, external::transfer_with_namespace) +} + +pub fn modify_metadata_address(params: &ModifyMetadataAddress) -> FunctionResult { + call_external_func(params, external::modify_metadata_address) +} + +pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { + call_external_func(params, external::modify_metadata_mosaic) +} + +pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionResult { + call_external_func(params, external::modify_metadata_namespace) +} + pub fn get_account_exchange_info(params: &GetAccountExchangeInfo) -> Result { call_external_func(params, external::get_account_exchange_info) } diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 4e271f1..2b06471 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -307,14 +307,6 @@ pub struct GetTransactionEffectiveFee { // Transactions //========================================== -#[derive(Debug, Deserialize, Serialize)] -pub struct MosaicDefinitionTransaction { - pub basic_transction: AbstractTransaction, - pub mosaic_properties: Option, - pub mosaic_nonce: u32, - pub mosaic_id: Option, -} - pub trait SignedTransaction { fn id(&self) -> TransactionID; fn transaction_type() -> TransactionType; From 84a31957b80aca19d31e542395e56241b0528265 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 21 Feb 2020 21:47:59 +0200 Subject: [PATCH 08/28] Added Functions documentations --- examples/http.rs | 2 +- src/http.rs | 64 +++-- src/lib.rs | 2 +- src/tools/call.rs | 14 +- src/transactions.rs | 601 ++++++++++++++++++++++++++++++++++++++- src/transactions_type.rs | 14 +- 6 files changed, 662 insertions(+), 35 deletions(-) diff --git a/examples/http.rs b/examples/http.rs index 691379d..43668d5 100644 --- a/examples/http.rs +++ b/examples/http.rs @@ -1,4 +1,4 @@ -// Example for `http_get` WasmVM function. +/// Example for `http_get` WasmVM function. use std::collections::HashMap; use xpx_supercontracts_sdk::http::{http_get, HttpRequest}; diff --git a/src/http.rs b/src/http.rs index 627794f..cd8d2e5 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,46 +1,62 @@ -//! Basic HTTP functions +//! # Basic HTTP functions -use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use serde::{Deserialize, Serialize}; + use crate::external; use crate::statuses::{Error, MultipleFunctionResult}; /// HTTP request data #[derive(Debug, Deserialize, Serialize)] pub struct HttpRequest { - /// URL for request - pub url: String, - /// HTTP headers for request body - pub headers: HashMap, + /// URL for request + pub url: String, + /// HTTP headers for request body + pub headers: HashMap, } /// HTTP response data #[derive(Debug, Deserialize, Serialize)] struct HttpResponse { - /// HTTP statuscode - status_code: u64, - /// Response body - body: String, + /// HTTP statuscode + status_code: u64, + /// Response body + body: String, } /// Send HTTPP requst with specific parameters. /// -/// # Examples +/// ## Examples /// ```rust,no_run -/// use xpx_supercontracts_sdk::http::http_get; +/// use std::collections::HashMap; +/// use xpx_supercontracts_sdk::http::{http_get, HttpRequest}; +/// +/// let mut headers: HashMap = HashMap::new(); +/// headers.insert("content-type".to_string(), "text/html".to_string()); +/// let req = HttpRequest { +/// url: "http://google.com/".to_string(), +/// headers: headers, +/// }; +/// let resp = http_get(&req); +/// if resp.is_err() { +/// // Some error handling +/// } +/// // Return response body length +/// let result = resp.unwrap().len() as i64; /// ``` +/// pub fn http_get(request: &HttpRequest) -> MultipleFunctionResult { - let request_body = serde_json::to_vec(&request); - if request_body.is_err() { - return Err(Error::SerializeJson); - } - let request_body = request_body.unwrap(); - let data: &mut Vec = &mut vec![]; - return unsafe { - let body_len = - external::get_http(request_body.as_ptr(), request_body.len(), data.as_mut_ptr()); - let data_bytes = data.get_unchecked_mut(0..body_len as usize); - Ok(data_bytes.to_vec()) - }; + let request_body = serde_json::to_vec(&request); + if request_body.is_err() { + return Err(Error::SerializeJson); + } + let request_body = request_body.unwrap(); + let data: &mut Vec = &mut vec![]; + return unsafe { + let body_len = + external::get_http(request_body.as_ptr(), request_body.len(), data.as_mut_ptr()); + let data_bytes = data.get_unchecked_mut(0..body_len as usize); + Ok(data_bytes.to_vec()) + }; } diff --git a/src/lib.rs b/src/lib.rs index 69eaaff..e3eb6ef 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,7 +22,7 @@ //! ## Notes //! Supercontract functions should be //! external with specific attributes: -//! ```ingore +//! ```ignore //! use xpx_supercontracts_sdk::utils::{ping, debug_message}; //! //! #[no_mangle] diff --git a/src/tools/call.rs b/src/tools/call.rs index 0a98fc8..bd965bf 100644 --- a/src/tools/call.rs +++ b/src/tools/call.rs @@ -1,7 +1,11 @@ +//! Basic additional toolkit for SuperContract functions +//! + use serde::{de::DeserializeOwned, Serialize}; use crate::statuses::{Error, Result}; -/// Extrnral function type definition for call closure func +/// External function type definition for call +/// closure external FFI functions type ExternalFn = unsafe extern "C" fn( data_ptr: *const u8, data_len: usize, @@ -9,7 +13,13 @@ type ExternalFn = unsafe extern "C" fn( ) -> i64; /// External functions call wrapper. It serialize input data -/// and deserialize output data after raw call of external function +/// and deserialize output data after raw call of external function. +/// It support any kind ofr external functions to wrap for basic flow +/// for SuperContract functions with specific flow like this: +/// * serialize input data +/// * invoke external function with serialized function parameters +/// * fetch external function result +/// * deserialize external function to specific type for SuperContract function pub fn call_external_func(params: &T, extenral_fn: ExternalFn) -> Result where T: Serialize, U: DeserializeOwned { let fn_param = serde_json::to_vec(¶ms); diff --git a/src/transactions.rs b/src/transactions.rs index 0eefe40..be11f7b 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -1,4 +1,24 @@ -//! Basic Blockchain functions and getters +//! # Basic Blockchain functions +//! Basic functionality to interact with Catapulta Blockchain. +//! It represent via twa main part: transactions +//! and getters (**get functions** of some information from Blockchain). +//! +//! ## Transaction functions +//! Main principle of transaction functions is +//! that aggregation to pool of transactions. So it will send not immediately. +//! The reason is minimize `Gas spent` and reducing Blockchain resources utilization. +//! +//! When SuperContract will End transactions Flush autromaticaly (it mean it will send +//! to Blocchain). +//! +//! But it possible send transaction pull immediately. +//! For that case exist function `flush`. +//! When function `flush` invoking then Transactions Pool +//! will be send to Blockchain, and then clear. +//! +//! And again - only **end execution of SuperContract** +//! or Flush** can send transactions to Blockchaing. +//! Otherwise it will gather to Transactions Pool. use serde::de::DeserializeOwned; @@ -7,110 +27,689 @@ use crate::statuses::{FunctionResult, Result}; use crate::tools::call::call_external_func; use crate::transactions_type::*; +/// Flush send immediately Transactions from current +/// transactions pool. +/// +/// Flush should use carefully. If Leader of SuperContract +/// execution invoke Flush then SuperContract will be +/// paused ann waite +/// Signing from other Executors. +/// When Flush will send from non-leader it mean fire +/// process of signing transactions +/// from Leader of SuperContract execution. +/// In both case SuperContract will be paused waiting +/// event from other Executors. +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// mosaic_definition, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::MosaicDefinition; +/// +/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".as_bytes().to_vec(); +/// let params = MosaicDefinition{ +/// nonce: 100, +/// owner_public_key: pub_key, +/// mosaic_props: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = mosaic_definition(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// // Flush current Transactions Pool +/// let flush_result = flush(); +/// if flush_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn flush() -> FunctionResult { return unsafe { Ok(external::flush()) }; } +/// Send to transaction pool **MosaicDefinition transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// mosaic_definition, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::MosaicDefinition; +/// +/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".as_bytes().to_vec(); +/// let params = MosaicDefinition{ +/// nonce: 100, +/// owner_public_key: pub_key, +/// mosaic_props: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = mosaic_definition(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn mosaic_definition(params: &MosaicDefinition) -> FunctionResult { call_external_func(params, external::mosaic_definition) } +/// Send to transaction pool **AddressAlias transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// address_alias, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::AddressAlias; +/// +/// let params = AddressAlias{ +/// address: None, +/// namespace_id: None, +/// action_type: 10, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = address_alias(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn address_alias(params: &AddressAlias) -> FunctionResult { call_external_func(params, external::address_alias) } +/// Send to transaction pool **MosaicAlias transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// mosaic_alias, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::MosaicAlias; +/// +/// let params = MosaicAlias{ +/// mosaic_id: None, +/// namespace_id: None, +/// action_type: 10, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = mosaic_alias(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn mosaic_alias(params: &MosaicAlias) -> FunctionResult { call_external_func(params, external::mosaic_alias) } +/// Send to transaction pool **AddExchangeOffer transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// add_exchange_offer, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::AddExchangeOffer; +/// +/// let params = AddExchangeOffer{ +/// add_offers: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = add_exchange_offer(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn add_exchange_offer(params: &AddExchangeOffer) -> FunctionResult { call_external_func(params, external::add_exchange_offer) } +/// Send to transaction pool **AddExchangeOffer transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// add_exchange_offer, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::AddExchangeOffer; +/// +/// let params = AddExchangeOffer{ +/// add_offers: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = add_exchange_offer(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { call_external_func(params, external::exchange_offer) } +/// Send to transaction pool **Transfer transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// transfer, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{Transfer, PubKey}; +/// +/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".as_bytes(); +/// let mut pk: PubKey = [0; 32]; +/// pk.copy_from_slice(&pub_key[..32]); +/// let params = Transfer{ +/// pub_key: pk, +/// asset_id: 10, +/// amount: 1000, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = transfer(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn transfer(params: &Transfer) -> FunctionResult { call_external_func(params, external::transfer) } +/// Send to transaction pool **RemoveExchangeOffer transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// remove_exchange_offer, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::RemoveExchangeOffer; +/// +/// let params = RemoveExchangeOffer{ +/// remove_offers: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = remove_exchange_offer(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn remove_exchange_offer(params: &RemoveExchangeOffer) -> FunctionResult { call_external_func(params, external::remove_exchange_offer) } +/// Send to transaction pool **MosaicSupplyChange transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// mosaic_supply_change, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::MosaicSupplyChange; +/// +/// let params = MosaicSupplyChange{ +/// asset_id: 10, +/// supply_type: 20, +/// delta: 300, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = mosaic_supply_change(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn mosaic_supply_change(params: &MosaicSupplyChange) -> FunctionResult { call_external_func(params, external::mosaic_supply_change) } +/// Send to transaction pool **RegisterRootNamespace transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// register_root_namespace, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::RegisterRootNamespace; +/// +/// let params = RegisterRootNamespace{ +/// namespace_name: String::from("my_name_space"), +/// duration: 3000, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = register_root_namespace(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn register_root_namespace(params: &RegisterRootNamespace) -> FunctionResult { call_external_func(params, external::register_root_namespace) } +/// Send to transaction pool **RegisterRootNamespace transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// register_root_namespace, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::RegisterRootNamespace; +/// +/// let params = RegisterRootNamespace{ +/// namespace_name: String::from("my_name_space"), +/// duration: 3000, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = register_root_namespace(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn register_sub_namespace(params: &RegisterSubNamespace) -> FunctionResult { call_external_func(params, external::register_sub_namespace) } +/// Send to transaction pool **SecretLock transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// secret_lock, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::SecretLock; +/// +/// let params = SecretLock{ +/// mosaic: None, +/// duration: 3000, +/// secret: None, +/// recipient: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = secret_lock(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn secret_lock(params: &SecretLock) -> FunctionResult { call_external_func(params, external::secret_lock) } +/// Send to transaction pool **SecretProof transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// secret_proof, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::SecretProof; +/// +/// let params = SecretProof{ +/// hash_type: 10, +/// proof: None, +/// recipient: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = secret_proof(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn secret_proof(params: &SecretProof) -> FunctionResult { call_external_func(params, external::secret_proof) } +/// Send to transaction pool **TransferWithNamespace transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// transfer_with_namespace, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::TransferWithNamespace; +/// +/// let params = TransferWithNamespace{ +/// recipient: None, +/// mosaics: None, +/// message: "some message".as_bytes().to_vec(), +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = transfer_with_namespace(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn transfer_with_namespace(params: &TransferWithNamespace) -> FunctionResult { call_external_func(params, external::transfer_with_namespace) } +/// Send to transaction pool **ModifyMetadataAddress transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// modify_metadata_address, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::ModifyMetadataAddress; +/// +/// let params = ModifyMetadataAddress{ +/// address: None, +/// modifications: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = modify_metadata_address(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn modify_metadata_address(params: &ModifyMetadataAddress) -> FunctionResult { call_external_func(params, external::modify_metadata_address) } +/// Send to transaction pool **ModifyMetadataMosaic transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// modify_metadata_mosaic, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::ModifyMetadataMosaic; +/// +/// let params = ModifyMetadataMosaic{ +/// mosaic_id: None, +/// modifications: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = modify_metadata_mosaic(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { call_external_func(params, external::modify_metadata_mosaic) } +/// Send to transaction pool **ModifyMetadataNamespace transaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// modify_metadata_namespace, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::ModifyMetadataNamespace; +/// +/// let params = ModifyMetadataNamespace{ +/// namespace_id: 10, +/// modifications: None, +/// }; +/// // Add transaction to Transactions Pool +/// let tx_result = modify_metadata_namespace(¶ms); +/// if tx_result.is_err() { +/// // Some error handling +/// } +/// ``` +/// pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionResult { call_external_func(params, external::modify_metadata_namespace) } +/// Get data via **GetAccountExchangeInfo** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_account_exchange_info, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetAccountExchangeInfo, UserExchangeInfo}; +/// +/// let params = GetAccountExchangeInfo{ +/// account: None, +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_account_exchange_info(¶ms); +/// if result.is_err() { +/// // Some error handling +/// } +/// let info: UserExchangeInfo = result.unwrap(); +/// ``` +/// pub fn get_account_exchange_info(params: &GetAccountExchangeInfo) -> Result { call_external_func(params, external::get_account_exchange_info) } +/// Get data via **GetExchangeOfferByAssetId** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_exchange_offer_by_asset_id, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetExchangeOfferByAssetId, OfferInfo}; +/// +/// let params = GetExchangeOfferByAssetId{ +/// asset_id: 10, +/// offer_type: 20, +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_exchange_offer_by_asset_id(¶ms); +/// if result.is_err() { +/// // Some error handling +/// } +/// let info: OfferInfo = result.unwrap(); +/// ``` +/// pub fn get_exchange_offer_by_asset_id(params: &GetExchangeOfferByAssetId) -> Result { call_external_func(params, external::get_exchange_offer_by_asset_id) } +/// Get data via **GetMosaicInfo** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_mosaic_info, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetMosaicInfo, MosaicInfo}; +/// +/// let params = GetMosaicInfo{ +/// mosaic_id: None, +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_mosaic_info(¶ms); +/// if result.is_err() { +/// // Some error handling +/// } +/// let info: Option = result.unwrap(); +/// ``` +/// pub fn get_mosaic_info(params: &GetMosaicInfo) -> Result> { call_external_func(params, external::get_mosaic_info) } +/// Get data via **GetMosaicInfos** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_mosaic_infos, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetMosaicInfos, MosaicInfo}; +/// +/// let params = GetMosaicInfos{ +/// msc_ids: None, +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_mosaic_infos(¶ms); +/// if result.is_err() { +/// // Some error handling +/// } +/// let info: Option> = result.unwrap(); +/// ``` +/// pub fn get_mosaic_infos(params: &GetMosaicInfos) -> Result>> { call_external_func(params, external::get_mosaic_infos) } +/// Get data via **GetMosaicsNames** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_mosaics_names, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetMosaicsNames, MosaicName}; +/// +/// let params = GetMosaicsNames{ +/// msc_ids: None, +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_mosaics_names(¶ms); +/// if result.is_err() { +/// // Some error handling +/// } +/// let info: Option> = result.unwrap(); +/// ``` +/// pub fn get_mosaics_names(params: &GetMosaicsNames) -> Result>> { call_external_func(params, external::get_mosaics_names) } +/// Get data via **GetTransaction** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_transaction, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::GetTransaction; +/// +/// let params = GetTransaction{ +/// id: [0; 32], +/// }; +/// // Add transaction to Transactions Pool +/// let _ = get_transaction(¶ms); +/// ``` +/// pub fn get_transaction(params: &GetTransaction) -> Result { call_external_func(params, external::get_transaction) } +/// Get data via **GetTransactions** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_transactions, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::GetTransactions; +/// +/// let params = GetTransactions{ +/// ids: vec!([0; 32]), +/// }; +/// // Add transaction to Transactions Pool +/// let _ = get_transactions(¶ms); +/// ``` +/// pub fn get_transactions(params: &GetTransactions) -> Result> { call_external_func(params, external::get_transactions) } +/// Get data via **GetTransactionStatus** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_transaction_status, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetTransactionStatus, TransactionStatus}; +/// +/// let params = GetTransactionStatus{ +/// id: [0; 32], +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_transaction_status(¶ms); +/// let info: Option = result.unwrap(); +/// ``` +/// pub fn get_transaction_status(params: &GetTransactionStatus) -> Result> { call_external_func(params, external::get_transaction_status) } +/// Get data via **GetTransactionStatuses** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_transaction_statuses, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetTransactionStatuses, TransactionStatus}; +/// +/// let params = GetTransactionStatuses{ +/// ids: vec!([0;32]), +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_transaction_statuses(¶ms); +/// let info: Option> = result.unwrap(); +/// ``` +/// pub fn get_transaction_statuses(params: &GetTransactionStatuses) -> Result>> { call_external_func(params, external::get_transaction_statuses) } +/// Get data via **GetTransactionEffectiveFee** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// flush, +/// get_transaction_effective_fee, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetTransactionEffectiveFee}; +/// +/// let params = GetTransactionEffectiveFee{ +/// id: [0;32], +/// }; +/// // Add transaction to Transactions Pool +/// let result = get_transaction_effective_fee(¶ms); +/// let info: i64 = result.unwrap(); +/// ``` +/// pub fn get_transaction_effective_fee(params: &GetTransactionEffectiveFee) -> Result { call_external_func(params, external::get_transaction_effective_fee) } diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 2b06471..b958f97 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -1,4 +1,7 @@ -//! Basic Transactions types for Blockchain functions and getters +//! # Basic Transactions types for Blockchain functions and getters +//! +//! Most common representations for Blockchain transactions type, +//! traits, and informations getters. use std::collections::HashMap; @@ -50,7 +53,7 @@ pub struct AbstractTransaction { #[derive(Debug, Deserialize, Serialize)] pub struct MosaicDefinition { pub nonce: u32, - pub owner_public_key: Vec, + pub owner_public_key: Vec, pub mosaic_props: Option, } @@ -303,10 +306,9 @@ pub struct GetTransactionEffectiveFee { pub id: TransactionID, } -//========================================== -// Transactions -//========================================== - +/// # Transactions +/// **SignedTransaction** is common interface for transactions data +/// from Blockchain. pub trait SignedTransaction { fn id(&self) -> TransactionID; fn transaction_type() -> TransactionType; From f74fe5fce29ac75730261b5d79eac4524b3935fb Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 21 Feb 2020 23:41:47 +0200 Subject: [PATCH 09/28] Added DriveFS transaction --- src/external.rs | 5 ---- src/transactions.rs | 60 ++++++++++++---------------------------- src/transactions_type.rs | 56 +++++++++++++++++++++++++++++++++++-- 3 files changed, 71 insertions(+), 50 deletions(-) diff --git a/src/external.rs b/src/external.rs index 192fe9b..b2a950b 100644 --- a/src/external.rs +++ b/src/external.rs @@ -60,11 +60,6 @@ extern "C" { data_len: usize, transaction: *mut u8, ) -> i64; - pub fn get_transactions( - data_ptr: *const u8, - data_len: usize, - transaction: *mut u8, - ) -> i64; pub fn get_transaction_status( data_ptr: *const u8, data_len: usize, diff --git a/src/transactions.rs b/src/transactions.rs index be11f7b..689deb2 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -384,7 +384,6 @@ pub fn secret_proof(params: &SecretProof) -> FunctionResult { /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ -/// flush, /// transfer_with_namespace, /// }; /// use xpx_supercontracts_sdk::transactions_type::TransferWithNamespace; @@ -410,7 +409,6 @@ pub fn transfer_with_namespace(params: &TransferWithNamespace) -> FunctionResult /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ -/// flush, /// modify_metadata_address, /// }; /// use xpx_supercontracts_sdk::transactions_type::ModifyMetadataAddress; @@ -435,7 +433,6 @@ pub fn modify_metadata_address(params: &ModifyMetadataAddress) -> FunctionResult /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ -/// flush, /// modify_metadata_mosaic, /// }; /// use xpx_supercontracts_sdk::transactions_type::ModifyMetadataMosaic; @@ -460,7 +457,6 @@ pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ -/// flush, /// modify_metadata_namespace, /// }; /// use xpx_supercontracts_sdk::transactions_type::ModifyMetadataNamespace; @@ -485,7 +481,6 @@ pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionRe /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ -/// flush, /// get_account_exchange_info, /// }; /// use xpx_supercontracts_sdk::transactions_type::{GetAccountExchangeInfo, UserExchangeInfo}; @@ -493,7 +488,7 @@ pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionRe /// let params = GetAccountExchangeInfo{ /// account: None, /// }; -/// // Add transaction to Transactions Pool +/// // Get info data /// let result = get_account_exchange_info(¶ms); /// if result.is_err() { /// // Some error handling @@ -510,7 +505,6 @@ pub fn get_account_exchange_info(params: &GetAccountExchangeInfo) -> Result Result Res /// let params = GetMosaicInfo{ /// mosaic_id: None, /// }; -/// // Add transaction to Transactions Pool +/// // Get info data /// let result = get_mosaic_info(¶ms); /// if result.is_err() { /// // Some error handling @@ -569,7 +563,7 @@ pub fn get_mosaic_info(params: &GetMosaicInfo) -> Result> { /// let params = GetMosaicInfos{ /// msc_ids: None, /// }; -/// // Add transaction to Transactions Pool +/// // Get info data /// let result = get_mosaic_infos(¶ms); /// if result.is_err() { /// // Some error handling @@ -594,7 +588,7 @@ pub fn get_mosaic_infos(params: &GetMosaicInfos) -> Result Result = get_transaction(¶ms); +/// if tx_result.is_err() { +/// // Handle error +/// } +/// let tx = tx_result.unwrap(); /// ``` /// pub fn get_transaction(params: &GetTransaction) -> Result { call_external_func(params, external::get_transaction) } -/// Get data via **GetTransactions** -/// -/// ## Examples -/// ```rust,no_run -/// use xpx_supercontracts_sdk::transactions::{ -/// flush, -/// get_transactions, -/// }; -/// use xpx_supercontracts_sdk::transactions_type::GetTransactions; -/// -/// let params = GetTransactions{ -/// ids: vec!([0; 32]), -/// }; -/// // Add transaction to Transactions Pool -/// let _ = get_transactions(¶ms); -/// ``` -/// -pub fn get_transactions(params: &GetTransactions) -> Result> { - call_external_func(params, external::get_transactions) -} - /// Get data via **GetTransactionStatus** /// /// ## Examples @@ -661,9 +639,9 @@ pub fn get_transactions(params: &GetTra /// let params = GetTransactionStatus{ /// id: [0; 32], /// }; -/// // Add transaction to Transactions Pool +/// // Get info data /// let result = get_transaction_status(¶ms); -/// let info: Option = result.unwrap(); +/// let info = result.unwrap(); /// ``` /// pub fn get_transaction_status(params: &GetTransactionStatus) -> Result> { @@ -675,7 +653,6 @@ pub fn get_transaction_status(params: &GetTransactionStatus) -> Result Result> = result.unwrap(); /// ``` @@ -697,7 +674,6 @@ pub fn get_transaction_statuses(params: &GetTransactionStatuses) -> Result Result Result { diff --git a/src/transactions_type.rs b/src/transactions_type.rs index b958f97..5bbac7d 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -311,7 +311,57 @@ pub struct GetTransactionEffectiveFee { /// from Blockchain. pub trait SignedTransaction { fn id(&self) -> TransactionID; - fn transaction_type() -> TransactionType; - fn signer() -> PubKey; - fn signature() -> Vec; + fn transaction_type(&self) -> TransactionType; + fn signer(&self) -> PubKey; + fn signature(&self) -> Vec; +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct Action { + pub hash: Hash, + pub action_type: i64, + pub size: u64, +} + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct DriveFsTransaction { + pub id: TransactionID, + pub transaction_type: TransactionType, + pub signer: PubKey, + pub signature: Vec, + pub drive_id: Hash, + pub add_actions: Option>, + pub remove_actions: Option>, +} + +impl DriveFsTransaction { + pub fn drive_id(&self) -> Hash { + self.drive_id + } + + pub fn add_actions(&self) -> Option> { + self.add_actions.clone() + } + + pub fn remove_actions(&self) -> Option> { + self.remove_actions.clone() + } +} + +impl SignedTransaction for DriveFsTransaction { + fn id(&self) -> TransactionID { + self.id + } + + fn transaction_type(&self) -> TransactionType { + self.transaction_type + } + + fn signer(&self) -> PubKey { + self.signer + } + + fn signature(&self) -> Vec { + self.signature.clone() + } } From a697aeedb33ffdc243e9453061acd315fd13c5d0 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sun, 23 Feb 2020 23:50:14 +0200 Subject: [PATCH 10/28] External functions: added Simple Call logic for non-result external functions --- src/external.rs | 90 ++++++++++++++++++++------------------------- src/tools/call.rs | 30 +++++++++++++-- src/transactions.rs | 34 ++++++++--------- 3 files changed, 82 insertions(+), 72 deletions(-) diff --git a/src/external.rs b/src/external.rs index b2a950b..f481c5f 100644 --- a/src/external.rs +++ b/src/external.rs @@ -24,130 +24,118 @@ extern "C" { body: *mut u8, ) -> i64; + //================================================== + // Blockchain Transactions manipulations pub fn flush() -> i64; pub fn mosaic_definition( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_account_exchange_info( + pub fn address_alias( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_exchange_offer_by_asset_id( + pub fn mosaic_alias( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_mosaic_info( + pub fn add_exchange_offer( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_mosaic_infos( + pub fn exchange_offer( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_mosaics_names( + pub fn transfer( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_transaction( + pub fn remove_exchange_offer( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_transaction_status( + pub fn mosaic_supply_change( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, - ) -> i64; - pub fn get_transaction_statuses( + ) -> i64; + pub fn register_root_namespace( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn get_transaction_effective_fee( + pub fn register_sub_namespace( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn address_alias( + pub fn secret_lock( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn mosaic_alias( + pub fn secret_proof( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn add_exchange_offer( + pub fn transfer_with_namespace( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn exchange_offer( + pub fn modify_metadata_address( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn transfer( + pub fn modify_metadata_mosaic( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn remove_exchange_offer( + pub fn modify_metadata_namespace( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, ) -> i64; - pub fn mosaic_supply_change( + //============================================== + // Blockchain Getters + pub fn get_account_exchange_info( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, - ) -> i64; - pub fn register_root_namespace( + data: *mut u8, + ) -> i64; + pub fn get_exchange_offer_by_asset_id( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; - pub fn register_sub_namespace( + pub fn get_mosaic_info( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; - pub fn secret_lock( + pub fn get_mosaic_infos( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; - pub fn secret_proof( + pub fn get_mosaics_names( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; - pub fn transfer_with_namespace( + pub fn get_transaction( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; - pub fn modify_metadata_address( + pub fn get_transaction_status( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; - pub fn modify_metadata_mosaic( + pub fn get_transaction_statuses( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; - pub fn modify_metadata_namespace( + pub fn get_transaction_effective_fee( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; } diff --git a/src/tools/call.rs b/src/tools/call.rs index bd965bf..de2dc6f 100644 --- a/src/tools/call.rs +++ b/src/tools/call.rs @@ -2,14 +2,15 @@ //! use serde::{de::DeserializeOwned, Serialize}; -use crate::statuses::{Error, Result}; + +use crate::statuses::{Error, FunctionResult, Result}; /// External function type definition for call /// closure external FFI functions -type ExternalFn = unsafe extern "C" fn( +type ExternalFnWithReturnData = unsafe extern "C" fn( data_ptr: *const u8, data_len: usize, - transaction: *mut u8, + data: *mut u8, ) -> i64; /// External functions call wrapper. It serialize input data @@ -20,7 +21,7 @@ type ExternalFn = unsafe extern "C" fn( /// * invoke external function with serialized function parameters /// * fetch external function result /// * deserialize external function to specific type for SuperContract function -pub fn call_external_func(params: &T, extenral_fn: ExternalFn) -> Result +pub fn call_external_func(params: &T, extenral_fn: ExternalFnWithReturnData) -> Result where T: Serialize, U: DeserializeOwned { let fn_param = serde_json::to_vec(¶ms); if fn_param.is_err() { @@ -41,3 +42,24 @@ pub fn call_external_func(params: &T, extenral_fn: ExternalFn) -> Result i64; + +/// Similar call_external_func but without return data from external function +pub fn simple_call_external_func(params: &T, extenral_fn: ExternalFn) -> FunctionResult + where T: Serialize { + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } + + let fn_params_body = fn_param.unwrap(); + unsafe { + Ok(extenral_fn(fn_params_body.as_ptr(), fn_params_body.len())) + } +} diff --git a/src/transactions.rs b/src/transactions.rs index 689deb2..53e41fe 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -24,7 +24,7 @@ use serde::de::DeserializeOwned; use crate::external; use crate::statuses::{FunctionResult, Result}; -use crate::tools::call::call_external_func; +use crate::tools::call::{call_external_func, simple_call_external_func}; use crate::transactions_type::*; /// Flush send immediately Transactions from current @@ -94,7 +94,7 @@ pub fn flush() -> FunctionResult { /// ``` /// pub fn mosaic_definition(params: &MosaicDefinition) -> FunctionResult { - call_external_func(params, external::mosaic_definition) + simple_call_external_func(params, external::mosaic_definition) } /// Send to transaction pool **AddressAlias transaction** @@ -120,7 +120,7 @@ pub fn mosaic_definition(params: &MosaicDefinition) -> FunctionResult { /// ``` /// pub fn address_alias(params: &AddressAlias) -> FunctionResult { - call_external_func(params, external::address_alias) + simple_call_external_func(params, external::address_alias) } /// Send to transaction pool **MosaicAlias transaction** @@ -146,7 +146,7 @@ pub fn address_alias(params: &AddressAlias) -> FunctionResult { /// ``` /// pub fn mosaic_alias(params: &MosaicAlias) -> FunctionResult { - call_external_func(params, external::mosaic_alias) + simple_call_external_func(params, external::mosaic_alias) } /// Send to transaction pool **AddExchangeOffer transaction** @@ -170,7 +170,7 @@ pub fn mosaic_alias(params: &MosaicAlias) -> FunctionResult { /// ``` /// pub fn add_exchange_offer(params: &AddExchangeOffer) -> FunctionResult { - call_external_func(params, external::add_exchange_offer) + simple_call_external_func(params, external::add_exchange_offer) } /// Send to transaction pool **AddExchangeOffer transaction** @@ -194,7 +194,7 @@ pub fn add_exchange_offer(params: &AddExchangeOffer) -> FunctionResult { /// ``` /// pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { - call_external_func(params, external::exchange_offer) + simple_call_external_func(params, external::exchange_offer) } /// Send to transaction pool **Transfer transaction** @@ -223,7 +223,7 @@ pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { /// ``` /// pub fn transfer(params: &Transfer) -> FunctionResult { - call_external_func(params, external::transfer) + simple_call_external_func(params, external::transfer) } /// Send to transaction pool **RemoveExchangeOffer transaction** @@ -247,7 +247,7 @@ pub fn transfer(params: &Transfer) -> FunctionResult { /// ``` /// pub fn remove_exchange_offer(params: &RemoveExchangeOffer) -> FunctionResult { - call_external_func(params, external::remove_exchange_offer) + simple_call_external_func(params, external::remove_exchange_offer) } /// Send to transaction pool **MosaicSupplyChange transaction** @@ -273,7 +273,7 @@ pub fn remove_exchange_offer(params: &RemoveExchangeOffer) -> FunctionResult { /// ``` /// pub fn mosaic_supply_change(params: &MosaicSupplyChange) -> FunctionResult { - call_external_func(params, external::mosaic_supply_change) + simple_call_external_func(params, external::mosaic_supply_change) } /// Send to transaction pool **RegisterRootNamespace transaction** @@ -298,7 +298,7 @@ pub fn mosaic_supply_change(params: &MosaicSupplyChange) -> FunctionResult { /// ``` /// pub fn register_root_namespace(params: &RegisterRootNamespace) -> FunctionResult { - call_external_func(params, external::register_root_namespace) + simple_call_external_func(params, external::register_root_namespace) } /// Send to transaction pool **RegisterRootNamespace transaction** @@ -323,7 +323,7 @@ pub fn register_root_namespace(params: &RegisterRootNamespace) -> FunctionResult /// ``` /// pub fn register_sub_namespace(params: &RegisterSubNamespace) -> FunctionResult { - call_external_func(params, external::register_sub_namespace) + simple_call_external_func(params, external::register_sub_namespace) } /// Send to transaction pool **SecretLock transaction** @@ -350,7 +350,7 @@ pub fn register_sub_namespace(params: &RegisterSubNamespace) -> FunctionResult { /// ``` /// pub fn secret_lock(params: &SecretLock) -> FunctionResult { - call_external_func(params, external::secret_lock) + simple_call_external_func(params, external::secret_lock) } /// Send to transaction pool **SecretProof transaction** @@ -376,7 +376,7 @@ pub fn secret_lock(params: &SecretLock) -> FunctionResult { /// ``` /// pub fn secret_proof(params: &SecretProof) -> FunctionResult { - call_external_func(params, external::secret_proof) + simple_call_external_func(params, external::secret_proof) } /// Send to transaction pool **TransferWithNamespace transaction** @@ -401,7 +401,7 @@ pub fn secret_proof(params: &SecretProof) -> FunctionResult { /// ``` /// pub fn transfer_with_namespace(params: &TransferWithNamespace) -> FunctionResult { - call_external_func(params, external::transfer_with_namespace) + simple_call_external_func(params, external::transfer_with_namespace) } /// Send to transaction pool **ModifyMetadataAddress transaction** @@ -425,7 +425,7 @@ pub fn transfer_with_namespace(params: &TransferWithNamespace) -> FunctionResult /// ``` /// pub fn modify_metadata_address(params: &ModifyMetadataAddress) -> FunctionResult { - call_external_func(params, external::modify_metadata_address) + simple_call_external_func(params, external::modify_metadata_address) } /// Send to transaction pool **ModifyMetadataMosaic transaction** @@ -449,7 +449,7 @@ pub fn modify_metadata_address(params: &ModifyMetadataAddress) -> FunctionResult /// ``` /// pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { - call_external_func(params, external::modify_metadata_mosaic) + simple_call_external_func(params, external::modify_metadata_mosaic) } /// Send to transaction pool **ModifyMetadataNamespace transaction** @@ -473,7 +473,7 @@ pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { /// ``` /// pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionResult { - call_external_func(params, external::modify_metadata_namespace) + simple_call_external_func(params, external::modify_metadata_namespace) } /// Get data via **GetAccountExchangeInfo** From 7e155cee9a8d3377f3d1b600347c73efe1b5368d Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 25 Feb 2020 00:42:00 +0200 Subject: [PATCH 11/28] Added Init func (constructor function). Fixed types definitions. --- src/external.rs | 1 + src/transactions.rs | 4 ++-- src/transactions_type.rs | 6 +++--- src/utils.rs | 36 +++++++++++++++++++++++++++++++----- 4 files changed, 37 insertions(+), 10 deletions(-) diff --git a/src/external.rs b/src/external.rs index f481c5f..130e868 100644 --- a/src/external.rs +++ b/src/external.rs @@ -1,5 +1,6 @@ extern "C" { pub fn __ping(number: usize) -> i64; + pub fn init() -> i64; pub fn __write_log(msg: *const u8, len: usize) -> i64; pub fn save_to_storage( file_ptr: *const u8, diff --git a/src/transactions.rs b/src/transactions.rs index 53e41fe..98e15ee 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -462,7 +462,7 @@ pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { /// use xpx_supercontracts_sdk::transactions_type::ModifyMetadataNamespace; /// /// let params = ModifyMetadataNamespace{ -/// namespace_id: 10, +/// namespace_id: Some(10), /// modifications: None, /// }; /// // Add transaction to Transactions Pool @@ -486,7 +486,7 @@ pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionRe /// use xpx_supercontracts_sdk::transactions_type::{GetAccountExchangeInfo, UserExchangeInfo}; /// /// let params = GetAccountExchangeInfo{ -/// account: None, +/// pub_key: None, /// }; /// // Get info data /// let result = get_account_exchange_info(¶ms); diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 5bbac7d..2baab0c 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -147,7 +147,7 @@ pub struct RegisterRootNamespace { #[derive(Debug, Deserialize, Serialize)] pub struct RegisterSubNamespace { pub namespace_name: String, - pub parent_id: NamespaceId, + pub parent_id: Option, } #[derive(Debug, Deserialize, Serialize)] @@ -210,7 +210,7 @@ pub struct MetadataModification { #[derive(Debug, Deserialize, Serialize)] pub struct ModifyMetadataNamespace { - pub namespace_id: NamespaceId, + pub namespace_id: Option, pub modifications: Option>, } @@ -232,7 +232,7 @@ pub struct UserExchangeInfo { #[derive(Debug, Deserialize, Serialize)] pub struct GetAccountExchangeInfo { - pub account: Option, + pub pub_key: Option, } #[derive(Debug, Deserialize, Serialize)] diff --git a/src/utils.rs b/src/utils.rs index 8888108..45638a4 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -3,6 +3,32 @@ use crate::external; use crate::statuses::FunctionResult; +/// Init is function constructor that can can invoked only one time. +/// +/// Most useful case is run some specifuc functionality and +/// functions to tune-up and prepare some state for SuperContract. +/// +/// It's impossible run that function twice. +/// +/// # Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::utils::{init, ping}; +/// init(|| { +/// let respond = ping(10); +/// assert_eq!(respond.unwrap(), 11); +/// }); +/// ``` +/// +pub fn init(init_handler: fn() -> ()) { + unsafe { + let status = external::init(); + if status != 0 { + return; + } + }; + init_handler(); +} + /// Send ping message to `WasmVM`. Successful result should be /// incremented value. Useful for most simple request/response /// message tests for `WasmVM`. @@ -14,7 +40,7 @@ use crate::statuses::FunctionResult; /// assert_eq!(respond.unwrap(), 11); /// ``` pub fn ping(msg: usize) -> FunctionResult { - return unsafe { Ok(external::__ping(msg)) }; + return unsafe { Ok(external::__ping(msg)) }; } /// Send debug message to `WasmVM`. It's convenient @@ -31,8 +57,8 @@ pub fn ping(msg: usize) -> FunctionResult { /// debug_message(&"Debug message from Supercontract".to_string()); /// ``` pub fn debug_message(msg: &String) { - let raw_msg = msg.as_bytes(); - unsafe { - external::__write_log(raw_msg.as_ptr(), raw_msg.len()); - }; + let raw_msg = msg.as_bytes(); + unsafe { + external::__write_log(raw_msg.as_ptr(), raw_msg.len()); + }; } From 9588107133b231b99aee4b01c10b8efdc12df392 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Wed, 26 Feb 2020 18:51:57 +0200 Subject: [PATCH 12/28] Added Constructor function --- Cargo.toml | 4 ++++ examples/README.md | 2 +- examples/mosaic.rs | 12 ++++++++++++ src/external.rs | 3 ++- src/utils.rs | 31 ++++++++++++++++++++++++++++++- 5 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 examples/mosaic.rs diff --git a/Cargo.toml b/Cargo.toml index 539426f..b737030 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,10 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" failure = "0.1.5" +[[example]] +name = "mosaic" +crate-type = ["cdylib"] + [[example]] name = "ping" crate-type = ["cdylib"] diff --git a/examples/README.md b/examples/README.md index d779834..e8b65be 100644 --- a/examples/README.md +++ b/examples/README.md @@ -3,7 +3,7 @@ That directory provide basic examples for **How-To** work with SDK. ### Examples list -* `ping`git c +* `ping` * `http` * `debug` diff --git a/examples/mosaic.rs b/examples/mosaic.rs new file mode 100644 index 0000000..7819379 --- /dev/null +++ b/examples/mosaic.rs @@ -0,0 +1,12 @@ +use xpx_supercontracts_sdk::{ + transactions::mosaic_definition, + utils::init, +}; + +pub fn create_mosaic() {} + +#[no_mangle] +pub extern "C" fn app_main() -> i64 { + init(create_mosaic); + 0 +} diff --git a/src/external.rs b/src/external.rs index 130e868..725bd32 100644 --- a/src/external.rs +++ b/src/external.rs @@ -1,6 +1,7 @@ extern "C" { pub fn __ping(number: usize) -> i64; - pub fn init() -> i64; + pub fn __constructor() -> i64; + pub fn __init() -> i64; pub fn __write_log(msg: *const u8, len: usize) -> i64; pub fn save_to_storage( file_ptr: *const u8, diff --git a/src/utils.rs b/src/utils.rs index 45638a4..3706b97 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -3,6 +3,35 @@ use crate::external; use crate::statuses::FunctionResult; +/// Constructor is function for one time call that can +/// can invoke only once for all lifetime of SuperContract. +/// +/// Most useful case is run some specific functionality and +/// functions once for SuperContract life. Example: create Mosaic +/// +/// Difference from `init` fucntion that, function can call +/// every time when execute some SuperContract function. And +/// for that concrete function it can call only once. +/// +/// # Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::utils::{constructor, ping}; +/// constructor(|| { +/// let respond = ping(10); +/// assert_eq!(respond.unwrap(), 11); +/// }); +/// ``` +/// +pub fn constructor(init_handler: fn() -> ()) { + unsafe { + let status = external::__constructor(); + if status != 0 { + return; + } + }; + init_handler(); +} + /// Init is function constructor that can can invoked only one time. /// /// Most useful case is run some specifuc functionality and @@ -21,7 +50,7 @@ use crate::statuses::FunctionResult; /// pub fn init(init_handler: fn() -> ()) { unsafe { - let status = external::init(); + let status = external::__init(); if status != 0 { return; } From a3bbce626877d2e8a4b232104b4f664dd74910db Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Wed, 26 Feb 2020 22:11:42 +0200 Subject: [PATCH 13/28] Added mosaic example and changed func constructor --- examples/mosaic.rs | 34 ++++++++++++++++++++++++++++++---- src/external.rs | 5 ++++- src/transactions.rs | 29 +++++++++++++++++++++++++++++ src/transactions_type.rs | 21 +++++++++++++++++++++ src/utils.rs | 15 +++++++++------ 5 files changed, 93 insertions(+), 11 deletions(-) diff --git a/examples/mosaic.rs b/examples/mosaic.rs index 7819379..edf158b 100644 --- a/examples/mosaic.rs +++ b/examples/mosaic.rs @@ -1,12 +1,38 @@ use xpx_supercontracts_sdk::{ transactions::mosaic_definition, - utils::init, + transactions_type::{MosaicDefinition, MosaicProperties, MosaicProperty}, + utils::{constructor, debug_message}, }; +use xpx_supercontracts_sdk::transactions_type::{FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE, FUNCTION_RETURN_SUCCESS, FUNCTION_ERROR}; -pub fn create_mosaic() {} +pub fn create_mosaic() -> i64 { + let res = mosaic_definition(&MosaicDefinition { + nonce: 0, + owner_public_key: vec![], + mosaic_props: Some(MosaicProperties { + supply_mutable: true, + transferable: true, + divisibility: 0, + optional_properties: vec![MosaicProperty { + id: 0, + value: 0, + }], + }), + }); + if res.is_err() { + return FUNCTION_ERROR; + } + if res.unwrap() < FUNCTION_RETURN_SUCCESS { + debug_message(&"failed create mosaic".to_string()); + } + FUNCTION_RETURN_SUCCESS +} #[no_mangle] pub extern "C" fn app_main() -> i64 { - init(create_mosaic); - 0 + let res = constructor(create_mosaic); + if res != FUNCTION_RETURN_SUCCESS && res == FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE { + return res; + } + FUNCTION_RETURN_SUCCESS } diff --git a/src/external.rs b/src/external.rs index 725bd32..10d7a63 100644 --- a/src/external.rs +++ b/src/external.rs @@ -60,7 +60,7 @@ extern "C" { pub fn mosaic_supply_change( data_ptr: *const u8, data_len: usize, - ) -> i64; + ) -> i64; pub fn register_root_namespace( data_ptr: *const u8, data_len: usize, @@ -140,4 +140,7 @@ extern "C" { data_len: usize, data: *mut u8, ) -> i64; + pub fn get_supercontract( + data: *mut u8, + ) -> i64; } diff --git a/src/transactions.rs b/src/transactions.rs index 98e15ee..f0662eb 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -24,6 +24,7 @@ use serde::de::DeserializeOwned; use crate::external; use crate::statuses::{FunctionResult, Result}; +use crate::statuses::Error; use crate::tools::call::{call_external_func, simple_call_external_func}; use crate::transactions_type::*; @@ -689,3 +690,31 @@ pub fn get_transaction_statuses(params: &GetTransactionStatuses) -> Result Result { call_external_func(params, external::get_transaction_effective_fee) } + +/// Get data current SuperContract data +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// get_supercontract, +/// }; +/// +/// // Get SC data +/// let result = get_supercontract(); +/// let sc = result.unwrap(); +/// ``` +/// +pub fn get_supercontract() -> Result { + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = external::get_supercontract(fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; + + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) +} diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 2baab0c..3f074ab 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -7,6 +7,10 @@ use std::collections::HashMap; use serde::{Deserialize, Serialize}; +pub const FUNCTION_RETURN_SUCCESS: i64 = 0; +pub const FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE: i64 = -39; +pub const FUNCTION_ERROR: i64 = -1000; + pub type NetworkType = u8; pub type EntityType = u16; pub type EntityVersion = u32; @@ -31,6 +35,23 @@ pub type TransactionID = [u8; 32]; pub type TransactionType = u8; pub type Signature = [u8; 64]; +#[derive(Debug, Deserialize, Serialize)] +pub struct Drive { + id: Hash, + owner: PubKey, + root: Hash, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct SuperContract { + id: Hash, + drive: Drive, + file: Hash, + vm_version: u64, + functions: Vec, +} + + #[derive(Debug, Deserialize, Serialize)] pub struct AbstractTransaction { pub height: Height, diff --git a/src/utils.rs b/src/utils.rs index 3706b97..8566b29 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -2,6 +2,7 @@ use crate::external; use crate::statuses::FunctionResult; +use crate::transactions_type::FUNCTION_RETURN_SUCCESS; /// Constructor is function for one time call that can /// can invoke only once for all lifetime of SuperContract. @@ -16,20 +17,22 @@ use crate::statuses::FunctionResult; /// # Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::utils::{constructor, ping}; -/// constructor(|| { +/// let res = constructor(|| -> i64 { /// let respond = ping(10); -/// assert_eq!(respond.unwrap(), 11); +/// let res = respond.unwrap(); +/// assert_eq!(res, 11); +/// res /// }); /// ``` /// -pub fn constructor(init_handler: fn() -> ()) { +pub fn constructor(constructor_handler: fn() -> i64) -> i64 { unsafe { let status = external::__constructor(); - if status != 0 { - return; + if status != FUNCTION_RETURN_SUCCESS { + return status; } }; - init_handler(); + constructor_handler() } /// Init is function constructor that can can invoked only one time. From ef9bb3cae75d1cbce4c09bf13d4d62ded3f62d95 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 27 Feb 2020 22:32:34 +0200 Subject: [PATCH 14/28] Changed examples for more common usage --- Cargo.toml | 4 ++++ examples/common.rs | 20 ++++++++++++++++++++ examples/http.rs | 2 +- examples/mosaic.rs | 11 +++++++++-- src/transactions_type.rs | 10 +++++----- 5 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 examples/common.rs diff --git a/Cargo.toml b/Cargo.toml index b737030..dc6d148 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,10 @@ crate-type = ["cdylib"] name = "ping" crate-type = ["cdylib"] +[[example]] +name = "common" +crate-type = ["cdylib"] + [[example]] name = "debug" crate-type = ["cdylib"] diff --git a/examples/common.rs b/examples/common.rs new file mode 100644 index 0000000..c848dca --- /dev/null +++ b/examples/common.rs @@ -0,0 +1,20 @@ +use xpx_supercontracts_sdk::utils::{constructor, init, ping}; + +#[no_mangle] +pub extern "C" fn ping100() -> i64 { + ping(100).unwrap() +} + +#[no_mangle] +pub extern "C" fn ping100init() -> i64 { + let _ = init(|| { ping(100).unwrap(); }); + let _ = init(|| { ping(100).unwrap(); }); + ping(100).unwrap() +} + +#[no_mangle] +pub extern "C" fn ping100constructor() -> i64 { + let _ = constructor(|| ping(100).unwrap()); + let _ = constructor(|| ping(100).unwrap()); + ping(100).unwrap() +} diff --git a/examples/http.rs b/examples/http.rs index 43668d5..ae37ee0 100644 --- a/examples/http.rs +++ b/examples/http.rs @@ -7,7 +7,7 @@ pub extern "C" fn app_main() -> i64 { let mut headers: HashMap = HashMap::new(); headers.insert("content-type".to_string(), "text/html".to_string()); let req = HttpRequest { - url: "http://google.com/".to_string(), + url: "https://s.dou.ua/files/dou-200x200.png".to_string(), headers: headers, }; let resp = http_get(&req); diff --git a/examples/mosaic.rs b/examples/mosaic.rs index edf158b..7699d1f 100644 --- a/examples/mosaic.rs +++ b/examples/mosaic.rs @@ -3,12 +3,19 @@ use xpx_supercontracts_sdk::{ transactions_type::{MosaicDefinition, MosaicProperties, MosaicProperty}, utils::{constructor, debug_message}, }; -use xpx_supercontracts_sdk::transactions_type::{FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE, FUNCTION_RETURN_SUCCESS, FUNCTION_ERROR}; +use xpx_supercontracts_sdk::transactions::get_supercontract; +use xpx_supercontracts_sdk::transactions_type::{FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE, FUNCTION_ERROR, FUNCTION_RETURN_SUCCESS, SuperContract}; pub fn create_mosaic() -> i64 { + let res = get_supercontract(); + if res.is_err() { + return -1; + } + let sc: SuperContract = res.unwrap(); + let res = mosaic_definition(&MosaicDefinition { nonce: 0, - owner_public_key: vec![], + owner_public_key: sc.id.to_vec(), mosaic_props: Some(MosaicProperties { supply_mutable: true, transferable: true, diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 3f074ab..feebb53 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -44,11 +44,11 @@ pub struct Drive { #[derive(Debug, Deserialize, Serialize)] pub struct SuperContract { - id: Hash, - drive: Drive, - file: Hash, - vm_version: u64, - functions: Vec, + pub id: Hash, + pub drive: Drive, + pub file: Hash, + pub vm_version: u64, + pub functions: Vec, } From 29835f5f0dfcbb94f8c5ace93e9b5e6527a6791b Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 28 Feb 2020 08:52:17 +0200 Subject: [PATCH 15/28] Changed Mosaic exemple --- examples/mosaic.rs | 3 ++- src/transactions_type.rs | 15 +++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/mosaic.rs b/examples/mosaic.rs index 7699d1f..e526700 100644 --- a/examples/mosaic.rs +++ b/examples/mosaic.rs @@ -13,9 +13,10 @@ pub fn create_mosaic() -> i64 { } let sc: SuperContract = res.unwrap(); + debug_message(&format!("SC.ID: {:?}", sc.drive.owner)); let res = mosaic_definition(&MosaicDefinition { nonce: 0, - owner_public_key: sc.id.to_vec(), + owner_public_key: sc.drive.owner, mosaic_props: Some(MosaicProperties { supply_mutable: true, transferable: true, diff --git a/src/transactions_type.rs b/src/transactions_type.rs index feebb53..5750c44 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -37,18 +37,17 @@ pub type Signature = [u8; 64]; #[derive(Debug, Deserialize, Serialize)] pub struct Drive { - id: Hash, - owner: PubKey, - root: Hash, + pub drive: String, + pub owner: String, + pub root: String, } #[derive(Debug, Deserialize, Serialize)] pub struct SuperContract { - pub id: Hash, + pub id: String, pub drive: Drive, - pub file: Hash, - pub vm_version: u64, - pub functions: Vec, + pub file: String, + pub vmversion: u64, } @@ -74,7 +73,7 @@ pub struct AbstractTransaction { #[derive(Debug, Deserialize, Serialize)] pub struct MosaicDefinition { pub nonce: u32, - pub owner_public_key: Vec, + pub owner_public_key: String, pub mosaic_props: Option, } From 1d3c9bc8645599d620d4d7ac210f5b04a1a30e0b Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 28 Feb 2020 12:31:41 +0200 Subject: [PATCH 16/28] Changed types --- examples/common.rs | 24 +++++++++++++++++++++++- examples/mosaic.rs | 4 ++-- src/external.rs | 1 + src/transactions.rs | 4 ++-- src/transactions_type.rs | 37 +++++++++++++++++++------------------ src/utils.rs | 14 ++++++++++++++ 6 files changed, 61 insertions(+), 23 deletions(-) diff --git a/examples/common.rs b/examples/common.rs index c848dca..27c7d84 100644 --- a/examples/common.rs +++ b/examples/common.rs @@ -1,4 +1,7 @@ -use xpx_supercontracts_sdk::utils::{constructor, init, ping}; +use serde::Serialize; + +use xpx_supercontracts_sdk::utils::{constructor, init, ping, debug_message}; +use xpx_supercontracts_sdk::storage::save_result; #[no_mangle] pub extern "C" fn ping100() -> i64 { @@ -18,3 +21,22 @@ pub extern "C" fn ping100constructor() -> i64 { let _ = constructor(|| ping(100).unwrap()); ping(100).unwrap() } + +#[no_mangle] +pub extern "C" fn save_sample_result() -> i64 { + #[derive(Serialize)] + struct SampleData<'a> { + pub id: i64, + pub message: &'a str, + } + let data = serde_json::to_vec(&SampleData{ + id: 10, + message: "awesome message", + }).unwrap(); + let res = save_result(&"data.txt".to_string(), &data[..]); + if let Err(err) = res { + debug_message(&format!("save_result error {:?}", err)); + return -1; + } + res.unwrap() +} \ No newline at end of file diff --git a/examples/mosaic.rs b/examples/mosaic.rs index e526700..58a9bff 100644 --- a/examples/mosaic.rs +++ b/examples/mosaic.rs @@ -13,10 +13,10 @@ pub fn create_mosaic() -> i64 { } let sc: SuperContract = res.unwrap(); - debug_message(&format!("SC.ID: {:?}", sc.drive.owner)); + debug_message(&format!("SC.ID: {:?}", sc.id)); let res = mosaic_definition(&MosaicDefinition { nonce: 0, - owner_public_key: sc.drive.owner, + owner_public_key: sc.id, mosaic_props: Some(MosaicProperties { supply_mutable: true, transferable: true, diff --git a/src/external.rs b/src/external.rs index 10d7a63..bac6919 100644 --- a/src/external.rs +++ b/src/external.rs @@ -2,6 +2,7 @@ extern "C" { pub fn __ping(number: usize) -> i64; pub fn __constructor() -> i64; pub fn __init() -> i64; + pub fn __inc() -> i64; pub fn __write_log(msg: *const u8, len: usize) -> i64; pub fn save_to_storage( file_ptr: *const u8, diff --git a/src/transactions.rs b/src/transactions.rs index f0662eb..85f5584 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -49,7 +49,7 @@ use crate::transactions_type::*; /// }; /// use xpx_supercontracts_sdk::transactions_type::MosaicDefinition; /// -/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".as_bytes().to_vec(); +/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".to_string(); /// let params = MosaicDefinition{ /// nonce: 100, /// owner_public_key: pub_key, @@ -81,7 +81,7 @@ pub fn flush() -> FunctionResult { /// }; /// use xpx_supercontracts_sdk::transactions_type::MosaicDefinition; /// -/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".as_bytes().to_vec(); +/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".to_string(); /// let params = MosaicDefinition{ /// nonce: 100, /// owner_public_key: pub_key, diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 5750c44..cef991a 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -11,42 +11,43 @@ pub const FUNCTION_RETURN_SUCCESS: i64 = 0; pub const FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE: i64 = -39; pub const FUNCTION_ERROR: i64 = -1000; +pub type Cid = String; pub type NetworkType = u8; pub type EntityType = u16; pub type EntityVersion = u32; pub type Amount = i64; pub type Deadline = i64; -pub type PublicAccount = [u8; 32]; +pub type PublicAccount = String; pub type Height = i64; -pub type Hash = [u8; 32]; -pub type Address = [u8; 25]; +pub type Hash = String; +pub type Address = String; pub type NamespaceId = i64; pub type AliasActionType = u8; pub type MosaicId = i64; -pub type PubKey = [u8; 32]; +pub type PubKey = String; pub type AssetId = u64; pub type Duration = i64; pub type MosaicSupplyType = u8; pub type MetadataModificationType = u8; pub type HashType = u8; -pub type Message = Vec; +pub type Message = String; pub type OfferType = u8; -pub type TransactionID = [u8; 32]; +pub type TransactionID = String; pub type TransactionType = u8; -pub type Signature = [u8; 64]; +pub type Signature = String; #[derive(Debug, Deserialize, Serialize)] pub struct Drive { - pub drive: String, - pub owner: String, - pub root: String, + pub drive: Cid, + pub owner: PubKey, + pub root: Cid, } #[derive(Debug, Deserialize, Serialize)] pub struct SuperContract { - pub id: String, + pub id: Cid, pub drive: Drive, - pub file: String, + pub file: Cid, pub vmversion: u64, } @@ -333,7 +334,7 @@ pub trait SignedTransaction { fn id(&self) -> TransactionID; fn transaction_type(&self) -> TransactionType; fn signer(&self) -> PubKey; - fn signature(&self) -> Vec; + fn signature(&self) -> Signature; } #[derive(Debug, Deserialize, Serialize, Clone)] @@ -348,7 +349,7 @@ pub struct DriveFsTransaction { pub id: TransactionID, pub transaction_type: TransactionType, pub signer: PubKey, - pub signature: Vec, + pub signature: Signature, pub drive_id: Hash, pub add_actions: Option>, pub remove_actions: Option>, @@ -356,7 +357,7 @@ pub struct DriveFsTransaction { impl DriveFsTransaction { pub fn drive_id(&self) -> Hash { - self.drive_id + self.drive_id.clone() } pub fn add_actions(&self) -> Option> { @@ -370,7 +371,7 @@ impl DriveFsTransaction { impl SignedTransaction for DriveFsTransaction { fn id(&self) -> TransactionID { - self.id + self.id.clone() } fn transaction_type(&self) -> TransactionType { @@ -378,10 +379,10 @@ impl SignedTransaction for DriveFsTransaction { } fn signer(&self) -> PubKey { - self.signer + self.signer.clone() } - fn signature(&self) -> Vec { + fn signature(&self) -> Signature { self.signature.clone() } } diff --git a/src/utils.rs b/src/utils.rs index 8566b29..6425e2e 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -75,6 +75,20 @@ pub fn ping(msg: usize) -> FunctionResult { return unsafe { Ok(external::__ping(msg)) }; } +/// Return incremented result from all previous invoke that functions. +/// +/// Useful for calculating some incremented state. +/// +/// # Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::utils::inc; +/// let respond = inc(); +/// assert_eq!(respond.unwrap(), 11); +/// ``` +pub fn inc() -> FunctionResult { + return unsafe { Ok(external::__inc()) }; +} + /// Send debug message to `WasmVM`. It's convenient /// basic function for development debugging. /// Message that was sent will display in `WasmVM` From f1c33ddad0b01a356815599f7fb2a44658a1e790 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Tue, 3 Mar 2020 16:51:16 +0200 Subject: [PATCH 17/28] Changed Doc Example tests. Change example/common sample code --- examples/common.rs | 19 ++++++++++++++++++- src/transactions.rs | 16 +++++++--------- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/examples/common.rs b/examples/common.rs index 27c7d84..464ba4b 100644 --- a/examples/common.rs +++ b/examples/common.rs @@ -1,6 +1,7 @@ use serde::Serialize; use xpx_supercontracts_sdk::utils::{constructor, init, ping, debug_message}; +use xpx_supercontracts_sdk::transactions as tx; use xpx_supercontracts_sdk::storage::save_result; #[no_mangle] @@ -15,6 +16,11 @@ pub extern "C" fn ping100init() -> i64 { ping(100).unwrap() } +#[no_mangle] +pub extern "C" fn ping_with_params(x: i64) -> i64 { + ping(x as usize).unwrap() +} + #[no_mangle] pub extern "C" fn ping100constructor() -> i64 { let _ = constructor(|| ping(100).unwrap()); @@ -39,4 +45,15 @@ pub extern "C" fn save_sample_result() -> i64 { return -1; } res.unwrap() -} \ No newline at end of file +} + +#[no_mangle] +pub extern "C" fn get_sc() -> i64 { + let res = tx::get_supercontract(); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("SC.ID: {:?}", res.unwrap().id)); + 0 +} diff --git a/src/transactions.rs b/src/transactions.rs index 85f5584..d0f2132 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -208,11 +208,9 @@ pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { /// }; /// use xpx_supercontracts_sdk::transactions_type::{Transfer, PubKey}; /// -/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".as_bytes(); -/// let mut pk: PubKey = [0; 32]; -/// pk.copy_from_slice(&pub_key[..32]); +/// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".to_string(); /// let params = Transfer{ -/// pub_key: pk, +/// pub_key: pub_key, /// asset_id: 10, /// amount: 1000, /// }; @@ -392,7 +390,7 @@ pub fn secret_proof(params: &SecretProof) -> FunctionResult { /// let params = TransferWithNamespace{ /// recipient: None, /// mosaics: None, -/// message: "some message".as_bytes().to_vec(), +/// message: "some message".to_string(), /// }; /// // Add transaction to Transactions Pool /// let tx_result = transfer_with_namespace(¶ms); @@ -613,7 +611,7 @@ pub fn get_mosaics_names(params: &GetMosaicsNames) -> Result = get_transaction(¶ms); @@ -638,7 +636,7 @@ pub fn get_transaction(params: &GetTran /// use xpx_supercontracts_sdk::transactions_type::{GetTransactionStatus, TransactionStatus}; /// /// let params = GetTransactionStatus{ -/// id: [0; 32], +/// id: String::from("some_id"), /// }; /// // Get info data /// let result = get_transaction_status(¶ms); @@ -659,7 +657,7 @@ pub fn get_transaction_status(params: &GetTransactionStatus) -> Result Result Date: Tue, 3 Mar 2020 21:08:26 +0200 Subject: [PATCH 18/28] Common Examples for test functions --- examples/common.rs | 252 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 249 insertions(+), 3 deletions(-) diff --git a/examples/common.rs b/examples/common.rs index 464ba4b..eaac09b 100644 --- a/examples/common.rs +++ b/examples/common.rs @@ -1,8 +1,11 @@ use serde::Serialize; -use xpx_supercontracts_sdk::utils::{constructor, init, ping, debug_message}; -use xpx_supercontracts_sdk::transactions as tx; +use xpx_supercontracts_sdk::statuses::Result; use xpx_supercontracts_sdk::storage::save_result; +use xpx_supercontracts_sdk::transactions as tx; +use xpx_supercontracts_sdk::transactions::get_transaction; +use xpx_supercontracts_sdk::transactions_type::{DriveFsTransaction, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, ModifyMetadataNamespace, Mosaic, RegisterSubNamespace, Secret, SecretLock, SecretProof, TransferWithNamespace, RegisterRootNamespace}; +use xpx_supercontracts_sdk::utils::{constructor, debug_message, init, ping}; #[no_mangle] pub extern "C" fn ping100() -> i64 { @@ -35,7 +38,7 @@ pub extern "C" fn save_sample_result() -> i64 { pub id: i64, pub message: &'a str, } - let data = serde_json::to_vec(&SampleData{ + let data = serde_json::to_vec(&SampleData { id: 10, message: "awesome message", }).unwrap(); @@ -57,3 +60,246 @@ pub extern "C" fn get_sc() -> i64 { debug_message(&format!("SC.ID: {:?}", res.unwrap().id)); 0 } + +#[no_mangle] +pub extern "C" fn get_transaction_effective_fee() -> i64 { + let res = tx::get_transaction_effective_fee(&GetTransactionEffectiveFee { + id: String::from("some_id"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn get_tx() -> i64 { + let tx_result: Result = get_transaction(&GetTransaction { + id: String::from("some_id"), + }); + if let Err(err) = tx_result { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", tx_result.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn get_transaction_status() -> i64 { + let res = tx::get_transaction_status(&GetTransactionStatus { + id: String::from("some_id"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn get_transaction_statuses() -> i64 { + let res = tx::get_transaction_statuses(&GetTransactionStatuses { + ids: vec![String::from("some_id")], + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + + +//--- +#[no_mangle] +pub extern "C" fn get_account_exchange_info() -> i64 { + let res = tx::get_account_exchange_info(&GetAccountExchangeInfo { + pub_key: Some(String::from("some_pub_key")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn get_exchange_offer_by_asset_id() -> i64 { + let res = tx::get_exchange_offer_by_asset_id(&GetExchangeOfferByAssetId { + asset_id: 1, + offer_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn get_mosaic_info() -> i64 { + let res = tx::get_mosaic_info(&GetMosaicInfo { + mosaic_id: Some(1), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn get_mosaic_infos() -> i64 { + let res = tx::get_mosaic_infos(&GetMosaicInfos { + msc_ids: Some(vec![2]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn get_mosaics_names() -> i64 { + let res = tx::get_mosaics_names(&GetMosaicsNames { + msc_ids: Some(vec![1]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn modify_metadata_namespace() -> i64 { + let res = tx::modify_metadata_namespace(&ModifyMetadataNamespace { + namespace_id: Some(1), + modifications: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn modify_metadata_mosaic() -> i64 { + let res = tx::modify_metadata_mosaic(&ModifyMetadataMosaic { + mosaic_id: Some(1), + modifications: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn modify_metadata_address() -> i64 { + let res = tx::modify_metadata_address(&ModifyMetadataAddress { + address: Some(String::from("some_address")), + modifications: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn secret_proof() -> i64 { + let res = tx::secret_proof(&SecretProof { + hash_type: 1, + proof: None, + recipient: Some(String::from("some recipient")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn transfer_with_namespace() -> i64 { + let res = tx::transfer_with_namespace(&TransferWithNamespace { + recipient: Some(1), + mosaics: Some(vec![]), + message: String::from("some message"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + + +#[no_mangle] +pub extern "C" fn secret_lock() -> i64 { + let res = tx::secret_lock(&SecretLock { + mosaic: Some(Mosaic { + asset_id: 1, + amount: 1000, + }), + duration: 10000, + secret: Some(Secret { + hash: String::from("some hash"), + hash_type: 1, + }), + recipient: Some(String::from("some addr")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn register_sub_namespace() -> i64 { + let res = tx::register_sub_namespace(&RegisterSubNamespace { + namespace_name: String::from("name"), + parent_id: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn register_root_namespace() -> i64 { + let res = tx::register_root_namespace(&RegisterRootNamespace { + namespace_name: String::from("name"), + duration: 1000, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} From 8da72a12ef52499ed85a371a945af59038e25bf2 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Wed, 4 Mar 2020 01:34:13 +0200 Subject: [PATCH 19/28] Added all sdk-functions to examples/common --- examples/common.rs | 161 +++++++++++++++++++++++++++++++++------ src/transactions_type.rs | 12 +-- 2 files changed, 145 insertions(+), 28 deletions(-) diff --git a/examples/common.rs b/examples/common.rs index eaac09b..c935b61 100644 --- a/examples/common.rs +++ b/examples/common.rs @@ -3,8 +3,7 @@ use serde::Serialize; use xpx_supercontracts_sdk::statuses::Result; use xpx_supercontracts_sdk::storage::save_result; use xpx_supercontracts_sdk::transactions as tx; -use xpx_supercontracts_sdk::transactions::get_transaction; -use xpx_supercontracts_sdk::transactions_type::{DriveFsTransaction, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, ModifyMetadataNamespace, Mosaic, RegisterSubNamespace, Secret, SecretLock, SecretProof, TransferWithNamespace, RegisterRootNamespace}; +use xpx_supercontracts_sdk::transactions_type::{AddExchangeOffer, AddOffer, AddressAlias, DriveFsTransaction, ExchangeConfirmation, ExchangeOffer, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, ModifyMetadataNamespace, Mosaic, MosaicAlias, MosaicSupplyChange, RegisterRootNamespace, RegisterSubNamespace, RemoveExchangeOffer, RemoveOffer, Secret, SecretLock, SecretProof, Transfer, TransferWithNamespace}; use xpx_supercontracts_sdk::utils::{constructor, debug_message, init, ping}; #[no_mangle] @@ -51,7 +50,7 @@ pub extern "C" fn save_sample_result() -> i64 { } #[no_mangle] -pub extern "C" fn get_sc() -> i64 { +pub extern "C" fn exmpl_get_supercontract() -> i64 { let res = tx::get_supercontract(); if let Err(err) = res { debug_message(&format!("{:?}", err)); @@ -62,7 +61,7 @@ pub extern "C" fn get_sc() -> i64 { } #[no_mangle] -pub extern "C" fn get_transaction_effective_fee() -> i64 { +pub extern "C" fn exmpl_get_transaction_effective_fee() -> i64 { let res = tx::get_transaction_effective_fee(&GetTransactionEffectiveFee { id: String::from("some_id"), }); @@ -75,8 +74,8 @@ pub extern "C" fn get_transaction_effective_fee() -> i64 { } #[no_mangle] -pub extern "C" fn get_tx() -> i64 { - let tx_result: Result = get_transaction(&GetTransaction { +pub extern "C" fn exmpl_get_transaction() -> i64 { + let tx_result: Result = tx::get_transaction(&GetTransaction { id: String::from("some_id"), }); if let Err(err) = tx_result { @@ -88,7 +87,7 @@ pub extern "C" fn get_tx() -> i64 { } #[no_mangle] -pub extern "C" fn get_transaction_status() -> i64 { +pub extern "C" fn exmpl_get_transaction_status() -> i64 { let res = tx::get_transaction_status(&GetTransactionStatus { id: String::from("some_id"), }); @@ -101,7 +100,7 @@ pub extern "C" fn get_transaction_status() -> i64 { } #[no_mangle] -pub extern "C" fn get_transaction_statuses() -> i64 { +pub extern "C" fn exmpl_get_transaction_statuses() -> i64 { let res = tx::get_transaction_statuses(&GetTransactionStatuses { ids: vec![String::from("some_id")], }); @@ -114,9 +113,8 @@ pub extern "C" fn get_transaction_statuses() -> i64 { } -//--- #[no_mangle] -pub extern "C" fn get_account_exchange_info() -> i64 { +pub extern "C" fn exmpl_get_account_exchange_info() -> i64 { let res = tx::get_account_exchange_info(&GetAccountExchangeInfo { pub_key: Some(String::from("some_pub_key")), }); @@ -129,7 +127,7 @@ pub extern "C" fn get_account_exchange_info() -> i64 { } #[no_mangle] -pub extern "C" fn get_exchange_offer_by_asset_id() -> i64 { +pub extern "C" fn exmpl_get_exchange_offer_by_asset_id() -> i64 { let res = tx::get_exchange_offer_by_asset_id(&GetExchangeOfferByAssetId { asset_id: 1, offer_type: 2, @@ -143,7 +141,7 @@ pub extern "C" fn get_exchange_offer_by_asset_id() -> i64 { } #[no_mangle] -pub extern "C" fn get_mosaic_info() -> i64 { +pub extern "C" fn exmpl_get_mosaic_info() -> i64 { let res = tx::get_mosaic_info(&GetMosaicInfo { mosaic_id: Some(1), }); @@ -156,7 +154,7 @@ pub extern "C" fn get_mosaic_info() -> i64 { } #[no_mangle] -pub extern "C" fn get_mosaic_infos() -> i64 { +pub extern "C" fn exmpl_get_mosaic_infos() -> i64 { let res = tx::get_mosaic_infos(&GetMosaicInfos { msc_ids: Some(vec![2]), }); @@ -169,7 +167,7 @@ pub extern "C" fn get_mosaic_infos() -> i64 { } #[no_mangle] -pub extern "C" fn get_mosaics_names() -> i64 { +pub extern "C" fn exmpl_get_mosaics_names() -> i64 { let res = tx::get_mosaics_names(&GetMosaicsNames { msc_ids: Some(vec![1]), }); @@ -182,7 +180,7 @@ pub extern "C" fn get_mosaics_names() -> i64 { } #[no_mangle] -pub extern "C" fn modify_metadata_namespace() -> i64 { +pub extern "C" fn exmpl_modify_metadata_namespace() -> i64 { let res = tx::modify_metadata_namespace(&ModifyMetadataNamespace { namespace_id: Some(1), modifications: None, @@ -196,7 +194,7 @@ pub extern "C" fn modify_metadata_namespace() -> i64 { } #[no_mangle] -pub extern "C" fn modify_metadata_mosaic() -> i64 { +pub extern "C" fn exmpl_modify_metadata_mosaic() -> i64 { let res = tx::modify_metadata_mosaic(&ModifyMetadataMosaic { mosaic_id: Some(1), modifications: None, @@ -210,7 +208,7 @@ pub extern "C" fn modify_metadata_mosaic() -> i64 { } #[no_mangle] -pub extern "C" fn modify_metadata_address() -> i64 { +pub extern "C" fn exmpl_modify_metadata_address() -> i64 { let res = tx::modify_metadata_address(&ModifyMetadataAddress { address: Some(String::from("some_address")), modifications: None, @@ -224,7 +222,7 @@ pub extern "C" fn modify_metadata_address() -> i64 { } #[no_mangle] -pub extern "C" fn secret_proof() -> i64 { +pub extern "C" fn exmpl_secret_proof() -> i64 { let res = tx::secret_proof(&SecretProof { hash_type: 1, proof: None, @@ -239,7 +237,7 @@ pub extern "C" fn secret_proof() -> i64 { } #[no_mangle] -pub extern "C" fn transfer_with_namespace() -> i64 { +pub extern "C" fn exmpl_transfer_with_namespace() -> i64 { let res = tx::transfer_with_namespace(&TransferWithNamespace { recipient: Some(1), mosaics: Some(vec![]), @@ -255,7 +253,7 @@ pub extern "C" fn transfer_with_namespace() -> i64 { #[no_mangle] -pub extern "C" fn secret_lock() -> i64 { +pub extern "C" fn exmpl_secret_lock() -> i64 { let res = tx::secret_lock(&SecretLock { mosaic: Some(Mosaic { asset_id: 1, @@ -277,7 +275,7 @@ pub extern "C" fn secret_lock() -> i64 { } #[no_mangle] -pub extern "C" fn register_sub_namespace() -> i64 { +pub extern "C" fn exmpl_register_sub_namespace() -> i64 { let res = tx::register_sub_namespace(&RegisterSubNamespace { namespace_name: String::from("name"), parent_id: None, @@ -291,7 +289,7 @@ pub extern "C" fn register_sub_namespace() -> i64 { } #[no_mangle] -pub extern "C" fn register_root_namespace() -> i64 { +pub extern "C" fn exmpl_register_root_namespace() -> i64 { let res = tx::register_root_namespace(&RegisterRootNamespace { namespace_name: String::from("name"), duration: 1000, @@ -303,3 +301,122 @@ pub extern "C" fn register_root_namespace() -> i64 { debug_message(&format!("Result: {:?}", res.unwrap())); 0 } + +#[no_mangle] +pub extern "C" fn exmpl_mosaic_supply_change() -> i64 { + let res = tx::mosaic_supply_change(&MosaicSupplyChange { + asset_id: 10, + supply_type: 100, + delta: 300, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn exmpl_remove_exchange_offer() -> i64 { + let res = tx::remove_exchange_offer(&RemoveExchangeOffer { + remove_offers: Some(vec![RemoveOffer { + asset_id: 10, + offer_type: 1, + }]) + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn exmpl_transfer() -> i64 { + let res = tx::transfer(&Transfer { + pub_key: String::from("some_pub_key"), + asset_id: 10, + amount: 1000, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn exmpl_exchange_offer() -> i64 { + let res = tx::exchange_offer(&ExchangeOffer { + offer: Some(vec![ExchangeConfirmation { + offer_type: 1, + mosaic: Some(Mosaic { + asset_id: 3, + amount: 10000, + }), + cost: 1000, + owner: Some(String::from("public account")), + }]) + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn exmpl_add_exchange_offer() -> i64 { + let res = tx::add_exchange_offer(&AddExchangeOffer { + add_offers: Some(vec![AddOffer { + offer_type: 3, + mosaic: Some(Mosaic { + amount: 1000, + asset_id: 3, + + }), + cost: 100, + duration: 1000, + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn exmpl_mosaic_alias() -> i64 { + let res = tx::mosaic_alias(&MosaicAlias { + mosaic_id: Some(10), + namespace_id: Some(3), + action_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn exmpl_address_alias() -> i64 { + let res = tx::address_alias(&AddressAlias { + address: Some(String::from("some addr")), + namespace_id: Some(3), + action_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} diff --git a/src/transactions_type.rs b/src/transactions_type.rs index cef991a..a6ebdde 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -115,10 +115,10 @@ pub struct AddExchangeOffer { #[derive(Debug, Deserialize, Serialize)] pub struct ExchangeConfirmation { - offer_type: OfferType, - mosaic: Option, - cost: Amount, - owner: Option, + pub offer_type: OfferType, + pub mosaic: Option, + pub cost: Amount, + pub owner: Option, } #[derive(Debug, Deserialize, Serialize)] @@ -143,8 +143,8 @@ pub struct Transfer { #[derive(Debug, Deserialize, Serialize)] pub struct RemoveOffer { - offer_type: OfferType, - asset_id: AssetId, + pub offer_type: OfferType, + pub asset_id: AssetId, } #[derive(Debug, Deserialize, Serialize)] From b0d3a0a2adaf37583d7df9d11c99cc607ab16ef8 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 5 Mar 2020 00:01:05 +0200 Subject: [PATCH 20/28] Changed examples/common. Fixed trantactions types --- examples/common.rs | 8 +++++--- src/tools/call.rs | 4 +++- src/transactions_type.rs | 20 ++++++++++++-------- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/examples/common.rs b/examples/common.rs index c935b61..01a6454 100644 --- a/examples/common.rs +++ b/examples/common.rs @@ -3,7 +3,7 @@ use serde::Serialize; use xpx_supercontracts_sdk::statuses::Result; use xpx_supercontracts_sdk::storage::save_result; use xpx_supercontracts_sdk::transactions as tx; -use xpx_supercontracts_sdk::transactions_type::{AddExchangeOffer, AddOffer, AddressAlias, DriveFsTransaction, ExchangeConfirmation, ExchangeOffer, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, ModifyMetadataNamespace, Mosaic, MosaicAlias, MosaicSupplyChange, RegisterRootNamespace, RegisterSubNamespace, RemoveExchangeOffer, RemoveOffer, Secret, SecretLock, SecretProof, Transfer, TransferWithNamespace}; +use xpx_supercontracts_sdk::transactions_type::{AddExchangeOffer, AddOffer, AddressAlias, DriveFsTransaction, ExchangeConfirmation, ExchangeOffer, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, ModifyMetadataNamespace, Mosaic, MosaicAlias, MosaicSupplyChange, PublicAccount, RegisterRootNamespace, RegisterSubNamespace, RemoveExchangeOffer, RemoveOffer, Secret, SecretLock, SecretProof, Transfer, TransferWithNamespace}; use xpx_supercontracts_sdk::utils::{constructor, debug_message, init, ping}; #[no_mangle] @@ -63,7 +63,7 @@ pub extern "C" fn exmpl_get_supercontract() -> i64 { #[no_mangle] pub extern "C" fn exmpl_get_transaction_effective_fee() -> i64 { let res = tx::get_transaction_effective_fee(&GetTransactionEffectiveFee { - id: String::from("some_id"), + id: String::from("baegqajaiaqjcb6qufter6rgkiyndqd273kp4n43q2q34uhbt24qb3ehexqcu74u3"), }); if let Err(err) = res { debug_message(&format!("{:?}", err)); @@ -358,7 +358,9 @@ pub extern "C" fn exmpl_exchange_offer() -> i64 { amount: 10000, }), cost: 1000, - owner: Some(String::from("public account")), + owner: Some(PublicAccount { + public_key: String::from("baegqajaiaqjcakxppt6hi3pcghh3en7fj47jkf6phllbkz2hx2bdvdeyelrrcmx5"), + }), }]) }); if let Err(err) = res { diff --git a/src/tools/call.rs b/src/tools/call.rs index de2dc6f..36bb13a 100644 --- a/src/tools/call.rs +++ b/src/tools/call.rs @@ -4,6 +4,7 @@ use serde::{de::DeserializeOwned, Serialize}; use crate::statuses::{Error, FunctionResult, Result}; +use crate::utils::debug_message; /// External function type definition for call /// closure external FFI functions @@ -37,7 +38,8 @@ pub fn call_external_func(params: &T, extenral_fn: ExternalFnWithReturnDat }; let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { + if let Err(err) = result { + debug_message(&format!("Err: {:?}", err)); return Err(Error::DeserializeJson); } Ok(result.unwrap()) diff --git a/src/transactions_type.rs b/src/transactions_type.rs index a6ebdde..6981a12 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -17,7 +17,6 @@ pub type EntityType = u16; pub type EntityVersion = u32; pub type Amount = i64; pub type Deadline = i64; -pub type PublicAccount = String; pub type Height = i64; pub type Hash = String; pub type Address = String; @@ -248,7 +247,7 @@ pub struct OfferInfo { #[derive(Debug, Deserialize, Serialize)] pub struct UserExchangeInfo { pub owner: Option, - pub offers: HashMap>>, + pub offers: Option>>>, } #[derive(Debug, Deserialize, Serialize)] @@ -262,14 +261,19 @@ pub struct GetExchangeOfferByAssetId { pub offer_type: OfferType, } +#[derive(Debug, Deserialize, Serialize)] +pub struct PublicAccount { + pub public_key: String, +} + #[derive(Debug, Deserialize, Serialize)] pub struct MosaicInfo { - mosaic_id: Option, - supply: Amount, - height: Height, - owner: Option, - revision: u32, - properties: Option, + //pub mosaic_id: Option, + pub supply: Amount, + pub height: Height, + pub owner: Option, + pub revision: u32, + pub properties: Option, } #[derive(Debug, Deserialize, Serialize)] From e6a0375fd6194fc5d3415306652f320ed8780a50 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 6 Mar 2020 13:38:48 +0200 Subject: [PATCH 21/28] Changes axamples/common for testing --- examples/common.rs | 640 +++++++++++++++++++++------------------ examples/mosaic.rs | 71 +++-- src/external.rs | 202 ++++-------- src/http.rs | 44 +-- src/lib.rs | 4 +- src/tools/call.rs | 85 +++--- src/tools/mod.rs | 2 +- src/transactions.rs | 224 +++++++------- src/transactions_type.rs | 353 +++++++++++---------- src/utils.rs | 58 ++-- 10 files changed, 843 insertions(+), 840 deletions(-) diff --git a/examples/common.rs b/examples/common.rs index 01a6454..af17302 100644 --- a/examples/common.rs +++ b/examples/common.rs @@ -3,422 +3,466 @@ use serde::Serialize; use xpx_supercontracts_sdk::statuses::Result; use xpx_supercontracts_sdk::storage::save_result; use xpx_supercontracts_sdk::transactions as tx; -use xpx_supercontracts_sdk::transactions_type::{AddExchangeOffer, AddOffer, AddressAlias, DriveFsTransaction, ExchangeConfirmation, ExchangeOffer, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, ModifyMetadataNamespace, Mosaic, MosaicAlias, MosaicSupplyChange, PublicAccount, RegisterRootNamespace, RegisterSubNamespace, RemoveExchangeOffer, RemoveOffer, Secret, SecretLock, SecretProof, Transfer, TransferWithNamespace}; +use xpx_supercontracts_sdk::transactions::{get_supercontract, mosaic_definition}; +use xpx_supercontracts_sdk::transactions_type::{ + AddExchangeOffer, AddOffer, AddressAlias, DriveFsTransaction, ExchangeConfirmation, + ExchangeOffer, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, + GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, + GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, + ModifyMetadataNamespace, Mosaic, MosaicAlias, MosaicDefinition, MosaicProperties, + MosaicProperty, MosaicSupplyChange, PublicAccount, RegisterRootNamespace, RegisterSubNamespace, + RemoveExchangeOffer, RemoveOffer, Secret, SecretLock, SecretProof, SuperContract, Transfer, + TransferWithNamespace, +}; use xpx_supercontracts_sdk::utils::{constructor, debug_message, init, ping}; #[no_mangle] pub extern "C" fn ping100() -> i64 { - ping(100).unwrap() + ping(100).unwrap() } #[no_mangle] pub extern "C" fn ping100init() -> i64 { - let _ = init(|| { ping(100).unwrap(); }); - let _ = init(|| { ping(100).unwrap(); }); - ping(100).unwrap() + let _ = init(|| { + ping(100).unwrap(); + }); + let _ = init(|| { + ping(100).unwrap(); + }); + ping(100).unwrap() } #[no_mangle] pub extern "C" fn ping_with_params(x: i64) -> i64 { - ping(x as usize).unwrap() + ping(x as usize).unwrap() } #[no_mangle] pub extern "C" fn ping100constructor() -> i64 { - let _ = constructor(|| ping(100).unwrap()); - let _ = constructor(|| ping(100).unwrap()); - ping(100).unwrap() + let _ = constructor(|| ping(100).unwrap()); + let _ = constructor(|| ping(100).unwrap()); + ping(100).unwrap() } #[no_mangle] pub extern "C" fn save_sample_result() -> i64 { - #[derive(Serialize)] - struct SampleData<'a> { - pub id: i64, - pub message: &'a str, - } - let data = serde_json::to_vec(&SampleData { - id: 10, - message: "awesome message", - }).unwrap(); - let res = save_result(&"data.txt".to_string(), &data[..]); - if let Err(err) = res { - debug_message(&format!("save_result error {:?}", err)); - return -1; - } - res.unwrap() + #[derive(Serialize)] + struct SampleData<'a> { + pub id: i64, + pub message: &'a str, + } + let data = serde_json::to_vec(&SampleData { + id: 10, + message: "awesome message", + }) + .unwrap(); + let res = save_result(&"data.txt".to_string(), &data[..]); + if let Err(err) = res { + debug_message(&format!("save_result error {:?}", err)); + return -1; + } + res.unwrap() } #[no_mangle] pub extern "C" fn exmpl_get_supercontract() -> i64 { - let res = tx::get_supercontract(); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("SC.ID: {:?}", res.unwrap().id)); - 0 + let res = tx::get_supercontract(); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("SC.ID: {:?}", res.unwrap().id)); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction_effective_fee() -> i64 { - let res = tx::get_transaction_effective_fee(&GetTransactionEffectiveFee { - id: String::from("baegqajaiaqjcb6qufter6rgkiyndqd273kp4n43q2q34uhbt24qb3ehexqcu74u3"), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_transaction_effective_fee(&GetTransactionEffectiveFee { + id: String::from("baegqajaiaqjcb6qufter6rgkiyndqd273kp4n43q2q34uhbt24qb3ehexqcu74u3"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction() -> i64 { - let tx_result: Result = tx::get_transaction(&GetTransaction { - id: String::from("some_id"), - }); - if let Err(err) = tx_result { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", tx_result.unwrap())); - 0 + let tx_result: Result = tx::get_transaction(&GetTransaction { + id: String::from("some_id"), + }); + if let Err(err) = tx_result { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", tx_result.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction_status() -> i64 { - let res = tx::get_transaction_status(&GetTransactionStatus { - id: String::from("some_id"), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_transaction_status(&GetTransactionStatus { + id: String::from("some_id"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction_statuses() -> i64 { - let res = tx::get_transaction_statuses(&GetTransactionStatuses { - ids: vec![String::from("some_id")], - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_transaction_statuses(&GetTransactionStatuses { + ids: vec![String::from("some_id")], + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } - #[no_mangle] pub extern "C" fn exmpl_get_account_exchange_info() -> i64 { - let res = tx::get_account_exchange_info(&GetAccountExchangeInfo { - pub_key: Some(String::from("some_pub_key")), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_account_exchange_info(&GetAccountExchangeInfo { + pub_key: Some(String::from("some_pub_key")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_exchange_offer_by_asset_id() -> i64 { - let res = tx::get_exchange_offer_by_asset_id(&GetExchangeOfferByAssetId { - asset_id: 1, - offer_type: 2, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_exchange_offer_by_asset_id(&GetExchangeOfferByAssetId { + asset_id: 1, + offer_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_mosaic_info() -> i64 { - let res = tx::get_mosaic_info(&GetMosaicInfo { - mosaic_id: Some(1), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_mosaic_info(&GetMosaicInfo { mosaic_id: Some(1) }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_mosaic_infos() -> i64 { - let res = tx::get_mosaic_infos(&GetMosaicInfos { - msc_ids: Some(vec![2]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_mosaic_infos(&GetMosaicInfos { + msc_ids: Some(vec![2]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_mosaics_names() -> i64 { - let res = tx::get_mosaics_names(&GetMosaicsNames { - msc_ids: Some(vec![1]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_mosaics_names(&GetMosaicsNames { + msc_ids: Some(vec![1]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_modify_metadata_namespace() -> i64 { - let res = tx::modify_metadata_namespace(&ModifyMetadataNamespace { - namespace_id: Some(1), - modifications: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::modify_metadata_namespace(&ModifyMetadataNamespace { + namespace_id: Some(1), + modifications: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_modify_metadata_mosaic() -> i64 { - let res = tx::modify_metadata_mosaic(&ModifyMetadataMosaic { - mosaic_id: Some(1), - modifications: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::modify_metadata_mosaic(&ModifyMetadataMosaic { + mosaic_id: Some(1), + modifications: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_modify_metadata_address() -> i64 { - let res = tx::modify_metadata_address(&ModifyMetadataAddress { - address: Some(String::from("some_address")), - modifications: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::modify_metadata_address(&ModifyMetadataAddress { + address: Some(String::from("some_address")), + modifications: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_secret_proof() -> i64 { - let res = tx::secret_proof(&SecretProof { - hash_type: 1, - proof: None, - recipient: Some(String::from("some recipient")), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::secret_proof(&SecretProof { + hash_type: 1, + proof: None, + recipient: Some(String::from("some recipient")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_transfer_with_namespace() -> i64 { - let res = tx::transfer_with_namespace(&TransferWithNamespace { - recipient: Some(1), - mosaics: Some(vec![]), - message: String::from("some message"), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::transfer_with_namespace(&TransferWithNamespace { + recipient: Some(1), + mosaics: Some(vec![Mosaic { + asset_id: 4, + amount: 10000, + }]), + message: String::from("some message"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } - #[no_mangle] pub extern "C" fn exmpl_secret_lock() -> i64 { - let res = tx::secret_lock(&SecretLock { - mosaic: Some(Mosaic { - asset_id: 1, - amount: 1000, - }), - duration: 10000, - secret: Some(Secret { - hash: String::from("some hash"), - hash_type: 1, - }), - recipient: Some(String::from("some addr")), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::secret_lock(&SecretLock { + mosaic: Some(Mosaic { + asset_id: 1, + amount: 1000, + }), + duration: 10000, + secret: Some(Secret { + hash: String::from("some hash"), + hash_type: 1, + }), + recipient: Some(String::from("some addr")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_register_sub_namespace() -> i64 { - let res = tx::register_sub_namespace(&RegisterSubNamespace { - namespace_name: String::from("name"), - parent_id: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::register_sub_namespace(&RegisterSubNamespace { + namespace_name: String::from("name"), + parent_id: None, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_register_root_namespace() -> i64 { - let res = tx::register_root_namespace(&RegisterRootNamespace { - namespace_name: String::from("name"), - duration: 1000, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::register_root_namespace(&RegisterRootNamespace { + namespace_name: String::from("name"), + duration: 1000, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_mosaic_supply_change() -> i64 { - let res = tx::mosaic_supply_change(&MosaicSupplyChange { - asset_id: 10, - supply_type: 100, - delta: 300, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::mosaic_supply_change(&MosaicSupplyChange { + asset_id: 10, + supply_type: 100, + delta: 300, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_remove_exchange_offer() -> i64 { - let res = tx::remove_exchange_offer(&RemoveExchangeOffer { - remove_offers: Some(vec![RemoveOffer { - asset_id: 10, - offer_type: 1, - }]) - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::remove_exchange_offer(&RemoveExchangeOffer { + remove_offers: Some(vec![RemoveOffer { + asset_id: 10, + offer_type: 1, + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_transfer() -> i64 { - let res = tx::transfer(&Transfer { - pub_key: String::from("some_pub_key"), - asset_id: 10, - amount: 1000, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::transfer(&Transfer { + pub_key: String::from("some_pub_key"), + asset_id: 10, + amount: 1000, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_exchange_offer() -> i64 { - let res = tx::exchange_offer(&ExchangeOffer { - offer: Some(vec![ExchangeConfirmation { - offer_type: 1, - mosaic: Some(Mosaic { - asset_id: 3, - amount: 10000, - }), - cost: 1000, - owner: Some(PublicAccount { - public_key: String::from("baegqajaiaqjcakxppt6hi3pcghh3en7fj47jkf6phllbkz2hx2bdvdeyelrrcmx5"), - }), - }]) - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::exchange_offer(&ExchangeOffer { + offer: Some(vec![ExchangeConfirmation { + offer_type: 1, + mosaic: Some(Mosaic { + asset_id: 3, + amount: 10000, + }), + cost: 1000, + owner: Some(PublicAccount { + public_key: String::from( + "baegqajaiaqjcakxppt6hi3pcghh3en7fj47jkf6phllbkz2hx2bdvdeyelrrcmx5", + ), + }), + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_add_exchange_offer() -> i64 { - let res = tx::add_exchange_offer(&AddExchangeOffer { - add_offers: Some(vec![AddOffer { - offer_type: 3, - mosaic: Some(Mosaic { - amount: 1000, - asset_id: 3, - - }), - cost: 100, - duration: 1000, - }]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::add_exchange_offer(&AddExchangeOffer { + add_offers: Some(vec![AddOffer { + offer_type: 3, + mosaic: Some(Mosaic { + amount: 1000, + asset_id: 3, + }), + cost: 100, + duration: 1000, + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_mosaic_alias() -> i64 { - let res = tx::mosaic_alias(&MosaicAlias { - mosaic_id: Some(10), - namespace_id: Some(3), - action_type: 2, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::mosaic_alias(&MosaicAlias { + mosaic_id: Some(10), + namespace_id: Some(3), + action_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_address_alias() -> i64 { - let res = tx::address_alias(&AddressAlias { - address: Some(String::from("some addr")), - namespace_id: Some(3), - action_type: 2, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::address_alias(&AddressAlias { + address: Some(String::from("SAONSOGFZZHNEIBRYXHDTDTBR2YSAXKTITRFHG2Y")), + namespace_id: Some(0xFF000000_FF000000), + action_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 +} + +#[no_mangle] +pub extern "C" fn exmpl_create_mosaic() -> i64 { + let res = get_supercontract(); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + let sc: SuperContract = res.unwrap(); + + debug_message(&format!("SC.ID: {:?}", sc.id)); + let res = mosaic_definition(&MosaicDefinition { + nonce: 0, + owner_public_key: sc.id, + mosaic_props: Some(MosaicProperties { + supply_mutable: true, + transferable: true, + divisibility: 0, + optional_properties: vec![MosaicProperty { id: 0, value: 0 }], + }), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } diff --git a/examples/mosaic.rs b/examples/mosaic.rs index 58a9bff..c560168 100644 --- a/examples/mosaic.rs +++ b/examples/mosaic.rs @@ -1,46 +1,45 @@ +use xpx_supercontracts_sdk::transactions::get_supercontract; +use xpx_supercontracts_sdk::transactions_type::{ + SuperContract, FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE, FUNCTION_ERROR, FUNCTION_RETURN_SUCCESS, +}; use xpx_supercontracts_sdk::{ - transactions::mosaic_definition, - transactions_type::{MosaicDefinition, MosaicProperties, MosaicProperty}, - utils::{constructor, debug_message}, + transactions::mosaic_definition, + transactions_type::{MosaicDefinition, MosaicProperties, MosaicProperty}, + utils::{constructor, debug_message}, }; -use xpx_supercontracts_sdk::transactions::get_supercontract; -use xpx_supercontracts_sdk::transactions_type::{FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE, FUNCTION_ERROR, FUNCTION_RETURN_SUCCESS, SuperContract}; pub fn create_mosaic() -> i64 { - let res = get_supercontract(); - if res.is_err() { - return -1; - } - let sc: SuperContract = res.unwrap(); + let res = get_supercontract(); + if res.is_err() { + return -1; + } + let sc: SuperContract = res.unwrap(); - debug_message(&format!("SC.ID: {:?}", sc.id)); - let res = mosaic_definition(&MosaicDefinition { - nonce: 0, - owner_public_key: sc.id, - mosaic_props: Some(MosaicProperties { - supply_mutable: true, - transferable: true, - divisibility: 0, - optional_properties: vec![MosaicProperty { - id: 0, - value: 0, - }], - }), - }); - if res.is_err() { - return FUNCTION_ERROR; - } - if res.unwrap() < FUNCTION_RETURN_SUCCESS { - debug_message(&"failed create mosaic".to_string()); - } - FUNCTION_RETURN_SUCCESS + debug_message(&format!("SC.ID: {:?}", sc.id)); + let res = mosaic_definition(&MosaicDefinition { + nonce: 0, + owner_public_key: sc.id, + mosaic_props: Some(MosaicProperties { + supply_mutable: true, + transferable: true, + divisibility: 0, + optional_properties: vec![MosaicProperty { id: 0, value: 0 }], + }), + }); + if res.is_err() { + return FUNCTION_ERROR; + } + if res.unwrap() < FUNCTION_RETURN_SUCCESS { + debug_message(&"failed create mosaic".to_string()); + } + FUNCTION_RETURN_SUCCESS } #[no_mangle] pub extern "C" fn app_main() -> i64 { - let res = constructor(create_mosaic); - if res != FUNCTION_RETURN_SUCCESS && res == FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE { - return res; - } - FUNCTION_RETURN_SUCCESS + let res = constructor(create_mosaic); + if res != FUNCTION_RETURN_SUCCESS && res == FUNCTION_CONSTRUCTOR_FAIL_TO_SAVE { + return res; + } + FUNCTION_RETURN_SUCCESS } diff --git a/src/external.rs b/src/external.rs index bac6919..e64a4e9 100644 --- a/src/external.rs +++ b/src/external.rs @@ -1,147 +1,61 @@ extern "C" { - pub fn __ping(number: usize) -> i64; - pub fn __constructor() -> i64; - pub fn __init() -> i64; - pub fn __inc() -> i64; - pub fn __write_log(msg: *const u8, len: usize) -> i64; - pub fn save_to_storage( - file_ptr: *const u8, - file_len: usize, - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn save_sc_result( - file_ptr: *const u8, - file_len: usize, - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn get_from_storage( - file_ptr: *const u8, - file_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_http( - url: *const u8, - url_len: usize, - body: *mut u8, - ) -> i64; + pub fn __ping(number: usize) -> i64; + pub fn __constructor() -> i64; + pub fn __init() -> i64; + pub fn __inc() -> i64; + pub fn __write_log(msg: *const u8, len: usize) -> i64; + pub fn save_to_storage( + file_ptr: *const u8, + file_len: usize, + data_ptr: *const u8, + data_len: usize, + ) -> i64; + pub fn save_sc_result( + file_ptr: *const u8, + file_len: usize, + data_ptr: *const u8, + data_len: usize, + ) -> i64; + pub fn get_from_storage(file_ptr: *const u8, file_len: usize, data: *mut u8) -> i64; + pub fn get_http(url: *const u8, url_len: usize, body: *mut u8) -> i64; - //================================================== - // Blockchain Transactions manipulations - pub fn flush() -> i64; - pub fn mosaic_definition( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn address_alias( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn mosaic_alias( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn add_exchange_offer( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn exchange_offer( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn transfer( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn remove_exchange_offer( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn mosaic_supply_change( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn register_root_namespace( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn register_sub_namespace( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn secret_lock( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn secret_proof( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn transfer_with_namespace( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn modify_metadata_address( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn modify_metadata_mosaic( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn modify_metadata_namespace( - data_ptr: *const u8, - data_len: usize, - ) -> i64; - //============================================== - // Blockchain Getters - pub fn get_account_exchange_info( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_exchange_offer_by_asset_id( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_mosaic_info( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_mosaic_infos( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_mosaics_names( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_transaction( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_transaction_status( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_transaction_statuses( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_transaction_effective_fee( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_supercontract( - data: *mut u8, - ) -> i64; + //================================================== + // Blockchain Transactions manipulations + pub fn flush() -> i64; + pub fn mosaic_definition(data_ptr: *const u8, data_len: usize) -> i64; + pub fn address_alias(data_ptr: *const u8, data_len: usize) -> i64; + pub fn mosaic_alias(data_ptr: *const u8, data_len: usize) -> i64; + pub fn add_exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn transfer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn remove_exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn mosaic_supply_change(data_ptr: *const u8, data_len: usize) -> i64; + pub fn register_root_namespace(data_ptr: *const u8, data_len: usize) -> i64; + pub fn register_sub_namespace(data_ptr: *const u8, data_len: usize) -> i64; + pub fn secret_lock(data_ptr: *const u8, data_len: usize) -> i64; + pub fn secret_proof(data_ptr: *const u8, data_len: usize) -> i64; + pub fn transfer_with_namespace(data_ptr: *const u8, data_len: usize) -> i64; + pub fn modify_metadata_address(data_ptr: *const u8, data_len: usize) -> i64; + pub fn modify_metadata_mosaic(data_ptr: *const u8, data_len: usize) -> i64; + pub fn modify_metadata_namespace(data_ptr: *const u8, data_len: usize) -> i64; + //============================================== + // Blockchain Getters + pub fn get_account_exchange_info(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_exchange_offer_by_asset_id( + data_ptr: *const u8, + data_len: usize, + data: *mut u8, + ) -> i64; + pub fn get_mosaic_info(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_mosaic_infos(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_mosaics_names(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction_status(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction_statuses(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction_effective_fee( + data_ptr: *const u8, + data_len: usize, + data: *mut u8, + ) -> i64; + pub fn get_supercontract(data: *mut u8) -> i64; } diff --git a/src/http.rs b/src/http.rs index cd8d2e5..cfb9c0c 100644 --- a/src/http.rs +++ b/src/http.rs @@ -10,19 +10,19 @@ use crate::statuses::{Error, MultipleFunctionResult}; /// HTTP request data #[derive(Debug, Deserialize, Serialize)] pub struct HttpRequest { - /// URL for request - pub url: String, - /// HTTP headers for request body - pub headers: HashMap, + /// URL for request + pub url: String, + /// HTTP headers for request body + pub headers: HashMap, } /// HTTP response data #[derive(Debug, Deserialize, Serialize)] struct HttpResponse { - /// HTTP statuscode - status_code: u64, - /// Response body - body: String, + /// HTTP statuscode + status_code: u64, + /// Response body + body: String, } /// Send HTTPP requst with specific parameters. @@ -31,7 +31,7 @@ struct HttpResponse { /// ```rust,no_run /// use std::collections::HashMap; /// use xpx_supercontracts_sdk::http::{http_get, HttpRequest}; -/// +/// /// let mut headers: HashMap = HashMap::new(); /// headers.insert("content-type".to_string(), "text/html".to_string()); /// let req = HttpRequest { @@ -45,18 +45,18 @@ struct HttpResponse { /// // Return response body length /// let result = resp.unwrap().len() as i64; /// ``` -/// +/// pub fn http_get(request: &HttpRequest) -> MultipleFunctionResult { - let request_body = serde_json::to_vec(&request); - if request_body.is_err() { - return Err(Error::SerializeJson); - } - let request_body = request_body.unwrap(); - let data: &mut Vec = &mut vec![]; - return unsafe { - let body_len = - external::get_http(request_body.as_ptr(), request_body.len(), data.as_mut_ptr()); - let data_bytes = data.get_unchecked_mut(0..body_len as usize); - Ok(data_bytes.to_vec()) - }; + let request_body = serde_json::to_vec(&request); + if request_body.is_err() { + return Err(Error::SerializeJson); + } + let request_body = request_body.unwrap(); + let data: &mut Vec = &mut vec![]; + return unsafe { + let body_len = + external::get_http(request_body.as_ptr(), request_body.len(), data.as_mut_ptr()); + let data_bytes = data.get_unchecked_mut(0..body_len as usize); + Ok(data_bytes.to_vec()) + }; } diff --git a/src/lib.rs b/src/lib.rs index e3eb6ef..09f445c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,7 +66,7 @@ mod external; pub mod http; pub mod statuses; pub mod storage; -pub mod utils; +mod tools; pub mod transactions; pub mod transactions_type; -mod tools; +pub mod utils; diff --git a/src/tools/call.rs b/src/tools/call.rs index 36bb13a..f24ae59 100644 --- a/src/tools/call.rs +++ b/src/tools/call.rs @@ -1,4 +1,4 @@ -//! Basic additional toolkit for SuperContract functions +//! Basic additional toolkit for SuperContract functions //! use serde::{de::DeserializeOwned, Serialize}; @@ -6,13 +6,10 @@ use serde::{de::DeserializeOwned, Serialize}; use crate::statuses::{Error, FunctionResult, Result}; use crate::utils::debug_message; -/// External function type definition for call -/// closure external FFI functions -type ExternalFnWithReturnData = unsafe extern "C" fn( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, -) -> i64; +/// External function type definition for call +/// closure external FFI functions +type ExternalFnWithReturnData = + unsafe extern "C" fn(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; /// External functions call wrapper. It serialize input data /// and deserialize output data after raw call of external function. @@ -21,47 +18,51 @@ type ExternalFnWithReturnData = unsafe extern "C" fn( /// * serialize input data /// * invoke external function with serialized function parameters /// * fetch external function result -/// * deserialize external function to specific type for SuperContract function +/// * deserialize external function to specific type for SuperContract function pub fn call_external_func(params: &T, extenral_fn: ExternalFnWithReturnData) -> Result - where T: Serialize, U: DeserializeOwned { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } +where + T: Serialize, + U: DeserializeOwned, +{ + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } - let fn_params_body = fn_param.unwrap(); - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = extenral_fn(fn_params_body.as_ptr(), fn_params_body.len(), fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; + let fn_params_body = fn_param.unwrap(); + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = extenral_fn( + fn_params_body.as_ptr(), + fn_params_body.len(), + fn_result.as_mut_ptr(), + ); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; - let result = serde_json::from_slice(&fn_result[..]); - if let Err(err) = result { - debug_message(&format!("Err: {:?}", err)); - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) + let result = serde_json::from_slice(&fn_result[..]); + if let Err(err) = result { + debug_message(&format!("Err: {:?}", err)); + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) } -/// External function type definition for call -/// simple closure external FFI functions -type ExternalFn = unsafe extern "C" fn( - data_ptr: *const u8, - data_len: usize, -) -> i64; +/// External function type definition for call +/// simple closure external FFI functions +type ExternalFn = unsafe extern "C" fn(data_ptr: *const u8, data_len: usize) -> i64; /// Similar call_external_func but without return data from external function pub fn simple_call_external_func(params: &T, extenral_fn: ExternalFn) -> FunctionResult - where T: Serialize { - let fn_param = serde_json::to_vec(¶ms); - if fn_param.is_err() { - return Err(Error::SerializeJson); - } +where + T: Serialize, +{ + let fn_param = serde_json::to_vec(¶ms); + if fn_param.is_err() { + return Err(Error::SerializeJson); + } - let fn_params_body = fn_param.unwrap(); - unsafe { - Ok(extenral_fn(fn_params_body.as_ptr(), fn_params_body.len())) - } + let fn_params_body = fn_param.unwrap(); + unsafe { Ok(extenral_fn(fn_params_body.as_ptr(), fn_params_body.len())) } } diff --git a/src/tools/mod.rs b/src/tools/mod.rs index 002ad68..8b6c1d4 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -1 +1 @@ -pub mod call; \ No newline at end of file +pub mod call; diff --git a/src/transactions.rs b/src/transactions.rs index d0f2132..62c6cb0 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -1,46 +1,46 @@ //! # Basic Blockchain functions -//! Basic functionality to interact with Catapulta Blockchain. -//! It represent via twa main part: transactions +//! Basic functionality to interact with Catapulta Blockchain. +//! It represent via twa main part: transactions //! and getters (**get functions** of some information from Blockchain). -//! +//! //! ## Transaction functions -//! Main principle of transaction functions is -//! that aggregation to pool of transactions. So it will send not immediately. +//! Main principle of transaction functions is +//! that aggregation to pool of transactions. So it will send not immediately. //! The reason is minimize `Gas spent` and reducing Blockchain resources utilization. -//! -//! When SuperContract will End transactions Flush autromaticaly (it mean it will send +//! +//! When SuperContract will End transactions Flush autromaticaly (it mean it will send //! to Blocchain). -//! +//! //! But it possible send transaction pull immediately. //! For that case exist function `flush`. -//! When function `flush` invoking then Transactions Pool +//! When function `flush` invoking then Transactions Pool //! will be send to Blockchain, and then clear. -//! +//! //! And again - only **end execution of SuperContract** -//! or Flush** can send transactions to Blockchaing. +//! or Flush** can send transactions to Blockchaing. //! Otherwise it will gather to Transactions Pool. use serde::de::DeserializeOwned; use crate::external; -use crate::statuses::{FunctionResult, Result}; use crate::statuses::Error; +use crate::statuses::{FunctionResult, Result}; use crate::tools::call::{call_external_func, simple_call_external_func}; use crate::transactions_type::*; -/// Flush send immediately Transactions from current +/// Flush send immediately Transactions from current /// transactions pool. -/// -/// Flush should use carefully. If Leader of SuperContract +/// +/// Flush should use carefully. If Leader of SuperContract /// execution invoke Flush then SuperContract will be -/// paused ann waite +/// paused ann waite /// Signing from other Executors. -/// When Flush will send from non-leader it mean fire -/// process of signing transactions +/// When Flush will send from non-leader it mean fire +/// process of signing transactions /// from Leader of SuperContract execution. /// In both case SuperContract will be paused waiting /// event from other Executors. -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -48,12 +48,12 @@ use crate::transactions_type::*; /// mosaic_definition, /// }; /// use xpx_supercontracts_sdk::transactions_type::MosaicDefinition; -/// +/// /// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".to_string(); /// let params = MosaicDefinition{ /// nonce: 100, /// owner_public_key: pub_key, -/// mosaic_props: None, +/// mosaic_props: None, /// }; /// // Add transaction to Transactions Pool /// let tx_result = mosaic_definition(¶ms); @@ -66,13 +66,13 @@ use crate::transactions_type::*; /// // Some error handling /// } /// ``` -/// +/// pub fn flush() -> FunctionResult { - return unsafe { Ok(external::flush()) }; + return unsafe { Ok(external::flush()) }; } /// Send to transaction pool **MosaicDefinition transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -80,12 +80,12 @@ pub fn flush() -> FunctionResult { /// mosaic_definition, /// }; /// use xpx_supercontracts_sdk::transactions_type::MosaicDefinition; -/// +/// /// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".to_string(); /// let params = MosaicDefinition{ /// nonce: 100, /// owner_public_key: pub_key, -/// mosaic_props: None, +/// mosaic_props: None, /// }; /// // Add transaction to Transactions Pool /// let tx_result = mosaic_definition(¶ms); @@ -95,11 +95,11 @@ pub fn flush() -> FunctionResult { /// ``` /// pub fn mosaic_definition(params: &MosaicDefinition) -> FunctionResult { - simple_call_external_func(params, external::mosaic_definition) + simple_call_external_func(params, external::mosaic_definition) } /// Send to transaction pool **AddressAlias transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -107,11 +107,11 @@ pub fn mosaic_definition(params: &MosaicDefinition) -> FunctionResult { /// address_alias, /// }; /// use xpx_supercontracts_sdk::transactions_type::AddressAlias; -/// +/// /// let params = AddressAlias{ /// address: None, /// namespace_id: None, -/// action_type: 10, +/// action_type: 10, /// }; /// // Add transaction to Transactions Pool /// let tx_result = address_alias(¶ms); @@ -121,11 +121,11 @@ pub fn mosaic_definition(params: &MosaicDefinition) -> FunctionResult { /// ``` /// pub fn address_alias(params: &AddressAlias) -> FunctionResult { - simple_call_external_func(params, external::address_alias) + simple_call_external_func(params, external::address_alias) } /// Send to transaction pool **MosaicAlias transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -133,11 +133,11 @@ pub fn address_alias(params: &AddressAlias) -> FunctionResult { /// mosaic_alias, /// }; /// use xpx_supercontracts_sdk::transactions_type::MosaicAlias; -/// +/// /// let params = MosaicAlias{ /// mosaic_id: None, /// namespace_id: None, -/// action_type: 10, +/// action_type: 10, /// }; /// // Add transaction to Transactions Pool /// let tx_result = mosaic_alias(¶ms); @@ -147,11 +147,11 @@ pub fn address_alias(params: &AddressAlias) -> FunctionResult { /// ``` /// pub fn mosaic_alias(params: &MosaicAlias) -> FunctionResult { - simple_call_external_func(params, external::mosaic_alias) + simple_call_external_func(params, external::mosaic_alias) } /// Send to transaction pool **AddExchangeOffer transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -159,9 +159,9 @@ pub fn mosaic_alias(params: &MosaicAlias) -> FunctionResult { /// add_exchange_offer, /// }; /// use xpx_supercontracts_sdk::transactions_type::AddExchangeOffer; -/// +/// /// let params = AddExchangeOffer{ -/// add_offers: None, +/// add_offers: None, /// }; /// // Add transaction to Transactions Pool /// let tx_result = add_exchange_offer(¶ms); @@ -171,11 +171,11 @@ pub fn mosaic_alias(params: &MosaicAlias) -> FunctionResult { /// ``` /// pub fn add_exchange_offer(params: &AddExchangeOffer) -> FunctionResult { - simple_call_external_func(params, external::add_exchange_offer) + simple_call_external_func(params, external::add_exchange_offer) } /// Send to transaction pool **AddExchangeOffer transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -183,9 +183,9 @@ pub fn add_exchange_offer(params: &AddExchangeOffer) -> FunctionResult { /// add_exchange_offer, /// }; /// use xpx_supercontracts_sdk::transactions_type::AddExchangeOffer; -/// +/// /// let params = AddExchangeOffer{ -/// add_offers: None, +/// add_offers: None, /// }; /// // Add transaction to Transactions Pool /// let tx_result = add_exchange_offer(¶ms); @@ -195,11 +195,11 @@ pub fn add_exchange_offer(params: &AddExchangeOffer) -> FunctionResult { /// ``` /// pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { - simple_call_external_func(params, external::exchange_offer) + simple_call_external_func(params, external::exchange_offer) } /// Send to transaction pool **Transfer transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -207,12 +207,12 @@ pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { /// transfer, /// }; /// use xpx_supercontracts_sdk::transactions_type::{Transfer, PubKey}; -/// +/// /// let pub_key = "2C8178EF9ED7A6D30ABDC1E4D30D68B05861112A98B1629FBE2C8D16FDE97A1C".to_string(); /// let params = Transfer{ -/// pub_key: pub_key, +/// pub_key: pub_key, /// asset_id: 10, -/// amount: 1000, +/// amount: 1000, /// }; /// // Add transaction to Transactions Pool /// let tx_result = transfer(¶ms); @@ -222,11 +222,11 @@ pub fn exchange_offer(params: &ExchangeOffer) -> FunctionResult { /// ``` /// pub fn transfer(params: &Transfer) -> FunctionResult { - simple_call_external_func(params, external::transfer) + simple_call_external_func(params, external::transfer) } /// Send to transaction pool **RemoveExchangeOffer transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -236,7 +236,7 @@ pub fn transfer(params: &Transfer) -> FunctionResult { /// use xpx_supercontracts_sdk::transactions_type::RemoveExchangeOffer; /// /// let params = RemoveExchangeOffer{ -/// remove_offers: None, +/// remove_offers: None, /// }; /// // Add transaction to Transactions Pool /// let tx_result = remove_exchange_offer(¶ms); @@ -246,11 +246,11 @@ pub fn transfer(params: &Transfer) -> FunctionResult { /// ``` /// pub fn remove_exchange_offer(params: &RemoveExchangeOffer) -> FunctionResult { - simple_call_external_func(params, external::remove_exchange_offer) + simple_call_external_func(params, external::remove_exchange_offer) } /// Send to transaction pool **MosaicSupplyChange transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -262,7 +262,7 @@ pub fn remove_exchange_offer(params: &RemoveExchangeOffer) -> FunctionResult { /// let params = MosaicSupplyChange{ /// asset_id: 10, /// supply_type: 20, -/// delta: 300, +/// delta: 300, /// }; /// // Add transaction to Transactions Pool /// let tx_result = mosaic_supply_change(¶ms); @@ -272,11 +272,11 @@ pub fn remove_exchange_offer(params: &RemoveExchangeOffer) -> FunctionResult { /// ``` /// pub fn mosaic_supply_change(params: &MosaicSupplyChange) -> FunctionResult { - simple_call_external_func(params, external::mosaic_supply_change) + simple_call_external_func(params, external::mosaic_supply_change) } /// Send to transaction pool **RegisterRootNamespace transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -287,7 +287,7 @@ pub fn mosaic_supply_change(params: &MosaicSupplyChange) -> FunctionResult { /// /// let params = RegisterRootNamespace{ /// namespace_name: String::from("my_name_space"), -/// duration: 3000, +/// duration: 3000, /// }; /// // Add transaction to Transactions Pool /// let tx_result = register_root_namespace(¶ms); @@ -297,11 +297,11 @@ pub fn mosaic_supply_change(params: &MosaicSupplyChange) -> FunctionResult { /// ``` /// pub fn register_root_namespace(params: &RegisterRootNamespace) -> FunctionResult { - simple_call_external_func(params, external::register_root_namespace) + simple_call_external_func(params, external::register_root_namespace) } /// Send to transaction pool **RegisterRootNamespace transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -312,7 +312,7 @@ pub fn register_root_namespace(params: &RegisterRootNamespace) -> FunctionResult /// /// let params = RegisterRootNamespace{ /// namespace_name: String::from("my_name_space"), -/// duration: 3000, +/// duration: 3000, /// }; /// // Add transaction to Transactions Pool /// let tx_result = register_root_namespace(¶ms); @@ -322,11 +322,11 @@ pub fn register_root_namespace(params: &RegisterRootNamespace) -> FunctionResult /// ``` /// pub fn register_sub_namespace(params: &RegisterSubNamespace) -> FunctionResult { - simple_call_external_func(params, external::register_sub_namespace) + simple_call_external_func(params, external::register_sub_namespace) } /// Send to transaction pool **SecretLock transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -339,7 +339,7 @@ pub fn register_sub_namespace(params: &RegisterSubNamespace) -> FunctionResult { /// mosaic: None, /// duration: 3000, /// secret: None, -/// recipient: None, +/// recipient: None, /// }; /// // Add transaction to Transactions Pool /// let tx_result = secret_lock(¶ms); @@ -349,11 +349,11 @@ pub fn register_sub_namespace(params: &RegisterSubNamespace) -> FunctionResult { /// ``` /// pub fn secret_lock(params: &SecretLock) -> FunctionResult { - simple_call_external_func(params, external::secret_lock) + simple_call_external_func(params, external::secret_lock) } /// Send to transaction pool **SecretProof transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -375,11 +375,11 @@ pub fn secret_lock(params: &SecretLock) -> FunctionResult { /// ``` /// pub fn secret_proof(params: &SecretProof) -> FunctionResult { - simple_call_external_func(params, external::secret_proof) + simple_call_external_func(params, external::secret_proof) } /// Send to transaction pool **TransferWithNamespace transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -400,11 +400,11 @@ pub fn secret_proof(params: &SecretProof) -> FunctionResult { /// ``` /// pub fn transfer_with_namespace(params: &TransferWithNamespace) -> FunctionResult { - simple_call_external_func(params, external::transfer_with_namespace) + simple_call_external_func(params, external::transfer_with_namespace) } /// Send to transaction pool **ModifyMetadataAddress transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -424,11 +424,11 @@ pub fn transfer_with_namespace(params: &TransferWithNamespace) -> FunctionResult /// ``` /// pub fn modify_metadata_address(params: &ModifyMetadataAddress) -> FunctionResult { - simple_call_external_func(params, external::modify_metadata_address) + simple_call_external_func(params, external::modify_metadata_address) } /// Send to transaction pool **ModifyMetadataMosaic transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -448,11 +448,11 @@ pub fn modify_metadata_address(params: &ModifyMetadataAddress) -> FunctionResult /// ``` /// pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { - simple_call_external_func(params, external::modify_metadata_mosaic) + simple_call_external_func(params, external::modify_metadata_mosaic) } /// Send to transaction pool **ModifyMetadataNamespace transaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -472,11 +472,11 @@ pub fn modify_metadata_mosaic(params: &ModifyMetadataMosaic) -> FunctionResult { /// ``` /// pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionResult { - simple_call_external_func(params, external::modify_metadata_namespace) + simple_call_external_func(params, external::modify_metadata_namespace) } /// Get data via **GetAccountExchangeInfo** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -492,15 +492,15 @@ pub fn modify_metadata_namespace(params: &ModifyMetadataNamespace) -> FunctionRe /// if result.is_err() { /// // Some error handling /// } -/// let info: UserExchangeInfo = result.unwrap(); +/// let info: UserExchangeInfo = result.unwrap(); /// ``` /// pub fn get_account_exchange_info(params: &GetAccountExchangeInfo) -> Result { - call_external_func(params, external::get_account_exchange_info) + call_external_func(params, external::get_account_exchange_info) } /// Get data via **GetExchangeOfferByAssetId** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -517,15 +517,15 @@ pub fn get_account_exchange_info(params: &GetAccountExchangeInfo) -> Result Result { - call_external_func(params, external::get_exchange_offer_by_asset_id) + call_external_func(params, external::get_exchange_offer_by_asset_id) } /// Get data via **GetMosaicInfo** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -542,15 +542,15 @@ pub fn get_exchange_offer_by_asset_id(params: &GetExchangeOfferByAssetId) -> Res /// if result.is_err() { /// // Some error handling /// } -/// let info: Option = result.unwrap(); +/// let info: Option = result.unwrap(); /// ``` /// pub fn get_mosaic_info(params: &GetMosaicInfo) -> Result> { - call_external_func(params, external::get_mosaic_info) + call_external_func(params, external::get_mosaic_info) } /// Get data via **GetMosaicInfos** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -567,15 +567,15 @@ pub fn get_mosaic_info(params: &GetMosaicInfo) -> Result> { /// if result.is_err() { /// // Some error handling /// } -/// let info: Option> = result.unwrap(); +/// let info: Option> = result.unwrap(); /// ``` /// pub fn get_mosaic_infos(params: &GetMosaicInfos) -> Result>> { - call_external_func(params, external::get_mosaic_infos) + call_external_func(params, external::get_mosaic_infos) } /// Get data via **GetMosaicsNames** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -592,15 +592,15 @@ pub fn get_mosaic_infos(params: &GetMosaicInfos) -> Result> = result.unwrap(); +/// let info: Option> = result.unwrap(); /// ``` /// pub fn get_mosaics_names(params: &GetMosaicsNames) -> Result>> { - call_external_func(params, external::get_mosaics_names) + call_external_func(params, external::get_mosaics_names) } /// Get data via **GetTransaction** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -621,12 +621,14 @@ pub fn get_mosaics_names(params: &GetMosaicsNames) -> Result(params: &GetTransaction) -> Result { - call_external_func(params, external::get_transaction) +pub fn get_transaction( + params: &GetTransaction, +) -> Result { + call_external_func(params, external::get_transaction) } /// Get data via **GetTransactionStatus** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -644,11 +646,11 @@ pub fn get_transaction(params: &GetTran /// ``` /// pub fn get_transaction_status(params: &GetTransactionStatus) -> Result> { - call_external_func(params, external::get_transaction_status) + call_external_func(params, external::get_transaction_status) } /// Get data via **GetTransactionStatuses** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -664,12 +666,14 @@ pub fn get_transaction_status(params: &GetTransactionStatus) -> Result> = result.unwrap(); /// ``` /// -pub fn get_transaction_statuses(params: &GetTransactionStatuses) -> Result>> { - call_external_func(params, external::get_transaction_statuses) +pub fn get_transaction_statuses( + params: &GetTransactionStatuses, +) -> Result>> { + call_external_func(params, external::get_transaction_statuses) } /// Get data via **GetTransactionEffectiveFee** -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -686,11 +690,11 @@ pub fn get_transaction_statuses(params: &GetTransactionStatuses) -> Result Result { - call_external_func(params, external::get_transaction_effective_fee) + call_external_func(params, external::get_transaction_effective_fee) } /// Get data current SuperContract data -/// +/// /// ## Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::transactions::{ @@ -703,16 +707,16 @@ pub fn get_transaction_effective_fee(params: &GetTransactionEffectiveFee) -> Res /// ``` /// pub fn get_supercontract() -> Result { - let fn_result = unsafe { - let fn_result: &mut Vec = &mut vec![]; - let fn_result_len = external::get_supercontract(fn_result.as_mut_ptr()); - let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); - fn_data_bytes.to_vec() - }; + let fn_result = unsafe { + let fn_result: &mut Vec = &mut vec![]; + let fn_result_len = external::get_supercontract(fn_result.as_mut_ptr()); + let fn_data_bytes = fn_result.get_unchecked_mut(0..fn_result_len as usize); + fn_data_bytes.to_vec() + }; - let result = serde_json::from_slice(&fn_result[..]); - if result.is_err() { - return Err(Error::DeserializeJson); - } - Ok(result.unwrap()) + let result = serde_json::from_slice(&fn_result[..]); + if result.is_err() { + return Err(Error::DeserializeJson); + } + Ok(result.unwrap()) } diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 6981a12..a80735b 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -1,5 +1,5 @@ //! # Basic Transactions types for Blockchain functions and getters -//! +//! //! Most common representations for Blockchain transactions type, //! traits, and informations getters. @@ -20,9 +20,9 @@ pub type Deadline = i64; pub type Height = i64; pub type Hash = String; pub type Address = String; -pub type NamespaceId = i64; +pub type NamespaceId = u64; pub type AliasActionType = u8; -pub type MosaicId = i64; +pub type MosaicId = u64; pub type PubKey = String; pub type AssetId = u64; pub type Duration = i64; @@ -37,356 +37,397 @@ pub type Signature = String; #[derive(Debug, Deserialize, Serialize)] pub struct Drive { - pub drive: Cid, - pub owner: PubKey, - pub root: Cid, + pub drive: Cid, + pub owner: PubKey, + pub root: Cid, } #[derive(Debug, Deserialize, Serialize)] pub struct SuperContract { - pub id: Cid, - pub drive: Drive, - pub file: Cid, - pub vmversion: u64, + pub id: Cid, + pub drive: Drive, + pub file: Cid, + pub vmversion: u64, } - #[derive(Debug, Deserialize, Serialize)] pub struct AbstractTransaction { - pub height: Height, - pub index: u32, - pub transaction_hash: Option, - pub merkle_component_hash: Option, - pub aggregate_hash: Option, - pub unique_aggregate_hash: Option, - pub aggregate_id: Vec, + pub height: Height, + pub index: u32, + pub transaction_hash: Option, + pub merkle_component_hash: Option, + pub aggregate_hash: Option, + pub unique_aggregate_hash: Option, + pub aggregate_id: Vec, - pub network_type: NetworkType, - pub deadline: Option, - pub entity_type: EntityType, - pub version: EntityVersion, - pub max_fee: Amount, - pub signature: Vec, - pub signer: Option, + pub network_type: NetworkType, + pub deadline: Option, + pub entity_type: EntityType, + pub version: EntityVersion, + pub max_fee: Amount, + pub signature: Vec, + pub signer: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MosaicDefinition { - pub nonce: u32, - pub owner_public_key: String, - pub mosaic_props: Option, + pub nonce: u32, + pub owner_public_key: String, + pub mosaic_props: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MosaicProperties { - pub supply_mutable: bool, - pub transferable: bool, - pub divisibility: u8, - pub optional_properties: Vec, + pub supply_mutable: bool, + pub transferable: bool, + pub divisibility: u8, + pub optional_properties: Vec, } pub type MosaicPropertyId = u8; #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MosaicProperty { - pub id: MosaicPropertyId, - pub value: i64, + pub id: MosaicPropertyId, + pub value: i64, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct AddressAlias { - pub address: Option
, - pub namespace_id: Option, - pub action_type: AliasActionType, + pub address: Option
, + pub namespace_id: Option, + pub action_type: AliasActionType, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MosaicAlias { - pub mosaic_id: Option, - pub namespace_id: Option, - pub action_type: AliasActionType, + pub mosaic_id: Option, + pub namespace_id: Option, + pub action_type: AliasActionType, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct AddExchangeOffer { - pub add_offers: Option>, + pub add_offers: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct ExchangeConfirmation { - pub offer_type: OfferType, - pub mosaic: Option, - pub cost: Amount, - pub owner: Option, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub mosaic: Option, + pub cost: Amount, + pub owner: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct AddOffer { - pub offer_type: OfferType, - pub mosaic: Option, - pub cost: Amount, - pub duration: Duration, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub mosaic: Option, + pub cost: Amount, + pub duration: Duration, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct ExchangeOffer { - pub offer: Option>, + pub offer: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct Transfer { - pub pub_key: PubKey, - pub asset_id: AssetId, - pub amount: i64, + pub pub_key: PubKey, + pub asset_id: AssetId, + pub amount: i64, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct RemoveOffer { - pub offer_type: OfferType, - pub asset_id: AssetId, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub asset_id: AssetId, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct RemoveExchangeOffer { - pub remove_offers: Option>, + pub remove_offers: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MosaicSupplyChange { - pub asset_id: AssetId, - pub supply_type: MosaicSupplyType, - pub delta: Duration, + pub asset_id: AssetId, + pub supply_type: MosaicSupplyType, + pub delta: Duration, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct RegisterRootNamespace { - pub namespace_name: String, - pub duration: Duration, + pub namespace_name: String, + pub duration: Duration, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct RegisterSubNamespace { - pub namespace_name: String, - pub parent_id: Option, + pub namespace_name: String, + pub parent_id: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct Mosaic { - pub asset_id: AssetId, - pub amount: Amount, + pub asset_id: AssetId, + pub amount: Amount, } #[derive(Debug, Deserialize, Serialize)] pub struct Secret { - pub hash: Hash, - pub hash_type: HashType, + pub hash: Hash, + pub hash_type: HashType, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct SecretLock { - pub mosaic: Option, - pub duration: Duration, - pub secret: Option, - pub recipient: Option
, + pub mosaic: Option, + pub duration: Duration, + pub secret: Option, + pub recipient: Option
, } #[derive(Debug, Deserialize, Serialize)] pub struct Proof { - pub data: Vec, + pub data: Vec, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct SecretProof { - pub hash_type: HashType, - pub proof: Option, - pub recipient: Option
, + pub hash_type: HashType, + pub proof: Option, + pub recipient: Option
, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct TransferWithNamespace { - pub recipient: Option, - pub mosaics: Option>, - pub message: Message, + pub recipient: Option, + pub mosaics: Option>, + pub message: Message, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct ModifyMetadataAddress { - pub address: Option
, - pub modifications: Option>, + pub address: Option
, + pub modifications: Option>, } #[derive(Debug, Deserialize, Serialize)] pub struct ModifyMetadataMosaic { - pub mosaic_id: Option, - pub modifications: Option>, + pub mosaic_id: Option, + pub modifications: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MetadataModification { - modification_type: MetadataModificationType, - key: String, - value: String, + #[serde(rename = "Type")] + pub modification_type: MetadataModificationType, + pub key: String, + pub value: String, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct ModifyMetadataNamespace { - pub namespace_id: Option, - pub modifications: Option>, + pub namespace_id: Option, + pub modifications: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct OfferInfo { - pub offer_type: OfferType, - pub owner: Option, - pub mosaic: Option, - pub price_numerator: Amount, - pub price_denominator: Amount, - pub deadline: Height, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub owner: Option, + pub mosaic: Option, + pub price_numerator: Amount, + pub price_denominator: Amount, + pub deadline: Height, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct UserExchangeInfo { - pub owner: Option, - pub offers: Option>>>, + pub owner: Option, + pub offers: Option>>>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetAccountExchangeInfo { - pub pub_key: Option, + pub pub_key: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetExchangeOfferByAssetId { - pub asset_id: AssetId, - pub offer_type: OfferType, + pub asset_id: AssetId, + pub offer_type: OfferType, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct PublicAccount { - pub public_key: String, + pub public_key: String, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MosaicInfo { - //pub mosaic_id: Option, - pub supply: Amount, - pub height: Height, - pub owner: Option, - pub revision: u32, - pub properties: Option, + pub mosaic_id: Option, + pub supply: Amount, + pub height: Height, + pub owner: Option, + pub revision: u32, + pub properties: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetMosaicInfo { - pub mosaic_id: Option, + pub mosaic_id: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetMosaicInfos { - pub msc_ids: Option>, + pub msc_ids: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct MosaicName { - pub mosaic_id: Option, - pub names: Vec, + pub mosaic_id: Option, + pub names: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetMosaicsNames { - pub msc_ids: Option>, + pub msc_ids: Option>, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetTransaction { - pub id: TransactionID, + pub id: TransactionID, } #[derive(Debug, Deserialize, Serialize)] pub struct GetTransactions { - pub ids: Vec, + pub ids: Vec, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct TransactionStatus { - deadline: Option, - group: String, - status: String, - hash: Option, - height: Height, + deadline: Option, + group: String, + status: String, + hash: Option, + height: Height, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetTransactionStatus { - pub id: TransactionID, + pub id: TransactionID, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetTransactionStatuses { - pub ids: Vec, + pub ids: Vec, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] pub struct GetTransactionEffectiveFee { - pub id: TransactionID, + pub id: TransactionID, } /// # Transactions /// **SignedTransaction** is common interface for transactions data -/// from Blockchain. +/// from Blockchain. pub trait SignedTransaction { - fn id(&self) -> TransactionID; - fn transaction_type(&self) -> TransactionType; - fn signer(&self) -> PubKey; - fn signature(&self) -> Signature; + fn id(&self) -> TransactionID; + fn transaction_type(&self) -> TransactionType; + fn signer(&self) -> PubKey; + fn signature(&self) -> Signature; } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Action { - pub hash: Hash, - pub action_type: i64, - pub size: u64, + pub hash: Hash, + pub action_type: i64, + pub size: u64, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct DriveFsTransaction { - pub id: TransactionID, - pub transaction_type: TransactionType, - pub signer: PubKey, - pub signature: Signature, - pub drive_id: Hash, - pub add_actions: Option>, - pub remove_actions: Option>, + pub id: TransactionID, + pub transaction_type: TransactionType, + pub signer: PubKey, + pub signature: Signature, + pub drive_id: Hash, + pub add_actions: Option>, + pub remove_actions: Option>, } impl DriveFsTransaction { - pub fn drive_id(&self) -> Hash { - self.drive_id.clone() - } + pub fn drive_id(&self) -> Hash { + self.drive_id.clone() + } - pub fn add_actions(&self) -> Option> { - self.add_actions.clone() - } + pub fn add_actions(&self) -> Option> { + self.add_actions.clone() + } - pub fn remove_actions(&self) -> Option> { - self.remove_actions.clone() - } + pub fn remove_actions(&self) -> Option> { + self.remove_actions.clone() + } } impl SignedTransaction for DriveFsTransaction { - fn id(&self) -> TransactionID { - self.id.clone() - } + fn id(&self) -> TransactionID { + self.id.clone() + } - fn transaction_type(&self) -> TransactionType { - self.transaction_type - } + fn transaction_type(&self) -> TransactionType { + self.transaction_type + } - fn signer(&self) -> PubKey { - self.signer.clone() - } + fn signer(&self) -> PubKey { + self.signer.clone() + } - fn signature(&self) -> Signature { - self.signature.clone() - } + fn signature(&self) -> Signature { + self.signature.clone() + } } diff --git a/src/utils.rs b/src/utils.rs index 6425e2e..58a786d 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -6,59 +6,59 @@ use crate::transactions_type::FUNCTION_RETURN_SUCCESS; /// Constructor is function for one time call that can /// can invoke only once for all lifetime of SuperContract. -/// +/// /// Most useful case is run some specific functionality and /// functions once for SuperContract life. Example: create Mosaic /// /// Difference from `init` fucntion that, function can call /// every time when execute some SuperContract function. And /// for that concrete function it can call only once. -/// +/// /// # Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::utils::{constructor, ping}; /// let res = constructor(|| -> i64 { /// let respond = ping(10); /// let res = respond.unwrap(); -/// assert_eq!(res, 11); +/// assert_eq!(res, 11); /// res /// }); /// ``` -/// +/// pub fn constructor(constructor_handler: fn() -> i64) -> i64 { - unsafe { - let status = external::__constructor(); - if status != FUNCTION_RETURN_SUCCESS { - return status; - } - }; - constructor_handler() + unsafe { + let status = external::__constructor(); + if status != FUNCTION_RETURN_SUCCESS { + return status; + } + }; + constructor_handler() } /// Init is function constructor that can can invoked only one time. -/// +/// /// Most useful case is run some specifuc functionality and /// functions to tune-up and prepare some state for SuperContract. /// /// It's impossible run that function twice. -/// +/// /// # Examples /// ```rust,no_run /// use xpx_supercontracts_sdk::utils::{init, ping}; /// init(|| { /// let respond = ping(10); -/// assert_eq!(respond.unwrap(), 11); +/// assert_eq!(respond.unwrap(), 11); /// }); /// ``` -/// +/// pub fn init(init_handler: fn() -> ()) { - unsafe { - let status = external::__init(); - if status != 0 { - return; - } - }; - init_handler(); + unsafe { + let status = external::__init(); + if status != 0 { + return; + } + }; + init_handler(); } /// Send ping message to `WasmVM`. Successful result should be @@ -72,11 +72,11 @@ pub fn init(init_handler: fn() -> ()) { /// assert_eq!(respond.unwrap(), 11); /// ``` pub fn ping(msg: usize) -> FunctionResult { - return unsafe { Ok(external::__ping(msg)) }; + return unsafe { Ok(external::__ping(msg)) }; } /// Return incremented result from all previous invoke that functions. -/// +/// /// Useful for calculating some incremented state. /// /// # Examples @@ -86,7 +86,7 @@ pub fn ping(msg: usize) -> FunctionResult { /// assert_eq!(respond.unwrap(), 11); /// ``` pub fn inc() -> FunctionResult { - return unsafe { Ok(external::__inc()) }; + return unsafe { Ok(external::__inc()) }; } /// Send debug message to `WasmVM`. It's convenient @@ -103,8 +103,8 @@ pub fn inc() -> FunctionResult { /// debug_message(&"Debug message from Supercontract".to_string()); /// ``` pub fn debug_message(msg: &String) { - let raw_msg = msg.as_bytes(); - unsafe { - external::__write_log(raw_msg.as_ptr(), raw_msg.len()); - }; + let raw_msg = msg.as_bytes(); + unsafe { + external::__write_log(raw_msg.as_ptr(), raw_msg.len()); + }; } From 68cd5839221b76edc2c7d12da597b376ea4c4567 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 6 Mar 2020 13:41:28 +0200 Subject: [PATCH 22/28] Transactions types: changed visibilities --- src/transactions_type.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/transactions_type.rs b/src/transactions_type.rs index a80735b..90520d2 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -347,11 +347,11 @@ pub struct GetTransactions { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct TransactionStatus { - deadline: Option, - group: String, - status: String, - hash: Option, - height: Height, + pub deadline: Option, + pub group: String, + pub status: String, + pub hash: Option, + pub height: Height, } #[derive(Debug, Deserialize, Serialize)] @@ -376,10 +376,10 @@ pub struct GetTransactionEffectiveFee { /// **SignedTransaction** is common interface for transactions data /// from Blockchain. pub trait SignedTransaction { - fn id(&self) -> TransactionID; - fn transaction_type(&self) -> TransactionType; - fn signer(&self) -> PubKey; - fn signature(&self) -> Signature; + pub fn id(&self) -> TransactionID; + pub fn transaction_type(&self) -> TransactionType; + pub fn signer(&self) -> PubKey; + pub fn signature(&self) -> Signature; } #[derive(Debug, Deserialize, Serialize, Clone)] From e63a4d2adcd58bb9244abd37935f827feb5d09e6 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 6 Mar 2020 13:42:29 +0200 Subject: [PATCH 23/28] Transactions types: changed visibilities for Traits --- src/transactions_type.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 90520d2..5d7d8ef 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -376,10 +376,10 @@ pub struct GetTransactionEffectiveFee { /// **SignedTransaction** is common interface for transactions data /// from Blockchain. pub trait SignedTransaction { - pub fn id(&self) -> TransactionID; - pub fn transaction_type(&self) -> TransactionType; - pub fn signer(&self) -> PubKey; - pub fn signature(&self) -> Signature; + fn id(&self) -> TransactionID; + fn transaction_type(&self) -> TransactionType; + fn signer(&self) -> PubKey; + fn signature(&self) -> Signature; } #[derive(Debug, Deserialize, Serialize, Clone)] From 4bca792264304e1e8e0f252d32197af406cd1cb0 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sat, 7 Mar 2020 00:50:14 +0200 Subject: [PATCH 24/28] Modify examples/common --- examples/common.rs | 679 +++++++++++++++++++++++---------------------- 1 file changed, 342 insertions(+), 337 deletions(-) diff --git a/examples/common.rs b/examples/common.rs index af17302..d6c2a5e 100644 --- a/examples/common.rs +++ b/examples/common.rs @@ -4,465 +4,470 @@ use xpx_supercontracts_sdk::statuses::Result; use xpx_supercontracts_sdk::storage::save_result; use xpx_supercontracts_sdk::transactions as tx; use xpx_supercontracts_sdk::transactions::{get_supercontract, mosaic_definition}; -use xpx_supercontracts_sdk::transactions_type::{ - AddExchangeOffer, AddOffer, AddressAlias, DriveFsTransaction, ExchangeConfirmation, - ExchangeOffer, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, - GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, - GetTransactionStatus, GetTransactionStatuses, ModifyMetadataAddress, ModifyMetadataMosaic, - ModifyMetadataNamespace, Mosaic, MosaicAlias, MosaicDefinition, MosaicProperties, - MosaicProperty, MosaicSupplyChange, PublicAccount, RegisterRootNamespace, RegisterSubNamespace, - RemoveExchangeOffer, RemoveOffer, Secret, SecretLock, SecretProof, SuperContract, Transfer, - TransferWithNamespace, -}; +use xpx_supercontracts_sdk::transactions_type::{AddExchangeOffer, AddOffer, AddressAlias, DriveFsTransaction, ExchangeConfirmation, ExchangeOffer, GetAccountExchangeInfo, GetExchangeOfferByAssetId, GetMosaicInfo, GetMosaicInfos, GetMosaicsNames, GetTransaction, GetTransactionEffectiveFee, GetTransactionStatus, GetTransactionStatuses, MetadataModification, ModifyMetadataAddress, ModifyMetadataMosaic, ModifyMetadataNamespace, Mosaic, MosaicAlias, MosaicDefinition, MosaicProperties, MosaicProperty, MosaicSupplyChange, Proof, PublicAccount, RegisterRootNamespace, RegisterSubNamespace, RemoveExchangeOffer, RemoveOffer, Secret, SecretLock, SecretProof, SuperContract, Transfer, TransferWithNamespace}; use xpx_supercontracts_sdk::utils::{constructor, debug_message, init, ping}; #[no_mangle] pub extern "C" fn ping100() -> i64 { - ping(100).unwrap() + ping(100).unwrap() } #[no_mangle] pub extern "C" fn ping100init() -> i64 { - let _ = init(|| { - ping(100).unwrap(); - }); - let _ = init(|| { - ping(100).unwrap(); - }); - ping(100).unwrap() + let _ = init(|| { + ping(100).unwrap(); + }); + let _ = init(|| { + ping(100).unwrap(); + }); + ping(100).unwrap() } #[no_mangle] pub extern "C" fn ping_with_params(x: i64) -> i64 { - ping(x as usize).unwrap() + ping(x as usize).unwrap() } #[no_mangle] pub extern "C" fn ping100constructor() -> i64 { - let _ = constructor(|| ping(100).unwrap()); - let _ = constructor(|| ping(100).unwrap()); - ping(100).unwrap() + let _ = constructor(|| ping(100).unwrap()); + let _ = constructor(|| ping(100).unwrap()); + ping(100).unwrap() } #[no_mangle] pub extern "C" fn save_sample_result() -> i64 { - #[derive(Serialize)] - struct SampleData<'a> { - pub id: i64, - pub message: &'a str, - } - let data = serde_json::to_vec(&SampleData { - id: 10, - message: "awesome message", - }) - .unwrap(); - let res = save_result(&"data.txt".to_string(), &data[..]); - if let Err(err) = res { - debug_message(&format!("save_result error {:?}", err)); - return -1; - } - res.unwrap() + #[derive(Serialize)] + struct SampleData<'a> { + pub id: i64, + pub message: &'a str, + } + let data = serde_json::to_vec(&SampleData { + id: 10, + message: "awesome message", + }) + .unwrap(); + let res = save_result(&"data.txt".to_string(), &data[..]); + if let Err(err) = res { + debug_message(&format!("save_result error {:?}", err)); + return -1; + } + res.unwrap() } #[no_mangle] pub extern "C" fn exmpl_get_supercontract() -> i64 { - let res = tx::get_supercontract(); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("SC.ID: {:?}", res.unwrap().id)); - 0 + let res = tx::get_supercontract(); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("SC.ID: {:?}", res.unwrap().id)); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction_effective_fee() -> i64 { - let res = tx::get_transaction_effective_fee(&GetTransactionEffectiveFee { - id: String::from("baegqajaiaqjcb6qufter6rgkiyndqd273kp4n43q2q34uhbt24qb3ehexqcu74u3"), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_transaction_effective_fee(&GetTransactionEffectiveFee { + id: String::from("baegqajaiaqjcb6qufter6rgkiyndqd273kp4n43q2q34uhbt24qb3ehexqcu74u3"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction() -> i64 { - let tx_result: Result = tx::get_transaction(&GetTransaction { - id: String::from("some_id"), - }); - if let Err(err) = tx_result { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", tx_result.unwrap())); - 0 + let tx_result: Result = tx::get_transaction(&GetTransaction { + id: String::from("some_id"), + }); + if let Err(err) = tx_result { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", tx_result.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction_status() -> i64 { - let res = tx::get_transaction_status(&GetTransactionStatus { - id: String::from("some_id"), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_transaction_status(&GetTransactionStatus { + id: String::from("some_id"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_transaction_statuses() -> i64 { - let res = tx::get_transaction_statuses(&GetTransactionStatuses { - ids: vec![String::from("some_id")], - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_transaction_statuses(&GetTransactionStatuses { + ids: vec![String::from("some_id")], + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_account_exchange_info() -> i64 { - let res = tx::get_account_exchange_info(&GetAccountExchangeInfo { - pub_key: Some(String::from("some_pub_key")), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_account_exchange_info(&GetAccountExchangeInfo { + pub_key: Some(String::from("some_pub_key")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_exchange_offer_by_asset_id() -> i64 { - let res = tx::get_exchange_offer_by_asset_id(&GetExchangeOfferByAssetId { - asset_id: 1, - offer_type: 2, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_exchange_offer_by_asset_id(&GetExchangeOfferByAssetId { + asset_id: 1, + offer_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_mosaic_info() -> i64 { - let res = tx::get_mosaic_info(&GetMosaicInfo { mosaic_id: Some(1) }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_mosaic_info(&GetMosaicInfo { mosaic_id: Some(1) }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_mosaic_infos() -> i64 { - let res = tx::get_mosaic_infos(&GetMosaicInfos { - msc_ids: Some(vec![2]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_mosaic_infos(&GetMosaicInfos { + msc_ids: Some(vec![2]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_get_mosaics_names() -> i64 { - let res = tx::get_mosaics_names(&GetMosaicsNames { - msc_ids: Some(vec![1]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::get_mosaics_names(&GetMosaicsNames { + msc_ids: Some(vec![1]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_modify_metadata_namespace() -> i64 { - let res = tx::modify_metadata_namespace(&ModifyMetadataNamespace { - namespace_id: Some(1), - modifications: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::modify_metadata_namespace(&ModifyMetadataNamespace { + namespace_id: Some(1), + modifications: Some(vec![MetadataModification { + modification_type: 1, + key: String::from("some_key"), + value: String::from("some_key"), + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_modify_metadata_mosaic() -> i64 { - let res = tx::modify_metadata_mosaic(&ModifyMetadataMosaic { - mosaic_id: Some(1), - modifications: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::modify_metadata_mosaic(&ModifyMetadataMosaic { + mosaic_id: Some(1), + modifications: Some(vec![MetadataModification { + modification_type: 3, + key: String::from("10"), + value: String::from("20"), + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_modify_metadata_address() -> i64 { - let res = tx::modify_metadata_address(&ModifyMetadataAddress { - address: Some(String::from("some_address")), - modifications: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::modify_metadata_address(&ModifyMetadataAddress { + address: Some(String::from("some_address")), + modifications: Some(vec![MetadataModification { + modification_type: 3, + key: String::from("10"), + value: String::from("20"), + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_secret_proof() -> i64 { - let res = tx::secret_proof(&SecretProof { - hash_type: 1, - proof: None, - recipient: Some(String::from("some recipient")), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::secret_proof(&SecretProof { + hash_type: 1, + proof: Some(Proof { + data: vec![1], + }), + recipient: Some(String::from("some recipient")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_transfer_with_namespace() -> i64 { - let res = tx::transfer_with_namespace(&TransferWithNamespace { - recipient: Some(1), - mosaics: Some(vec![Mosaic { - asset_id: 4, - amount: 10000, - }]), - message: String::from("some message"), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::transfer_with_namespace(&TransferWithNamespace { + recipient: Some(1), + mosaics: Some(vec![Mosaic { + asset_id: 4, + amount: 10000, + }]), + message: String::from("some message"), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_secret_lock() -> i64 { - let res = tx::secret_lock(&SecretLock { - mosaic: Some(Mosaic { - asset_id: 1, - amount: 1000, - }), - duration: 10000, - secret: Some(Secret { - hash: String::from("some hash"), - hash_type: 1, - }), - recipient: Some(String::from("some addr")), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::secret_lock(&SecretLock { + mosaic: Some(Mosaic { + asset_id: 1, + amount: 1000, + }), + duration: 10000, + secret: Some(Secret { + hash: String::from("some hash"), + hash_type: 1, + }), + recipient: Some(String::from("some addr")), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_register_sub_namespace() -> i64 { - let res = tx::register_sub_namespace(&RegisterSubNamespace { - namespace_name: String::from("name"), - parent_id: None, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::register_sub_namespace(&RegisterSubNamespace { + namespace_name: String::from("name"), + parent_id: Some(3), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_register_root_namespace() -> i64 { - let res = tx::register_root_namespace(&RegisterRootNamespace { - namespace_name: String::from("name"), - duration: 1000, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::register_root_namespace(&RegisterRootNamespace { + namespace_name: String::from("name"), + duration: 1000, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_mosaic_supply_change() -> i64 { - let res = tx::mosaic_supply_change(&MosaicSupplyChange { - asset_id: 10, - supply_type: 100, - delta: 300, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::mosaic_supply_change(&MosaicSupplyChange { + asset_id: 10, + supply_type: 100, + delta: 300, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_remove_exchange_offer() -> i64 { - let res = tx::remove_exchange_offer(&RemoveExchangeOffer { - remove_offers: Some(vec![RemoveOffer { - asset_id: 10, - offer_type: 1, - }]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::remove_exchange_offer(&RemoveExchangeOffer { + remove_offers: Some(vec![RemoveOffer { + asset_id: 10, + offer_type: 1, + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_transfer() -> i64 { - let res = tx::transfer(&Transfer { - pub_key: String::from("some_pub_key"), - asset_id: 10, - amount: 1000, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::transfer(&Transfer { + pub_key: String::from("some_pub_key"), + asset_id: 10, + amount: 1000, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_exchange_offer() -> i64 { - let res = tx::exchange_offer(&ExchangeOffer { - offer: Some(vec![ExchangeConfirmation { - offer_type: 1, - mosaic: Some(Mosaic { - asset_id: 3, - amount: 10000, - }), - cost: 1000, - owner: Some(PublicAccount { - public_key: String::from( - "baegqajaiaqjcakxppt6hi3pcghh3en7fj47jkf6phllbkz2hx2bdvdeyelrrcmx5", - ), - }), - }]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::exchange_offer(&ExchangeOffer { + offer: Some(vec![ExchangeConfirmation { + offer_type: 1, + mosaic: Some(Mosaic { + asset_id: 3, + amount: 10000, + }), + cost: 1000, + owner: Some(PublicAccount { + public_key: String::from( + "baegqajaiaqjcakxppt6hi3pcghh3en7fj47jkf6phllbkz2hx2bdvdeyelrrcmx5", + ), + }), + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_add_exchange_offer() -> i64 { - let res = tx::add_exchange_offer(&AddExchangeOffer { - add_offers: Some(vec![AddOffer { - offer_type: 3, - mosaic: Some(Mosaic { - amount: 1000, - asset_id: 3, - }), - cost: 100, - duration: 1000, - }]), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::add_exchange_offer(&AddExchangeOffer { + add_offers: Some(vec![AddOffer { + offer_type: 3, + mosaic: Some(Mosaic { + amount: 1000, + asset_id: 3, + }), + cost: 100, + duration: 1000, + }]), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_mosaic_alias() -> i64 { - let res = tx::mosaic_alias(&MosaicAlias { - mosaic_id: Some(10), - namespace_id: Some(3), - action_type: 2, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::mosaic_alias(&MosaicAlias { + mosaic_id: Some(10), + namespace_id: Some(3), + action_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_address_alias() -> i64 { - let res = tx::address_alias(&AddressAlias { - address: Some(String::from("SAONSOGFZZHNEIBRYXHDTDTBR2YSAXKTITRFHG2Y")), - namespace_id: Some(0xFF000000_FF000000), - action_type: 2, - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = tx::address_alias(&AddressAlias { + address: Some(String::from("SAONSOGFZZHNEIBRYXHDTDTBR2YSAXKTITRFHG2Y")), + namespace_id: Some(0xFF000000_FF000000), + action_type: 2, + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } #[no_mangle] pub extern "C" fn exmpl_create_mosaic() -> i64 { - let res = get_supercontract(); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - let sc: SuperContract = res.unwrap(); - - debug_message(&format!("SC.ID: {:?}", sc.id)); - let res = mosaic_definition(&MosaicDefinition { - nonce: 0, - owner_public_key: sc.id, - mosaic_props: Some(MosaicProperties { - supply_mutable: true, - transferable: true, - divisibility: 0, - optional_properties: vec![MosaicProperty { id: 0, value: 0 }], - }), - }); - if let Err(err) = res { - debug_message(&format!("{:?}", err)); - return -1; - } - - debug_message(&format!("Result: {:?}", res.unwrap())); - 0 + let res = get_supercontract(); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + let sc: SuperContract = res.unwrap(); + + debug_message(&format!("SC.ID: {:?}", sc.id)); + let res = mosaic_definition(&MosaicDefinition { + nonce: 0, + owner_public_key: sc.id, + mosaic_props: Some(MosaicProperties { + supply_mutable: true, + transferable: true, + divisibility: 0, + optional_properties: vec![MosaicProperty { id: 0, value: 0 }], + }), + }); + if let Err(err) = res { + debug_message(&format!("{:?}", err)); + return -1; + } + + debug_message(&format!("Result: {:?}", res.unwrap())); + 0 } From f333848e5ef1a04f41b56863d1e9dbc9305d9731 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Thu, 12 Mar 2020 21:27:51 +0200 Subject: [PATCH 25/28] Added basic flow for ICO from CSV example --- Cargo.lock | 62 +++++++++++++++++++++++++++++++++ Cargo.toml | 7 +++- examples/ico.rs | 86 ++++++++++++++++++++++++++++++++++++++++++++++ examples/mosaic.rs | 2 +- 4 files changed, 155 insertions(+), 2 deletions(-) create mode 100644 examples/ico.rs diff --git a/Cargo.lock b/Cargo.lock index 4862237..caefcf0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,6 +20,22 @@ dependencies = [ "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "bstr" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "regex-automata 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "byteorder" +version = "1.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "cc" version = "1.0.50" @@ -30,6 +46,26 @@ name = "cfg-if" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "csv" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bstr 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", + "csv-core 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "csv-core" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "failure" version = "0.1.6" @@ -55,11 +91,21 @@ name = "itoa" version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "libc" version = "0.2.66" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "memchr" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "proc-macro2" version = "1.0.8" @@ -76,6 +122,14 @@ dependencies = [ "proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "regex-automata" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "rustc-demangle" version = "0.1.16" @@ -144,6 +198,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "xpx_supercontracts_sdk" version = "0.2.0" dependencies = [ + "csv 1.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.48 (registry+https://github.com/rust-lang/crates.io-index)", @@ -152,14 +207,21 @@ dependencies = [ [metadata] "checksum backtrace 0.3.44 (registry+https://github.com/rust-lang/crates.io-index)" = "e4036b9bf40f3cf16aba72a3d65e8a520fc4bafcdc7079aea8f848c58c5b5536" "checksum backtrace-sys 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "5d6575f128516de27e3ce99689419835fce9643a9b215a14d2b5b685be018491" +"checksum bstr 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "502ae1441a0a5adb8fbd38a5955a6416b9493e92b465de5e4a9bde6a539c2c48" +"checksum byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" "checksum cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)" = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum csv 1.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "00affe7f6ab566df61b4be3ce8cf16bc2576bca0963ceb0955e45d514bf9a279" +"checksum csv-core 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" "checksum failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "f8273f13c977665c5db7eb2b99ae520952fe5ac831ae4cd09d80c4c7042b5ed9" "checksum failure_derive 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0bc225b78e0391e4b8683440bf2e63c2deeeb2ce5189eab46e2b68c6d3725d08" "checksum itoa 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" +"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" "checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" +"checksum memchr 2.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" "checksum proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3acb317c6ff86a4e579dfa00fc5e6cca91ecbb4e7eb2df0468805b674eb88548" "checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" +"checksum regex-automata 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "ae1ded71d66a4a97f5e961fd0cb25a5f366a42a41570d16a763a69c092c26ae4" "checksum rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" "checksum ryu 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8" "checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" diff --git a/Cargo.toml b/Cargo.toml index dc6d148..2a9fc3a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "xpx_supercontracts_sdk" version = "0.2.0" -authors = ["ProxymaX Core Development Team"] +authors = ["ProxymaX Core Development Team", "Evgeny Ukhanov "] description = "ProximaX Supercontracts Rust SDK" edition = "2018" homepage = "https://www.proximax.io/" @@ -17,6 +17,7 @@ repository = "https://github.com/proximax-storage/rust-xpx-supercontracts-sdk" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" failure = "0.1.5" +csv = "1.1" [[example]] name = "mosaic" @@ -26,6 +27,10 @@ crate-type = ["cdylib"] name = "ping" crate-type = ["cdylib"] +[[example]] +name = "ico" +crate-type = ["cdylib"] + [[example]] name = "common" crate-type = ["cdylib"] diff --git a/examples/ico.rs b/examples/ico.rs new file mode 100644 index 0000000..297723a --- /dev/null +++ b/examples/ico.rs @@ -0,0 +1,86 @@ +use xpx_supercontracts_sdk::utils::constructor; + +mod ico { + use serde::Deserialize; + + use xpx_supercontracts_sdk::storage::storage_get; + use xpx_supercontracts_sdk::transactions::{flush, get_supercontract, mosaic_definition}; + use xpx_supercontracts_sdk::transactions_type::{FUNCTION_ERROR, FUNCTION_RETURN_SUCCESS, MosaicDefinition, MosaicProperties, MosaicProperty, SuperContract}; + use xpx_supercontracts_sdk::utils::debug_message; + + const ICO_CSV_FILE: &str = "ico_init.csv"; + + #[derive(Debug, Deserialize)] + struct CsvIcoData { + name: Option, + shareholder_address: String, + amount: u64, + } + + pub fn create_ico() -> i64 { + let mosaic_result = create_mosaic(); + if mosaic_result < FUNCTION_RETURN_SUCCESS { + return mosaic_result; + } + + let file_result = storage_get(&ICO_CSV_FILE.to_string()); + if let Err(err) = file_result { + debug_message(&format!("failed load CSV file: {}", err)); + return FUNCTION_ERROR; + } + 0 + } + + fn parse_csv(data: &Vec) -> Vec { + let mut csv_reader = csv::ReaderBuilder::new() + .delimiter(b';') + .from_reader(&data[..]); + vec![] + } + + fn create_mosaic() -> i64 { + let res = get_supercontract(); + if res.is_err() { + return FUNCTION_ERROR; + } + let sc: SuperContract = res.unwrap(); + + debug_message(&format!("SC.ID: {:?}", sc.id)); + let res = mosaic_definition(&MosaicDefinition { + nonce: 0, + owner_public_key: sc.id, + mosaic_props: Some(MosaicProperties { + supply_mutable: true, + transferable: true, + divisibility: 0, + optional_properties: vec![MosaicProperty { + id: 0, + value: 0, + }], + }), + }); + if let Err(err) = res { + debug_message(&format!("failed create mosaic: {}", err)); + return FUNCTION_ERROR; + } + let result = res.unwrap(); + if result < FUNCTION_RETURN_SUCCESS { + debug_message(&"failed create mosaic".to_string()); + return result; + } + + // Flush Tx + let res = flush(); + if let Err(err) = res { + debug_message(&format!("failed flush transaction: {}", err)); + return FUNCTION_ERROR; + } + + FUNCTION_RETURN_SUCCESS + } +} + +#[no_mangle] +pub extern "C" fn ico_init() -> i64 { + constructor(ico::create_ico) +} diff --git a/examples/mosaic.rs b/examples/mosaic.rs index c560168..c7f8120 100644 --- a/examples/mosaic.rs +++ b/examples/mosaic.rs @@ -8,7 +8,7 @@ use xpx_supercontracts_sdk::{ utils::{constructor, debug_message}, }; -pub fn create_mosaic() -> i64 { +fn create_mosaic() -> i64 { let res = get_supercontract(); if res.is_err() { return -1; From 17631acc9e15ee9c81452afe9c14f0f624af8ac7 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 13 Mar 2020 00:04:02 +0200 Subject: [PATCH 26/28] Example ICO - implement constructor --- examples/ico.rs | 59 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/examples/ico.rs b/examples/ico.rs index 297723a..8d56584 100644 --- a/examples/ico.rs +++ b/examples/ico.rs @@ -3,18 +3,20 @@ use xpx_supercontracts_sdk::utils::constructor; mod ico { use serde::Deserialize; + use xpx_supercontracts_sdk::statuses::{Error, Result}; use xpx_supercontracts_sdk::storage::storage_get; - use xpx_supercontracts_sdk::transactions::{flush, get_supercontract, mosaic_definition}; - use xpx_supercontracts_sdk::transactions_type::{FUNCTION_ERROR, FUNCTION_RETURN_SUCCESS, MosaicDefinition, MosaicProperties, MosaicProperty, SuperContract}; + use xpx_supercontracts_sdk::transactions::{flush, get_supercontract, mosaic_definition, transfer}; + use xpx_supercontracts_sdk::transactions_type::{FUNCTION_ERROR, FUNCTION_RETURN_SUCCESS, MosaicDefinition, MosaicProperties, MosaicProperty, SuperContract, Transfer}; use xpx_supercontracts_sdk::utils::debug_message; const ICO_CSV_FILE: &str = "ico_init.csv"; + const TRANSACTIONS_LIMIT: u8 = 50; #[derive(Debug, Deserialize)] struct CsvIcoData { name: Option, shareholder_address: String, - amount: u64, + amount: i64, } pub fn create_ico() -> i64 { @@ -28,21 +30,64 @@ mod ico { debug_message(&format!("failed load CSV file: {}", err)); return FUNCTION_ERROR; } + + let csv_data = parse_csv(&file_result.unwrap()); + if csv_data.is_err() { + return FUNCTION_ERROR; + } + + let mut counter = 0; + for data in csv_data.unwrap() { + // Transfer tokens + let res = transfer(&Transfer { + pub_key: data.shareholder_address, + amount: data.amount, + asset_id: 1, + }); + if let Err(err) = res { + debug_message(&format!("failed transfer mosaic: {:?}", err)); + return FUNCTION_ERROR; + } + + counter += 1; + if counter >= TRANSACTIONS_LIMIT { + let res = flush(); + if let Err(err) = res { + debug_message(&format!("failed flush transaction: {}", err)); + return FUNCTION_ERROR; + } + counter = 0; + } + } + 0 } - fn parse_csv(data: &Vec) -> Vec { + fn parse_csv(data: &Vec) -> Result> { let mut csv_reader = csv::ReaderBuilder::new() .delimiter(b';') .from_reader(&data[..]); - vec![] + + let mut csv_result: Vec = vec![]; + for res in csv_reader.deserialize() { + if let Err(err) = res { + debug_message(&format!("failed parse csv file: {:?}", err)); + return Err(Error::DeserializeJson); + } + + let value: CsvIcoData = res.unwrap(); + csv_result.push(value); + } + Ok(csv_result) } fn create_mosaic() -> i64 { let res = get_supercontract(); - if res.is_err() { + if let Err(err) = res { + debug_message(&format!("failed get supercontract: {:?}", err)); return FUNCTION_ERROR; } + let sc: SuperContract = res.unwrap(); debug_message(&format!("SC.ID: {:?}", sc.id)); @@ -63,13 +108,13 @@ mod ico { debug_message(&format!("failed create mosaic: {}", err)); return FUNCTION_ERROR; } + let result = res.unwrap(); if result < FUNCTION_RETURN_SUCCESS { debug_message(&"failed create mosaic".to_string()); return result; } - // Flush Tx let res = flush(); if let Err(err) = res { debug_message(&format!("failed flush transaction: {}", err)); From f3e8b20e3a4460688b203e087742e7d78ab6b06a Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Fri, 13 Mar 2020 17:01:25 +0200 Subject: [PATCH 27/28] Added GetMosaicID --- examples/ico.rs | 131 ---------------- src/external.rs | 121 ++++++++------- src/transactions.rs | 22 +++ src/transactions_type.rs | 319 ++++++++++++++++++++------------------- 4 files changed, 248 insertions(+), 345 deletions(-) diff --git a/examples/ico.rs b/examples/ico.rs index 8d56584..e69de29 100644 --- a/examples/ico.rs +++ b/examples/ico.rs @@ -1,131 +0,0 @@ -use xpx_supercontracts_sdk::utils::constructor; - -mod ico { - use serde::Deserialize; - - use xpx_supercontracts_sdk::statuses::{Error, Result}; - use xpx_supercontracts_sdk::storage::storage_get; - use xpx_supercontracts_sdk::transactions::{flush, get_supercontract, mosaic_definition, transfer}; - use xpx_supercontracts_sdk::transactions_type::{FUNCTION_ERROR, FUNCTION_RETURN_SUCCESS, MosaicDefinition, MosaicProperties, MosaicProperty, SuperContract, Transfer}; - use xpx_supercontracts_sdk::utils::debug_message; - - const ICO_CSV_FILE: &str = "ico_init.csv"; - const TRANSACTIONS_LIMIT: u8 = 50; - - #[derive(Debug, Deserialize)] - struct CsvIcoData { - name: Option, - shareholder_address: String, - amount: i64, - } - - pub fn create_ico() -> i64 { - let mosaic_result = create_mosaic(); - if mosaic_result < FUNCTION_RETURN_SUCCESS { - return mosaic_result; - } - - let file_result = storage_get(&ICO_CSV_FILE.to_string()); - if let Err(err) = file_result { - debug_message(&format!("failed load CSV file: {}", err)); - return FUNCTION_ERROR; - } - - let csv_data = parse_csv(&file_result.unwrap()); - if csv_data.is_err() { - return FUNCTION_ERROR; - } - - let mut counter = 0; - for data in csv_data.unwrap() { - // Transfer tokens - let res = transfer(&Transfer { - pub_key: data.shareholder_address, - amount: data.amount, - asset_id: 1, - }); - if let Err(err) = res { - debug_message(&format!("failed transfer mosaic: {:?}", err)); - return FUNCTION_ERROR; - } - - counter += 1; - if counter >= TRANSACTIONS_LIMIT { - let res = flush(); - if let Err(err) = res { - debug_message(&format!("failed flush transaction: {}", err)); - return FUNCTION_ERROR; - } - counter = 0; - } - } - - 0 - } - - fn parse_csv(data: &Vec) -> Result> { - let mut csv_reader = csv::ReaderBuilder::new() - .delimiter(b';') - .from_reader(&data[..]); - - let mut csv_result: Vec = vec![]; - for res in csv_reader.deserialize() { - if let Err(err) = res { - debug_message(&format!("failed parse csv file: {:?}", err)); - return Err(Error::DeserializeJson); - } - - let value: CsvIcoData = res.unwrap(); - csv_result.push(value); - } - Ok(csv_result) - } - - fn create_mosaic() -> i64 { - let res = get_supercontract(); - if let Err(err) = res { - debug_message(&format!("failed get supercontract: {:?}", err)); - return FUNCTION_ERROR; - } - - let sc: SuperContract = res.unwrap(); - - debug_message(&format!("SC.ID: {:?}", sc.id)); - let res = mosaic_definition(&MosaicDefinition { - nonce: 0, - owner_public_key: sc.id, - mosaic_props: Some(MosaicProperties { - supply_mutable: true, - transferable: true, - divisibility: 0, - optional_properties: vec![MosaicProperty { - id: 0, - value: 0, - }], - }), - }); - if let Err(err) = res { - debug_message(&format!("failed create mosaic: {}", err)); - return FUNCTION_ERROR; - } - - let result = res.unwrap(); - if result < FUNCTION_RETURN_SUCCESS { - debug_message(&"failed create mosaic".to_string()); - return result; - } - - let res = flush(); - if let Err(err) = res { - debug_message(&format!("failed flush transaction: {}", err)); - return FUNCTION_ERROR; - } - - FUNCTION_RETURN_SUCCESS - } -} - -#[no_mangle] -pub extern "C" fn ico_init() -> i64 { - constructor(ico::create_ico) -} diff --git a/src/external.rs b/src/external.rs index e64a4e9..7445938 100644 --- a/src/external.rs +++ b/src/external.rs @@ -1,61 +1,66 @@ extern "C" { - pub fn __ping(number: usize) -> i64; - pub fn __constructor() -> i64; - pub fn __init() -> i64; - pub fn __inc() -> i64; - pub fn __write_log(msg: *const u8, len: usize) -> i64; - pub fn save_to_storage( - file_ptr: *const u8, - file_len: usize, - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn save_sc_result( - file_ptr: *const u8, - file_len: usize, - data_ptr: *const u8, - data_len: usize, - ) -> i64; - pub fn get_from_storage(file_ptr: *const u8, file_len: usize, data: *mut u8) -> i64; - pub fn get_http(url: *const u8, url_len: usize, body: *mut u8) -> i64; + pub fn __ping(number: usize) -> i64; + pub fn __constructor() -> i64; + pub fn __init() -> i64; + pub fn __inc() -> i64; + pub fn __write_log(msg: *const u8, len: usize) -> i64; + pub fn save_to_storage( + file_ptr: *const u8, + file_len: usize, + data_ptr: *const u8, + data_len: usize, + ) -> i64; + pub fn save_sc_result( + file_ptr: *const u8, + file_len: usize, + data_ptr: *const u8, + data_len: usize, + ) -> i64; + pub fn get_from_storage(file_ptr: *const u8, file_len: usize, data: *mut u8) -> i64; + pub fn get_http(url: *const u8, url_len: usize, body: *mut u8) -> i64; - //================================================== - // Blockchain Transactions manipulations - pub fn flush() -> i64; - pub fn mosaic_definition(data_ptr: *const u8, data_len: usize) -> i64; - pub fn address_alias(data_ptr: *const u8, data_len: usize) -> i64; - pub fn mosaic_alias(data_ptr: *const u8, data_len: usize) -> i64; - pub fn add_exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; - pub fn exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; - pub fn transfer(data_ptr: *const u8, data_len: usize) -> i64; - pub fn remove_exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; - pub fn mosaic_supply_change(data_ptr: *const u8, data_len: usize) -> i64; - pub fn register_root_namespace(data_ptr: *const u8, data_len: usize) -> i64; - pub fn register_sub_namespace(data_ptr: *const u8, data_len: usize) -> i64; - pub fn secret_lock(data_ptr: *const u8, data_len: usize) -> i64; - pub fn secret_proof(data_ptr: *const u8, data_len: usize) -> i64; - pub fn transfer_with_namespace(data_ptr: *const u8, data_len: usize) -> i64; - pub fn modify_metadata_address(data_ptr: *const u8, data_len: usize) -> i64; - pub fn modify_metadata_mosaic(data_ptr: *const u8, data_len: usize) -> i64; - pub fn modify_metadata_namespace(data_ptr: *const u8, data_len: usize) -> i64; - //============================================== - // Blockchain Getters - pub fn get_account_exchange_info(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; - pub fn get_exchange_offer_by_asset_id( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_mosaic_info(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; - pub fn get_mosaic_infos(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; - pub fn get_mosaics_names(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; - pub fn get_transaction(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; - pub fn get_transaction_status(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; - pub fn get_transaction_statuses(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; - pub fn get_transaction_effective_fee( - data_ptr: *const u8, - data_len: usize, - data: *mut u8, - ) -> i64; - pub fn get_supercontract(data: *mut u8) -> i64; + //================================================== + // Blockchain Transactions manipulations + pub fn flush() -> i64; + pub fn mosaic_definition(data_ptr: *const u8, data_len: usize) -> i64; + pub fn address_alias(data_ptr: *const u8, data_len: usize) -> i64; + pub fn mosaic_alias(data_ptr: *const u8, data_len: usize) -> i64; + pub fn add_exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn transfer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn remove_exchange_offer(data_ptr: *const u8, data_len: usize) -> i64; + pub fn mosaic_supply_change(data_ptr: *const u8, data_len: usize) -> i64; + pub fn register_root_namespace(data_ptr: *const u8, data_len: usize) -> i64; + pub fn register_sub_namespace(data_ptr: *const u8, data_len: usize) -> i64; + pub fn secret_lock(data_ptr: *const u8, data_len: usize) -> i64; + pub fn secret_proof(data_ptr: *const u8, data_len: usize) -> i64; + pub fn transfer_with_namespace(data_ptr: *const u8, data_len: usize) -> i64; + pub fn modify_metadata_address(data_ptr: *const u8, data_len: usize) -> i64; + pub fn modify_metadata_mosaic(data_ptr: *const u8, data_len: usize) -> i64; + pub fn modify_metadata_namespace(data_ptr: *const u8, data_len: usize) -> i64; + //============================================== + // Blockchain Getters + pub fn get_account_exchange_info(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_exchange_offer_by_asset_id( + data_ptr: *const u8, + data_len: usize, + data: *mut u8, + ) -> i64; + pub fn get_mosaic_info(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_mosaic_infos(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_mosaics_names(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction_status(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction_statuses(data_ptr: *const u8, data_len: usize, data: *mut u8) -> i64; + pub fn get_transaction_effective_fee( + data_ptr: *const u8, + data_len: usize, + data: *mut u8, + ) -> i64; + pub fn get_mosaic_id( + data_ptr: *const u8, + data_len: usize, + data: *mut u8, + ) -> i64; + pub fn get_supercontract(data: *mut u8) -> i64; } diff --git a/src/transactions.rs b/src/transactions.rs index 62c6cb0..fba09f5 100644 --- a/src/transactions.rs +++ b/src/transactions.rs @@ -693,6 +693,28 @@ pub fn get_transaction_effective_fee(params: &GetTransactionEffectiveFee) -> Res call_external_func(params, external::get_transaction_effective_fee) } +/// Get data via **GetMosaicID** +/// +/// ## Examples +/// ```rust,no_run +/// use xpx_supercontracts_sdk::transactions::{ +/// get_mosaic_id, +/// }; +/// use xpx_supercontracts_sdk::transactions_type::{GetMosaicID}; +/// +/// let params = GetMosaicID{ +/// nonce: 0, +/// owner_public_key: String::from("some_id"), +/// }; +/// // Get info data +/// let result = get_mosaic_id(¶ms); +/// let info = result.unwrap(); +/// ``` +/// +pub fn get_mosaci_id(params: &GetMosaicID) -> Result { + call_external_func(params, external::get_mosaic_id) +} + /// Get data current SuperContract data /// /// ## Examples diff --git a/src/transactions_type.rs b/src/transactions_type.rs index 5d7d8ef..b1f020a 100644 --- a/src/transactions_type.rs +++ b/src/transactions_type.rs @@ -37,53 +37,53 @@ pub type Signature = String; #[derive(Debug, Deserialize, Serialize)] pub struct Drive { - pub drive: Cid, - pub owner: PubKey, - pub root: Cid, + pub drive: Cid, + pub owner: PubKey, + pub root: Cid, } #[derive(Debug, Deserialize, Serialize)] pub struct SuperContract { - pub id: Cid, - pub drive: Drive, - pub file: Cid, - pub vmversion: u64, + pub id: Cid, + pub drive: Drive, + pub file: Cid, + pub vmversion: u64, } #[derive(Debug, Deserialize, Serialize)] pub struct AbstractTransaction { - pub height: Height, - pub index: u32, - pub transaction_hash: Option, - pub merkle_component_hash: Option, - pub aggregate_hash: Option, - pub unique_aggregate_hash: Option, - pub aggregate_id: Vec, + pub height: Height, + pub index: u32, + pub transaction_hash: Option, + pub merkle_component_hash: Option, + pub aggregate_hash: Option, + pub unique_aggregate_hash: Option, + pub aggregate_id: Vec, - pub network_type: NetworkType, - pub deadline: Option, - pub entity_type: EntityType, - pub version: EntityVersion, - pub max_fee: Amount, - pub signature: Vec, - pub signer: Option, + pub network_type: NetworkType, + pub deadline: Option, + pub entity_type: EntityType, + pub version: EntityVersion, + pub max_fee: Amount, + pub signature: Vec, + pub signer: Option, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MosaicDefinition { - pub nonce: u32, - pub owner_public_key: String, - pub mosaic_props: Option, + pub nonce: u32, + pub owner_public_key: String, + pub mosaic_props: Option, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MosaicProperties { - pub supply_mutable: bool, - pub transferable: bool, - pub divisibility: u8, - pub optional_properties: Vec, + pub supply_mutable: bool, + pub transferable: bool, + pub divisibility: u8, + pub optional_properties: Vec, } pub type MosaicPropertyId = u8; @@ -91,343 +91,350 @@ pub type MosaicPropertyId = u8; #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MosaicProperty { - pub id: MosaicPropertyId, - pub value: i64, + pub id: MosaicPropertyId, + pub value: i64, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct AddressAlias { - pub address: Option
, - pub namespace_id: Option, - pub action_type: AliasActionType, + pub address: Option
, + pub namespace_id: Option, + pub action_type: AliasActionType, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MosaicAlias { - pub mosaic_id: Option, - pub namespace_id: Option, - pub action_type: AliasActionType, + pub mosaic_id: Option, + pub namespace_id: Option, + pub action_type: AliasActionType, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct AddExchangeOffer { - pub add_offers: Option>, + pub add_offers: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct ExchangeConfirmation { - #[serde(rename = "Type")] - pub offer_type: OfferType, - pub mosaic: Option, - pub cost: Amount, - pub owner: Option, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub mosaic: Option, + pub cost: Amount, + pub owner: Option, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct AddOffer { - #[serde(rename = "Type")] - pub offer_type: OfferType, - pub mosaic: Option, - pub cost: Amount, - pub duration: Duration, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub mosaic: Option, + pub cost: Amount, + pub duration: Duration, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct ExchangeOffer { - pub offer: Option>, + pub offer: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct Transfer { - pub pub_key: PubKey, - pub asset_id: AssetId, - pub amount: i64, + pub pub_key: PubKey, + pub asset_id: AssetId, + pub amount: i64, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct RemoveOffer { - #[serde(rename = "Type")] - pub offer_type: OfferType, - pub asset_id: AssetId, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub asset_id: AssetId, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct RemoveExchangeOffer { - pub remove_offers: Option>, + pub remove_offers: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MosaicSupplyChange { - pub asset_id: AssetId, - pub supply_type: MosaicSupplyType, - pub delta: Duration, + pub asset_id: AssetId, + pub supply_type: MosaicSupplyType, + pub delta: Duration, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct RegisterRootNamespace { - pub namespace_name: String, - pub duration: Duration, + pub namespace_name: String, + pub duration: Duration, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct RegisterSubNamespace { - pub namespace_name: String, - pub parent_id: Option, + pub namespace_name: String, + pub parent_id: Option, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct Mosaic { - pub asset_id: AssetId, - pub amount: Amount, + pub asset_id: AssetId, + pub amount: Amount, } #[derive(Debug, Deserialize, Serialize)] pub struct Secret { - pub hash: Hash, - pub hash_type: HashType, + pub hash: Hash, + pub hash_type: HashType, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct SecretLock { - pub mosaic: Option, - pub duration: Duration, - pub secret: Option, - pub recipient: Option
, + pub mosaic: Option, + pub duration: Duration, + pub secret: Option, + pub recipient: Option
, } #[derive(Debug, Deserialize, Serialize)] pub struct Proof { - pub data: Vec, + pub data: Vec, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct SecretProof { - pub hash_type: HashType, - pub proof: Option, - pub recipient: Option
, + pub hash_type: HashType, + pub proof: Option, + pub recipient: Option
, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct TransferWithNamespace { - pub recipient: Option, - pub mosaics: Option>, - pub message: Message, + pub recipient: Option, + pub mosaics: Option>, + pub message: Message, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct ModifyMetadataAddress { - pub address: Option
, - pub modifications: Option>, + pub address: Option
, + pub modifications: Option>, } #[derive(Debug, Deserialize, Serialize)] pub struct ModifyMetadataMosaic { - pub mosaic_id: Option, - pub modifications: Option>, + pub mosaic_id: Option, + pub modifications: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MetadataModification { - #[serde(rename = "Type")] - pub modification_type: MetadataModificationType, - pub key: String, - pub value: String, + #[serde(rename = "Type")] + pub modification_type: MetadataModificationType, + pub key: String, + pub value: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct ModifyMetadataNamespace { - pub namespace_id: Option, - pub modifications: Option>, + pub namespace_id: Option, + pub modifications: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct OfferInfo { - #[serde(rename = "Type")] - pub offer_type: OfferType, - pub owner: Option, - pub mosaic: Option, - pub price_numerator: Amount, - pub price_denominator: Amount, - pub deadline: Height, + #[serde(rename = "Type")] + pub offer_type: OfferType, + pub owner: Option, + pub mosaic: Option, + pub price_numerator: Amount, + pub price_denominator: Amount, + pub deadline: Height, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct UserExchangeInfo { - pub owner: Option, - pub offers: Option>>>, + pub owner: Option, + pub offers: Option>>>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetAccountExchangeInfo { - pub pub_key: Option, + pub pub_key: Option, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetExchangeOfferByAssetId { - pub asset_id: AssetId, - pub offer_type: OfferType, + pub asset_id: AssetId, + pub offer_type: OfferType, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct PublicAccount { - pub public_key: String, + pub public_key: String, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MosaicInfo { - pub mosaic_id: Option, - pub supply: Amount, - pub height: Height, - pub owner: Option, - pub revision: u32, - pub properties: Option, + pub mosaic_id: Option, + pub supply: Amount, + pub height: Height, + pub owner: Option, + pub revision: u32, + pub properties: Option, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetMosaicInfo { - pub mosaic_id: Option, + pub mosaic_id: Option, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetMosaicInfos { - pub msc_ids: Option>, + pub msc_ids: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct MosaicName { - pub mosaic_id: Option, - pub names: Option>, + pub mosaic_id: Option, + pub names: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetMosaicsNames { - pub msc_ids: Option>, + pub msc_ids: Option>, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetTransaction { - pub id: TransactionID, + pub id: TransactionID, } #[derive(Debug, Deserialize, Serialize)] pub struct GetTransactions { - pub ids: Vec, + pub ids: Vec, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct TransactionStatus { - pub deadline: Option, - pub group: String, - pub status: String, - pub hash: Option, - pub height: Height, + pub deadline: Option, + pub group: String, + pub status: String, + pub hash: Option, + pub height: Height, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetTransactionStatus { - pub id: TransactionID, + pub id: TransactionID, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetTransactionStatuses { - pub ids: Vec, + pub ids: Vec, } #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "PascalCase")] pub struct GetTransactionEffectiveFee { - pub id: TransactionID, + pub id: TransactionID, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "PascalCase")] +pub struct GetMosaicID { + nonce: u32, + owner_public_key: String, } /// # Transactions /// **SignedTransaction** is common interface for transactions data /// from Blockchain. pub trait SignedTransaction { - fn id(&self) -> TransactionID; - fn transaction_type(&self) -> TransactionType; - fn signer(&self) -> PubKey; - fn signature(&self) -> Signature; + fn id(&self) -> TransactionID; + fn transaction_type(&self) -> TransactionType; + fn signer(&self) -> PubKey; + fn signature(&self) -> Signature; } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Action { - pub hash: Hash, - pub action_type: i64, - pub size: u64, + pub hash: Hash, + pub action_type: i64, + pub size: u64, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct DriveFsTransaction { - pub id: TransactionID, - pub transaction_type: TransactionType, - pub signer: PubKey, - pub signature: Signature, - pub drive_id: Hash, - pub add_actions: Option>, - pub remove_actions: Option>, + pub id: TransactionID, + pub transaction_type: TransactionType, + pub signer: PubKey, + pub signature: Signature, + pub drive_id: Hash, + pub add_actions: Option>, + pub remove_actions: Option>, } impl DriveFsTransaction { - pub fn drive_id(&self) -> Hash { - self.drive_id.clone() - } + pub fn drive_id(&self) -> Hash { + self.drive_id.clone() + } - pub fn add_actions(&self) -> Option> { - self.add_actions.clone() - } + pub fn add_actions(&self) -> Option> { + self.add_actions.clone() + } - pub fn remove_actions(&self) -> Option> { - self.remove_actions.clone() - } + pub fn remove_actions(&self) -> Option> { + self.remove_actions.clone() + } } impl SignedTransaction for DriveFsTransaction { - fn id(&self) -> TransactionID { - self.id.clone() - } + fn id(&self) -> TransactionID { + self.id.clone() + } - fn transaction_type(&self) -> TransactionType { - self.transaction_type - } + fn transaction_type(&self) -> TransactionType { + self.transaction_type + } - fn signer(&self) -> PubKey { - self.signer.clone() - } + fn signer(&self) -> PubKey { + self.signer.clone() + } - fn signature(&self) -> Signature { - self.signature.clone() - } + fn signature(&self) -> Signature { + self.signature.clone() + } } From db716beec45f1a629cc9d5786131ae656c5acc19 Mon Sep 17 00:00:00 2001 From: Evgeny Ukhanov Date: Sat, 14 Mar 2020 00:11:25 +0200 Subject: [PATCH 28/28] Chened docs --- Cargo.lock | 2 +- Cargo.toml | 3 +-- README.md | 1 + 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index caefcf0..104ca7c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -195,7 +195,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "xpx_supercontracts_sdk" +name = "xpx-supercontracts-sdk" version = "0.2.0" dependencies = [ "csv 1.1.3 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/Cargo.toml b/Cargo.toml index 2a9fc3a..bbc3018 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "xpx_supercontracts_sdk" +name = "xpx-supercontracts-sdk" version = "0.2.0" authors = ["ProxymaX Core Development Team", "Evgeny Ukhanov "] description = "ProximaX Supercontracts Rust SDK" @@ -12,7 +12,6 @@ categories = ["cryptography", "sdk"] license = "Apache-2.0" repository = "https://github.com/proximax-storage/rust-xpx-supercontracts-sdk" - [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/README.md b/README.md index 6227b31..9fa063b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +![Documentation](https://docs.rs/xpx-supercontracts-sdk/badge.svg) # ProximaX Supercontracts Rust SDK Official ProximaX Supercontracts SDK Library in Rust lang.