1

After logging in to a NEAR app with near-api-js (walletConnection.requestSignin()) you get a function access key with 0.25N allowance. This makes it possible to call the contract without confirming the transaction. When the allowance is spent all further contract calls requires confirmation.

How to detect that the allowance is spent, and to request a new function access key for that same contract, and be allowed to make new transactions without confirmation for each one?

Peter Salomonsen
  • 5,525
  • 2
  • 24
  • 38

1 Answers1

0

Here's a function that will check if you are logged in and that your remaining allowance is above a certain amount ( 0.05 in this case )

        const checkSignedin = async () => {
            const nearConnection = await connect(connectionConfig);
            const wc = await new WalletConnection(nearConnection);
            const acc = wc.account();
        
            const publicKey = await acc.connection.signer.getPublicKey(acc.accountId, acc.connection.networkId);
        
            if (!publicKey) {
                await wc.signOut();
            } else {
                const accessKey = await acc.connection.provider.query({
                    request_type: "view_access_key",
                    finality: "final",
                    account_id: acc.accountId,
                    public_key: publicKey.toString(),
                });
        
                if (accessKey.permission.FunctionCall.receiver_id != contractAccountId) {
                    wc.signOut();
                    await acc.deleteKey(publicKey.toString());
                } else {
                    const remainingAllowance = parseFloat(nearApi.utils.format.formatNearAmount(accessKey.permission.FunctionCall.allowance));
                    console.log('remaining allowance', remainingAllowance);
                    if (remainingAllowance < 0.05) {
                        wc.signOut();
                        await acc.deleteKey(publicKey.toString());
                    }
                }
            }
        
            if (!wc.isSignedIn()) {
                await wc.requestSignIn(
                    contractAccountId,
                    'JS music player'
                );
            }
            return wc;
        }
Peter Salomonsen
  • 5,525
  • 2
  • 24
  • 38