@skalenetwork/bite
Version:
TS Library to interact with BITE protocol
266 lines (260 loc) • 8.24 kB
JavaScript
// src/core/encrypt.ts
import {
encryptMessage as encryptRawMessage,
encryptMessageMockup as encryptRawMessageMockup
} from "@skalenetwork/t-encrypt";
// src/utils/constants.ts
var EPOCH_ID_SIZE_BYTES = 8;
var BITE_ADDRESS = "0x42495445204D452049274d20454e435259505444";
var NODE_ENV = "production";
// src/utils/helper.ts
function remove0xPrefixIfNeeded(str) {
return str.startsWith("0x") ? str.slice(2) : str;
}
function intTo8BytesHex(num) {
if (typeof num !== "number" && typeof num !== "bigint") {
throw new TypeError("Input must be a number or bigint");
}
return BigInt(num).toString(16).padStart(2 * EPOCH_ID_SIZE_BYTES, "0");
}
function validateUrl(url) {
try {
new URL(url);
} catch {
throw new Error(`Invalid provider URL: ${url}`);
}
}
function validateHexString(str) {
if (!/^[0-9a-fA-F]*$/.test(str)) {
throw new Error("Invalid input: Must contain only hexadecimal characters");
}
if (str.length % 2 !== 0) {
throw new Error("Invalid input: Must have an even length");
}
}
// src/utils/logger.ts
import { Logger } from "tslog";
var isDev = NODE_ENV === "development";
var logger = new Logger({
name: "bite",
minLevel: isDev ? "info" : 9
});
// src/core/biteRpc.ts
async function getDecryptedTransactionData(endpoint, transactionHash) {
try {
validateUrl(endpoint);
const requestBody = {
jsonrpc: "2.0",
method: "bite_getDecryptedTransactionData",
params: [transactionHash],
id: 1
};
const result = await sendRpcRequest(endpoint, requestBody);
return result;
} catch (error) {
logger.error("Error fetching decrypted transaction data:", error);
throw error;
}
}
async function getCommonPublicKey(endpoint) {
try {
const requestBody = {
jsonrpc: "2.0",
method: "bite_getCommonPublicKey",
params: [],
id: 1
};
const result = await sendRpcRequest(endpoint, requestBody);
if (typeof result !== "string") {
throw new Error("Result is not a string");
}
if (!/^[0-9a-fA-F]{256}$/.test(result)) {
throw new Error("Result is not a valid 256-character hexadecimal string");
}
return result;
} catch (error) {
logger.error("Error fetching BITE common public key:", error);
throw error;
}
}
async function sendRpcRequest(endpoint, requestBody) {
try {
validateUrl(endpoint);
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody)
});
if (response.status !== 200) {
throw new Error(`Received status code: ${response.status}`);
}
const data = await response.json();
if ("error" in data) {
throw new Error(`Error from server: ${data.error.message}`);
}
return data.result;
} catch (error) {
logger.error("Error sending RPC request:", error);
throw error;
}
}
// src/core/encrypt.ts
async function encryptTransaction(tx, endpoint) {
try {
const validatedTx = validateAndExtractTransactionFields(tx);
const txTo = validatedTx.to;
let txData = validatedTx.data;
txData += txTo;
tx.data = await encryptMessage(txData, endpoint);
tx.to = BITE_ADDRESS;
return tx;
} catch (error) {
logger.error("Error encrypting transaction:", error);
throw error;
}
}
async function encryptTransactionMockup(tx) {
try {
const validatedTx = validateAndExtractTransactionFields(tx);
const txTo = validatedTx.to;
let txData = validatedTx.data;
txData += txTo;
tx.data = await encryptMessageMockup(txData);
tx.to = BITE_ADDRESS;
return tx;
} catch (error) {
logger.error("Error encrypting transaction (mockup):", error);
throw error;
}
}
async function encryptMessage(message, endpoint) {
try {
const data = remove0xPrefixIfNeeded(message);
validateHexString(data);
const BLS_PUBLIC_KEY = await getCommonPublicKey(endpoint);
const encryptedRawMessage = await encryptRawMessage(data, BLS_PUBLIC_KEY);
const epochIDHex = intTo8BytesHex(0);
return `0x${epochIDHex}${encryptedRawMessage}`;
} catch (error) {
logger.error("Error encrypting message:", error);
throw error;
}
}
async function encryptMessageMockup(message) {
try {
const data = remove0xPrefixIfNeeded(message);
if (!/^[0-9a-fA-F]*$/.test(data) || data.length % 2 !== 0) {
throw new Error("Invalid input: message must be valid hex and even length");
}
const encryptedRawMessage = await encryptRawMessageMockup(data);
const epochIDHex = intTo8BytesHex(0);
return `0x${epochIDHex}${encryptedRawMessage}`;
} catch (error) {
logger.error("Error encrypting message:", error);
throw error;
}
}
function validateAndExtractTransactionFields(tx) {
const isValid = tx && typeof tx === "object" && tx.data && tx.to && typeof tx.data === "string" && typeof tx.to === "string";
if (!isValid) {
throw new Error("Invalid input: Must be an object with 'data' and 'to' fields of type string");
}
const txData = remove0xPrefixIfNeeded(tx.data);
const txTo = remove0xPrefixIfNeeded(tx.to);
validateHexString(txData);
validateHexString(txTo);
if (txTo.length !== 40) {
throw new Error("Invalid input: 'to' field must be exactly 20 bytes (40 hex characters) long");
}
return { data: txData, to: txTo };
}
// src/core/bite.ts
var BITE = class {
constructor(providerURL) {
this.providerURL = providerURL;
}
/**
* Encrypt a hex-encoded message using BLS public key.
* @param message - Hex string (with or without 0x).
*/
async encryptMessage(message) {
return encryptMessage(message, this.providerURL);
}
/**
* Encrypt a transaction object using BLS public key.
* @param tx - The transaction to encrypt.
*/
async encryptTransaction(tx) {
return encryptTransaction(tx, this.providerURL);
}
/**
* Fetch the common BLS public key from the configured endpoint.
*/
async getCommonPublicKey() {
return getCommonPublicKey(this.providerURL);
}
/**
* Get decrypted transaction data using the configured endpoint.
* @param transactionHash - The hash of the transaction.
*/
async getDecryptedTransactionData(transactionHash) {
return getDecryptedTransactionData(this.providerURL, transactionHash);
}
};
var BITEMockup = class {
/**
* Simulates encryption of a hex-encoded message
*
* @param message - Hex string (with or without 0x).
*/
async encryptMessage(message) {
return encryptMessageMockup(message);
}
/**
* Simulates encryption of a transaction object
*
* @param tx - The transaction to encrypt.
*/
async encryptTransaction(tx) {
return encryptTransactionMockup(tx);
}
};
export {
BITE,
BITEMockup
};
/**
* @license
* SKALE bite.ts
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @license
* SKALE libte-ts
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//# sourceMappingURL=index.mjs.map