Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add working v0.1.0 version of Sube/libwallet for JS #37

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion libwallet/js/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ js-sys = "0.3.61"
rand_core = { version = "0.6.3", features = ["getrandom"] }
serde = { version = "1.0.152", features = ["derive"] }
serde-wasm-bindgen = "0.4.5"
wasm-bindgen = "0.2.84"
wasm-bindgen = "=0.2.84"
wasm-bindgen-futures = "0.4.34"

[dev-dependencies]
Expand Down
13 changes: 10 additions & 3 deletions libwallet/src/key_pair.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
use core::fmt::Debug;


use core::{fmt::Debug, convert::TryInto};

pub use derive::Derive;

type Bytes<const N: usize> = [u8; N];
// struct Bytes<const N: usize>([u8; N]);

/// A key pair with a public key
pub trait Pair: Signer + Derive {
Expand All @@ -18,10 +21,13 @@ pub trait Pair: Signer + Derive {
pub trait Public: AsRef<[u8]> + Debug {}
impl<const N: usize> Public for Bytes<N> {}

pub trait Signature: AsRef<[u8]> + Debug + PartialEq {}
pub trait Signature: AsRef<[u8]> + Debug + PartialEq {
fn as_bytes<const N: usize>(&self) -> Bytes<N> {
self.as_ref().try_into().expect("error")
}
}
impl<const N: usize> Signature for Bytes<N> {}

/// Something that can sign messages
pub trait Signer {
type Signature: Signature;
fn sign_msg<M: AsRef<[u8]>>(&self, msg: M) -> Self::Signature;
Expand Down Expand Up @@ -135,6 +141,7 @@ pub mod any {
Ok(())
}
}

impl Public for AnyPublic {}

#[derive(Debug, PartialEq)]
Expand Down
3 changes: 3 additions & 0 deletions libwallet/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#![feature(async_fn_in_trait, impl_trait_projections)]
#![feature(trait_alias)]
// #![feature(result_option_inspect)]
#![cfg_attr(not(any(test, feature = "std")), no_std)]
//! `libwallet` is the one-stop tool to build easy, slightly opinionated crypto wallets
//! that run in all kinds of environments and plattforms including embedded hardware,
Expand Down
30 changes: 18 additions & 12 deletions sube/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ log = "0.4.17"
async-trait = "0.1.53"
blake2 = { version = "0.10.5", default-features = false }
codec = { version = "3.1.2", package = "parity-scale-codec", default-features = false }
frame-metadata = { version = "15.0.0", git = "https://github.com/paritytech/frame-metadata.git", default-features = false, features = ["serde_full", "decode"] }
frame-metadata = { version = "16.0.0", default-features = false, features = ["serde_full", "decode"] }
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }
twox-hash = { version = "1.6.2", default-features = false }
serde = { version = "1.0.137", default-features = false }
async-once-cell = "0.4.4"

scale-info = { version = "2.1.1", default-features = false, optional = true }
jsonrpc = { version = "0.12.1", default-features = false, optional = true }
scales = { path = "../scales", package = "scale-serialization", default-features = false, features = ["codec", "experimental-serializer"] }
scales = { git = "https://github.com/virto-network/scales.git", package = "scale-serialization", default-features = false, features = ["codec", "experimental-serializer"] }

# http backend
surf = { version = "2.3.2", default_features = false, optional = true }
Expand All @@ -36,29 +36,35 @@ async-tls = { version = "0.11.0", default-features = false, optional = true }
async-std = { version = "1.11.0", default_features = false, optional = true }
serde_json = { version = "1.0.80", default-features = false, optional = true }
url = { version = "2.2.2", optional = true }

wasm-bindgen = "0.2.63"

paste = { version = "1.0", optional = true }
wasm-bindgen = { version = "=0.2.84", optional = true }
once_cell = { version = "1.17.1", optional = true }
heapless = { version = "0.7.16", optional = true }
anyhow = { version = "1.0.40", optional = true }
rand_core = {version = "0.6.3", optional = true }
[dev-dependencies]
async-std = { version = "1.11.0", features = ["attributes"] }
hex-literal = "0.3.4"
libwallet = { path = "../libwallet" }

[features]
# default = ["json", "std"]
default = ["async-std", "builder", "v14", "url", "wss", "ws", "http", "json"]
default = ["async-std", "builder", "url", "wss", "ws", "http", "json", "v14", "serde_json"]
#default = ["v14", "ws", "decode", "json", "std"]
# decode = ["v14", "serde", "scales/codec"]
# encode = ["v14", ]
http = ["jsonrpc", "surf/h1-client-rustls"]
http-web = ["jsonrpc", "surf/wasm-client"]
json = ["v14", "scales/json"]
http-web = ["jsonrpc", "surf/wasm-client", "wasm-bindgen", "url", "serde_json"]
json = [ "scales/json"]
std = []
builder = []
v12 = ["frame-metadata/v12"]
v13 = ["frame-metadata/v13"]
v14 = ["frame-metadata/v14", "scale-info"]

builder = ["paste", "once_cell", "heapless"]
# v12 = ["frame-metadata/v12"]
# v13 = ["frame-metadata/v13"]
v14 = ["scale-info", "frame-metadata/current"]
ws = ["async-std", "async-tungstenite", "async-mutex", "futures-util", "futures-channel", "jsonrpc"]
wss = ["ws", "async-tls", "async-tungstenite/async-tls"]
examples = ["anyhow", "rand_core"]


[package.metadata.docs.rs]
Expand Down
1 change: 0 additions & 1 deletion sube/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ hex = { version = "0.4.3", default-features = false, features = ["alloc"] }
path = ".."
features = [
"std",
"v14",
"http",
# "wss",
]
Expand Down
14 changes: 8 additions & 6 deletions sube/examples/query_balance.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@



use sube::{ builder::SubeBuilder as Sube };
use async_trait::async_trait;
use core::future::{Future, IntoFuture};
use sube::{ Response, sube, Result };

#[async_std::main]
async fn main () {
let a = Sube("wss://rpc.polkadot.io").await?;
async fn main() -> Result<()> {

let result = sube!("https://kusama.olanod.com/system/_constants/version").await?;

println!("{:?}", result);
Ok(())
}
13 changes: 13 additions & 0 deletions sube/examples/query_balance_builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use async_trait::async_trait;

use sube::{ Response, sube, Result, builder::QueryBuilder, SignerFn, ExtrinicBody };

#[async_std::main]
async fn main() -> Result<()> {
let builder = QueryBuilder::default()
.with_url("https://kusama.olanod.com/system/_constants/version")
.await?;

println!("{:?}", builder);
Ok(())
}
47 changes: 47 additions & 0 deletions sube/examples/send_tx.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use futures_util::TryFutureExt;
use serde_json::json;
use libwallet::{self, vault};
use sube::sube;
use std::env;
use rand_core::OsRng;

type Wallet = libwallet::Wallet<vault::Simple>;

use anyhow::{ Result, anyhow };

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let phrase = env::args().skip(1).collect::<Vec<_>>().join(" ");

let (vault, phrase) = if phrase.is_empty() {
vault::Simple::generate_with_phrase(&mut rand_core::OsRng)
} else {
let phrase: libwallet::Mnemonic = phrase.parse().expect("Invalid phrase");
(vault::Simple::from_phrase(&phrase), phrase)
};

let mut wallet = Wallet::new(vault);
wallet.unlock(None).await?;

let account = wallet.default_account();
let public = account.public();

let response = sube!("https://kusama.olanod.com/balances/transfer" => {
signer: |message: &[u8]| Ok(wallet.sign(message).into()),
sender: public.as_ref(),
body: json!({
"dest": {
"Id": public.as_ref()
},
"value": 100000
}),
})
.map_err(|err| anyhow!(format!("SubeError {:?}", err)))
.await?;


println!("Secret phrase: \"{phrase}\"");
println!("Default Account: 0x{account}");

Ok(())
}
44 changes: 44 additions & 0 deletions sube/examples/send_tx_builder.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use jsonrpc::error;
use serde_json::json;
use libwallet::{self, vault, Signature};
use sube::builder::TxBuilder;
use std::env;
use rand_core::OsRng;

type Wallet = libwallet::Wallet<vault::Simple>;
use anyhow::{ Result, anyhow };

#[async_std::main]
async fn main() -> Result<()> {
let phrase = env::args().skip(1).collect::<Vec<_>>().join(" ");

let (vault, phrase) = if phrase.is_empty() {
vault::Simple::generate_with_phrase(&mut rand_core::OsRng)
} else {
let phrase: libwallet::Mnemonic = phrase.parse().expect("Invalid phrase");
(vault::Simple::from_phrase(&phrase), phrase)
};

let mut wallet = Wallet::new(vault);

wallet.unlock(None).await?;

let account = wallet.default_account();

let response = TxBuilder::default()
.with_url("https://kusama.olanod.com/balances/transfer")
.with_signer(|message: &[u8]| Ok(wallet.sign(message).as_bytes()) )
.with_sender(wallet.default_account().public().as_ref())
.with_body(json!({
"dest": {
"Id": wallet.default_account().public().as_ref()
},
"value": 100000
}))
.await
.map_err(|err| {
anyhow!(format!("Error {:?}", err))
})?;

Ok(())
}
47 changes: 47 additions & 0 deletions sube/examples/send_tx_signer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use futures_util::TryFutureExt;
use serde_json::json;
use libwallet::{self, vault, Signature};
use sube::{ sube };
use std::env;
use rand_core::OsRng;

type Wallet = libwallet::Wallet<vault::Simple>;

use anyhow::{ Result, anyhow };

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let phrase = env::args().skip(1).collect::<Vec<_>>().join(" ");

let (vault, phrase) = if phrase.is_empty() {
vault::Simple::generate_with_phrase(&mut rand_core::OsRng)
} else {
let phrase: libwallet::Mnemonic = phrase.parse().expect("Invalid phrase");
(vault::Simple::from_phrase(&phrase), phrase)
};

let mut wallet = Wallet::new(vault);
wallet.unlock(None).await?;

let account = wallet.default_account();
let public = account.public();


let response = sube!(
"https://kusama.olanod.com/balances/transfer" =>
(wallet, json!({
"dest": {
"Id": public.as_ref(),
},
"value": 100000
}))
)
.await
.map_err(|err| anyhow!(format!("SubeError {:?}", err)))?;


println!("Secret phrase: \"{phrase}\"");
// println!("Default Account: 0x{account}");

Ok(())
}
72 changes: 72 additions & 0 deletions sube/examples/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#![feature(prelude_import)]
#[prelude_import]
use std::prelude::rust_2021::*;
#[macro_use]
extern crate std;
use futures_util::TryFutureExt;
use serde_json::json;
use libwallet::{self, vault};
use sube::sube;
use std::env;
use rand_core::OsRng;
type Wallet = libwallet::Wallet<vault::Simple>;
use anyhow::{Result, anyhow};
fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn main() -> Result<(), Box<dyn std::error::Error>> {
{
let phrase = env::args().skip(1).collect::<Vec<_>>().join(" ");
let (vault, phrase) = if phrase.is_empty() {
vault::Simple::generate_with_phrase(&mut rand_core::OsRng)
} else {
let phrase: libwallet::Mnemonic = phrase
.parse()
.expect("Invalid phrase");
(vault::Simple::from_phrase(&phrase), phrase)
};
let mut wallet = Wallet::new(vault);
wallet.unlock(None).await?;
let account = wallet.default_account().public();
let public = account.as_ref();

let response = async {
let mut builder = ::sube::builder::TxBuilder::default();
// let account = &wallet.default_account();
// let public = account.public();

builder
.with_signer(|message: &[u8]| Ok(wallet.sign(message).into()))
.with_sender(public.into())
.with_body(
::serde_json::Value::Object({
let mut object = ::serde_json::Map::new();
let _ = object
.insert(
("dest").into(),
::serde_json::Value::Object({
let mut object = ::serde_json::Map::new();
let _ = object
.insert(
("Id").into(),
::serde_json::to_value(&public.as_ref()).unwrap(),
);
object
}),
);
let _ = object
.insert(
("value").into(),
::serde_json::to_value(&100000).unwrap(),
);
object
}),
)
.await
}
.map_err(|err| anyhow!(format!("SubeError {:?}", err)))
.await?;

Ok(())
}
}
async_std::task::block_on(async { main().await })
}
Loading
Loading