Skip to content

Commit

Permalink
expose ErgoTree and Address::new_p2pk() in WASM;
Browse files Browse the repository at this point in the history
  • Loading branch information
greenhat committed Nov 6, 2020
1 parent 03870d0 commit a0d95ad
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
2 changes: 2 additions & 0 deletions bindings/ergo-lib-wasm/Cargo.toml
Expand Up @@ -27,6 +27,8 @@ getrandom = {version = "0.1", features = ["wasm-bindgen"]}
# code size when deploying.
console_error_panic_hook = { version = "0.1.6", optional = true }

derive_more = "0.99"

[dependencies.wasm-bindgen]
version = "0.2"
features = ["serde-serialize"]
Expand Down
9 changes: 9 additions & 0 deletions bindings/ergo-lib-wasm/src/address.rs
Expand Up @@ -7,6 +7,8 @@ use ergo_lib::{
};
use wasm_bindgen::prelude::*;

use crate::ergo_tree::ErgoTree;

/// Network type
#[wasm_bindgen]
#[repr(u8)]
Expand Down Expand Up @@ -121,6 +123,13 @@ pub struct Address(chain::address::Address);

#[wasm_bindgen]
impl Address {
/// Create a P2PK address from an ergo tree if ProveDlog is the root of the tree, otherwise returns an error
pub fn new_p2pk(ergo_tree: &ErgoTree) -> Result<Address, JsValue> {
chain::address::Address::new_p2pk(&ergo_tree.clone().into())
.map(Address)
.map_err(|e| JsValue::from_str(&format!("{}", e)))
}

/// Decode (base58) testnet address from string
pub fn from_testnet_str(s: &str) -> Result<Address, JsValue> {
chain::address::AddressEncoder::new(chain::address::NetworkPrefix::Testnet)
Expand Down
27 changes: 27 additions & 0 deletions bindings/ergo-lib-wasm/src/ergo_tree.rs
@@ -0,0 +1,27 @@
//! ErgoTree

use std::convert::TryFrom;

use ergo_lib::chain::Base16DecodedBytes;
use ergo_lib::serialization::SigmaSerializable;
use wasm_bindgen::prelude::*;

extern crate derive_more;
use derive_more::{From, Into};

/// The root of ErgoScript IR. Serialized instances of this class are self sufficient and can be passed around.
#[wasm_bindgen]
#[derive(PartialEq, Eq, Debug, Clone, From, Into)]
pub struct ErgoTree(ergo_lib::ErgoTree);

#[wasm_bindgen]
impl ErgoTree {
/// Decode from base16 encoded serialized ErgoTree
pub fn from_base16_bytes(s: &str) -> Result<ErgoTree, JsValue> {
let bytes = Base16DecodedBytes::try_from(s.to_string())
.map_err(|e| JsValue::from_str(&format!("{}", e)))?;
ergo_lib::ErgoTree::sigma_parse_bytes(bytes.0)
.map(ErgoTree)
.map_err(|e| JsValue::from_str(&format!("{}", e)))
}
}
1 change: 1 addition & 0 deletions bindings/ergo-lib-wasm/src/lib.rs
Expand Up @@ -22,6 +22,7 @@ pub mod contract;
pub mod data_input;
pub mod ergo_box;
pub mod ergo_state_ctx;
pub mod ergo_tree;
pub mod secret_key;
pub mod token;
pub mod transaction;
Expand Down

0 comments on commit a0d95ad

Please sign in to comment.