@otoplo/wallet-common 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,183 +1,202 @@
1
- import { Address, AddressType, BufferUtils, CommonUtils, Networks } from "libnexa-ts";
2
- import type { Balance } from "../types/wallet.types";
3
- import bigDecimal from 'js-big-decimal';
4
-
5
- export const HD_WALLET_ID = -1;
6
- export const MAX_INT64 = 9223372036854775807n;
7
-
8
- export const CURRENCIES = {
9
- usd: { symbol: '$', name: 'US Dollar' },
10
- eur: { symbol: '€', name: 'Euro' },
11
- gbp: { symbol: '£', name: 'British Pound' },
12
- aud: { symbol: 'A$', name: 'Australian Dollar' },
13
- cad: { symbol: 'CA$', name: 'Canadian Dollar' },
14
- chf: { symbol: 'CHF', name: 'Swiss Franc' },
15
- inr: { symbol: '₹', name: 'Indian Rupee' },
16
- cny: { symbol: 'CN¥', name: 'Chinese Yuan' },
17
- jpy: { symbol: '¥', name: 'Japanese Yen' },
18
- } as const satisfies Record<string, { symbol: string; name: string }>;
19
-
20
- export type CurrencyCode = keyof typeof CURRENCIES;
21
-
22
- export const currencyCodes = Object.keys(CURRENCIES) as CurrencyCode[];
23
-
24
- export function isTestnet(): boolean {
25
- return Networks.defaultNetwork == Networks.testnet;
26
- }
27
-
28
- export function isGenesisHashValid(hash: string): boolean {
29
- if(isTestnet()) {
30
- return hash == "508c843a4b98fb25f57cf9ebafb245a5c16468f06519cdd467059a91e7b79d52";
31
- }
32
- return hash == "edc7144fe1ba4edd0edf35d7eea90f6cb1dba42314aa85da8207e97c5339c801";
33
- }
34
-
35
- export function isValidNexaAddress(address: string, type = AddressType.PayToScriptTemplate): boolean {
36
- return Address.isValid(address, Networks.defaultNetwork, type);
37
- }
38
-
39
- export function getExplorerUrl(): string {
40
- return `https://${(isTestnet() ? 'testnet-' : '')}explorer.nexa.org`;
41
- }
42
-
43
- export function currentTimestamp(): number {
44
- return Math.floor(Date.now() / 1000);
45
- }
46
-
47
- export function isNullOrEmpty(arg?: string | any[] | null): arg is undefined | [] | null | '' {
48
- return !arg || arg.length === 0;
49
- }
50
-
51
- export function truncateStringMiddle(str?: string, maxLength = 0): string {
52
- if (!str || str.length <= maxLength) {
53
- return str || '';
54
- }
55
-
56
- const ellipsis = '...';
57
- const halfLength = Math.floor((maxLength - ellipsis.length) / 2);
58
- const firstHalf = str.slice(0, halfLength);
59
- const secondHalf = str.slice(str.length - halfLength);
60
-
61
- return firstHalf + ellipsis + secondHalf;
62
- };
63
-
64
- export function capitalizeFirstLetter(str: string): string {
65
- if (str.length === 0) {
66
- return "";
67
- }
68
- return str.charAt(0).toUpperCase() + str.substring(1);
69
- }
70
-
71
- export function getAddressBuffer(address: string): Uint8Array {
72
- if (CommonUtils.isHexa(address)) {
73
- return BufferUtils.hexToBuffer(address) ;
74
- }
75
- return Address.fromString(address).data;
76
- }
77
-
78
- export function tokenIdToHex(token: string): string {
79
- if (CommonUtils.isHexa(token)) {
80
- return token;
81
- }
82
- return BufferUtils.bufferToHex(getAddressBuffer(token));
83
- }
84
-
85
- export function tokenHexToAddr(token: string): string {
86
- if (!CommonUtils.isHexa(token)) {
87
- return token;
88
- }
89
- return new Address(getAddressBuffer(token), Networks.defaultNetwork, AddressType.GroupIdAddress).toString();
90
- }
91
-
92
- export function tokenAmountToAssetAmount(amount?: string | number | bigint): string {
93
- if (amount == null || amount === "") {
94
- return "";
95
- }
96
- if (BigInt(amount) <= 0n) {
97
- return "0";
98
- }
99
- return amount.toString();
100
- }
101
-
102
- export function sumBalance(balances: Balance[]): Balance {
103
- let confirmed = BigInt(0), unconfirmed = BigInt(0);
104
- balances.forEach(b => {
105
- confirmed += BigInt(b.confirmed);
106
- unconfirmed += BigInt(b.unconfirmed);
107
- });
108
- return {confirmed: confirmed.toString(), unconfirmed: unconfirmed.toString()};
109
- }
110
-
111
- export function sumTokensBalance(balances: Record<string, Balance>[]): Record<string, Balance> {
112
- const tokensBalance: Record<string, Balance> = {};
113
- balances.forEach(b => {
114
- for (const key in b) {
115
- if (tokensBalance[key]) {
116
- tokensBalance[key].confirmed = (BigInt(tokensBalance[key].confirmed) + BigInt(b[key].confirmed)).toString();
117
- tokensBalance[key].unconfirmed = (BigInt(tokensBalance[key].unconfirmed) + BigInt(b[key].unconfirmed)).toString();
118
- } else {
119
- tokensBalance[key] = { confirmed: BigInt(b[key].confirmed).toString(), unconfirmed: BigInt(b[key].unconfirmed).toString() };
120
- }
121
- }
122
- });
123
-
124
- return tokensBalance;
125
- }
126
-
127
- const FILE_EXTENSION_TO_TYPE = {
128
- // Images
129
- //'.svg': { media: 'image', mime: 'image/svg+xml' },
130
- '.gif': { media: 'image', mime: 'image/gif' },
131
- '.png': { media: 'image', mime: 'image/png' },
132
- '.apng': { media: 'image', mime: 'image/apng' },
133
- '.jpg': { media: 'image', mime: 'image/jpeg' },
134
- '.jpeg': { media: 'image', mime: 'image/jpeg' },
135
- '.avif': { media: 'image', mime: 'image/avif' },
136
- '.webp': { media: 'image', mime: 'image/webp' },
137
- '.bmp': { media: 'image', mime: 'image/bmp' },
138
-
139
- // Videos
140
- '.mp4': { media: 'video', mime: 'video/mp4' },
141
- '.mpeg': { media: 'video', mime: 'video/mpeg' },
142
- '.mpg': { media: 'video', mime: 'video/mpeg' },
143
- '.webm': { media: 'video', mime: 'video/webm' },
144
- '.mov': { media: 'video', mime: 'video/quicktime' },
145
-
146
- // Audio
147
- '.mp3': { media: 'audio', mime: 'audio/mpeg' },
148
- '.ogg': { media: 'audio', mime: 'audio/ogg' },
149
- '.wav': { media: 'audio', mime: 'audio/wav' },
150
- '.m4a': { media: 'audio', mime: 'audio/mp4' },
151
- } as const;
152
-
153
- export function getFileMediaType(filename: string): 'video' | 'audio' | 'image' | 'unknown' {
154
- const lastDotIndex = filename.lastIndexOf('.');
155
- if (lastDotIndex === -1) return 'unknown';
156
-
157
- const extension = filename.slice(lastDotIndex).toLowerCase();
158
- return FILE_EXTENSION_TO_TYPE[extension as keyof typeof FILE_EXTENSION_TO_TYPE]?.media ?? 'unknown';
159
- }
160
-
161
- export function getFileMimeType(filename: string): string {
162
- const lastDotIndex = filename.lastIndexOf('.');
163
- if (lastDotIndex === -1) return 'application/octet-stream';
164
-
165
- const extension = filename.slice(lastDotIndex).toLowerCase();
166
- return FILE_EXTENSION_TO_TYPE[extension as keyof typeof FILE_EXTENSION_TO_TYPE]?.mime ?? 'application/octet-stream';
167
- }
168
-
169
- export function sleep(ms: number): Promise<void> {
170
- return new Promise(resolve => setTimeout(resolve, ms));
171
- }
172
-
173
- export function prettifyAmount(amount: string | number | bigint): string {
174
- return new bigDecimal(amount).stripTrailingZero().getPrettyValue();
175
- }
176
-
177
- export function calculateFiatValue(amount: string | number, price: number, currency: CurrencyCode, locale = 'en-US'): string {
178
- const value = bigDecimal.multiply(amount, price);
179
- return new Intl.NumberFormat(locale, {
180
- style: 'currency',
181
- currency,
182
- }).format(Number(value));
183
- }
1
+ import { Address, AddressType, BufferUtils, CommonUtils, Networks } from "libnexa-ts";
2
+ import type { Balance } from "../types/wallet.types";
3
+
4
+ export const HD_WALLET_ID = -1;
5
+ export const MAX_INT64 = 9223372036854775807n;
6
+
7
+ /** Nexa's target block time, in minutes. */
8
+ export const BLOCK_TIME_MINUTES = 2;
9
+
10
+ export const CURRENCIES = {
11
+ usd: { symbol: '$', name: 'US Dollar' },
12
+ eur: { symbol: '€', name: 'Euro' },
13
+ gbp: { symbol: '£', name: 'British Pound' },
14
+ aud: { symbol: 'A$', name: 'Australian Dollar' },
15
+ cad: { symbol: 'CA$', name: 'Canadian Dollar' },
16
+ chf: { symbol: 'CHF', name: 'Swiss Franc' },
17
+ inr: { symbol: '₹', name: 'Indian Rupee' },
18
+ cny: { symbol: 'CN¥', name: 'Chinese Yuan' },
19
+ jpy: { symbol: '¥', name: 'Japanese Yen' },
20
+ } as const satisfies Record<string, { symbol: string; name: string }>;
21
+
22
+ export type CurrencyCode = keyof typeof CURRENCIES;
23
+
24
+ export const currencyCodes = Object.keys(CURRENCIES) as CurrencyCode[];
25
+
26
+ export function isTestnet(): boolean {
27
+ return Networks.defaultNetwork == Networks.testnet;
28
+ }
29
+
30
+ /** `NEXA` on mainnet, `tNEXA` on testnet. */
31
+ export function getNexaTicker(): string {
32
+ return isTestnet() ? 'tNEXA' : 'NEXA';
33
+ }
34
+
35
+ export function isGenesisHashValid(hash: string): boolean {
36
+ if(isTestnet()) {
37
+ return hash == "508c843a4b98fb25f57cf9ebafb245a5c16468f06519cdd467059a91e7b79d52";
38
+ }
39
+ return hash == "edc7144fe1ba4edd0edf35d7eea90f6cb1dba42314aa85da8207e97c5339c801";
40
+ }
41
+
42
+ export function isValidNexaAddress(address: string, type = AddressType.PayToScriptTemplate): boolean {
43
+ return Address.isValid(address, Networks.defaultNetwork, type);
44
+ }
45
+
46
+ export function getExplorerUrl(): string {
47
+ return `https://${(isTestnet() ? 'testnet-' : '')}explorer.nexa.org`;
48
+ }
49
+
50
+ export function currentTimestamp(): number {
51
+ return Math.floor(Date.now() / 1000);
52
+ }
53
+
54
+ /** Estimated minutes until `future` block, from the block time. 0 once it's reached. */
55
+ export function estimateMinutesToBlock(current: number, future: number): number {
56
+ return Math.max(future - current, 0) * BLOCK_TIME_MINUTES;
57
+ }
58
+
59
+ /**
60
+ * Estimated date of a future block, e.g. `Mar 14, 2027`.
61
+ * `locale` and `options` go to `toLocaleDateString` — defaults to `en-US` like `calculateFiatValue`.
62
+ */
63
+ export function estimateDateByFutureBlock(
64
+ current: number,
65
+ future: number,
66
+ locale = 'en-US',
67
+ options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', year: 'numeric' },
68
+ ): string {
69
+ const time = new Date(Date.now() + estimateMinutesToBlock(current, future) * 60_000);
70
+ return time.toLocaleDateString(locale, options);
71
+ }
72
+
73
+ export function isNullOrEmpty(arg?: string | any[] | null): arg is undefined | [] | null | '' {
74
+ return !arg || arg.length === 0;
75
+ }
76
+
77
+ export function truncateStringMiddle(str?: string, maxLength = 0): string {
78
+ if (!str || str.length <= maxLength) {
79
+ return str || '';
80
+ }
81
+
82
+ const ellipsis = '...';
83
+ const halfLength = Math.floor((maxLength - ellipsis.length) / 2);
84
+ const firstHalf = str.slice(0, halfLength);
85
+ const secondHalf = str.slice(str.length - halfLength);
86
+
87
+ return firstHalf + ellipsis + secondHalf;
88
+ };
89
+
90
+ export function capitalizeFirstLetter(str: string): string {
91
+ if (str.length === 0) {
92
+ return "";
93
+ }
94
+ return str.charAt(0).toUpperCase() + str.substring(1);
95
+ }
96
+
97
+ export function getAddressBuffer(address: string): Uint8Array {
98
+ if (CommonUtils.isHexa(address)) {
99
+ return BufferUtils.hexToBuffer(address) ;
100
+ }
101
+ return Address.fromString(address).data;
102
+ }
103
+
104
+ export function tokenIdToHex(token: string): string {
105
+ if (CommonUtils.isHexa(token)) {
106
+ return token;
107
+ }
108
+ return BufferUtils.bufferToHex(getAddressBuffer(token));
109
+ }
110
+
111
+ export function tokenHexToAddr(token: string): string {
112
+ if (!CommonUtils.isHexa(token)) {
113
+ return token;
114
+ }
115
+ return new Address(getAddressBuffer(token), Networks.defaultNetwork, AddressType.GroupIdAddress).toString();
116
+ }
117
+
118
+ export function tokenAmountToAssetAmount(amount?: string | number | bigint): string {
119
+ if (amount == null || amount === "") {
120
+ return "";
121
+ }
122
+ if (BigInt(amount) <= 0n) {
123
+ return "0";
124
+ }
125
+ return amount.toString();
126
+ }
127
+
128
+ /** Confirmed plus unconfirmed, in base units. The unconfirmed part can be negative (spent, not yet confirmed). */
129
+ export function balanceTotal(balance: Balance): bigint {
130
+ return BigInt(balance.confirmed) + BigInt(balance.unconfirmed);
131
+ }
132
+
133
+ export function sumBalance(balances: Balance[]): Balance {
134
+ let confirmed = BigInt(0), unconfirmed = BigInt(0);
135
+ balances.forEach(b => {
136
+ confirmed += BigInt(b.confirmed);
137
+ unconfirmed += BigInt(b.unconfirmed);
138
+ });
139
+ return {confirmed: confirmed.toString(), unconfirmed: unconfirmed.toString()};
140
+ }
141
+
142
+ export function sumTokensBalance(balances: Record<string, Balance>[]): Record<string, Balance> {
143
+ const tokensBalance: Record<string, Balance> = {};
144
+ balances.forEach(b => {
145
+ for (const key in b) {
146
+ if (tokensBalance[key]) {
147
+ tokensBalance[key].confirmed = (BigInt(tokensBalance[key].confirmed) + BigInt(b[key].confirmed)).toString();
148
+ tokensBalance[key].unconfirmed = (BigInt(tokensBalance[key].unconfirmed) + BigInt(b[key].unconfirmed)).toString();
149
+ } else {
150
+ tokensBalance[key] = { confirmed: BigInt(b[key].confirmed).toString(), unconfirmed: BigInt(b[key].unconfirmed).toString() };
151
+ }
152
+ }
153
+ });
154
+
155
+ return tokensBalance;
156
+ }
157
+
158
+ const FILE_EXTENSION_TO_TYPE = {
159
+ // Images
160
+ //'.svg': { media: 'image', mime: 'image/svg+xml' },
161
+ '.gif': { media: 'image', mime: 'image/gif' },
162
+ '.png': { media: 'image', mime: 'image/png' },
163
+ '.apng': { media: 'image', mime: 'image/apng' },
164
+ '.jpg': { media: 'image', mime: 'image/jpeg' },
165
+ '.jpeg': { media: 'image', mime: 'image/jpeg' },
166
+ '.avif': { media: 'image', mime: 'image/avif' },
167
+ '.webp': { media: 'image', mime: 'image/webp' },
168
+ '.bmp': { media: 'image', mime: 'image/bmp' },
169
+
170
+ // Videos
171
+ '.mp4': { media: 'video', mime: 'video/mp4' },
172
+ '.mpeg': { media: 'video', mime: 'video/mpeg' },
173
+ '.mpg': { media: 'video', mime: 'video/mpeg' },
174
+ '.webm': { media: 'video', mime: 'video/webm' },
175
+ '.mov': { media: 'video', mime: 'video/quicktime' },
176
+
177
+ // Audio
178
+ '.mp3': { media: 'audio', mime: 'audio/mpeg' },
179
+ '.ogg': { media: 'audio', mime: 'audio/ogg' },
180
+ '.wav': { media: 'audio', mime: 'audio/wav' },
181
+ '.m4a': { media: 'audio', mime: 'audio/mp4' },
182
+ } as const;
183
+
184
+ export function getFileMediaType(filename: string): 'video' | 'audio' | 'image' | 'unknown' {
185
+ const lastDotIndex = filename.lastIndexOf('.');
186
+ if (lastDotIndex === -1) return 'unknown';
187
+
188
+ const extension = filename.slice(lastDotIndex).toLowerCase();
189
+ return FILE_EXTENSION_TO_TYPE[extension as keyof typeof FILE_EXTENSION_TO_TYPE]?.media ?? 'unknown';
190
+ }
191
+
192
+ export function getFileMimeType(filename: string): string {
193
+ const lastDotIndex = filename.lastIndexOf('.');
194
+ if (lastDotIndex === -1) return 'application/octet-stream';
195
+
196
+ const extension = filename.slice(lastDotIndex).toLowerCase();
197
+ return FILE_EXTENSION_TO_TYPE[extension as keyof typeof FILE_EXTENSION_TO_TYPE]?.mime ?? 'application/octet-stream';
198
+ }
199
+
200
+ export function sleep(ms: number): Promise<void> {
201
+ return new Promise(resolve => setTimeout(resolve, ms));
202
+ }
@@ -1,3 +1,4 @@
1
+ export * from './amount';
1
2
  export * from './asset';
2
3
  export * from './common';
3
4
  export * from './enums';
@@ -40,9 +40,10 @@ export function generateVaultAddress(pubKey: PublicKey, args: number[]): string
40
40
  return address.toString();
41
41
  }
42
42
 
43
- export function estimateDateByFutureBlock(current: number, future: number): string {
44
- const estimateMins = (future - current) * 2;
45
- const time = new Date();
46
- time.setMinutes(time.getMinutes() + estimateMins);
47
- return time.toLocaleDateString();
43
+ /**
44
+ * A vault is spendable once the chain reached its lock block: a transaction with that lock time
45
+ * can go into the next block (`OP_CHECKLOCKTIMEVERIFY` in the template). `false` while the height is unknown (0).
46
+ */
47
+ export function isVaultUnlocked(lockBlock: number, height: number): boolean {
48
+ return height > 0 && height >= lockBlock;
48
49
  }