@onmax_/core
Version:
Nimiq's Rust-to-WASM web client (patched for Cloudflare Workers logging fix)
1,291 lines (1,233 loc) • 104 kB
JavaScript
let wasm_bindgen;
(function() {
const __exports = {};
let script_src;
if (typeof document !== 'undefined' && document.currentScript !== null) {
script_src = new URL(document.currentScript.src, location.href).toString();
}
let wasm = undefined;
let WASM_VECTOR_LEN = 0;
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}
const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } );
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length, 1) >>> 0;
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len, 1) >>> 0;
const mem = getUint8ArrayMemory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
let cachedDataViewMemory0 = null;
function getDataViewMemory0() {
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
}
return cachedDataViewMemory0;
}
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
function addToExternrefTable0(obj) {
const idx = wasm.__externref_table_alloc();
wasm.__wbindgen_export_4.set(idx, obj);
return idx;
}
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
const idx = addToExternrefTable0(e);
wasm.__wbindgen_exn_store(idx);
}
}
function isLikeNone(x) {
return x === undefined || x === null;
}
function getArrayU8FromWasm0(ptr, len) {
ptr = ptr >>> 0;
return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
}
const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(state => {
wasm.__wbindgen_export_5.get(state.dtor)(state.a, state.b)
});
function makeMutClosure(arg0, arg1, dtor, f) {
const state = { a: arg0, b: arg1, cnt: 1, dtor };
const real = (...args) => {
// First up with a closure we increment the internal reference
// count. This ensures that the Rust closure environment won't
// be deallocated while we're invoking it.
state.cnt++;
const a = state.a;
state.a = 0;
try {
return f(a, state.b, ...args);
} finally {
if (--state.cnt === 0) {
wasm.__wbindgen_export_5.get(state.dtor)(a, state.b);
CLOSURE_DTORS.unregister(state);
} else {
state.a = a;
}
}
};
real.original = state;
CLOSURE_DTORS.register(real, state, state);
return real;
}
function makeClosure(arg0, arg1, dtor, f) {
const state = { a: arg0, b: arg1, cnt: 1, dtor };
const real = (...args) => {
// First up with a closure we increment the internal reference
// count. This ensures that the Rust closure environment won't
// be deallocated while we're invoking it.
state.cnt++;
try {
return f(state.a, state.b, ...args);
} finally {
if (--state.cnt === 0) {
wasm.__wbindgen_export_5.get(state.dtor)(state.a, state.b);
state.a = 0;
CLOSURE_DTORS.unregister(state);
}
}
};
real.original = state;
CLOSURE_DTORS.register(real, state, state);
return real;
}
function debugString(val) {
// primitive types
const type = typeof val;
if (type == 'number' || type == 'boolean' || val == null) {
return `${val}`;
}
if (type == 'string') {
return `"${val}"`;
}
if (type == 'symbol') {
const description = val.description;
if (description == null) {
return 'Symbol';
} else {
return `Symbol(${description})`;
}
}
if (type == 'function') {
const name = val.name;
if (typeof name == 'string' && name.length > 0) {
return `Function(${name})`;
} else {
return 'Function';
}
}
// objects
if (Array.isArray(val)) {
const length = val.length;
let debug = '[';
if (length > 0) {
debug += debugString(val[0]);
}
for(let i = 1; i < length; i++) {
debug += ', ' + debugString(val[i]);
}
debug += ']';
return debug;
}
// Test for built-in
const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
let className;
if (builtInMatches && builtInMatches.length > 1) {
className = builtInMatches[1];
} else {
// Failed to match the standard '[object ClassName]'
return toString.call(val);
}
if (className == 'Object') {
// we're a user defined class or Object
// JSON.stringify avoids problems with cycles, and is generally much
// easier than looping through ownProperties of `val`.
try {
return 'Object(' + JSON.stringify(val) + ')';
} catch (_) {
return 'Object';
}
}
// errors
if (val instanceof Error) {
return `${val.name}: ${val.message}\n${val.stack}`;
}
// TODO we could test for more things here, like `Set`s and `Map`s.
return className;
}
function passArray8ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 1, 1) >>> 0;
getUint8ArrayMemory0().set(arg, ptr / 1);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
function takeFromExternrefTable0(idx) {
const value = wasm.__wbindgen_export_4.get(idx);
wasm.__externref_table_dealloc(idx);
return value;
}
function _assertClass(instance, klass) {
if (!(instance instanceof klass)) {
throw new Error(`expected instance of ${klass.name}`);
}
}
function __wbg_adapter_54(arg0, arg1, arg2) {
wasm.closure376_externref_shim(arg0, arg1, arg2);
}
function __wbg_adapter_57(arg0, arg1, arg2) {
wasm.closure374_externref_shim(arg0, arg1, arg2);
}
function __wbg_adapter_60(arg0, arg1, arg2) {
wasm.closure1716_externref_shim(arg0, arg1, arg2);
}
function __wbg_adapter_67(arg0, arg1) {
wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h5eb8352eb092153c(arg0, arg1);
}
function __wbg_adapter_70(arg0, arg1) {
wasm._dyn_core__ops__function__FnMut_____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hb9247d8182e24adf(arg0, arg1);
}
function __wbg_adapter_73(arg0, arg1, arg2) {
wasm.closure2336_externref_shim(arg0, arg1, arg2);
}
function __wbg_adapter_76(arg0, arg1, arg2) {
wasm.closure2667_externref_shim(arg0, arg1, arg2);
}
function __wbg_adapter_412(arg0, arg1, arg2, arg3) {
wasm.closure2862_externref_shim(arg0, arg1, arg2, arg3);
}
/**
* @enum {0 | 1 | 2 | 3}
*/
__exports.AccountType = Object.freeze({
Basic: 0, "0": "Basic",
Vesting: 1, "1": "Vesting",
HTLC: 2, "2": "HTLC",
Staking: 3, "3": "Staking",
});
/**
* A transaction flag signals a special purpose of the transaction. `ContractCreation` must be set
* to create new vesting contracts or HTLCs. `Signaling` must be set to interact with the staking
* contract for non-value transactions. All other transactions' flag is set to `None`.
* @enum {0 | 1 | 2}
*/
__exports.TransactionFlag = Object.freeze({
None: 0, "0": "None",
ContractCreation: 1, "1": "ContractCreation",
Signaling: 2, "2": "Signaling",
});
/**
* @enum {0 | 1}
*/
__exports.TransactionFormat = Object.freeze({
Basic: 0, "0": "Basic",
Extended: 1, "1": "Extended",
});
const __wbindgen_enum_BinaryType = ["blob", "arraybuffer"];
const __wbindgen_enum_IdbTransactionMode = ["readonly", "readwrite", "versionchange", "readwriteflush", "cleanup"];
const AddressFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_address_free(ptr >>> 0, 1));
/**
* An object representing a Nimiq address.
* Offers methods to parse and format addresses from and to strings.
*/
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 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;
}
/**
* 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]);
}
/**
* 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);
}
}
}
__exports.Address = Address;
const ClientFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_client_free(ptr >>> 0, 1));
/**
* 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();
* // ...
* });
* ```
*/
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);
}
/**
* 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 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 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 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;
}
/**
* 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 block hash of the current blockchain head.
* @returns {Promise<string>}
*/
getHeadHash() {
const ret = wasm.client_getHeadHash(this.__wbg_ptr);
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;
}
/**
* 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 network ID that the client is connecting to.
* @returns {Promise<number>}
*/
getNetworkId() {
const ret = wasm.client_getNetworkId(this.__wbg_ptr);
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;
}
/**
* 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;
}
/**
* Returns the block number of the current blockchain head.
* @returns {Promise<number>}
*/
getHeadHeight() {
const ret = wasm.client_getHeadHeight(this.__wbg_ptr);
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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* Returns if the client currently has consensus with the network.
* @returns {Promise<boolean>}
*/
isConsensusEstablished() {
const ret = wasm.client_isConsensusEstablished(this.__wbg_ptr);
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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
}
__exports.Client = Client;
const ClientConfigurationFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_clientconfiguration_free(ptr >>> 0, 1));
/**
* 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.
*/
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);
}
}
__exports.ClientConfiguration = ClientConfiguration;
const HashedTimeLockedContractFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_hashedtimelockedcontract_free(ptr >>> 0, 1));
/**
* Utility class providing methods to parse Hashed Time Locked Contract transaction data and proofs.
*/
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);
}
}
__exports.HashedTimeLockedContract = HashedTimeLockedContract;
const PolicyFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_policy_free(ptr >>> 0, 1));
/**
* Policy constants
*/
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);
}
/**
* 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;
}
/**
* The current version number of the protocol. Changing this always results in a hard fork.
* @returns {number}
*/
static get VERSION() {
const ret = wasm.policy_wasm_min_epochs_stored();
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;
}
/**
* 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 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 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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 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;
}
/**
* 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;
}
/**
* How many batches constitute an epoch
* @returns {number}
*/
static get BATCHES_PER_EPOCH() {
const ret = wasm.policy_batches_per_epoch();
return ret;
}
/**
* 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 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 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;
}
/**
* Total supply in units.
* @returns {bigint}
*/
static get TOTAL_SUPPLY() {
const ret = wasm.policy_wasm_total_supply();
return BigInt.asUintN(64, ret);
}
/**
* 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 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 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;
}
/**
* 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;
}
/**
* 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 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 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 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;
}
/**
* 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;
}
/**
* 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);
}
}
/**
* 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 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);
}
/**
* 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 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);
}
/**
* 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);
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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);
}
}
/**
* 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;
}
/**
* 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);
}
/**
* 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 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;
}
/**
* 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 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 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