How to use serde_json in pallet? - substrate

On using serde_json in my pallet dependency it throws this throws these error:-
``
#[weight=10_000]
pub fn insert_data_class(origin,app_id:Vec<u8>,db_id:Vec<u8>,cid:Vec<u8>,data:Vec<u8>,signature:H512)->DispatchResult{
let caller = ensure_signed(origin)?;
let app_data = alioth_register::Module::<T>::check_ownership(&caller,&app_id);
ensure!(app_data.0,Error::<T>::AppNotFound);
let data_str = String::from_utf8(data.clone()).unwrap();
let data_json = json!(data_str);
let uid:Vec<u8> = data_json["uid"].to_string().as_bytes().to_vec();
//let uuid_str = data_json["uuid"].to_string();
let uuid:Vec<u8> = data_json["uuid"].to_string().as_bytes().to_vec();
let data1 = data.clone();
let data1 = String::from_utf8(data1).unwrap();
let user_data = alioth_users::Module::<T>::check_user_extern(&uuid,&app_id);
ensure!(user_data.0,Error::<T>::UserNotFound);
let class_data = alioth_class::Module::<T>::check_class(&db_id,&cid);
ensure!(class_data.0,Error::<T>::ClassOrDatabaseNotFound);
//I needed a public key for this purpose we are going to write a function in alioth-users
let pub_key_ref:(bool,H256) = alioth_users::Module::<T>::get_public_key(&uuid,&app_id);
ensure!(pub_key_ref.0,Error::<T>::ObjectNotCreated);
//now we are going to verify the signature for the further transaction
ensure!(sp_io::crypto::sr25519_verify(&Signature::from_h512(signature),data1.as_bytes(),&Public::from_h256(pub_key_ref.1)),Error::<T>::SignatureNotVerified);
//its over now we are going ahead to check the uniqness of data and insert it later.
let data_from_self = Self::check_obj_store(&uid,&cid);
ensure!(!data_from_self.0,Error::<T>::DataIsNotUnique);
let struct_data = ObjectData{
duid:uid,
object:data,
};
if data_from_self.1==0{
let vec_data = vec![struct_data];
<ObjectStore>::insert(cid,vec_data);
Self::deposit_event(Event::ObjectCreated());
}
else{
let mut vec_data = <ObjectStore>::get(&cid);
vec_data.insert(vec_data.len(),struct_data);
<ObjectStore>::insert(cid,vec_data);
Self::deposit_event(Event::ObjectCreated());
}
Ok(())
}**this code uses serde_json::json macro**
error: failed to run custom build command for node-template-runtime v3.0.0 (/home/corteri/Desktop/blockchain/new_tmp/substrate-node-template/runtime)
Caused by:
process didn't exit successfully: /home/corteri/Desktop/blockchain/new_tmp/substrate-node-template/target/debug/build/node-template-runtime-e56bc02a2834241f/build-script-build (exit status: 1)
--- stdout
Information that should be included in a bug report.
Executing build command: "rustup" "run" "nightly" "cargo" "-Zfeatures=build_dep" "rustc" "--target=wasm32-unknown-unknown" "--manifest-path=/home/corteri/Desktop/blockchain/new_tmp/substrate-node-template/target/debug/wbuild/node-template-runtime/Cargo.toml" "--color=always" "--release"
Using rustc version: rustc 1.56.0-nightly (b7404c898 2021-09-03)
--- stderr
warning: flag -Z features has been stabilized in the 1.51 release, and is no longer necessary
The new feature resolver is now available by specifying resolver = "2" in Cargo.toml.
See https://doc.rust-lang.org/nightly/cargo/reference/features.html#feature-resolver-version-2 for more information.
Compiling getrandom v0.2.1
error: target is not supported, for more information see: https://docs.rs/getrandom/#unsupported-targets
--> /home/corteri/.cargo/registry/src/github.com-1ecc6299db9ec823/getrandom-0.2.1/src/lib.rs:214:9
|
214 | / compile_error!("target is not supported, for more information see:
215 | | https://docs.rs/getrandom/#unsupported-targets");
| |_________________________________________________________________________^
error[E0433]: failed to resolve: use of undeclared crate or module imp
--> /home/corteri/.cargo/registry/src/github.com-1ecc6299db9ec823/getrandom-0.2.1/src/lib.rs:236:5
|
236 | imp::getrandom_inner(dest)
| ^^^ use of undeclared crate or module imp
For more information about this error, try rustc --explain E0433.
error: could not compile getrandom due to 2 previous errors

getrandom/js feature needs to be activated in your Cargo.toml:
# We enable it only for web-wasm check
# See https://docs.rs/getrandom/0.2.1/getrandom/#webassembly-support
getrandom = { version = "0.2", features = ["js"] }
(I don't think this is a serde_json specific error btw)

Related

failed to resolve: maybe a missing crate `image`? Rust

I'm attempting to start my first project in Rust using VScode. I added the '''image = "0.24.5"''' to the dependencies section of the Cargo.toml file, built the project with cargo build. However, whenever I try and run the file I get an error that says:
error[E0433]: failed to resolve: maybe a missing crate `image`?
--> main.rs:1:5
|
1 | use image::io::Reader;
| ^^^^^ maybe a missing crate `image`?
|
= help: consider adding `extern crate image` to use the `image` crate
This is the main file:
use image::io::Reader;
fn main() {
println!("Hello, world!");
}
Cargo.toml
[package]
name = "imaging"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
image = "0.24.5"
Not quite sure why I'm getting this error. My guess is that it may be that VScode is unable to find the dependency.

WASM/Yew - failed to resolve: could not find `unix` in `os`

Building Yew App on Windows
I'm building a yew app alongside a rocket backend on Windows following
this tutorial
(although the tutorial is for a Linux environment). I'm trying to build the yew app
using wasm-pack. I'm not using the Linux subsystem to build the app, though
I do have it installed.
Code / Configuration
The repository.
I have already installed the wasm toolchain and cargo make:
rustup target add wasm32-unknown-unknown
The following is my toolchain list:
stable-x86_64-pc-windows-gnu
stable-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc (default)
1.30.0-x86_64-pc-windows-msvc
Here is my folder structure:
Project root
├───backend <-- rocket backend
| ├───Cargo.toml
│ └───src
│ ├───bin
│ └───db
├───frontend <-- yew frontend
│ ├───pkg
│ ├───src
| ├───Cargo.toml
| └───Makefile.toml
├───src
├───Cargo.toml
└───Makefile.toml
This is rootdir\Cargo.toml:
[package]
name = "sentinel"
version = "0.1.0"
authors = ["zachdelano <email>"]
edition = "2018"
[workspace]
members = ["backend", "frontend"]
This is rootdir\Makefile.toml:
[env]
CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = "true"
[tasks.default]
clear = true
dependencies = ["build"]
This is rootdir\frontend\Cargo.toml:
[dependencies]
sentinel = { path = ".." }
yew = "0.17.3"
wasm-pack = "0.9.1"
wasm-bindgen = "0.2.68"
web-sys = "0.3.45"
[lib]
crate-type = ["cdylib", "rlib"]
This is rootdir\frontend\Makefile.toml:
[tasks.default]
dependencies = ["create_wasm"]
[tasks.create_wasm]
command = "wasm-pack"
args = ["build", "--target", "web", "--out-name", "package", "--dev"]
dependencies = ["build"]
Expected result
I expect the app to finish building with no errors when I run
cargo make. The Yew tutorial
seems to indicate nothing else is needed.
Actual output
I get a host of errors when running cargo make (from the root directory) like the following:
error[E0433]: failed to resolve: could not find `unix` in `os`
--> C:\Users\Zach\.cargo\registry\src\github.com-1ecc6299db9ec823\dirs-1.0.5\src\lin.rs:41:18
|
41 | use std::os::unix::ffi::OsStringExt;
| ^^^^ could not find `unix` in `os`
See the entire list of errors.
Is this a toolchain sort of thing? How can I fix this?
Running rustup update
I get the following output
from running rustup update.
Now when I run cargo make from the root directory, I get different errors:
error[E0432]: unresolved import `crate::sys`
--> C:\Users\Zach\.cargo\registry\src\github.com-1ecc6299db9ec823\socket2-0.3.15\src\socket.rs:23:5
|
23 | use crate::sys;
| ^^^^^^^^^^ no `sys` in the root
See the full list of errors.
Some of the code changed in the repository.
The issue ended up being that I was trying to install wasm-pack and web-sys. I don't know why that was an issue but when I commented them out and ran cargo make, everything built just fine. I also deleted target and reran cargo make just to make sure.
[package]
name = "frontend"
version = "0.1.0"
authors = ["zachdelano <email>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
sentinel = { path = ".." }
yew = "0.17.3"
wasm-bindgen = "0.2.68"
# wasm-pack = "0.9.1"
# web-sys = "0.3.45"
[lib]
crate-type = ["cdylib", "rlib"]

'No such file or directory' error when using buildGoPackage in nix

I'm trying to build the hasura cli: https://github.com/hasura/graphql-engine/tree/master/cli with the following code (deps derived from dep2nix):
{ buildGoPackage, fetchFromGitHub }:
buildGoPackage rec {
version = "1.0.0-beta.2";
name = "hasura-${version}";
goPackagePath = "github.com/hasura/graphql-engine";
subPackages = [ "cli" ];
src = fetchFromGitHub {
owner = "hasura";
repo = "graphql-engine";
rev = "v${version}";
sha256 = "1b40s41idkp1nyb9ygxgsvrwv8rsll6dnwrifpn25bvnfk8idafr";
};
goDeps = ./deps.nix;
}
but I get the following errors after the post-installation fixup step:
find: '/nix/store/gkck68cm2z9k1qxgmh350pq3kwsbyn8q-hasura-cli-1.0.0-beta.2': No such file or directory.
What am I doing wrong here? For reference, I'm on macOS and using home-manager.
For anyone still wondering:
There are a couple of things to consider:
dep has been deprecated in favor of go modules
This is also reflected in Nix, as buildGoPackage is now legacy and moved to buildGoModule
There is already a hasura-cli package in nixpkgs. You can just use it with nix-shell -p hasura-cli

cctools-binutils-darwin/bin/ranlib failed, malformed object (unknown load command)

I am attempting to build the gitlib-libgit2 Haskell package on macos via nix in roughly the following manner.
mkdir nix-repro && cd nix-repro
cabal2nix --no-check cabal://gitlib-libgit2 > gitlib-libgit2.nix
echo '(import <nixpkgs> {}).haskellPackages.callPackage ./gitlib-libgit2.nix {}' > default.nix
nix-build
I am seeing the following warnings and error:
ld: warning: /nix/store/spx9xz1jv3yhmqw8y3agki1fvdr2x2fv-libiconv-osx-10.11.6/lib/libiconv.dylib, ignoring unexpected dylib file
ld: warning: /nix/store/spx9xz1jv3yhmqw8y3agki1fvdr2x2fv-libiconv-osx-10.11.6/lib/libiconv.dylib, ignoring unexpected dylib file
/nix/store/s33984hx2gwcg2d4dgpcm4342md19qvh-cctools-binutils-darwin/bin/ranlib: object: dist/build/libHSgitlib-libgit2-3.1.2.1-1fYQZMedHRP3aXiBXJFDO2-ghc8.6.3.a(s2_meth.o) malformed object (unknown load command 1)
`ranlib' failed in phase `Ranlib'. (Exit code: 1)
builder for '/nix/store/yrran1p69pvdq1b34jqfq7dmd95j9fh9-gitlib-libgit2-3.1.2.1.drv' failed with exit code 1
error: build of '/nix/store/yrran1p69pvdq1b34jqfq7dmd95j9fh9-gitlib-libgit2-3.1.2.1.drv' failed
What does this mean, and how can I go about fixing it?
It only fails this way on macos, as far as I can tell. I'm on nixpkgs-unstable. I am able to build this package using other tools, so the failure must be something specific to the nix tooling I'm using to build it.
$ cat $HOME/.nix-defexpr/channels/nixpkgs/.git-revision
6e5caa3f8ac48750233ef82a94825be238940825
Here's the full gitlib-libgit2.nix expression if you don't want to run cabal2nix for yourself:
{ mkDerivation, base, bytestring, conduit, conduit-combinators
, containers, directory, exceptions, fast-logger, filepath, gitlib
, gitlib-test, hlibgit2, hspec, hspec-expectations, HUnit, mmorph
, monad-loops, mtl, resourcet, stdenv, stm, stm-conduit, tagged
, template-haskell, text, text-icu, time, transformers
, transformers-base, unliftio, unliftio-core
}:
mkDerivation {
pname = "gitlib-libgit2";
version = "3.1.2.1";
sha256 = "b90e0ad2e7e0f58379e02cbe60d2900c95f0a255c34bd3461f8ee5753a6aa23e";
libraryHaskellDepends = [
base bytestring conduit conduit-combinators containers directory
exceptions fast-logger filepath gitlib hlibgit2 mmorph monad-loops
mtl resourcet stm stm-conduit tagged template-haskell text text-icu
time transformers transformers-base unliftio unliftio-core
];
testHaskellDepends = [
base exceptions gitlib gitlib-test hspec hspec-expectations HUnit
transformers
];
doCheck = false;
description = "Libgit2 backend for gitlib";
license = stdenv.lib.licenses.mit;
}

Swift 2.0, Xcode 7 issue

I was using RAMAnimatedTabBarController Module from here:
https://github.com/Ramotion/animated-tab-bar
I developed my entire application in swift 1.2 using Xcode 6 and the app was running perfectly . I wanted to try out "side loading" of my app using Xcode 7 which has swift 2.0. I had too many errors and I managed to solve most of the errors but three.
1) This line of code which is from that RAMAnimatedTabBarController module is throwing an error saying the function can't be evoked, when this perfectly compiled in Xcode 6:
var constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString,options:NSLayoutFormatOptions.DirectionRightToLeft,metrics: nil,views: containersDict as [NSObject : AnyObject])
the compiler error for this was:
Cannot invoke 'constraintsWithVisualFormat' with an argument list of
type '(String, options: NSLayoutFormatOptions, metrics: nil, views:
[NSObject : AnyObject])'
2) Another unusual error was thrown:
linker command failed with exit code 1 (use -v to see invocation)
3) And another:
(null): error: cannot parse the debug map for
"/Users/Rakshith/Library/Developer/Xcode/DerivedData/Blubot-heabwwmhqxxvctaabxkwcpgzsadx/Build/Intermediates/SwiftMigration/Blubot/Products/Debug-iphonesimulator/BlubotTests.xctest/BlubotTests":
No such file or directory
What is actually wrong with my project? It is still set to iOS 8.3.
Disable BitCode
Build Settings -> BitCode
I managed to correct the 2nd and 3rd error which most of you probably will face when you're running Xcode 7 Beta as well as Xcode 6.
Just solve these two errors by following the steps mentioned in this tread:
Xcode Version 6.1 (6A1030) - Apple Match O-Linker Error - Building
Try this method:
func createViewContainers() -> [String: UIView] {
var containersDict = [String: UIView]()
guard let tabBarItems = tabBar.items else
{
return containersDict
}
let itemsCount: Int = tabBarItems.count - 1
for index in 0...itemsCount {
let viewContainer = createViewContainer()
containersDict["container\(index)"] = viewContainer
}
var formatString = "H:|-(0)-[container0]"
for index in 1...itemsCount {
formatString += "-(0)-[container\(index)(==container0)]"
}
formatString += "-(0)-|"
let constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString,
options:NSLayoutFormatOptions.DirectionRightToLeft,
metrics: nil,
views: containersDict)
view.addConstraints(constranints)
return containersDict
}
how about to change the small code from "containersDict as [NSObject : AnyObject]" to "containersDict as [String : AnyObject]".
then I solved the issue above method.

Resources