@needmoretruth/nmts-cli 0.48.1 → 0.49.0
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/CHANGELOG.md +11 -0
- package/README.ko.md +1 -1
- package/README.md +1 -1
- package/dist/artifact-about.d.ts +1 -1
- package/dist/commands/wallet-swap.d.ts +3 -7
- package/dist/commands/wallet-swap.js +110 -86
- package/dist/help-options.js +2 -1
- package/dist/help.js +4 -3
- package/dist/product.d.ts +1 -1
- package/dist/product.js +1 -1
- package/dist/shared/lib/wallet/swap-routes.d.ts +43 -0
- package/dist/shared/lib/wallet/swap-routes.js +62 -0
- package/dist/shared/lib/wallet/swap-rules.d.ts +48 -10
- package/dist/shared/lib/wallet/swap-rules.js +109 -21
- package/dist/shared/lib/wallet/venue-ids.d.ts +19 -2
- package/dist/shared/lib/wallet/venue-ids.js +35 -2
- package/dist/wallet-swap-chain.d.ts +12 -4
- package/dist/wallet-swap-chain.js +76 -36
- package/dist/wallet-swap-quote.d.ts +20 -3
- package/dist/wallet-swap-quote.js +101 -13
- package/dist/wallet-swap-words.d.ts +30 -0
- package/dist/wallet-swap-words.js +70 -0
- package/dist/wallet.d.ts +6 -0
- package/dist/wallet.js +11 -3
- package/package.json +1 -1
- package/server.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,17 @@
|
|
|
3
3
|
Each version's entry is what changed for the person or the program using `nmts`. The product's own
|
|
4
4
|
update history, which covers the site and the server too, is at https://nmts.me/updates.
|
|
5
5
|
|
|
6
|
+
## 0.49.0 — 2026-09-28
|
|
7
|
+
|
|
8
|
+
- `nmts wallet swap` now trades SUI, WAL and USDC in all six directions:
|
|
9
|
+
`nmts wallet swap <SUI|WAL|USDC> <amount|max> --to <SUI|WAL|USDC> --venue deepbook|bluefin`.
|
|
10
|
+
USDC means Circle's native USDC on Sui, matched by its full coin type. A coin that only shares the
|
|
11
|
+
name is refused.
|
|
12
|
+
- On DeepBook, WAL↔SUI is quoted both directly and through USDC in one transaction. The route that
|
|
13
|
+
pays more is the one that gets signed.
|
|
14
|
+
- An agent grant with a spending cap refuses swaps that spend USDC, because the cap counts only SUI
|
|
15
|
+
and WAL.
|
|
16
|
+
|
|
6
17
|
## 0.48.1 — 2026-09-28
|
|
7
18
|
|
|
8
19
|
- 0.48.0 was tagged but never reached npm: one test named the public code file by hand and failed
|
package/README.ko.md
CHANGED
|
@@ -50,7 +50,7 @@ nmts --help
|
|
|
50
50
|
|
|
51
51
|
```sh
|
|
52
52
|
npm install -g github:needmoretruth/nmts-cli # 기본 브랜치
|
|
53
|
-
npm install -g github:needmoretruth/nmts-cli#v0.
|
|
53
|
+
npm install -g github:needmoretruth/nmts-cli#v0.49.0 # 버전을 고정할 때
|
|
54
54
|
npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
|
|
55
55
|
```
|
|
56
56
|
|
package/README.md
CHANGED
|
@@ -51,7 +51,7 @@ default branch, from a pinned version, or from the tarball attached to the
|
|
|
51
51
|
|
|
52
52
|
```sh
|
|
53
53
|
npm install -g github:needmoretruth/nmts-cli # the default branch
|
|
54
|
-
npm install -g github:needmoretruth/nmts-cli#v0.
|
|
54
|
+
npm install -g github:needmoretruth/nmts-cli#v0.49.0 # a pinned version
|
|
55
55
|
npm install -g https://github.com/needmoretruth/nmts-cli/releases/latest/download/nmts.tgz
|
|
56
56
|
```
|
|
57
57
|
|
package/dist/artifact-about.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export declare const CRYPTO_SPEC_URL = "https://github.com/needmoretruth/nmts-re
|
|
|
11
11
|
* is the field's own contract — what the writer says about itself — and a person holding two
|
|
12
12
|
* copies of one account's artefacts can then tell which program made each.
|
|
13
13
|
*/
|
|
14
|
-
export declare const WRITTEN_BY = "nmts-cli 0.
|
|
14
|
+
export declare const WRITTEN_BY = "nmts-cli 0.49.0";
|
|
15
15
|
/** Which of the three artefacts a wrapper is. A reader holding several can sort them. */
|
|
16
16
|
export type ArtifactKind = "recovery-list" | "file-list" | "recovery-kit";
|
|
17
17
|
/**
|
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import { type Network } from "../network.ts";
|
|
2
2
|
import { type SwapReads } from "../wallet-swap-chain.ts";
|
|
3
|
+
import { type MarketPrices } from "../wallet-swap-words.ts";
|
|
3
4
|
import type { SignSwap } from "../wallet-sign.ts";
|
|
4
|
-
|
|
5
|
-
export interface MarketPrices {
|
|
6
|
-
suiUsd: number | null;
|
|
7
|
-
walUsd: number | null;
|
|
8
|
-
}
|
|
5
|
+
export { asMarketPrices, type MarketPrices } from "../wallet-swap-words.ts";
|
|
9
6
|
export interface WalletSwapOptions {
|
|
10
7
|
server?: string | undefined;
|
|
11
8
|
network?: string | undefined;
|
|
@@ -14,7 +11,7 @@ export interface WalletSwapOptions {
|
|
|
14
11
|
yes?: boolean;
|
|
15
12
|
dryRun?: boolean;
|
|
16
13
|
feeCap?: string | undefined;
|
|
17
|
-
/** `--to`: the coin to receive
|
|
14
|
+
/** `--to`: the coin to receive — SUI, WAL or USDC. Without it SUI→WAL and WAL→SUI; USDC must say. */
|
|
18
15
|
to?: string | undefined;
|
|
19
16
|
/** `--venue`: deepbook or bluefin. Without it, both are quoted and the run stops. */
|
|
20
17
|
venue?: string | undefined;
|
|
@@ -31,5 +28,4 @@ export interface WalletSwapOptions {
|
|
|
31
28
|
readPrices?: (server: string) => Promise<MarketPrices | null>;
|
|
32
29
|
sign?: SignSwap;
|
|
33
30
|
}
|
|
34
|
-
export declare function asMarketPrices(value: unknown): MarketPrices | null;
|
|
35
31
|
export declare function walletSwap(operands: readonly string[], options?: WalletSwapOptions): Promise<number>;
|
|
@@ -1,15 +1,21 @@
|
|
|
1
|
-
// `nmts wallet swap <SUI|WAL> <amount|max
|
|
2
|
-
// NMTS key derives, on the venue the person names. ⛔ SIGNS AND SPENDS.
|
|
1
|
+
// `nmts wallet swap <SUI|WAL|USDC> <amount|max> [--to <coin>]` — turn one coin into another, from the
|
|
2
|
+
// wallet this NMTS key derives, on the venue the person names. ⛔ SIGNS AND SPENDS.
|
|
3
3
|
//
|
|
4
|
-
// ⛔
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
4
|
+
// ⛔ THREE COINS, SIX DIRECTIONS. SUI, WAL and Circle's native USDC, any into either of the other two.
|
|
5
|
+
// Without --to, SUI goes to WAL and WAL to SUI (the two-coin behaviour, kept); USDC must say --to.
|
|
6
|
+
// A coin may also be named by its full coin type, and then only the EXACT type counts — a coin
|
|
7
|
+
// whose symbol is "USDC" from another package is refused, never swapped.
|
|
8
|
+
//
|
|
9
|
+
// ⛔ THE ORDER IS THE SAFETY. ① the balances the trade touches are READ, and an unread one stops the
|
|
10
|
+
// run ② the amount and the slippage are judged by the browser's own rules (`shared/lib/wallet/
|
|
11
|
+
// swap-rules.ts`, copied byte-for-byte) ③ the venue's quote is read from the chain — on mainnet
|
|
12
|
+
// BOTH venues when none was named, printed side by side, and the run stops there: neither is a
|
|
13
|
+
// default and nobody recommends one ④ the exact swap is dry-run for its fee ⑤ the quote is compared
|
|
14
|
+
// with the site's reference price when one can be read, and said to be uncompared when none can
|
|
15
|
+
// ⑥ the review is printed ⑦ anything outside the ordinary bands — slippage, fee cap, market
|
|
16
|
+
// distance — is refused; only a person, in mode off, may say `--accept-extremes` ⑧ without `--yes`
|
|
17
|
+
// that is the end ⑨ the wallet agreement is held against the amount and the fee, scope `all`
|
|
18
|
+
// ⑩ only then the signature.
|
|
13
19
|
//
|
|
14
20
|
// ⛔ NOT ON THE MCP SURFACE. A model can ask a person to run this; it cannot run it through a tool call.
|
|
15
21
|
import { request } from "../api.js";
|
|
@@ -17,61 +23,25 @@ import { currentMode } from "../autonomy.js";
|
|
|
17
23
|
import { requireAccountCode } from "../code-access.js";
|
|
18
24
|
import { readCredentialsFile } from "../credentials.js";
|
|
19
25
|
import { NmtsError } from "../errors.js";
|
|
20
|
-
import { isRecord } from "../guards.js";
|
|
21
26
|
import { resolveNetwork } from "../network.js";
|
|
22
27
|
import { BINARY_NAME } from "../product.js";
|
|
23
28
|
import { resolveServer } from "../server.js";
|
|
24
29
|
import { explorerTxUrl } from "../shared/lib/wallet/activity.js";
|
|
25
30
|
import { clampGasBudgetMist, parseTokenAmountToBaseUnits, SUI_GAS_RESERVE_MIST } from "../shared/lib/wallet/send-rules.js";
|
|
26
|
-
import { clampSlippageBps, impliedRate, marketRate, maxSwappableSuiMist, minOutFromQuote, priceDeviationBps, SLIPPAGE_BPS_DEFAULT, SLIPPAGE_BPS_MAX, SLIPPAGE_BPS_MIN, swapExtremes, } from "../shared/lib/wallet/swap-rules.js";
|
|
31
|
+
import { clampSlippageBps, COIN_DECIMALS, directionOf, impliedRate, marketRate, maxSwappableSuiMist, minOutFromQuote, priceDeviationBps, SLIPPAGE_BPS_DEFAULT, SLIPPAGE_BPS_MAX, SLIPPAGE_BPS_MIN, swapExtremes, } from "../shared/lib/wallet/swap-rules.js";
|
|
27
32
|
import { coinAmount, walletAddress } from "../wallet.js";
|
|
28
33
|
import { payingWalletIndex } from "../wallet-pay-index.js";
|
|
29
34
|
import { recordWalletSpend, requireWalletGrant } from "../wallet-grant.js";
|
|
30
35
|
import { railsFor } from "../wallet-swap-chain.js";
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
highSlippage: "the slippage is above 200 bps: a thin order book may keep that much of what goes in",
|
|
34
|
-
lowFee: "the fee cap is under 1.2 times the measured fee: the swap may fail for want of gas, and that gas is gone",
|
|
35
|
-
highFee: "the fee cap is over ten times the measured fee and over 0.05 SUI",
|
|
36
|
-
deviation: "the quote is more than 3% from the site's reference price: the book may be thin or moved",
|
|
37
|
-
};
|
|
38
|
-
function coinOf(raw, what) {
|
|
39
|
-
const up = (raw ?? "").toUpperCase();
|
|
40
|
-
if (up === "SUI" || up === "WAL")
|
|
41
|
-
return up;
|
|
42
|
-
throw new NmtsError(`Say which coin ${what}: SUI or WAL.`, {
|
|
43
|
-
exitCode: 2,
|
|
44
|
-
nextStep: `\`${BINARY_NAME} wallet swap <SUI|WAL> <amount|max> --venue deepbook|bluefin\``,
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
function pct(bps) {
|
|
48
|
-
return `${(bps / 100).toFixed(2).replace(/0+$/, "").replace(/\.$/, "")}%`;
|
|
49
|
-
}
|
|
50
|
-
export function asMarketPrices(value) {
|
|
51
|
-
if (!isRecord(value) || value["unavailable"] === true)
|
|
52
|
-
return null;
|
|
53
|
-
const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null);
|
|
54
|
-
return { suiUsd: num(value["suiUsd"]), walUsd: num(value["walUsd"]) };
|
|
55
|
-
}
|
|
56
|
-
function venueName(venue) {
|
|
57
|
-
return venue === "deepbook" ? "DeepBook" : venue === "bluefin" ? "Bluefin" : "the official Walrus testnet exchange";
|
|
58
|
-
}
|
|
59
|
-
function quoteLine(q, outCoin, inCoin) {
|
|
60
|
-
const fee = q.feeRateBps === null ? "venue fee could not be measured" : `venue fee about ${pct(q.feeRateBps)}`;
|
|
61
|
-
const left = q.leftoverInUnits > 0n ? ` (${coinAmount(q.leftoverInUnits)} ${inCoin} would come back unused)` : "";
|
|
62
|
-
return `${q.venue.padEnd(9)} ${coinAmount(q.outUnits)} ${outCoin} — ${fee}${left}`;
|
|
63
|
-
}
|
|
36
|
+
import { amountOf, asMarketPrices, coinWordOf, EXTREME_WORDS, pct, quoteLine, resolveCoin, USAGE, venueName, } from "../wallet-swap-words.js";
|
|
37
|
+
export { asMarketPrices } from "../wallet-swap-words.js";
|
|
64
38
|
export async function walletSwap(operands, options = {}) {
|
|
65
39
|
const say = options.write ?? ((line) => process.stdout.write(`${line}\n`));
|
|
66
40
|
const [coinRaw, amountRaw] = operands;
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
if (options.to !== undefined && coinOf(options.to, "comes out") !== coinOut) {
|
|
70
|
-
throw new NmtsError(`${coinIn} can only be swapped for ${coinOut}.`, { exitCode: 2, nextStep: `Drop --to, or say --to ${coinOut}.` });
|
|
71
|
-
}
|
|
72
|
-
const direction = coinIn === "SUI" ? "SUI_TO_WAL" : "WAL_TO_SUI";
|
|
41
|
+
const inWord = coinWordOf(coinRaw, "goes in");
|
|
42
|
+
const toWord = options.to === undefined ? null : coinWordOf(options.to, "comes out");
|
|
73
43
|
if (amountRaw === undefined) {
|
|
74
|
-
throw new NmtsError("Say how much.", { exitCode: 2, nextStep:
|
|
44
|
+
throw new NmtsError("Say how much.", { exitCode: 2, nextStep: `${USAGE} — "max" swaps everything that can be swapped.` });
|
|
75
45
|
}
|
|
76
46
|
const resolved = await requireAccountCode();
|
|
77
47
|
// ⛔ WHICH WALLET SWAPS, FIRST — the coins that are read, the quote that is priced, the address
|
|
@@ -81,34 +51,62 @@ export async function walletSwap(operands, options = {}) {
|
|
|
81
51
|
const stored = resolved.source === "file" || resolved.source === "file-locked" ? readCredentialsFile() : null;
|
|
82
52
|
const server = resolveServer(options.server ?? stored?.server);
|
|
83
53
|
const network = resolveNetwork(server, options.network ?? stored?.network);
|
|
54
|
+
// The direction: the coin named, into --to; without --to, SUI↔WAL as before, and USDC must say.
|
|
55
|
+
const coinIn = resolveCoin(inWord, network);
|
|
56
|
+
let coinOut;
|
|
57
|
+
if (toWord !== null) {
|
|
58
|
+
coinOut = resolveCoin(toWord, network);
|
|
59
|
+
}
|
|
60
|
+
else if (coinIn === "USDC") {
|
|
61
|
+
throw new NmtsError("Say which coin USDC becomes: --to SUI or --to WAL.", { exitCode: 2, nextStep: USAGE });
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
coinOut = coinIn === "SUI" ? "WAL" : "SUI";
|
|
65
|
+
}
|
|
66
|
+
const direction = directionOf(coinIn, coinOut);
|
|
67
|
+
if (direction === null) {
|
|
68
|
+
throw new NmtsError(`${coinIn} cannot be swapped for itself.`, { exitCode: 2, nextStep: `Say --to one of the other two coins.` });
|
|
69
|
+
}
|
|
84
70
|
const rails = railsFor(network);
|
|
85
71
|
const reads = await (options.readChain ?? (async (net) => (await import("../wallet-swap-chain.js")).swapReads(net)))(network);
|
|
86
|
-
// ① The balances — read, and refused as unread rather than treated as zero.
|
|
72
|
+
// ① The balances — read, and refused as unread rather than treated as zero. USDC is read only when
|
|
73
|
+
// the trade touches it, so an unreadable USDC never stops a SUI↔WAL swap.
|
|
87
74
|
const purse = await reads.readWallet(address);
|
|
88
|
-
|
|
89
|
-
|
|
75
|
+
const usdcRead = coinIn === "USDC" || coinOut === "USDC" ? await reads.readUsdc(address) : null;
|
|
76
|
+
if (!purse.sui.read || !purse.wal.read || (usdcRead !== null && !usdcRead.read)) {
|
|
77
|
+
const which = [
|
|
78
|
+
!purse.sui.read ? `SUI: ${purse.sui.why}` : null,
|
|
79
|
+
!purse.wal.read ? `WAL: ${purse.wal.why}` : null,
|
|
80
|
+
usdcRead !== null && !usdcRead.read ? `USDC: ${usdcRead.why}` : null,
|
|
81
|
+
].filter((w) => w !== null);
|
|
90
82
|
throw new NmtsError("A balance could not be read, so this tool cannot tell what can be swapped.", {
|
|
91
83
|
exitCode: 1,
|
|
92
84
|
nextStep: `Nothing was signed. That is not an empty wallet — ${which.join("; ")}.`,
|
|
93
85
|
});
|
|
94
86
|
}
|
|
95
|
-
const
|
|
96
|
-
|
|
87
|
+
const held = {
|
|
88
|
+
SUI: purse.sui.baseUnits,
|
|
89
|
+
WAL: purse.wal.baseUnits,
|
|
90
|
+
USDC: usdcRead !== null && usdcRead.read ? usdcRead.baseUnits : 0n,
|
|
91
|
+
};
|
|
92
|
+
const sui = held.SUI;
|
|
97
93
|
// ② The numbers — the browser's rules, unchanged. The gas kept back is the cap the person set,
|
|
98
94
|
// or the same reserve `wallet send` keeps when none was set.
|
|
99
95
|
const gasBudgetMist = options.feeCap === undefined ? undefined : clampGasBudgetMist(parseTokenAmountToBaseUnits(options.feeCap) ?? 0n);
|
|
100
96
|
const keptForGas = gasBudgetMist ?? SUI_GAS_RESERVE_MIST;
|
|
101
|
-
const maxIn =
|
|
102
|
-
const amountInUnits = amountRaw.toLowerCase() === "max" ? maxIn : parseTokenAmountToBaseUnits(amountRaw);
|
|
97
|
+
const maxIn = coinIn === "SUI" ? maxSwappableSuiMist(sui, keptForGas) : held[coinIn];
|
|
98
|
+
const amountInUnits = amountRaw.toLowerCase() === "max" ? maxIn : parseTokenAmountToBaseUnits(amountRaw, COIN_DECIMALS[coinIn]);
|
|
103
99
|
if (amountInUnits === null || amountInUnits <= 0n) {
|
|
104
|
-
throw new NmtsError(
|
|
100
|
+
throw new NmtsError(`The amount must be a number above zero, with at most ${COIN_DECIMALS[coinIn]} decimals for ${coinIn}.`, { exitCode: 2 });
|
|
105
101
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
102
|
+
const shortOfGas = coinIn !== "SUI" && sui < keptForGas;
|
|
103
|
+
if (amountInUnits > maxIn || shortOfGas) {
|
|
104
|
+
const holds = [`${coinAmount(sui)} SUI`, `${coinAmount(held.WAL)} WAL`, ...(usdcRead !== null ? [`${amountOf("USDC", held.USDC)} USDC`] : [])];
|
|
105
|
+
throw new NmtsError(shortOfGas
|
|
106
|
+
? `A ${coinIn} swap pays its fee in SUI, and the wallet holds less SUI than is kept back for that.`
|
|
109
107
|
: "The wallet does not hold that much.", {
|
|
110
108
|
exitCode: 4,
|
|
111
|
-
nextStep: `Nothing was signed. The wallet holds ${
|
|
109
|
+
nextStep: `Nothing was signed. The wallet holds ${holds.join(", ")}; the most that can go in is ${amountOf(coinIn, maxIn)} ${coinIn} (SUI keeps ${coinAmount(keptForGas)} back for the fee).`,
|
|
112
110
|
});
|
|
113
111
|
}
|
|
114
112
|
let slippageBps = SLIPPAGE_BPS_DEFAULT;
|
|
@@ -126,7 +124,7 @@ export async function walletSwap(operands, options = {}) {
|
|
|
126
124
|
if (rails[0] === "exchange") {
|
|
127
125
|
if (options.venue !== undefined)
|
|
128
126
|
throw new NmtsError(`On testnet the only rail is ${venueName("exchange")}; --venue does not apply.`, { exitCode: 2 });
|
|
129
|
-
if (direction
|
|
127
|
+
if (direction !== "SUI_TO_WAL")
|
|
130
128
|
throw new NmtsError(`${venueName("exchange")} only turns SUI into WAL.`, { exitCode: 2 });
|
|
131
129
|
if (options.slippageBps !== undefined)
|
|
132
130
|
throw new NmtsError("The testnet facility takes no minimum; --slippage-bps does not apply.", { exitCode: 2 });
|
|
@@ -135,7 +133,7 @@ export async function walletSwap(operands, options = {}) {
|
|
|
135
133
|
throw new NmtsError("The testnet exchange could not be read, so what it would give is unknown.", { exitCode: 1, nextStep: `Nothing was signed. ${error instanceof Error ? error.message : String(error)}` });
|
|
136
134
|
});
|
|
137
135
|
// The facility's rate is a fraction read off its object; there is no fee to measure and no lot to leave over.
|
|
138
|
-
quote = { outUnits: (amountInUnits * exchange.rateWal) / exchange.rateSui, feeRateBps: null, leftoverInUnits: 0n };
|
|
136
|
+
quote = { outUnits: (amountInUnits * exchange.rateWal) / exchange.rateSui, feeRateBps: null, leftoverInUnits: 0n, route: "direct", leftoverMidUnits: 0n };
|
|
139
137
|
}
|
|
140
138
|
else {
|
|
141
139
|
if (options.venue !== undefined && options.venue !== "deepbook" && options.venue !== "bluefin") {
|
|
@@ -154,10 +152,10 @@ export async function walletSwap(operands, options = {}) {
|
|
|
154
152
|
if (options.venue === undefined) {
|
|
155
153
|
const lines = answers.map((a) => (a.quote === null ? `${a.venue.padEnd(9)} did not answer — ${a.why}` : quoteLine(a.quote, coinOut, coinIn)));
|
|
156
154
|
if (options.json) {
|
|
157
|
-
say(JSON.stringify({ direction, amountInUnits: amountInUnits.toString(), network, quotes: answers.map((a) => (a.quote === null ? { venue: a.venue, answered: false, why: a.why } : { venue: a.venue, answered: true, outUnits: a.quote.outUnits.toString(), feeRateBps: a.quote.feeRateBps, leftoverInUnits: a.quote.leftoverInUnits.toString() })), signed: false }));
|
|
155
|
+
say(JSON.stringify({ direction, amountInUnits: amountInUnits.toString(), network, quotes: answers.map((a) => (a.quote === null ? { venue: a.venue, answered: false, why: a.why } : { venue: a.venue, answered: true, outUnits: a.quote.outUnits.toString(), feeRateBps: a.quote.feeRateBps, leftoverInUnits: a.quote.leftoverInUnits.toString(), route: a.quote.route, leftoverMidUnits: a.quote.leftoverMidUnits.toString() })), signed: false }));
|
|
158
156
|
return 4;
|
|
159
157
|
}
|
|
160
|
-
say(`Quotes for ${
|
|
158
|
+
say(`Quotes for ${amountOf(coinIn, amountInUnits)} ${coinIn} → ${coinOut}, read from the ${network} chain just now`);
|
|
161
159
|
for (const line of lines)
|
|
162
160
|
say(` ${line}`);
|
|
163
161
|
say(``);
|
|
@@ -175,48 +173,66 @@ export async function walletSwap(operands, options = {}) {
|
|
|
175
173
|
bluefin = only.binding ?? undefined;
|
|
176
174
|
}
|
|
177
175
|
if (quote.outUnits <= 0n) {
|
|
178
|
-
throw new NmtsError(`${venueName(venue)} would give nothing for ${
|
|
176
|
+
throw new NmtsError(`${venueName(venue)} would give nothing for ${amountOf(coinIn, amountInUnits)} ${coinIn}: the amount is below one lot, or the book is empty.`, { exitCode: 4, nextStep: "Nothing was signed." });
|
|
179
177
|
}
|
|
180
178
|
const minOutUnits = venue === "exchange" ? 0n : minOutFromQuote(quote.outUnits, slippageBps);
|
|
181
|
-
const shape = { venue, direction, amountInUnits, minOutUnits, gasBudgetMist, bluefin, exchange };
|
|
179
|
+
const shape = { venue, direction, amountInUnits, minOutUnits, gasBudgetMist, bluefin, exchange, route: quote.route };
|
|
182
180
|
// ④ The fee of this exact swap. ⑤ The market check, said as unknown when it is.
|
|
183
181
|
const feeMist = await reads.estimateFee(shape, address);
|
|
184
182
|
const prices = await (options.readPrices ?? (async (base) => asMarketPrices(await request(base, "/api/prices").catch(() => null))))(server).catch(() => null);
|
|
185
|
-
const market = marketRate(direction, prices?.suiUsd, prices?.walUsd);
|
|
186
|
-
const implied = impliedRate(quote.outUnits, amountInUnits);
|
|
183
|
+
const market = marketRate(direction, prices?.suiUsd, prices?.walUsd, prices?.usdcUsd);
|
|
184
|
+
const implied = impliedRate(quote.outUnits, amountInUnits, COIN_DECIMALS[coinOut], COIN_DECIMALS[coinIn]);
|
|
187
185
|
const deviationBps = market !== null && implied !== null ? priceDeviationBps(implied, market) : null;
|
|
188
186
|
const extremes = venue === "exchange" ? [] : swapExtremes({ slippageBps, budgetMist: gasBudgetMist ?? null, estimateMist: feeMist, deviationBps });
|
|
189
|
-
|
|
190
|
-
|
|
187
|
+
// What each coin would be afterwards if the chain gives exactly the quote. USDC handed back by the
|
|
188
|
+
// middle of a through-USDC route counts as USDC.
|
|
189
|
+
const after = (coin) => {
|
|
190
|
+
let v = held[coin];
|
|
191
|
+
if (coin === coinIn)
|
|
192
|
+
v -= amountInUnits - quote.leftoverInUnits;
|
|
193
|
+
if (coin === coinOut)
|
|
194
|
+
v += quote.outUnits;
|
|
195
|
+
if (coin === "USDC")
|
|
196
|
+
v += quote.leftoverMidUnits;
|
|
197
|
+
if (coin === "SUI")
|
|
198
|
+
v -= feeMist ?? 0n;
|
|
199
|
+
return v < 0n ? 0n : v;
|
|
200
|
+
};
|
|
201
|
+
const showsUsdc = usdcRead !== null || quote.leftoverMidUnits > 0n;
|
|
191
202
|
const facts = {
|
|
192
203
|
from: address,
|
|
193
204
|
venue,
|
|
194
205
|
direction,
|
|
206
|
+
route: quote.route,
|
|
195
207
|
amountInUnits: amountInUnits.toString(),
|
|
196
|
-
amountIn:
|
|
208
|
+
amountIn: amountOf(coinIn, amountInUnits),
|
|
197
209
|
coinIn,
|
|
198
210
|
coinOut,
|
|
199
211
|
quotedOutUnits: quote.outUnits.toString(),
|
|
200
|
-
quotedOut:
|
|
212
|
+
quotedOut: amountOf(coinOut, quote.outUnits),
|
|
201
213
|
minOutUnits: minOutUnits.toString(),
|
|
202
|
-
minOut:
|
|
214
|
+
minOut: amountOf(coinOut, minOutUnits),
|
|
203
215
|
slippageBps: venue === "exchange" ? null : slippageBps,
|
|
204
216
|
venueFeeBps: quote.feeRateBps,
|
|
205
217
|
leftoverInUnits: quote.leftoverInUnits.toString(),
|
|
218
|
+
leftoverMidUsdcUnits: quote.leftoverMidUnits.toString(),
|
|
206
219
|
feeMist: feeMist === null ? null : feeMist.toString(),
|
|
207
220
|
feeSui: feeMist === null ? null : coinAmount(feeMist),
|
|
208
221
|
feeCapMist: gasBudgetMist === undefined ? null : gasBudgetMist.toString(),
|
|
209
222
|
deviationBps: deviationBps === null ? null : Math.round(deviationBps * 100) / 100,
|
|
210
223
|
extremes,
|
|
211
224
|
network,
|
|
212
|
-
suiAfter: coinAmount(
|
|
213
|
-
walAfter: coinAmount(
|
|
225
|
+
suiAfter: coinAmount(after("SUI")),
|
|
226
|
+
walAfter: coinAmount(after("WAL")),
|
|
227
|
+
usdcAfter: showsUsdc ? amountOf("USDC", after("USDC")) : null,
|
|
214
228
|
};
|
|
215
229
|
// ⑥ The review, every time.
|
|
216
230
|
if (!options.json) {
|
|
217
231
|
say(`Swapping ${facts.amountIn} ${coinIn} for ${coinOut} on ${venueName(venue)}`);
|
|
218
232
|
say(` from ${address} (wallet ${wallet})`);
|
|
219
|
-
|
|
233
|
+
if (quote.route === "viaUsdc")
|
|
234
|
+
say(` Route ${coinIn} → USDC → ${coinOut}, two pools in one transaction; the minimum covers the whole trade`);
|
|
235
|
+
say(` Quoted ${facts.quotedOut} ${coinOut} — the chain's answer just now, not a promise${quote.leftoverInUnits > 0n ? `; ${amountOf(coinIn, quote.leftoverInUnits)} ${coinIn} would come back unused` : ""}${quote.leftoverMidUnits > 0n ? `; ${amountOf("USDC", quote.leftoverMidUnits)} USDC would come back unused` : ""}`);
|
|
220
236
|
if (venue === "exchange")
|
|
221
237
|
say(` Rate ${exchange?.rateWal} WAL per ${exchange?.rateSui} SUI, read off the facility; it takes no minimum`);
|
|
222
238
|
else
|
|
@@ -226,7 +242,7 @@ export async function walletSwap(operands, options = {}) {
|
|
|
226
242
|
if (gasBudgetMist !== undefined)
|
|
227
243
|
say(` Fee cap ${coinAmount(gasBudgetMist)} SUI — only up to this is used; the rest stays`);
|
|
228
244
|
say(deviationBps === null ? ` Market no reference price could be read just now, so the quote was not compared with the market` : ` Market ${pct(deviationBps)} from the site's reference price (1 ${coinIn} ≈ ${market?.toFixed(4)} ${coinOut})`);
|
|
229
|
-
say(` Afterwards, if the chain gives exactly the quote: about ${facts.suiAfter} SUI and ${facts.walAfter} WAL`);
|
|
245
|
+
say(` Afterwards, if the chain gives exactly the quote: about ${facts.suiAfter} SUI and ${facts.walAfter} WAL${facts.usdcAfter === null ? "" : ` and ${facts.usdcAfter} USDC`}`);
|
|
230
246
|
say(``);
|
|
231
247
|
say(` NMTS is not a party to this trade and takes nothing from it. Any other exchange may be used instead.`);
|
|
232
248
|
if (extremes.length > 0) {
|
|
@@ -271,10 +287,18 @@ export async function walletSwap(operands, options = {}) {
|
|
|
271
287
|
}
|
|
272
288
|
// ⑨ The agreement — scope `all`, the amount and the fee held against its ceiling.
|
|
273
289
|
const spend = {
|
|
274
|
-
walFrost:
|
|
275
|
-
suiMist: (
|
|
290
|
+
walFrost: coinIn === "WAL" ? amountInUnits : 0n,
|
|
291
|
+
suiMist: (coinIn === "SUI" ? amountInUnits : 0n) + (feeMist ?? 0n),
|
|
276
292
|
};
|
|
277
|
-
requireWalletGrant("exchange", spend, new Date(options.now ?? Date.now()));
|
|
293
|
+
const grant = requireWalletGrant("exchange", spend, new Date(options.now ?? Date.now()));
|
|
294
|
+
// ⛔ The agreement's ceilings count SUI and WAL. A USDC spend cannot be held against them, so under
|
|
295
|
+
// an agreement that HAS a ceiling it is refused rather than signed uncounted.
|
|
296
|
+
if (coinIn === "USDC" && (grant.capWalFrost !== null || grant.capSuiMist !== null)) {
|
|
297
|
+
throw new NmtsError("The wallet agreement on this machine has a spending ceiling, and its ceilings count SUI and WAL only.", {
|
|
298
|
+
exitCode: 5,
|
|
299
|
+
nextStep: `Nothing was signed. A USDC swap under a ceiling would go uncounted, so it is refused. To swap USDC, agree again without --cap-wal and --cap-sui: ${BINARY_NAME} unlock wallet --days 7 --scope all`,
|
|
300
|
+
});
|
|
301
|
+
}
|
|
278
302
|
// ⑩ The signature.
|
|
279
303
|
const sign = options.sign ?? (await import("../wallet-sign.js")).signSwap;
|
|
280
304
|
const digest = await sign({ network, code: resolved.code, wallet, shape });
|
|
@@ -286,6 +310,6 @@ export async function walletSwap(operands, options = {}) {
|
|
|
286
310
|
say(``);
|
|
287
311
|
say(` Swapped. Transaction ${digest}`);
|
|
288
312
|
say(` ${explorerTxUrl(digest, network)}`);
|
|
289
|
-
say(` What arrived is what the chain gave — at least the minimum above. \`${BINARY_NAME} wallet\` shows
|
|
313
|
+
say(` What arrived is what the chain gave — at least the minimum above. \`${BINARY_NAME} wallet\` shows the SUI and WAL balances now.`);
|
|
290
314
|
return 0;
|
|
291
315
|
}
|
package/dist/help-options.js
CHANGED
|
@@ -80,7 +80,8 @@ export function optionLines() {
|
|
|
80
80
|
` be listed under in the gift hall of fame (wallet hall)`,
|
|
81
81
|
` --to <folder> Destination folder, as \`${BINARY_NAME} ls\` prints it (put, push).`,
|
|
82
82
|
` For \`credits transfer\` it is the account identifier that receives;`,
|
|
83
|
-
` for \`handover make\`, a public code or a public code file
|
|
83
|
+
` for \`handover make\`, a public code or a public code file;`,
|
|
84
|
+
` for \`wallet swap\`, the coin to receive (SUI, WAL or USDC)`,
|
|
84
85
|
` --dry-run Say what it would cost, and stop (put, push, extend), or what it`,
|
|
85
86
|
` would install, and stop (update). With \`extend\` and \`--pay`,
|
|
86
87
|
` wallet\` nothing is signed and the wallet key is never touched`,
|
package/dist/help.js
CHANGED
|
@@ -78,9 +78,10 @@ export function helpText(version) {
|
|
|
78
78
|
` wallet send <SUI|WAL> <amount|max> <address>`,
|
|
79
79
|
` Send coins to an address — **signs and spends from the wallet**.`,
|
|
80
80
|
` Prints the review; sends only with --yes`,
|
|
81
|
-
` wallet swap <SUI|WAL> <amount|max
|
|
82
|
-
` Swap
|
|
83
|
-
` **signs and spends**. Without --venue, quotes both
|
|
81
|
+
` wallet swap <SUI|WAL|USDC> <amount|max> [--to <SUI|WAL|USDC>]`,
|
|
82
|
+
` Swap SUI, WAL and USDC, any direction, on DeepBook or Bluefin`,
|
|
83
|
+
` (mainnet) — **signs and spends**. Without --venue, quotes both`,
|
|
84
|
+
` and stops. Without --to, SUI→WAL and WAL→SUI; USDC needs --to`,
|
|
84
85
|
` wallet donate <SUI|WAL> <amount>`,
|
|
85
86
|
` A voluntary gift to the developer — **signs and spends**. A person's`,
|
|
86
87
|
` act: refused in mode auto, and needs --yes every time`,
|
package/dist/product.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export declare const BINARY_NAME = "nmts";
|
|
|
9
9
|
* beside it. Here rather than in `main.ts` because the MCP server has to say it too, and a
|
|
10
10
|
* command importing the entry point is a cycle waiting to bite.
|
|
11
11
|
*/
|
|
12
|
-
export declare const VERSION = "0.
|
|
12
|
+
export declare const VERSION = "0.49.0";
|
|
13
13
|
/** Where the product lives, for messages that need to send somebody somewhere real. */
|
|
14
14
|
export declare const HOME_URL = "https://nmts.me";
|
|
15
15
|
/** The source, so a person holding only the built program can find what it was built from. */
|
package/dist/product.js
CHANGED
|
@@ -18,7 +18,7 @@ export const BINARY_NAME = "nmts";
|
|
|
18
18
|
* beside it. Here rather than in `main.ts` because the MCP server has to say it too, and a
|
|
19
19
|
* command importing the entry point is a cycle waiting to bite.
|
|
20
20
|
*/
|
|
21
|
-
export const VERSION = "0.
|
|
21
|
+
export const VERSION = "0.49.0";
|
|
22
22
|
/** Where the product lives, for messages that need to send somebody somewhere real. */
|
|
23
23
|
export const HOME_URL = "https://nmts.me";
|
|
24
24
|
/** The source, so a person holding only the built program can find what it was built from. */
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type SwapCoin, type SwapDirection, type SwapVenue } from "./swap-rules.ts";
|
|
2
|
+
/**
|
|
3
|
+
* The three pools, named FIRST_SECOND. On every pool this product uses, the first coin is
|
|
4
|
+
* DeepBook's base and Bluefin's coin_a, and the pool's on-chain type is `Pool<first, second>` —
|
|
5
|
+
* so the type arguments of a call are always this order, whichever way the trade runs.
|
|
6
|
+
*/
|
|
7
|
+
export type SwapPair = "WAL_SUI" | "SUI_USDC" | "WAL_USDC";
|
|
8
|
+
/** The two coins of each pool, first coin first. */
|
|
9
|
+
export declare const PAIR_COINS: Readonly<Record<SwapPair, readonly [SwapCoin, SwapCoin]>>;
|
|
10
|
+
/** One trade through one pool: which pool, which coin goes in, and whether that is the first coin. */
|
|
11
|
+
export interface SwapHop {
|
|
12
|
+
pair: SwapPair;
|
|
13
|
+
from: SwapCoin;
|
|
14
|
+
to: SwapCoin;
|
|
15
|
+
/** True when the coin going in is the pool's first coin (DeepBook: sells base; Bluefin: a2b). */
|
|
16
|
+
sellsFirst: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** The hop from one coin to another through the one pool that holds both. Throws for one coin twice. */
|
|
19
|
+
export declare function hopFor(from: SwapCoin, to: SwapCoin): SwapHop;
|
|
20
|
+
/**
|
|
21
|
+
* How a venue gets from one coin to the other: straight through the pool that holds both, or —
|
|
22
|
+
* for WAL ↔ SUI only — through USDC, two pools in ONE transaction, where the minimum is enforced
|
|
23
|
+
* on the last pool and so covers the whole trade.
|
|
24
|
+
*/
|
|
25
|
+
export type SwapRoute = "direct" | "viaUsdc";
|
|
26
|
+
/** The pools a route trades through, in order; null when the route does not apply to the direction. */
|
|
27
|
+
export declare function routeHops(direction: SwapDirection, route: SwapRoute): readonly SwapHop[] | null;
|
|
28
|
+
/**
|
|
29
|
+
* The routes a venue quotes for a direction. DeepBook quotes WAL ↔ SUI both ways: its WAL_SUI book
|
|
30
|
+
* measured thin on 2026-09-28 (1,000 WAL → 14.26 SUI against about 29.1 at market, while WAL_USDC
|
|
31
|
+
* then SUI_USDC gave 29.0), but below the USDC books' one-coin minimum the direct book was the
|
|
32
|
+
* only one that paid anything (10 WAL → 0.28 SUI direct, 0 through USDC). Bluefin's WAL/SUI pool
|
|
33
|
+
* is deep, so it trades direct only.
|
|
34
|
+
*/
|
|
35
|
+
export declare function venueRoutes(venue: SwapVenue, direction: SwapDirection): readonly SwapRoute[];
|
|
36
|
+
/**
|
|
37
|
+
* Of one venue's route answers, the one that pays more — that route is what gets built and signed.
|
|
38
|
+
* A tie goes to the direct route (one pool, one fee, fewer coins back). Null when nothing answered.
|
|
39
|
+
*/
|
|
40
|
+
export declare function pickRoute<T extends {
|
|
41
|
+
route: SwapRoute;
|
|
42
|
+
outUnits: bigint;
|
|
43
|
+
}>(answers: readonly T[]): T | null;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Which pools an in-app swap trades through: the three pools among SUI, WAL and USDC, the hop a
|
|
2
|
+
// direction takes, the routes each venue quotes, and how one route is chosen over another.
|
|
3
|
+
// ⚠ PUBLISHED — copied byte-for-byte into the `nmts` command-line package; keep comments
|
|
4
|
+
// self-contained English.
|
|
5
|
+
//
|
|
6
|
+
// CONTRACT: every function is pure — no I/O, no network. Pool ADDRESSES are not here (they are
|
|
7
|
+
// values per network, in `venue-ids.ts`); this file only says which pair and which way.
|
|
8
|
+
import { directionCoins } from "./swap-rules.js";
|
|
9
|
+
/** The two coins of each pool, first coin first. */
|
|
10
|
+
export const PAIR_COINS = {
|
|
11
|
+
WAL_SUI: ["WAL", "SUI"],
|
|
12
|
+
SUI_USDC: ["SUI", "USDC"],
|
|
13
|
+
WAL_USDC: ["WAL", "USDC"],
|
|
14
|
+
};
|
|
15
|
+
const PAIRS = ["WAL_SUI", "SUI_USDC", "WAL_USDC"];
|
|
16
|
+
/** The hop from one coin to another through the one pool that holds both. Throws for one coin twice. */
|
|
17
|
+
export function hopFor(from, to) {
|
|
18
|
+
for (const pair of PAIRS) {
|
|
19
|
+
const [first, second] = PAIR_COINS[pair];
|
|
20
|
+
if (from === first && to === second)
|
|
21
|
+
return { pair, from, to, sellsFirst: true };
|
|
22
|
+
if (from === second && to === first)
|
|
23
|
+
return { pair, from, to, sellsFirst: false };
|
|
24
|
+
}
|
|
25
|
+
throw new Error(`No pool trades ${from} for ${to}.`);
|
|
26
|
+
}
|
|
27
|
+
/** The pools a route trades through, in order; null when the route does not apply to the direction. */
|
|
28
|
+
export function routeHops(direction, route) {
|
|
29
|
+
const { in: from, out: to } = directionCoins(direction);
|
|
30
|
+
if (route === "direct")
|
|
31
|
+
return [hopFor(from, to)];
|
|
32
|
+
if (from === "USDC" || to === "USDC")
|
|
33
|
+
return null;
|
|
34
|
+
return [hopFor(from, "USDC"), hopFor("USDC", to)];
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The routes a venue quotes for a direction. DeepBook quotes WAL ↔ SUI both ways: its WAL_SUI book
|
|
38
|
+
* measured thin on 2026-09-28 (1,000 WAL → 14.26 SUI against about 29.1 at market, while WAL_USDC
|
|
39
|
+
* then SUI_USDC gave 29.0), but below the USDC books' one-coin minimum the direct book was the
|
|
40
|
+
* only one that paid anything (10 WAL → 0.28 SUI direct, 0 through USDC). Bluefin's WAL/SUI pool
|
|
41
|
+
* is deep, so it trades direct only.
|
|
42
|
+
*/
|
|
43
|
+
export function venueRoutes(venue, direction) {
|
|
44
|
+
if (venue === "deepbook" && routeHops(direction, "viaUsdc") !== null)
|
|
45
|
+
return ["direct", "viaUsdc"];
|
|
46
|
+
return ["direct"];
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Of one venue's route answers, the one that pays more — that route is what gets built and signed.
|
|
50
|
+
* A tie goes to the direct route (one pool, one fee, fewer coins back). Null when nothing answered.
|
|
51
|
+
*/
|
|
52
|
+
export function pickRoute(answers) {
|
|
53
|
+
let best = null;
|
|
54
|
+
for (const answer of answers) {
|
|
55
|
+
if (best === null ||
|
|
56
|
+
answer.outUnits > best.outUnits ||
|
|
57
|
+
(answer.outUnits === best.outUnits && answer.route === "direct")) {
|
|
58
|
+
best = answer;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return best;
|
|
62
|
+
}
|