-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathfund.ts
More file actions
374 lines (338 loc) · 13.7 KB
/
Copy pathfund.ts
File metadata and controls
374 lines (338 loc) · 13.7 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
/**
* payments fund command
*
* Adjusts funds to exactly match a target runway (days) or a target deposited amount.
*/
import { confirm, isCancel } from '@clack/prompts'
import type { Synapse } from '@filoz/synapse-sdk'
import pc from 'picocolors'
import { parseUnits } from 'viem'
import { CliFatal, CliIncomplete, isCliFatal, isCliIncomplete, setIncompleteExitCode } from '../common/cli-errors.js'
import { MIN_RUNWAY_DAYS } from '../common/constants.js'
import { resolveIpfsIndexedMetadata } from '../core/metadata/index.js'
import {
checkUSDFCBalance,
clampDepositToLimit,
DEFAULT_LOCKUP_DAYS,
depositUSDFC,
executeFilecoinPayFunding,
planFilecoinPayFunding,
toStorageRunwaySummary,
withdrawUSDFC,
} from '../core/payments/index.js'
import { initializeSynapse } from '../core/synapse/index.js'
import { formatUSDFC } from '../core/utils/format.js'
import { formatRunwaySummary } from '../core/utils/index.js'
import { getCLILogger, parseCLIAuth } from '../utils/cli-auth.js'
import type { Spinner } from '../utils/cli-helpers.js'
import { cancel, createSpinner, intro, isInteractive, outro } from '../utils/cli-helpers.js'
import { isTTY, log } from '../utils/cli-logger.js'
import type { AutoFundOptions, FundingAdjustmentResult, FundOptions } from './types.js'
// Helper: confirm/warn or bail when target implies < lockup-days runway
async function ensureBelowThirtyDaysAllowed(opts: {
spinner: Spinner
warningLine1: string
warningLine2: string
}): Promise<void> {
const { spinner, warningLine1, warningLine2 } = opts
if (!isInteractive()) {
spinner.stop()
log.line(pc.red(warningLine1))
log.line(pc.red(warningLine2))
log.flush()
cancel('Fund adjustment aborted')
throw new CliFatal(`Unsafe target below ${DEFAULT_LOCKUP_DAYS}-day baseline`)
}
log.line(pc.yellow('⚠ Warning'))
log.indent(pc.yellow(warningLine1))
log.indent(pc.yellow(warningLine2))
log.flush()
const proceed = await confirm({
message: 'Proceed with reducing runway below 30 days?',
initialValue: false,
})
if (isCancel(proceed) || !proceed) {
throw new CliIncomplete('Fund adjustment cancelled by user')
}
}
// Helper: perform deposit or withdraw according to delta
async function performAdjustment(params: {
synapse: Synapse
spinner: Spinner
delta: bigint
depositMsg: string
withdrawMsg: string
}): Promise<void> {
const { synapse, spinner, delta, depositMsg, withdrawMsg } = params
if (delta > 0n) {
const needed = delta
const usdfcWallet = await checkUSDFCBalance(synapse)
if (needed > usdfcWallet) {
throw new Error(
`Insufficient USDFC in wallet (need ${formatUSDFC(needed)} USDFC, have ${formatUSDFC(usdfcWallet)} USDFC)`
)
}
if (isTTY()) {
// we will deposit `needed` USDFC, display confirmation to user unless not TTY or --auto flag was passed
const proceed = await confirm({
message: `Deposit ${formatUSDFC(needed)} USDFC?`,
initialValue: false,
})
if (isCancel(proceed) || !proceed) {
throw new CliIncomplete('Deposit cancelled by user')
}
}
spinner.start(depositMsg)
const { depositTx } = await depositUSDFC(synapse, needed)
spinner.stop(`${pc.green('✓')} Deposit complete`)
log.line(pc.bold('Transaction details:'))
log.indent(pc.gray(`Deposit: ${depositTx}`))
log.flush()
} else if (delta < 0n) {
const withdrawAmount = -delta
if (isTTY()) {
// we will withdraw `withdrawAmount` USDFC, display confirmation to user unless not TTY or --auto flag was passed
const proceed = await confirm({
message: `Withdraw ${formatUSDFC(withdrawAmount)} USDFC?`,
initialValue: false,
})
if (isCancel(proceed) || !proceed) {
throw new CliIncomplete('Withdraw cancelled by user')
}
}
spinner.start(withdrawMsg)
const txHash = await withdrawUSDFC(synapse, withdrawAmount)
spinner.stop(`${pc.green('✓')} Withdraw complete`)
log.line(pc.bold('Transaction'))
log.indent(pc.gray(txHash))
log.flush()
}
}
// Helper: summary after adjustment
async function printSummary(synapse: Synapse, title = 'Updated'): Promise<void> {
const summary = await synapse.payments.accountSummary({})
const runway = toStorageRunwaySummary(summary)
const runwayDisplay = formatRunwaySummary(runway)
const lines = [`Deposited: ${formatUSDFC(summary.funds)} USDFC`]
if (runway.state === 'active') {
lines.push(`Storage covered: ~${runwayDisplay.coverage} total`)
lines.push(`Top-up needed in: ~${runwayDisplay.runway}`)
} else {
lines.push(runwayDisplay.coverage)
}
log.section(title, lines)
}
/**
* Automatically adjust funding to meet target runway or deposit amount.
* This is a non-interactive version suitable for programmatic use.
*
* @param options - Auto-funding options
* @returns Funding adjustment result
* @throws Error if adjustment fails or target is unsafe
*/
export async function autoFund(options: AutoFundOptions): Promise<FundingAdjustmentResult> {
const { synapse, fileSize, copies, providerIds, dataSetIds, metadata, spinner, maxBalance, withCDN } = options
const targetRunwayDays = options.minRunwayDays ?? MIN_RUNWAY_DAYS
spinner?.message('Checking wallet readiness...')
const resolvedMetadata = resolveIpfsIndexedMetadata(metadata, dataSetIds)
const contexts = await synapse.storage.createContexts({
...(copies != null ? { copies } : {}),
...(providerIds != null ? { providerIds } : {}),
...(dataSetIds != null ? { dataSetIds } : {}),
metadata: resolvedMetadata,
})
const newDataSetCount = contexts.filter((context) => context.dataSetId == null).length
const planResult = await planFilecoinPayFunding({
synapse,
targetRunwayDays,
pieceSizeBytes: fileSize,
newDataSetCount,
withCDN: withCDN === true,
ensureAllowances: true,
allowWithdraw: false,
})
const { plan, status, allowances } = planResult
spinner?.message(
allowances.updated ? 'WarmStorage permissions configured' : 'WarmStorage permissions already configured'
)
spinner?.message('Calculating funding requirements...')
// Auto-fund only deposits, never withdraws
if (plan.delta <= 0n) {
spinner?.message('No additional funding required')
return {
adjusted: false,
delta: 0n,
newDepositedAmount: plan.projected.depositedBalance,
newRunwayDays: plan.projected.runway.runwayDays,
newRunwayHours: plan.projected.runway.runwayHours,
}
}
// Apply --max-balance ceiling (skip or clamp the planned deposit)
const warnings: string[] = []
const clamp = clampDepositToLimit(status.filecoinPayBalance, plan.delta, maxBalance)
if (clamp.reason === 'already-at-limit') {
if (clamp.message) warnings.push(clamp.message)
return {
adjusted: false,
delta: 0n,
newDepositedAmount: status.filecoinPayBalance,
newRunwayDays: plan.current.runway.runwayDays,
newRunwayHours: plan.current.runway.runwayHours,
warnings,
}
}
if (clamp.reason === 'clamped' && clamp.message != null) {
warnings.push(clamp.message)
}
const adjustedPlan = clamp.deposit !== plan.delta ? { ...plan, delta: clamp.deposit } : plan
if (status.walletUsdfcBalance < adjustedPlan.delta) {
throw new Error(
`Insufficient USDFC in wallet (need ${formatUSDFC(adjustedPlan.delta)} USDFC, have ${formatUSDFC(status.walletUsdfcBalance)} USDFC)`
)
}
const depositMsg =
clamp.reason === 'clamped'
? `Depositing ${formatUSDFC(adjustedPlan.delta)} USDFC toward ${targetRunwayDays} day(s) runway (limited by --max-balance)...`
: `Depositing ${formatUSDFC(adjustedPlan.delta)} USDFC to ensure at least ${targetRunwayDays} day(s) runway...`
spinner?.message(depositMsg)
const execution = await executeFilecoinPayFunding(synapse, adjustedPlan)
spinner?.message(`${pc.green('✓')} Deposit complete`)
return {
adjusted: execution.adjusted,
delta: adjustedPlan.delta,
transactionHash: execution.transactionHash,
newDepositedAmount: execution.newDepositedAmount,
newRunwayDays: execution.newRunwayDays,
newRunwayHours: execution.newRunwayHours,
warnings,
}
}
export async function runFund(options: FundOptions): Promise<void> {
intro(pc.bold('Filecoin Onchain Cloud Fund Adjustment'))
const spinner = createSpinner()
// Validate inputs
const hasDays = options.days != null
const hasAmount = options.amount != null
if ((hasDays && hasAmount) || (!hasDays && !hasAmount)) {
log.line(pc.red('Error: Specify exactly one of --days <N> or --amount <USDFC>'))
log.flush()
throw new CliFatal('Specify exactly one of --days <N> or --amount <USDFC>')
}
if (options.mode != null && !['exact', 'minimum'].includes(options.mode)) {
log.line(pc.red(`Error: Invalid mode (must be "exact" or "minimum"), received: '${options.mode}'`))
log.flush()
throw new CliFatal(`Invalid mode (must be "exact" or "minimum"), received: '${options.mode}'`)
}
spinner.start('Connecting...')
try {
// Parse and validate authentication
const authConfig = await parseCLIAuth(options)
const logger = getCLILogger()
const synapse = await initializeSynapse(authConfig, logger)
spinner.stop(`${pc.green('✓')} Connected`)
const targetDays: number = hasDays ? Number(options.days) : 0
if (hasDays && (!Number.isFinite(targetDays) || targetDays < 0)) {
throw new Error('--days must be a non-negative number')
}
let targetDeposit: bigint = 0n
try {
targetDeposit = options.amount != null ? parseUnits(String(options.amount), 18) : 0n
} catch {
throw new Error(`Invalid --amount '${options.amount}'`)
}
spinner.start('Calculating funding plan...')
const planResult = await planFilecoinPayFunding({
synapse,
targetRunwayDays: hasDays ? targetDays : undefined,
targetDeposit: hasAmount ? targetDeposit : undefined,
mode: options.mode ?? 'exact',
allowWithdraw: options.mode !== 'minimum',
})
const { plan } = planResult
spinner.stop(`${pc.green('✓')} Funding plan prepared`)
if (plan.targetType === 'runway-days' && plan.current.runway.rateUsed === 0n) {
log.line(`${pc.red('✗')} No active spend detected (rateUsed = 0). Cannot compute runway.`)
log.line('Use --amount to set a target deposit instead.')
log.flush()
cancel('Fund adjustment aborted')
throw new CliFatal('No active spend')
}
// Safety baseline measures projected top-up window (net runway after deposit),
// sourced from the SDK so --days and --amount paths share one metric.
const projectedRunwayDays = plan.projected.runway.state === 'active' ? plan.projected.runway.runwayDays : null
if (plan.mode !== 'minimum' && projectedRunwayDays != null && projectedRunwayDays < DEFAULT_LOCKUP_DAYS) {
const line1 = `Projected top-up window after this adjustment is less than ${DEFAULT_LOCKUP_DAYS} days.`
const line2 = `WarmStorage reserves ${DEFAULT_LOCKUP_DAYS} days of costs; a shorter top-up window risks termination.`
await ensureBelowThirtyDaysAllowed({
spinner,
warningLine1: line1,
warningLine2: line2,
})
}
const targetDepositLabel = formatUSDFC(plan.targetDeposit ?? targetDeposit)
let alreadyMessage: string
if (plan.targetType === 'runway-days') {
const runwayLabel = plan.targetRunwayDays ?? 0
alreadyMessage =
plan.mode === 'minimum'
? `Already above minimum of ${runwayLabel} day(s) runway. No changes needed.`
: `Already at target of ~${runwayLabel} day(s). No changes needed.`
} else {
alreadyMessage =
plan.mode === 'minimum'
? `Already above minimum deposit of ${targetDepositLabel} USDFC. No changes needed.`
: `Already at target deposit of ${targetDepositLabel} USDFC. No changes needed.`
}
let depositMsg: string
let withdrawMsg: string
if (plan.targetType === 'runway-days') {
const runwayLabel = plan.targetRunwayDays ?? 0
depositMsg = `Depositing ${formatUSDFC(plan.delta)} USDFC to reach ~${runwayLabel} day(s) runway...`
withdrawMsg = `Withdrawing ${formatUSDFC(-plan.delta)} USDFC to reach ~${runwayLabel} day(s) runway...`
} else {
depositMsg = `Depositing ${formatUSDFC(plan.delta)} USDFC to reach ${targetDepositLabel} USDFC total...`
withdrawMsg = `Withdrawing ${formatUSDFC(-plan.delta)} USDFC to reach ${targetDepositLabel} USDFC total...`
}
if (plan.mode === 'minimum' && plan.delta > 0n) {
if (hasAmount) {
depositMsg = `Depositing ${formatUSDFC(plan.delta)} USDFC to reach minimum of ${targetDepositLabel} USDFC total...`
} else if (targetDays > 0) {
depositMsg = `Depositing ${formatUSDFC(plan.delta)} USDFC to reach minimum of ${targetDays} day(s) runway...`
}
}
if (plan.delta === 0n) {
await printSummary(synapse, 'No Changes Needed')
outro(alreadyMessage)
return
}
if (plan.walletShortfall != null && plan.walletShortfall > 0n) {
throw new Error(
`Insufficient USDFC in wallet (need ${formatUSDFC(plan.delta)} USDFC, have ${formatUSDFC(planResult.status.walletUsdfcBalance)} USDFC)`
)
}
await performAdjustment({
synapse,
spinner,
delta: plan.delta,
depositMsg,
withdrawMsg,
})
await printSummary(synapse)
outro('Fund adjustment completed')
} catch (error) {
if (isCliIncomplete(error)) {
spinner.stop()
cancel(error.message)
setIncompleteExitCode()
return
}
if (isCliFatal(error)) {
spinner.stop()
throw error
}
const msg = error instanceof Error ? error.message : String(error)
spinner.stop(`${pc.red('✗')} Fund adjustment failed: ${msg}`)
cancel('Fund adjustment failed')
throw new CliFatal(msg, { cause: error instanceof Error ? error : undefined })
}
}