I am working with a course on coatings with the Solana Spotify Project and studying on YouTube. Please tell me the code produces such errors, but everything is written correctly and clearly. I don't know where I forgot.
use anchor_lang::prelude::*;
use anchor_lang::solana_program::entrypoint::ProgramResult;
use anchor_spl::token::{self,Token};
use std::mem::size_of;
// This is your program's public key and it will update
// automatically when you build the project.
declare_id!("11111111111111111111111111111111");
#[program]
mod spotify_clone {
use super::*;
pub fn accept_payment(ctx: Context<PayerContext>, data: u64) -> ProgramResult {
let payer_wallet = &mut ctx.accounts.payer_wallet;
payer_wallet.wallet = ctx.accounts.authority.key();
let ix = anchor_lang::solana_program::system_instruction::transfer(
&ctx.accounts.authority.key(),
&ctx.accounts.receiver.key(),
100000000,
);
anchor_lang::solana_program::program::invoke(
&ix,
&[
ctx.accounts.authority.to_account_info(),
ctx.accounts.receiver.to_account_info(),
],
)
}
}
#[derive(Accounts)]
pub struct PayerContext<'info> {
#[account(
init,
seeds = [b"payer".as_ref(), authority.key().as_ref()],
bump,
payer = authority,
space = size_of::<PayerAccount>() + 8,
)]
pub payer_wallet: Account<'info, PayerAccount>,
//Specific param to object
#[account(mut)]
pub receiver: AccountInfo<'info>,
//Specific param to object
//Authority[this is signer who paid transaction fee]
#[account(mut)]
pub authority: Signer<'info>,
pub system_programm: UncheckedAccount <'info>,
//Token Programm
#[account(constraint = token_program.key == &token::ID)]
pub token_program: Program<'info, Token>,
//Clock to the Save Your Time
pub clock: Sysvar<'info,Clock>,
}
#[account]
pub struct PayerAccount{
pub wallet: Pubkey,
}
Error appears here. The main problem in the code i think is here:
pub payer_wallet: Account<'info, PayerAccount>,
Code of error E0277:
error[E0277]: the trait bound `PayerContext<'_>: anchor_lang::Accounts<'_>` is not satisfied
--> /src/lib.rs:10:1
|
10 | #[program]
| ^^^^^^^^^^ the trait `anchor_lang::Accounts<'_>` is not implemented for `PayerContext<'_>`
|
note: required by `anchor_lang::context::Context::<'a, 'b, 'c, 'info, T>::new`
Second error E0432:
error[E0432]: unresolved import `crate`
--> /src/lib.rs:10:1
|
10 | #[program]
| ^^^^^^^^^^ could not find `__client_accounts_payer_context` in the crate root
|
= note: this error originates in the attribute macro `program` (in Nightly builds, run with -Z macro-backtrace for more info)
Third error E0599:
error[E0599]: no method named `exit` found for struct `PayerContext` in the current scope
--> /src/lib.rs:10:1
|
10 | #[program]
| ^^^^^^^^^^ method not found in `PayerContext<'_>`
...
34 | pub struct PayerContext<'info> {
| ------------------------------ method `exit` not found for this
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `exit`, perhaps you need to implement it:
candidate #1: `anchor_lang::AccountsExit`
= note: this error originates in the attribute macro `program` (in Nightly builds, run with -Z macro-backtrace for more info)
Try adding
#[derive(Accounts)] to PayerContext
Like this
#[derive(Accounts)]
pub struct PayerContext<'info> {}
Related
I am relatively new to rust and have really enjoyed playing around with it. However I am stuck on an error for my CRUD application using Diesel and Rocket. I have a main.rs, model.rs and schema.rs.
I get an error with my POST method that uses the User struct i created.
I am using a postgres DB i have running in the background on docker, Diesel and rocket for routing.
My models.rs
use super::schema::users;
use diesel::{prelude::*, table, Queryable, Insertable, RunQueryDsl};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Queryable, Debug, Insertable)]
#[table_name= "users"]
pub struct User {
pub id: i32,
pub first_name: String,
pub last_name: String,
pub user_name: String,
pub email_address: String,
}
My main.rs (included everything for detail but really question is about the Post method - create_user
#[macro_use] extern crate rocket;
mod models;
mod schema;
use rocket_sync_db_pools::{database};
use models::{User};
use rocket::{serde::json::Json};
use diesel::{RunQueryDsl};
use schema::users;
#[database("my_db")]
pub struct Db(rocket_sync_db_pools::diesel::PgConnection);
#[get("/")]
fn index() -> &'static str {
"Hello World"
}
#[get("/<id>")]
fn get_user(id: i32) -> Json<User> {
Json(User {
id: id,
first_name: "A Fist Name".to_string(),
last_name: "A Last Name".to_string(),
user_name: "A User Name".to_string(),
email_address: "AnEmail#email.com".to_string(),
})
}
#[post("/", data = "<user>")]
async fn create_user(connection: Db, user: Json<User>) -> Json<User> {
connection.run(move |c| {
diesel::insert_into(users::table)
.values(&user.into_inner())
.get_result(c)
})
.await
.map(Json)
.expect("There was an error saving the user")
}
#[launch]
fn rocket() -> _ {
let rocket = rocket::build();
rocket
.attach(Db::fairing())
.mount("/", routes![index])
.mount("/users", routes![get_user, create_user])
}
Dependencies from Cargo.toml
[dependencies]
diesel = "2.0.2"
diesel_cli = { version = "1.4.1", default-features = false, features = ["postgres"] }
rocket = { version = "0.5.0-rc.2", features = ["json"] }
rocket_sync_db_pools = { version = "0.1.0-rc.2", features = ["diesel_postgres_pool"] }
serde = "1.0.140"
The error message
--> src/main.rs:66:6
|
66 | .get_result(c)
| ^^^^^^^^^^
|
= help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`with_auth_rust_rocket_diesel_binary`)
= note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<_>` for `DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>`
= note: 123 redundant requirements hidden
= note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<_>` for `DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>`
= note: required because of the requirements on the impl of `diesel::insertable::InsertValues<table, _>` for `DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>`
= note: 3 redundant requirements hidden
= note: required because of the requirements on the impl of `diesel::query_builder::QueryFragment<_>` for `diesel::query_builder::InsertStatement<table, diesel::query_builder::insert_statement::ValuesClause<(DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::first_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::last_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::user_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::email_address, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>), table>, diesel::query_builder::insert_statement::private::Insert, diesel::query_builder::returning_clause::ReturningClause<(columns::id, columns::first_name, columns::last_name, columns::user_name, columns::email_address)>>`
= note: required because of the requirements on the impl of `diesel::query_dsl::LoadQuery<'_, _, _>` for `diesel::query_builder::InsertStatement<table, diesel::query_builder::insert_statement::ValuesClause<(DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::id, diesel::expression::bound::Bound<diesel::sql_types::Integer, &i32>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::first_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::last_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::user_name, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>, DefaultableColumnInsertValue<diesel::insertable::ColumnInsertValue<columns::email_address, diesel::expression::bound::Bound<diesel::sql_types::Text, &std::string::String>>>), table>>`
note: required by a bound in `diesel::RunQueryDsl::get_result`
--> /Users/me/.cargo/registry/src/github.com-1ecc6299db9ec823/diesel-2.0.2/src/query_dsl/mod.rs:1679:15
|
1679 | Self: LoadQuery<'query, Conn, U>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `diesel::RunQueryDsl::get_result`
I have reviewed both Diesel, Rocket and Rust documentation and worked worked through other examples for what I can find online however still do not quite get what i am doing incorrectly. Thanks in advance for any help.
I tried to create a post method that uses Diesel to take a Json version of my User object and insert it into my database.
This is a mismatch between the diesel version used by your project (2.0.2) and the diesel version provided by rocket_sync_db_pools (1.4.8). This means the c in connection.run(move |c| { is just a completely different type than expected by get_result, even if the types share the same name.
I am using rust diesel diesel = { version = "1.4.8", features = ["postgres","64-column-tables","chrono","serde_json"] } to do the group by query follow the docs like this:
fpub fn get_bill_book_account_sum(){
use crate::diesel::GroupByDsl;
use diesel::dsl::max;
use crate::model::diesel::dict::dict_schema::test as bill_record_table;
let source_query = bill_record_table::table
.group_by(bill_record_table::id)
.select((max(bill_record_table::tags),bill_record_table::id))
.filter(bill_record_table::dsl::tags.eq(9));
}
then compile this code, shows error like this:
error[E0277]: the trait bound `aggregate_ordering::max::max<BigInt, columns::tags>: NonAggregate` is not satisfied
--> src/main.rs:19:17
|
19 | .select((max(bill_record_table::tags),bill_record_table::id))
| ------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `NonAggregate` is not implemented for `aggregate_ordering::max::max<BigInt, columns::tags>`
| |
| required by a bound introduced by this call
|
= note: required because of the requirements on the impl of `diesel::Expression` for `(aggregate_ordering::max::max<BigInt, columns::tags>, columns::id)`
note: required by a bound in `diesel::QueryDsl::select`
--> /Users/xiaoqiangjiang/.cargo/registry/src/mirrors.tuna.tsinghua.edu.cn-df7c3c540f42cdbd/diesel-1.4.8/src/query_dsl/mod.rs:291:20
|
291 | Selection: Expression,
| ^^^^^^^^^^ required by this bound in `diesel::QueryDsl::select`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `rust-learn` due to previous error
where am I doing wrong? what should I do to fixed this problem? this is the schema define(I have removed all the columns just using 2 columns to make a minimal reproduce example):
table! {
test (id) {
id -> Int8,
tags -> Int8,
}
}
and this is the model define:
// Generated by diesel_ext
#![allow(unused)]
#![allow(clippy::all)]
use std::io::Write;
use diesel::deserialize::FromSql;
use diesel::pg::Pg;
use diesel::serialize::{Output, ToSql};
use diesel::sql_types::Jsonb;
use rocket::serde::Serialize;
use serde::Deserialize;
use crate::model::diesel::dict::dict_schema::*;
#[derive(Queryable,Debug,Serialize,Deserialize,Default)]
pub struct Test {
pub id: i64,
pub tags: i64,
}
this is the minimal main.rs entrypoint:
#[macro_use]
extern crate diesel;
mod model;
use diesel::{ ExpressionMethods, QueryDsl};
fn main() {
get_bill_book_account_sum();
}
pub fn get_bill_book_account_sum(){
use crate::diesel::GroupByDsl;
use diesel::dsl::max;
use crate::model::diesel::dict::dict_schema::test as bill_record_table;
let source_query = bill_record_table::table
.group_by(bill_record_table::id)
.select((max(bill_record_table::tags),bill_record_table::id))
.filter(bill_record_table::dsl::tags.eq(9));
}
change the aggregate query like this fixed this problem:
pub fn get_bill_book_account_sum(request: &BillAccountRequest) -> Result<Vec<(i64, i32)>, diesel::result::Error>{
use crate::diesel::GroupByDsl;
use crate::model::diesel::fortune::fortune_schema::bill_record as bill_record_table;
let source_query = bill_record_table::table
.group_by(bill_record_table::account_id)
.select((diesel::dsl::sql::<diesel::sql_types::BigInt>("SUM(CAST(amount AS Integer))"),bill_record_table::account_id))
.filter(bill_record_table::dsl::bill_book_id.eq(request.bill_book_id));
let result = source_query.load::<(i64,i32)>(&get_connection());
return result;
}
the solution come from this issue. This is the answer come from the maintainer that shows diesel 1.x did not support group by official.
I'm working on a pallet and after switching to the newest node template it stopped building. Here is declaration
#[derive(Encode, Decode, Clone)]
pub struct VendorData<T :Config>
{
pub vendor : VendorId,
pub owner_account_id : T::AccountId,
}
impl<T:Config> Default for VendorData<T> {
fn default() -> Self {
Self {
vendor : Default::default(),
owner_account_id : Default::default(),
}
}
}
#[pallet::storage]
pub(super) type Vendors<T: Config> = StorageMap<_, Blake2_128Concat, VendorId, VendorData<T>, ValueQuery>;
The cargo build error:
error[E0277]: the trait bound `VendorData<T>: TypeInfo` is not satisfied
...
#[pallet::storage]
^^^^^^^ the trait `TypeInfo` is not implemented for `VendorData<T>`
I've tried declaring struct in a different ways, for example by adding TypeInfo:
#[derive(Encode, Decode, Default, Eq, PartialEq, TypeInfo)]
but every time another errors arise, like this:
error: cannot find macro `format` in this scope
--> /home/psu/.cargo/git/checkouts/substrate-7e08433d4c370a21/352c46a/primitives/consensus/aura/src/lib.rs:50:3
|
50 | app_crypto!(ed25519, AURA);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: consider importing this macro:
scale_info::prelude::format
= note: this error originates in the macro `$crate::app_crypto_public_common_if_std` (in Nightly builds, run with -Z macro-backtrace for more info)
There is another storage item which does not cause errors
pub type Cid = Vec<u8>;
#[pallet::storage]
pub(super) type VendorModels<T: Config> = StorageMap<_, Blake2_128Concat, VendorId, Vec<Cid>, ValueQuery>;
So it seems it's only about storing VendorData struct. Please assist, after hours of experiments and googling I'm lost
UPDATE: after adding TypeInfo to all storage structs declaration the pallet is compiled but a lot of errors like below arised:
error: cannot find macro `format` in this scope
error: cannot find macro `vec` in this scope
You will need to either make sure that all your generic types implement TypeInfo or skip the types explicitly.
Based on this example code in Substrate you could write:
#[derive(Encode, Decode, Clone, TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct VendorData<T :Config>
{
pub vendor : VendorId,
pub owner_account_id : T::AccountId,
}
Or alternatively the following should work:
#[derive(Encode, Decode, Clone, TypeInfo)]
pub struct VendorData<AccountId>
{
pub vendor : VendorId,
pub owner_account_id : AccountId,
}
I'm building a wrapper around a DLL. This DLL gives me access to a database engine which implements an OOP design pattern. This requires me to create multiple overlapping traits that cover all the functionality:
pub trait CursorStatement { /* ... */ }
pub trait CursorTable { /* ... */ }
pub trait CursorStatementTable { /* ... */ }
...
I want to be able to bring these traits in scope so that I can call the functions without having to list every trait. Right now I'm doing:
mod traittest;
use traittest::*;
fn test() -> Result<(), AceError> {
let t = traittest::Table::new(3, "ORDERS")?;
let c = traittest::Cursor { handle: 42 };
println!("t.fields={}", t.fields());
println!("c.fields={}", c.fields());
Ok(())
}
fn main() {
test().expect("success");
}
The problem with use foo::* is that it puts everything from the module into my namespace, which I don't want.
In the example above, I don't have to type traittest::Table or traittest::Cursor, I just have to type Table or Cursor. However, I want to have to prefix those objects with the module name so when I'm reading the code I know where the objects came from. I might want to create a Table object in my local file that is distinguished from the one coming from the module.
I also don't want to have to do the following because if I later have to add a new trait I will have to update a bunch of other source files that depend on this module:
mod traittest;
use traittest::{CursorStatement, CursorStatementTable, CursorTable, /* ... */};
I tried creating a Traits supertrait that would inherit all other traits as shown in Is there any way to create a type alias for multiple traits?, but it doesn't work because I can't implement the trait for anything because there's nothing that would be an implementation of every trait in the file:
pub trait Traits: CursorStatement, CursorTable, CursorStatementHandle, /* ... */ {}
If I could create a named scope for all the traits, that would work, but I can't figure out how to make Rust happy with this idea:
let traits = {
pub trait CursorTable { /* ... */ }
}
It looks like this trait_group macro might do the trick but it's not obvious to me how I could use it to solve my problem.
Here's my entire program
mod traittest {
#[derive(Debug)]
pub struct AceError {
code: u32,
description: String,
}
pub trait CursorTable {
fn get_handle(&self) -> u32; // impl's must write this function
fn fields(&self) -> String {
return format!("(get_handle() -> {})", self.get_handle());
}
}
pub struct Table {
pub handle: u32,
pub table_name: String,
}
pub struct Cursor {
pub handle: u32,
}
impl Table {
pub fn new(handle: u32, table_name: &str) -> Result<Table, AceError> {
let table = Table {
handle: handle,
table_name: table_name.to_string(),
};
return Ok(table);
}
}
impl CursorTable for Table {
fn get_handle(&self) -> u32 {
return self.handle;
}
}
impl CursorTable for Cursor {
fn get_handle(&self) -> u32 {
return self.handle;
}
}
pub trait Traits: CursorTable {} /* super trait to bring all other traits in scope */
}
use traittest::Traits;
fn test() -> Result<(), traittest::AceError> {
let t = traittest::Table::new(3, "ORDERS")?;
let c = traittest::Cursor { handle: 42 };
println!("t.fields={}", t.fields());
println!("c.fields={}", c.fields());
Ok(())
}
fn main() {
test().expect("success");
}
and here's the error I get:
warning: unused import: `traittest::Traits`
--> src/main.rs:49:5
|
49 | use traittest::Traits;
| ^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error[E0599]: no method named `fields` found for struct `traittest::Table` in the current scope
--> src/main.rs:54:31
|
10 | fn fields(&self) -> String {
| ------
| |
| the method is available for `std::boxed::Box<traittest::Table>` here
| the method is available for `std::sync::Arc<traittest::Table>` here
| the method is available for `std::rc::Rc<traittest::Table>` here
...
15 | pub struct Table {
| ---------------- method `fields` not found for this
...
54 | println!("t.fields={}", t.fields());
| ^^^^^^ method not found in `traittest::Table`
|
= 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:
|
49 | use crate::traittest::CursorTable;
|
error[E0599]: no method named `fields` found for struct `traittest::Cursor` in the current scope
--> src/main.rs:55:31
|
10 | fn fields(&self) -> String {
| ------
| |
| the method is available for `std::boxed::Box<traittest::Cursor>` here
| the method is available for `std::sync::Arc<traittest::Cursor>` here
| the method is available for `std::rc::Rc<traittest::Cursor>` here
...
20 | pub struct Cursor {
| ----------------- method `fields` not found for this
...
55 | println!("c.fields={}", c.fields());
| ^^^^^^ method not found in `traittest::Cursor`
|
= 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:
|
49 | use crate::traittest::CursorTable;
|
I finally figured out a solution I can live with, in case anybody else is looking for a solution to this problem.
In your module where you define your traits, create a sub-module with all the traits, like so:
pub mod Traits
{
pub trait CursorTrait
{
fn get_handle ( &self ) -> u32; // impl's must write this function
fn fields ( &self ) -> String
{
return format! ( "(get_handle() -> {})", self.get_handle() );
}
}
}
Now in your other modules, if you want to bring the traits in scope without bringing in the entire module, you can just bring in the submodule, like so:
mod foo; use foo::Traits::*;
I'm trying to serialize the following Result object, however I'm getting an error because while it workings for some of the properties, it doesn't seem to work on path, even though all of the elements involved have implementations provided by Serde.
#[macro_use]
extern crate serde;
extern crate rocket;
use rocket_contrib::json::Json;
use std::rc::Rc;
#[derive(Serialize)]
struct Result {
success: bool,
path: Vec<Rc<GraphNode>>,
visited_count: u32,
}
struct GraphNode {
value: u32,
parent: Option<Rc<GraphNode>>,
}
fn main(){}
fn index() -> Json<Result> {
Json(Result {
success: true,
path: vec![],
visited_count: 1,
})
}
Playground, although I can't get it to pull in the Rocket crate, it must not be one of the 100 most popular.
error[E0277]: the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `std::rc::Rc<GraphNode>`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`
From my understanding, #[derive(Serialize)] should automatically create a serialize method which serde can then use. However I would expect it to work for the properties too. Do I need to create structs for all the types and then derive Serialize for all of those structs?
Do I need to do something to enable it?
The following crates are in use:
rocket = "*"
serde = { version = "1.0", features = ["derive"] }
rocket_contrib = "*"
the trait bound `std::rc::Rc<GraphNode>: serde::Serialize` is not satisfied
This means that Rc does not implement Serialize. See How do I serialize or deserialize an Arc<T> in Serde?. TL;DR:
serde = { version = "1.0", features = ["derive", "rc"] }
Once adding that, the error message changes to:
error[E0277]: the trait bound `GraphNode: serde::Serialize` is not satisfied
--> src/main.rs:11:5
|
11 | path: Vec<Rc<GraphNode>>,
| ^^^^ the trait `serde::Serialize` is not implemented for `GraphNode`
|
= note: required because of the requirements on the impl of `serde::Serialize` for `std::rc::Rc<GraphNode>`
= note: required because of the requirements on the impl of `serde::Serialize` for `std::vec::Vec<std::rc::Rc<GraphNode>>`
= note: required by `serde::ser::SerializeStruct::serialize_field`
That's because every type that needs to be serialized must implement Serialize:
#[derive(Serialize)]
struct GraphNode {