@omnipair/dusk-sdk 2.27.0 → 3.0.1
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 +92 -104
- package/dist/constants.d.ts +0 -6
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +0 -12
- package/dist/constants.js.map +1 -1
- package/dist/get.d.ts +97 -345
- package/dist/get.d.ts.map +1 -1
- package/dist/get.js +1 -2
- package/dist/get.js.map +1 -1
- package/dist/hlp-liquidation-client.d.ts.map +1 -1
- package/dist/hlp-liquidation-client.js +0 -1
- package/dist/hlp-liquidation-client.js.map +1 -1
- package/dist/idl_delegate.json +82 -390
- package/dist/idl_v2.json +226 -1098
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/indexer.d.ts +1 -1
- package/dist/indexer.d.ts.map +1 -1
- package/dist/interest-accounting.d.ts +82 -47
- package/dist/interest-accounting.d.ts.map +1 -1
- package/dist/interest-accounting.js +103 -53
- package/dist/interest-accounting.js.map +1 -1
- package/dist/leverage-preview.d.ts +24 -86
- package/dist/leverage-preview.d.ts.map +1 -1
- package/dist/liquidation-client.js +2 -2
- package/dist/liquidation-client.js.map +1 -1
- package/dist/operator-client.d.ts.map +1 -1
- package/dist/operator-client.js +8 -9
- package/dist/operator-client.js.map +1 -1
- package/dist/referral.d.ts +6 -3
- package/dist/referral.d.ts.map +1 -1
- package/dist/referral.js +8 -7
- package/dist/referral.js.map +1 -1
- package/dist/tranche-client.d.ts +0 -56
- package/dist/tranche-client.d.ts.map +1 -1
- package/dist/tranche-client.js +2 -103
- package/dist/tranche-client.js.map +1 -1
- package/dist/transfer-fees.d.ts +6 -0
- package/dist/transfer-fees.d.ts.map +1 -1
- package/dist/transfer-fees.js +19 -0
- package/dist/transfer-fees.js.map +1 -1
- package/dist/type-aliases.d.ts +3 -15
- package/dist/type-aliases.d.ts.map +1 -1
- package/dist/types_delegate.d.ts +82 -390
- package/dist/types_delegate.d.ts.map +1 -1
- package/dist/types_v2.d.ts +227 -1099
- package/dist/types_v2.d.ts.map +1 -1
- package/dist/virtual-book/market.d.ts +24 -86
- package/dist/virtual-book/market.d.ts.map +1 -1
- package/dist/virtual-book/quotes.d.ts +61 -173
- package/dist/virtual-book/quotes.d.ts.map +1 -1
- package/dist/virtual-book/quotes.js +55 -6
- package/dist/virtual-book/quotes.js.map +1 -1
- package/dist/write.d.ts +1 -3
- package/dist/write.d.ts.map +1 -1
- package/dist/write.js +7 -24
- package/dist/write.js.map +1 -1
- package/dist/yield-client.d.ts +7 -20
- package/dist/yield-client.d.ts.map +1 -1
- package/dist/yield-client.js +6 -37
- package/dist/yield-client.js.map +1 -1
- package/package.json +2 -2
- package/src/constants.ts +0 -25
- package/src/get.ts +0 -3
- package/src/hlp-liquidation-client.ts +0 -1
- package/src/idl_delegate.json +82 -390
- package/src/idl_v2.json +226 -1098
- package/src/index.ts +0 -1
- package/src/indexer.ts +1 -1
- package/src/interest-accounting.ts +149 -71
- package/src/liquidation-client.ts +2 -2
- package/src/operator-client.ts +8 -9
- package/src/referral.ts +9 -14
- package/src/tranche-client.ts +3 -106
- package/src/transfer-fees.ts +18 -0
- package/src/type-aliases.ts +3 -15
- package/src/types_delegate.ts +82 -390
- package/src/types_v2.ts +226 -1098
- package/src/virtual-book/quotes.ts +70 -6
- package/src/write.ts +8 -36
- package/src/yield-client.ts +9 -48
- package/dist/income-receivable.d.ts +0 -77
- package/dist/income-receivable.d.ts.map +0 -1
- package/dist/income-receivable.js +0 -135
- package/dist/income-receivable.js.map +0 -1
- package/src/income-receivable.ts +0 -145
package/src/index.ts
CHANGED
package/src/indexer.ts
CHANGED
|
@@ -19,7 +19,7 @@ export interface ApiResponse<T = unknown> {
|
|
|
19
19
|
export interface RequestOptions {
|
|
20
20
|
params?: Record<string, string | number | boolean | undefined | null>;
|
|
21
21
|
signal?: AbortSignal;
|
|
22
|
-
headers?:
|
|
22
|
+
headers?: NonNullable<Parameters<FetchLike>[1]>["headers"];
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
export interface PaginationOptions {
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { BorrowPosition, Market } from "./type-aliases.js";
|
|
1
|
+
import type { BorrowPosition, HlpCohort, HlpVault, JuniorCohort, Market, YieldAccount } from "./type-aliases.js";
|
|
3
2
|
|
|
4
3
|
const U64_MAX = (1n << 64n) - 1n;
|
|
5
4
|
const U128_MAX = (1n << 128n) - 1n;
|
|
@@ -32,9 +31,10 @@ function amount(value: bigint, max = U64_MAX): void {
|
|
|
32
31
|
}
|
|
33
32
|
|
|
34
33
|
/** Funding interest the opposite-side hLP vault owes in `asset`: its indexed
|
|
35
|
-
* funding debt less principal, floored at zero.
|
|
36
|
-
*
|
|
37
|
-
* is accrued to the
|
|
34
|
+
* funding debt less principal, floored at zero. It is credited to ordinary
|
|
35
|
+
* srLP and junior holders as it accrues and recorded as the ledger's
|
|
36
|
+
* `fundingRecognized`. Read from a market whose interest is accrued to the
|
|
37
|
+
* funding slot. */
|
|
38
38
|
export function hlpFundingInterest(
|
|
39
39
|
market: Pick<Market, "debt" | "baseHlpVault" | "quoteHlpVault">,
|
|
40
40
|
asset: "base" | "quote",
|
|
@@ -52,73 +52,151 @@ export function hlpFundingInterest(
|
|
|
52
52
|
return debt > principal ? debt - principal : 0n;
|
|
53
53
|
}
|
|
54
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
|
-
|
|
55
|
+
/** One asset's accrued-interest ledger as bigints, read from `fees.ledger`.
|
|
56
|
+
* Interest is credited to holders when it accrues, so `credited` can exceed
|
|
57
|
+
* reserve cash; claims are paid from cash as it allows. `deficit` is the
|
|
58
|
+
* part of a loss LP capital could not absorb; while either asset has one,
|
|
59
|
+
* the market refuses new liquidity (`InterestDeficit`). */
|
|
60
|
+
export interface MarketInterestLedger {
|
|
61
|
+
/** Fixed and isolated borrower interest outstanding, as last recognized. */
|
|
62
|
+
publicRecognized: bigint;
|
|
63
|
+
/** hLP funding interest outstanding in this asset, as last recognized. */
|
|
64
|
+
fundingRecognized: bigint;
|
|
65
|
+
/** Credited, unclaimed interest of every holder lane, the junior seed and the operator. */
|
|
66
|
+
credited: bigint;
|
|
67
|
+
/** Protocol share of outstanding interest, paid only when borrowers pay. */
|
|
68
|
+
protocolUnpaid: bigint;
|
|
69
|
+
/** The current operator recipient's credited, unclaimed share (part of `credited`). */
|
|
70
|
+
operatorClaimable: bigint;
|
|
71
|
+
/** Protocol interest paid but not yet booked into its revenue liabilities. */
|
|
72
|
+
protocolPending: bigint;
|
|
73
|
+
/** Pool loss beyond LP capital. Never decreases. */
|
|
74
|
+
deficit: bigint;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function marketInterestLedger(market: Pick<Market, "baseSide" | "quoteSide">, asset: "base" | "quote"): MarketInterestLedger {
|
|
78
|
+
const ledger = (asset === "base" ? market.baseSide : market.quoteSide).fees.ledger;
|
|
79
|
+
const read = (value: { toString(): string }) => BigInt(value.toString());
|
|
80
|
+
return {
|
|
81
|
+
publicRecognized: read(ledger.publicRecognized),
|
|
82
|
+
fundingRecognized: read(ledger.fundingRecognized),
|
|
83
|
+
credited: read(ledger.credited),
|
|
84
|
+
protocolUnpaid: read(ledger.protocolUnpaid),
|
|
85
|
+
operatorClaimable: read(ledger.operatorClaimable),
|
|
86
|
+
protocolPending: read(ledger.protocolPending),
|
|
87
|
+
deficit: read(ledger.deficit),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Protocol share of an interest payment of `interestPaid` atoms, as the
|
|
92
|
+
* program takes it: `floor(paid · protocolUnpaid / interest)` where
|
|
93
|
+
* `interest = publicRecognized + fundingRecognized`, both read from the same
|
|
94
|
+
* accrued market state. The protocol is paid only from interest borrowers
|
|
95
|
+
* actually pay; the rest of the payment stays in reserve cash for holders. */
|
|
96
|
+
export function quoteProtocolInterestShare(input: {
|
|
97
|
+
interestPaid: bigint;
|
|
98
|
+
ledger: Pick<MarketInterestLedger, "publicRecognized" | "fundingRecognized" | "protocolUnpaid">;
|
|
99
|
+
}): bigint {
|
|
100
|
+
const { interestPaid: paid, ledger } = input;
|
|
101
|
+
amount(paid);
|
|
102
|
+
const interest = ledger.publicRecognized + ledger.fundingRecognized;
|
|
103
|
+
if (ledger.protocolUnpaid < 0n || ledger.protocolUnpaid > interest) throw new RangeError("Inconsistent interest ledger");
|
|
104
|
+
if (paid > interest) throw new RangeError("Payment exceeds outstanding interest");
|
|
105
|
+
return interest === 0n ? 0n : paid * ledger.protocolUnpaid / interest;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Holder interest lane a yield account checkpoints against. */
|
|
109
|
+
export type InterestLaneKind = "srlp" | "junior" | "baseHlp" | "quoteHlp";
|
|
110
|
+
|
|
111
|
+
/** The Q64 interest growth index a holder of `kind` checkpoints against for
|
|
112
|
+
* revenue `asset`, as harvest reads it: ordinary srLP
|
|
113
|
+
* `fees.interestGrowthIndexQ64`, junior `fees.junior.interestGrowthQ64`, each
|
|
114
|
+
* hLP vault's per-asset index. A retired junior generation or hLP cohort
|
|
115
|
+
* reads its frozen final index instead; pass the decoded cohort. */
|
|
116
|
+
export function interestGrowthIndexQ64(input: {
|
|
117
|
+
market: Pick<Market, "baseSide" | "quoteSide" | "baseHlpVault" | "quoteHlpVault">;
|
|
118
|
+
kind: InterestLaneKind;
|
|
119
|
+
asset: "base" | "quote";
|
|
120
|
+
retiredJuniorCohort?: Pick<JuniorCohort, "finalIncome">;
|
|
121
|
+
retiredHlpCohort?: Pick<HlpCohort, "finalVault">;
|
|
122
|
+
}): bigint {
|
|
123
|
+
const { market, kind, asset } = input;
|
|
124
|
+
const side = asset === "base" ? market.baseSide : market.quoteSide;
|
|
125
|
+
const hlpIndex = (vault: Pick<HlpVault, "baseInterestGrowthIndexQ64" | "quoteInterestGrowthIndexQ64">) =>
|
|
126
|
+
BigInt((asset === "base" ? vault.baseInterestGrowthIndexQ64 : vault.quoteInterestGrowthIndexQ64).toString());
|
|
127
|
+
if (kind === "srlp") {
|
|
128
|
+
if (input.retiredJuniorCohort || input.retiredHlpCohort) throw new Error("srLP has no retired cohorts");
|
|
129
|
+
return BigInt(side.fees.interestGrowthIndexQ64.toString());
|
|
104
130
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
131
|
+
if (kind === "junior") {
|
|
132
|
+
if (input.retiredHlpCohort) throw new Error("Junior cannot use an hLP cohort");
|
|
133
|
+
const income = input.retiredJuniorCohort ? input.retiredJuniorCohort.finalIncome[asset === "base" ? 0 : 1]! : side.fees.junior;
|
|
134
|
+
return BigInt(income.interestGrowthQ64.toString());
|
|
135
|
+
}
|
|
136
|
+
if (kind !== "baseHlp" && kind !== "quoteHlp") throw new Error("Invalid yield token kind");
|
|
137
|
+
if (input.retiredJuniorCohort) throw new Error("hLP cannot use a junior cohort");
|
|
138
|
+
if (input.retiredHlpCohort) return hlpIndex(input.retiredHlpCohort.finalVault);
|
|
139
|
+
return hlpIndex(kind === "baseHlp" ? market.baseHlpVault : market.quoteHlpVault);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Mirror of `accrue_fee_liability_with_remainder`: whole atoms a balance
|
|
143
|
+
* earns as a Q64 growth index moves past its checkpoint, carrying the
|
|
144
|
+
* sub-atom remainder. */
|
|
145
|
+
export function accrueGrowthQ64(input: {
|
|
146
|
+
balance: bigint;
|
|
147
|
+
growthIndexQ64: bigint;
|
|
148
|
+
checkpointQ64: bigint;
|
|
149
|
+
remainderQ64: bigint;
|
|
150
|
+
}): { amount: bigint; remainderQ64: bigint } {
|
|
151
|
+
const { balance, growthIndexQ64: index, checkpointQ64: checkpoint, remainderQ64: remainder } = input;
|
|
152
|
+
amount(balance);
|
|
153
|
+
amount(index, U128_MAX);
|
|
154
|
+
amount(checkpoint, U128_MAX);
|
|
155
|
+
amount(remainder);
|
|
156
|
+
if (balance === 0n || index <= checkpoint) return { amount: 0n, remainderQ64: remainder };
|
|
157
|
+
const delta = index - checkpoint;
|
|
158
|
+
const fractional = balance * (delta & U64_MAX) + remainder;
|
|
159
|
+
const accrued = balance * (delta >> 64n) + (fractional >> 64n);
|
|
160
|
+
amount(accrued);
|
|
161
|
+
return { amount: accrued, remainderQ64: fractional & U64_MAX };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Interest a yield account can claim at `growthIndexQ64`, computed as
|
|
165
|
+
* `YieldAccount::accrue` checkpoints it: the stored `accruedInterestAmount`
|
|
166
|
+
* plus the balance's share of the index change since the holder's
|
|
167
|
+
* checkpoint. Junior escrow receipts earn alongside the wallet balance. Pass
|
|
168
|
+
* the LP balance the program reads (the owner's LP token account) and an
|
|
169
|
+
* index from `interestGrowthIndexQ64` read with the account. The index
|
|
170
|
+
* includes interest up to the market's last accrual.
|
|
171
|
+
*
|
|
172
|
+
* A harvest pays `min(claimable, cashReserve)` of the asset's reserve side;
|
|
173
|
+
* the rest stays claimable (`harvestableInterest`). */
|
|
174
|
+
export function claimableInterest(input: {
|
|
175
|
+
yieldAccount: Pick<YieldAccount, "tokenKind" | "escrowBalance" | "accruedInterestAmount" | "interestCheckpointQ64" | "interestRemainderQ64">;
|
|
176
|
+
lpBalance: bigint;
|
|
177
|
+
growthIndexQ64: bigint;
|
|
178
|
+
}): bigint {
|
|
179
|
+
const holder = input.yieldAccount;
|
|
180
|
+
const escrow = holder.tokenKind === 2 ? BigInt(holder.escrowBalance.toString()) : 0n;
|
|
181
|
+
const balance = input.lpBalance + escrow;
|
|
182
|
+
const accrued = accrueGrowthQ64({
|
|
183
|
+
balance,
|
|
184
|
+
growthIndexQ64: input.growthIndexQ64,
|
|
185
|
+
checkpointQ64: BigInt(holder.interestCheckpointQ64.toString()),
|
|
186
|
+
remainderQ64: BigInt(holder.interestRemainderQ64.toString()),
|
|
187
|
+
}).amount;
|
|
188
|
+
const claimable = BigInt(holder.accruedInterestAmount.toString()) + accrued;
|
|
189
|
+
amount(claimable);
|
|
190
|
+
return claimable;
|
|
108
191
|
}
|
|
109
192
|
|
|
110
|
-
/**
|
|
111
|
-
*
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
const { grossTransfer, pendingFeeGross: fees, measuredVaultCredit: credit } = input;
|
|
120
|
-
for (const value of [grossTransfer, fees, credit]) amount(value);
|
|
121
|
-
if (credit > grossTransfer || fees > grossTransfer) throw new RangeError("Custody credit or fees exceed settlement");
|
|
122
|
-
const revenueCredit = grossTransfer === 0n ? 0n : credit * fees / grossTransfer;
|
|
123
|
-
return { grossTransfer, revenueCredit, lpCredit: credit - revenueCredit };
|
|
193
|
+
/** Interest a harvest pays now: claimable interest limited by the asset's
|
|
194
|
+
* reserve cash. Unpaid interest stays claimable and is not lost. */
|
|
195
|
+
export function harvestableInterest(input: {
|
|
196
|
+
claimable: bigint;
|
|
197
|
+
market: Pick<Market, "baseSide" | "quoteSide">;
|
|
198
|
+
asset: "base" | "quote";
|
|
199
|
+
}): bigint {
|
|
200
|
+
const cash = BigInt((input.asset === "base" ? input.market.baseSide : input.market.quoteSide).reserves.cashReserve.toString());
|
|
201
|
+
return input.claimable < cash ? input.claimable : cash;
|
|
124
202
|
}
|
|
@@ -217,7 +217,7 @@ export class DuskLiquidations {
|
|
|
217
217
|
const referralPartner = partner.equals(PublicKey.default) ? null : partner;
|
|
218
218
|
const accounts = { ...r.readAccounts, buyer, buyerCollateralAccount, buyerRefundAccount, ownerDebtAccount,
|
|
219
219
|
collateralVault: params.kind === "borrow" ? r.collateralSide.collateralVault : deriveLeverageCollateralVaultAddress(r.market, r.collateralSide.assetMint, this.program.programId)[0],
|
|
220
|
-
reserveVault: r.debtSide.reserveVault,
|
|
220
|
+
reserveVault: r.debtSide.reserveVault,
|
|
221
221
|
futarchyAuthority: deriveFutarchyAuthorityAddress(this.program.programId)[0], referralPartner,
|
|
222
222
|
referralAccrual: referralPartner ? deriveReferralAccrualAddress(referralPartner, r.market, r.debtSide.assetMint, this.program.programId)[0] : null,
|
|
223
223
|
tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID, debtTokenProgram };
|
|
@@ -293,7 +293,7 @@ export class DuskLiquidations {
|
|
|
293
293
|
const accounts = {
|
|
294
294
|
...r.readAccounts, buyer, buyerCollateralAccount, buyerRefundAccount: buyerDebtAccount, ownerDebtAccount,
|
|
295
295
|
collateralVault: params.kind === "borrow" ? r.collateralSide.collateralVault : deriveLeverageCollateralVaultAddress(r.market, r.collateralSide.assetMint, this.program.programId)[0],
|
|
296
|
-
reserveVault: r.debtSide.reserveVault,
|
|
296
|
+
reserveVault: r.debtSide.reserveVault,
|
|
297
297
|
futarchyAuthority: deriveFutarchyAuthorityAddress(this.program.programId)[0], referralPartner,
|
|
298
298
|
referralAccrual: referralPartner ? deriveReferralAccrualAddress(referralPartner, r.market, r.debtSide.assetMint, this.program.programId)[0] : null,
|
|
299
299
|
tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID, debtTokenProgram,
|
package/src/operator-client.ts
CHANGED
|
@@ -126,23 +126,22 @@ export class DuskOperator {
|
|
|
126
126
|
const side=state.baseSide.assetMint.equals(mint)?state.baseSide:state.quoteSide.assetMint.equals(mint)?state.quoteSide:null;
|
|
127
127
|
if(!side)throw new Error("asset mint is not part of the market");
|
|
128
128
|
const asset=state.baseSide.assetMint.equals(mint)?0:1;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
claimable+=BigInt((current?revenueBook.operatorClaimable:archive!.claimable[i]!).toString());
|
|
133
|
-
}
|
|
129
|
+
// Operator interest is credited at accrual and paid from reserve cash as
|
|
130
|
+
// it allows; a sealed recipient keeps the amount credited before handoff.
|
|
131
|
+
const claimable=BigInt((current?side.fees.ledger.operatorClaimable:archive!.claimable[asset]!).toString());
|
|
134
132
|
const requested=BigInt(integerBN(params.maxDebit??0xffff_ffff_ffff_ffffn,"maxDebit").toString());
|
|
135
|
-
const
|
|
136
|
-
|
|
133
|
+
const cash=BigInt(side.reserves.cashReserve.toString());
|
|
134
|
+
const debit=[claimable,requested,cash].reduce((a,b)=>a<b?a:b);
|
|
135
|
+
if(debit===0n)throw new Error(claimable===0n?"no operator interest is claimable":"no reserve cash is available for operator interest");
|
|
137
136
|
const tokenProgram=await tokenProgramForMint(this.program.provider.connection,mint);
|
|
138
137
|
const mintState=await getMint(this.program.provider.connection,mint,undefined,tokenProgram);
|
|
139
138
|
const ata=getAssociatedTokenAddressSync(mint,recipient,true,tokenProgram);
|
|
140
139
|
const hook=await resolveTransferHookAccountMetas(this.program.provider.connection,[{
|
|
141
|
-
mint,source:side.
|
|
140
|
+
mint,source:side.reserveVault,destination:ata,authority:market,amount:debit,decimals:mintState.decimals,tokenProgram,
|
|
142
141
|
}]);
|
|
143
142
|
const instruction=await this.write.instruction("claimOperatorRevenue",{revenueEpoch:epoch,
|
|
144
143
|
maxDebit:integerBN(debit,"maxDebit"),minimumCredit:integerBN(params.minimumCredit??0,"minimumCredit")},
|
|
145
|
-
{accounts:{market,revenue,recipient,assetMint:mint,
|
|
144
|
+
{accounts:{market,revenue,recipient,assetMint:mint,reserveVault:side.reserveVault,recipientAssetAccount:ata,
|
|
146
145
|
tokenProgram:TOKEN_PROGRAM_ID,token2022Program:TOKEN_2022_PROGRAM_ID},remainingAccounts:[...hook,...(params.remainingAccounts??[])]});
|
|
147
146
|
const transaction=new Transaction().add(createAssociatedTokenAccountIdempotentInstruction(payer,ata,recipient,mint,tokenProgram),instruction);
|
|
148
147
|
return {instruction,transaction,recipient,revenue,recipientAssetAccount:ata};
|
package/src/referral.ts
CHANGED
|
@@ -25,7 +25,6 @@ export type IntegerLike = bigint | number | string | { toString(): string };
|
|
|
25
25
|
|
|
26
26
|
export interface ReferralInterestQuote {
|
|
27
27
|
interestPaid: bigint;
|
|
28
|
-
interestVaultCredit: bigint;
|
|
29
28
|
protocolInterestRevenue: bigint;
|
|
30
29
|
interestShareBps: number;
|
|
31
30
|
referralAmount: bigint;
|
|
@@ -42,32 +41,28 @@ export function referralBindingInterestShareBps(params: {
|
|
|
42
41
|
return Math.min(params.configuredShareBps, params.maxShareBps);
|
|
43
42
|
}
|
|
44
43
|
|
|
44
|
+
/** Mirror of the program's referral quote for one interest payment.
|
|
45
|
+
* `protocolInterestRevenue` is the protocol share of that payment, which the
|
|
46
|
+
* program takes pro rata from the asset's unpaid protocol interest
|
|
47
|
+
* (`quoteProtocolInterestShare`); the partner receives its capped share of
|
|
48
|
+
* it, rounded down. */
|
|
45
49
|
export function quoteReferralInterestShare(params: {
|
|
46
50
|
interestPaid: IntegerLike;
|
|
47
|
-
|
|
48
|
-
protocolInterestBps: number;
|
|
51
|
+
protocolInterestRevenue: IntegerLike;
|
|
49
52
|
interestShareBps: number;
|
|
50
53
|
}): ReferralInterestQuote {
|
|
51
|
-
assertBps(params.protocolInterestBps, "protocol interest share");
|
|
52
54
|
assertReferralInterestShareBps(params.interestShareBps);
|
|
53
55
|
const interestPaid = BigInt(params.interestPaid.toString());
|
|
54
56
|
if (interestPaid < 0n) throw new Error("interestPaid must be non-negative");
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
if (interestVaultCredit < 0n || interestVaultCredit > interestPaid) {
|
|
59
|
-
throw new Error("interestVaultCredit must be between 0 and interestPaid");
|
|
57
|
+
const protocolInterestRevenue = BigInt(params.protocolInterestRevenue.toString());
|
|
58
|
+
if (protocolInterestRevenue < 0n || protocolInterestRevenue > interestPaid) {
|
|
59
|
+
throw new Error("protocolInterestRevenue must be between 0 and interestPaid");
|
|
60
60
|
}
|
|
61
|
-
|
|
62
|
-
const protocolInterestRevenue =
|
|
63
|
-
(interestVaultCredit * BigInt(params.protocolInterestBps)) /
|
|
64
|
-
BigInt(REFERRAL_BPS_DENOMINATOR);
|
|
65
61
|
const referralAmount =
|
|
66
62
|
(protocolInterestRevenue * BigInt(params.interestShareBps)) /
|
|
67
63
|
BigInt(REFERRAL_BPS_DENOMINATOR);
|
|
68
64
|
return {
|
|
69
65
|
interestPaid,
|
|
70
|
-
interestVaultCredit,
|
|
71
66
|
protocolInterestRevenue,
|
|
72
67
|
interestShareBps: params.interestShareBps,
|
|
73
68
|
referralAmount,
|
package/src/tranche-client.ts
CHANGED
|
@@ -1,36 +1,14 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Program } from "@coral-xyz/anchor";
|
|
2
2
|
import { PublicKey, SystemProgram, Transaction, SYSVAR_INSTRUCTIONS_PUBKEY, type AccountMeta } from "@solana/web3.js";
|
|
3
3
|
import { createAssociatedTokenAccountIdempotentInstruction, getAssociatedTokenAddressSync, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from "@solana/spl-token";
|
|
4
4
|
import { address, type AddressLike } from "./address.js";
|
|
5
|
-
import { deriveJuniorMintAddress, deriveJuniorCohortAddress, deriveJuniorExitAddress, deriveYieldAccountAddress,
|
|
5
|
+
import { deriveJuniorMintAddress, deriveJuniorCohortAddress, deriveJuniorExitAddress, deriveYieldAccountAddress, deriveTokenMetadataAddress, TOKEN_METADATA_PROGRAM_ID } from "./constants.js";
|
|
6
6
|
import { integerBN, type IntegerLike } from "./parameters.js";
|
|
7
7
|
import { assertLpTokenMetadata, type LpTokenMetadataInput } from "./lp-naming.js";
|
|
8
8
|
import { oracleComputeBudgetInstructions, oracleReadAccounts } from "./oracle.js";
|
|
9
9
|
import { DuskWrite } from "./write.js";
|
|
10
10
|
import { assertCurrentMarketLayout } from "./market-layout.js";
|
|
11
11
|
import type { Dusk as DuskIdl } from "./types_v2.js";
|
|
12
|
-
import type { Market } from "./type-aliases.js";
|
|
13
|
-
|
|
14
|
-
type IncomeBook = Market["income"]["books"][number];
|
|
15
|
-
|
|
16
|
-
/** Whether `value` reaches half of an unsigned `bits`-bit range (Rust's
|
|
17
|
-
* `MAX / 2`, which is 2^(bits−1) − 1). */
|
|
18
|
-
const atHalfRange = (value: BN, bits: number) => value.addn(1).bitLength() >= bits;
|
|
19
|
-
|
|
20
|
-
/** Mirrors `roll_income_epoch`: a book with settled units rolls once at least
|
|
21
|
-
* half its units are repaid, or once any counter reaches half its range.
|
|
22
|
-
* Rolling earlier would let anyone fragment holders' catch-up into many
|
|
23
|
-
* archived epochs. */
|
|
24
|
-
export function incomeBookMayRoll(book: IncomeBook): boolean {
|
|
25
|
-
if (book.units.lte(book.unpaid)) return false;
|
|
26
|
-
if (book.unpaid.lte(book.units.divn(2))) return true;
|
|
27
|
-
return (
|
|
28
|
-
atHalfRange(book.units, 64) ||
|
|
29
|
-
atHalfRange(book.unpaid, 64) ||
|
|
30
|
-
atHalfRange(book.paidPerUnitQ64, 128) ||
|
|
31
|
-
book.growth.some((lane) => atHalfRange(lane.unitsQ64, 128) || atHalfRange(lane.weightedPaidQ128[3], 64))
|
|
32
|
-
);
|
|
33
|
-
}
|
|
34
12
|
|
|
35
13
|
export type TrancheAction =
|
|
36
14
|
| { kind: "enter"; seniorAmount: IntegerLike; minimumJunior: IntegerLike }
|
|
@@ -49,87 +27,6 @@ export class DuskTranches {
|
|
|
49
27
|
return assertCurrentMarketLayout(await this.program.account.market.fetch(market));
|
|
50
28
|
}
|
|
51
29
|
|
|
52
|
-
/** Archive an income denomination once at least half of its units are
|
|
53
|
-
* repaid, or once it nears its numeric limits, so further issuance does not
|
|
54
|
-
* overflow. Anyone may roll; this does not claim anyone's income. */
|
|
55
|
-
async rollIncome(params: { market: AddressLike; payer: AddressLike; bookIndex: number }) {
|
|
56
|
-
const market = address(params.market), payer = address(params.payer);
|
|
57
|
-
const state = await this.marketState(market);
|
|
58
|
-
const { bookIndex } = params;
|
|
59
|
-
if (!Number.isInteger(bookIndex) || bookIndex < 0 || bookIndex > 3) throw new Error("bookIndex must be 0–3");
|
|
60
|
-
const book = state.income.books[bookIndex];
|
|
61
|
-
if (!incomeBookMayRoll(book)) {
|
|
62
|
-
throw new Error("Income book cannot roll until half its units are repaid or it nears its numeric limits");
|
|
63
|
-
}
|
|
64
|
-
if (!state.income.pending[bookIndex].isZero()) throw new Error("Income custody settlement is pending");
|
|
65
|
-
const incomeEpoch = deriveIncomeEpochAddress(market, bookIndex, book.epoch, this.program.programId)[0];
|
|
66
|
-
const instruction = await this.write.instruction("rollIncomeEpoch", { bookIndex, epoch: book.epoch }, { accounts: {
|
|
67
|
-
payer, market, incomeEpoch, systemProgram: SystemProgram.programId,
|
|
68
|
-
} });
|
|
69
|
-
return { incomeEpoch, instruction, transaction: new Transaction().add(instruction) };
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Prepare one bounded history catch-up per source. Submit and fetch again
|
|
73
|
-
* while hasMore is true, before transferring, converting or harvesting. */
|
|
74
|
-
async checkpointIncome(params: { market: AddressLike; owner: AddressLike; kind: "senior" | "junior"; asset: "base" | "quote"; retiredJuniorMint?: AddressLike }) {
|
|
75
|
-
const market = address(params.market), owner = address(params.owner);
|
|
76
|
-
if (params.kind !== "junior" && params.retiredJuniorMint) throw new Error("Only junior has retired generations");
|
|
77
|
-
const state = await this.marketState(market);
|
|
78
|
-
const lpMint = params.kind === "senior" ? state.srlpMint : params.retiredJuniorMint ? address(params.retiredJuniorMint) : state.juniorMint;
|
|
79
|
-
const assetIndex = params.asset === "base" ? 0 : 1;
|
|
80
|
-
const assetMint = assetIndex === 0 ? state.baseSide.assetMint : state.quoteSide.assetMint;
|
|
81
|
-
const yieldAccount = deriveYieldAccountAddress(market, owner, lpMint, assetMint, params.kind === "senior" ? "srlp" : "junior", this.program.programId)[0];
|
|
82
|
-
const holder = await this.program.account.yieldAccount.fetch(yieldAccount);
|
|
83
|
-
if (!holder.incomeInitialized) throw new Error("Initialize the holder's income ledger before catch-up");
|
|
84
|
-
const ownerLp = getAssociatedTokenAddressSync(lpMint, owner, true, TOKEN_2022_PROGRAM_ID);
|
|
85
|
-
const instructions = [];
|
|
86
|
-
let hasMore = false;
|
|
87
|
-
for (let source = 0; source < 2; source++) {
|
|
88
|
-
const bookIndex = assetIndex + source * 2;
|
|
89
|
-
const epoch = BigInt(holder.income[source].epoch.toString());
|
|
90
|
-
const liveEpoch = BigInt(state.income.books[bookIndex].epoch.toString());
|
|
91
|
-
if (epoch > liveEpoch) throw new Error("Holder income epoch exceeds market epoch");
|
|
92
|
-
const count = Number(liveEpoch - epoch > 8n ? 8n : liveEpoch - epoch);
|
|
93
|
-
const remainingAccounts: AccountMeta[] = [];
|
|
94
|
-
if (params.kind === "junior" && !lpMint.equals(state.juniorMint)) remainingAccounts.push({ pubkey: deriveJuniorCohortAddress(market, lpMint, this.program.programId)[0], isSigner: false, isWritable: false });
|
|
95
|
-
for (let i = 0; i < count; i++) remainingAccounts.push({ pubkey: deriveIncomeEpochAddress(market, bookIndex, epoch + BigInt(i), this.program.programId)[0], isSigner: false, isWritable: false });
|
|
96
|
-
instructions.push(await this.write.instruction("checkpointIncome", { source }, { accounts: { market, lpMint, ownerLp, yieldAccount }, remainingAccounts }));
|
|
97
|
-
hasMore ||= epoch + BigInt(count) < liveEpoch;
|
|
98
|
-
}
|
|
99
|
-
return { instructions, hasMore, yieldAccount };
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/** Prepare bounded, separate transactions to catch up both assets before a
|
|
103
|
-
* srLP/jrLP transfer, exit or claim. No transaction is sent by this method.
|
|
104
|
-
* If hasMore is true, submit these batches and call again. A concurrent epoch
|
|
105
|
-
* roll can also require another fetch; never discard the holder's old claim. */
|
|
106
|
-
async prepareHolderIncome(params: { market: AddressLike; owner: AddressLike; kind: "senior" | "junior"; retiredJuniorMint?: AddressLike }) {
|
|
107
|
-
const transactions: Transaction[] = [];
|
|
108
|
-
let hasMore = false;
|
|
109
|
-
for (const asset of ["base", "quote"] as const) {
|
|
110
|
-
const batch = await this.checkpointIncome({ ...params, asset });
|
|
111
|
-
transactions.push(...batch.instructions.map(ix => new Transaction().add(ix)));
|
|
112
|
-
hasMore ||= batch.hasMore;
|
|
113
|
-
}
|
|
114
|
-
return { transactions, hasMore };
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/** Archive drained books before another operation issues income. This is a
|
|
118
|
-
* market-wide maintenance step, separate from catching up individual holders.
|
|
119
|
-
* A numerically exhausted, partially paid book can be rolled explicitly with
|
|
120
|
-
* rollIncome after IncomeEpochNeedsRollover. The payer funds archival rent. */
|
|
121
|
-
async prepareDrainedIncomeBooks(params: { market: AddressLike; payer: AddressLike }) {
|
|
122
|
-
const state = await this.marketState(address(params.market));
|
|
123
|
-
const transactions: Transaction[] = [];
|
|
124
|
-
for (let bookIndex = 0; bookIndex < 4; bookIndex++) {
|
|
125
|
-
const book = state.income.books[bookIndex];
|
|
126
|
-
if (!book.units.isZero() && book.unpaid.isZero()) {
|
|
127
|
-
transactions.push((await this.rollIncome({ ...params, bookIndex })).transaction);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
return { transactions };
|
|
131
|
-
}
|
|
132
|
-
|
|
133
30
|
/** A retired receipt has zero principal but can still own earned income. */
|
|
134
31
|
async burnRetired(params: { market: AddressLike; owner: AddressLike; retiredMint: AddressLike; amount: IntegerLike }) {
|
|
135
32
|
const market = address(params.market), owner = address(params.owner), retiredMint = address(params.retiredMint);
|
|
@@ -152,7 +49,7 @@ export class DuskTranches {
|
|
|
152
49
|
const state = await this.marketState(market);
|
|
153
50
|
const side = params.asset === "base" ? state.baseSide : state.quoteSide;
|
|
154
51
|
const instruction = await this.write.instruction("fundJuniorSeed", undefined, { accounts: {
|
|
155
|
-
market, assetMint: side.assetMint, reserveVault: side.reserveVault,
|
|
52
|
+
market, assetMint: side.assetMint, reserveVault: side.reserveVault,
|
|
156
53
|
tokenProgram: TOKEN_PROGRAM_ID, token2022Program: TOKEN_2022_PROGRAM_ID,
|
|
157
54
|
}, remainingAccounts: params.remainingAccounts });
|
|
158
55
|
return { instruction, transaction: new Transaction().add(instruction) };
|
package/src/transfer-fees.ts
CHANGED
|
@@ -54,6 +54,24 @@ export function transferFeeCredit(gross: bigint, notice: TransferFeeNotice, valu
|
|
|
54
54
|
return credit;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/** Fee to add to `postFeeAmount` under the effective schedule so a transfer
|
|
58
|
+
* of the sum delivers at least `postFeeAmount`: SPL `calculate_inverse_fee`,
|
|
59
|
+
* with a 100% rate charging its maximum fee. The program grosses up interest
|
|
60
|
+
* moved into income custody by exactly this amount.
|
|
61
|
+
*/
|
|
62
|
+
export function transferInverseFee(postFeeAmount: bigint, notice: TransferFeeNotice): bigint {
|
|
63
|
+
u64(postFeeAmount);
|
|
64
|
+
const fee = notice.effective;
|
|
65
|
+
if (!fee || postFeeAmount === 0n || fee.transferFeeBasisPoints === 0) return 0n;
|
|
66
|
+
if (fee.transferFeeBasisPoints === 10_000) return fee.maximumFee;
|
|
67
|
+
const numerator = postFeeAmount * 10_000n;
|
|
68
|
+
const denominator = 10_000n - BigInt(fee.transferFeeBasisPoints);
|
|
69
|
+
const raw = (numerator + denominator - 1n) / denominator;
|
|
70
|
+
const preFeeAmount = raw - postFeeAmount >= fee.maximumFee ? postFeeAmount + fee.maximumFee : raw;
|
|
71
|
+
u64(preFeeAmount);
|
|
72
|
+
return calculateFee(fee, preFeeAmount);
|
|
73
|
+
}
|
|
74
|
+
|
|
57
75
|
export interface MintTransferFeeNotice extends TransferFeeNotice {
|
|
58
76
|
mint: string;
|
|
59
77
|
tokenProgram: string;
|
package/src/type-aliases.ts
CHANGED
|
@@ -10,7 +10,7 @@ type TypeNamed<N extends Dusk["types"][number]["name"]> = Extract<
|
|
|
10
10
|
>;
|
|
11
11
|
type DuskAccountTypes = [
|
|
12
12
|
TypeNamed<"operatorRevenueAccount">,
|
|
13
|
-
TypeNamed<"
|
|
13
|
+
TypeNamed<"interestLedger">,
|
|
14
14
|
TypeNamed<"operatorProposal">,
|
|
15
15
|
TypeNamed<"operatorState">,
|
|
16
16
|
TypeNamed<"concentrationRamp">,
|
|
@@ -37,7 +37,6 @@ type DuskAccountTypes = [
|
|
|
37
37
|
TypeNamed<"deferredControllerTarget">,
|
|
38
38
|
TypeNamed<"feeProfile">,
|
|
39
39
|
TypeNamed<"fees">,
|
|
40
|
-
TypeNamed<"publicInterestAdvance">,
|
|
41
40
|
TypeNamed<"futarchyAuthority">,
|
|
42
41
|
TypeNamed<"hlpCohort">,
|
|
43
42
|
TypeNamed<"hlpVault">,
|
|
@@ -47,15 +46,9 @@ type DuskAccountTypes = [
|
|
|
47
46
|
TypeNamed<"tranchePolicy">,
|
|
48
47
|
TypeNamed<"trancheRevenueCarry">,
|
|
49
48
|
TypeNamed<"juniorExitConfig">,
|
|
50
|
-
TypeNamed<"marketIncomeBooks">,
|
|
51
|
-
TypeNamed<"incomeReceivableBook">,
|
|
52
|
-
TypeNamed<"incomeReceivableClaim">,
|
|
53
|
-
TypeNamed<"incomeExposureEnd">,
|
|
54
|
-
TypeNamed<"incomeEpoch">,
|
|
55
49
|
TypeNamed<"juniorCohort">,
|
|
56
50
|
TypeNamed<"juniorExitAccount">,
|
|
57
51
|
TypeNamed<"juniorExitTicket">,
|
|
58
|
-
TypeNamed<"receivableGrowth">,
|
|
59
52
|
TypeNamed<"leverageDelegation">,
|
|
60
53
|
TypeNamed<"leverageMarginTerms">,
|
|
61
54
|
TypeNamed<"leveragePosition">,
|
|
@@ -102,9 +95,6 @@ type DuskEventTypes = [
|
|
|
102
95
|
TypeNamed<"flashLiquidationSettled">,
|
|
103
96
|
TypeNamed<"emergencyLiquidationSettled">,
|
|
104
97
|
TypeNamed<"ammConfig">,
|
|
105
|
-
TypeNamed<"fundInterestReceipt">,
|
|
106
|
-
TypeNamed<"publicInterestFunded">,
|
|
107
|
-
TypeNamed<"hlpInterestAllocated">,
|
|
108
98
|
TypeNamed<"hlpFlashQuote">,
|
|
109
99
|
TypeNamed<"hlpFlashStarted">,
|
|
110
100
|
TypeNamed<"hlpFlashSettled">,
|
|
@@ -195,8 +185,9 @@ type DuskFlashAmmIdl = {
|
|
|
195
185
|
};
|
|
196
186
|
|
|
197
187
|
export type Market = IdlTypes<DuskAccountIdl>["market"];
|
|
188
|
+
export type HlpVault = IdlTypes<DuskAccountIdl>["hlpVault"];
|
|
189
|
+
export type InterestLedger = IdlTypes<DuskAccountIdl>["interestLedger"];
|
|
198
190
|
export type HlpFlashQuote = IdlTypes<DuskAccountIdl>["hlpFlashQuote"];
|
|
199
|
-
export type FundInterestReceipt = IdlTypes<DuskEventIdl>["fundInterestReceipt"];
|
|
200
191
|
export type FlashLiquidationQuote = IdlTypes<DuskEventIdl>["flashLiquidationQuote"];
|
|
201
192
|
export type FlashAmmLiquidationQuote = IdlTypes<DuskFlashAmmIdl>["flashAmmLiquidationQuote"];
|
|
202
193
|
export type EmergencyLiquidationQuote = IdlTypes<DuskEventIdl>["emergencyLiquidationQuote"];
|
|
@@ -206,7 +197,6 @@ export type LeverageDelegation = IdlTypes<DuskAccountIdl>["leverageDelegation"];
|
|
|
206
197
|
export type YieldAccount = IdlTypes<DuskAccountIdl>["yieldAccount"];
|
|
207
198
|
export type JuniorCohort = IdlTypes<DuskAccountIdl>["juniorCohort"];
|
|
208
199
|
export type JuniorExitAccount = IdlTypes<DuskAccountIdl>["juniorExitAccount"];
|
|
209
|
-
export type IncomeEpoch = IdlTypes<DuskAccountIdl>["incomeEpoch"];
|
|
210
200
|
export type FutarchyAuthority = IdlTypes<DuskAccountIdl>["futarchyAuthority"];
|
|
211
201
|
export type ReferralPartner = IdlTypes<DuskAccountIdl>["referralPartner"];
|
|
212
202
|
export type ReferralAccrual = IdlTypes<DuskAccountIdl>["referralAccrual"];
|
|
@@ -273,8 +263,6 @@ export type EmergencyLiquidationSettled = IdlTypes<DuskEventIdl>["emergencyLiqui
|
|
|
273
263
|
export type HlpFlashSession = IdlTypes<DuskAccountIdl>["hlpFlashSession"];
|
|
274
264
|
export type HlpFlashStarted = IdlTypes<DuskEventIdl>["hlpFlashStarted"];
|
|
275
265
|
export type HlpFlashSettled = IdlTypes<DuskEventIdl>["hlpFlashSettled"];
|
|
276
|
-
export type HlpInterestAllocated = IdlTypes<DuskEventIdl>["hlpInterestAllocated"];
|
|
277
|
-
export type PublicInterestFunded = IdlTypes<DuskEventIdl>["publicInterestFunded"];
|
|
278
266
|
|
|
279
267
|
export type JuniorSeedCompounded = IdlTypes<DuskEventIdl>["juniorSeedCompounded"];
|
|
280
268
|
export type JuniorCohortInitialized = IdlTypes<DuskEventIdl>["juniorCohortInitialized"];
|