-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathfunding.ts
More file actions
438 lines (395 loc) · 14.1 KB
/
funding.ts
File metadata and controls
438 lines (395 loc) · 14.1 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
import { calibration, type Synapse } from '@filoz/synapse-sdk'
import { MIN_FIL_FOR_GAS } from './constants.js'
import {
calculateStorageRunway,
checkAndSetAllowances,
computeAdjustmentForExactDays,
computeAdjustmentForExactDaysWithPiece,
computeAdjustmentForExactDeposit,
depositUSDFC,
getPaymentStatus,
USDFC_SYBIL_FEE,
validatePaymentRequirements,
withdrawUSDFC,
} from './index.js'
import type {
FilecoinPayFundingExecution,
FilecoinPayFundingInsights,
FilecoinPayFundingPlan,
FilecoinPayFundingPlanOptions,
FundingMode,
FundingReasonCode,
PaymentStatus,
ServiceApprovalStatus,
} from './types.js'
function calculateDepletionTiming(
available: bigint,
perDay: bigint
): { seconds: bigint; timestampMs?: number | null } | null {
if (available <= 0n || perDay <= 0n) {
return null
}
const seconds = (available * 86_400n) / perDay
if (seconds <= 0n) {
return null
}
const maxSecondsForNumber = BigInt(Number.MAX_SAFE_INTEGER) / 1000n
const timestampMs = seconds <= maxSecondsForNumber ? Date.now() + Number(seconds) * 1000 : null
return {
seconds,
timestampMs,
}
}
/**
* Get funding insights for a payment status
*
* This function calculates runway projections, depletion times, and spend rates
* based on current or projected balances and usage.
*
* @param status - Current payment status
* @param overrides - Optional overrides for projected scenarios
* @returns Funding insights including runway and depletion predictions
*/
export function getFilecoinPayFundingInsights(
status: PaymentStatus,
overrides?: { depositedBalance?: bigint; rateUsed?: bigint; lockupUsed?: bigint }
): FilecoinPayFundingInsights {
const depositedBalance = overrides?.depositedBalance ?? status.filecoinPayBalance
const rateUsed = overrides?.rateUsed ?? status.currentAllowances.rateUsed ?? 0n
const lockupUsed = overrides?.lockupUsed ?? status.currentAllowances.lockupUsed ?? 0n
const runway = calculateStorageRunway({
filecoinPayBalance: depositedBalance,
currentAllowances: {
...status.currentAllowances,
rateUsed,
lockupUsed,
},
})
const availableDeposited = runway.available
const filecoinPayDepletion = calculateDepletionTiming(availableDeposited, runway.perDay)
const ownerDepletion = calculateDepletionTiming(availableDeposited + status.walletUsdfcBalance, runway.perDay)
return {
spendRatePerEpoch: rateUsed,
spendRatePerDay: runway.perDay,
depositedBalance,
availableDeposited,
walletUsdfcBalance: status.walletUsdfcBalance,
runway,
filecoinPayDepletionSeconds: filecoinPayDepletion?.seconds ?? null,
filecoinPayDepletionTimestampMs: filecoinPayDepletion?.timestampMs ?? null,
ownerDepletionSeconds: ownerDepletion?.seconds ?? null,
ownerDepletionTimestampMs: ownerDepletion?.timestampMs ?? null,
}
}
/**
* Format a funding reason code into a human-readable message
*
* @param reasonCode - The funding reason code
* @param plan - Optional plan for additional context (e.g., days)
* @returns Human-readable message explaining the funding reason
*/
export function formatFundingReason(reasonCode: FundingReasonCode, plan?: FilecoinPayFundingPlan): string {
switch (reasonCode) {
case 'none':
return 'No funding adjustment needed'
case 'piece-upload':
return 'Required funding for file upload (lockup requirement)'
case 'runway-insufficient':
return plan?.targetRunwayDays != null
? `Required funding for ${plan.targetRunwayDays} days of storage`
: 'Required funding to meet runway target'
case 'runway-with-piece':
return plan?.targetRunwayDays != null
? `Required funding for ${plan.targetRunwayDays} days of storage (including upcoming upload)`
: 'Required funding for storage runway (including upcoming upload)'
case 'target-deposit':
return 'Required funding to reach target deposit amount'
case 'withdrawal-excess':
return 'Excess funds available for withdrawal'
default:
return 'Unknown funding reason'
}
}
/**
* Calculate a Filecoin Pay funding plan without making network calls
*
* This is a pure calculation function that determines what funding adjustments
* are needed to reach a target. Use this when you already have PaymentStatus
* and pricing information, or when you need synchronous calculation logic.
*
* For full workflow including network calls, allowance checks, and execution,
* use planFilecoinPayFunding instead.
*
* @param options - Calculation options with payment status
* @returns Funding plan with delta, action, and insights
*/
export function calculateFilecoinPayFundingPlan(options: FilecoinPayFundingPlanOptions): FilecoinPayFundingPlan {
const {
status,
targetRunwayDays,
targetDeposit,
pieceSizeBytes,
pricePerTiBPerEpoch,
newDataSetCount = 0,
mode = 'exact',
allowWithdraw = true,
} = options
if (targetRunwayDays != null && targetDeposit != null) {
throw new Error('Specify either targetRunwayDays or targetDeposit, not both')
}
if (targetRunwayDays == null && targetDeposit == null) {
throw new Error('A funding target is required')
}
if (pieceSizeBytes != null && pricePerTiBPerEpoch == null) {
throw new Error('pricePerTiBPerEpoch is required when pieceSizeBytes is provided')
}
if (!Number.isInteger(newDataSetCount) || newDataSetCount < 0) {
throw new Error('newDataSetCount must be a non-negative integer')
}
let delta: bigint
let projectedDeposit = status.filecoinPayBalance
let projectedRateUsed = status.currentAllowances.rateUsed ?? 0n
let projectedLockupUsed: bigint
let resolvedTargetDeposit: bigint | undefined
let reasonCode: FundingReasonCode = 'none'
let targetType: 'runway-days' | 'deposit'
if (targetRunwayDays != null) {
targetType = 'runway-days'
if (pieceSizeBytes != null) {
if (pricePerTiBPerEpoch == null) {
throw new Error('pricePerTiBPerEpoch is required when planning with pieceSizeBytes')
}
const adjustment = computeAdjustmentForExactDaysWithPiece(
status,
targetRunwayDays,
pieceSizeBytes,
pricePerTiBPerEpoch
)
const dataSetCreationFees = BigInt(newDataSetCount) * USDFC_SYBIL_FEE
delta = adjustment.delta + dataSetCreationFees
resolvedTargetDeposit = adjustment.targetDeposit + dataSetCreationFees
projectedRateUsed = adjustment.newRateUsed
projectedLockupUsed = adjustment.newLockupUsed
// Determine reason: piece upload with or without runway
if (targetRunwayDays === 0) {
/**
* Special case: targetRunwayDays === 0 means "fund this upload only" (no runway target).
* Even with 0 days, onboarding a new piece can still require additional deposit to satisfy
* the piece's lockup requirement (and the small safety buffer). If delta <= 0, no adjustment needed.
*/
reasonCode = delta > 0n ? 'piece-upload' : 'none'
} else if (delta > 0n) {
reasonCode = 'runway-with-piece'
} else if (delta < 0n) {
reasonCode = 'withdrawal-excess'
}
} else {
const adjustment = computeAdjustmentForExactDays(status, targetRunwayDays)
delta = adjustment.delta
projectedRateUsed = adjustment.rateUsed
projectedLockupUsed = adjustment.lockupUsed
resolvedTargetDeposit = status.filecoinPayBalance + delta
// Runway adjustment without piece
if (delta > 0n) {
reasonCode = 'runway-insufficient'
} else if (delta < 0n) {
reasonCode = 'withdrawal-excess'
}
}
} else {
targetType = 'deposit'
const adjustment = computeAdjustmentForExactDeposit(status, targetDeposit ?? 0n)
delta = adjustment.delta
resolvedTargetDeposit = adjustment.clampedTarget
projectedLockupUsed = adjustment.lockupUsed
// Target deposit adjustment
if (delta > 0n) {
reasonCode = 'target-deposit'
} else if (delta < 0n) {
reasonCode = 'withdrawal-excess'
}
}
if (mode === 'minimum' && delta < 0n) {
delta = 0n
reasonCode = 'none' // Reset reason if we're not actually adjusting
}
if (!allowWithdraw && delta < 0n) {
delta = 0n
reasonCode = 'none' // Reset reason if we're not actually adjusting
}
const projectedDepositUnsafe = status.filecoinPayBalance + delta
projectedDeposit = projectedDepositUnsafe > 0n ? projectedDepositUnsafe : 0n
const walletShortfall =
delta > 0n && delta > status.walletUsdfcBalance ? delta - status.walletUsdfcBalance : undefined
const currentInsights = getFilecoinPayFundingInsights(status)
const projectedInsights = getFilecoinPayFundingInsights(status, {
depositedBalance: projectedDeposit,
rateUsed: projectedRateUsed,
lockupUsed: projectedLockupUsed,
})
const plan: FilecoinPayFundingPlan = {
targetType,
delta,
action: delta > 0n ? 'deposit' : delta < 0n ? 'withdraw' : 'none',
reasonCode,
mode,
projectedDeposit,
projectedRateUsed,
projectedLockupUsed,
current: currentInsights,
projected: projectedInsights,
...(targetRunwayDays != null ? { targetRunwayDays } : {}),
...(resolvedTargetDeposit != null ? { targetDeposit: resolvedTargetDeposit } : {}),
...(pieceSizeBytes != null ? { pieceSizeBytes } : {}),
...(pricePerTiBPerEpoch != null ? { pricePerTiBPerEpoch } : {}),
...(newDataSetCount > 0 ? { newDataSetCount } : {}),
...(walletShortfall != null ? { walletShortfall } : {}),
}
return plan
}
/**
* Options for planning Filecoin Pay funding with network calls
*
* Used by `planFilecoinPayFunding` - the async planning function.
* Requires a `Synapse` instance and will fetch current status and pricing.
*
* Specify either `targetRunwayDays` OR `targetDeposit`, not both.
*/
export interface PlanFilecoinPayFundingOptions {
synapse: Synapse
targetRunwayDays?: number | undefined
targetDeposit?: bigint | undefined
pieceSizeBytes?: number | undefined
pricePerTiBPerEpoch?: bigint | undefined
newDataSetCount?: number | undefined
mode?: FundingMode | undefined
allowWithdraw?: boolean | undefined
ensureAllowances?: boolean | undefined
}
/**
* Plan Filecoin Pay funding adjustments with network calls
*
* This async function handles the full workflow:
* - Fetches current payment status from chain
* - Optionally ensures allowances are configured
* - Validates payment requirements (FIL for gas, USDFC availability)
* - Fetches pricing if needed
* - Calculates funding plan using calculateFilecoinPayFundingPlan
*
* @param options - Planning options including synapse instance
* @returns Plan with status and allowance information
*/
export async function planFilecoinPayFunding(options: PlanFilecoinPayFundingOptions): Promise<{
plan: FilecoinPayFundingPlan
status: PaymentStatus
allowances: {
updated: boolean
transactionHash?: string
currentAllowances: ServiceApprovalStatus
}
}> {
const {
synapse,
targetRunwayDays,
targetDeposit,
pieceSizeBytes,
pricePerTiBPerEpoch,
newDataSetCount = 0,
mode = 'exact',
allowWithdraw = true,
ensureAllowances = false,
} = options
if (targetRunwayDays != null && targetDeposit != null) {
throw new Error('Specify either targetRunwayDays or targetDeposit, not both')
}
if (targetRunwayDays == null && targetDeposit == null) {
throw new Error('A funding target is required')
}
let allowanceStatus: {
updated: boolean
transactionHash?: string
currentAllowances: ServiceApprovalStatus
} | null = null
if (ensureAllowances) {
allowanceStatus = await checkAndSetAllowances(synapse)
}
const status = await getPaymentStatus(synapse)
const allowances = allowanceStatus ?? {
updated: false,
currentAllowances: status.currentAllowances,
}
const isCalibnet = status.chainId === calibration.id
const hasSufficientGas = status.filBalance >= MIN_FIL_FOR_GAS
const validation = validatePaymentRequirements(hasSufficientGas, status.walletUsdfcBalance, isCalibnet)
if (!validation.isValid) {
const help = validation.helpMessage ? ` ${validation.helpMessage}` : ''
throw new Error(`${validation.errorMessage}${help}`)
}
let pricing = pricePerTiBPerEpoch
if (pieceSizeBytes != null && pricing == null) {
const storageInfo = await synapse.storage.getStorageInfo()
pricing = storageInfo.pricing.noCDN.perTiBPerEpoch
}
// Delegate to pure calculation function
const plan = calculateFilecoinPayFundingPlan({
status,
targetRunwayDays,
targetDeposit,
pieceSizeBytes,
pricePerTiBPerEpoch: pricing,
newDataSetCount,
mode,
allowWithdraw,
})
return {
plan,
status,
allowances,
}
}
/**
* Execute a Filecoin Pay funding plan by depositing or withdrawing USDFC.
*
* - No-op when `plan.delta` is 0 (returns projected insights unchanged).
* - Deposits when delta > 0, withdraws when delta < 0.
* - Returns updated balances/runway after execution.
*
* @param synapse - Initialized Synapse instance
* @param plan - Funding plan produced by calculate/plan helpers
* @returns Execution result with transaction hash (if any) and updated insights
*/
export async function executeFilecoinPayFunding(
synapse: Synapse,
plan: FilecoinPayFundingPlan
): Promise<FilecoinPayFundingExecution> {
if (plan.delta === 0n) {
return {
adjusted: false,
delta: 0n,
newDepositedAmount: plan.projected.depositedBalance,
newRunwayDays: plan.projected.runway.days,
newRunwayHours: plan.projected.runway.hours,
plan,
updatedInsights: plan.projected,
}
}
let transactionHash: string | undefined
if (plan.delta > 0n) {
const { depositTx } = await depositUSDFC(synapse, plan.delta)
transactionHash = depositTx
} else {
transactionHash = await withdrawUSDFC(synapse, -plan.delta)
}
const updatedStatus = await getPaymentStatus(synapse)
const updatedInsights = getFilecoinPayFundingInsights(updatedStatus)
return {
adjusted: true,
delta: plan.delta,
transactionHash,
newDepositedAmount: updatedStatus.filecoinPayBalance,
newRunwayDays: updatedInsights.runway.days,
newRunwayHours: updatedInsights.runway.hours,
plan,
updatedInsights,
}
}