-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathstatus.ts
More file actions
390 lines (336 loc) · 13.6 KB
/
Copy pathstatus.ts
File metadata and controls
390 lines (336 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/**
* Payment status display command
*
* Shows current payment configuration and balances for Filecoin Onchain Cloud.
* This provides a quick overview of the user's payment setup without making changes.
*/
import { SIZE_CONSTANTS } from '@filoz/synapse-core/utils'
import type { Synapse } from '@filoz/synapse-sdk'
import { TIME_CONSTANTS } from '@filoz/synapse-sdk'
import pc from 'picocolors'
import { parseUnits } from 'viem'
import { type ActualStorageResult, calculateActualStorage, listDataSets } from '../core/data-set/index.js'
import {
calculateDepositCapacity,
checkFILBalance,
checkUSDFCBalance,
getUsdfcAcquisitionHelpMessage,
toStorageRunwaySummary,
} from '../core/payments/index.js'
import { getClientAddress, initializeSynapse } from '../core/synapse/index.js'
import { formatFIL, formatUSDFC } from '../core/utils/format.js'
import { formatRunwaySummary } from '../core/utils/index.js'
import { type CLIAuthOptions, getCLILogger, parseCLIAuth } from '../utils/cli-auth.js'
import { cancel, createSpinner, formatFileSize, intro, outro } from '../utils/cli-helpers.js'
import { log } from '../utils/cli-logger.js'
import { displayDepositWarning } from './setup.js'
interface StatusOptions extends CLIAuthOptions {
includeRails?: boolean
}
const STORAGE_DISPLAY_PRECISION_DIGITS = 6
const STORAGE_DISPLAY_PRECISION = 10n ** BigInt(STORAGE_DISPLAY_PRECISION_DIGITS)
const { TiB } = SIZE_CONSTANTS
/**
* Convert a payment rate (USDFC per epoch) to storage bytes using the provider's pricing.
*
* This calculates: "How much storage does this payment rate cover?"
*
* Formula: storageBytes = (rate / pricePerTiBPerEpoch) * TiB
*
* NOTE: This calculation assumes a linear relationship between payment rate and
* storage size, which breaks down when floor pricing is applied to small files.
* The result represents "storage equivalent" at the given rate, not actual bytes stored.
* Use calculateActualStorage() from core/data-set for accurate byte counts.
*
* @param ratePerEpoch - Payment rate in USDFC per epoch
* @param pricePerTiBPerEpoch - Provider's price for 1 TiB per epoch in USDFC
* @returns Storage bytes that the rate covers, or null if invalid inputs
*/
function convertRateToStorageBytes(ratePerEpoch: bigint, pricePerTiBPerEpoch: bigint): bigint | null {
if (ratePerEpoch <= 0n || pricePerTiBPerEpoch <= 0n) {
return null
}
// storageTiBScaled preserves fractional precision using STORAGE_DISPLAY_PRECISION scaling
const storageTiBScaled = (ratePerEpoch * STORAGE_DISPLAY_PRECISION) / pricePerTiBPerEpoch
if (storageTiBScaled <= 0n) {
return null
}
// Convert scaled TiB to bytes: TiB * 1024^4 bytes, then unscale
return (storageTiBScaled * TiB) / STORAGE_DISPLAY_PRECISION
}
/**
* Display current payment status
*
* @param options - Options from command line
*/
export async function showPaymentStatus(options: StatusOptions): Promise<void> {
intro(pc.bold('Filecoin Onchain Cloud Payment Status'))
const spinner = createSpinner()
spinner.start('Fetching current configuration...')
try {
// Parse and validate authentication
const authConfig = await parseCLIAuth(options)
const logger = getCLILogger()
const synapse = await initializeSynapse(authConfig, logger)
const network = synapse.chain.name
const address = getClientAddress(synapse)
// Check balances and status
const filStatus = await checkFILBalance(synapse)
// Early exit if account has no funds
if (filStatus.balance === 0n) {
spinner.stop('━━━ Current Status ━━━')
log.line(`Address: ${address}`)
log.line(`Network: ${network}`)
log.line('')
log.line(`${pc.red('✗')} Account has no FIL balance`)
log.line('')
log.line(
`Get test FIL from: ${filStatus.isCalibnet ? 'https://faucet.calibnet.chainsafe-fil.io/' : 'Purchase FIL from an exchange'}`
)
log.flush()
cancel('Account not funded')
throw new Error('Account has no FIL balance')
}
const walletUsdfcBalance = await checkUSDFCBalance(synapse)
// Check if we have USDFC tokens before continuing
if (walletUsdfcBalance === 0n) {
spinner.stop('━━━ Current Status ━━━')
log.line(`Address: ${address}`)
log.line(`Network: ${network}`)
log.line('')
log.line(`${pc.red('✗')} No USDFC tokens found`)
log.line('')
const helpMessage = getUsdfcAcquisitionHelpMessage(filStatus.isCalibnet)
log.line(` ${pc.cyan(helpMessage)}`)
log.flush()
cancel('USDFC required to use Filecoin Onchain Cloud')
throw new Error('No USDFC tokens found')
}
const [accountSummary, storageInfo] = await Promise.all([
synapse.payments.accountSummary({}),
synapse.storage.getStorageInfo(),
])
const runway = toStorageRunwaySummary(accountSummary)
const pricePerTiBPerEpoch = storageInfo.pricing.noCDN.perTiBPerEpoch
const datasetFeePerMonth = storageInfo.pricing.priceList.rates.datasetFeePerMonth
let paymentRailsData: PaymentRailsData | null = null
if (options.includeRails === true) {
paymentRailsData = await fetchPaymentRailsData(synapse)
}
spinner.stop(`${pc.green('✓')} Configuration loaded`)
// Display all status information
log.line('━━━ Current Status ━━━')
// Show wallet balances
log.line(pc.bold('Wallet'))
log.indent(`Owner address: ${address}`)
log.indent(`Network: ${network}`)
log.indent(`FIL: ${formatFIL(filStatus.balance, filStatus.isCalibnet)}`)
log.indent(`USDFC: ${formatUSDFC(walletUsdfcBalance)} USDFC`)
log.line('')
// Show deposit and capacity
const totalDeposited = accountSummary.funds
const lockupUsed = runway.lockupUsed
const rateUsed = runway.rateUsed
const availableDeposit = totalDeposited > lockupUsed ? totalDeposited - lockupUsed : 0n
const capacity = calculateDepositCapacity(totalDeposited, pricePerTiBPerEpoch)
const runwayDisplay = formatRunwaySummary(runway)
const dailyCost = runway.perDay
const monthlyCost = dailyCost * TIME_CONSTANTS.DAYS_PER_MONTH
log.line(pc.bold('Filecoin Pay'))
log.indent(`Balance: ${formatUSDFC(totalDeposited)} USDFC`)
log.indent(`Locked: ${formatUSDFC(lockupUsed)} USDFC (30-day reserve)`)
log.indent(`Available: ${formatUSDFC(availableDeposit)} USDFC`)
if (rateUsed > 0n) {
log.indent(`Epoch cost: ${formatUSDFC(rateUsed)} USDFC`)
log.indent(`Daily cost: ${formatUSDFC(dailyCost)} USDFC`)
log.indent(`Monthly cost: ${formatUSDFC(monthlyCost)} USDFC`)
} else {
log.indent(`Epoch cost: ${pc.gray('0 USDFC')}`)
log.indent(`Daily cost: ${pc.gray('0 USDFC')}`)
log.indent(`Monthly cost: ${pc.gray('0 USDFC')}`)
}
if (paymentRailsData != null) {
displayPaymentRailsSummary(paymentRailsData, 1)
}
log.line('')
// Show storage usage details
log.line(pc.bold('WarmStorage Usage'))
let actualStorageResult: ActualStorageResult | null = null
try {
spinner.start('Fetching data sets...')
// Get all active data sets for this address
const dataSets = await listDataSets(synapse, {
address,
filter: (ds) => ds.isLive, // Only count active/live data sets
logger,
})
spinner.stop(`${pc.green('✓')} Data sets fetched`)
spinner.start('Calculating actual storage from data sets...')
actualStorageResult = await calculateActualStorage(synapse, dataSets, {
logger,
onProgress: (progress) => {
if (progress.type === 'actual-storage:progress') {
spinner.message(
`Calculating actual storage from data sets (${progress.data.dataSetsProcessed}/${progress.data.dataSetCount})`
)
}
},
})
if (actualStorageResult.timedOut) {
spinner.stop(`${pc.yellow('⚠')} Calculation timed out`)
} else if (actualStorageResult.warnings.length > 0) {
spinner.stop(
`${pc.yellow('⚠')} Actual storage calculated with ${actualStorageResult.warnings.length} warning(s)`
)
} else {
spinner.stop(`${pc.green('✓')} Actual storage calculated`)
}
if (actualStorageResult.warnings.length > 0) {
for (const warning of actualStorageResult.warnings) {
log.indent(pc.yellow(`⚠ ${warning.message}`))
}
}
if (actualStorageResult.totalBytes > 0n) {
const formattedSize = formatFileSize(actualStorageResult.totalBytes)
log.indent(`Stored: ${formattedSize}`)
} else {
log.indent(pc.gray('Stored: 0 B'))
}
} catch (error) {
spinner.stop(`${pc.yellow('⚠')} Could not calculate actual storage`)
log.indent(pc.gray(` Error: ${error instanceof Error ? error.message : String(error)}`))
}
if (runway.state === 'active') {
log.indent(`Storage covered: ~${runwayDisplay.coverage} total`)
log.indent(`Top-up needed in: ~${runwayDisplay.runway}`)
} else {
log.indent(pc.gray(runwayDisplay.coverage))
}
const capacityTibPerMonth = parseUnits(capacity.tibPerMonth.toString(), 18)
const capacityBytes = (capacityTibPerMonth * TiB) / 10n ** 18n
const capacityLine = `Funding could cover ~${formatFileSize(capacityBytes)} for one month`
log.indent(capacityLine)
log.flush()
const billedBytes = convertRateToStorageBytes(rateUsed, pricePerTiBPerEpoch)
if (billedBytes != null) {
const epochsInFloorPeriod = TIME_CONSTANTS.DAYS_PER_MONTH * TIME_CONSTANTS.EPOCHS_PER_DAY
const floorRatePerEpoch = datasetFeePerMonth / epochsInFloorPeriod
const floorEquivalentBytes = convertRateToStorageBytes(floorRatePerEpoch, pricePerTiBPerEpoch)
const floorEquivalentFormatted = floorEquivalentBytes ? formatFileSize(floorEquivalentBytes) : '~24.6 GiB'
const sectionContent = [
pc.gray('Filecoin Onchain Cloud uses floor pricing for DataSets.'),
pc.gray(`Each DataSet is billed a minimum of ${formatUSDFC(datasetFeePerMonth, 2)} USDFC per 30 days.`),
pc.gray(`This is equivalent to ~${floorEquivalentFormatted} per month.`),
`Billed capacity: ~${formatFileSize(billedBytes)}`,
]
if (actualStorageResult != null && billedBytes > actualStorageResult.totalBytes) {
const additionalStorage = billedBytes - actualStorageResult.totalBytes
sectionContent.push(`Storage remaining: ~${formatFileSize(additionalStorage)}`)
}
log.indent(pc.bold('Storage usage details:'))
for (const content of sectionContent) {
log.indent(content, 2)
}
}
// Show deposit warning if needed
displayDepositWarning(totalDeposited, lockupUsed)
log.flush()
// Show success outro
outro('Status check complete')
} catch (error) {
spinner.stop(`${pc.red('✗')} Status check failed`)
log.line('')
log.line(`${pc.red('Error:')} ${error instanceof Error ? error.message : String(error)}`)
log.flush()
cancel('Status check failed')
throw error
}
}
interface PaymentRailsData {
activeRails: number
terminatedRails: number
totalActiveRate: bigint
totalPendingSettlements: bigint
railsNeedingSettlement: number
error?: string
}
/**
* Fetch payment rails data without displaying anything
*/
async function fetchPaymentRailsData(synapse: Synapse): Promise<PaymentRailsData> {
try {
// Get rails as payer
const payerRails = await synapse.payments.getRailsAsPayer()
if (payerRails.length === 0) {
return {
activeRails: 0,
terminatedRails: 0,
totalActiveRate: 0n,
totalPendingSettlements: 0n,
railsNeedingSettlement: 0,
}
}
// Analyze rails for summary
let totalPendingSettlements = 0n
let totalActiveRate = 0n
let activeRails = 0
let terminatedRails = 0
let railsNeedingSettlement = 0
for (const rail of payerRails) {
try {
const railDetails = await synapse.payments.getRail({ railId: rail.railId })
const settlementPreview = await synapse.payments.getSettlementAmounts({ railId: rail.railId })
if (rail.isTerminated) {
terminatedRails++
} else {
activeRails++
totalActiveRate += railDetails.paymentRate
}
// Check for pending settlements
if (settlementPreview.totalSettledAmount > 0n) {
totalPendingSettlements += settlementPreview.totalSettledAmount
railsNeedingSettlement++
}
} catch (error) {
log.warn(`Could not analyze rail ${rail.railId}: ${error instanceof Error ? error.message : String(error)}`)
}
}
return {
activeRails,
terminatedRails,
totalActiveRate,
totalPendingSettlements,
railsNeedingSettlement,
}
} catch {
return {
activeRails: 0,
terminatedRails: 0,
totalActiveRate: 0n,
totalPendingSettlements: 0n,
railsNeedingSettlement: 0,
error: 'Unable to fetch rail information',
}
}
}
/**
* Display payment rails summary
*/
function displayPaymentRailsSummary(data: PaymentRailsData, indentLevel: number = 1): void {
log.indent(pc.bold('Payment Rails'), indentLevel)
if (data.error) {
log.indent(pc.gray(data.error), indentLevel + 1)
return
}
if (data.activeRails === 0 && data.terminatedRails === 0) {
log.indent(pc.gray('No active payment rails'), indentLevel + 1)
return
}
log.indent(`${data.activeRails} active, ${data.terminatedRails} terminated`, indentLevel + 1)
if (data.totalPendingSettlements > 0n) {
log.indent(`Pending settlement: ${formatUSDFC(data.totalPendingSettlements)} USDFC`, indentLevel + 1)
}
if (data.railsNeedingSettlement > 0) {
log.indent(`${data.railsNeedingSettlement} rail(s) need settlement`, indentLevel + 1)
}
}