Skip to content

Commit

Permalink
v1.0.0 (#115)
Browse files Browse the repository at this point in the history
* basic generic upgrade function

* adding Upgrade and UpgradeHook traits

* update to stable near-sdk-rs

* broken upgrade workspaces-tests

* fix: remove migrate argument

* Added basic failure tests for upgrade

* added owner check for upgrade tests

* not owner failure test

* removing JS scripts

* feat: adds more derives to events

* cleaned up workspaces tests for upgrade

* removed unnecessary near_bindgen

* fixed macro version issue

* fix: some comments

* chore: conciseness

* fix: repo url in Cargo.toml

* fixing naming conventions

* chore: adds build task to workspaces tests

* feat: #[derive(Nep297)] allows enums

* feat: #[event] supports enums

* fix: Owner uses borsh storage keys

* fix: upgrade workspaces version to 0.6

* fix: removes generic requirement from Event trait

* chore: convert events back to enum shape with owned values

* fix: pin Rust version to 1.64; fixes #83

* Use dtolnay/rust-toolchain (#87)

* fix: use dtolnay/rust-toolchain for GH Action

* fix: rust doc warning from README.md

* Add safety invariants to owner module docs (#75)

* Add safety invariants to owner module docs

* Add usage and safety guide for owner component

* Add module docs for pause and rbac

* Add module docs for migrate and resolve comments

* Update links

* Resolve comments

* Fix cargo docs warning

* Resolve comments

* chore: minor corrections & formatting

Co-authored-by: Jacob <encody@users.noreply.github.com>

* chore: adds .DS_Store to .gitignore

* fix: better doc links in Slot

* Default storage keys enum (#90)

* feat: default storage keys enum

* fix: doc links

* Link items in docs and other improvements (#91)

* Link items and doc improvements

* Add rbac macro attr doc and resolve comments

* Upgrade macro (#84)

* adding upgrade macro

* fix linting issues

* removing generic parameters

* fixing lint issues

* feat: new upgrade macro

* fix: tests for new upgrade macro

* fix: use Box to decrease enum size

* chore: better documentation for new upgrade modules

* fix: macro documentation

* wip: transfer to mac

* chore: workspace tests for upgrade

* upgrade multisig testing

* feat: better naming for raw functions + args structs

* chore: rename "none" hook body flag to "empty"

* chore: serialized upgrade uses PostUpgrade struct

* Upgrade macros safety docs (#96)

* chore: simplify api

Co-authored-by: Jacob <encody@users.noreply.github.com>
Co-authored-by: Ishan Bhanuka <bhanuka.ishan@gmail.com>

* feat: unstable feature flag and upgrade near_sdk -> 4.1.0

* fix: Eq derive now that Base64VecU8: Eq

* fix: remove near-sdk default features usage (#98)

* fix: remove near-sdk default features usage

* commit to re-trigger CI

* explicitly increase sdk version on test to ensure it gets used internally

* chore: Cow -> String (#100)

* Makes `Rbac` iterable (#99)

* wip: how to implement iterator

* fix: unused imports

* feat: possible rbac iter implementation

* feat: iterable rbac works

* chore: finish docs & tests

* chore: upgrade Rust to 1.65

* chore: upgrade GH Actions Rust to 1.65

* feat: update version to 0.7.0

* chore: optimize has_role (#102)

* chore: update version to 0.7.1

* Fuller Iterator implementation for Rbac iterator (#105)

* feat: fuller Iterator implementation for Rbac iterator

* feat: mut and non-mut versions of with_members_of, more Iter guarantees

* Disallows Event name collisions (#108)

* feat: disallow event name collisions, tests

* chore: clippy fix

* chore: add name change notification

* chore: versions to 0.7.2

* Change package name to `near-sdk-contract-tools` (#109)

* chore: change name

* chore: change repository details

* fix: inaccurate documentation

* chore: upgrade rust, workspaces, adds approval keys test

* fix: clippy: needless borrow

* feat: easier network specification in tests

* feat: create account test

* chore: create account test, base64 for Vec<u8> in native tx actions

* feat: delete account native transaction action test

* feat: stake action test

* feat: utils tests

* chore: unused imports

* fix: check additional fees sum

* chore: add rename warning to docs

* feat: finally, a decent prefix_key signature

* BREAKING: Internal Traits (#111)

* feat: internal trait for Rbac

* feat: Pause internal trait and separate default implementation

* fix: remove duplicate empty impl in Pause macro

* feat: Owner internal trait

* feat: Nep141 internal trait

* feat: ApprovalManager internal trait

* fix: grammar

* better test naming

* fix: double underscore warning (#113)

* feat: adds kudelski audit final doc (#114)

* chore: mention audit in README.md

* chore: version bump to v1.0.0

---------

Co-authored-by: nearken <ken.miyachi@near.foundation>
Co-authored-by: nearken <108417131+nearken@users.noreply.github.com>
Co-authored-by: Ishan Bhanuka <bhanuka.ishan@gmail.com>
Co-authored-by: Austin Abell <austinabell8@gmail.com>
  • Loading branch information
5 people authored Jun 27, 2023
1 parent aa71257 commit d2f644b
Show file tree
Hide file tree
Showing 55 changed files with 1,166 additions and 387 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.65
toolchain: 1.66
components: rustfmt
- name: Check formatting
run: >
Expand All @@ -30,7 +30,7 @@ jobs:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.65
toolchain: 1.66
components: clippy
- name: Run linter
run: cargo clippy -- -D warnings
Expand All @@ -41,7 +41,7 @@ jobs:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.65
toolchain: 1.66
- name: Run unit and integration tests
run: cargo test --workspace --exclude workspaces-tests
workspaces-test:
Expand All @@ -51,7 +51,7 @@ jobs:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.65
toolchain: 1.66
targets: wasm32-unknown-unknown
- name: Run workspaces tests
run: >
Expand Down
10 changes: 5 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ categories = ["wasm", "cryptography::cryptocurrencies"]
description = """
Helpful functions and macros for developing smart contracts on NEAR Protocol.
"""
documentation = "https://docs.rs/near-contract-tools"
documentation = "https://docs.rs/near-sdk-contract-tools"
edition = "2021"
license = "GPL-3.0"
name = "near-contract-tools"
repository = "https://github.com/NEARFoundation/near-contract-tools"
version = "0.7.2"
name = "near-sdk-contract-tools"
repository = "https://github.com/NEARFoundation/near-sdk-contract-tools"
version = "1.0.0"

[dependencies]
near-contract-tools-macros = {version = "=0.7.2", path = "./macros"}
near-sdk = {version = "4.1.0", default-features = false}
near-sdk-contract-tools-macros = {version = "=1.0.0", path = "./macros"}
serde = "1.0.144"
serde_json = "1.0.85"
thiserror = "1.0.35"
Expand Down
30 changes: 17 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# This package will be renamed to [`near-sdk-contract-tools`](https://crates.io/crates/near-sdk-contract-tools)

# near-contract-tools
# near-sdk-contract-tools

> Helpful functions and macros for developing smart contracts on NEAR Protocol.
Expand All @@ -17,15 +15,17 @@ Not to be confused with [`near-contract-standards`](https://crates.io/crates/nea

**WARNING:** This is still early software, and there may be breaking changes between versions. I'll try my best to keep the docs & changelogs up-to-date. Don't hesitate to create an issue if find anything wrong.

(Formerly known as [`near-contract-tools`](https://crates.io/crates/near-contract-tools).)

## Benefits

- requires fewer lines of code
- Without near-contract-tools, implementing fungible token events (mint, transfer, and burn) takes ~100 lines of code. Using near-contract-tools, you can [implement them in ~40 lines](https://youtu.be/kJzes_UP5j0?t=1058).
- Without near-sdk-contract-tools, implementing fungible token events (mint, transfer, and burn) takes ~100 lines of code. Using near-sdk-contract-tools, you can [implement them in ~40 lines](https://youtu.be/kJzes_UP5j0?t=1058).
- is more readable
- follows a consistent pattern
- Every time you use the events macro, it will [implement events in the same way](https://youtu.be/kJzes_UP5j0?t=1150). Without it, you’d need to ensure that `emit`, `emit_many`, etc all work (and work the same).
- is more thorough
- near-contract-standards is also not implementing traits, so that’s another improvement that near-contract-tools offers.
- near-contract-standards is also not implementing traits, so that’s another improvement that near-sdk-contract-tools offers.

You can think of this collection of common tools and patterns (mostly in the form of [derive macros](https://doc.rust-lang.org/reference/procedural-macros.html#derive-macros)) as sort of an OpenZeppelin for NEAR.

Expand All @@ -34,7 +34,7 @@ You can think of this collection of common tools and patterns (mostly in the for
```text
rustup target add wasm32-unknown-unknown
cargo init
cargo add near-contract-tools
cargo add near-sdk-contract-tools
cargo add near-sdk
# https://raen.dev/guide/intro/getting-set-up.html
cargo install raen
Expand Down Expand Up @@ -80,7 +80,7 @@ See also: [the full integration tests](tests/macros/mod.rs).

```rust
use near_sdk::{near_bindgen, AccountId};
use near_contract_tools::{owner::Owner, Owner};
use near_sdk_contract_tools::{owner::Owner, Owner};

#[derive(Owner)]
#[near_bindgen]
Expand Down Expand Up @@ -124,7 +124,7 @@ fn own_accept_owner(&mut self);
The `#[event]` macro can be applied to structs or enums.

```rust
use near_contract_tools::{event, standard::nep297::Event};
use near_sdk_contract_tools::{event, standard::nep297::Event};

#[event(standard = "nft", version = "1.0.0")]
pub struct MintEvent {
Expand All @@ -146,7 +146,7 @@ e.emit();
To create a contract that is compatible with the NEP-141 and NEP-148 standards, that emits standard-compliant (NEP-141, NEP-297) events.

```rust
use near_contract_tools::FungibleToken;
use near_sdk_contract_tools::FungibleToken;
use near_sdk::near_bindgen;

#[derive(FungibleToken)]
Expand All @@ -169,7 +169,7 @@ Standalone macros for each individual standard also exist.
One may wish to combine the features of multiple macros in one contract. All of the macros are written such that they will work in a standalone manner, so this should largely work without issue. However, sometimes it may be desirable for the macros to work in _combination_ with each other. For example, to make a fungible token pausable, use the fungible token hooks to require that a contract be unpaused before making a token transfer:

```rust
use near_contract_tools::{
use near_sdk_contract_tools::{
pause::Pause,
standard::nep141::{Nep141Hook, Nep141Transfer},
FungibleToken, Pause,
Expand All @@ -192,13 +192,13 @@ Note: Hooks can be disabled using `#[nep141(no_hooks)]` or `#[fungible_token(no_

### Custom Crates

If you are a library developer, have modified a crate that one of the `near-contract-tools` macros uses (like `serde` or `near-sdk`), or are otherwise using a crate under a different name, you can specify crate names in macros like so:
If you are a library developer, have modified a crate that one of the `near-sdk-contract-tools` macros uses (like `serde` or `near-sdk`), or are otherwise using a crate under a different name, you can specify crate names in macros like so:

```rust, ignore
#[event(
// ...
crate = "near_contract_tools",
macros = "near_contract_tools_macros",
crate = "near_sdk_contract_tools",
macros = "near_sdk_contract_tools_macros",
serde = "serde",
)]
// ...
Expand Down Expand Up @@ -255,6 +255,10 @@ See [src/slot.rs](src/slot.rs) They are very thin wrappers over a storage key. I

First, run `git config core.hooksPath hooks/` to install the hooks of this directory (without affecting how git hooks work for other projects).

## Audit

This library has been [audited](./documents/NEAR%20Contract%20Tools%20-%20Final%20-%2005.05.2023.pdf) by [Kudelski Security](https://www.kudelskisecurity.com/).

## Authors

- Jacob Lindahl [@sudo_build](https://twitter.com/sudo_build)
Binary file not shown.
6 changes: 3 additions & 3 deletions macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
authors = ["Jacob Lindahl <jacob@near.foundation>"]
categories = ["wasm"]
description = """
Macros for `near-contract-tools`
Macros for `near-sdk-contract-tools`
"""
edition = "2021"
license = "GPL-3.0"
name = "near-contract-tools-macros"
version = "0.7.2"
name = "near-sdk-contract-tools-macros"
version = "1.0.0"

[dependencies]
base64 = "0.13.0"
Expand Down
2 changes: 1 addition & 1 deletion macros/src/approval/simple_multisig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub fn expand(meta: SimpleMultisigMeta) -> Result<TokenStream, darling::Error> {
});

Ok(quote! {
impl #imp #me::approval::ApprovalManager<
impl #imp #me::approval::ApprovalManagerInternal<
#action,
#me::approval::simple_multisig::ApprovalState,
#me::approval::simple_multisig::Configuration<Self>,
Expand Down
28 changes: 21 additions & 7 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Macros for near-contract-tools
//! Macros for near-sdk-contract-tools.

use darling::{FromDeriveInput, FromMeta};
use proc_macro::TokenStream;
Expand All @@ -14,11 +14,11 @@ mod standard;
mod upgrade;

fn default_crate_name() -> syn::Path {
syn::parse_str("::near_contract_tools").unwrap()
syn::parse_str("::near_sdk_contract_tools").unwrap()
}

fn default_macros() -> syn::Path {
syn::parse_str("::near_contract_tools").unwrap()
syn::parse_str("::near_sdk_contract_tools").unwrap()
}

fn default_near_sdk() -> syn::Path {
Expand Down Expand Up @@ -59,6 +59,18 @@ where
/// - `SHOUTY_SNAKE_CASE`
/// - `SHOUTY-KEBAB-CASE`
/// - `Title Case`
///
/// # Warning
///
/// Rename strategies are provided for convenience, and the actual string
/// transformation is delegated to the [`heck`](https://crates.io/crates/heck)
/// crate. It _is_ possible that unexpected name transformations or collisions
/// may occur, but it is _extremely unlikely_ if reasonable Rust naming
/// conventions are followed.
///
/// For example, `"HelloWorld"`, `"hello_world"`, and `"hello__world"`, when
/// snake-case-ified, are `"hello_world"`, so if you happened to name distinct
/// events thusly, the transformed names would collide.
#[proc_macro_derive(Nep297, attributes(nep297))]
pub fn derive_nep297(input: TokenStream) -> TokenStream {
make_derive(input, standard::nep297::expand)
Expand All @@ -85,8 +97,8 @@ pub fn derive_pause(input: TokenStream) -> TokenStream {

/// Adds role-based access control. No external methods are exposed.
///
/// The roles prefix must be specify a type using #[rbac(roles = "MyRoles")].
/// Typically "MyRoles" is an enum and it's variants are the different role
/// The roles prefix can be specified using `#[rbac(roles = "MyRoles")]`.
/// Typically `"MyRoles"` is an enum and its variants are the different role
/// names.
///
/// The storage key prefix for the fields can be optionally specified (default:
Expand All @@ -98,7 +110,7 @@ pub fn derive_rbac(input: TokenStream) -> TokenStream {

/// Adds NEP-141 fungible token core functionality to a contract. Exposes
/// `ft_*` functions to the public blockchain, implements internal controller
/// and receiver functionality (see: `near_contract_tools::standard::nep141`).
/// and receiver functionality (see: [`near_sdk_contract_tools::standard::nep141`]).
///
/// The storage key prefix for the fields can be optionally specified (default:
/// `"~$141"`) using `#[nep141(storage_key = "<expression>")]`.
Expand Down Expand Up @@ -170,7 +182,9 @@ pub fn derive_simple_multisig(input: TokenStream) -> TokenStream {
make_derive(input, approval::simple_multisig::expand)
}

/// Smart `#[event]` macro
/// Smart `#[event]` macro.
///
/// See documentation on the [`derive@Nep297`] derive macro for more details.
#[proc_macro_attribute]
pub fn event(attr: TokenStream, item: TokenStream) -> TokenStream {
let attr = parse_macro_input!(attr as AttributeArgs);
Expand Down
12 changes: 6 additions & 6 deletions macros/src/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,36 +39,36 @@ pub fn expand(meta: OwnerMeta) -> Result<TokenStream, darling::Error> {
});

Ok(quote! {
impl #imp #me::owner::Owner for #ident #ty #wher {
impl #imp #me::owner::OwnerInternal for #ident #ty #wher {
#root
}

#[#near_sdk::near_bindgen]
impl #imp #me::owner::OwnerExternal for #ident #ty #wher {
fn own_get_owner(&self) -> Option<#near_sdk::AccountId> {
<Self as #me::owner::Owner>::slot_owner().read()
<Self as #me::owner::OwnerInternal>::slot_owner().read()
}

fn own_get_proposed_owner(&self) -> Option<#near_sdk::AccountId> {
<Self as #me::owner::Owner>::slot_proposed_owner().read()
<Self as #me::owner::OwnerInternal>::slot_proposed_owner().read()
}

#[payable]
fn own_renounce_owner(&mut self) {
#near_sdk::assert_one_yocto();
self.renounce_owner()
#me::owner::Owner::renounce_owner(self);
}

#[payable]
fn own_propose_owner(&mut self, account_id: Option<#near_sdk::AccountId>) {
#near_sdk::assert_one_yocto();
self.propose_owner(account_id);
#me::owner::Owner::propose_owner(self, account_id);
}

#[payable]
fn own_accept_owner(&mut self) {
#near_sdk::assert_one_yocto();
self.accept_owner();
#me::owner::Owner::accept_owner(self);
}
}
})
Expand Down
2 changes: 1 addition & 1 deletion macros/src/pause.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub fn expand(meta: PauseMeta) -> Result<TokenStream, darling::Error> {
});

Ok(quote! {
impl #imp #me::pause::Pause for #ident #ty #wher {
impl #imp #me::pause::PauseInternal for #ident #ty #wher {
#root
}

Expand Down
2 changes: 1 addition & 1 deletion macros/src/rbac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub fn expand(meta: RbacMeta) -> Result<TokenStream, darling::Error> {
});

Ok(quote! {
impl #imp #me::rbac::Rbac for #ident #ty #wher {
impl #imp #me::rbac::RbacInternal for #ident #ty #wher {
type Role = #roles;

#root
Expand Down
2 changes: 1 addition & 1 deletion macros/src/standard/nep141.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub fn expand(meta: Nep141Meta) -> Result<TokenStream, darling::Error> {
});

Ok(quote! {
impl #imp #me::standard::nep141::Nep141Controller for #ident #ty #wher {
impl #imp #me::standard::nep141::Nep141ControllerInternal for #ident #ty #wher {
#root
}

Expand Down
4 changes: 2 additions & 2 deletions macros/src/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ impl FromMeta for HookBody {
.and_then(|s| syn::parse_str::<Expr>(s.as_str()).ok())
.map(|e| HookBody::Role(Box::new(e)))
.ok_or_else(|| {
darling::Error::custom(&format!(
darling::Error::custom(format!(
r#"Invalid value "{value}", expected "empty", "owner", or "role(...)""#,
))
})
Expand All @@ -51,7 +51,7 @@ impl FromMeta for Serializer {
match value {
"borsh" => Ok(Self::Borsh),
"jsonbase64" => Ok(Self::JsonBase64),
_ => Err(darling::Error::custom(&format!(
_ => Err(darling::Error::custom(format!(
r#"Invalid value "{value}", expected "borsh" or "jsonbase64""#
))),
}
Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.65"
channel = "1.66"
Loading

0 comments on commit d2f644b

Please sign in to comment.