Observe the status of Transactions
Transactions can go through different states. Since they are sent to be executed until they finish successfully or with errors. The sdk allows you to view or react to changes in the state of a transaction either locally or on the server.
Observe with events
The sdk has in its transaction module a utility api that has the observeSaga method. This method receives the transaction identifier and will return an CommandEvent observable.
const erc20Api = sdk.transactions.erc20Api
const transaction = await erc20Api.transfer(payload, caller);
if(transaction.isLeft()) throw new Error(transaction.left()?.message);
const utilsApi = sdk.transactions.blkUtilsApi;
const obs$ = blkUtilsApi.observeSaga(transaction.right());
obs$.subscribe((event) => {
console.log(event.name); // name of the event
console.log(event.id); // event id
console.log(event.payload); // event payload
})
It is a class that inherits from DomainEvent and in its payload property we find the event data that complies with the CommandEventPayload interface.
interface CommandEventPayload {
id: string;
name: string;
status: 'success' | failed | 'in_progress';
progress: number;
error?: string;
hash?: string;
}
Observe with adapter
The sdk has the ITransaction interface if listening for events is not your use case. This functionality was kept for compatibility with previously built applications and is useful for speeding up transaction state enforcement. This will return an instance of TransactionObserver, which is a utility class for handling reactions to specific transaction states.
const erc20Api = sdk.transactions.erc20Api
const transaction = erc20Api.transfer(payload, caller); // We don't use the await
const observer = sdk.transactions.adapterTx(transaction);
observe
.on(TransactionStatus.Pending, (tx) => {
console.log(`Transaction ${tx.id} is pending`);
})
.on(TransactionStatus.Success, (tx) => {
console.log(`Transaction ${tx.id} is successful`);
})
.on(TransactionStatus.Fail, (tx) => {
console.log(`Transaction ${tx.id} is failed`);
})
.listen();
It is an interface with the following properties
export interface ITransaction {
id: UUID;
method: ITransactionMethod;
params: TransactionComand;
status: TransactionStatus;
hash?: TransactionHash;
info?: string;
error?: string;
}
In this mode of use for transactions adapted to the ITransaction interface, the params property will not be available and will be an empty object.