@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.
- package/dist/index.d.ts +71 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +221 -142
- package/dist/index.js.map +1 -1
- package/package.json +3 -4
- package/src/services/asset.ts +3 -3
- package/src/services/market.ts +4 -1
- package/src/services/transaction.ts +2 -2
- package/src/services/tx-transformer.ts +50 -34
- package/src/utils/amount.ts +112 -0
- package/src/utils/common.ts +202 -183
- package/src/utils/index.ts +1 -0
- package/src/utils/vault.ts +6 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@otoplo/wallet-common",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.1",
|
|
4
4
|
"description": "Shared common library for internal use in Otoplo wallet",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "vgrunner",
|
|
@@ -32,12 +32,11 @@
|
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@otoplo/electrum-client": "^2.0.0",
|
|
35
|
-
"@scure/bip39": "^2.4.0"
|
|
36
|
-
"js-big-decimal": "^2.2.0"
|
|
35
|
+
"@scure/bip39": "^2.4.0"
|
|
37
36
|
},
|
|
38
37
|
"devDependencies": {
|
|
39
38
|
"eslint": "^10.16.0",
|
|
40
|
-
"tsdown": "^0.23.
|
|
39
|
+
"tsdown": "^0.23.8",
|
|
41
40
|
"typescript": "^6.0.3",
|
|
42
41
|
"typescript-eslint": "^8.74.0"
|
|
43
42
|
},
|
package/src/services/asset.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { NftEntity, TokenEntity } from "../types/db.types";
|
|
2
2
|
import { getAssetFileUrl, getAssetMetadataUrl } from "../utils/asset";
|
|
3
|
-
import { currentTimestamp, tokenIdToHex } from "../utils/common";
|
|
3
|
+
import { balanceTotal, currentTimestamp, tokenIdToHex } from "../utils/common";
|
|
4
4
|
import type { WalletDB } from "../persistence/wallet-db";
|
|
5
5
|
import type { WalletCache } from "./cache";
|
|
6
6
|
import type { AssetInfo, Balance } from "../types/wallet.types";
|
|
@@ -76,7 +76,7 @@ export class AssetService {
|
|
|
76
76
|
public async syncTokens(accountId: number, tokenBalances: Record<string, Balance>): Promise<void> {
|
|
77
77
|
for (const tokenId in tokenBalances) {
|
|
78
78
|
const balance = tokenBalances[tokenId];
|
|
79
|
-
if (balance &&
|
|
79
|
+
if (balance && balanceTotal(balance) > 0n) {
|
|
80
80
|
const token = await this.getAssetInfo(tokenId);
|
|
81
81
|
if (token && token.type == 'token') {
|
|
82
82
|
const tokenEntity: TokenEntity = {
|
|
@@ -102,7 +102,7 @@ export class AssetService {
|
|
|
102
102
|
|
|
103
103
|
for (const [token, balance] of Object.entries(tokensBalance)) {
|
|
104
104
|
const tokenId = tokenIdToHex(token);
|
|
105
|
-
const hasBalance = balance &&
|
|
105
|
+
const hasBalance = balance && balanceTotal(balance) > 0n;
|
|
106
106
|
const isAssetExist = internalAssets?.some(a => a.tokenIdHex == tokenId);
|
|
107
107
|
if ((!hasBalance && !isAssetExist) || (hasBalance && isAssetExist)) {
|
|
108
108
|
continue;
|
package/src/services/market.ts
CHANGED
|
@@ -21,6 +21,9 @@ interface MarketDataResponse {
|
|
|
21
21
|
total_volume?: number | null;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/** Key of NEXA in the market data (`market_data_updated`'s `data`). */
|
|
25
|
+
export const NEXA_MARKET_ID = 'nexa';
|
|
26
|
+
|
|
24
27
|
export type MarketEvent =
|
|
25
28
|
| { type: 'market_data_updated'; currency: CurrencyCode; data: Record<string, MarketData> }
|
|
26
29
|
| { type: 'currency_updated'; currency: CurrencyCode };
|
|
@@ -32,7 +35,7 @@ export class MarketService {
|
|
|
32
35
|
private static readonly POLL_INTERVAL_MS = 2 * 60 * 1000;
|
|
33
36
|
private static readonly CURRENCY_SETTING = "market-currency";
|
|
34
37
|
private static readonly SUPPORTED_TOKENS: Record<string, string> = {
|
|
35
|
-
nexacoin:
|
|
38
|
+
nexacoin: NEXA_MARKET_ID
|
|
36
39
|
};
|
|
37
40
|
|
|
38
41
|
private readonly walletDb: WalletDB;
|
|
@@ -3,7 +3,7 @@ import { Address, AddressType, Transaction, TransactionBuilder, UnitUtils } from
|
|
|
3
3
|
import type { KeyManager } from "./key";
|
|
4
4
|
import type { RostrumService } from "./rostrum";
|
|
5
5
|
import type { AssetMovement, TransactionDTO, TransactionType } from "../types/db.types";
|
|
6
|
-
import { currentTimestamp, isNullOrEmpty, isValidNexaAddress, MAX_INT64, tokenAmountToAssetAmount, tokenIdToHex } from "../utils/common";
|
|
6
|
+
import { balanceTotal, currentTimestamp, isNullOrEmpty, isValidNexaAddress, MAX_INT64, tokenAmountToAssetAmount, tokenIdToHex } from "../utils/common";
|
|
7
7
|
import { VAULT_FIRST_BLOCK } from "../utils/vault";
|
|
8
8
|
import type { WalletDB } from "../persistence/wallet-db";
|
|
9
9
|
import type { ITXHistory } from "../types/rostrum.types";
|
|
@@ -226,7 +226,7 @@ export class TransactionService {
|
|
|
226
226
|
}
|
|
227
227
|
|
|
228
228
|
private async populateNexaInputsAndChange(txBuilder: TransactionBuilder, from: AddressKey[], toChange: string, options: TxOptions): Promise<Map<string, PrivateKey>> {
|
|
229
|
-
const allKeys = from.filter(k =>
|
|
229
|
+
const allKeys = from.filter(k => balanceTotal(k.balance) > 0n);
|
|
230
230
|
if (isNullOrEmpty(allKeys)) {
|
|
231
231
|
throw new Error("Not enough Nexa balance.");
|
|
232
232
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Input, PrivateKey} from "libnexa-ts";
|
|
2
|
-
import { BufferUtils, Hash, Opcode, Output, OutputSighashType, Script, ScriptFactory, SighashType, Transaction, TxSigner } from "libnexa-ts";
|
|
2
|
+
import { BufferUtils, Hash, InputSighashType, Opcode, Output, OutputSighashType, Script, ScriptFactory, SighashType, Transaction, TxSigner } from "libnexa-ts";
|
|
3
3
|
import type { KeyManager } from "./key";
|
|
4
4
|
import type { RostrumService } from "./rostrum";
|
|
5
5
|
import type { AddressKey, AssetMovement, MovementDetails, TransactionDetails } from "../types";
|
|
@@ -14,8 +14,6 @@ interface TransactionContext {
|
|
|
14
14
|
myOutputs: Map<number, AssetMovement>;
|
|
15
15
|
involvedAssets: Set<string>;
|
|
16
16
|
inputsToSign: Set<number>;
|
|
17
|
-
coveredOutputs: Set<number>;
|
|
18
|
-
allMyOutputsCovered: boolean;
|
|
19
17
|
}
|
|
20
18
|
|
|
21
19
|
export class TransactionTransformer {
|
|
@@ -55,8 +53,6 @@ export class TransactionTransformer {
|
|
|
55
53
|
myOutputs: new Map<number, AssetMovement>(),
|
|
56
54
|
involvedAssets: new Set<string>(),
|
|
57
55
|
inputsToSign: new Set<number>(),
|
|
58
|
-
coveredOutputs: new Set<number>(),
|
|
59
|
-
allMyOutputsCovered: false,
|
|
60
56
|
};
|
|
61
57
|
} catch {
|
|
62
58
|
throw new Error("Invalid transaction format.");
|
|
@@ -96,10 +92,27 @@ export class TransactionTransformer {
|
|
|
96
92
|
}
|
|
97
93
|
|
|
98
94
|
if (input.scriptSig.findPlaceholder() > 0) {
|
|
95
|
+
if (input.output.address != context.address && !this.isMyContractInput(context, input)) {
|
|
96
|
+
throw new Error("Transaction requests a signature for an input this wallet does not control.");
|
|
97
|
+
}
|
|
99
98
|
context.inputsToSign.add(index);
|
|
100
99
|
}
|
|
101
100
|
}
|
|
102
101
|
|
|
102
|
+
/**
|
|
103
|
+
* A script template input that this wallet may sign: its visible args contain the wallet's public key
|
|
104
|
+
* (e.g. withdrawing or closing a contract offer posted by this wallet).
|
|
105
|
+
*/
|
|
106
|
+
private isMyContractInput(context: TransactionContext, input: Input): boolean {
|
|
107
|
+
const scriptPubKey = input.output!.scriptPubKey;
|
|
108
|
+
if (!scriptPubKey.isScriptTemplateOut()) {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const pubKey = context.privateKey.publicKey.toBuffer();
|
|
113
|
+
return scriptPubKey.getVisibleArgs().chunks.some(chunk => chunk.buf != null && BufferUtils.equals(chunk.buf, pubKey));
|
|
114
|
+
}
|
|
115
|
+
|
|
103
116
|
private processOutputs(context: TransactionContext): void {
|
|
104
117
|
for (let i = 0; i < context.txDetails.tx.outputs.length; i++) {
|
|
105
118
|
const output = context.txDetails.tx.outputs[i].toObject();
|
|
@@ -130,7 +143,6 @@ export class TransactionTransformer {
|
|
|
130
143
|
const subscript = this.validateAndGetSubscript(input);
|
|
131
144
|
|
|
132
145
|
if (input.scriptSig.isEmpty()) { // only p2pkt can be empty
|
|
133
|
-
context.allMyOutputsCovered = true;
|
|
134
146
|
const txSig = TxSigner.sign(context.txDetails.tx, index, SighashType.ALL, subscript, context.privateKey).toTxFormat();
|
|
135
147
|
const constraint = Script.empty().add(context.privateKey.publicKey.toBuffer());
|
|
136
148
|
input.scriptSig = ScriptFactory.buildScriptTemplateIn(undefined, constraint, Script.empty().add(txSig))
|
|
@@ -139,16 +151,13 @@ export class TransactionTransformer {
|
|
|
139
151
|
const placeholder = input.scriptSig.chunks[placeholderIndex];
|
|
140
152
|
const sigHashBuf = placeholder.buf!.subarray(64);
|
|
141
153
|
const sigHashType = SighashType.fromBuffer(sigHashBuf);
|
|
142
|
-
this.
|
|
154
|
+
this.validateSigHashType(sigHashType, index);
|
|
155
|
+
this.validateOutputsCoverage(context, sigHashType);
|
|
143
156
|
|
|
144
157
|
const txSig = TxSigner.sign(context.txDetails.tx, index, sigHashType, subscript, context.privateKey).toTxFormat(sigHashBuf);
|
|
145
158
|
input.scriptSig.replaceChunk(placeholderIndex, Script.empty().add(txSig));
|
|
146
159
|
}
|
|
147
160
|
}
|
|
148
|
-
|
|
149
|
-
if (!context.allMyOutputsCovered) {
|
|
150
|
-
throw new Error("Some of interested outputs are not covered by signatures.");
|
|
151
|
-
}
|
|
152
161
|
}
|
|
153
162
|
|
|
154
163
|
private validateAndGetSubscript(input: Input): Script {
|
|
@@ -176,37 +185,44 @@ export class TransactionTransformer {
|
|
|
176
185
|
throw new Error("Unsupported prevout script type.");
|
|
177
186
|
}
|
|
178
187
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
188
|
+
/**
|
|
189
|
+
* The signature must commit to the input it signs, otherwise it is not bound to any outpoint
|
|
190
|
+
* and can be replayed on any other coin locked by the same key and subscript.
|
|
191
|
+
* Only output sighash types that we know how to check coverage for are accepted.
|
|
192
|
+
*/
|
|
193
|
+
private validateSigHashType(sigHashType: SighashType, index: number): void {
|
|
194
|
+
const inputCovered = sigHashType.inType == InputSighashType.ALL
|
|
195
|
+
|| sigHashType.inType == InputSighashType.THISIN
|
|
196
|
+
|| (sigHashType.inType == InputSighashType.FIRSTN && sigHashType.inData[0] > index);
|
|
197
|
+
|
|
198
|
+
if (!inputCovered) {
|
|
199
|
+
throw new Error("Signature type does not cover the input being signed.");
|
|
182
200
|
}
|
|
183
201
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
context.coveredOutputs.add(i);
|
|
192
|
-
}
|
|
193
|
-
this.checkSignatureCoverage(context);
|
|
194
|
-
} else {
|
|
195
|
-
context.allMyOutputsCovered = true;
|
|
202
|
+
switch (sigHashType.outType) {
|
|
203
|
+
case OutputSighashType.ALL:
|
|
204
|
+
case OutputSighashType.FIRSTN:
|
|
205
|
+
case OutputSighashType.TWO:
|
|
206
|
+
break;
|
|
207
|
+
default:
|
|
208
|
+
throw new Error("Unsupported signature type.");
|
|
196
209
|
}
|
|
197
210
|
}
|
|
198
211
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
212
|
+
/**
|
|
213
|
+
* Each signature must commit to every output paid to this wallet.
|
|
214
|
+
* Coverage is checked per signature, never pooled across signatures.
|
|
215
|
+
*/
|
|
216
|
+
private validateOutputsCoverage(context: TransactionContext, sigHashType: SighashType): void {
|
|
204
217
|
for (const i of context.myOutputs.keys()) {
|
|
205
|
-
|
|
206
|
-
|
|
218
|
+
const covered = sigHashType.outType == OutputSighashType.ALL
|
|
219
|
+
|| (sigHashType.outType == OutputSighashType.FIRSTN && i < sigHashType.outData[0])
|
|
220
|
+
|| (sigHashType.outType == OutputSighashType.TWO && sigHashType.outData.includes(i));
|
|
221
|
+
|
|
222
|
+
if (!covered) {
|
|
223
|
+
throw new Error("Signature does not cover your outputs.");
|
|
207
224
|
}
|
|
208
225
|
}
|
|
209
|
-
context.allMyOutputsCovered = true;
|
|
210
226
|
}
|
|
211
227
|
|
|
212
228
|
private async processAssetMovements(context: TransactionContext): Promise<void> {
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { UnitType, UnitUtils } from "libnexa-ts";
|
|
2
|
+
import { type CurrencyCode, getNexaTicker } from "./common";
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* Display formatting for amounts. Amounts are bigint base units (satoshis, token units) and stay that way
|
|
6
|
+
* for any math (sums, fees, balance checks) — these helpers only turn them into text.
|
|
7
|
+
*
|
|
8
|
+
* Formatting goes through `Number` and `Intl.NumberFormat`: Hermes' `Intl` throws on a bigint and turns a decimal
|
|
9
|
+
* string into a `Number` anyway. A `Number` shows the exact digits while the amount, counted in its smallest
|
|
10
|
+
* *shown* unit, is below 2^52 (~4.5 quadrillion) — 45 trillion with 2 decimals shown, 45 billion with 5,
|
|
11
|
+
* 45 million with 8. Above that, the last digit or two come out rounded. NEXA (21 trillion max supply,
|
|
12
|
+
* 2 decimals) is always exact.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Cached `Intl.NumberFormat`s: creating one is slow (on Hermes especially), formatting with one is fast. */
|
|
16
|
+
const numberFormatters = new Map<string, Intl.NumberFormat>();
|
|
17
|
+
|
|
18
|
+
function getNumberFormatter(locale: string, options: Intl.NumberFormatOptions): Intl.NumberFormat {
|
|
19
|
+
const key = `${locale}|${JSON.stringify(options)}`;
|
|
20
|
+
let formatter = numberFormatters.get(key);
|
|
21
|
+
if (!formatter) {
|
|
22
|
+
formatter = new Intl.NumberFormat(locale, options);
|
|
23
|
+
numberFormatters.set(key, formatter);
|
|
24
|
+
}
|
|
25
|
+
return formatter;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface FormatAmountOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Decimals shown at most — the rest are cut off, not rounded. Default 5; pass the token's `decimals` to show all.
|
|
31
|
+
*
|
|
32
|
+
* Each extra decimal shown lowers the exact range tenfold (see above): showing all decimals is exact up to
|
|
33
|
+
* 45 million tokens with 8 decimals, but only up to 0.0045 with 18. Where every digit must be right
|
|
34
|
+
* (e.g. a send confirmation), use `UnitUtils.formatUnits(amount, decimals)` — exact, but not grouped or localized.
|
|
35
|
+
*/
|
|
36
|
+
maxDecimals?: number;
|
|
37
|
+
/** Grouping, separators and digits. Default `en-US`, like `calculateFiatValue`. */
|
|
38
|
+
locale?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* An amount in base units (token units, satoshis) for display, without trailing zeros:
|
|
43
|
+
* `formatTokenAmount(123456789n, 2)` → `1,234,567.89`, `formatTokenAmount(100n, 2)` → `1`.
|
|
44
|
+
*
|
|
45
|
+
* Decimals beyond `maxDecimals` are cut off in bigint, so a balance never shows more than it holds
|
|
46
|
+
* (`0.999999` → `0.99999`, not `1`). A non-zero amount that would show as 0 becomes `<0.00001`.
|
|
47
|
+
*/
|
|
48
|
+
export function formatTokenAmount(
|
|
49
|
+
amount: bigint | string,
|
|
50
|
+
decimals: number,
|
|
51
|
+
{ maxDecimals = 5, locale = 'en-US' }: FormatAmountOptions = {},
|
|
52
|
+
): string {
|
|
53
|
+
const units = BigInt(amount);
|
|
54
|
+
const shown = Math.min(decimals, maxDecimals);
|
|
55
|
+
// Bigint division truncates toward zero: the hidden decimals are dropped, for negatives too.
|
|
56
|
+
const cut = units / 10n ** BigInt(decimals - shown);
|
|
57
|
+
const formatter = getNumberFormatter(locale, { maximumFractionDigits: shown });
|
|
58
|
+
|
|
59
|
+
if (cut === 0n && units !== 0n) {
|
|
60
|
+
return `${units < 0n ? '-' : ''}<${formatter.format(10 ** -shown)}`;
|
|
61
|
+
}
|
|
62
|
+
// Parsing the exact decimal string rounds once; Intl's rounding to `shown` decimals then snaps it back.
|
|
63
|
+
return formatter.format(Number(UnitUtils.formatUnits(cut, shown)));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* A token amount with its ticker, e.g. `1,500.25 USDT`.
|
|
68
|
+
* Tokens without a ticker (it's optional in the token's genesis) show the amount alone.
|
|
69
|
+
*/
|
|
70
|
+
export function formatTokenAmountWithTicker(
|
|
71
|
+
amount: bigint | string,
|
|
72
|
+
decimals: number,
|
|
73
|
+
ticker: string,
|
|
74
|
+
options: FormatAmountOptions = {},
|
|
75
|
+
): string {
|
|
76
|
+
const formatted = formatTokenAmount(amount, decimals, options);
|
|
77
|
+
return ticker ? `${formatted} ${ticker}` : formatted;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Satoshis as a NEXA amount: `1,234,567.5`. Negative amounts keep their minus sign. Always exact (see above). */
|
|
81
|
+
export function formatNexaAmount(sats: bigint | string, options: FormatAmountOptions = {}): string {
|
|
82
|
+
return formatTokenAmount(sats, UnitType.NEXA, options);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Satoshis as a NEXA amount with the ticker: `1,234,567.5 NEXA` (`tNEXA` on testnet). */
|
|
86
|
+
export function formatNexaAmountWithTicker(sats: bigint | string, options: FormatAmountOptions = {}): string {
|
|
87
|
+
return formatTokenAmountWithTicker(sats, UnitType.NEXA, getNexaTicker(), options);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Fiat value of an amount in base units (satoshis, token units), e.g. `$1,234.56`.
|
|
92
|
+
* A non-zero value that would round to zero shows as below the currency's smallest unit: `<$0.01`, `<¥1`.
|
|
93
|
+
* Exact to the cent below ~$10 trillion.
|
|
94
|
+
*/
|
|
95
|
+
export function calculateFiatValue(
|
|
96
|
+
amount: bigint | string,
|
|
97
|
+
decimals: number,
|
|
98
|
+
price: number,
|
|
99
|
+
currency: CurrencyCode,
|
|
100
|
+
locale = 'en-US',
|
|
101
|
+
): string {
|
|
102
|
+
const formatter = getNumberFormatter(locale, { style: 'currency', currency });
|
|
103
|
+
const value = Number(UnitUtils.formatUnits(amount, decimals)) * price;
|
|
104
|
+
|
|
105
|
+
// The currency's smallest unit, from its decimals: 0.01 for most, 1 for yen.
|
|
106
|
+
const smallest = 10 ** -(formatter.resolvedOptions().maximumFractionDigits ?? 2);
|
|
107
|
+
// Below half of it, the formatted value would round to zero.
|
|
108
|
+
if (value !== 0 && Math.abs(value) < smallest / 2) {
|
|
109
|
+
return `${value < 0 ? '-' : ''}<${formatter.format(smallest)}`;
|
|
110
|
+
}
|
|
111
|
+
return formatter.format(value);
|
|
112
|
+
}
|