Staking API Tutorial

An example showing how to send a NEAR transaction using the Blockdaemon Staking API.

Here is a TypeScript example showing how to send a NEAR transaction using the Staking API.

import {connect, KeyPair, transactions, InMemorySigner} from 'near-api-js';


const apiAddress = 'https://svc.blockdaemon.com/boss';

async function processTransaction(transactionType: string, requestOptions: any) {

    const request = {
      amount: '1000000000000000000000000',
      wallet_address: 'somerandomtest.testnet',
      to: 'nodeasy.pool.f863973.m0',
      public_key: 'ed25519:6KqjK2Avs54rRQwyMoVecq332jGGdBcsUCfZJhAHuXBt',
    };

    requestOptions.body = JSON.stringify(request);

    const response = await fetch(`${apiAddress}/v1/near/testnet/${transactionType}`, requestOptions);

    if (!response.ok) {
        throw new Error('Response from BOSS API was not ok: ' + await response.text());
    }

    const responseJson = await response.json();

    if (!responseJson.near) {
        throw new Error('Response from BOSS API did not include near field: ' + JSON.stringify(responseJson));
    }

    const networkId = 'testnet';
    const { connection } = await connect({
      networkId: networkId,
      nodeUrl: 'https://rpc.testnet.near.org',
    });

    let privKey = process.env['PRIVATE_KEY'];
    if (!privKey) {
      throw new Error('No private key found in environment');
    }

    const keyPair = KeyPair.fromString(privKey);
    const signer = await InMemorySigner.fromKeyPair(networkId, responseJson.near.wallet_address, keyPair);
    const tx = transactions.Transaction.decode(Buffer.from(responseJson.near.unsigned_transaction, 'hex'));
    const [ _, txWithSignature ] = await transactions.signTransaction(tx, signer, responseJson.near.wallet_address, networkId);
    return connection.provider.sendTransaction(txWithSignature);
}

async function createStake() {
    return await processTransaction('stake-intents', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-API-Key': process.env['BOSS_API_KEY'],
        },
    });
}

createStake()
    .then(() => process.exit(0))
    .catch(err => {
        console.error(err);
        process.exit(1);
    });

👋 Need Help?

Contact us through email or our support page for any issues, bugs, or assistance you may need.