How to send near tokens to payable function in near api js and near cli?

Viewed 598

I have a following function in the contract:

#[payable]
pub fn buy_tokens(&mut self) {
    let amount = env::attached_deposit()
}

But how to call the function in near-api-js and near cli with attached near tokens deposit?

await nearvar.contract.buy_tokens()

Edit:

await nearvar.contract.buy_tokens({}, GAS_AMOUNT, ATTACHED_DEPOSIT);

Gives error {InvalidTxError: {InvalidAccessKeyError: "DepositWithFunctionCall"}
The error seems because of function call action is not allowed with a function call access key https://docs.near.org/docs/roles/integrator/errors/error-implementation

How to call payable function with full access keys?

This is my index file: Link

This is where I am calling the function: Link

1 Answers

The second and third arguments of the functions in the Contract are gas and attached deposit:

await nearvar.contract.buy_tokens({}, GAS_AMOUNT, ATTACHED_DEPOSIT);

Or you can use the Account API (see details here) to do that:

let account = await connection.account(senderAccountId);
account.functionCall(contractId, 'buy_tokens', {}, GAS_AMOUNT, ATTACHED_DEPOSIT);

where GAS_AMOUNT can be 100000000000000 for 100Tgas (can also pass null instead for default 30Tgas). ATTACHED_DEPOSIT for example for 1N: 10000000000000000000000000

Related