Skip to content

Commit

Permalink
Merge branch 'master' into as-wasm-builder-meta-location
Browse files Browse the repository at this point in the history
  • Loading branch information
shamilsan committed Jul 24, 2023
2 parents cfb272b + 86295f6 commit 6fe25a4
Show file tree
Hide file tree
Showing 13 changed files with 70 additions and 60 deletions.
18 changes: 9 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ base64 = "0.21.0"
blake2-rfc = { version = "0.2.18", default-features = false }
bs58 = { version = "0.4.0", default-features = false }
clap = { version = "4.2.1" }
codec = { package = "parity-scale-codec", version = "3.4.0", default-features = false }
codec = { package = "parity-scale-codec", version = "3.6.4", default-features = false }
color-eyre = "0.6.2"
colored = "2.0.0"
const-str = "0.5"
Expand All @@ -136,7 +136,7 @@ lazy_static = "1.4.0"
libc = { version = "0.2", default-features = false }
log = { version = "0.4.17", default-features = false }
once_cell = "1.17.1"
parity-scale-codec = { version = "3.6.1", default-features = false }
parity-scale-codec = { version = "3.6.4", default-features = false }
parity-wasm = "0.45.0"
parking_lot = "0.12.1"
path-clean = "1.0.1"
Expand Down
11 changes: 1 addition & 10 deletions common/src/gas_provider/lockable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use super::{scheduler::StorageType, *};
use enum_iterator::Sequence;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Sequence)]
#[repr(u8)]
pub enum LockId {
Mailbox,
Waitlist,
Reservation,
DispatchStash,
}
pub use gear_core::gas::LockId;

/// An error indicating there is no corresponding enum variant to the one provided
#[derive(Debug)]
Expand Down
1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ hex = { workspace = true, features = ["alloc"] }
hashbrown.workspace = true
static_assertions.workspace = true
paste = { workspace = true }
enum-iterator.workspace = true

[dev-dependencies]
wabt.workspace = true
Expand Down
15 changes: 15 additions & 0 deletions core/src/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,23 @@
//! Gas module.

use crate::costs::RuntimeCosts;
use enum_iterator::Sequence;
use scale_info::scale::{Decode, Encode};

/// The id of the gas lock.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Sequence)]
#[repr(u8)]
pub enum LockId {
/// The gas lock is provided by the mailbox.
Mailbox,
/// The gas lock is provided by the waitlist.
Waitlist,
/// The gas lock is provided by reservation.
Reservation,
/// The gas lock is provided by dispatch stash.
DispatchStash,
}

/// This trait represents a token that can be used for charging `GasCounter`.
///
/// Implementing type is expected to be super lightweight hence `Copy` (`Clone` is added
Expand Down
33 changes: 17 additions & 16 deletions examples/fungible-token/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,42 +54,44 @@ impl FungibleToken {
}

fn mint(&mut self, amount: u128) {
let source = msg::source();
self.balances
.entry(msg::source())
.entry(source)
.and_modify(|balance| *balance += amount)
.or_insert(amount);
self.total_supply += amount;
msg::reply(
FTEvent::Transfer {
from: ZERO_ID,
to: msg::source(),
to: source,
amount,
},
0,
)
.unwrap();
}

/// Executed on receiving `fungible-token-messages::BurnInput`.
fn burn(&mut self, amount: u128) {
if self.balances.get(&msg::source()).unwrap_or(&0) < &amount {
let source = msg::source();
if self.balances.get(&source).unwrap_or(&0) < &amount {
panic!("Amount exceeds account balance");
}
self.balances
.entry(msg::source())
.entry(source)
.and_modify(|balance| *balance -= amount);
self.total_supply -= amount;

msg::reply(
FTEvent::Transfer {
from: msg::source(),
from: source,
to: ZERO_ID,
amount,
},
0,
)
.unwrap();
}

/// Executed on receiving `fungible-token-messages::TransferInput` or `fungible-token-messages::TransferFromInput`.
/// Transfers `amount` tokens from `sender` account to `recipient` account.
fn transfer(&mut self, from: &ActorId, to: &ActorId, amount: u128) {
if from == &ZERO_ID || to == &ZERO_ID {
Expand Down Expand Up @@ -119,17 +121,19 @@ impl FungibleToken {
.unwrap();
}

/// Executed on receiving `fungible-token-messages::ApproveInput`.
fn approve(&mut self, to: &ActorId, amount: u128) {
if to == &ZERO_ID {
panic!("Approve to zero address");
}
let source = msg::source();
self.allowances
.entry(msg::source())
.entry(source)
.or_default()
.insert(*to, amount);
msg::reply(
FTEvent::Approve {
from: msg::source(),
from: source,
to: *to,
amount,
},
Expand All @@ -139,17 +143,14 @@ impl FungibleToken {
}

fn can_transfer(&mut self, from: &ActorId, amount: u128) -> bool {
if from == &msg::source() || self.balances.get(&msg::source()).unwrap_or(&0) >= &amount {
let source = msg::source();
if from == &source || self.balances.get(&source).unwrap_or(&0) >= &amount {
return true;
}
if let Some(allowed_amount) = self
.allowances
.get(from)
.and_then(|m| m.get(&msg::source()))
{
if let Some(allowed_amount) = self.allowances.get(from).and_then(|m| m.get(&source)) {
if allowed_amount >= &amount {
self.allowances.entry(*from).and_modify(|m| {
m.entry(msg::source()).and_modify(|a| *a -= amount);
m.entry(source).and_modify(|a| *a -= amount);
});
return true;
}
Expand Down
6 changes: 3 additions & 3 deletions examples/fungible-token/tests/benchmarks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ use ft_io::*;
use gclient::{EventProcessor, GearApi, Result};
use gear_core::ids::{MessageId, ProgramId};
use gstd::{vec, ActorId, Encode, Vec};
use rand::Rng;
use rand::{rngs::StdRng, Rng, SeedableRng};
use statrs::statistics::Statistics;

/// Path to the gear node binary.
const GEAR_PATH: &str = "../../../target/release/gear";
const GEAR_PATH: &str = "../../target/release/gear";

/// This constant defines the number of messages in the batch.
/// It is calculated empirically, and 25 is considered the optimal value for
Expand Down Expand Up @@ -206,7 +206,7 @@ async fn stress_test() -> Result<()> {
#[ignore]
#[tokio::test]
async fn stress_transfer() -> Result<()> {
let mut rng = rand::thread_rng();
let mut rng = StdRng::seed_from_u64(42);

let api = GearApi::dev_from_path(GEAR_PATH).await?;
// Use this code in comment for custom node run:
Expand Down
1 change: 0 additions & 1 deletion gclient/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ gear-utils.workspace = true
gsdk = { workspace = true, features = ["testing"] }
gear-core.workspace = true
gear-core-errors.workspace = true
gear-common = { workspace = true, features = ["std"] }

futures.workspace = true
anyhow.workspace = true
Expand Down
2 changes: 1 addition & 1 deletion gclient/src/api/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@

use super::{GearApi, Result};
use crate::{api::storage::account_id::IntoAccountId32, utils, Error};
use gear_common::LockId;
use gear_core::{
gas::LockId,
ids::*,
memory::PageBuf,
pages::{GearPage, PageNumber, PageU32Size, GEAR_PAGE_SIZE, WASM_PAGE_SIZE},
Expand Down
12 changes: 6 additions & 6 deletions gsdk/src/signer/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,16 +343,16 @@ impl Signer {
b.block_hash(),
b.extrinsic_hash()
),
TxStatus::Retracted(h) => log::info!(" Status: Retracted( {h} )"),
TxStatus::FinalityTimeout(h) => log::info!(" Status: FinalityTimeout( {h} )"),
TxStatus::Retracted(h) => log::warn!(" Status: Retracted( {h} )"),
TxStatus::FinalityTimeout(h) => log::error!(" Status: FinalityTimeout( {h} )"),
TxStatus::Finalized(b) => log::info!(
" Status: Finalized( block hash: {}, extrinsic hash: {} )",
b.block_hash(),
b.extrinsic_hash()
),
TxStatus::Usurped(h) => log::info!(" Status: Usurped( {h} )"),
TxStatus::Dropped => log::info!(" Status: Dropped"),
TxStatus::Invalid => log::info!(" Status: Invalid"),
TxStatus::Usurped(h) => log::error!(" Status: Usurped( {h} )"),
TxStatus::Dropped => log::error!(" Status: Dropped"),
TxStatus::Invalid => log::error!(" Status: Invalid"),
}
}

Expand Down Expand Up @@ -389,7 +389,7 @@ impl Signer {
let status = status?;
self.log_status(&status);
match status {
Future | Ready | Broadcast(_) | InBlock(_) => (),
Future | Ready | Broadcast(_) | InBlock(_) | Retracted(_) => (),
Finalized(b) => {
log::info!(
"Successfully submitted call {}::{} {} at {}!",
Expand Down
15 changes: 7 additions & 8 deletions gsdk/src/signer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,15 @@ impl Signer {
}

/// Change inner signer.
pub fn change(self, suri: &str, passwd: Option<&str>) -> Result<Self> {
Ok(Self {
api: self.api,
signer: PairSigner::new(
Pair::from_string(suri, passwd).map_err(|_| Error::InvalidSecret)?,
),
nonce: None,
})
pub fn change(mut self, suri: &str, passwd: Option<&str>) -> Result<Self> {
let signer =
PairSigner::new(Pair::from_string(suri, passwd).map_err(|_| Error::InvalidSecret)?);
self.signer = signer;

Ok(self)
}

/// Set nonce of the signer
pub fn set_nonce(&mut self, nonce: u32) {
self.nonce = Some(nonce)
}
Expand Down
1 change: 1 addition & 0 deletions utils/wasm-builder/src/optimize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ pub fn do_optimization(
"z" => OptimizationOptions::new_optimize_for_size_aggressively(),
_ => panic!("Invalid optimization level {}", optimization_level),
}
.shrink_level(wasm_opt::ShrinkLevel::Level2)
.add_pass(Pass::Dae)
.add_pass(Pass::Vacuum)
// the memory in our module is imported, `wasm-opt` needs to be told that
Expand Down
11 changes: 7 additions & 4 deletions utils/wasm-builder/src/wasm_project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ use std::{
};
use toml::value::Table;

const OPT_LEVEL: &str = "z";

/// Enum defining type of binary compiling: production program or metawasm.
pub enum ProjectType {
Program(Option<MetadataRepr>),
Expand Down Expand Up @@ -158,11 +160,12 @@ impl WasmProject {
lib.insert("crate-type".into(), vec!["cdylib".to_string()].into());

let mut dev_profile = Table::new();
dev_profile.insert("opt-level".into(), "s".into());
dev_profile.insert("opt-level".into(), OPT_LEVEL.into());

let mut release_profile = Table::new();
release_profile.insert("lto".into(), true.into());
release_profile.insert("opt-level".into(), "s".into());
release_profile.insert("lto".into(), "fat".into());
release_profile.insert("opt-level".into(), OPT_LEVEL.into());
release_profile.insert("codegen-units".into(), 1.into());

let mut production_profile = Table::new();
production_profile.insert("inherits".into(), "release".into());
Expand Down Expand Up @@ -318,7 +321,7 @@ extern "C" fn metahash() {{
let path = optimize::optimize_wasm(
original_copy_wasm_path.clone(),
opt_wasm_path.clone(),
"s",
"4",
true,
)
.map(|res| {
Expand Down

0 comments on commit 6fe25a4

Please sign in to comment.