Commit 93d91ba2 authored by Andrew Jones's avatar Andrew Jones Committed by Hero Bird

[examples] remove core & model examples, except erc20 (#138)

parent db766e2c
[target.wasm32-unknown-unknown]
rustflags = [
"-C", "overflow-checks=on",
"-C", "link-args=-z stack-size=65536 --import-memory"
]
[package]
name = "incrementer"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
ink_core = { path = "../../../core" }
parity-codec = { version = "3.2", default-features = false, features = ["derive"] }
[lib]
name = "incrementer"
crate-type = ["cdylib"]
[features]
default = []
test-env = [
"ink_core/test-env",
]
[profile.release]
panic = "abort"
lto = true
opt-level = "z"
debug = false
#!/bin/bash
# Deprecated Note:
# The wasm-build executable that is used to tree-shake the wasm binary
# resulting from the cargo build in the first step expects to find it
# under target/release/wasm32-unknown-unknown/ in the cwd.
PROJNAME=incrementer
#cargo clean
#rm Cargo.lock
CARGO_INCREMENTAL=0 cargo build --release --target=wasm32-unknown-unknown --verbose
wasm2wat -o target/$PROJNAME.wat target/wasm32-unknown-unknown/release/$PROJNAME.wasm
cat target/$PROJNAME.wat | sed "s/(import \"env\" \"memory\" (memory (;0;) 2))/(import \"env\" \"memory\" (memory (;0;) 2 16))/" > target/$PROJNAME-fixed.wat
wat2wasm -o target/$PROJNAME.wasm target/$PROJNAME-fixed.wat
#wasm-build target enyzme --target-runtime=substrate --final=adder --save-raw=./target/enzyme-deployed.wasm --target wasm32-unknown-unknown
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
// ink! is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ink! is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ink!. If not, see <http://www.gnu.org/licenses/>.
#![cfg_attr(not(all(test, feature = "test-env")), no_std)]
use parity_codec::Decode;
use ink_core::{
env::{
self,
ContractEnv,
DefaultSrmlTypes,
Env,
},
storage::{
alloc::{
self,
Allocate,
AllocateUsing,
Initialize,
},
Flush,
Key,
Value,
},
};
/// An incrementer smart contract.
///
/// Can only increment and return its current value.
struct Incrementer {
/// The current value stored in the storage.
current: Value<u32>,
}
impl Incrementer {
/// Increments the current value.
pub fn inc(&mut self, by: u32) {
self.current += by;
}
/// Returns the current value.
pub fn get(&self) -> u32 {
*self.current
}
}
impl Initialize for Incrementer {
type Args = ();
fn initialize(&mut self, _args: Self::Args) {
self.current.set(0)
}
}
// Everything below this point can be generated by the upcoming eDSL.
impl AllocateUsing for Incrementer {
unsafe fn allocate_using<A>(alloc: &mut A) -> Self
where
A: Allocate,
{
Self {
current: AllocateUsing::allocate_using(alloc),
}
}
}
impl Flush for Incrementer {
fn flush(&mut self) {
self.current.flush()
}
}
#[derive(parity_codec::Encode, parity_codec::Decode)]
enum Action {
Get,
Inc(u32),
}
fn ret<T>(val: T) -> !
where
T: parity_codec::Encode,
{
unsafe { env::r#return::<T, ContractEnv<DefaultSrmlTypes>>(val) }
}
fn instantiate() -> Incrementer {
unsafe {
let mut alloc = alloc::BumpAlloc::from_raw_parts(Key([0x0; 32]));
Incrementer::allocate_using(&mut alloc)
}
}
#[no_mangle]
pub extern "C" fn deploy() {
instantiate().initialize_into(()).flush()
}
#[no_mangle]
pub extern "C" fn call() {
let input = <ContractEnv<DefaultSrmlTypes> as Env>::input();
let action = Action::decode(&mut &input[..]).unwrap();
let mut incrementer = instantiate();
match action {
Action::Get => {
let returned_val = &incrementer.get();
// println!("CALL: identified get() and returned {:?}", returned_val);
ret(&returned_val)
}
Action::Inc(by) => {
// println!("CALL: identified inc({:?})", by);
incrementer.inc(by);
incrementer.flush();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get() {
let incrementer = instantiate().initialize_into(());
assert_eq!(incrementer.get(), 0)
}
#[test]
fn test_set() {
let mut incrementer = instantiate().initialize_into(());
incrementer.inc(1);
assert_eq!(incrementer.get(), 1);
incrementer.inc(42);
assert_eq!(incrementer.get(), 43);
}
}
[target.wasm32-unknown-unknown]
rustflags = [
"-C", "overflow-checks=on",
"-C", "link-args=-z stack-size=65536 --import-memory"
]
[package]
name = "noop"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
ink_core = { path = "../../../core" }
parity-codec = { version = "3.2", default-features = false, features = ["derive"] }
[lib]
name = "noop"
path = "noop.rs"
crate-type = ["cdylib"]
[features]
default = []
test-env = ["ink_core/test-env"]
[profile.release]
panic = "abort"
lto = true
opt-level = "z"
#!/bin/bash
# Deprecated Note:
# The wasm-build executable that is used to tree-shake the wasm binary
# resulting from the cargo build in the first step expects to find it
# under target/release/wasm32-unknown-unknown/ in the cwd.
PROJNAME=noop
#cargo clean
#rm Cargo.lock
CARGO_INCREMENTAL=0 cargo build --release --target=wasm32-unknown-unknown --verbose
wasm2wat -o target/$PROJNAME.wat target/wasm32-unknown-unknown/release/$PROJNAME.wasm
cat target/$PROJNAME.wat | sed "s/(import \"env\" \"memory\" (memory (;0;) 2))/(import \"env\" \"memory\" (memory (;0;) 2 16))/" > target/$PROJNAME-fixed.wat
wat2wasm -o target/$PROJNAME.wasm target/$PROJNAME-fixed.wat
#wasm-build target enyzme --target-runtime=substrate --final=adder --save-raw=./target/enzyme-deployed.wasm --target wasm32-unknown-unknown
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
// ink! is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ink! is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ink!. If not, see <http://www.gnu.org/licenses/>.
#![no_std]
// use ink_core::{
// env::{Env, ContractEnv},
// };
#[allow(unused)]
use ink_core;
#[no_mangle]
pub extern "C" fn deploy() {
// ContractEnv::println("noop contract: CREATE");
}
#[no_mangle]
pub extern "C" fn call() {
// ContractEnv::println("noop contract: CALL");
}
[target.wasm32-unknown-unknown]
rustflags = [
"-C", "overflow-checks=on",
"-C", "link-args=-z stack-size=65536 --import-memory"
]
[package]
name = "subpeep"
version = "0.1.0"
authors = ["Robin Freyler <robin@parity.io>", "Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies]
ink_core = { path = "../../../core" }
parity-codec = { version = "3.2", default-features = false, features = ["derive", "full"] }
[lib]
name = "subpeep"
crate-type = ["cdylib"]
[features]
default = []
test-env = ["ink_core/test-env"]
[profile.release]
panic = "abort"
lto = true
opt-level = "z"
# Subpeep
Decentralized message distribution inspired by Twitter.
## Features
### Required
- Register users by their name.
- Checks if the account is allowed to peep.
- Users can peep messages that are prodcasted to the global channel.
- Users can follow other users by their name.
## Data Structures
```rust
// All global peeps.
GLOBAL_PEEPS = [Peep; 10]
// The address for the registered user
AUTH = mapping Username -> AccountId
// All peeps by a single user
USER_PEEPS = mapping Username -> Vec<Peep>
// All users that this user is following
USER_FOLLOWS = mapping Username -> Vec<Username>
```
## API
**Note:** `caller()` returns the senders address.
```python
fn register(username)
AUTH[username] = caller()
fn peep(username, peep)
if AUTH[username] = caller()
PEEPS[username].append(peep)
fn follow(username: String, followed: String)
if AUTH[username] == caller() and AUTH[followed].is_some()
FOLLOWING[username].append(followed)
```
#!/bin/bash
# Deprecated Note:
# The wasm-build executable that is used to tree-shake the wasm binary
# resulting from the cargo build in the first step expects to find it
# under target/release/wasm32-unknown-unknown/ in the cwd.
PROJNAME=subpeep
#cargo clean
#rm Cargo.lock
CARGO_INCREMENTAL=0 cargo build --release --target=wasm32-unknown-unknown --verbose
wasm2wat -o target/$PROJNAME.wat target/wasm32-unknown-unknown/release/$PROJNAME.wasm
cat target/$PROJNAME.wat | sed "s/(import \"env\" \"memory\" (memory (;0;) 2))/(import \"env\" \"memory\" (memory (;0;) 2 16))/" > target/$PROJNAME-fixed.wat
wat2wasm -o target/$PROJNAME.wasm target/$PROJNAME-fixed.wat
#wasm-build target enyzme --target-runtime=substrate --final=adder --save-raw=./target/enzyme-deployed.wasm --target wasm32-unknown-unknown
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
// ink! is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ink! is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ink!. If not, see <http://www.gnu.org/licenses/>.
#![no_std]
#[cfg(all(test, feature = "test-env"))]
mod tests;
use parity_codec::{
Decode,
Encode,
};
use ink_core::{
env::{
ContractEnv,
DefaultSrmlTypes,
Env,
EnvTypes,
},
memory::string::String,
storage::{
self,
alloc::{
AllocateUsing,
BumpAlloc,
Initialize,
},
Flush,
Key,
},
};
type AccountId = <ContractEnv<DefaultSrmlTypes> as EnvTypes>::AccountId;
type Balance = <ContractEnv<DefaultSrmlTypes> as EnvTypes>::Balance;
/// A peep done by a registered user.
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)]
pub struct Peep {
/// By whom the peep was done.
by: String,
/// The message of the peep.
message: String,
}
impl Peep {
/// Creates a new peep from `by` with content `message`.
pub fn new(by: String, message: String) -> Self {
Self { by, message }
}
}
/// The data of a registered user.
#[derive(Debug, Encode, Decode)]
pub struct UserData {
/// Owner address.
owner: AccountId,
/// The peeps.
peeps: storage::Vec<String>,
/// The follows.
following: storage::Vec<String>,
}
impl AllocateUsing for UserData {
unsafe fn allocate_using<A>(alloc: &mut A) -> Self
where
A: ink_core::storage::alloc::Allocate,
{
Self {
owner: AccountId::from([0x0; 32]),
peeps: storage::Vec::allocate_using(alloc),
following: storage::Vec::allocate_using(alloc),
}
}
}
impl Initialize for UserData {
type Args = AccountId;
fn initialize(&mut self, address: Self::Args) {
self.owner = address;
}
}
impl Flush for UserData {
fn flush(&mut self) {
self.peeps.flush();
self.following.flush();
}
}
/// The entire subpeep contract.
pub struct Subpeep {
/// All peeps done by all users.
peeps: storage::Vec<Peep>,
/// Database of all registered users and their data.
users: storage::HashMap<String, UserData>,
/// The allocator for newly allocated entities.
alloc: storage::alloc::CellChunkAlloc,
}
impl AllocateUsing for Subpeep {
unsafe fn allocate_using<A>(alloc: &mut A) -> Self
where
A: ink_core::storage::alloc::Allocate,
{
Self {
peeps: storage::Vec::allocate_using(alloc),
users: storage::HashMap::allocate_using(alloc),
alloc: storage::alloc::CellChunkAlloc::allocate_using(alloc),
}
}
}
impl Initialize for Subpeep {
type Args = ();
fn initialize(&mut self, _args: Self::Args) {
self.peeps.initialize(());
self.users.initialize(());
self.alloc.initialize(());
}
}
impl Flush for Subpeep {
fn flush(&mut self) {
self.peeps.flush();
self.users.flush();
self.alloc.flush();
}
}
impl Subpeep {
/// Posts a message to the global channel.
///
/// Will only ever store the latest 10 messages in the channel at most.
fn peep_global(&mut self, username: &str, message: &str) {
self.peeps.push(Peep::new(username.into(), message.into()))
}
/// Register a new user.
///
/// Returns `true` if registration was successful.
pub fn register(&mut self, username: &str) -> bool {
if self.users.get(username).is_none() {
let user_data = unsafe { UserData::allocate_using(&mut self.alloc) }
.initialize_into(ContractEnv::<DefaultSrmlTypes>::caller());
self.users.insert(username.into(), user_data);
return true
}
false
}
/// Post a message by a user.
pub fn peep_message(&mut self, username: &str, message: &str) {
// Check if the caller is registered as the peeping user.
assert_eq!(
self.users.get(username).map(|data| data.owner).unwrap(),
ContractEnv::<DefaultSrmlTypes>::caller()
);
self.peep_global(username, message);
self.users
.mutate_with(username, |user| user.peeps.push(message.into()));
}
/// Make a user follow the other.
pub fn follow(&mut self, following: &str, followed: &str) {
// Check if the caller is registered as the following user.
assert_eq!(
self.users.get(following).map(|data| data.owner).unwrap(),
ContractEnv::<DefaultSrmlTypes>::caller()
);
self.users.mutate_with(following, |following| {
following.following.push(followed.into())
});
}
}
/// Subpeep API.
#[derive(Encode, Decode)]
enum Action {
/// Register a new user.
Register { username: String },
/// Post a message by a user.
PeepMessage { username: String, message: String },
/// Make a user follow the other.
Follow { following: String, followed: String },
}
fn instantiate() -> Subpeep {
unsafe {
let mut alloc = BumpAlloc::from_raw_parts(Key([0x0; 32]));
AllocateUsing::allocate_using(&mut alloc)
}
}
#[no_mangle]
pub extern "C" fn deploy() {
instantiate().initialize_into(()).flush()
}
#[no_mangle]
pub extern "C" fn call() {
let input = ContractEnv::<DefaultSrmlTypes>::input();
let action = Action::decode(&mut &input[..]).unwrap();
let mut subpeep = instantiate();
match action {
Action::Register { username } => {
subpeep.register(&username);
}
Action::PeepMessage { username, message } => {
subpeep.peep_message(&username, &message)
}
Action::Follow {
following,
followed,
} => subpeep.follow(&following, &followed),
}
}
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
// ink! is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ink! is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ink!. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use ink_core::memory::vec::Vec;
impl Subpeep {
/// Returns all recent global posts as vector.
pub(crate) fn recent_peeps(&self, amount: usize) -> Vec<Peep> {
self.peeps.iter().rev().take(amount).cloned().collect()
}
/// Returns the `n` most recent peeps of the given user.
///
/// Returns `None` if the user does not exist.
pub(crate) fn recent_user_peeps(
&self,
amount: usize,
username: &str,
) -> Option<Vec<Peep>> {
self.users.get(username).map(|user| {
user.peeps
.iter()
.rev()
.take(amount)
.cloned()
.map(|message| Peep::new(username.into(), message))
.collect()
})
}
}
#[macro_use]
use ink_core::memory::vec;
#[test]
fn deploy() {
let subpeep = instantiate().initialize_into(());
assert_eq!(subpeep.recent_peeps(10), Vec::new());
assert_eq!(subpeep.recent_user_peeps(10, "alice"), None);
}
#[test]
fn peep_message() {
let mut subpeep = instantiate().initialize_into(());
let test_user = "Alice";
let test_message = "Hello, World!";
subpeep.register(test_user.into());
subpeep.peep_message(test_user.into(), test_message.into());
assert_eq!(
subpeep.recent_peeps(10),
vec![Peep::new(test_user.into(), test_message.into())],
);
assert_eq!(
subpeep.recent_user_peeps(10, test_user.into()),
Some(vec![Peep::new(test_user.into(), test_message.into())])
);
}
// #[test]
// fn follow_user() {