Declaring a hashmap (storageMap) in substrate - rust

I want to create a StorageMap in substrate and am following this example to do that. The purpose of the storage map is to have a HashMap where the key will be the account ID of the user and the value will be the count of how many times an invalid transaction has been done. For example:
Adkqwd4324dqlwdOqwdd: 2,
XCvqwd4324dqlwdOqwdd: 0,
Adkqwd4324dqlwdOqwPu: 0,
Xcvqwd4324dqlwdOqwdd: 1
My current decl_storage macro inside transaction_payment>src>lib.rs looks like this:
decl_storage! {
/// StorageMap to keep track of invalid transactions
trait Store for Module<T: Trait> as InvalidTransactionCount {
InvalidTransactionCount get(fn invalid_transaction_count): map hasher(identity) T::AccountId => u32;
}
/// already present in the substrate master code
trait Store for Module<T: Config> as TransactionPayment {
pub NextFeeMultiplier get(fn next_fee_multiplier): Multiplier = Multiplier::saturating_from_integer(1);
StorageVersion build(|_: &GenesisConfig| Releases::V2): Releases;
}
}
However, when I compile this code, I am getting errors related to NextFeeMultiplier because it is not being initialized properly due to the error in the decl_storage macro because of InvalidTransactionCount StorageMap. Full traceback of error is given below:
error: unexpected token
--> frame/transaction-payment/src/lib.rs:242:2
|
242 | trait Store for Module<T: Config> as TransactionPayment {
| ^^^^^
error[E0433]: failed to resolve: use of undeclared type `NextFeeMultiplier`
--> frame/transaction-payment/src/lib.rs:259:4
|
259 | NextFeeMultiplier::mutate(|fm| {
| ^^^^^^^^^^^^^^^^^ use of undeclared type `NextFeeMultiplier`
error[E0433]: failed to resolve: use of undeclared type `NextFeeMultiplier`
--> frame/transaction-payment/src/lib.rs:446:3
|
446 | NextFeeMultiplier::get().saturating_mul_int(Self::weight_to_fee(weight))
| ^^^^^^^^^^^^^^^^^ use of undeclared type `NextFeeMultiplier`
error[E0599]: no function or associated item named `next_fee_multiplier` found for struct `Module<T>` in the current scope
--> frame/transaction-payment/src/lib.rs:414:27
|
249 | / decl_module! {
250 | | pub struct Module<T: Config> for enum Call where origin: T::Origin {
251 | | /// The fee to be paid for making a transaction; the per-byte portion.
252 | | const TransactionByteFee: BalanceOf<T> = T::TransactionByteFee::get();
... |
304 | | }
305 | | }
| |_- function or associated item `next_fee_multiplier` not found for this
...
414 | let multiplier = Self::next_fee_multiplier();
| ^^^^^^^^^^^^^^^^^^^ function or associated item
not found in `Module<T>`
warning: unused import: `StorageMap`
--> frame/transaction-payment/src/lib.rs:46:2
|
46 | StorageMap,
| ^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error: aborting due to 4 previous errors; 1 warning emitted
Some errors have detailed explanations: E0433, E0599.
For more information about an error, try `rustc --explain E0433`.
error: could not compile `pallet-transaction-payment`
If I remove the InvalidTransactionCount trait Store from the decl_storage, then the code is being compiled fine.
Any help in identifying the correct way to declare a storage map inside the decl_storage macro will be highly appreciated. Thanks!

This line only can be written once. In the decl_module macro.
trait Store for Module<T: Config> as TransactionPayment {
If you want multi storage item just:
decl_storage! {
trait Store for Module<T: Trait> as InvalidTransactionCount {
InvalidTransactionCount get(fn invalid_transaction_count): map hasher(identity) T::AccountId => u32;
pub NextFeeMultiplier get(fn next_fee_multiplier): Multiplier = Multiplier::saturating_from_integer(1);
StorageVersion build(|_: &GenesisConfig| Releases::V2): Releases;
}
}

Related

Cannot determine return type for grpc stream

I am trying to implement a simple stream rpc using tonic and grpc. I have been following the routeguide tutorial.
When I try to return a tokio_stream::wrappers::ReceiverStream from my stream method I get compile error indicating I should return a Result wrapped by a ReceiverStream.
warning: unused manifest key: package.author
Compiling prng_generator v0.1.0 (/home/babbleshack/projects/prng_generator)
error[E0308]: mismatched types
--> src/bin/server.rs:51:46
|
51 | Ok(Response::new(ReceiverStream::new(rx)))
| ^^ expected enum `Result`, found struct `PrngResponse`
|
= note: expected struct `tokio::sync::mpsc::Receiver<Result<PrngResponse, Status>>`
found struct `tokio::sync::mpsc::Receiver<PrngResponse>`
note: return type inferred to be `tokio::sync::mpsc::Receiver<Result<PrngResponse, Status>>` here
--> src/bin/server.rs:41:67
|
41 | ) -> Result<Response<Self::PRNGServiceRequestStream>, Status> {
| ___________________________________________________________________^
42 | | let (mut tx, rx) = mpsc::channel(4);
43 | | let response_data = self.data.clone();
44 | |
... |
51 | | Ok(Response::new(ReceiverStream::new(rx)))
52 | | }
| |_____^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `prng_generator` due to previous error
When I wrap my return channel in a Result I get a contradicting error message:
error[E0308]: mismatched types
--> src/bin/server.rs:51:46
|
51 | Ok(Response::new(ReceiverStream::new(Ok(rx))))
| ^^^^^^ expected struct `tokio::sync::mpsc::Receiver`, found enum `Result`
|
= note: expected struct `tokio::sync::mpsc::Receiver<Result<PrngResponse, Status>>`
found enum `Result<tokio::sync::mpsc::Receiver<PrngResponse>, _>`
note: return type inferred to be `tokio::sync::mpsc::Receiver<Result<PrngResponse, Status>>` here
--> src/bin/server.rs:41:67
|
41 | ) -> Result<Response<Self::PRNGServiceRequestStream>, Status> {
| ___________________________________________________________________^
42 | | let (mut tx, rx) = mpsc::channel(4);
43 | | let response_data = self.data.clone();
44 | |
... |
51 | | Ok(Response::new(ReceiverStream::new(Ok(rx))))
52 | | }
| |_____^
Here is my proto:
use std::sync::Arc;
use tokio::sync::mpsc;
use tonic::{Request, Response, Status};
use tokio_stream::wrappers::ReceiverStream;
pub mod types {
tonic::include_proto!("types");
}
use types::prng_service_server::PrngService;
use types::{PrngRequest, PrngResponse};
And the implementing rust code:
use std::sync::Arc;
use tokio::sync::mpsc;
use tonic::{Request, Response, Status};
use tokio_stream::wrappers::ReceiverStream;
pub mod types {
tonic::include_proto!("types");
}
use types::prng_service_server::PrngService;
use types::{PrngRequest, PrngResponse};
#[derive(Debug, Default)]
pub struct PRNGServiceImpl{
data: Arc<Vec<PrngResponse>>,
}
#[tonic::async_trait]
impl PrngService for PRNGServiceImpl {
type PRNGServiceRequestStream = ReceiverStream<Result<PrngResponse, Status>>;
async fn prng_service_request(
&self,
request: Request<PrngRequest>,
) -> Result<Response<Self::PRNGServiceRequestStream>, Status> {
let (mut tx, rx) = mpsc::channel(256);
let response_data = self.data.clone();
tokio::spawn(async move {
for response in &response_data[..] {
Ok(tx.send(response.clone()).await.unwrap());
}
println!(" /// done sending");
});
Ok(Response::new(ReceiverStream::new(rx)))
//Ok(Response::new(ReceverStream::new(Ok(rx))))
}
}
How do I determine what my return type should be here?
The error message indicates that your return type declares a stream that produces Result<PrngResponse, Status> values, but the stream you have given it produces PrngResponse values. Your attempt to fix the solution wraps the receiver channel in a Result, which is not the same thing.
To fix this, you need to change the type that rx is inferred to be. It's inferred to be a stream of PrngResponse because of the tx.send() call, which sends a PrngResponse, so you can fix this by sending a Result instead:
tx.send(Ok(response.clone()))
The compiler points at the returned value and not the tx.send() line because the problem is the mismatch between the declared return type of the function and what it actually returns. The compiler could probably figure out that this is due to the tx.send() invocation, but in many cases type inference uses information spread out over multiple lines and there may not be one single line responsible for the inferred type of the returned value.
One way you could trace the problem to its source is to provide an explicit type somewhere matching the return type. For example:
let (mut tx, rx) = mpsc::channel::<Result<PrngResponse, Status>>(256);
This change would resolve the return type issue, and the compiler would have then pointed at the tx.send() line indicating that the sent value is not a Result.

How to compile this rust code using GATs?

I wrote the rust code using generic associated types like below:
#![feature(generic_associated_types)]
pub trait Foo {
type Arg<N: Clone>;
fn foo<N: Clone>(arg: Self::Arg<N>) {
println!("hello");
}
}
pub fn call_foo<N: Clone, F: Foo<Arg<N> = N>>() {
// I want to create this Box value here
let a = Box::new(1);
F::foo(a);
}
This code causes the following compilation error:
error[E0283]: type annotations needed
--> core/src/utils.rs:33:5
|
33 | F::foo(a);
| ^^^^^^ cannot infer type for type parameter `N` declared on the associated function `foo`
|
= note: cannot satisfy `_: Clone`
note: required by a bound in `Foo::foo`
--> core/src/utils.rs:26:15
|
26 | fn foo<N: Clone>(arg: Self::Arg<N>) {
| ^^^^^ required by this bound in `Foo::foo`
help: consider specifying the type argument in the function call
|
33 | F::foo::<N>(a);
| +++++
And when I fix the code following the help message, I got another error:
error[E0308]: mismatched types
--> core/src/utils.rs:33:17
|
31 | pub fn call_foo<N: Clone, F: Foo<Arg<N> = N>>() {
| - this type parameter
32 | let a = Box::new(1);
33 | F::foo::<N>(a);
| ----------- ^ expected type parameter `N`, found struct `Box`
| |
| arguments to this function are incorrect
|
= note: expected type parameter `N`
found struct `Box<{integer}>`
note: associated function defined here
--> core/src/utils.rs:26:8
|
26 | fn foo<N: Clone>(arg: Self::Arg<N>) {
| ^^^ -----------------
F::foo::<Box<usize>>(a) also causes the same error error[E0308]: mismatched types .
Can I compile this code?

How to use set_source_pixbuf in rust?

I have a code where i use set_source_pixbuf,
use gdk::prelude::*;
use gdk_pixbuf::{Colorspace, Pixbuf};
use gtk::prelude::*;
use std::sync::{Arc, Mutex};
use super::prelude::*;
mod control_panel;
use control_panel::setup_control_panel;
macro_rules! clone {
(#param _) => ( _ );
(#param $x:ident) => ( $x );
($($n:ident),+ => move || $body:expr) => (
{
$( let $n = $n.clone(); )+
move || $body
}
);
($($n:ident),+ => move |$($p:tt),+| $body:expr) => (
{
$( let $n = $n.clone(); )+
move |$(clone!(#param $p),)+| $body
}
);
}
pub fn process_key(controller: &Arc<Mutex<Controller>>, drawing_area: &gtk::DrawingArea, key: u16) {
{
let mut contr = controller.lock().unwrap();
contr.process_key(key);
}
drawing_area.queue_draw();
}
pub fn build_ui(app: &gtk::Application) {
let window = gtk::ApplicationWindow::new(app);
window.set_title("Muscle");
let glade_src = "config/control_window.glade";
let builder = gtk::Builder::from_file(glade_src);
let control_window: gtk::Window = builder.get_object("window").expect("Couldn't get window");
control_window.set_application(Some(app));
control_window.set_title("Control panel");
let fixed = gtk::Fixed::new();
let drawing_area = gtk::DrawingArea::new();
fixed.add(&drawing_area);
window.add(&fixed);
drawing_area.set_size_request(constants::WIDTH as i32, constants::HEIGHT as i32);
let Config {
muscle_config: mconf,
carcass_config: cconf,
} = read_from_config();
let muscle = Arc::new(Mutex::new(Muscle::new(
mconf.radiuses,
mconf.grow_mults,
mconf.len,
)));
let carcass = Arc::new(Mutex::new(Carcass::new(
cconf.data,
cconf.thickness,
mconf.len,
)));
let pixbuf = Pixbuf::new(
Colorspace::Rgb,
constants::HAS_ALPHA,
constants::BITS_PER_COLOR,
constants::WIDTH as i32,
constants::HEIGHT as i32,
)
.unwrap();
let mut controller = Controller::new(pixbuf.clone(), muscle, carcass);
controller.update_pixbuf();
let controller = Arc::new(Mutex::new(controller));
drawing_area.connect_draw(clone!(pixbuf => move |_, context| {
context.set_source_pixbuf(&pixbuf, 0_f64, 0_f64);
context.paint();
Inhibit(false)
}));
window.connect_key_press_event(clone!(controller, drawing_area => move |_, key| {
process_key(&controller, &drawing_area, key.get_hardware_keycode());
Inhibit(false)
}));
window.show_all();
setup_control_panel(&builder, &controller, &drawing_area);
control_window.show_all();
}
when i try to build this module it gives me an error:
better0fdead#better0fdead-To-be-filled-by-O-E-M:~/Downloads/bmstu-cg-course$ cargo run --release
warning: the cargo feature `edition2021` has been stabilized in the 1.56 release and is no longer necessary to be listed in the manifest
See https://doc.rust-lang.org/nightly/cargo/reference/manifest.html#the-edition-field for more information about using this feature.
Compiling course_g v0.1.0 (/home/better0fdead/Downloads/bmstu-cg-course)
error[E0599]: no method named `set_source_pixbuf` found for reference `&cairo::context::Context` in the current scope
--> src/lib/ui.rs:80:17
|
80 | context.set_source_pixbuf(&pixbuf, 0_f64, 0_f64);
| ^^^^^^^^^^^^^^^^^
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use gdk::cairo_interaction::GdkContextExt;
|
help: there is an associated function with a similar name
|
80 | context.set_source_rgb(&pixbuf, 0_f64, 0_f64);
| ~~~~~~~~~~~~~~
warning: unused import: `gdk::prelude`
--> src/lib/ui.rs:1:5
|
1 | use gdk::prelude::*;
| ^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
For more information about this error, try `rustc --explain E0599`.
warning: `course_g` (bin "course_g") generated 1 warning
error: could not compile `course_g` due to previous error; 1 warning emitted
i tried adding command : use gdk::cairo_interaction::GdkContextExt; to the file , which does not help me.
better0fdead#better0fdead-To-be-filled-by-O-E-M:~/Downloads/bmstu-cg-course$ cargo run --release
warning: the cargo feature `edition2021` has been stabilized in the 1.56 release and is no longer necessary to be listed in the manifest
See https://doc.rust-lang.org/nightly/cargo/reference/manifest.html#the-edition-field for more information about using this feature.
Compiling course_g v0.1.0 (/home/better0fdead/Downloads/bmstu-cg-course)
error[E0603]: module `cairo_interaction` is private
--> src/lib/ui.rs:5:10
|
5 | use gdk::cairo_interaction::GdkContextExt;
| ^^^^^^^^^^^^^^^^^ private module
|
note: the module `cairo_interaction` is defined here
--> /home/better0fdead/.cargo/registry/src/github.com-1ecc6299db9ec823/gdk-0.15.2/src/lib.rs:31:1
|
31 | mod cairo_interaction;
| ^^^^^^^^^^^^^^^^^^^^^^
error[E0599]: no method named `set_source_pixbuf` found for reference `&cairo::context::Context` in the current scope
--> src/lib/ui.rs:81:17
|
81 | context.set_source_pixbuf(&pixbuf, 0_f64, 0_f64);
| ^^^^^^^^^^^^^^^^^
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use gdk::cairo_interaction::GdkContextExt;
|
help: there is an associated function with a similar name
|
81 | context.set_source_rgb(&pixbuf, 0_f64, 0_f64);
| ~~~~~~~~~~~~~~
warning: unused import: `gdk::prelude`
--> src/lib/ui.rs:1:5
|
1 | use gdk::prelude::*;
| ^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
Some errors have detailed explanations: E0599, E0603.
For more information about an error, try `rustc --explain E0599`.
warning: `course_g` (bin "course_g") generated 1 warning
error: could not compile `course_g` due to 2 previous errors; 1 warning emitted
use gdk::prelude::GdkContextExt;
does not work aswell
better0fdead#better0fdead-To-be-filled-by-O-E-M:~/Downloads/bmstu-cg-course$ cargo run --release
warning: the cargo feature `edition2021` has been stabilized in the 1.56 release and is no longer necessary to be listed in the manifest
See https://doc.rust-lang.org/nightly/cargo/reference/manifest.html#the-edition-field for more information about using this feature.
Compiling course_g v0.1.0 (/home/better0fdead/Downloads/bmstu-cg-course)
error[E0599]: no method named `set_source_pixbuf` found for reference `&cairo::context::Context` in the current scope
--> src/lib/ui.rs:80:17
|
80 | context.set_source_pixbuf(&pixbuf, 0_f64, 0_f64);
| ^^^^^^^^^^^^^^^^^
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use gdk::cairo_interaction::GdkContextExt;
|
help: there is an associated function with a similar name
|
80 | context.set_source_rgb(&pixbuf, 0_f64, 0_f64);
| ~~~~~~~~~~~~~~
warning: unused import: `gdk::prelude`
--> src/lib/ui.rs:1:5
|
1 | use gdk::prelude::*;
| ^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: unused import: `gdk::prelude::GdkContextExt`
--> src/lib/ui.rs:5:5
|
5 | use gdk::prelude::GdkContextExt;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
For more information about this error, try `rustc --explain E0599`.
warning: `course_g` (bin "course_g") generated 2 warnings
error: could not compile `course_g` due to previous error; 2 warnings emitted
As the error message says, gdt::cairo_interaction is a private module, so we can't use it.
The documentation says GdkContentExt is exposed in the gdk::prelude module. So importing it from the module solves the problem.
use gdk::prelude::GdkContentExt;

How to fix the trait `parity_scale_codec::codec::WrapperTypeEncode` is not implemented for `Hash`

I am trying to define Substrate runtime-api. I am using substrate master branch for dependencies.
Here is code
#![cfg_attr(not(feature = "std"), no_std)]
use codec::Codec;
use codec::{Encode, Decode};
sp_api::decl_runtime_apis! {
/// The API to verify barcode
pub trait BarcodeScannerApi<Hash> where
Hash: Codec, {
/// Verify barcode
fn is_valid_barcode(barcode: Hash) -> bool;
}
}
While building code, I am getting below error:
error[E0277]: the trait bound `Hash: parity_scale_codec::codec::WrapperTypeEncode` is not satisfied
--> pallets/barcode-scanner/runtime-api/src/lib.rs:6:1
|
6 | / sp_api::decl_runtime_apis! {
7 | | /// The API to verify barcode
8 | | pub trait BarcodeScannerApi<Hash> where
9 | | Hash: Codec, {
... |
12 | | }
13 | | }
| |_^ the trait `parity_scale_codec::codec::WrapperTypeEncode` is not implemented for `Hash`
|
= note: required because of the requirements on the impl of `sp_api::Encode` for `Hash`
= note: required because of the requirements on the impl of `sp_api::Encode` for `&Hash`
= note: required by `sp_api::Encode::encode`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider further restricting this bound
|
9 | Hash: Codec + parity_scale_codec::codec::WrapperTypeEncode, {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Please help me to fix this.

How to call a `dyn Fn` which is a field?

struct DummyRtspClient<'a> {
on_produce: &'a dyn Fn(EncodedPacket)
}
impl ... for DummyRtspClient {
fn set_on_produce(&self, f: &'a dyn Fn(EncodedPacket)){
self.on_produce = f;
}
}
Then how can I use on_produce?
I tried
let encoded_packet = EncodedPacket{
data: Vec::new(),
};
self.on_produce(encoded_packet);
but it says that on_produce is not a member function, but a field.
I tried self.on_produce.call(encoded_packet) but I also get errors.
Your error message should say something like this:
error[E0599]: no method named `on_produce` found for reference `&DummyRtspClient<'a>` in the current scope
--> src/lib.rs:14:18
|
14 | self.on_produce(encoded_packet);
| ^^^^^^^^^^ field, not a method
|
help: to call the function stored in `on_produce`, surround the field access with parentheses
|
14 | (self.on_produce)(encoded_packet);
| ^ ^
In particular, the second part tells exactly you how to solve this: wrap self.on_produce in a set of parentheses to disambiguate it from attempting to call a member function.

Resources