Passing account to near-js-api function call

112 views Asked by At

I am trying to call the following method from near-js-api for my contract. It takes Rsut AccountId as an argument.

What is the proper way to serialise an Account and pass it to the contract?

Furthermore, are there any special considerations when calling the contract initialiser?

#[near_bindgen]
impl BurnerPool {

    #[init]
    fn new(token_id: AccountId) -> Self {

        assert!(!env::state_exists(), "Already initialized");

        let pool = Self {
            token_id: token_id,
            total_received: 0,
        };

        return pool;
    }
}
1

There are 1 answers

0
Robert Zaremba On BEST ANSWER

AccountId is a string. So just paste a string value.

Considerations:

  1. It's good to validate an account before you will do anything with it:

    #[inline]
    pub fn assert_account_is_valid(a: &AccountId) {
        assert!(
            env::is_valid_account_id(a.as_bytes()),
            format!("{} account ID is invalid", a)
        );
    }
    
  2. If contract initialization is strictly required before the use, and bad things will happen if someone else will initialize it instead of you (eg setting an owner address), then you can add some protection methods (eg hardcoding hash in a smart contract and doing preimage check in the new method).

  3. If a contract shouldn't be initialized twice, then always call !env::state_exists() with assert, exactly as you did.