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

upgradability functionality #48

Merged
merged 20 commits into from
Sep 29, 2022
Merged
Show file tree
Hide file tree
Changes from 19 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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ version = "0.6.1"

[dependencies]
near-contract-tools-macros = {version = "=0.6.1", path = "./macros"}
near-sdk = "4.0.0"
near-sdk = {version = "4.0.0", features = ["unstable"]}
serde = "1.0.144"
serde_json = "1.0.85"
thiserror = "1.0.35"
Expand Down
6 changes: 2 additions & 4 deletions macros/src/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,10 @@ pub fn expand(meta: MigrateMeta) -> Result<TokenStream, darling::Error> {
#[#near_sdk::near_bindgen]
impl #imp #me::migrate::MigrateExternal for #ident #ty #wh {
#[init(ignore_state)]
fn migrate(args: Option<String>) -> Self {
let old_state = <#ident as #me::migrate::MigrateController>::deserialize_old_schema();

fn migrate() -> Self {
let old_state = <#ident as ::near_contract_tools::migrate::MigrateController>::deserialize_old_schema();
<#ident as #me::migrate::MigrateHook>::on_migrate(
old_state,
args,
)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod owner;
pub mod pause;
pub mod rbac;
pub mod slot;
pub mod upgrade;
pub mod utils;

pub use near_contract_tools_macros::*;
3 changes: 1 addition & 2 deletions src/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,12 @@ pub trait MigrateHook: MigrateController {
/// arguments from caller, and replaces it with the new schema.
fn on_migrate(
old_schema: <Self as MigrateController>::OldSchema,
args: Option<String>,
) -> <Self as MigrateController>::NewSchema;
}

/// Migrate-able contracts expose this trait publically
#[ext_contract(ext_migrate)]
pub trait MigrateExternal {
/// Perform the migration with optional arguments
fn migrate(args: Option<String>) -> Self;
fn migrate() -> Self;
}
12 changes: 12 additions & 0 deletions src/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,18 @@ pub trait Owner {
proposed_owner.set(new.as_ref());
}

/// Same as require_owner but as a method
fn assert_owner(&self) {
require!(
&env::predecessor_account_id()
== Self::slot_owner()
.read()
.as_ref()
.unwrap_or_else(|| env::panic_str(NO_OWNER_FAIL_MESSAGE)),
ONLY_OWNER_FAIL_MESSAGE,
);
}

/// Initializes the contract owner. Can only be called once.
///
/// Emits an `OwnerEvent::Transfer` event.
Expand Down
54 changes: 54 additions & 0 deletions src/upgrade.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//! Upgrade Mod
//!
//! Makes it easier to upgrade your contract by providing a simple interface for upgrading the code and the state of your contract.

use near_sdk::{env, sys, Gas};

use near_sdk::borsh::{BorshDeserialize, BorshSerialize};

/// Upgrade Trait
pub trait Upgrade {
/// upgrade_all - Upgrades the code and the state of the contract
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this comment accurate?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

fn upgrade_all();
}

/// Contracts may implement this trait to inject code into Upgrade functions.
pub trait UpgradeHook {
/// Executed before a upgrade call is conducted
fn on_upgrade();
}
Comment on lines +16 to +19
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this function is ever called.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea was to keep it flexible


/// Naked upgrade function which calls migrate method on the contract
pub fn upgrade<T>()
where
T: BorshDeserialize + BorshSerialize,
{
env::setup_panic_hook();

const MIGRATE_METHOD_NAME: &[u8; 7] = b"migrate";
const UPDATE_GAS_LEFTOVER: Gas = Gas(5_000_000_000_000);

unsafe {
// Load code into register 0 result from the input argument if factory call or from promise if callback.
sys::input(0);
// Create a promise batch to update current contract with code from register 0.
let promise_id = sys::promise_batch_create(
env::current_account_id().as_bytes().len() as u64,
env::current_account_id().as_bytes().as_ptr() as u64,
);
// Deploy the contract code from register 0.
sys::promise_batch_action_deploy_contract(promise_id, u64::MAX, 0);
// Call promise to migrate the state.
// Batched together to fail upgrade if migration fails.
sys::promise_batch_action_function_call(
promise_id,
MIGRATE_METHOD_NAME.len() as u64,
MIGRATE_METHOD_NAME.as_ptr() as u64,
0,
0,
0,
(env::prepaid_gas() - env::used_gas() - UPDATE_GAS_LEFTOVER).0,
);
sys::promise_return(promise_id);
}
}
4 changes: 2 additions & 2 deletions tests/macros/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ struct MyContract {
}

impl MigrateHook for MyContract {
fn on_migrate(old: Old, _args: Option<String>) -> Self {
fn on_migrate(old: Old) -> Self {
Self { bar: old.foo }
}
}
Expand All @@ -43,7 +43,7 @@ fn default_from() {

assert_eq!(old.foo, 99);

let migrated = <MyContract as MigrateExternal>::migrate(None);
let migrated = <MyContract as MigrateExternal>::migrate();

assert_eq!(migrated.bar, 99);
}
8 changes: 4 additions & 4 deletions tests/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ struct MigrateIntegration {
}

impl MigrateHook for MigrateIntegration {
fn on_migrate(old: Integration, _args: Option<String>) -> Self {
fn on_migrate(old: Integration) -> Self {
Self::require_owner();
Self::require_unpaused();

Expand Down Expand Up @@ -217,7 +217,7 @@ fn integration() {
// Perform migration
env::state_write(&c);

let mut migrated = <MigrateIntegration as MigrateExternal>::migrate(None);
let mut migrated = <MigrateIntegration as MigrateExternal>::migrate();

assert_eq!(migrated.moved_value, 25);
assert_eq!(migrated.get_value(), 25);
Expand Down Expand Up @@ -330,7 +330,7 @@ fn integration_fail_migrate_allow() {

testing_env!(context);

<MigrateIntegration as MigrateExternal>::migrate(None);
<MigrateIntegration as MigrateExternal>::migrate();
}

#[test]
Expand All @@ -348,7 +348,7 @@ fn integration_fail_migrate_paused() {

env::state_write(&c);

<MigrateIntegration as MigrateExternal>::migrate(None);
<MigrateIntegration as MigrateExternal>::migrate();
}

#[cfg(test)]
Expand Down
11 changes: 10 additions & 1 deletion workspaces-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ name = "workspaces-tests"
publish = false
version = "0.1.0"

[[bin]]
name = "upgrade_bad"

[[bin]]
name = "upgrade_old"

[[bin]]
name = "upgrade_new"

[[bin]]
name = "counter_multisig"

Expand All @@ -22,7 +31,7 @@ name = "simple_multisig"

[dependencies]
near-contract-tools = {path = "../"}
near-sdk = "4.0.0"
near-sdk = {version = "4.0.0", features = ["unstable"]}
strum = "0.24.1"
strum_macros = "0.24.3"
thiserror = "1.0.34"
Expand Down
30 changes: 30 additions & 0 deletions workspaces-tests/src/bin/upgrade_bad.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#![allow(missing_docs)]

use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
near_bindgen, PanicOnDefault,
};

pub fn main() {} // Ignore

#[derive(BorshSerialize, BorshDeserialize, PanicOnDefault)]
#[near_bindgen]
pub struct ContractBad {
pub foo: u32,
}

#[near_bindgen]
impl ContractBad {
#[init]
pub fn new() -> Self {
Self { foo: 0 }
}

pub fn increment_foo(&mut self) {
self.foo += 1;
}

pub fn get_foo(&self) -> u32 {
self.foo
}
}
45 changes: 45 additions & 0 deletions workspaces-tests/src/bin/upgrade_new.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#![allow(missing_docs)]

use near_contract_tools::{migrate::MigrateExternal, migrate::MigrateHook, Migrate};
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
near_bindgen, PanicOnDefault,
};

pub fn main() {}

#[derive(BorshSerialize, BorshDeserialize, PanicOnDefault)]
pub struct ContractOld {
pub foo: u32,
}

#[derive(BorshSerialize, BorshDeserialize, PanicOnDefault, Migrate)]
#[migrate(from = "ContractOld")]
#[near_bindgen]
pub struct ContractNew {
pub bar: u64,
}

impl MigrateHook for ContractNew {
fn on_migrate(old_schema: ContractOld) -> Self {
Self {
bar: old_schema.foo as u64,
}
}
}

#[near_bindgen]
impl ContractNew {
#[init]
pub fn new() -> Self {
Self { bar: 0 }
}

pub fn decrement_bar(&mut self) {
self.bar -= 1;
}

pub fn get_bar(&self) -> u64 {
self.bar
}
}
50 changes: 50 additions & 0 deletions workspaces-tests/src/bin/upgrade_old.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#![allow(missing_docs)]

use near_contract_tools::upgrade::{upgrade as other_upgrade, Upgrade, UpgradeHook};

use near_contract_tools::{owner::Owner, owner::OwnerExternal, Owner};

use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
env, near_bindgen, PanicOnDefault,
};
pub fn main() {}

#[derive(BorshSerialize, BorshDeserialize, PanicOnDefault, Owner)]
#[near_bindgen]
pub struct ContractOld {
pub foo: u32,
}

#[near_bindgen]
impl ContractOld {
#[init]
pub fn new() -> Self {
let mut contract = Self { foo: 0 };

Owner::init(&mut contract, &env::predecessor_account_id());
contract
}

pub fn increment_foo(&mut self) {
self.foo += 1;
}

pub fn get_foo(&self) -> u32 {
self.foo
}
}

impl UpgradeHook for ContractOld {
fn on_upgrade() {
Self::require_owner();
}
}

impl Upgrade for ContractOld {
#[no_mangle]
fn upgrade_all() {
Self::require_owner();
other_upgrade::<ContractOld>();
}
}
Loading