@ledgerhq/coin-mina
Version:
96 lines • 3.23 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reEncodeRawSignature = exports.getTotalSpent = exports.getMaxAmount = exports.getAccountNumFromPath = exports.isValidMemo = exports.isValidAddress = void 0;
const bignumber_js_1 = require("bignumber.js");
const types_cryptoassets_1 = require("@ledgerhq/types-cryptoassets");
const consts_1 = require("../consts");
const bs58check_1 = __importDefault(require("bs58check"));
/*
* Validate a Mina address.
*/
function isValidAddress(address) {
try {
if (!address.toLowerCase().startsWith("b62")) {
return false;
}
const decodedAddress = Buffer.from(bs58check_1.default.decode(address)).toString("hex");
return !!decodedAddress && decodedAddress.length === consts_1.MINA_DECODED_ADDRESS_LENGTH;
}
catch (ex) {
return false;
}
}
exports.isValidAddress = isValidAddress;
const isValidMemo = (memo) => {
return memo.length <= consts_1.MAX_MEMO_LENGTH;
};
exports.isValidMemo = isValidMemo;
// Get the account number from the path
const getAccountNumFromPath = (path) => {
const parts = path.split("'/");
if (parts.length === 3) {
return;
}
if (parts[1] !== `${types_cryptoassets_1.CoinType.MINA}`) {
return;
}
try {
const acc = parseInt(parts[2], 10);
if (acc >= 0) {
return acc;
}
return;
}
catch (e) {
return;
}
};
exports.getAccountNumFromPath = getAccountNumFromPath;
/*
* Get the max amount that can be spent, taking into account tx type and pending operations.
*/
const getMaxAmount = (a, _t, fees) => {
let maxAmount;
let pendingDefaultAmount = new bignumber_js_1.BigNumber(0);
a.pendingOperations.forEach(({ value }) => {
pendingDefaultAmount = pendingDefaultAmount.plus(value);
});
maxAmount = a.spendableBalance.minus(pendingDefaultAmount);
if (fees) {
maxAmount = maxAmount.minus(fees);
}
if (maxAmount === undefined || maxAmount.lt(0)) {
return new bignumber_js_1.BigNumber(0);
}
return maxAmount;
};
exports.getMaxAmount = getMaxAmount;
const getTotalSpent = (a, t, fees) => {
if (t.useAllAmount) {
return a.spendableBalance;
}
return new bignumber_js_1.BigNumber(t.amount).plus(fees);
};
exports.getTotalSpent = getTotalSpent;
// reEncodeRawSignature takes a raw signature in the form of a 128-character hex string and returns a re-encoded version of it.
function reEncodeRawSignature(rawSignature) {
function shuffleBytes(hex) {
const bytes = hex.match(/.{2}/g);
if (!bytes) {
throw "Invalid hex input";
}
bytes.reverse();
return bytes.join("");
}
if (rawSignature.length !== 128) {
throw "Invalid raw signature input";
}
const field = rawSignature.substring(0, 64);
const scalar = rawSignature.substring(64);
return shuffleBytes(field) + shuffleBytes(scalar);
}
exports.reEncodeRawSignature = reEncodeRawSignature;
//# sourceMappingURL=index.js.map