@nimiq/core
Version:
Nimiq's Rust-to-WASM web client
1,384 lines (1,375 loc) • 95.2 kB
JavaScript
/**
* @enum {0 | 1 | 2 | 3}
*/
export const AccountType = Object.freeze({
Basic: 0, "0": "Basic",
Vesting: 1, "1": "Vesting",
HTLC: 2, "2": "HTLC",
Staking: 3, "3": "Staking",
});
/**
* An object representing a Nimiq address.
* Offers methods to parse and format addresses from and to strings.
*/
export class Address {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(Address.prototype);
obj.__wbg_ptr = ptr;
AddressFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
AddressFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_address_free(ptr, 0);
}
/**
* Deserializes an address from a byte array.
* @param {Uint8Array} bytes
* @returns {Address}
*/
static deserialize(bytes) {
const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.address_deserialize(ptr0, len0);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return Address.__wrap(ret[0]);
}
/**
* Parses an address from an {@link Address} instance, a hex string representation, or a byte array.
*
* Throws when an address cannot be parsed from the argument.
* @param {string | Uint8Array} addr
* @returns {Address}
*/
static fromAny(addr) {
const ret = wasm.address_fromAny(addr);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return Address.__wrap(ret[0]);
}
/**
* Parses an address from a string representation, either user-friendly or hex format.
*
* Throws when an address cannot be parsed from the string.
* @param {string} str
* @returns {Address}
*/
static fromString(str) {
const ptr0 = passStringToWasm0(str, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.address_fromString(ptr0, len0);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return Address.__wrap(ret[0]);
}
/**
* @param {Uint8Array} bytes
*/
constructor(bytes) {
const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.address_new(ptr0, len0);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
this.__wbg_ptr = ret[0] >>> 0;
AddressFinalization.register(this, this.__wbg_ptr, this);
return this;
}
/**
* The all-zeroes burn address.
* @returns {Address}
*/
static get NULL() {
const ret = wasm.address_null();
return Address.__wrap(ret);
}
/**
* Formats the address into a plain string format.
* @returns {string}
*/
toPlain() {
let deferred1_0;
let deferred1_1;
try {
const ret = wasm.address_toPlain(this.__wbg_ptr);
deferred1_0 = ret[0];
deferred1_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
}
}
}
if (Symbol.dispose) Address.prototype[Symbol.dispose] = Address.prototype.free;
/**
* Nimiq Albatross client that runs in browsers via WASM and is exposed to Javascript.
*
* ### Usage:
*
* ```js
* import init, * as Nimiq from "./pkg/nimiq_web_client.js";
*
* init().then(async () => {
* const config = new Nimiq.ClientConfiguration();
* const client = await config.instantiateClient();
* // ...
* });
* ```
*/
export class Client {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(Client.prototype);
obj.__wbg_ptr = ptr;
ClientFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
ClientFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_client_free(ptr, 0);
}
/**
* Adds an event listener for consensus-change events, such as when consensus is established or lost.
* @param {(state: ConsensusState) => any} listener
* @returns {Promise<number>}
*/
addConsensusChangedListener(listener) {
const ret = wasm.client_addConsensusChangedListener(this.__wbg_ptr, listener);
return ret;
}
/**
* Adds an event listener for new blocks added to the blockchain.
* @param {(hash: string, reason: string, reverted_blocks: string[], adopted_blocks: string[]) => any} listener
* @returns {Promise<number>}
*/
addHeadChangedListener(listener) {
const ret = wasm.client_addHeadChangedListener(this.__wbg_ptr, listener);
return ret;
}
/**
* Adds an event listener for peer-change events, such as when a new peer joins, or a peer leaves.
* @param {(peer_id: string, reason: 'joined' | 'left', peer_count: number, peer_info?: PlainPeerInfo) => any} listener
* @returns {Promise<number>}
*/
addPeerChangedListener(listener) {
const ret = wasm.client_addPeerChangedListener(this.__wbg_ptr, listener);
return ret;
}
/**
* Adds an event listener for transactions to and from the provided addresses.
*
* The listener is called for transactions when they are _included_ in the blockchain.
* @param {(transaction: PlainTransactionDetails) => any} listener
* @param {(string | Uint8Array)[]} addresses
* @returns {Promise<number>}
*/
addTransactionListener(listener, addresses) {
const ret = wasm.client_addTransactionListener(this.__wbg_ptr, listener, addresses);
return ret;
}
/**
* This function is used to tell the network to (re)start connecting to peers.
* This is could be used to tell the network to restart connection operations after
* disconnect network is called.
* @returns {Promise<void>}
*/
connectNetwork() {
const ret = wasm.client_connectNetwork(this.__wbg_ptr);
return ret;
}
/**
* Creates a new Client that automatically starts connecting to the network.
* @param {PlainClientConfiguration} config
* @returns {Promise<Client>}
*/
static create(config) {
const ret = wasm.client_create(config);
return ret;
}
/**
* This function is used to tell the network to disconnect from every connected
* peer and stop trying to connect to other peers.
*
* **Important**: this function returns when the signal to disconnect was sent,
* before all peers actually disconnect. This means that in order to ensure the
* network is disconnected, wait for all peers to disappear after calling.
* @returns {Promise<void>}
*/
disconnectNetwork() {
const ret = wasm.client_disconnectNetwork(this.__wbg_ptr);
return ret;
}
/**
* Fetches the account for the provided address from the network.
*
* Throws if the address cannot be parsed and on network errors.
* @param {string | Uint8Array} address
* @returns {Promise<PlainAccount>}
*/
getAccount(address) {
const ret = wasm.client_getAccount(this.__wbg_ptr, address);
return ret;
}
/**
* Fetches the accounts for the provided addresses from the network.
*
* Throws if an address cannot be parsed and on network errors.
* @param {(string | Uint8Array)[]} addresses
* @returns {Promise<PlainAccount[]>}
*/
getAccounts(addresses) {
const ret = wasm.client_getAccounts(this.__wbg_ptr, addresses);
return ret;
}
/**
* Returns the current address books peers.
* Each peer will have one address and currently no guarantee for the usefulness of that address can be given.
*
* The resulting Array may be empty if there is no peers in the address book.
* @returns {Promise<PlainPeerInfo[]>}
*/
getAddressBook() {
const ret = wasm.client_getAddressBook(this.__wbg_ptr);
return ret;
}
/**
* Fetches a block by its hash.
*
* Throws if the client does not have the block.
*
* Fetching blocks from the network is not yet available.
* @param {string} hash
* @returns {Promise<PlainBlock>}
*/
getBlock(hash) {
const ptr0 = passStringToWasm0(hash, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.client_getBlock(this.__wbg_ptr, ptr0, len0);
return ret;
}
/**
* Fetches a block by its height (block number).
*
* Throws if the client does not have the block.
*
* Fetching blocks from the network is not yet available.
* @param {number} height
* @returns {Promise<PlainBlock>}
*/
getBlockAt(height) {
const ret = wasm.client_getBlockAt(this.__wbg_ptr, height);
return ret;
}
/**
* Returns the validators elected for the current epoch, together with the number of validator
* slots assigned to each of them.
*
* The slot distribution is fixed for the duration of an epoch and is the metric used on-chain
* to evaluate support for protocol upgrades. Combine this with {@link Client.getValidators} to
* relate slot counts to each validator's stake and signal data.
*
* Throws if the elected validators are not available (e.g. before consensus is established).
* @returns {Promise<PlainElectedValidator[]>}
*/
getElectedValidators() {
const ret = wasm.client_getElectedValidators(this.__wbg_ptr);
return ret;
}
/**
* Returns the current blockchain head block.
* Note that the web client is a light client and does not have block bodies, i.e. no transactions.
* @returns {Promise<PlainBlock>}
*/
getHeadBlock() {
const ret = wasm.client_getHeadBlock(this.__wbg_ptr);
return ret;
}
/**
* Returns the block hash of the current blockchain head.
* @returns {Promise<string>}
*/
getHeadHash() {
const ret = wasm.client_getHeadHash(this.__wbg_ptr);
return ret;
}
/**
* Returns the block number of the current blockchain head.
* @returns {Promise<number>}
*/
getHeadHeight() {
const ret = wasm.client_getHeadHeight(this.__wbg_ptr);
return ret;
}
/**
* Returns the network ID that the client is connecting to.
* @returns {Promise<number>}
*/
getNetworkId() {
const ret = wasm.client_getNetworkId(this.__wbg_ptr);
return ret;
}
/**
* Fetches the staker for the provided address from the network.
*
* Throws if the address cannot be parsed and on network errors.
* @param {string | Uint8Array} address
* @returns {Promise<PlainStaker | undefined>}
*/
getStaker(address) {
const ret = wasm.client_getStaker(this.__wbg_ptr, address);
return ret;
}
/**
* Fetches the stakers for the provided addresses from the network.
*
* Throws if an address cannot be parsed and on network errors.
* @param {(string | Uint8Array)[]} addresses
* @returns {Promise<(PlainStaker | undefined)[]>}
*/
getStakers(addresses) {
const ret = wasm.client_getStakers(this.__wbg_ptr, addresses);
return ret;
}
/**
* Fetches the transaction details for the given transaction hash.
* @param {string} hash
* @returns {Promise<PlainTransactionDetails>}
*/
getTransaction(hash) {
const ptr0 = passStringToWasm0(hash, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.client_getTransaction(this.__wbg_ptr, ptr0, len0);
return ret;
}
/**
* This function is used to query the network for transaction receipts from and to a
* specific address, that have been included in the chain.
*
* The obtained receipts are _not_ verified before being returned.
*
* Up to a `limit` number of transaction receipts are returned from newest to oldest.
* It starts at the `start_at` transaction and goes backwards. If this hash does not exist
* or does not belong to the address, an empty list is returned.
* If the network does not have at least `min_peers` to query, then an error is returned.
* @param {string | Uint8Array} address
* @param {number | null} [limit]
* @param {string | null} [start_at]
* @param {number | null} [min_peers]
* @returns {Promise<PlainTransactionReceipt[]>}
*/
getTransactionReceiptsByAddress(address, limit, start_at, min_peers) {
var ptr0 = isLikeNone(start_at) ? 0 : passStringToWasm0(start_at, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
const ret = wasm.client_getTransactionReceiptsByAddress(this.__wbg_ptr, address, isLikeNone(limit) ? 0xFFFFFF : limit, ptr0, len0, isLikeNone(min_peers) ? 0x100000001 : (min_peers) >>> 0);
return ret;
}
/**
* This function is used to query the network for transactions from and to a specific
* address, that have been included in the chain.
*
* The obtained transactions are verified before being returned.
*
* If you already have transactions belonging to this address, you can provide some of that
* information to reduce the amount of network requests made:
* - Provide the `since_block_height` parameter to exclude any history from before
* that block height. You should be completely certain about its state. This should not be
* the last known block height, but an earlier block height that could not have been forked
* from (e.g. the last known election or checkpoint block).
* - Provide a list of `known_transaction_details` to have them verified and/or broadcasted
* again.
* - Provide a `start_at` parameter to start the query at a specific transaction hash
* (which will not be included). This hash must exist and the corresponding transaction
* must involve this address for the query to work correctly.
*
* Up to a `limit` number of transactions are returned from newest to oldest.
* If the network does not have at least `min_peers` to query, an error is returned.
* @param {string | Uint8Array} address
* @param {number | null} [since_block_height]
* @param {PlainTransactionDetails[] | null} [known_transaction_details]
* @param {string | null} [start_at]
* @param {number | null} [limit]
* @param {number | null} [min_peers]
* @returns {Promise<PlainTransactionDetails[]>}
*/
getTransactionsByAddress(address, since_block_height, known_transaction_details, start_at, limit, min_peers) {
var ptr0 = isLikeNone(start_at) ? 0 : passStringToWasm0(start_at, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
const ret = wasm.client_getTransactionsByAddress(this.__wbg_ptr, address, isLikeNone(since_block_height) ? 0x100000001 : (since_block_height) >>> 0, isLikeNone(known_transaction_details) ? 0 : addToExternrefTable0(known_transaction_details), ptr0, len0, isLikeNone(limit) ? 0xFFFFFF : limit, isLikeNone(min_peers) ? 0x100000001 : (min_peers) >>> 0);
return ret;
}
/**
* Fetches the validator for the provided address from the network.
*
* Throws if the address cannot be parsed and on network errors.
* @param {string | Uint8Array} address
* @returns {Promise<PlainValidator | undefined>}
*/
getValidator(address) {
const ret = wasm.client_getValidator(this.__wbg_ptr, address);
return ret;
}
/**
* Fetches the validators for the provided addresses from the network.
*
* Throws if an address cannot be parsed and on network errors.
* @param {(string | Uint8Array)[]} addresses
* @returns {Promise<(PlainValidator | undefined)[]>}
*/
getValidators(addresses) {
const ret = wasm.client_getValidators(this.__wbg_ptr, addresses);
return ret;
}
/**
* Returns the version of the web client, including a `+dirty` build-metadata
* suffix when it was built from a Git work tree with uncommitted changes.
* @returns {Promise<string>}
*/
getVersion() {
const ret = wasm.client_getVersion(this.__wbg_ptr);
return ret;
}
/**
* Returns if the client currently has consensus with the network.
* @returns {Promise<boolean>}
*/
isConsensusEstablished() {
const ret = wasm.client_isConsensusEstablished(this.__wbg_ptr);
return ret;
}
/**
* Removes an event listener by its handle.
* @param {number} handle
* @returns {Promise<void>}
*/
removeListener(handle) {
const ret = wasm.client_removeListener(this.__wbg_ptr, handle);
return ret;
}
/**
* Sends a transaction to the network and returns {@link PlainTransactionDetails}.
*
* Throws in case of network errors.
* @param {PlainTransaction | string | Uint8Array} transaction
* @returns {Promise<PlainTransactionDetails>}
*/
sendTransaction(transaction) {
const ret = wasm.client_sendTransaction(this.__wbg_ptr, transaction);
return ret;
}
/**
* Returns a promise that resolves when the client has established consensus with the network.
* @returns {Promise<void>}
*/
waitForConsensusEstablished() {
const ret = wasm.client_waitForConsensusEstablished(this.__wbg_ptr);
return ret;
}
}
if (Symbol.dispose) Client.prototype[Symbol.dispose] = Client.prototype.free;
/**
* Use this to provide initialization-time configuration to the Client.
* This is a simplified version of the configuration that is used for regular nodes,
* since not all configuration knobs are available when running inside a browser.
*/
export class ClientConfiguration {
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
ClientConfigurationFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_clientconfiguration_free(ptr, 0);
}
}
if (Symbol.dispose) ClientConfiguration.prototype[Symbol.dispose] = ClientConfiguration.prototype.free;
/**
* Utility class providing methods to parse Hashed Time Locked Contract transaction data and proofs.
*/
export class HashedTimeLockedContract {
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
HashedTimeLockedContractFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_hashedtimelockedcontract_free(ptr, 0);
}
}
if (Symbol.dispose) HashedTimeLockedContract.prototype[Symbol.dispose] = HashedTimeLockedContract.prototype.free;
/**
* A Merkle path consisting of a sequence of hashes that can be used to verify the inclusion of a leaf in a Merkle tree.
*/
export class MerklePath {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(MerklePath.prototype);
obj.__wbg_ptr = ptr;
MerklePathFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
MerklePathFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_merklepath_free(ptr, 0);
}
/**
* Computes the Merkle root of the path given a leaf hash.
* @param {Uint8Array} leaf
* @returns {Uint8Array}
*/
computeRoot(leaf) {
const ptr0 = passArray8ToWasm0(leaf, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.merklepath_computeRoot(this.__wbg_ptr, ptr0, len0);
if (ret[3]) {
throw takeFromExternrefTable0(ret[2]);
}
var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
return v2;
}
/**
* Deserializes a Merkle path from a byte array.
* @param {Uint8Array} data
* @returns {MerklePath}
*/
static deserialize(data) {
const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.merklepath_deserialize(ptr0, len0);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return MerklePath.__wrap(ret[0]);
}
/**
* Returns the hashes in the Merkle path.
* @returns {Uint8Array[]}
*/
get hashes() {
const ret = wasm.merklepath_hashes(this.__wbg_ptr);
var v1 = getArrayJsValueFromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 4, 4);
return v1;
}
/**
* Returns the length of the Merkle path.
* @returns {number}
*/
get length() {
const ret = wasm.merklepath_length(this.__wbg_ptr);
return ret >>> 0;
}
/**
* Serializes the Merkle path into a byte array.
* @returns {Uint8Array}
*/
serialize() {
const ret = wasm.merklepath_serialize(this.__wbg_ptr);
var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
return v1;
}
}
if (Symbol.dispose) MerklePath.prototype[Symbol.dispose] = MerklePath.prototype.free;
/**
* Policy constants
*/
export class Policy {
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
PolicyFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_policy_free(ptr, 0);
}
/**
* Returns the batch number at a given `block_number` (height)
* @param {number} block_number
* @returns {number}
*/
static batchAt(block_number) {
const ret = wasm.policy_batchAt(block_number);
return ret >>> 0;
}
/**
* Returns the percentage reduction that should be applied to the rewards due to a delayed batch.
* This function returns a float in the range [0, 1]
* I.e 1 means that the full rewards should be given, whereas 0.5 means that half of the rewards should be given
* The input to this function is the batch delay, in milliseconds
* The function is: [(1 - MINIMUM_REWARDS_PERCENTAGE) * BLOCKS_DELAY_DECAY ^ (t^2)] + MINIMUM_REWARDS_PERCENTAGE
* @param {bigint} delay
* @returns {number}
*/
static batchDelayPenalty(delay) {
const ret = wasm.policy_batchDelayPenalty(delay);
return ret;
}
/**
* Returns the batch index at a given block number. The batch index is the number of a block relative
* to the batch it is in. For example, the first block of any batch always has an batch index of 0.
* @param {number} block_number
* @returns {number}
*/
static batchIndexAt(block_number) {
const ret = wasm.policy_batchIndexAt(block_number);
return ret >>> 0;
}
/**
* How many batches constitute an epoch
* @returns {number}
*/
static get BATCHES_PER_EPOCH() {
const ret = wasm.policy_batches_per_epoch();
return ret;
}
/**
* Returns the first block after the jail period of a given block number has ended.
* @param {number} block_number
* @returns {number}
*/
static blockAfterJail(block_number) {
const ret = wasm.policy_blockAfterJail(block_number);
return ret >>> 0;
}
/**
* Returns the first block after the reporting window of a given block number has ended.
* @param {number} block_number
* @returns {number}
*/
static blockAfterReportingWindow(block_number) {
const ret = wasm.policy_blockAfterReportingWindow(block_number);
return ret >>> 0;
}
/**
* Length of a batch including the macro block
* @returns {number}
*/
static get BLOCKS_PER_BATCH() {
const ret = wasm.policy_blocks_per_batch();
return ret >>> 0;
}
/**
* Length of an epoch including the election block
* @returns {number}
*/
static get BLOCKS_PER_EPOCH() {
const ret = wasm.policy_blocks_per_epoch();
return ret >>> 0;
}
/**
* Returns the number (height) of the next election macro block after a given block number (height).
* @param {number} block_number
* @returns {number}
*/
static electionBlockAfter(block_number) {
const ret = wasm.policy_electionBlockAfter(block_number);
return ret >>> 0;
}
/**
* Returns the block number (height) of the preceding election macro block before a given block number (height).
* If the given block number is an election macro block, it returns the election macro block before it.
* @param {number} block_number
* @returns {number}
*/
static electionBlockBefore(block_number) {
const ret = wasm.policy_electionBlockBefore(block_number);
return ret >>> 0;
}
/**
* Returns the block number of the election macro block of the given epoch (which is always the last block).
* If the index is out of bounds, None is returned
* @param {number} epoch
* @returns {number | undefined}
*/
static electionBlockOf(epoch) {
const ret = wasm.policy_electionBlockOf(epoch);
return ret === 0x100000001 ? undefined : ret;
}
/**
* Returns the epoch number at a given block number (height).
* @param {number} block_number
* @returns {number}
*/
static epochAt(block_number) {
const ret = wasm.policy_epochAt(block_number);
return ret >>> 0;
}
/**
* Returns the epoch index at a given block number. The epoch index is the number of a block relative
* to the epoch it is in. For example, the first block of any epoch always has an epoch index of 0.
* @param {number} block_number
* @returns {number}
*/
static epochIndexAt(block_number) {
const ret = wasm.policy_epochIndexAt(block_number);
return ret >>> 0;
}
/**
* Returns a boolean expressing if the batch at a given block number (height) is the first batch
* of the epoch.
* @param {number} block_number
* @returns {boolean}
*/
static firstBatchOfEpoch(block_number) {
const ret = wasm.policy_firstBatchOfEpoch(block_number);
return ret !== 0;
}
/**
* Returns the block number of the first block of the given epoch (which is always a micro block).
* If the index is out of bounds, None is returned
* @param {number} epoch
* @returns {number | undefined}
*/
static firstBlockOf(epoch) {
const ret = wasm.policy_firstBlockOf(epoch);
return ret === 0x100000001 ? undefined : ret;
}
/**
* Returns the block number of the first block of the given batch (which is always a micro block).
* If the index is out of bounds, None is returned
* @param {number} batch
* @returns {number | undefined}
*/
static firstBlockOfBatch(batch) {
const ret = wasm.policy_firstBlockOfBatch(batch);
return ret === 0x100000001 ? undefined : ret;
}
/**
* Genesis block number
* @returns {number}
*/
static get GENESIS_BLOCK_NUMBER() {
const ret = wasm.policy_genesis_block_number();
return ret >>> 0;
}
/**
* Returns a boolean expressing if the block at a given block number (height) is an election macro block.
* @param {number} block_number
* @returns {boolean}
*/
static isElectionBlockAt(block_number) {
const ret = wasm.policy_isElectionBlockAt(block_number);
return ret !== 0;
}
/**
* Returns a boolean expressing if the block at a given block number (height) is a macro block.
* @param {number} block_number
* @returns {boolean}
*/
static isMacroBlockAt(block_number) {
const ret = wasm.policy_isMacroBlockAt(block_number);
return ret !== 0;
}
/**
* Returns a boolean expressing if the block at a given block number (height) is a micro block.
* @param {number} block_number
* @returns {boolean}
*/
static isMicroBlockAt(block_number) {
const ret = wasm.policy_isMicroBlockAt(block_number);
return ret !== 0;
}
/**
* Returns the block height for the last block of the reporting window of a given block number.
* Note: This window is meant for reporting malicious behaviour (aka `jailable` behaviour).
* @param {number} block_number
* @returns {number}
*/
static lastBlockOfReportingWindow(block_number) {
const ret = wasm.policy_lastBlockOfReportingWindow(block_number);
return ret >>> 0;
}
/**
* Returns the block number (height) of the last election macro block at a given block number (height).
* If the given block number is an election macro block, then it returns that block number.
* @param {number} block_number
* @returns {number}
*/
static lastElectionBlock(block_number) {
const ret = wasm.policy_lastElectionBlock(block_number);
return ret >>> 0;
}
/**
* Returns the block number (height) of the last macro block at a given block number (height).
* If the given block number is a macro block, then it returns that block number.
* @param {number} block_number
* @returns {number}
*/
static lastMacroBlock(block_number) {
const ret = wasm.policy_lastMacroBlock(block_number);
return ret >>> 0;
}
/**
* Returns the block number (height) of the next macro block after a given block number (height).
* If the given block number is a macro block, it returns the macro block after it.
* @param {number} block_number
* @returns {number}
*/
static macroBlockAfter(block_number) {
const ret = wasm.policy_macroBlockAfter(block_number);
return ret >>> 0;
}
/**
* Returns the block number (height) of the preceding macro block before a given block number (height).
* If the given block number is a macro block, it returns the macro block before it.
* @param {number} block_number
* @returns {number}
*/
static macroBlockBefore(block_number) {
const ret = wasm.policy_macroBlockBefore(block_number);
return ret >>> 0;
}
/**
* Returns the block number of the macro block (checkpoint or election) of the given batch (which
* is always the last block).
* If the index is out of bounds, None is returned
* @param {number} batch
* @returns {number | undefined}
*/
static macroBlockOf(batch) {
const ret = wasm.policy_macroBlockOf(batch);
return ret === 0x100000001 ? undefined : ret;
}
/**
* Maximum supported protocol version
* @returns {number}
*/
static get MAX_SUPPORTED_VERSION() {
const ret = wasm.policy_max_supported_version();
return ret;
}
/**
* Maximum size of accounts trie chunks.
* @returns {number}
*/
static get STATE_CHUNKS_MAX_SIZE() {
const ret = wasm.policy_state_chunks_max_size();
return ret >>> 0;
}
/**
* Returns the supply at a given time (as Unix time) in Lunas (1 NIM = 100,000 Lunas). It is
* calculated using the following formula:
* ```text
* supply(t) = total_supply - (total_supply - genesis_supply) * supply_decay^t
* ```
* Where t is the time in milliseconds since the PoS genesis block and `genesis_supply` is the supply at
* the genesis of the Nimiq 2.0 chain.
* @param {bigint} genesis_supply
* @param {bigint} genesis_time
* @param {bigint} current_time
* @returns {bigint}
*/
static supplyAt(genesis_supply, genesis_time, current_time) {
const ret = wasm.policy_supplyAt(genesis_supply, genesis_time, current_time);
return BigInt.asUintN(64, ret);
}
/**
* Number of batches a transaction is valid with Albatross consensus.
* @returns {number}
*/
static get TRANSACTION_VALIDITY_WINDOW() {
const ret = wasm.policy_transaction_validity_window();
return ret >>> 0;
}
/**
* Number of blocks a transaction is valid with Albatross consensus.
* @returns {number}
*/
static get TRANSACTION_VALIDITY_WINDOW_BLOCKS() {
const ret = wasm.policy_transaction_validity_window_blocks();
return ret >>> 0;
}
/**
* The optimal time in milliseconds between blocks (1s)
* @returns {bigint}
*/
static get BLOCK_SEPARATION_TIME() {
const ret = wasm.policy_wasm_block_separation_time();
return BigInt.asUintN(64, ret);
}
/**
* The maximum size of the BLS public key cache.
* @returns {number}
*/
static get BLS_CACHE_MAX_CAPACITY() {
const ret = wasm.policy_wasm_bls_cache_max_capacity();
return ret >>> 0;
}
/**
* This is the address for the coinbase. Note that this is not a real account, it is just the
* address we use to denote that some coins originated from a coinbase event.
* @returns {string}
*/
static get COINBASE_ADDRESS() {
let deferred1_0;
let deferred1_1;
try {
const ret = wasm.policy_wasm_coinbase_address();
deferred1_0 = ret[0];
deferred1_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
}
}
/**
* Calculates f+1 slots which is the minimum number of slots necessary to be guaranteed to have at
* least one honest slots. That's because from a total of 3f+1 slots at most f will be malicious.
* It is calculated as `ceil(SLOTS/3)` and we use the formula `ceil(x/y) = (x+y-1)/y` for the
* ceiling division.
* @returns {number}
*/
static get F_PLUS_ONE() {
const ret = wasm.policy_wasm_f_plus_one();
return ret;
}
/**
* Maximum size of history chunks.
* 25 MB.
* @returns {bigint}
*/
static get HISTORY_CHUNKS_MAX_SIZE() {
const ret = wasm.policy_wasm_history_chunks_max_size();
return BigInt.asUintN(64, ret);
}
/**
* The number of epochs a validator is put in jail for. The jailing only happens for severe offenses.
* @returns {number}
*/
static get JAIL_EPOCHS() {
const ret = wasm.policy_wasm_jail_epochs();
return ret >>> 0;
}
/**
* The maximum allowed size, in bytes, for a micro block body.
* @returns {number}
*/
static get MAX_SIZE_MICRO_BODY() {
const ret = wasm.policy_wasm_max_size_micro_body();
return ret >>> 0;
}
/**
* The minimum timeout in milliseconds for a validator to produce a block (4s)
* @returns {bigint}
*/
static get MIN_PRODUCER_TIMEOUT() {
const ret = wasm.policy_wasm_min_block_producer_timeout();
return BigInt.asUintN(64, ret);
}
/**
* Minimum number of epochs that the ChainStore will store fully
* @returns {number}
*/
static get MIN_EPOCHS_STORED() {
const ret = wasm.policy_wasm_min_epochs_stored();
return ret >>> 0;
}
/**
* The minimum rewards percentage that we allow
* @returns {number}
*/
static get MINIMUM_REWARDS_PERCENTAGE() {
const ret = wasm.policy_wasm_minimum_rewards_percentage();
return ret;
}
/**
* Number of available validator slots. Note that a single validator may own several validator slots.
* @returns {number}
*/
static get SLOTS() {
const ret = wasm.policy_wasm_slots();
return ret;
}
/**
* This is the address for the staking contract.
* @returns {string}
*/
static get STAKING_CONTRACT_ADDRESS() {
let deferred1_0;
let deferred1_1;
try {
const ret = wasm.policy_wasm_staking_contract_address();
deferred1_0 = ret[0];
deferred1_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
}
}
/**
* The maximum drift, in milliseconds, that is allowed between any block's timestamp and the node's
* system time. We only care about drifting to the future.
* @returns {bigint}
*/
static get TIMESTAMP_MAX_DRIFT() {
const ret = wasm.policy_wasm_timestamp_max_drift();
return BigInt.asUintN(64, ret);
}
/**
* Total supply in units.
* @returns {bigint}
*/
static get TOTAL_SUPPLY() {
const ret = wasm.policy_wasm_total_supply();
return BigInt.asUintN(64, ret);
}
/**
* Calculates 2f+1 slots which is the minimum number of slots necessary to produce a macro block,
* a skip block and other actions.
* It is also the minimum number of slots necessary to be guaranteed to have a majority of honest
* slots. That's because from a total of 3f+1 slots at most f will be malicious. If in a group of
* 2f+1 slots we have f malicious ones (which is the worst case scenario), that still leaves us
* with f+1 honest slots. Which is more than the f slots that are not in this group (which must all
* be honest).
* It is calculated as `ceil(SLOTS*2/3)` and we use the formula `ceil(x/y) = (x+y-1)/y` for the
* ceiling division.
* @returns {number}
*/
static get TWO_F_PLUS_ONE() {
const ret = wasm.policy_wasm_two_f_plus_one();
return ret;
}
/**
* The deposit necessary to create a validator in Lunas (1 NIM = 100,000 Lunas).
* A validator is someone who actually participates in block production. They are akin to miners
* in proof-of-work.
* @returns {bigint}
*/
static get VALIDATOR_DEPOSIT() {
const ret = wasm.policy_wasm_validator_deposit();
return BigInt.asUintN(64, ret);
}
}
if (Symbol.dispose) Policy.prototype[Symbol.dispose] = Policy.prototype.free;
/**
* A signature proof represents a signature together with its public key and the public key's merkle path.
* It is used as the proof for transactions.
*/
export class SignatureProof {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(SignatureProof.prototype);
obj.__wbg_ptr = ptr;
SignatureProofFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
SignatureProofFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_signatureproof_free(ptr, 0);
}
/**
* Deserializes a signature proof from a byte array.
* @param {Uint8Array} bytes
* @returns {SignatureProof}
*/
static deserialize(bytes) {
const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.signatureproof_deserialize(ptr0, len0);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return SignatureProof.__wrap(ret[0]);
}
}
if (Symbol.dispose) SignatureProof.prototype[Symbol.dispose] = SignatureProof.prototype.free;
/**
* Utility class providing methods to parse Staking Contract transaction data and proofs.
*/
export class StakingContract {
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
StakingContractFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_stakingcontract_free(ptr, 0);
}
}
if (Symbol.dispose) StakingContract.prototype[Symbol.dispose] = StakingContract.prototype.free;
/**
* Transactions describe a transfer of value, usually from the sender to the recipient.
* However, transactions can also have no value, when they are used to _signal_ a change in the staking contract.
*
* Transactions can be used to create contracts, such as vesting contracts and HTLCs.
*
* Transactions require a valid signature proof over their serialized content.
* Furthermore, transactions are only valid for 2 hours after their validity-start block height.
*/
export class Transaction {
static __wrap(ptr) {
ptr = ptr >>> 0;
const obj = Object.create(Transaction.prototype);
obj.__wbg_ptr = ptr;
TransactionFinalization.register(obj, obj.__wbg_ptr, obj);
return obj;
}
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
TransactionFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_transaction_free(ptr, 0);
}
/**
* The transaction's data as a byte array.
* @returns {Uint8Array}
*/
get data() {
const ret = wasm.transaction_data(this.__wbg_ptr);
var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
return v1;
}
/**
* Deserializes a transaction from a byte array.
* @param {Uint8Array} bytes
* @returns {Transaction}
*/
static deserialize(bytes) {
const ptr0 = passArray8ToWasm0(bytes, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.transaction_deserialize(ptr0, len0);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return Transaction.__wrap(ret[0]);
}
/**
* The transaction's fee in luna (NIM's smallest unit).
* @returns {bigint}
*/
get fee() {
const ret = wasm.transaction_fee(this.__wbg_ptr);
return BigInt.asUintN(64, ret);
}
/**
* The transaction's fee per byte in luna (NIM's smallest unit).
* @returns {number}
*/
get feePerByte() {
const ret = wasm.transaction_feePerByte(this.__wbg_ptr);
return ret;
}
/**
* The transaction's flags: `0b1` = contract creation, `0b10` = signaling.
* Bit patterns outside the known variants collapse to `None`.
* Inspect `toPlain().flags` for the raw value.
* @returns {TransactionFlag}
*/
get flags() {
const ret = wasm.transaction_flags(this.__wbg_ptr);
return ret;
}
/**
* The transaction's {@link TransactionFormat}.
* @returns {TransactionFormat}
*/
get format() {
const ret = wasm.transaction_format(this.__wbg_ptr);
return ret;
}
/**
* Parses a transaction from a {@link Transaction} instance, a plain object, a hex string
* representation, or a byte array.
*
* Throws when a transaction cannot be parsed from the argument.
* @param {PlainTransaction | string | Uint8Array} tx
* @returns {Transaction}
*/
static fromAny(tx) {
const ret = wasm.transaction_fromAny(tx);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return Transaction.__wrap(ret[0]);
}
/**
* Parses a transaction from a plain object.
*
* Throws when a transaction cannot be parsed from the argument.
* @param {PlainTransaction} plain
* @returns {Transaction}
*/
static fromPlain(plain) {
const ret = wasm.transaction_fromPlain(plain);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
return Transaction.__wrap(ret[0]);
}
/**
* Returns the address of the contract that is created with this transaction.
* @returns {Address}
*/
getContractCreationAddress() {
const ret = wasm.transaction_getContractCreationAddress(this.__wbg_ptr);
return Address.__wrap(ret);
}
/**
* Computes the transaction's hash, which is used as its unique identifier on the blockchain.
* @returns {string}
*/
hash() {
let deferred1_0;
let deferred1_1;
try {
const ret = wasm.transaction_hash(this.__wbg_ptr);
deferred1_0 = ret[0];
deferred1_1 = ret[1];
return getStringFromWasm0(ret[0], ret[1]);
} finally {
wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
}
}
/**
* Tests if the transaction is valid at the specified block height.
* @param {number} block_height
* @returns {boolean}
*/
isValidAt(block_height) {
const ret = wasm.transaction_isValidAt(this.__wbg_ptr, block_height);
return ret !== 0;
}
/**
* The transaction's network ID.
* @returns {number}
*/
get networkId() {
const ret = wasm.transaction_networkId(this.__wbg_ptr);
return ret;
}
/**
* Creates a new unsigned transaction that transfers `value` amount of luna (NIM's smallest unit)
* from the sender to the recipient, where both sender and recipient can be any account type,
* and custom extra data can be added to the transaction.
*
* ### Basic transactions
* If both the sender and recipient types are omitted or `0` and both data and flags are empty,
* a smaller basic transaction is created.
*
* ### Extended transactions
* If no flags are given, but sender type is not basic (`0`) or data is set, an extended
* transaction is created.
*
* ### Contract creation transactions
* To create a new vesting or HTLC contract, set `flags` to `0b1` and specify the contract
* type as the `recipient_type`: `1` for vesting, `2` for HTLC. The `data` bytes must have
* the correct format of contract creation data for the respective contract type.
*
* ### Signaling transactions
* To interact with the staking contract, signaling transaction are often used to not
* transfer any value, but to simply _signal_ a state change instead, such as changing one's
* delegation from one validator to another. To create such a transaction, set `flags` to `
* 0b10` and populate the `data` bytes accordingly.
*
* The returned transaction is not yet signed. You can sign it e.g. with `tx.sign(keyPair)`.
*
* Throws when an account type is unknown, the numbers given for value and fee do not fit
* within a u64 or the networkId is unknown. Also throws when no data or recipient type is
* given for contract creation transactions, or no data is given for signaling transactions.
* @param {Address} sender
* @param {number | null | undefined} sender_type
* @param {Uint8Array | null | undefined} sender_data
* @param {Address} recipient
* @param {number | null | undefined} recipient_type
* @param {Uint8Array | null | undefined} recipient_data
* @param {bigint} value
* @param {bigint} fee
* @param {number | null | undefined} flags
* @param {number} validity_start_height
* @param {number} network_id
*/
constructor(sender, sender_type, sender_data, recipient, recipient_type, recipient_data, value, fee, flags, validity_start_height, network_id) {
_assertClass(sender, Address);
var ptr0 = isLikeNone(sender_data) ? 0 : passArray8ToWasm0(sender_data, wasm.__wbindgen_malloc);
var len0 = WASM_VECTOR_LEN;
_assertClass(recipient, Address);
var ptr1 = isLikeNone(recipient_data) ? 0 : passArray8ToWasm0(recipient_data, wasm.__wbindgen_malloc);
var len1 = WASM_VECTOR_LEN;
const ret = wasm.transaction_new(sender.__wbg_ptr, isLikeNone(sender_type) ? 0xFFFFFF : sender_type, ptr0, len0, recipient.__wbg_ptr, isLikeNone(recipient_type) ? 0xFFFFFF : recipient_type, ptr1, len1, value, fee, isLikeNone(flags) ? 0xFFFFFF : flags, validity_start_height, network_id);
if (ret[2]) {
throw takeFromExternrefTable0(ret[1]);
}
this.__wbg_ptr = ret[0] >>> 0;
TransactionFinalization.register(this, this.__wbg_ptr, this);
return this;
}
/**
* The transaction's signature proof as a byte array.
* @returns {Uint8Array}
*/
get proof() {
const ret = wasm.transaction_proof(this.__wbg_ptr);
var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
return v1;
}
/**
* The transaction's recipient address.
* @returns {Address}
*/
get recipient() {
const ret = wasm.transaction_recipient(this.__wbg_ptr);
return Address.__wrap(ret);
}
/**
* The transaction's recipient {@link AccountType}.
* @returns {AccountType}
*/
get recipientType() {
const ret = wasm.transaction_recipientType(this.__wbg_ptr);
return ret;
}
/**
* The transaction's sender address.
* @returns {Address}
*/
get sender() {
const ret = wasm.transaction_sender(this.__wbg_ptr);
return Address.__wrap(ret);
}
/**
* Th