Skip to content

Commit

Permalink
Add missing exports needed by our projects (#1)
Browse files Browse the repository at this point in the history
* [Added] Missing utils needed forour projects

* Code cleaning & formatting

* bump version

---------

Co-authored-by: Segfault <[email protected]>
  • Loading branch information
greedyboi and Segfaultd authored Jan 16, 2024
1 parent 691d690 commit 1c1dfa6
Show file tree
Hide file tree
Showing 18 changed files with 749 additions and 6 deletions.
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@lum-network/sdk-javascript",
"version": "1.0.0-beta.1",
"version": "1.0.0-beta.2",
"description": "Javascript SDK library for NodeJS and Web browsers to interact with the Lum Network.",
"author": "Lum Network <[email protected]>",
"homepage": "https://github.com/lum-network/lumjs#readme",
Expand All @@ -16,9 +16,9 @@
"!CHANGELOG.md"
],
"scripts": {
"build:cjs": "yarn tsc -p tsconfig.json --outDir build --module commonjs || true",
"build:mjs": "yarn tsc -p tsconfig.json --outDir mjs --module es2022 --declaration false || true",
"build:lib": "tsc",
"build:cjs": "npx tsc -p ./tsconfig.json --outDir build --module commonjs || true",
"build:mjs": "npx tsc -p ./tsconfig.json --outDir mjs --module es2022 --declaration false || true",
"build:lib": "npx tsc",
"build:docs": "rimraf docs/lib && typedoc --entryPoints src/helpers --excludeExternals --readme none --out docs/lib --disableSources",
"clean:mjs": "rimraf mjs",
"clean:build": "rimraf build",
Expand Down Expand Up @@ -98,4 +98,4 @@
"dotenv": "^16.3.1",
"uuid": "^9.0.0"
}
}
}
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export * from './codegen';
export * from './codegen';
export * from './registry';
export * from './types';
export * from './utils';
20 changes: 20 additions & 0 deletions src/registry/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-nocheck
import { GeneratedType, Registry } from '@cosmjs/proto-signing';
import { cosmosProtoRegistry, ibcProtoRegistry, lumProtoRegistry, strideProtoRegistry } from '../codegen';

import { TextProposal } from '../codegen/cosmos/gov/v1beta1/gov';
import { SoftwareUpgradeProposal } from '../codegen/cosmos/upgrade/v1beta1/upgrade';
import { WithdrawAndMintProposal } from '../codegen/lum/network/dfract/proposal';
import { ProposalRegisterPool, ProposalUpdatePool, ProposalUpdateParams } from '../codegen/lum/network/millions/gov';

const proposalsRegistry: ReadonlyArray<[string, GeneratedType]> = [
['/cosmos.gov.v1beta1.TextProposal', TextProposal],
['/cosmos.upgrade.v1beta1.SoftwareUpgradeProposal', SoftwareUpgradeProposal],
['/lum.network.millions.ProposalRegisterPool', ProposalRegisterPool],
['/lum.network.millions.ProposalUpdatePool', ProposalUpdatePool],
['/lum.network.millions.ProposalUpdateParams', ProposalUpdateParams],
['/lum.network.dfract.WithdrawAndMintProposal', WithdrawAndMintProposal],
];

export const LumRegistry = new Registry([...lumProtoRegistry, ...proposalsRegistry, ...cosmosProtoRegistry, ...ibcProtoRegistry, ...strideProtoRegistry]);
15 changes: 15 additions & 0 deletions src/types/Account.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Pubkey } from '@cosmjs/amino';
import { ModuleAccount } from '../codegen/cosmos/auth/v1beta1/auth';
import { BaseVestingAccount, ContinuousVestingAccount, DelayedVestingAccount, PeriodicVestingAccount } from '../codegen/cosmos/vesting/v1beta1/vesting';

export interface Account {
readonly address: string;
readonly accountNumber: number;
readonly sequence: number;
readonly pubkey: Pubkey | null;
readonly _moduleAccount?: ModuleAccount;
readonly _baseVestingAccount?: BaseVestingAccount;
readonly _continuousVestingAccount?: ContinuousVestingAccount;
readonly _delayedVestingAccount?: DelayedVestingAccount;
readonly _periodicVestingAccount?: PeriodicVestingAccount;
}
4 changes: 4 additions & 0 deletions src/types/Coin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Coin {
denom: string;
amount: string;
}
4 changes: 4 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './account';
export * from './coin';
export * from './key-store';
export * from './logs';
23 changes: 23 additions & 0 deletions src/types/key-store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* KeyStore storage format (web3 secret storage format)
*/
export interface KeyStore {
version: number;
id: string;
crypto: {
ciphertext: string;
cipherparams: {
iv: string;
};
cipher: string;
kdf: string;
kdfparams: {
dklen: number;
salt: string;
c: number;
prf: string;
};
/** Must use sha3 according to web3 secret storage spec. */
mac: string;
};
}
15 changes: 15 additions & 0 deletions src/types/logs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export interface LogAttribute {
readonly key: string;
readonly value: string;
}

export interface LogEvent {
readonly type: string;
readonly attributes: readonly LogAttribute[];
}

export interface Log {
readonly msg_index: number;
readonly log: string;
readonly events: readonly LogEvent[];
}
66 changes: 66 additions & 0 deletions src/utils/account.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { decodePubkey } from '@cosmjs/proto-signing';
import { assert } from '@cosmjs/utils';

import { BaseAccount, ModuleAccount } from '../codegen/cosmos/auth/v1beta1/auth';
import { BaseVestingAccount, ContinuousVestingAccount, DelayedVestingAccount, PeriodicVestingAccount } from '../codegen/cosmos/vesting/v1beta1/vesting';
import { Any } from '../codegen/google/protobuf/any';

import { Account } from '../types';

function accountFromBaseAccount(input: BaseAccount): Account {
const { address, pubKey, accountNumber, sequence } = input;
const pubkey = pubKey ? decodePubkey(pubKey) : null;

return {
address: address,
pubkey: pubkey,
accountNumber: Number(accountNumber),
sequence: Number(sequence),
};
}

export const accountFromAny = (input: Any): Account => {
const { typeUrl, value } = input;
switch (typeUrl) {
case '/cosmos.auth.v1beta1.BaseAccount':
return accountFromBaseAccount(BaseAccount.decode(value));
case '/cosmos.auth.v1beta1.ModuleAccount': {
const moduleAccount = ModuleAccount.decode(value);
assert(moduleAccount.baseAccount);
return Object.assign(accountFromBaseAccount(moduleAccount.baseAccount), { _moduleAccount: moduleAccount });
}
case '/cosmos.vesting.v1beta1.BaseVestingAccount': {
const vestingAccount = BaseVestingAccount.decode(value);
assert(vestingAccount.baseAccount);
return Object.assign(accountFromBaseAccount(vestingAccount.baseAccount), {
_baseVestingAccount: vestingAccount,
});
}
case '/cosmos.vesting.v1beta1.ContinuousVestingAccount': {
const vestingAccount = ContinuousVestingAccount.decode(value);
assert(vestingAccount.baseVestingAccount);
assert(vestingAccount.baseVestingAccount.baseAccount);
return Object.assign(accountFromBaseAccount(vestingAccount.baseVestingAccount.baseAccount), {
_continuousVestingAccount: vestingAccount,
});
}
case '/cosmos.vesting.v1beta1.DelayedVestingAccount': {
const vestingAccount = DelayedVestingAccount.decode(value);
assert(vestingAccount.baseVestingAccount);
assert(vestingAccount.baseVestingAccount.baseAccount);
return Object.assign(accountFromBaseAccount(vestingAccount.baseVestingAccount.baseAccount), {
_delayedVestingAccount: vestingAccount,
});
}
case '/cosmos.vesting.v1beta1.PeriodicVestingAccount': {
const vestingAccount = PeriodicVestingAccount.decode(value);
assert(vestingAccount.baseVestingAccount);
assert(vestingAccount.baseVestingAccount.baseAccount);
return Object.assign(accountFromBaseAccount(vestingAccount.baseVestingAccount.baseAccount), {
_periodicVestingAccount: vestingAccount,
});
}
default:
throw new Error(`Unsupported type: '${typeUrl}'`);
}
};
45 changes: 45 additions & 0 deletions src/utils/commons.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
export { isNonNullObject, isUint8Array } from '@cosmjs/utils';

import { toHex } from './encoding';

/**
* Sorts an object properties recursively.
*
* @param jsonObj object to sort
* @returns a new object with keys sorted alphabetically
*/
export const sortJSON = <T>(jsonObj: T): T => {
if (jsonObj instanceof Array) {
for (let i = 0; i < jsonObj.length; i++) {
jsonObj[i] = sortJSON(jsonObj[i]);
}
return jsonObj;
} else if (typeof jsonObj !== 'object') {
return jsonObj;
}

let keys = Object.keys(jsonObj as object) as Array<keyof T>;
keys = keys.sort();
const newObject: Partial<T> = {};
for (let i = 0; i < keys.length; i++) {
newObject[keys[i]] = sortJSON((jsonObj as T)[keys[i]]);
}
return newObject as T;
};

/**
* Find the index of an Uint8Array element in an array of Uint8Array.
*
* @param arr Array to search elem
* @param elem Elem to search in array
* @returns The index of the element in the array or -1
*/
export const uint8IndexOf = (arr: Uint8Array[], elem: Uint8Array) => {
const hexElem = toHex(elem);
for (let i = 0; i < arr.length; i++) {
if (hexElem === toHex(arr[i])) {
return i;
}
}
return -1;
};
59 changes: 59 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Lum Exponent
* 1 lum = 10^6 ulum
*/
export const LUM_EXPONENT = 6;

/**
* Lum Coin denomination
*/
export const LUM_DENOM = 'lum';

/**
* Micro Lum Coin denomination
*/
export const MICRO_LUM_DENOM = 'ulum';

/**
* Lum Network Bech32 prefixes
*/
export enum LumBech32Prefixes {
ACC_ADDR = 'lum',
ACC_PUB = 'lumpub',
VAL_ADDR = 'lumvaloper',
VAL_PUB = 'lumvaloperpub',
CONS_ADDR = 'lumvalcons',
CONS_PUB = 'lumvalconspub',
}

/**
* Lum Network HDPath
*
* @see https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
* @see https://github.com/satoshilabs/slips/blob/master/slip-0044.md
*/
export const HD_PATH = "m/44'/880'/0'/";

/**
* Private Key length
*/
export const PRIVATE_KEY_LENGTH = 32;

/**
* Signing version of the SDK
*/
export const LUM_WALLET_SIGNING_VERSION = '1';

/**
* Signing wallets
*/
export enum LumMessageSigner {
PAPER = 'lum-sdk/paper',
LEDGER = 'lum-sdk/ledger',
OFFLINE = 'lum-sdk/offline',
}

/**
* Chain ID used for message signature by wallet implementations that require one
*/
export const LUM_SIGN_ONLY_CHAIN_ID = 'lum-signature-only';
74 changes: 74 additions & 0 deletions src/utils/encoding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import hexEncoding from 'crypto-js/enc-hex';
import { toHex, fromHex, toBase64, fromBase64, toAscii, fromAscii, toUtf8, fromUtf8, toRfc3339, fromRfc3339, fromBech32, toBech32 } from '@cosmjs/encoding';
import { sha256 } from '@cosmjs/crypto';
import SHA3 from 'crypto-js/sha3';
import { isUint8Array } from '@cosmjs/utils';

/**
* Sha3 hash
*
* @param hex hex bytes to hash
*/
export const sha3 = (hex: string): string => {
const hexEncoded = hexEncoding.parse(hex);
return SHA3(hexEncoded).toString();
};

/**
* Convert a Uint8Array key into its hexadecimal version
*
* @param key (should be secp256k1 but works with anything though)
* @param xPrefix whether or not to prefix the returned hex value by "0x"
*/
export const keyToHex = (key: Uint8Array, xPrefix = false): string => {
const hexKey = toHex(key);
if (xPrefix) {
return '0x' + hexKey;
}
return hexKey;
};

/**
* Convert an hex key into its Uint8Array verison
*
* @param hexKey hexadecimal key to convert
*/
export const keyFromHex = (hexKey: string): Uint8Array => {
if (hexKey.startsWith('0x')) {
return fromHex(hexKey.substr(2));
}
return fromHex(hexKey);
};

/**
* Converts the provided data recursively in order to obtain a json usable version by removing
* complex types and making it serializable
*
* - Uint8Array will be converted to HEX
* - Date will be converted to ISO string
* - Anything else will not be touched
*
* @param data data to convert (can be anything)
*/
export const toJSON = (data: unknown): unknown => {
if (isUint8Array(data)) {
// Force uppercase hex format
return toHex(data).toUpperCase();
} else if (data instanceof Date) {
// Otherwise custom Date class with nanosecond will be stringified as objects instead of datetime
// Note: Nanoseconds data will be lost in the process
return data.toISOString();
} else if (Array.isArray(data)) {
return data.map((v) => toJSON(v));
} else if (typeof data === 'object') {
const jsonObj: { [Key: string]: unknown } = {};
const ks = data as { [key: string]: unknown };
for (const prop in ks) {
jsonObj[prop] = toJSON(ks[prop]);
}
return jsonObj;
}
return data;
};

export { sha256, toHex, fromHex, toBase64, fromBase64, toAscii, fromAscii, toUtf8, fromUtf8, toRfc3339, fromRfc3339, fromBech32, toBech32 };
9 changes: 9 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export * from './account';
export * from './commons';
export * from './constants';
export * from './encoding';
export * from './path';
export * from './txlogs';
export * from './units';
export * from './wallets';
export * from './vesting';
10 changes: 10 additions & 0 deletions src/utils/path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { HD_PATH } from "./constants";

/**
* Get a Lum Network HDPath for a specified account index
*
* @param accountIndex appended at the end of the default Lum derivation path
*/
export const getLumHdPath = (accountIndex = 0, walletIndex = 0): string => {
return HD_PATH + accountIndex.toString() + '/' + walletIndex.toString();
};
Loading

0 comments on commit 1c1dfa6

Please sign in to comment.