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

refactor(types): change account id to newtype and deprecate ValidAccountId #448

Merged
merged 31 commits into from
Jul 12, 2021
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
3ad2d55
refactor(types): change account id to newtype and deprecate ValidAcco…
austinabell Jun 24, 2021
07c1fec
update contract standards
austinabell Jun 24, 2021
26a9f8d
update sim and tests
austinabell Jun 24, 2021
51c2782
fmt
austinabell Jun 24, 2021
05e57ed
fix examples and refactor sim usage
austinabell Jun 24, 2021
17475b0
remove ValidAccountId
austinabell Jun 24, 2021
3e858be
fix examples
austinabell Jun 24, 2021
2c4e449
delete commented out mod
austinabell Jun 24, 2021
7cae165
Merge branch 'master' into austin/account_id_newtype
mikedotexe Jun 24, 2021
71fa951
fix typo
austinabell Jun 25, 2021
d36276c
update docs
austinabell Jun 25, 2021
082c5d5
changelog
austinabell Jun 25, 2021
148d39a
Merge branch 'master' into austin/account_id_newtype
mikedotexe Jun 28, 2021
f007efd
Merge branch 'master' into austin/account_id_newtype
mikedotexe Jul 4, 2021
a409a25
update account id initializations
austinabell Jul 5, 2021
b5388f6
remove generic use of account id from promise calls
austinabell Jul 5, 2021
3bf1cae
cleanup account id code
austinabell Jul 5, 2021
a0f4c25
auxiliary tweaks and remove into_string method
austinabell Jul 5, 2021
8e704b9
other relevant cleanup
austinabell Jul 5, 2021
e7112fc
add test for borsh serialize
austinabell Jul 5, 2021
1376e92
remove TryFrom<&str> and add borsh deserialize validation
austinabell Jul 6, 2021
e8e06dd
fix breakages
austinabell Jul 6, 2021
36e6708
avoid re-allocation by not parsing from str
austinabell Jul 6, 2021
28f1d39
remove conversion from bytes to account id
austinabell Jul 6, 2021
d38e251
updated wasm blobs
austinabell Jul 6, 2021
a13c8f2
remove validations to keep consistent with previous version
austinabell Jul 6, 2021
11c42fb
remove other unnecessary conversions
austinabell Jul 6, 2021
afbc330
Merge branch 'master' of github.com:near/near-sdk-rs into austin/acco…
austinabell Jul 7, 2021
f22bdb5
update mission control example
austinabell Jul 7, 2021
3d050be
remove account id error kind and nit
austinabell Jul 9, 2021
3e24240
prohibit error creation manually
austinabell Jul 9, 2021
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
10 changes: 5 additions & 5 deletions HELP.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,15 +320,15 @@ 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) {
pub fn set_owner_id(&mut self, new_owner_id: AccountId) {
self.owner_id = new_owner_id.into();
austinabell marked this conversation as resolved.
Show resolved Hide resolved
}

/// 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 {
pub fn update_stats(&self, account_id: AccountId, score: U64) -> Account {
let account = self.accounts.get(account_id).expect("account not found");
austinabell marked this conversation as resolved.
Show resolved Hide resolved
account.total += score;
account
Expand Down Expand Up @@ -427,7 +427,7 @@ E.g.
```rust
#[near_bindgen]
impl Contract {
pub fn withdraw_100(&mut self, receiver_id: ValidAccountId) -> Promise {
pub fn withdraw_100(&mut self, receiver_id: AccountId) -> Promise {
Promise::new(receiver_id.into()).transfer(100)
austinabell marked this conversation as resolved.
Show resolved Hide resolved
}
}
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,
Copy link
Contributor

Choose a reason for hiding this comment

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

Why do we need cross_contract_high_level.wasm and cross_contract_low_level.wasm blobs here, and why they grew by several kbs?

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.
10 changes: 5 additions & 5 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
6 changes: 3 additions & 3 deletions examples/cross-contract-low-level/tests/general.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ 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("alice".parse().unwrap(), initial_balance);
(master_account, contract_account, alice)
}

Expand All @@ -39,7 +39,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();
Copy link
Contributor

Choose a reason for hiding this comment

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

I wonder if these unwraps are to blame for additional bloat?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'll check around the code size in a bit. Committing the wasm files was a mistake and how I built them also causes a difference on master. Definitely want to look into making it part of the CI in some way to check differences

Copy link
Contributor

Choose a reason for hiding this comment

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

Agreed, and as we discussed in this morning's meeting, this is capture in #465

let status_amt = to_yocto("35");
let res = call!(
master_account,
Expand All @@ -64,7 +64,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.

15 changes: 4 additions & 11 deletions examples/fungible-token/examples/heavy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,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,13 +32,13 @@ fn init(
// User deploying the contract,
signer_account: root,
// init method
init_method:
init_method:
new_default_meta(
root.account_id().try_into().unwrap(),
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 defi = deploy!(
Expand Down Expand Up @@ -88,9 +83,7 @@ fn transfer(

fn main() {
let iterations: u64 = if std::env::args().len() >= 2 {
(&std::env::args().collect::<Vec<String>>()[1])
.parse()
.unwrap()
(&std::env::args().collect::<Vec<String>>()[1]).parse().unwrap()
austinabell marked this conversation as resolved.
Show resolved Hide resolved
} else {
10
};
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.
6 changes: 3 additions & 3 deletions examples/fungible-token/test-contract-defi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Some hypothetical DeFi contract that will do smart things with the transferred t
*/
use near_contract_standards::fungible_token::receiver::FungibleTokenReceiver;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::json_types::{ValidAccountId, U128};
use near_sdk::json_types::U128;
use near_sdk::{
env, ext_contract, log, near_bindgen, setup_alloc, AccountId, Balance, Gas, PanicOnDefault,
PromiseOrValue,
Expand Down Expand Up @@ -37,7 +37,7 @@ trait ValueReturnTrait {
#[near_bindgen]
impl DeFi {
#[init]
pub fn new(fungible_token_account_id: ValidAccountId) -> Self {
pub fn new(fungible_token_account_id: AccountId) -> Self {
assert!(!env::state_exists(), "Already initialized");
Self { fungible_token_account_id: fungible_token_account_id.into() }
}
Expand All @@ -50,7 +50,7 @@ impl FungibleTokenReceiver for DeFi {
/// value_please will attempt to parse `msg` as an integer and return a U128 version of it
fn ft_on_transfer(
&mut self,
sender_id: ValidAccountId,
sender_id: AccountId,
amount: U128,
msg: String,
) -> PromiseOrValue<U128> {
Expand Down
6 changes: 3 additions & 3 deletions examples/fungible-token/tests/sim/no_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn simulate_simple_transfer() {
ft.account_id(),
"ft_transfer",
&json!({
"receiver_id": alice.valid_account_id(),
"receiver_id": alice.account_id(),
"amount": U128::from(transfer_amount)
})
.to_string()
Expand All @@ -40,7 +40,7 @@ fn simulate_simple_transfer() {
ft.account_id(),
"ft_balance_of",
&json!({
"account_id": root.valid_account_id()
"account_id": root.account_id()
})
.to_string()
.into_bytes(),
Expand All @@ -51,7 +51,7 @@ fn simulate_simple_transfer() {
ft.account_id(),
"ft_balance_of",
&json!({
"account_id": alice.valid_account_id()
"account_id": alice.account_id()
})
.to_string()
.into_bytes(),
Expand Down
Loading