Skip to content

Commit

Permalink
Merge pull request #1 from matiasbenary/update-and-reorganize
Browse files Browse the repository at this point in the history
feat: update and reorganize repo
  • Loading branch information
gagdiez committed Jan 24, 2024
2 parents 1e56bc4 + 9162fb8 commit d3cd558
Show file tree
Hide file tree
Showing 60 changed files with 231 additions and 1,045 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Tests
name: Tests Contract RS
on: push
jobs:
workflows:
Expand All @@ -11,7 +11,7 @@ jobs:
- uses: actions/setup-node@v2
with:
node-version: "16"
- name: Install modules
run: yarn
- name: Run tests
run: yarn test
- name: Install and test modules
run: |
cd ./contract-rs
./test.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Tests
name: Tests Contract TS
on: push
jobs:
workflows:
Expand All @@ -11,7 +11,8 @@ jobs:
- uses: actions/setup-node@v2
with:
node-version: "16"
- name: Install modules
run: yarn
- name: Run tests
run: yarn test
- name: Install and test modules
run: |
cd ./contract-ts
yarn
yarn test
22 changes: 22 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Rust
./contract-rs/target/
./contract-rs/Cargo.lock

# TypeScript - Sandbox
./contract-ts/sandbox-ts/package-lock.json
./contract-ts/sandbox-ts/node_modules/

# TypeScript
./contract-ts/build/
./contract-ts/node_modules/
./contract-ts/sandbox-ts/node_modules/
./contract-ts/sandbox-ts/yarn.lock
./contract-ts/yarn.lock
./contract-ts/package-lock.json

# Frontend
./frontend/dist/
./frontend/node_modules/
./frontend/.parcel-cache
./frontend/yarn.lock
./frontend/package-lock.json
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# Hello World Examples

This repository contains examples of a simple Hello World smart contract in both JavaScript and Rust.
This repository contains examples of a simple Hello World smart contract in both JavaScript and Rust, and an examples of a frontend interacting with a Hello World smart contract.

## Repositories

- [Hello World JavaScript](hello-near-js)
- [Hello World Rust](hello-near-rust)
- [Hello World JavaScript](contract-ts)
- [Hello World Rust](contract-ts)
- [Hello World Frontend](frontend)
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "contract"
name = "hello_near"
version = "1.0.0"
authors = ["Near Inc <hello@near.org>"]
edition = "2021"
Expand All @@ -8,9 +8,12 @@ edition = "2021"
crate-type = ["cdylib"]

[dependencies]
near-sdk = "4.0.0"
near-sdk = "4.1.1"
uint = { version = "0.9.3", default-features = false }

[patch.crates-io]
parity-secp256k1 = { git = 'https://github.com/paritytech/rust-secp256k1.git' }

[profile.release]
codegen-units = 1
opt-level = "z"
Expand All @@ -20,4 +23,4 @@ panic = "abort"
overflow-checks = true

[workspace]
members = []
members = ["sandbox-rs"]
23 changes: 16 additions & 7 deletions hello-near-rust/contract/README.md → contract-rs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network.

```rust
const DEFAULT_MESSAGE: &str = "Hello";
const DEFAULT_GREETING: &str = "Hello";

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize)]
Expand All @@ -13,7 +13,7 @@ pub struct Contract {

impl Default for Contract {
fn default() -> Self {
Self{greeting: DEFAULT_MESSAGE.to_string()}
Self { greeting: DEFAULT_GREETING.to_string() }
}
}

Expand Down Expand Up @@ -42,14 +42,23 @@ impl Contract {

<br />

## 1. Build and Deploy the Contract
You can automatically compile and deploy the contract in the NEAR testnet by running:
## 1. Build, Test and Deploy
To build the contract you can execute the `./build.sh` script, which will in turn run:

```bash
./deploy.sh
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown --release
```

Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed:
Then, run the `./deploy.sh` script, which will in turn run:

```bash
near dev-deploy --wasmFile ./target/wasm32-unknown-unknown/release/hello_near.wasm
```

the command [`near dev-deploy`](https://docs.near.org/tools/near-cli#near-dev-deploy) automatically creates an account in the NEAR testnet, and deploys the compiled contract on it.

Once finished, check the `./neardev/dev-account` file to find the address in which the contract was deployed:

```bash
cat ./neardev/dev-account
Expand All @@ -74,7 +83,7 @@ near view <dev-account> get_greeting
## 3. Store a New Greeting
`set_greeting` changes the contract's state, for which it is a `change` method.

`Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction.
`Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. In this case, we are asking the account we created in step 1 to sign the transaction.

```bash
# Use near-cli to set a new greeting
Expand Down
3 changes: 3 additions & 0 deletions contract-rs/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown --release
7 changes: 1 addition & 6 deletions hello-near-rust/contract/deploy.sh → contract-rs/deploy.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,2 @@
#!/bin/sh

./build.sh

echo ">> Deploying contract"

near dev-deploy --wasmFile ./target/wasm32-unknown-unknown/release/contract.wasm
near dev-deploy --wasmFile ./target/wasm32-unknown-unknown/release/hello_near.wasm
4 changes: 4 additions & 0 deletions contract-rs/rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[toolchain]
channel = "1.73.0"
components = ["rustfmt"]
targets = ["wasm32-unknown-unknown"]
14 changes: 14 additions & 0 deletions contract-rs/sandbox-rs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "sandbox"
version = "1.0.0"
publish = false
edition = "2021"

[dev-dependencies]
tokio = { version = "1.18.1", features = ["full"] }
near-workspaces = "0.9.0"
serde_json = { version = "1.0", features = ["arbitrary_precision"] }

[[example]]
name = "sandbox"
path = "src/tests.rs"
65 changes: 65 additions & 0 deletions contract-rs/sandbox-rs/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use near_workspaces::{types::NearToken, Account, Contract};
use serde_json::json;
use std::{env, fs};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let wasm_arg: &str = &(env::args().nth(1).unwrap());
let wasm_filepath = fs::canonicalize(env::current_dir()?.join(wasm_arg))?;

let worker = near_workspaces::sandbox().await?;
let wasm = std::fs::read(wasm_filepath)?;
let contract = worker.dev_deploy(&wasm).await?;

// create accounts
let account = worker.dev_create_account().await?;
let alice = account
.create_subaccount("alice")
.initial_balance(NearToken::from_near(30))
.transact()
.await?
.into_result()?;

// begin tests
test_default_message(&alice, &contract).await?;
test_changes_message(&alice, &contract).await?;
Ok(())
}

async fn test_default_message(
user: &Account,
contract: &Contract,
) -> Result<(), Box<dyn std::error::Error>> {
let greeting: String = user
.call(contract.id(), "get_greeting")
.args_json(json!({}))
.transact()
.await?
.json()?;

assert_eq!(greeting, "Hello".to_string());
println!(" Passed ✅ gets default greeting");
Ok(())
}

async fn test_changes_message(
user: &Account,
contract: &Contract,
) -> Result<(), Box<dyn std::error::Error>> {
user.call(contract.id(), "set_greeting")
.args_json(json!({"greeting": "Howdy"}))
.transact()
.await?
.into_result()?;

let greeting: String = user
.call(contract.id(), "get_greeting")
.args_json(json!({}))
.transact()
.await?
.json()?;

assert_eq!(greeting, "Howdy".to_string());
println!(" Passed ✅ changes greeting");
Ok(())
}
29 changes: 16 additions & 13 deletions hello-near-rust/contract/src/lib.rs → contract-rs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Find all our documentation at https://docs.near.org
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{log, near_bindgen};

const DEFAULT_MESSAGE: &str = "Hello";
use near_sdk::env::log_str;
use near_sdk::near_bindgen;

// Define the contract structure
#[near_bindgen]
Expand All @@ -10,27 +10,24 @@ pub struct Contract {
greeting: String,
}

// Define the default, which automatically initializes the contract
impl Default for Contract {
// The default trait with which to initialize the contract
fn default() -> Self {
Self {
greeting: DEFAULT_MESSAGE.to_string(),
}
Self { greeting: "Hello".to_string() }
}
}

// Implement the contract structure
#[near_bindgen]
impl Contract {
// Public: Returns the stored greeting, defaulting to 'Hello'
// Public method - returns the greeting saved, defaulting to DEFAULT_GREETING
pub fn get_greeting(&self) -> String {
return self.greeting.clone();
}

// Public: Takes a greeting, such as 'howdy', and records it
// Public method - accepts a greeting, such as "howdy", and records it
pub fn set_greeting(&mut self, greeting: String) {
// Record a log permanently to the blockchain!
log!("Saving greeting {}", greeting);
log_str(&format!("Saving greeting: {greeting}"));
self.greeting = greeting;
}
}
Expand All @@ -47,13 +44,19 @@ mod tests {
fn get_default_greeting() {
let contract = Contract::default();
// this test did not call set_greeting so should return the default "Hello" greeting
assert_eq!(contract.get_greeting(), "Hello".to_string());
assert_eq!(
contract.get_greeting(),
"Hello".to_string()
);
}

#[test]
fn set_then_get_greeting() {
let mut contract = Contract::default();
contract.set_greeting("howdy".to_string());
assert_eq!(contract.get_greeting(), "howdy".to_string());
assert_eq!(
contract.get_greeting(),
"howdy".to_string()
);
}
}
9 changes: 9 additions & 0 deletions contract-rs/test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/sh

# unit testing
cargo test

# sandbox testing
./build.sh
cd sandbox-rs
cargo run --example sandbox "../target/wasm32-unknown-unknown/release/hello_near.wasm"
1 change: 1 addition & 0 deletions hello-near-js/contract/README.md → contract-ts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class HelloNear {
You can automatically compile and deploy the contract in the NEAR testnet by running:

```bash
npm run build
npm run deploy
```

Expand Down
23 changes: 23 additions & 0 deletions contract-ts/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "hello_near",
"version": "1.0.0",
"license": "(MIT AND Apache-2.0)",
"engines": {
"node": "16.x"
},
"type": "module",
"scripts": {
"build": "near-sdk-js build src/contract.ts build/hello_near.wasm",
"deploy": "near dev-deploy --wasmFile build/hello_near.wasm",
"test": "$npm_execpath run build && cd sandbox-ts && $npm_execpath run test -- -- ../build/hello_near.wasm",
"postinstall": "cd sandbox-ts && $npm_execpath install"
},
"dependencies": {
"near-cli": "^3.4.2",
"near-sdk-js": "1.0.0"
},
"devDependencies": {
"typescript": "^5.2.2",
"ts-morph": "^20.0.0"
}
}
9 changes: 9 additions & 0 deletions contract-ts/sandbox-ts/ava.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
require('util').inspect.defaultOptions.depth = 5; // Increase AVA's printing depth

module.exports = {
timeout: '300000',
files: ['src/*.ava.ts'],
failWithoutAssertions: false,
extensions: ['ts'],
require: ['ts-node/register'],
};
Loading

0 comments on commit d3cd558

Please sign in to comment.