/** * Component: BlocksList * Author: Nearblocks Pte Ltd * License: Business Source License 1.1 * Description: Table of blocks on Near Protocol. * @interface Props * @param {string} [network] - The network data to show, either mainnet or testnet. * @param {Function} [t] - A function for internationalization (i18n) provided by the next-translate package. * @param {number} [currentPage] - The current page number being displayed. (Optional) * Example: If provided, currentPage=3 will display the third page of blocks. * @param {function} [setPage] - A function used to set the current page. (Optional) * Example: setPage={handlePageChange} where handlePageChange is a function to update the page. */ /* INCLUDE COMPONENT: "includes/Common/Skeleton.jsx" */ /** * @interface Props * @param {string} [className] - The CSS class name(s) for styling purposes. */ const Skeleton = (props) => { return ( <div className={`bg-gray-200 rounded shadow-sm animate-pulse ${props.className}`} ></div> ); };/* END_INCLUDE COMPONENT: "includes/Common/Skeleton.jsx" */ /* INCLUDE: "includes/formats.jsx" */ function convertToMetricPrefix(numberStr) { const prefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; // Metric prefixes let result = new Big(numberStr); let count = 0; while (result.abs().gte('1e3') && count < prefixes.length - 1) { result = result.div(1e3); count++; } // Check if the value is an integer or has more than two digits before the decimal point if (result.abs().lt(1e2) && result.toFixed(2) !== result.toFixed(0)) { result = result.toFixed(2); } else { result = result.toFixed(0); } return result.toString() + ' ' + prefixes[count]; } function formatNumber(value) { let bigValue = new Big(value); const suffixes = ['', 'K', 'M', 'B', 'T']; let suffixIndex = 0; while (bigValue.gte(10000) && suffixIndex < suffixes.length - 1) { bigValue = bigValue.div(1000); suffixIndex++; } const formattedValue = bigValue.toFixed(1).replace(/\.0+$/, ''); return `${formattedValue} ${suffixes[suffixIndex]}`; } function gasFee(gas, price) { const near = yoctoToNear(Big(gas).mul(Big(price)).toString(), true); return `${near}`; } function currency(number) { let absNumber = new Big(number).abs(); const suffixes = ['', 'K', 'M', 'B', 'T', 'Q']; let suffixIndex = 0; while (absNumber.gte(1000) && suffixIndex < suffixes.length - 1) { absNumber = absNumber.div(1000); // Divide using big.js's div method suffixIndex++; } const formattedNumber = absNumber.toFixed(2); // Format with 2 decimal places return ( (number < '0' ? '-' : '') + formattedNumber + ' ' + suffixes[suffixIndex] ); } function formatDate(dateString) { const inputDate = new Date(dateString); const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; const dayOfWeek = days[inputDate.getDay()]; const month = months[inputDate.getMonth()]; const day = inputDate.getDate(); const year = inputDate.getFullYear(); const formattedDate = dayOfWeek + ', ' + month + ' ' + day + ', ' + year; return formattedDate; } function formatCustomDate(inputDate) { var date = new Date(inputDate); // Array of month names var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; // Get month and day var month = monthNames[date.getMonth()]; var day = date.getDate(); // Create formatted date string in "MMM DD" format var formattedDate = month + ' ' + (day < 10 ? '0' + day : day); return formattedDate; } function shortenHex(address) { return `${address && address.substr(0, 6)}...${address.substr(-4)}`; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function shortenToken(token) { return truncateString(token, 14, ''); } function shortenTokenSymbol(token) { return truncateString(token, 5, ''); } function gasPercentage(gasUsed, gasAttached) { if (!gasAttached) return 'N/A'; const formattedNumber = (Big(gasUsed).div(Big(gasAttached)) * 100).toFixed(2); return `${formattedNumber}%`; } function serialNumber(index, page, perPage) { return index + 1 + (page - 1) * perPage; } function capitalizeWords(str) { const words = str.split('_'); const capitalizedWords = words.map( (word) => word.charAt(0).toUpperCase() + word.slice(1), ); const result = capitalizedWords.join(' '); return result; } function toSnakeCase(str) { return str .replace(/[A-Z]/g, (match) => '_' + match.toLowerCase()) .replace(/^_/, ''); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function formatTimestampToString(timestamp) { const date = new Date(timestamp); // Format the date to 'YYYY-MM-DD HH:mm:ss' format const formattedDate = date.toISOString().replace('T', ' ').split('.')[0]; return formattedDate; } function convertToMetricPrefix(numberStr) { const prefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; // Metric prefixes let result = new Big(numberStr); let count = 0; while (result.abs().gte('1e3') && count < prefixes.length - 1) { result = result.div(1e3); count++; } // Check if the value is an integer or has more than two digits before the decimal point if (result.abs().lt(1e2) && result.toFixed(2) !== result.toFixed(0)) { result = result.toFixed(2); } else { result = result.toFixed(0); } return result.toString() + ' ' + prefixes[count]; } function formatNumber(value) { let bigValue = new Big(value); const suffixes = ['', 'K', 'M', 'B', 'T']; let suffixIndex = 0; while (bigValue.gte(10000) && suffixIndex < suffixes.length - 1) { bigValue = bigValue.div(1000); suffixIndex++; } const formattedValue = bigValue.toFixed(1).replace(/\.0+$/, ''); return `${formattedValue} ${suffixes[suffixIndex]}`; } function gasFee(gas, price) { const near = yoctoToNear(Big(gas).mul(Big(price)).toString(), true); return `${near}`; } function currency(number) { let absNumber = new Big(number).abs(); const suffixes = ['', 'K', 'M', 'B', 'T', 'Q']; let suffixIndex = 0; while (absNumber.gte(1000) && suffixIndex < suffixes.length - 1) { absNumber = absNumber.div(1000); // Divide using big.js's div method suffixIndex++; } const formattedNumber = absNumber.toFixed(2); // Format with 2 decimal places return ( (number < '0' ? '-' : '') + formattedNumber + ' ' + suffixes[suffixIndex] ); } function formatDate(dateString) { const inputDate = new Date(dateString); const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; const dayOfWeek = days[inputDate.getDay()]; const month = months[inputDate.getMonth()]; const day = inputDate.getDate(); const year = inputDate.getFullYear(); const formattedDate = dayOfWeek + ', ' + month + ' ' + day + ', ' + year; return formattedDate; } function formatCustomDate(inputDate) { var date = new Date(inputDate); // Array of month names var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; // Get month and day var month = monthNames[date.getMonth()]; var day = date.getDate(); // Create formatted date string in "MMM DD" format var formattedDate = month + ' ' + (day < 10 ? '0' + day : day); return formattedDate; } function shortenHex(address) { return `${address && address.substr(0, 6)}...${address.substr(-4)}`; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function shortenToken(token) { return truncateString(token, 14, ''); } function shortenTokenSymbol(token) { return truncateString(token, 5, ''); } function gasPercentage(gasUsed, gasAttached) { if (!gasAttached) return 'N/A'; const formattedNumber = (Big(gasUsed).div(Big(gasAttached)) * 100).toFixed(2); return `${formattedNumber}%`; } function serialNumber(index, page, perPage) { return index + 1 + (page - 1) * perPage; } function capitalizeWords(str) { const words = str.split('_'); const capitalizedWords = words.map( (word) => word.charAt(0).toUpperCase() + word.slice(1), ); const result = capitalizedWords.join(' '); return result; } function toSnakeCase(str) { return str .replace(/[A-Z]/g, (match) => '_' + match.toLowerCase()) .replace(/^_/, ''); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function gasFee(gas, price) { const near = yoctoToNear(Big(gas).mul(Big(price)).toString(), true); return `${near}`; } function currency(number) { let absNumber = new Big(number).abs(); const suffixes = ['', 'K', 'M', 'B', 'T', 'Q']; let suffixIndex = 0; while (absNumber.gte(1000) && suffixIndex < suffixes.length - 1) { absNumber = absNumber.div(1000); // Divide using big.js's div method suffixIndex++; } const formattedNumber = absNumber.toFixed(2); // Format with 2 decimal places return ( (number < '0' ? '-' : '') + formattedNumber + ' ' + suffixes[suffixIndex] ); } function formatDate(dateString) { const inputDate = new Date(dateString); const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; const dayOfWeek = days[inputDate.getDay()]; const month = months[inputDate.getMonth()]; const day = inputDate.getDate(); const year = inputDate.getFullYear(); const formattedDate = dayOfWeek + ', ' + month + ' ' + day + ', ' + year; return formattedDate; } function formatCustomDate(inputDate) { var date = new Date(inputDate); // Array of month names var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; // Get month and day var month = monthNames[date.getMonth()]; var day = date.getDate(); // Create formatted date string in "MMM DD" format var formattedDate = month + ' ' + (day < 10 ? '0' + day : day); return formattedDate; } function shortenHex(address) { return `${address && address.substr(0, 6)}...${address.substr(-4)}`; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function shortenToken(token) { return truncateString(token, 14, ''); } function shortenTokenSymbol(token) { return truncateString(token, 5, ''); } function gasPercentage(gasUsed, gasAttached) { if (!gasAttached) return 'N/A'; const formattedNumber = (Big(gasUsed).div(Big(gasAttached)) * 100).toFixed(2); return `${formattedNumber}%`; } function serialNumber(index, page, perPage) { return index + 1 + (page - 1) * perPage; } function capitalizeWords(str) { const words = str.split('_'); const capitalizedWords = words.map( (word) => word.charAt(0).toUpperCase() + word.slice(1), ); const result = capitalizedWords.join(' '); return result; } function toSnakeCase(str) { return str .replace(/[A-Z]/g, (match) => '_' + match.toLowerCase()) .replace(/^_/, ''); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function getTimeAgoString(timestamp) { const currentUTC = Date.now(); const date = new Date(timestamp); const seconds = Math.floor((currentUTC - date.getTime()) / 1000); const intervals = { year: seconds / (60 * 60 * 24 * 365), month: seconds / (60 * 60 * 24 * 30), week: seconds / (60 * 60 * 24 * 7), day: seconds / (60 * 60 * 24), hour: seconds / (60 * 60), minute: seconds / 60, }; if (intervals.year >= 1) { return ( Math.floor(intervals.year) + ' year' + (Math.floor(intervals.year) > 1 ? 's' : '') + ' ago' ); } else if (intervals.month >= 1) { return ( Math.floor(intervals.month) + ' month' + (Math.floor(intervals.month) > 1 ? 's' : '') + ' ago' ); } else if (intervals.day >= 1) { return ( Math.floor(intervals.day) + ' day' + (Math.floor(intervals.day) > 1 ? 's' : '') + ' ago' ); } else if (intervals.hour >= 1) { return ( Math.floor(intervals.hour) + ' hour' + (Math.floor(intervals.hour) > 1 ? 's' : '') + ' ago' ); } else if (intervals.minute >= 1) { return ( Math.floor(intervals.minute) + ' minute' + (Math.floor(intervals.minute) > 1 ? 's' : '') + ' ago' ); } else { return 'a few seconds ago'; } } function formatWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function formatTimestampToString(timestamp) { const date = new Date(timestamp); // Format the date to 'YYYY-MM-DD HH:mm:ss' format const formattedDate = date.toISOString().replace('T', ' ').split('.')[0]; return formattedDate; } function convertToMetricPrefix(numberStr) { const prefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; // Metric prefixes let result = new Big(numberStr); let count = 0; while (result.abs().gte('1e3') && count < prefixes.length - 1) { result = result.div(1e3); count++; } // Check if the value is an integer or has more than two digits before the decimal point if (result.abs().lt(1e2) && result.toFixed(2) !== result.toFixed(0)) { result = result.toFixed(2); } else { result = result.toFixed(0); } return result.toString() + ' ' + prefixes[count]; } function formatNumber(value) { let bigValue = new Big(value); const suffixes = ['', 'K', 'M', 'B', 'T']; let suffixIndex = 0; while (bigValue.gte(10000) && suffixIndex < suffixes.length - 1) { bigValue = bigValue.div(1000); suffixIndex++; } const formattedValue = bigValue.toFixed(1).replace(/\.0+$/, ''); return `${formattedValue} ${suffixes[suffixIndex]}`; } function gasFee(gas, price) { const near = yoctoToNear(Big(gas).mul(Big(price)).toString(), true); return `${near}`; } function currency(number) { let absNumber = new Big(number).abs(); const suffixes = ['', 'K', 'M', 'B', 'T', 'Q']; let suffixIndex = 0; while (absNumber.gte(1000) && suffixIndex < suffixes.length - 1) { absNumber = absNumber.div(1000); // Divide using big.js's div method suffixIndex++; } const formattedNumber = absNumber.toFixed(2); // Format with 2 decimal places return ( (number < '0' ? '-' : '') + formattedNumber + ' ' + suffixes[suffixIndex] ); } function formatDate(dateString) { const inputDate = new Date(dateString); const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; const dayOfWeek = days[inputDate.getDay()]; const month = months[inputDate.getMonth()]; const day = inputDate.getDate(); const year = inputDate.getFullYear(); const formattedDate = dayOfWeek + ', ' + month + ' ' + day + ', ' + year; return formattedDate; } function formatCustomDate(inputDate) { var date = new Date(inputDate); // Array of month names var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; // Get month and day var month = monthNames[date.getMonth()]; var day = date.getDate(); // Create formatted date string in "MMM DD" format var formattedDate = month + ' ' + (day < 10 ? '0' + day : day); return formattedDate; } function shortenHex(address) { return `${address && address.substr(0, 6)}...${address.substr(-4)}`; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function shortenToken(token) { return truncateString(token, 14, ''); } function shortenTokenSymbol(token) { return truncateString(token, 5, ''); } function gasPercentage(gasUsed, gasAttached) { if (!gasAttached) return 'N/A'; const formattedNumber = (Big(gasUsed).div(Big(gasAttached)) * 100).toFixed(2); return `${formattedNumber}%`; } function serialNumber(index, page, perPage) { return index + 1 + (page - 1) * perPage; } function capitalizeWords(str) { const words = str.split('_'); const capitalizedWords = words.map( (word) => word.charAt(0).toUpperCase() + word.slice(1), ); const result = capitalizedWords.join(' '); return result; } function toSnakeCase(str) { return str .replace(/[A-Z]/g, (match) => '_' + match.toLowerCase()) .replace(/^_/, ''); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function localFormat(number) { const bigNumber = Big(number); const formattedNumber = bigNumber .toFixed(5) .replace(/(\d)(?=(\d{3})+\.)/g, '$1,'); // Add commas before the decimal point return formattedNumber.replace(/\.?0*$/, ''); // Remove trailing zeros and the dot } function dollarFormat(number) { const bigNumber = new Big(number); // Format to two decimal places without thousands separator const formattedNumber = bigNumber.toFixed(2); // Add comma as a thousands separator const parts = formattedNumber.split('.'); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); const dollarFormattedNumber = `${parts.join('.')}`; return dollarFormattedNumber; } function dollarNonCentFormat(number) { const bigNumber = new Big(number).toFixed(0); // Extract integer part and format with commas const integerPart = bigNumber.toString(); const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ','); return formattedInteger; } function weight(number) { let sizeInBytes = new Big(number); if (sizeInBytes.lt(0)) { throw new Error('Invalid input. Please provide a non-negative number.'); } const suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; let suffixIndex = 0; while (sizeInBytes.gte(1000) && suffixIndex < suffixes.length - 1) { sizeInBytes = sizeInBytes.div(1000); // Assign the result back to sizeInBytes suffixIndex++; } const formattedSize = sizeInBytes.toFixed(2) + ' ' + suffixes[suffixIndex]; return formattedSize; } function convertToUTC(timestamp, hour) { const date = new Date(timestamp); // Get UTC date components const utcYear = date.getUTCFullYear(); const utcMonth = ('0' + (date.getUTCMonth() + 1)).slice(-2); // Adding 1 because months are zero-based const utcDay = ('0' + date.getUTCDate()).slice(-2); const utcHours = ('0' + date.getUTCHours()).slice(-2); const utcMinutes = ('0' + date.getUTCMinutes()).slice(-2); const utcSeconds = ('0' + date.getUTCSeconds()).slice(-2); // Array of month abbreviations const monthAbbreviations = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; const monthIndex = Number(utcMonth) - 1; // Format the date as required (Jul-25-2022 16:25:37) let formattedDate = monthAbbreviations[monthIndex] + '-' + utcDay + '-' + utcYear + ' ' + utcHours + ':' + utcMinutes + ':' + utcSeconds; if (hour) { // Convert hours to 12-hour format let hour12 = parseInt(utcHours); const ampm = hour12 >= 12 ? 'PM' : 'AM'; hour12 = hour12 % 12 || 12; // Add AM/PM to the formatted date (Jul-25-2022 4:25:37 PM) formattedDate = monthAbbreviations[monthIndex] + '-' + utcDay + '-' + utcYear + ' ' + hour12 + ':' + utcMinutes + ':' + utcSeconds + ' ' + ampm; } return formattedDate; } function getTimeAgoString(timestamp) { const currentUTC = Date.now(); const date = new Date(timestamp); const seconds = Math.floor((currentUTC - date.getTime()) / 1000); const intervals = { year: seconds / (60 * 60 * 24 * 365), month: seconds / (60 * 60 * 24 * 30), week: seconds / (60 * 60 * 24 * 7), day: seconds / (60 * 60 * 24), hour: seconds / (60 * 60), minute: seconds / 60, }; if (intervals.year >= 1) { return ( Math.floor(intervals.year) + ' year' + (Math.floor(intervals.year) > 1 ? 's' : '') + ' ago' ); } else if (intervals.month >= 1) { return ( Math.floor(intervals.month) + ' month' + (Math.floor(intervals.month) > 1 ? 's' : '') + ' ago' ); } else if (intervals.day >= 1) { return ( Math.floor(intervals.day) + ' day' + (Math.floor(intervals.day) > 1 ? 's' : '') + ' ago' ); } else if (intervals.hour >= 1) { return ( Math.floor(intervals.hour) + ' hour' + (Math.floor(intervals.hour) > 1 ? 's' : '') + ' ago' ); } else if (intervals.minute >= 1) { return ( Math.floor(intervals.minute) + ' minute' + (Math.floor(intervals.minute) > 1 ? 's' : '') + ' ago' ); } else { return 'a few seconds ago'; } } function formatWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function formatTimestampToString(timestamp) { const date = new Date(timestamp); // Format the date to 'YYYY-MM-DD HH:mm:ss' format const formattedDate = date.toISOString().replace('T', ' ').split('.')[0]; return formattedDate; } function convertToMetricPrefix(numberStr) { const prefixes = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; // Metric prefixes let result = new Big(numberStr); let count = 0; while (result.abs().gte('1e3') && count < prefixes.length - 1) { result = result.div(1e3); count++; } // Check if the value is an integer or has more than two digits before the decimal point if (result.abs().lt(1e2) && result.toFixed(2) !== result.toFixed(0)) { result = result.toFixed(2); } else { result = result.toFixed(0); } return result.toString() + ' ' + prefixes[count]; } function formatNumber(value) { let bigValue = new Big(value); const suffixes = ['', 'K', 'M', 'B', 'T']; let suffixIndex = 0; while (bigValue.gte(10000) && suffixIndex < suffixes.length - 1) { bigValue = bigValue.div(1000); suffixIndex++; } const formattedValue = bigValue.toFixed(1).replace(/\.0+$/, ''); return `${formattedValue} ${suffixes[suffixIndex]}`; } function gasFee(gas, price) { const near = yoctoToNear(Big(gas).mul(Big(price)).toString(), true); return `${near}`; } function currency(number) { let absNumber = new Big(number).abs(); const suffixes = ['', 'K', 'M', 'B', 'T', 'Q']; let suffixIndex = 0; while (absNumber.gte(1000) && suffixIndex < suffixes.length - 1) { absNumber = absNumber.div(1000); // Divide using big.js's div method suffixIndex++; } const formattedNumber = absNumber.toFixed(2); // Format with 2 decimal places return ( (number < '0' ? '-' : '') + formattedNumber + ' ' + suffixes[suffixIndex] ); } function formatDate(dateString) { const inputDate = new Date(dateString); const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]; const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]; const dayOfWeek = days[inputDate.getDay()]; const month = months[inputDate.getMonth()]; const day = inputDate.getDate(); const year = inputDate.getFullYear(); const formattedDate = dayOfWeek + ', ' + month + ' ' + day + ', ' + year; return formattedDate; } function formatCustomDate(inputDate) { var date = new Date(inputDate); // Array of month names var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]; // Get month and day var month = monthNames[date.getMonth()]; var day = date.getDate(); // Create formatted date string in "MMM DD" format var formattedDate = month + ' ' + (day < 10 ? '0' + day : day); return formattedDate; } function shortenHex(address) { return `${address && address.substr(0, 6)}...${address.substr(-4)}`; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } function shortenToken(token) { return truncateString(token, 14, ''); } function shortenTokenSymbol(token) { return truncateString(token, 5, ''); } function gasPercentage(gasUsed, gasAttached) { if (!gasAttached) return 'N/A'; const formattedNumber = (Big(gasUsed).div(Big(gasAttached)) * 100).toFixed(2); return `${formattedNumber}%`; } function serialNumber(index, page, perPage) { return index + 1 + (page - 1) * perPage; } function capitalizeWords(str) { const words = str.split('_'); const capitalizedWords = words.map( (word) => word.charAt(0).toUpperCase() + word.slice(1), ); const result = capitalizedWords.join(' '); return result; } function toSnakeCase(str) { return str .replace(/[A-Z]/g, (match) => '_' + match.toLowerCase()) .replace(/^_/, ''); } function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function yoctoToNear(yocto, format) { const YOCTO_PER_NEAR = Big(10).pow(24).toString(); const near = Big(yocto).div(YOCTO_PER_NEAR).toString(); return format ? localFormat(near) : near; } /* END_INCLUDE: "includes/formats.jsx" */ /* INCLUDE COMPONENT: "includes/icons/Clock.jsx" */ /** * @interface Props * @param {string} [className] - The CSS class name(s) for styling purposes. */ const Clock = (props) => ( <svg viewBox="64 64 896 896" focusable="false" data-icon="clock-circle" width="1em" height="1em" fill="currentColor" aria-hidden="true" {...props} > <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm0 820c-205.4 0-372-166.6-372-372s166.6-372 372-372 372 166.6 372 372-166.6 372-372 372z"></path> <path d="M686.7 638.6L544.1 535.5V288c0-4.4-3.6-8-8-8H488c-4.4 0-8 3.6-8 8v275.4c0 2.6 1.2 5 3.3 6.5l165.4 120.6c3.6 2.6 8.6 1.8 11.2-1.7l28.6-39c2.6-3.7 1.8-8.7-1.8-11.2z"></path> </svg> );/* END_INCLUDE COMPONENT: "includes/icons/Clock.jsx" */ /* INCLUDE: "includes/libs.jsx" */ function getConfig(network) { switch (network) { case 'mainnet': return { ownerId: 'nearblocks.near', nodeUrl: 'https://rpc.mainnet.near.org', backendUrl: 'https://api3.nearblocks.io/v1/', rpcUrl: 'https://archival-rpc.testnet.near.org', appUrl: 'https://nearblocks.io/', }; case 'testnet': return { ownerId: 'nearblocks.testnet', nodeUrl: 'https://rpc.testnet.near.org', backendUrl: 'https://api3-testnet.nearblocks.io/v1/', rpcUrl: 'https://archival-rpc.testnet.near.org', appUrl: 'https://testnet.nearblocks.io/', }; default: return {}; } } function debounce( delay, func, ) { let timer; let active = true; const debounced = (arg) => { if (active) { clearTimeout(timer); timer = setTimeout(() => { active && func(arg); timer = undefined; }, delay); } else { func(arg); } }; debounced.isPending = () => { return timer !== undefined; }; debounced.cancel = () => { active = false; }; debounced.flush = (arg) => func(arg); return debounced; } function timeAgo(unixTimestamp) { const currentTimestamp = Math.floor(Date.now() / 1000); const secondsAgo = currentTimestamp - unixTimestamp; if (secondsAgo < 5) { return 'Just now'; } else if (secondsAgo < 60) { return `${secondsAgo} seconds ago`; } else if (secondsAgo < 3600) { const minutesAgo = Math.floor(secondsAgo / 60); return `${minutesAgo} minute${minutesAgo > 1 ? 's' : ''} ago`; } else if (secondsAgo < 86400) { const hoursAgo = Math.floor(secondsAgo / 3600); return `${hoursAgo} hour${hoursAgo > 1 ? 's' : ''} ago`; } else { const daysAgo = Math.floor(secondsAgo / 86400); return `${daysAgo} day${daysAgo > 1 ? 's' : ''} ago`; } } function shortenAddress(address) { const string = String(address); if (string.length <= 20) return string; return `${string.substr(0, 10)}...${string.substr(-7)}`; } function urlHostName(url) { try { const domain = new URL(url); return domain?.hostname ?? null; } catch (e) { return null; } } function holderPercentage(supply, quantity) { return Math.min(Big(quantity).div(Big(supply)).mul(Big(100)).toFixed(2), 100); } function isAction(type) { const actions = [ 'DEPLOY_CONTRACT', 'TRANSFER', 'STAKE', 'ADD_KEY', 'DELETE_KEY', 'DELETE_ACCOUNT', ]; return actions.includes(type.toUpperCase()); } function isJson(string) { const str = string.replace(/\\/g, ''); try { JSON.parse(str); return false; } catch (e) { return false; } } function uniqueId() { return Math.floor(Math.random() * 1000); } function handleRateLimit( data, reFetch, Loading, ) { if (data.status === 429 || data.status === undefined) { const retryCount = 4; const delay = Math.pow(2, retryCount) * 1000; setTimeout(() => { reFetch(); }, delay); } else { if (Loading) { Loading(); } } } function localFormat(number) { const bigNumber = Big(number); const formattedNumber = bigNumber .toFixed(5) .replace(/(\d)(?=(\d{3})+\.)/g, '$1,'); // Add commas before the decimal point return formattedNumber.replace(/\.?0*$/, ''); // Remove trailing zeros and the dot } function formatWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function handleRateLimit( data, reFetch, Loading, ) { if (data.status === 429 || data.status === undefined) { const retryCount = 4; const delay = Math.pow(2, retryCount) * 1000; setTimeout(() => { reFetch(); }, delay); } else { if (Loading) { Loading(); } } } function nanoToMilli(nano) { return Big(nano).div(Big(10).pow(6)).round().toNumber(); } function truncateString(str, maxLength, suffix) { if (str.length <= maxLength) { return str; } return str.substring(0, maxLength) + suffix; } function getConfig(network) { switch (network) { case 'mainnet': return { ownerId: 'nearblocks.near', nodeUrl: 'https://rpc.mainnet.near.org', backendUrl: 'https://api3.nearblocks.io/v1/', rpcUrl: 'https://archival-rpc.testnet.near.org', appUrl: 'https://nearblocks.io/', }; case 'testnet': return { ownerId: 'nearblocks.testnet', nodeUrl: 'https://rpc.testnet.near.org', backendUrl: 'https://api3-testnet.nearblocks.io/v1/', rpcUrl: 'https://archival-rpc.testnet.near.org', appUrl: 'https://testnet.nearblocks.io/', }; default: return {}; } } function debounce( delay, func, ) { let timer; let active = true; const debounced = (arg) => { if (active) { clearTimeout(timer); timer = setTimeout(() => { active && func(arg); timer = undefined; }, delay); } else { func(arg); } }; debounced.isPending = () => { return timer !== undefined; }; debounced.cancel = () => { active = false; }; debounced.flush = (arg) => func(arg); return debounced; } function timeAgo(unixTimestamp) { const currentTimestamp = Math.floor(Date.now() / 1000); const secondsAgo = currentTimestamp - unixTimestamp; if (secondsAgo < 5) { return 'Just now'; } else if (secondsAgo < 60) { return `${secondsAgo} seconds ago`; } else if (secondsAgo < 3600) { const minutesAgo = Math.floor(secondsAgo / 60); return `${minutesAgo} minute${minutesAgo > 1 ? 's' : ''} ago`; } else if (secondsAgo < 86400) { const hoursAgo = Math.floor(secondsAgo / 3600); return `${hoursAgo} hour${hoursAgo > 1 ? 's' : ''} ago`; } else { const daysAgo = Math.floor(secondsAgo / 86400); return `${daysAgo} day${daysAgo > 1 ? 's' : ''} ago`; } } function shortenAddress(address) { const string = String(address); if (string.length <= 20) return string; return `${string.substr(0, 10)}...${string.substr(-7)}`; } function urlHostName(url) { try { const domain = new URL(url); return domain?.hostname ?? null; } catch (e) { return null; } } function holderPercentage(supply, quantity) { return Math.min(Big(quantity).div(Big(supply)).mul(Big(100)).toFixed(2), 100); } function isAction(type) { const actions = [ 'DEPLOY_CONTRACT', 'TRANSFER', 'STAKE', 'ADD_KEY', 'DELETE_KEY', 'DELETE_ACCOUNT', ]; return actions.includes(type.toUpperCase()); } function isJson(string) { const str = string.replace(/\\/g, ''); try { JSON.parse(str); return false; } catch (e) { return false; } } function uniqueId() { return Math.floor(Math.random() * 1000); } function handleRateLimit( data, reFetch, Loading, ) { if (data.status === 429 || data.status === undefined) { const retryCount = 4; const delay = Math.pow(2, retryCount) * 1000; setTimeout(() => { reFetch(); }, delay); } else { if (Loading) { Loading(); } } } function localFormat(number) { const bigNumber = Big(number); const formattedNumber = bigNumber .toFixed(5) .replace(/(\d)(?=(\d{3})+\.)/g, '$1,'); // Add commas before the decimal point return formattedNumber.replace(/\.?0*$/, ''); // Remove trailing zeros and the dot } function formatWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function shortenAddress(address) { const string = String(address); if (string.length <= 20) return string; return `${string.substr(0, 10)}...${string.substr(-7)}`; } function urlHostName(url) { try { const domain = new URL(url); return domain?.hostname ?? null; } catch (e) { return null; } } function holderPercentage(supply, quantity) { return Math.min(Big(quantity).div(Big(supply)).mul(Big(100)).toFixed(2), 100); } function isAction(type) { const actions = [ 'DEPLOY_CONTRACT', 'TRANSFER', 'STAKE', 'ADD_KEY', 'DELETE_KEY', 'DELETE_ACCOUNT', ]; return actions.includes(type.toUpperCase()); } function isJson(string) { const str = string.replace(/\\/g, ''); try { JSON.parse(str); return false; } catch (e) { return false; } } function uniqueId() { return Math.floor(Math.random() * 1000); } function handleRateLimit( data, reFetch, Loading, ) { if (data.status === 429 || data.status === undefined) { const retryCount = 4; const delay = Math.pow(2, retryCount) * 1000; setTimeout(() => { reFetch(); }, delay); } else { if (Loading) { Loading(); } } } function localFormat(number) { const bigNumber = Big(number); const formattedNumber = bigNumber .toFixed(5) .replace(/(\d)(?=(\d{3})+\.)/g, '$1,'); // Add commas before the decimal point return formattedNumber.replace(/\.?0*$/, ''); // Remove trailing zeros and the dot } function formatWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } /* END_INCLUDE: "includes/libs.jsx" */ function MainComponent({ currentPage, setPage, t, network }) { const [isLoading, setIsLoading] = useState(false); const [totalCount, setTotalCount] = useState(0); const [showAge, setShowAge] = useState(true); const [blocks, setBlocks] = useState({}); const errorMessage = t ? t('blocks:noBlocks') : 'No blocks!'; const config = getConfig(network); useEffect(() => { function fetchTotalBlocks() { asyncFetch(`${config?.backendUrl}blocks/count`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }) .then( (data ) => { const resp = data?.body?.blocks?.[0]; if (data.status === 200) { setTotalCount(resp?.count ?? 0); } else { handleRateLimit(data, fetchTotalBlocks); } }, ) .catch(() => {}) .finally(() => {}); } function fetchBlocks(page) { setIsLoading(true); asyncFetch(`${config?.backendUrl}blocks?page=${page}&per_page=25`, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }) .then( (data ) => { const resp = data?.body?.blocks; if (data.status === 200) { setBlocks((prevData) => ({ ...prevData, [page]: resp || [] })); setIsLoading(false); } else { handleRateLimit( data, () => fetchBlocks(page), () => setIsLoading(false), ); } }, ) .catch(() => {}); } fetchTotalBlocks(); fetchBlocks(currentPage); }, [config?.backendUrl, currentPage]); const start = blocks[currentPage]?.[0]; const end = blocks[currentPage]?.[blocks[currentPage]?.length - 1]; const toggleShowAge = () => setShowAge((s) => !s); const columns = [ { header: <span>{t ? t('blocks:blocks') : 'BLOCK'}</span>, key: 'block_hash', cell: (row) => ( <span> <a href={`/blocks/${row?.block_hash}`} className="hover:no-underline"> <a className="text-green-500 hover:no-underline"> {row?.block_height ? localFormat(row?.block_height) : row?.block_height ?? ''} </a> </a> </span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600 font-medium', thClassName: 'px-6 py-2 text-left text-xs font-semibold text-nearblue-600 uppercase tracking-wider whitespace-nowrap', }, { header: ( <div> <Tooltip.Provider> <Tooltip.Root> <Tooltip.Trigger asChild> <button type="button" onClick={toggleShowAge} className="w-full flex items-center px-6 py-2 text-left text-xs font-semibold uppercase tracking-wider text-green-500 focus:outline-none flex-row" > {showAge ? ( <> {t ? t('blocks:age') : 'AGE'} <Clock className="text-green-500 ml-2" /> </> ) : ( 'DATE TIME (UTC)' )} </button> </Tooltip.Trigger> <Tooltip.Content className="h-auto max-w-xs bg-black bg-opacity-90 z-10 text-xs text-white px-3 py-2 break-words" align="center" side="top" > {showAge ? 'Click to show Datetime Format' : 'Click to show Age Format'} </Tooltip.Content> </Tooltip.Root> </Tooltip.Provider> </div> ), key: 'block_timestamp', cell: (row) => ( <span> <Tooltip.Provider> <Tooltip.Root> <Tooltip.Trigger asChild> <span> {!showAge ? row?.block_timestamp ? formatTimestampToString( nanoToMilli(row?.block_timestamp), ) : '' : row?.block_timestamp ? getTimeAgoString(nanoToMilli(row?.block_timestamp)) : ''} </span> </Tooltip.Trigger> <Tooltip.Content className="h-auto max-w-xs bg-black bg-opacity-90 z-10 text-xs text-white px-3 py-2 break-words" align="center" side="bottom" > {showAge ? row?.block_timestamp ? formatTimestampToString(nanoToMilli(row?.block_timestamp)) : '' : row?.block_timestamp ? getTimeAgoString(nanoToMilli(row?.block_timestamp)) : ''} </Tooltip.Content> </Tooltip.Root> </Tooltip.Provider> </span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600', }, { header: <span>{t ? t('blocks:txn') : 'TXN'}</span>, key: 'count', cell: (row) => ( <span> {row?.transactions_agg?.count ? localFormat(row?.transactions_agg?.count) : row?.transactions_agg?.count ?? ''} </span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600', thClassName: 'px-6 py-2 text-left text-xs font-semibold text-nearblue-600 uppercase tracking-wider whitespace-nowrap', }, { header: <span>{t ? t('blocks:block.receipt') : 'RECEIPT'}</span>, key: 'count', cell: (row) => ( <span> {row?.receipts_agg?.count ? localFormat(row?.receipts_agg?.count) : row?.receipts_agg?.count ?? ''} </span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600', thClassName: 'px-6 py-2 text-left text-xs font-semibold text-nearblue-600 uppercase tracking-wider whitespace-nowrap', }, { header: <span>{t ? t('blocks:miner') : 'AUTHOR'}</span>, key: 'author_account_id', cell: (row) => ( <span> <a href={`/address/${row?.author_account_id}`} className="hover:no-underline" > <a className="text-green-500 hover:no-underline"> {shortenAddress(row?.author_account_id ?? '')} </a> </a> </span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600 font-medium', thClassName: 'px-6 py-2 text-left text-xs font-semibold text-nearblue-600 uppercase tracking-wider whitespace-nowrap', }, { header: <span>{t ? t('blocks:block.gasUsed') : 'GAS USED'}</span>, key: 'gas_used', cell: (row) => ( <span> {row?.chunks_agg?.gas_used !== null ? convertToMetricPrefix(row?.chunks_agg?.gas_used) + 'gas' : ''} </span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600', thClassName: 'px-6 py-2 text-left text-xs font-semibold text-nearblue-600 uppercase tracking-wider whitespace-nowrap', }, { header: <span>{t ? t('blocks:block.gasLimit') : 'GAS LIMIT'}</span>, key: 'gas_limit', cell: (row) => ( <span>{convertToMetricPrefix(row?.chunks_agg?.gas_limit ?? 0)}gas</span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600', thClassName: 'px-6 py-2 text-left text-xs font-semibold text-nearblue-600 uppercase tracking-wider whitespace-nowrap', }, { header: <span>{t ? t('blocks:block.gasFee') : 'GAS FEE'}</span>, key: 'gas_price', cell: (row) => ( <span> {row?.chunks_agg?.gas_used ? gasFee(row?.chunks_agg?.gas_used, row?.gas_price) : row?.chunks_agg?.gas_used ?? ''} Ⓝ </span> ), tdClassName: 'px-6 py-4 whitespace-nowrap text-sm text-nearblue-600', thClassName: 'px-6 py-2 text-left text-xs font-semibold text-nearblue-600 uppercase tracking-wider whitespace-nowrap', }, ]; return ( <div className="bg-white border soft-shadow rounded-xl pb-1 "> {isLoading ? ( <div className="pl-6 max-w-lg w-full py-5 "> <Skeleton className="h-4" /> </div> ) : ( <p className="leading-7 pl-6 text-sm py-4 text-nearblue-600"> {t ? t('blocks:listing', { from: start?.block_height ? localFormat(start?.block_height) : start?.block_height ?? '', to: end?.block_height ? localFormat(end?.block_height) : end?.block_height ?? '', count: localFormat(totalCount.toString()), }) : `Block #${ start?.block_height ? localFormat(start?.block_height) : start?.block_height ?? '' } to ${ '#' + end?.block_height ? localFormat(end?.block_height) : end?.block_height ?? '' } (Total of ${localFormat(totalCount.toString())} blocks)`}{' '} </p> )} { <Widget src={`${config.ownerId}/widget/bos-components.components.Shared.Table`} props={{ columns: columns, data: blocks[currentPage], isLoading: isLoading, isPagination: true, count: totalCount, page: currentPage, limit: 25, pageLimit: 200, setPage: setPage, Error: errorMessage, }} /> } </div> ); } return MainComponent(props, context);