Low vs High level API
Interactions
AeSdk
is a general, high-level interface that wraps multiple low-level interfaces. A general interface is preferred for its simplicity and resilience to breaking changes.
But there is also low-level interfaces. It's excellent for additional control, and as a teaching tool to understand the underlying operations. Most real-world requirements involves a series of low-level operations, so the SDK provides abstractions for these.
Node API
The aeternity node exposes a REST API. This API is described in the OpenAPI document. SDK uses this document to generate a TypeScript client. The result client (implemented in Node
class) a basically a mapping of all node endpoints as functions.
So to get a transaction based on its hash you would invoke node.getTransactionByHash('th_fWEsg152BNYcrqA9jDh9VVpacYojCUb1yu45zUnqhmQ3dAAC6')
. In this way the SDK is simply a mapping of the raw API calls into JavaScript.
Transaction builder
Any blockchain state change requires signing a transaction. Transaction should be built according to the protocol. SDK implements it in buildTx
, buildTxAsync
, and unpackTx
. buildTxAsync
requires fewer arguments than buildTx
, but it expects the node instance provided in arguments.
High-level SDK usage (preferable)
Example spend call, using æternity's SDK abstraction:
import { AeSdk, Node, AccountMemory, encode, Encoding } from '@aeternity/aepp-sdk';
const aeSdk = new AeSdk({
nodes: [
{
name: 'testnet',
instance: new Node('https://testnet.aeternity.io'), // host your node for better decentralization
},
],
accounts: [new AccountMemory('sk_2CuofqWZHrABCrM7GY95YSQn8PyFvKQadnvFnpwhjUnDCFAWmf')],
});
const transactionInfo = await aeSdk.spend(
100, // aettos
'ak_21A27UVVt3hDkBE5J7rhhqnH5YNb4Y1dqo4PnSybrH85pnWo7E',
{ payload: encode(Buffer.from('spend tx payload'), Encoding.Bytearray) },
);
console.log(transactionInfo);
Low-level SDK usage
The same spend execution, but using low-level SDK functions:
import { Node, AccountMemory, buildTxAsync, Tag, encode, Encoding } from '@aeternity/aepp-sdk';
const onNode = new Node('https://testnet.aeternity.io'); // host your node for better decentralization
const account = new AccountMemory('sk_2CuofqWZHrABCrM7GY95YSQn8PyFvKQadnvFnpwhjUnDCFAWmf');
const spendTx = await buildTxAsync({
tag: Tag.SpendTx,
senderId: account.address,
recipientId: 'ak_21A27UVVt3hDkBE5J7rhhqnH5YNb4Y1dqo4PnSybrH85pnWo7E',
amount: 100, // aettos
payload: encode(Buffer.from('spend tx payload'), Encoding.Bytearray),
onNode,
});
const signedTx = await account.signTransaction(spendTx, { networkId: await onNode.getNetworkId() });
// broadcast the signed tx to the node
const { txHash } = await onNode.postTransaction({ tx: signedTx });
console.log(txHash);