Polls

Synchronous Polling

Synchronous polling mechanisms are implemented to await the fulfillment of specific conditions. Upon the satisfaction of these conditions, the polling process yields the result of the given condition.

Monitoring for a New Block Production

This section illustrates the methodology for monitoring the production of a new block. Utilizing synchronous polling, the waitUntil function is employed to efficiently wait for the production of a new block.

import { Poll, TESTNET_URL, ThorClient } from '@vechain/sdk-network';
import { expect } from 'expect';

// 1 - Create thor client for testnet

const thorClient = ThorClient.at(TESTNET_URL);

// 2 - Get current block

const currentBlock = await thorClient.blocks.getBestBlockCompressed();

console.log('Current block:', currentBlock);

// 3 - Wait until a new block is created

// Wait until a new block is created with polling interval of 3 seconds
const newBlock = await Poll.SyncPoll(
    // Get the latest block as polling target function
    async () => await thorClient.blocks.getBlockCompressed('best'),
    // Polling interval is 3 seconds
    { requestIntervalInMilliseconds: 3000 }
).waitUntil((newBlockData) => {
    // Stop polling when the new block number is greater than the current block number
    return (newBlockData?.number as number) > (currentBlock?.number as number);
});

expect(newBlock).toBeDefined();
expect(newBlock?.number).toBeGreaterThan(currentBlock?.number as number);

console.log('New block:', newBlock);

Observing Balance Changes Post-Transfer

Here, we explore the approach to monitor balance changes after a transfer. Synchronous polling leverages the waitUntil function to detect balance changes following a transfer.

Asynchronous Polling

Asynchronous polling is utilized for waiting in a non-blocking manner until a specific condition is met or to capture certain events. This type of polling makes use of the Event Emitter pattern, providing notifications when the specified condition or event has been met or emitted.

Implementing a Simple Async Poll in a DAPP

This example demonstrates the application of an asynchronous poll for tracking transaction events, allowing for the execution of additional operations concurrently.

Last updated

Was this helpful?