@dsh-ft/dsh-fft-paper-trading 0.7.2 → 0.8.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/README.md +4 -3
- package/README.zh.md +4 -3
- package/lib/agent/account-tools.d.ts +18 -0
- package/lib/agent/account-tools.d.ts.map +1 -0
- package/lib/agent/account-tools.js +127 -0
- package/lib/agent/account-tools.js.map +1 -0
- package/lib/agent/futures-tools.d.ts.map +1 -1
- package/lib/agent/futures-tools.js +1 -6
- package/lib/agent/futures-tools.js.map +1 -1
- package/lib/agent/ledger-tools.d.ts +15 -3
- package/lib/agent/ledger-tools.d.ts.map +1 -1
- package/lib/agent/ledger-tools.js +11 -15
- package/lib/agent/ledger-tools.js.map +1 -1
- package/lib/agent/tool-result.d.ts +19 -0
- package/lib/agent/tool-result.d.ts.map +1 -0
- package/lib/agent/tool-result.js +22 -0
- package/lib/agent/tool-result.js.map +1 -0
- package/lib/agent/tools.d.ts +10 -2
- package/lib/agent/tools.d.ts.map +1 -1
- package/lib/agent/tools.js +26 -11
- package/lib/agent/tools.js.map +1 -1
- package/lib/client.js +1448 -282
- package/lib/contract/accounts.d.ts +76 -0
- package/lib/contract/accounts.d.ts.map +1 -0
- package/lib/contract/accounts.js +6 -0
- package/lib/contract/accounts.js.map +1 -0
- package/lib/contract/common.d.ts +144 -0
- package/lib/contract/common.d.ts.map +1 -0
- package/lib/contract/common.js +33 -0
- package/lib/contract/common.js.map +1 -0
- package/lib/contract/domain.d.ts +196 -0
- package/lib/contract/domain.d.ts.map +1 -0
- package/lib/contract/domain.js +14 -0
- package/lib/contract/domain.js.map +1 -0
- package/lib/contract/errors.d.ts +6 -0
- package/lib/contract/errors.d.ts.map +1 -0
- package/lib/contract/errors.js +6 -0
- package/lib/contract/errors.js.map +1 -0
- package/lib/contract/index.d.ts +15 -0
- package/lib/contract/index.d.ts.map +1 -0
- package/lib/contract/index.js +15 -0
- package/lib/contract/index.js.map +1 -0
- package/lib/contract/ledger.d.ts +40 -0
- package/lib/contract/ledger.d.ts.map +1 -0
- package/lib/contract/ledger.js +6 -0
- package/lib/contract/ledger.js.map +1 -0
- package/lib/contract/market.d.ts +30 -0
- package/lib/contract/market.d.ts.map +1 -0
- package/lib/contract/market.js +6 -0
- package/lib/contract/market.js.map +1 -0
- package/lib/contract/rpc.d.ts +24 -0
- package/lib/contract/rpc.d.ts.map +1 -0
- package/lib/contract/rpc.js +6 -0
- package/lib/contract/rpc.js.map +1 -0
- package/lib/contract.d.ts +6 -403
- package/lib/contract.d.ts.map +1 -1
- package/lib/contract.js +6 -24
- package/lib/contract.js.map +1 -1
- package/lib/core/session.d.ts +1 -1
- package/lib/core/session.d.ts.map +1 -1
- package/lib/core/session.js +1 -2
- package/lib/core/session.js.map +1 -1
- package/lib/data/cached-market-data.d.ts +61 -0
- package/lib/data/cached-market-data.d.ts.map +1 -0
- package/lib/data/cached-market-data.js +174 -0
- package/lib/data/cached-market-data.js.map +1 -0
- package/lib/data/futures-market-data.d.ts.map +1 -1
- package/lib/data/futures-market-data.js +9 -10
- package/lib/data/futures-market-data.js.map +1 -1
- package/lib/index.d.ts +25 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +156 -18
- package/lib/index.js.map +1 -1
- package/lib/service/account-moves.d.ts +64 -0
- package/lib/service/account-moves.d.ts.map +1 -0
- package/lib/service/account-moves.js +49 -0
- package/lib/service/account-moves.js.map +1 -0
- package/lib/service/accounts-rpc.d.ts +17 -0
- package/lib/service/accounts-rpc.d.ts.map +1 -0
- package/lib/service/accounts-rpc.js +77 -0
- package/lib/service/accounts-rpc.js.map +1 -0
- package/lib/service/compare-rpc.d.ts +22 -0
- package/lib/service/compare-rpc.d.ts.map +1 -0
- package/lib/service/compare-rpc.js +70 -0
- package/lib/service/compare-rpc.js.map +1 -0
- package/lib/service/errors.d.ts +20 -4
- package/lib/service/errors.d.ts.map +1 -1
- package/lib/service/errors.js +12 -5
- package/lib/service/errors.js.map +1 -1
- package/lib/service/futures-rpc.d.ts.map +1 -1
- package/lib/service/futures-rpc.js +7 -25
- package/lib/service/futures-rpc.js.map +1 -1
- package/lib/service/futures-service.d.ts +28 -8
- package/lib/service/futures-service.d.ts.map +1 -1
- package/lib/service/futures-service.js +144 -146
- package/lib/service/futures-service.js.map +1 -1
- package/lib/service/ledger-admin.d.ts +67 -0
- package/lib/service/ledger-admin.d.ts.map +1 -0
- package/lib/service/ledger-admin.js +102 -0
- package/lib/service/ledger-admin.js.map +1 -0
- package/lib/service/paper-service.d.ts +39 -12
- package/lib/service/paper-service.d.ts.map +1 -1
- package/lib/service/paper-service.js +177 -156
- package/lib/service/paper-service.js.map +1 -1
- package/lib/service/route.d.ts.map +1 -1
- package/lib/service/route.js +5 -2
- package/lib/service/route.js.map +1 -1
- package/lib/service/rpc-support.d.ts +34 -0
- package/lib/service/rpc-support.d.ts.map +1 -0
- package/lib/service/rpc-support.js +57 -0
- package/lib/service/rpc-support.js.map +1 -0
- package/lib/service/rpc.d.ts +20 -3
- package/lib/service/rpc.d.ts.map +1 -1
- package/lib/service/rpc.js +44 -25
- package/lib/service/rpc.js.map +1 -1
- package/lib/store/accounts.d.ts +110 -0
- package/lib/store/accounts.d.ts.map +1 -0
- package/lib/store/accounts.js +352 -0
- package/lib/store/accounts.js.map +1 -0
- package/lib/store/atomic-file.d.ts +16 -0
- package/lib/store/atomic-file.d.ts.map +1 -0
- package/lib/store/atomic-file.js +34 -0
- package/lib/store/atomic-file.js.map +1 -0
- package/lib/store/futures-repo.d.ts +8 -49
- package/lib/store/futures-repo.d.ts.map +1 -1
- package/lib/store/futures-repo.js +34 -246
- package/lib/store/futures-repo.js.map +1 -1
- package/lib/store/ledger-repo-base.d.ts +120 -0
- package/lib/store/ledger-repo-base.d.ts.map +1 -0
- package/lib/store/ledger-repo-base.js +275 -0
- package/lib/store/ledger-repo-base.js.map +1 -0
- package/lib/store/notes.d.ts +29 -0
- package/lib/store/notes.d.ts.map +1 -0
- package/lib/store/notes.js +78 -0
- package/lib/store/notes.js.map +1 -0
- package/lib/store/paths.d.ts +2 -0
- package/lib/store/paths.d.ts.map +1 -1
- package/lib/store/paths.js +4 -0
- package/lib/store/paths.js.map +1 -1
- package/lib/store/repo.d.ts +15 -55
- package/lib/store/repo.d.ts.map +1 -1
- package/lib/store/repo.js +41 -206
- package/lib/store/repo.js.map +1 -1
- package/lib/store/shortlist.d.ts.map +1 -1
- package/lib/store/shortlist.js +4 -6
- package/lib/store/shortlist.js.map +1 -1
- package/lib/store/snapshots.d.ts +0 -3
- package/lib/store/snapshots.d.ts.map +1 -1
- package/lib/store/snapshots.js +0 -3
- package/lib/store/snapshots.js.map +1 -1
- package/package.json +1 -1
- package/src/agent/account-tools.ts +136 -0
- package/src/agent/futures-tools.ts +1 -6
- package/src/agent/ledger-tools.ts +29 -16
- package/src/agent/tool-result.ts +27 -0
- package/src/agent/tools.ts +30 -10
- package/src/client/entry.js +14 -0
- package/src/client/parts/10-core.js +535 -0
- package/src/client/parts/20-styles.js +336 -0
- package/src/client/parts/30-atoms.js +769 -0
- package/src/client/parts/35-hooks.js +447 -0
- package/src/client/parts/40-stock-tabs.js +641 -0
- package/src/client/parts/50-futures.js +911 -0
- package/src/client/parts/60-shell.js +706 -0
- package/src/client/parts/70-plugin.js +67 -0
- package/src/contract/accounts.ts +82 -0
- package/src/contract/common.ts +173 -0
- package/src/contract/domain.ts +217 -0
- package/src/contract/errors.ts +34 -0
- package/src/contract/index.ts +15 -0
- package/src/contract/ledger.ts +42 -0
- package/src/contract/market.ts +39 -0
- package/src/contract/rpc.ts +15 -0
- package/src/contract.ts +6 -472
- package/src/core/session.ts +1 -2
- package/src/data/cached-market-data.ts +193 -0
- package/src/data/futures-market-data.ts +9 -10
- package/src/index.ts +168 -20
- package/src/service/account-moves.ts +72 -0
- package/src/service/accounts-rpc.ts +80 -0
- package/src/service/compare-rpc.ts +77 -0
- package/src/service/errors.ts +23 -4
- package/src/service/futures-rpc.ts +7 -24
- package/src/service/futures-service.ts +161 -159
- package/src/service/ledger-admin.ts +140 -0
- package/src/service/paper-service.ts +183 -153
- package/src/service/route.ts +5 -2
- package/src/service/rpc-support.ts +61 -0
- package/src/service/rpc.ts +59 -23
- package/src/store/accounts.ts +373 -0
- package/src/store/atomic-file.ts +37 -0
- package/src/store/futures-repo.ts +35 -260
- package/src/store/ledger-repo-base.ts +337 -0
- package/src/store/notes.ts +86 -0
- package/src/store/paths.ts +5 -0
- package/src/store/repo.ts +47 -229
- package/src/store/shortlist.ts +3 -5
- package/src/store/snapshots.ts +0 -3
- package/src/client/index.js +0 -3275
|
@@ -10,6 +10,7 @@ import type { RpcResult } from '../contract.js'
|
|
|
10
10
|
import type { FuturesDraft, FuturesExchange } from '../futures-contract.js'
|
|
11
11
|
import type { FuturesService } from './futures-service.js'
|
|
12
12
|
import { FuturesError } from './futures-service.js'
|
|
13
|
+
import { argumentGuards, failure, ok } from './rpc-support.js'
|
|
13
14
|
|
|
14
15
|
export type FuturesRpcHandler = (
|
|
15
16
|
endpoint: string,
|
|
@@ -19,25 +20,10 @@ export type FuturesRpcHandler = (
|
|
|
19
20
|
|
|
20
21
|
const EXCHANGES: readonly FuturesExchange[] = ['SHFE', 'INE', 'DCE', 'CZCE', 'GFEX']
|
|
21
22
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
function record(value: unknown): Record<string, unknown> {
|
|
27
|
-
if (value === undefined || value === null) return {}
|
|
28
|
-
if (typeof value !== 'object') throw new FuturesError('INVALID_ARGUMENT', '请求参数必须是对象')
|
|
29
|
-
return value as Record<string, unknown>
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function text(value: unknown, field: string): string {
|
|
33
|
-
if (typeof value !== 'string' || value.trim() === '') throw new FuturesError('INVALID_ARGUMENT', `缺少 ${field}`)
|
|
34
|
-
return value.trim()
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function num(value: unknown, field: string): number {
|
|
38
|
-
if (typeof value !== 'number' || !Number.isFinite(value)) throw new FuturesError('INVALID_ARGUMENT', `${field} 必须是数字`)
|
|
39
|
-
return value
|
|
40
|
-
}
|
|
23
|
+
const guard = argumentGuards(message => new FuturesError('INVALID_ARGUMENT', message))
|
|
24
|
+
const record = (value: unknown) => guard.record(value, { allowEmpty: true })
|
|
25
|
+
const text = guard.text
|
|
26
|
+
const num = guard.num
|
|
41
27
|
|
|
42
28
|
function draftOf(value: unknown): FuturesDraft {
|
|
43
29
|
const input = record(value)
|
|
@@ -134,13 +120,10 @@ export function createFuturesRpcHandler(service: FuturesService): FuturesRpcHand
|
|
|
134
120
|
case 'futures/tick':
|
|
135
121
|
return ok(await service.tick())
|
|
136
122
|
default:
|
|
137
|
-
throw new FuturesError('INVALID_ARGUMENT', `未知 endpoint: ${endpoint}
|
|
123
|
+
throw new FuturesError('INVALID_ARGUMENT', `未知 endpoint: ${endpoint}`)
|
|
138
124
|
}
|
|
139
125
|
} catch (error) {
|
|
140
|
-
|
|
141
|
-
return { ok: false, error: { code: error.code, message: error.message } }
|
|
142
|
-
}
|
|
143
|
-
return { ok: false, error: { code: 'INTERNAL', message: error instanceof Error ? error.message : String(error) } }
|
|
126
|
+
return failure(error, item => item instanceof FuturesError)
|
|
144
127
|
}
|
|
145
128
|
}
|
|
146
129
|
}
|
|
@@ -59,9 +59,14 @@ import {
|
|
|
59
59
|
toOrderView,
|
|
60
60
|
toReview,
|
|
61
61
|
} from '../core/futures/views.js'
|
|
62
|
+
import { LedgerAdmin } from './ledger-admin.js'
|
|
63
|
+
import { FuturesError, type FuturesServiceErrorCode } from './errors.js'
|
|
64
|
+
import { moveCash as runCashMove, openAccountOnce } from './account-moves.js'
|
|
62
65
|
import { QuoteRefreshGate } from './quote-gate.js'
|
|
66
|
+
|
|
67
|
+
export { FuturesError, type FuturesServiceErrorCode }
|
|
63
68
|
import { classifyDataProblem, friendlyDataNotice } from './data-source.js'
|
|
64
|
-
import type { DataProblem,
|
|
69
|
+
import type { DataProblem, LedgerSnapshotsView } from '../contract.js'
|
|
65
70
|
import type {
|
|
66
71
|
ContractTerms,
|
|
67
72
|
FuturesAccountState,
|
|
@@ -72,7 +77,6 @@ import type {
|
|
|
72
77
|
SettleInput,
|
|
73
78
|
} from '../core/futures/types.js'
|
|
74
79
|
import type { FuturesStore } from '../store/futures-repo.js'
|
|
75
|
-
import type { LedgerSnapshot } from '../store/port.js'
|
|
76
80
|
|
|
77
81
|
/** Data calls are chunked to the adapter's documented 20-symbol batch cap. */
|
|
78
82
|
const SYMBOL_BATCH = 20
|
|
@@ -104,34 +108,6 @@ export function normalizeFuturesSymbol(raw: string): string {
|
|
|
104
108
|
return suffix === undefined ? text : `${text.slice(0, dot)}.${suffix}`
|
|
105
109
|
}
|
|
106
110
|
|
|
107
|
-
export type FuturesServiceErrorCode =
|
|
108
|
-
| 'INSUFFICIENT_MARGIN'
|
|
109
|
-
| 'INSUFFICIENT_CASH'
|
|
110
|
-
| 'INSUFFICIENT_POSITION'
|
|
111
|
-
| 'CONTRACT_NOT_FOUND'
|
|
112
|
-
| 'CONTRACT_EXPIRED'
|
|
113
|
-
| 'NO_VOLUME'
|
|
114
|
-
| 'LIMIT_UNAVAILABLE'
|
|
115
|
-
| 'MARGIN_UNAVAILABLE'
|
|
116
|
-
| 'ACCOUNT_BLOCKED'
|
|
117
|
-
| 'INVALID_ARGUMENT'
|
|
118
|
-
| 'ORDER_NOT_FOUND'
|
|
119
|
-
| 'ORDER_NOT_PENDING'
|
|
120
|
-
| 'SESSION_CLOSED'
|
|
121
|
-
| 'INTERNAL'
|
|
122
|
-
| 'LEDGER_RESTORE_FAILED'
|
|
123
|
-
|
|
124
|
-
export class FuturesError extends Error {
|
|
125
|
-
constructor(
|
|
126
|
-
readonly code: FuturesServiceErrorCode,
|
|
127
|
-
message: string,
|
|
128
|
-
readonly status = 400,
|
|
129
|
-
) {
|
|
130
|
-
super(message)
|
|
131
|
-
this.name = 'FuturesError'
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
111
|
export interface FuturesServiceOptions {
|
|
136
112
|
repo: FuturesStore
|
|
137
113
|
data: FuturesMarketDataPort
|
|
@@ -140,6 +116,14 @@ export interface FuturesServiceOptions {
|
|
|
140
116
|
accountId?: string
|
|
141
117
|
now?: () => Date
|
|
142
118
|
logger?: { warn(message: string): void }
|
|
119
|
+
/**
|
|
120
|
+
* Human freeze from the account registry, read live so `accounts/lock`
|
|
121
|
+
* applies immediately. Resting orders keep matching (they are already in the
|
|
122
|
+
* book and can be cancelled); only new state changes are refused.
|
|
123
|
+
*/
|
|
124
|
+
isLocked?: () => boolean
|
|
125
|
+
/** Archived accounts are frozen as well; asked before `isLocked`. */
|
|
126
|
+
isArchived?: () => boolean
|
|
143
127
|
}
|
|
144
128
|
|
|
145
129
|
interface ContractCache {
|
|
@@ -239,6 +223,27 @@ export class FuturesService {
|
|
|
239
223
|
this.now = options.now ?? (() => new Date())
|
|
240
224
|
}
|
|
241
225
|
|
|
226
|
+
private admin: LedgerAdmin<FuturesAccountState, ReturnType<typeof toAccountView>> | undefined
|
|
227
|
+
|
|
228
|
+
/** Export/snapshot/recovery plumbing shared with the stock plane. */
|
|
229
|
+
private ledgerAdmin(): LedgerAdmin<FuturesAccountState, ReturnType<typeof toAccountView>> {
|
|
230
|
+
if (this.admin === undefined) {
|
|
231
|
+
this.admin = new LedgerAdmin<FuturesAccountState, ReturnType<typeof toAccountView>>({
|
|
232
|
+
repo: this.options.repo,
|
|
233
|
+
isBlocked: state => state.blocked,
|
|
234
|
+
blockedReason: state => state.blockedReason,
|
|
235
|
+
ledgerVersion: state => state.ledgerVersion,
|
|
236
|
+
viewOf: state => this.viewOf(state),
|
|
237
|
+
assertUnlocked: () => this.assertUnlocked(),
|
|
238
|
+
ts: () => this.ts(),
|
|
239
|
+
makeError: (code, message) => new FuturesError(code as FuturesServiceErrorCode, message),
|
|
240
|
+
label: 'paper-trading: futures',
|
|
241
|
+
...(this.options.logger === undefined ? {} : { logger: this.options.logger }),
|
|
242
|
+
})
|
|
243
|
+
}
|
|
244
|
+
return this.admin
|
|
245
|
+
}
|
|
246
|
+
|
|
242
247
|
private ts(): string {
|
|
243
248
|
return this.now().toISOString()
|
|
244
249
|
}
|
|
@@ -247,9 +252,23 @@ export class FuturesService {
|
|
|
247
252
|
return toAccountView(state, this.options.repo.ledgerPath)
|
|
248
253
|
}
|
|
249
254
|
|
|
255
|
+
/**
|
|
256
|
+
* Refuse a state change from a registry-locked account. Mirrors the stock
|
|
257
|
+
* service: the RPC guard is not enough because tools resolve services
|
|
258
|
+
* directly and the futures route bypasses the paper guard.
|
|
259
|
+
*/
|
|
260
|
+
private assertUnlocked(): void {
|
|
261
|
+
if (this.options.isArchived?.() === true) {
|
|
262
|
+
throw new FuturesError('ACCOUNT_ARCHIVED', `账户「${this.accountId}」已归档,恢复归档后才能交易`)
|
|
263
|
+
}
|
|
264
|
+
if (this.options.isLocked?.() === true) {
|
|
265
|
+
throw new FuturesError('ACCOUNT_LOCKED', `账户「${this.accountId}」已锁定,不能交易`)
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
250
269
|
private blocked(state: FuturesAccountState): FuturesError {
|
|
251
270
|
const reason = reasonText(state.blockedReason)
|
|
252
|
-
return new FuturesError('ACCOUNT_BLOCKED', `账户已锁定,可用 paper_ledger 从备份恢复,或重置后继续${reason === '' ? '' : `(${reason})`}
|
|
271
|
+
return new FuturesError('ACCOUNT_BLOCKED', `账户已锁定,可用 paper_ledger 从备份恢复,或重置后继续${reason === '' ? '' : `(${reason})`}`)
|
|
253
272
|
}
|
|
254
273
|
|
|
255
274
|
// ---------------------------------------------------------------- account --
|
|
@@ -259,14 +278,13 @@ export class FuturesService {
|
|
|
259
278
|
}
|
|
260
279
|
|
|
261
280
|
private async ensureAccount(): Promise<FuturesAccountState> {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
281
|
+
return openAccountOnce<FuturesAccountState, FuturesLedgerEvent>({
|
|
282
|
+
transact: build => this.options.repo.transact(build),
|
|
283
|
+
hasAccount: state => state.tradeDate !== '',
|
|
284
|
+
tradeDateForNow: () => this.tradeDateForNow(this.now()),
|
|
285
|
+
open: (state, tradeDate, ts) => openAccount(state, this.settings, tradeDate, ts, this.accountId),
|
|
286
|
+
now: () => this.now(),
|
|
268
287
|
})
|
|
269
|
-
return outcome.state
|
|
270
288
|
}
|
|
271
289
|
|
|
272
290
|
private async sync(): Promise<FuturesAccountState> {
|
|
@@ -286,66 +304,91 @@ export class FuturesService {
|
|
|
286
304
|
|
|
287
305
|
/**
|
|
288
306
|
* Idempotent clock advance: settle every due trade date at 15:30 and open the
|
|
289
|
-
* current one at 09:00.
|
|
290
|
-
*
|
|
307
|
+
* current one at 09:00.
|
|
308
|
+
*
|
|
309
|
+
* Two phases: the plan (calendar + close/open prices) is built against a clone
|
|
310
|
+
* of the state outside the store's write queue, then the transaction re-checks
|
|
311
|
+
* that nobody wrote meanwhile and appends the pre-built events. A slow data
|
|
312
|
+
* call therefore cannot block reads and writes, and a lost race merely defers
|
|
313
|
+
* the settlement to the next read — never duplicates it.
|
|
291
314
|
*/
|
|
292
315
|
private async advanceTo(): Promise<AdvanceOutcome> {
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
316
|
+
const snapshot = await this.options.repo.current()
|
|
317
|
+
if (snapshot.tradeDate === '' || snapshot.blocked) {
|
|
318
|
+
return { state: snapshot, notices: [], expired: [] }
|
|
319
|
+
}
|
|
320
|
+
const now = this.now()
|
|
321
|
+
const nowIso = now.toISOString()
|
|
322
|
+
const today = todayTradeDate(now)
|
|
323
|
+
const base = structuredClone(snapshot)
|
|
324
|
+
// Primitive fingerprint: the live state is mutated in place by any
|
|
325
|
+
// concurrent write, so comparing its fields after an await is meaningless.
|
|
326
|
+
const plannedFor = { seq: base.lastSeq, tradeDate: base.tradeDate }
|
|
327
|
+
const plan = await this.planAdvance(base, nowIso, today)
|
|
328
|
+
if (plan.events.length === 0) return { state: snapshot, notices: plan.notices, expired: plan.expired }
|
|
329
|
+
const outcome = await this.options.repo.transact(current => {
|
|
330
|
+
if (current.lastSeq !== plannedFor.seq || current.tradeDate !== plannedFor.tradeDate) {
|
|
331
|
+
return { events: [], value: { applied: false } }
|
|
299
332
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
333
|
+
return { events: plan.events, value: { applied: true } }
|
|
334
|
+
})
|
|
335
|
+
if (outcome.value.applied !== true) return { state: outcome.state, notices: [], expired: [] }
|
|
336
|
+
return { state: outcome.state, notices: plan.notices, expired: plan.expired }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Build the due settlement/open events; all network calls happen here, unlocked. */
|
|
340
|
+
private async planAdvance(
|
|
341
|
+
base: FuturesAccountState,
|
|
342
|
+
nowIso: string,
|
|
343
|
+
today: string,
|
|
344
|
+
): Promise<{ events: FuturesLedgerEvent[]; notices: string[]; expired: FuturesOrder[] }> {
|
|
345
|
+
const events: FuturesLedgerEvent[] = []
|
|
346
|
+
const notices: string[] = []
|
|
347
|
+
const expired: FuturesOrder[] = []
|
|
348
|
+
let current = base
|
|
349
|
+
const apply = (result: {
|
|
350
|
+
events: FuturesLedgerEvent[]
|
|
351
|
+
state: FuturesAccountState
|
|
352
|
+
notices?: string[]
|
|
353
|
+
expired?: FuturesOrder[]
|
|
354
|
+
}): void => {
|
|
355
|
+
events.push(...result.events)
|
|
356
|
+
current = result.state
|
|
357
|
+
if (result.notices !== undefined) notices.push(...result.notices)
|
|
358
|
+
if (result.expired !== undefined) expired.push(...result.expired)
|
|
359
|
+
}
|
|
360
|
+
for (let guard = 0; guard < 400; guard += 1) {
|
|
361
|
+
const settlementAt = isoAt(current.tradeDate, SETTLEMENT_MINUTES)
|
|
362
|
+
if (current.tradeDate < today || (current.tradeDate === today && nowIso >= settlementAt)) {
|
|
363
|
+
const closes = await this.fetchCloses(current)
|
|
364
|
+
const next = await this.options.calendar.nextTradingDay(current.tradeDate)
|
|
365
|
+
apply(closeDay(current, {
|
|
366
|
+
date: current.tradeDate,
|
|
367
|
+
nextTradeDate: next,
|
|
368
|
+
ts: settlementAt,
|
|
369
|
+
recordedAt: nowIso,
|
|
370
|
+
closes: closes.prices,
|
|
371
|
+
closeSource: closes.source,
|
|
372
|
+
warnings: closes.notice === undefined ? [] : [closes.notice],
|
|
373
|
+
}))
|
|
374
|
+
continue
|
|
314
375
|
}
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
date: current.tradeDate,
|
|
322
|
-
nextTradeDate: next,
|
|
323
|
-
ts: settlementAt,
|
|
376
|
+
if (current.tradeDate === today) {
|
|
377
|
+
if (nowIso >= isoAt(today, OPEN_MINUTES) && current.lastOpenedDate !== today) {
|
|
378
|
+
const opens = await this.fetchOpens(current)
|
|
379
|
+
apply(openDay(current, {
|
|
380
|
+
date: today,
|
|
381
|
+
ts: isoAt(today, OPEN_MINUTES),
|
|
324
382
|
recordedAt: nowIso,
|
|
325
|
-
|
|
326
|
-
closeSource: closes.source,
|
|
327
|
-
warnings: closes.notice === undefined ? [] : [closes.notice],
|
|
383
|
+
opens: opens.prices,
|
|
328
384
|
}))
|
|
329
|
-
|
|
330
|
-
}
|
|
331
|
-
if (current.tradeDate === today) {
|
|
332
|
-
if (nowIso >= isoAt(today, OPEN_MINUTES) && current.lastOpenedDate !== today) {
|
|
333
|
-
const opens = await this.fetchOpens(current)
|
|
334
|
-
apply(openDay(current, {
|
|
335
|
-
date: today,
|
|
336
|
-
ts: isoAt(today, OPEN_MINUTES),
|
|
337
|
-
recordedAt: nowIso,
|
|
338
|
-
opens: opens.prices,
|
|
339
|
-
}))
|
|
340
|
-
if (opens.notice !== undefined) notices.push(opens.notice)
|
|
341
|
-
}
|
|
342
|
-
break
|
|
385
|
+
if (opens.notice !== undefined) notices.push(opens.notice)
|
|
343
386
|
}
|
|
344
387
|
break
|
|
345
388
|
}
|
|
346
|
-
|
|
347
|
-
}
|
|
348
|
-
return {
|
|
389
|
+
break
|
|
390
|
+
}
|
|
391
|
+
return { events, notices, expired }
|
|
349
392
|
}
|
|
350
393
|
|
|
351
394
|
/** Symbols whose price the account cares about: open orders and held positions. */
|
|
@@ -681,45 +724,29 @@ export class FuturesService {
|
|
|
681
724
|
}
|
|
682
725
|
|
|
683
726
|
async exportLedger(): Promise<FuturesLedgerExport> {
|
|
684
|
-
|
|
685
|
-
if (ledger.content === null) return { path: ledger.path, exists: false, notice: '账本文件尚未创建' }
|
|
686
|
-
return { path: ledger.path, exists: true, content: ledger.content }
|
|
727
|
+
return this.ledgerAdmin().exportLedger()
|
|
687
728
|
}
|
|
688
729
|
|
|
689
730
|
/** Snapshots that can be restored, newest first, plus the live ledger's state. */
|
|
690
731
|
async ledgerSnapshots(): Promise<LedgerSnapshotsView> {
|
|
691
|
-
|
|
692
|
-
const snapshots = await this.options.repo.snapshots()
|
|
693
|
-
return {
|
|
694
|
-
path: this.options.repo.ledgerPath ?? '',
|
|
695
|
-
blocked: state?.blocked === true,
|
|
696
|
-
blockedReason: state?.blockedReason,
|
|
697
|
-
ledgerVersion: state?.ledgerVersion,
|
|
698
|
-
snapshots: snapshots.map(toSnapshotView),
|
|
699
|
-
}
|
|
732
|
+
return this.ledgerAdmin().ledgerSnapshots()
|
|
700
733
|
}
|
|
701
734
|
|
|
702
735
|
/** Replace the live futures ledger with one snapshot; allowed while blocked. */
|
|
703
736
|
async restoreLedger(name: string, confirm: boolean): Promise<ReturnType<typeof toAccountView>> {
|
|
704
|
-
|
|
705
|
-
try {
|
|
706
|
-
return this.viewOf(await this.options.repo.restore(name))
|
|
707
|
-
} catch (error) {
|
|
708
|
-
throw new FuturesError('LEDGER_RESTORE_FAILED', error instanceof Error ? error.message : String(error), 409)
|
|
709
|
-
}
|
|
737
|
+
return this.ledgerAdmin().restoreLedger(name, confirm)
|
|
710
738
|
}
|
|
711
739
|
|
|
712
740
|
/** Take one manual snapshot (the automatic one runs at most daily). */
|
|
713
741
|
async backupLedger(): Promise<boolean> {
|
|
714
|
-
|
|
715
|
-
return this.options.repo.backup(`manual-${stamp}`)
|
|
742
|
+
return this.ledgerAdmin().backupLedger()
|
|
716
743
|
}
|
|
717
744
|
|
|
718
745
|
// ---------------------------------------------------------------- writing --
|
|
719
746
|
|
|
720
747
|
private assertLotQty(qty: number): void {
|
|
721
748
|
if (!Number.isInteger(qty) || qty <= 0) {
|
|
722
|
-
throw new FuturesError('INVALID_ARGUMENT', '手数必须是正整数'
|
|
749
|
+
throw new FuturesError('INVALID_ARGUMENT', '手数必须是正整数')
|
|
723
750
|
}
|
|
724
751
|
}
|
|
725
752
|
|
|
@@ -744,6 +771,7 @@ export class FuturesService {
|
|
|
744
771
|
}
|
|
745
772
|
|
|
746
773
|
async place(input: FuturesDraft, requestId: string = randomUUID()): Promise<FuturesOrderView> {
|
|
774
|
+
this.assertUnlocked()
|
|
747
775
|
const state = await this.sync()
|
|
748
776
|
if (state.blocked) throw this.blocked(state)
|
|
749
777
|
// Reject a bad lot before it reaches the ledger: a rejected order with
|
|
@@ -755,7 +783,7 @@ export class FuturesService {
|
|
|
755
783
|
const nowIso = this.ts()
|
|
756
784
|
const phase = phaseAt(nowIso, state.tradeDate, data.sessions)
|
|
757
785
|
if (phase !== 'trading') {
|
|
758
|
-
throw new FuturesError('SESSION_CLOSED', '当前非期货日盘连续交易时段,不接受委托'
|
|
786
|
+
throw new FuturesError('SESSION_CLOSED', '当前非期货日盘连续交易时段,不接受委托')
|
|
759
787
|
}
|
|
760
788
|
const outcome = await this.options.repo.transact<PlaceOutcome>(current => {
|
|
761
789
|
const duplicate = Object.values(current.orders).find(order => order.requestId === requestId)
|
|
@@ -774,19 +802,19 @@ export class FuturesService {
|
|
|
774
802
|
})
|
|
775
803
|
if (outcome.value.duplicateId !== undefined) {
|
|
776
804
|
const duplicate = outcome.state.orders[outcome.value.duplicateId]
|
|
777
|
-
if (duplicate === undefined) throw new FuturesError('ORDER_NOT_FOUND', '订单不存在'
|
|
805
|
+
if (duplicate === undefined) throw new FuturesError('ORDER_NOT_FOUND', '订单不存在')
|
|
778
806
|
const limitPrice = typeof draft.limitPrice === 'number' ? draft.limitPrice : undefined
|
|
779
807
|
const price = typeof draft.price === 'number' ? draft.price : undefined
|
|
780
808
|
if (duplicate.symbol !== draft.symbol || duplicate.side !== draft.side
|
|
781
809
|
|| duplicate.offset !== draft.offset || duplicate.type !== draft.type || duplicate.qty !== draft.qty
|
|
782
810
|
|| duplicate.limitPrice !== limitPrice || duplicate.price !== price) {
|
|
783
|
-
throw new FuturesError('INVALID_ARGUMENT', 'requestId 已被另一笔不同的委托占用'
|
|
811
|
+
throw new FuturesError('INVALID_ARGUMENT', 'requestId 已被另一笔不同的委托占用')
|
|
784
812
|
}
|
|
785
813
|
return toOrderView(duplicate)
|
|
786
814
|
}
|
|
787
815
|
if (outcome.value.blocked === true || outcome.state.blocked) throw this.blocked(outcome.state)
|
|
788
816
|
const order = outcome.value.orderId === undefined ? undefined : outcome.state.orders[outcome.value.orderId]
|
|
789
|
-
if (order === undefined) throw new FuturesError('INTERNAL', '订单未写入账本'
|
|
817
|
+
if (order === undefined) throw new FuturesError('INTERNAL', '订单未写入账本')
|
|
790
818
|
return toOrderView(order)
|
|
791
819
|
}
|
|
792
820
|
|
|
@@ -801,10 +829,10 @@ export class FuturesService {
|
|
|
801
829
|
return { events: result.events, value: {} }
|
|
802
830
|
})
|
|
803
831
|
if (outcome.value.blocked === true) throw this.blocked(outcome.state)
|
|
804
|
-
if (outcome.value.missing === true) throw new FuturesError('ORDER_NOT_FOUND', '订单不存在'
|
|
805
|
-
if (outcome.value.notPending === true) throw new FuturesError('ORDER_NOT_PENDING', '订单不是挂单状态'
|
|
832
|
+
if (outcome.value.missing === true) throw new FuturesError('ORDER_NOT_FOUND', '订单不存在')
|
|
833
|
+
if (outcome.value.notPending === true) throw new FuturesError('ORDER_NOT_PENDING', '订单不是挂单状态')
|
|
806
834
|
const order = outcome.state.orders[orderId]
|
|
807
|
-
if (order === undefined) throw new FuturesError('ORDER_NOT_FOUND', '订单不存在'
|
|
835
|
+
if (order === undefined) throw new FuturesError('ORDER_NOT_FOUND', '订单不存在')
|
|
808
836
|
return toOrderView(order)
|
|
809
837
|
}
|
|
810
838
|
|
|
@@ -868,7 +896,8 @@ export class FuturesService {
|
|
|
868
896
|
|
|
869
897
|
/** Wipe the account by replacing the ledger with one genesis event. */
|
|
870
898
|
async reset(confirm: boolean): Promise<ReturnType<typeof toAccountView>> {
|
|
871
|
-
|
|
899
|
+
this.assertUnlocked()
|
|
900
|
+
if (confirm !== true) throw new FuturesError('INVALID_ARGUMENT', '重置需要 confirm=true')
|
|
872
901
|
const ts = this.ts()
|
|
873
902
|
await this.options.repo.backup(ts)
|
|
874
903
|
const previous = await this.options.repo.current().catch(error => {
|
|
@@ -899,60 +928,33 @@ export class FuturesService {
|
|
|
899
928
|
|
|
900
929
|
/** Add free cash; the amount is yuan from the UI, stored as integer cents. */
|
|
901
930
|
async deposit(amount: number): Promise<ReturnType<typeof toAccountView>> {
|
|
931
|
+
this.assertUnlocked()
|
|
902
932
|
return this.moveCash('deposit', amount)
|
|
903
933
|
}
|
|
904
934
|
|
|
905
935
|
/** Take free cash out; margin already reserved by positions cannot leave. */
|
|
906
936
|
async withdraw(amount: number): Promise<ReturnType<typeof toAccountView>> {
|
|
937
|
+
this.assertUnlocked()
|
|
907
938
|
return this.moveCash('withdraw', amount)
|
|
908
939
|
}
|
|
909
940
|
|
|
910
941
|
private async moveCash(kind: 'deposit' | 'withdraw', amount: number): Promise<ReturnType<typeof toAccountView>> {
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
? depositCash(current, amountCents, this.ts())
|
|
923
|
-
: withdrawCash(current, amountCents, this.ts())
|
|
924
|
-
return { events: result.events, value: { blocked: false, insufficient: false } }
|
|
925
|
-
})
|
|
926
|
-
if (outcome.value.blocked === true) throw this.blocked(outcome.state)
|
|
927
|
-
if (outcome.value.insufficient === true) throw new FuturesError('INSUFFICIENT_CASH', '可提现金不足', 409)
|
|
928
|
-
return this.viewOf(outcome.state)
|
|
942
|
+
return runCashMove<FuturesAccountState, ReturnType<typeof toAccountView>, FuturesLedgerEvent>({
|
|
943
|
+
sync: () => this.sync(),
|
|
944
|
+
transact: build => this.options.repo.transact(build),
|
|
945
|
+
isBlocked: state => state.blocked,
|
|
946
|
+
blocked: state => this.blocked(state),
|
|
947
|
+
cashCents: state => state.cashCents,
|
|
948
|
+
deposit: depositCash,
|
|
949
|
+
withdraw: withdrawCash,
|
|
950
|
+
viewOf: state => this.viewOf(state),
|
|
951
|
+
ts: () => this.ts(),
|
|
952
|
+
}, kind, this.cashAmountCents(amount))
|
|
929
953
|
}
|
|
930
954
|
|
|
931
955
|
/** `amount` is yuan from the UI; the ledger stores integer cents. */
|
|
932
956
|
private cashAmountCents(amount: number): number {
|
|
933
|
-
|
|
934
|
-
throw new FuturesError('INVALID_ARGUMENT', '金额必须是正数', 400)
|
|
935
|
-
}
|
|
936
|
-
const cents = Math.round(amount * 100)
|
|
937
|
-
if (!Number.isSafeInteger(cents) || cents <= 0) {
|
|
938
|
-
throw new FuturesError('INVALID_ARGUMENT', '金额至少 0.01 元', 400)
|
|
939
|
-
}
|
|
940
|
-
return cents
|
|
957
|
+
return this.ledgerAdmin().cashAmountCents(amount)
|
|
941
958
|
}
|
|
942
959
|
}
|
|
943
960
|
|
|
944
|
-
/** Ledger cents → the yuan the rest of the views use. */
|
|
945
|
-
function toSnapshotView(snapshot: LedgerSnapshot): LedgerSnapshotView {
|
|
946
|
-
return {
|
|
947
|
-
name: snapshot.name,
|
|
948
|
-
createdAt: snapshot.createdAt,
|
|
949
|
-
bytes: snapshot.bytes,
|
|
950
|
-
ledgerVersion: snapshot.ledgerVersion,
|
|
951
|
-
lastSeq: snapshot.lastSeq,
|
|
952
|
-
tradeDate: snapshot.tradeDate,
|
|
953
|
-
cash: snapshot.cashCents / 100,
|
|
954
|
-
valid: snapshot.valid,
|
|
955
|
-
migratable: snapshot.migratable,
|
|
956
|
-
problem: snapshot.problem,
|
|
957
|
-
}
|
|
958
|
-
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ledger-level operations shared by both account services.
|
|
3
|
+
*
|
|
4
|
+
* Export, snapshot listing, backup and restore are plane-independent: they only
|
|
5
|
+
* touch the repository and marshal the result into a view. The stock and futures
|
|
6
|
+
* services used to carry identical copies; the differences are the account's
|
|
7
|
+
* blocked flag, the error class and the view shape, which each service passes in.
|
|
8
|
+
* @module @dsh-ft/dsh-fft-paper-trading/service/ledger-admin
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { LedgerExport, LedgerSnapshotView, LedgerSnapshotsView } from '../contract.js'
|
|
12
|
+
import type { LedgerFile, LedgerSnapshot } from '../store/port.js'
|
|
13
|
+
|
|
14
|
+
/** The repository surface the admin needs; both planes satisfy it. */
|
|
15
|
+
export interface LedgerRepositoryPort<S> {
|
|
16
|
+
readonly ledgerPath?: string
|
|
17
|
+
readLedger(): Promise<LedgerFile>
|
|
18
|
+
current(): Promise<S>
|
|
19
|
+
snapshots(): Promise<LedgerSnapshot[]>
|
|
20
|
+
restore(name: string): Promise<S>
|
|
21
|
+
backup(label: string): Promise<boolean>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface LedgerStatusView {
|
|
25
|
+
path: string
|
|
26
|
+
exists: boolean
|
|
27
|
+
blocked: boolean
|
|
28
|
+
blockedReason?: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface LedgerAdminDeps<S, V> {
|
|
32
|
+
repo: LedgerRepositoryPort<S>
|
|
33
|
+
/** Read the plane's frozen/blocked flag. */
|
|
34
|
+
isBlocked: (state: S) => boolean
|
|
35
|
+
blockedReason: (state: S) => string | undefined
|
|
36
|
+
ledgerVersion: (state: S) => number | undefined
|
|
37
|
+
viewOf: (state: S) => V
|
|
38
|
+
/** Refuse recovery on a human-frozen account (recovery is a state change). */
|
|
39
|
+
assertUnlocked: () => void
|
|
40
|
+
ts: () => string
|
|
41
|
+
/** Domain error factory: `PaperError` or `FuturesError`. */
|
|
42
|
+
makeError: (code: string, message: string) => Error
|
|
43
|
+
/** Log prefix for the one warning this helper emits. */
|
|
44
|
+
label: string
|
|
45
|
+
logger?: { warn(message: string): void }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Ledger cents → the yuan the rest of the views use. */
|
|
49
|
+
function toSnapshotView(snapshot: LedgerSnapshot): LedgerSnapshotView {
|
|
50
|
+
return {
|
|
51
|
+
name: snapshot.name,
|
|
52
|
+
createdAt: snapshot.createdAt,
|
|
53
|
+
bytes: snapshot.bytes,
|
|
54
|
+
ledgerVersion: snapshot.ledgerVersion,
|
|
55
|
+
lastSeq: snapshot.lastSeq,
|
|
56
|
+
tradeDate: snapshot.tradeDate,
|
|
57
|
+
cash: snapshot.cashCents / 100,
|
|
58
|
+
valid: snapshot.valid,
|
|
59
|
+
migratable: snapshot.migratable,
|
|
60
|
+
...(snapshot.problem === undefined ? {} : { problem: snapshot.problem }),
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class LedgerAdmin<S, V> {
|
|
65
|
+
constructor(private readonly deps: LedgerAdminDeps<S, V>) {}
|
|
66
|
+
|
|
67
|
+
/** Read-only export of the raw ledger, for a frozen account's banner. */
|
|
68
|
+
async exportLedger(): Promise<LedgerExport> {
|
|
69
|
+
const ledger = await this.deps.repo.readLedger()
|
|
70
|
+
if (ledger.content === null) return { path: ledger.path, exists: false, notice: '账本文件尚未创建' }
|
|
71
|
+
return { path: ledger.path, exists: true, content: ledger.content }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Where the ledger is and why it is frozen — without the raw text. */
|
|
75
|
+
async ledgerStatus(): Promise<LedgerStatusView> {
|
|
76
|
+
const ledger = await this.deps.repo.readLedger()
|
|
77
|
+
const state = await this.deps.repo.current().catch(error => {
|
|
78
|
+
this.deps.logger?.warn(`${this.deps.label}: ledger status could not replay: ${String(error)}`)
|
|
79
|
+
return undefined
|
|
80
|
+
})
|
|
81
|
+
return {
|
|
82
|
+
path: ledger.path,
|
|
83
|
+
exists: ledger.content !== null,
|
|
84
|
+
blocked: state === undefined ? false : this.deps.isBlocked(state),
|
|
85
|
+
...(state === undefined || this.deps.blockedReason(state) === undefined
|
|
86
|
+
? {}
|
|
87
|
+
: { blockedReason: this.deps.blockedReason(state) }),
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Snapshots that can be restored, newest first, plus the live ledger's state. */
|
|
92
|
+
async ledgerSnapshots(): Promise<LedgerSnapshotsView> {
|
|
93
|
+
const state = await this.deps.repo.current().catch(() => undefined)
|
|
94
|
+
const snapshots = await this.deps.repo.snapshots()
|
|
95
|
+
return {
|
|
96
|
+
path: this.deps.repo.ledgerPath ?? '',
|
|
97
|
+
blocked: state !== undefined && this.deps.isBlocked(state),
|
|
98
|
+
...(state === undefined ? {} : { ledgerVersion: this.deps.ledgerVersion(state) }),
|
|
99
|
+
...(state === undefined || this.deps.blockedReason(state) === undefined
|
|
100
|
+
? {}
|
|
101
|
+
: { blockedReason: this.deps.blockedReason(state) }),
|
|
102
|
+
snapshots: snapshots.map(toSnapshotView),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Replace the live ledger with one snapshot.
|
|
108
|
+
*
|
|
109
|
+
* Deliberately reachable while the ledger is blocked and without `sync()`:
|
|
110
|
+
* recovery must not depend on the current ledger replaying, and the store
|
|
111
|
+
* validates the target before touching the file.
|
|
112
|
+
*/
|
|
113
|
+
async restoreLedger(name: string, confirm: boolean): Promise<V> {
|
|
114
|
+
this.deps.assertUnlocked()
|
|
115
|
+
if (confirm !== true) throw this.deps.makeError('INVALID_ARGUMENT', '恢复账本需要 confirm=true')
|
|
116
|
+
try {
|
|
117
|
+
return this.deps.viewOf(await this.deps.repo.restore(name))
|
|
118
|
+
} catch (error) {
|
|
119
|
+
throw this.deps.makeError('LEDGER_RESTORE_FAILED', error instanceof Error ? error.message : String(error))
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Take one manual snapshot (the automatic one runs at most daily). */
|
|
124
|
+
async backupLedger(): Promise<boolean> {
|
|
125
|
+
const stamp = this.deps.ts().replace(/[:.]/g, '-')
|
|
126
|
+
return this.deps.repo.backup(`manual-${stamp}`)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Yuan from the UI → integer cents, rejecting non-positive or unsafe amounts. */
|
|
130
|
+
cashAmountCents(amount: number): number {
|
|
131
|
+
if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {
|
|
132
|
+
throw this.deps.makeError('INVALID_ARGUMENT', '金额必须是正数')
|
|
133
|
+
}
|
|
134
|
+
const cents = Math.round(amount * 100)
|
|
135
|
+
if (!Number.isSafeInteger(cents) || cents <= 0) {
|
|
136
|
+
throw this.deps.makeError('INVALID_ARGUMENT', '金额至少 0.01 元')
|
|
137
|
+
}
|
|
138
|
+
return cents
|
|
139
|
+
}
|
|
140
|
+
}
|