@rarible/types
Version:
`@rarible/types` is a TypeScript library that provides type definitions and interfaces for the Rarible ecosystem. This package is designed to facilitate seamless integration with Rarible's APIs and services, ensuring type safety and improved developer exp
70 lines (69 loc) • 2.46 kB
JavaScript
import { randomBinary } from "../../../common/binary/index.js";
import { InvalidAddressError } from "../../common/address.js";
import { createLayer1fulValidator } from "../../common/common.js";
import { BlockchainLayer1Enum } from "../../union/enum/domain.js";
export const aptosAddressRegExp = new RegExp(/^0x[a-fA-F0-9]{1,64}$/);
/**
* Checks Short AND Long formats of address with or without 0-pad
*
* @example 0x1
* @example 0xeeff357ea5c1a4e7bc11b2b17ff2dc2dcca69750bfef1e1ebcaccf8c8018175b
*/
export function isAptosAddress(address) {
return aptosAddressRegExp.test(address);
}
export const aptosAddressLongRegExp = new RegExp(/^0x[a-fA-F0-9]{64}$/);
/**
* Checks Long formats of address with or without 0-pad
*
* @example 0xeeff357ea5c1a4e7bc11b2b17ff2dc2dcca69750bfef1e1ebcaccf8c8018175b
*/
export function isAptosLongAddress(address) {
return aptosAddressLongRegExp.test(address);
}
/**
* Checks Long format of address with 0-pad
*/
export const aptosAddressValidator = createLayer1fulValidator(BlockchainLayer1Enum.APTOS, isAptosAddress);
/**
* Check and convert Aptos-compatible addresses
*
* @note it does normalization (0-pad and lowercase)
* @example 0x1
* @example 0xeeff357ea5c1a4e7bc11b2b17ff2dc2dcca69750bfef1e1ebcaccf8c8018175b
* @see https://aptos.dev/concepts/accounts
*/
export function toAptosAddress(address) {
const safe = toAptosAddressSafe(address);
if (!safe)
throw new InvalidAddressError(BlockchainLayer1Enum.APTOS, address);
return safe;
}
export function toAptosAddressSafe(address) {
if (isAptosAddress(address)) {
const lowercaseAddress = address.toLowerCase();
const addressWithoutPrefix = lowercaseAddress.startsWith("0x") ? lowercaseAddress.slice(2) : lowercaseAddress;
const addressWithPadding = addressWithoutPrefix.padStart(64, "0");
return `0x${addressWithPadding}`;
}
return undefined;
}
/**
* Removes 0-pad from address
*/
export function shortenAptosAddress(address) {
if (address.startsWith("0x")) {
// Remove the '0x' prefix and then strip leading zeros
let trimmedAddress = address.slice(2).replace(/^0+/, "");
return ("0x" + (trimmedAddress || "0"));
}
return address;
}
/**
* Generates random Aptos address
*
* @example 0xeeff357ea5c1a4e7bc11b2b17ff2dc2dcca69750bfef1e1ebcaccf8c8018175b
*/
export function randomAptosAddress() {
return toAptosAddress(randomBinary(32));
}