Skip to content

Commit

Permalink
Merge pull request #448 from near/austin/account_id_newtype
Browse files Browse the repository at this point in the history
refactor(types): change account id to newtype and deprecate ValidAccountId
  • Loading branch information
mikedotexe authored Jul 12, 2021
2 parents 5cc2a33 + 3e24240 commit e4abb73
Show file tree
Hide file tree
Showing 73 changed files with 523 additions and 549 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
* This removes the re-export of `wee_alloc` because if this feature is enabled, the allocator will already be set.
* Deprecates `setup_alloc!` macro as this will be setup by default, as long as the `wee_alloc` feature is not specifically disabled. In this case, the allocator can be overriden to a custom one or set manually if intended.
* Update `TreeMap` iterator implementation to avoid unnecessary storage reads. [PR 428](https://github.com/near/near-sdk-rs/pull/428).
* Update `AccountId` to be a newtype with merged functionality from `ValidAccountId`
* Removes `ValidAccountId` to avoid having multiple types for account IDs
* This type will have `ValidAccountId`'s JSON (de)serialization and the borsh serialization will be equivalent to what it was previously
* Initializes default for `BLOCKCHAIN_INTERFACE` to avoid requiring to initialize testing environment for tests that don't require custom blockchain interface configuration
* This default only affects outside of `wasm32` environments and is optional/backwards compatible

Expand Down
16 changes: 8 additions & 8 deletions HELP.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,16 +320,16 @@ impl Contract {
}

/// Change method. Changes the state, and then saves the new state internally.
pub fn set_owner_id(&mut self, new_owner_id: ValidAccountId) {
self.owner_id = new_owner_id.into();
pub fn set_owner_id(&mut self, new_owner_id: AccountId) {
self.owner_id = new_owner_id;
}

/// View method that "modifies" state, for code structure or computational
/// efficiency reasons. Changes state in-memory, but does NOT save the new
/// state. If called internally by a change method, WILL result in updated
/// contract state.
pub fn update_stats(&self, account_id: ValidAccountId, score: U64) -> Account {
let account = self.accounts.get(account_id).expect("account not found");
pub fn update_stats(&self, account_id: AccountId, score: U64) -> Account {
let account = self.accounts.get(&account_id).expect("account not found");
account.total += score;
account
}
Expand Down Expand Up @@ -427,8 +427,8 @@ E.g.
```rust
#[near_bindgen]
impl Contract {
pub fn withdraw_100(&mut self, receiver_id: ValidAccountId) -> Promise {
Promise::new(receiver_id.into()).transfer(100)
pub fn withdraw_100(&mut self, receiver_id: AccountId) -> Promise {
Promise::new(receiver_id).transfer(100)
}
}
```
Expand Down Expand Up @@ -641,8 +641,8 @@ impl Contract {
self.status_updates.remove(&env::predecessor_account_id());
}

pub fn get_status(&self, account_id: ValidAccountId) -> Option<String> {
self.status_updates.get(account_id.as_ref())
pub fn get_status(&self, account_id: AccountId) -> Option<String> {
self.status_updates.get(&account_id)
}
}
```
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use near_sdk::{near_bindgen, env};
#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct StatusMessage {
records: HashMap<String, String>,
records: HashMap<AccountId, String>,
}

#[near_bindgen]
Expand All @@ -54,7 +54,7 @@ impl StatusMessage {
self.records.insert(account_id, message);
}

pub fn get_status(&self, account_id: String) -> Option<String> {
pub fn get_status(&self, account_id: AccountId) -> Option<String> {
self.records.get(&account_id).cloned()
}
}
Expand Down
Binary file not shown.
11 changes: 6 additions & 5 deletions examples/cross-contract-high-level/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use near_sdk::{
// callback_vec,
log,
near_bindgen,
AccountId,
Promise,
PromiseOrValue,
};
Expand Down Expand Up @@ -37,12 +38,12 @@ pub trait ExtCrossContract {
#[ext_contract]
pub trait ExtStatusMessage {
fn set_status(&mut self, message: String);
fn get_status(&self, account_id: String) -> Option<String>;
fn get_status(&self, account_id: AccountId) -> Option<String>;
}

#[near_bindgen]
impl CrossContract {
pub fn deploy_status_message(&self, account_id: String, amount: U128) {
pub fn deploy_status_message(&self, account_id: AccountId, amount: U128) {
Promise::new(account_id)
.create_account()
.transfer(amount.0)
Expand Down Expand Up @@ -119,10 +120,10 @@ impl CrossContract {
// self.internal_merge(arrs.pop().unwrap(), arrs.pop().unwrap())
// }

pub fn simple_call(&mut self, account_id: String, message: String) {
pub fn simple_call(&mut self, account_id: AccountId, message: String) {
ext_status_message::set_status(message, &account_id, 0, env::prepaid_gas() / 2);
}
pub fn complex_call(&mut self, account_id: String, message: String) -> Promise {
pub fn complex_call(&mut self, account_id: AccountId, message: String) -> Promise {
// 1) call status_message to record a message from the signer.
// 2) call status_message to retrieve the message of the signer.
// 3) return that message as its own result.
Expand All @@ -139,7 +140,7 @@ impl CrossContract {
)
}

pub fn transfer_money(&mut self, account_id: String, amount: u64) {
pub fn transfer_money(&mut self, account_id: AccountId, amount: u64) {
Promise::new(account_id).transfer(amount as u128);
}
}
2 changes: 1 addition & 1 deletion examples/cross-contract-high-level/tests/general.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn init() -> (UserAccount, ContractAccount<CrossContractContract>) {
fn test_sim_transfer() {
let (master_account, contract) = init();

let status_id = "status".to_string();
let status_id: near_sdk::AccountId = "status".parse().unwrap();
let status_amt = to_yocto("35");
call!(
master_account,
Expand Down
Binary file not shown.
12 changes: 6 additions & 6 deletions examples/cross-contract-low-level/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::json_types::U128;
use near_sdk::serde_json::{self, json};
use near_sdk::{env, near_bindgen, PromiseResult};
use near_sdk::{env, near_bindgen, AccountId, PromiseResult};

near_sdk::setup_alloc!();

Expand All @@ -22,7 +22,7 @@ impl Default for CrossContract {

#[near_bindgen]
impl CrossContract {
pub fn deploy_status_message(&self, account_id: String, amount: U128) {
pub fn deploy_status_message(&self, account_id: AccountId, amount: U128) {
let promise_idx = env::promise_batch_create(&account_id);
env::promise_batch_action_create_account(promise_idx);
env::promise_batch_action_transfer(promise_idx, amount.0);
Expand Down Expand Up @@ -103,16 +103,16 @@ impl CrossContract {
result
}

pub fn simple_call(&mut self, account_id: String, message: String) {
pub fn simple_call(&mut self, account_id: AccountId, message: String) {
env::promise_create(
account_id.clone(),
account_id,
b"set_status",
json!({ "message": message }).to_string().as_bytes(),
0,
SINGLE_CALL_GAS,
);
}
pub fn complex_call(&mut self, account_id: String, message: String) {
pub fn complex_call(&mut self, account_id: AccountId, message: String) {
// 1) call status_message to record a message from the signer.
// 2) check that the promise succeed
// 3) call status_message to retrieve the message of the signer.
Expand Down Expand Up @@ -154,7 +154,7 @@ impl CrossContract {
};
}

pub fn transfer_money(&mut self, account_id: String, amount: u64) {
pub fn transfer_money(&mut self, account_id: AccountId, amount: u64) {
let promise_idx = env::promise_batch_create(&account_id);
env::promise_batch_action_transfer(promise_idx, amount as u128);
}
Expand Down
8 changes: 5 additions & 3 deletions examples/cross-contract-low-level/tests/general.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use near_sdk::AccountId;
use near_sdk_sim::{
call, deploy, init_simulator, to_yocto, view, ContractAccount, UserAccount, DEFAULT_GAS,
STORAGE_AMOUNT,
Expand Down Expand Up @@ -25,7 +26,8 @@ fn init(
bytes: &TOKEN_WASM_BYTES,
signer_account: master_account
};
let alice = master_account.create_user("alice".to_string(), initial_balance);
let alice =
master_account.create_user(AccountId::new_unchecked("alice".to_string()), initial_balance);
(master_account, contract_account, alice)
}

Expand All @@ -39,7 +41,7 @@ fn check_promise() {
let (master_account, contract, _alice) = init(to_yocto("10000"));
let res = view!(contract.promise_checked());
assert_eq!(res.unwrap_json::<bool>(), false);
let status_id = "status".to_string();
let status_id: near_sdk::AccountId = "status".parse().unwrap();
let status_amt = to_yocto("35");
let res = call!(
master_account,
Expand All @@ -64,7 +66,7 @@ fn test_sim_transfer() {
// let transfer_amount = to_yocto("100");
let initial_balance = to_yocto("100000");
let (master_account, contract, _alice) = init(initial_balance);
let status_id = "status".to_string();
let status_id: near_sdk::AccountId = "status".parse().unwrap();
let status_amt = to_yocto("35");
let res = call!(
master_account,
Expand Down
2 changes: 1 addition & 1 deletion examples/fungible-token/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

56 changes: 14 additions & 42 deletions examples/fungible-token/examples/heavy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ use defi::*;
/// Import the generated proxy contract
use fungible_token::ContractContract as FtContract;

use std::convert::TryInto;

near_sdk_sim::lazy_static_include::lazy_static_include_bytes! {
TOKEN_WASM_BYTES => "res/fungible_token.wasm",
DEFI_WASM_BYTES => "res/defi.wasm",
Expand All @@ -19,12 +17,7 @@ const DEFI_ID: &str = "defi";

fn init(
initial_balance: u128,
) -> (
UserAccount,
ContractAccount<FtContract>,
ContractAccount<DeFiContract>,
UserAccount,
) {
) -> (UserAccount, ContractAccount<FtContract>, ContractAccount<DeFiContract>, UserAccount) {
let root = init_simulator(None);
// uses default values for deposit and gas
let ft = deploy!(
Expand All @@ -37,23 +30,23 @@ fn init(
// User deploying the contract,
signer_account: root,
// init method
init_method:
init_method:
new_default_meta(
root.account_id().try_into().unwrap(),
root.account_id(),
initial_balance.into()
)
);
let alice = root.create_user("alice".to_string(), to_yocto("100"));
let alice = root.create_user(AccountId::new_unchecked("alice".to_string()), to_yocto("100"));
register_user(&ft, &alice);

let id = AccountId::new_unchecked(FT_ID.to_string());

let defi = deploy!(
contract: DeFiContract,
contract_id: DEFI_ID,
bytes: &DEFI_WASM_BYTES,
signer_account: root,
init_method: new(
FT_ID.try_into().unwrap()
)
init_method: new(id)
);

(root, ft, defi, alice)
Expand All @@ -64,7 +57,7 @@ fn init(
fn register_user(contract: &ContractAccount<FtContract>, user: &UserAccount) {
call!(
user,
contract.storage_deposit(Some(user.account_id().try_into().unwrap()), None),
contract.storage_deposit(Some(user.account_id()), None),
deposit = env::storage_byte_cost() * 125
)
.assert_success();
Expand All @@ -78,47 +71,26 @@ fn transfer(
amount: u128,
contract: &ContractAccount<FtContract>,
) {
call!(
from,
contract.ft_transfer(to.try_into().unwrap(), amount.into(), None),
deposit = TRANSFER_DEPOSIT
)
.assert_success()
call!(from, contract.ft_transfer(to, amount.into(), None), deposit = TRANSFER_DEPOSIT)
.assert_success()
}

fn main() {
let iterations: u64 = if std::env::args().len() >= 2 {
(&std::env::args().collect::<Vec<String>>()[1])
.parse()
.unwrap()
std::env::args().nth(1).unwrap().parse().unwrap()
} else {
10
};
let transfer_amount = to_yocto("1");
let initial_balance = to_yocto("10000000000");
let (master_account, contract, _defi, alice) = init(initial_balance);
transfer(
&master_account,
alice.account_id(),
transfer_amount,
&contract,
);
transfer(&master_account, alice.account_id(), transfer_amount, &contract);
let now = std::time::Instant::now();
for i in 0..iterations {
if i % 2 == 0 {
transfer(
&master_account,
alice.account_id(),
transfer_amount,
&contract,
);
transfer(&master_account, alice.account_id(), transfer_amount, &contract);
} else {
transfer(
&alice,
master_account.account_id(),
transfer_amount,
&contract,
);
transfer(&alice, master_account.account_id(), transfer_amount, &contract);
}
}
let elapsed = now.elapsed().as_millis();
Expand Down
17 changes: 6 additions & 11 deletions examples/fungible-token/ft/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use near_contract_standards::fungible_token::metadata::{
use near_contract_standards::fungible_token::FungibleToken;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LazyOption;
use near_sdk::json_types::{ValidAccountId, U128};
use near_sdk::json_types::U128;
use near_sdk::{
env, log, near_bindgen, AccountId, Balance, BorshStorageKey, PanicOnDefault, PromiseOrValue,
};
Expand All @@ -48,7 +48,7 @@ impl Contract {
/// Initializes the contract with the given total supply owned by the given `owner_id` with
/// default metadata (for example purposes only).
#[init]
pub fn new_default_meta(owner_id: ValidAccountId, total_supply: U128) -> Self {
pub fn new_default_meta(owner_id: AccountId, total_supply: U128) -> Self {
Self::new(
owner_id,
total_supply,
Expand All @@ -67,19 +67,15 @@ impl Contract {
/// Initializes the contract with the given total supply owned by the given `owner_id` with
/// the given fungible token metadata.
#[init]
pub fn new(
owner_id: ValidAccountId,
total_supply: U128,
metadata: FungibleTokenMetadata,
) -> Self {
pub fn new(owner_id: AccountId, total_supply: U128, metadata: FungibleTokenMetadata) -> Self {
assert!(!env::state_exists(), "Already initialized");
metadata.assert_valid();
let mut this = Self {
token: FungibleToken::new(StorageKey::FungibleToken),
metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)),
};
this.token.internal_register_account(owner_id.as_ref());
this.token.internal_deposit(owner_id.as_ref(), total_supply.into());
this.token.internal_register_account(&owner_id);
this.token.internal_deposit(&owner_id, total_supply.into());
this
}

Expand All @@ -105,14 +101,13 @@ impl FungibleTokenMetadataProvider for Contract {
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use near_sdk::test_utils::{accounts, VMContextBuilder};
use near_sdk::MockedBlockchain;
use near_sdk::{testing_env, Balance};

use super::*;

const TOTAL_SUPPLY: Balance = 1_000_000_000_000_000;

fn get_context(predecessor_account_id: ValidAccountId) -> VMContextBuilder {
fn get_context(predecessor_account_id: AccountId) -> VMContextBuilder {
let mut builder = VMContextBuilder::new();
builder
.current_account_id(accounts(0))
Expand Down
Binary file modified examples/fungible-token/res/defi.wasm
Binary file not shown.
Binary file modified examples/fungible-token/res/fungible_token.wasm
Binary file not shown.
Loading

0 comments on commit e4abb73

Please sign in to comment.