Staking API Tutorial
An example on how to use Blockdaemon Avalanche Staking API.
In this guide, you will find a TypeScript example showing how to send an Avalanche transaction using the Avalanche Staking API.
import { Avalanche, Buffer } from 'avalanche';
import {
PlatformVMAPI,
KeyChain,
UnsignedTx,
Tx,
} from 'avalanche/dist/apis/platformvm';
import { PrivateKeyPrefix } from 'avalanche/dist/utils';
export async function signAndSubmitTx(
hexEncodedTx: string,
avalanche: Avalanche,
privKey: string,
): Promise<string> {
const pchain: PlatformVMAPI = avalanche.PChain();
const pKeychain: KeyChain = pchain.keyChain();
if (!privKey.startsWith(PrivateKeyPrefix)) {
privKey = `${PrivateKeyPrefix}${privKey}`;
}
pKeychain.importKey(privKey);
const unsignedTx: UnsignedTx = new UnsignedTx();
unsignedTx.deserialize(hexToObject(hexEncodedTx));
const signedTx: Tx = unsignedTx.sign(pKeychain);
return pchain.issueTx(signedTx);
}
function hexToObject(hexString: string) {
const buffer = Buffer.from(hexString, 'hex');
const jsonString = buffer.toString('utf-8');
return JSON.parse(jsonString);
}
const apiAddress = 'https://svc.blockdaemon.com/boss';
async function processTransaction(transactionType: string, requestOptions: any) {
const request = {
amount: '1000000000',
delegator_address: 'P-fuji1ajsy7pf4jdd6zyhywzmvvvr54rs03j0hrqtm4g',
validator_address: 'NodeID-3tKjUEqW9kqEZ3JYAC89BWttahsELRqpc',
};
requestOptions.body = JSON.stringify(request);
const response = await fetch(`${apiAddress}/v1/avax/fuji/${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.avax) {
throw new Error('Response from BOSS API did not include avax field: ' + JSON.stringify(responseJson));
}
const avalanche = new Avalanche('api.avax-test.network', 443, 'https', 5);
const pchain: PlatformVMAPI = avalanche.PChain();
const pKeychain: KeyChain = pchain.keyChain();
let privKey = process.env["PRIVATE_KEY"];
if (!privKey) {
throw new Error('No private key found in environment');
}
if (!privKey.startsWith(PrivateKeyPrefix)) {
privKey = `${PrivateKeyPrefix}${privKey}`;
}
pKeychain.importKey(privKey);
const unsignedTx: UnsignedTx = new UnsignedTx();
unsignedTx.deserialize(hexToObject(responseJson.avax.unsigned_transaction));
console.log(pKeychain.getAddressStrings());
const signedTx: Tx = unsignedTx.sign(pKeychain);
return pchain.issueTx(signedTx);
}
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);
});
Updated about 1 month ago