Search code examples
nearprotocol

Transferring user token balance to contract in cross contract call


Contract A

#[payable]
pub fn add_liquidity(&mut self, tokens: u128, avrit_id: AccountId) -> u128 {
        let amount = env::attached_deposit();            

        Promise::new(avrit_id).function_call(
            b"transfer".to_vec(),
            json!({"new_owner_id":"avrit.testnet", "amount": U128(tokens)}).to_string().as_bytes().to_vec(),
            38600000000000000000000,
            env::prepaid_gas() - GAS_FOR_SWAP,
        );

        amount
}

Promise function call is done by contract A instead of the person who calls the add_liquidity.
How to call the Promise where predecessor is user who calls add_liquidity instead of contract A address? Explorer


Solution

  • You're right. It's not possible to make a Promise function call where the predecessor is some other account than the current one.

    This is an important security feature of contract development on NEAR. Because if you could have spoofed the predecessor account ID, then you'd be able to pretend to be this account and do actions on behalf of this account.

    Instead when a contract makes a cross-contract call, the predecessor becomes this contract instead of the transaction signer. The receiving contract will be able to see which account called it directly.