Skip to content

Commit e6765c1

Browse files
committed
fix: account opener should not claim more then it needs
1 parent aeaec49 commit e6765c1

File tree

2 files changed

+70
-37
lines changed

2 files changed

+70
-37
lines changed

src/dev/AccountOpener.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -519,8 +519,8 @@ export class AccountOpener extends SDKConstruct {
519519
);
520520
}
521521

522-
let totalUSD = 0n;
523522
const deposits: [PoolContract, bigint][] = [];
523+
const claims: AddressMap<bigint> = new AddressMap();
524524
for (const [p, minAvailable] of Object.entries(minAvailableByPool)) {
525525
const market = this.sdk.marketRegister.findByPool(p as Address);
526526
const pool = market.pool.pool;
@@ -538,21 +538,19 @@ export class AccountOpener extends SDKConstruct {
538538
);
539539
if (diff > 0n) {
540540
deposits.push([pool, diff]);
541-
totalUSD += market.priceOracle.convertToUSD(pool.underlying, diff);
541+
let claim = claims.get(pool.underlying) ?? 0n;
542+
// pool.available * linearModel.U2 can be borrowed
543+
// U2 is currently at 90% in all pools
544+
claim += (diff * PERCENTAGE_FACTOR) / 8950n;
545+
claims.upsert(pool.underlying, claim);
542546
}
543547
}
544-
// pool.available * linearModel.U2 can be borrowed
545-
// U2 is currently at 90% in all pools
546-
totalUSD = (totalUSD * PERCENTAGE_FACTOR) / 8950n;
547-
this.#logger?.debug(
548-
`total USD to claim from faucet: ${formatBN(totalUSD, 8)}`,
549-
);
550548

551549
const depositor = await this.#getDepositor();
552550
this.#logger?.debug(`depositor: ${depositor.address}`);
553551

554552
try {
555-
await this.#claimFromFaucet(depositor, "depositor", totalUSD);
553+
await this.#claimFromFaucet(depositor, "depositor", claims);
556554
} catch (e) {
557555
if (this.#allowMint) {
558556
this.#logger?.error(`depositor failed to claim from faucet: ${e}`);
@@ -686,9 +684,9 @@ export class AccountOpener extends SDKConstruct {
686684
const borrower = await this.#getBorrower();
687685

688686
// each account will have minDebt*minDebtMultiplier in USD, see how much we need to claim from faucet
689-
let claimUSD = 0n;
690687
// collect all degen nfts
691688
const degenNFTS: Record<Address, number> = {};
689+
const claims: AddressMap<bigint> = new AddressMap();
692690
for (const target of targets) {
693691
const cm = this.sdk.marketRegister.findCreditManager(
694692
target.creditManager,
@@ -700,15 +698,16 @@ export class AccountOpener extends SDKConstruct {
700698
const minDebt =
701699
(this.#minDebtMultiplier * cm.creditFacade.minDebt) / PERCENTAGE_FACTOR;
702700

703-
claimUSD += market.priceOracle.convertToUSD(cm.underlying, minDebt);
701+
const claim = claims.get(cm.underlying) ?? 0n;
702+
// 10% more to be safe
703+
claims.upsert(cm.underlying, claim + (minDebt * 11n) / 10n);
704704

705705
if (isAddress(degenNFT) && degenNFT !== ADDRESS_0X0) {
706706
degenNFTS[degenNFT] = (degenNFTS[degenNFT] ?? 0) + 1;
707707
}
708708
}
709-
claimUSD = (claimUSD * 11n) / 10n; // 10% more to be safe
710709

711-
await this.#claimFromFaucet(borrower, "borrower", claimUSD);
710+
await this.#claimFromFaucet(borrower, "borrower", claims);
712711

713712
for (const [degenNFT, amount] of Object.entries(degenNFTS)) {
714713
await this.#mintDegenNft(degenNFT as Address, borrower.address, amount);
@@ -720,15 +719,16 @@ export class AccountOpener extends SDKConstruct {
720719
async #claimFromFaucet(
721720
claimer: PrivateKeyAccount,
722721
role: string,
723-
amountUSD: bigint,
722+
claims: AddressMap<bigint>,
724723
): Promise<void> {
725724
await claimFromFaucet({
725+
sdk: this.sdk,
726726
publicClient: this.#anvil,
727727
wallet: this.#anvil,
728728
faucet: this.faucet,
729729
claimer,
730730
role,
731-
amountUSD,
731+
amount: claims.entries().map(([k, v]) => ({ token: k, amount: v })),
732732
logger: this.#logger,
733733
});
734734
}
@@ -878,6 +878,7 @@ export class AccountOpener extends SDKConstruct {
878878
value: parseEther("100"),
879879
});
880880
await claimFromFaucet({
881+
sdk: this.sdk,
881882
publicClient: this.#anvil,
882883
wallet: this.#anvil,
883884
faucet: this.faucet,

src/dev/claimFromFaucet.ts

Lines changed: 54 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
import type {
2+
AbiParametersToPrimitiveTypes,
3+
ExtractAbiFunction,
4+
} from "abitype";
15
import {
26
type Account,
37
type Address,
@@ -6,15 +10,28 @@ import {
610
type WalletClient,
711
} from "viem";
812
import { readContract } from "viem/actions";
9-
import { formatBN, type ILogger } from "../sdk/index.js";
13+
import { formatBN, type GearboxSDK, type ILogger } from "../sdk/index.js";
14+
15+
interface TokenClaim {
16+
token: Address;
17+
amount: bigint;
18+
}
1019

1120
interface ClaimFromFaucetOptions {
21+
sdk: GearboxSDK;
1222
publicClient: PublicClient;
1323
wallet: WalletClient;
1424
faucet: Address;
1525
claimer: Account;
1626
role?: string;
17-
amountUSD?: bigint | ((minAmountUSD: bigint) => bigint);
27+
/**
28+
* Either:
29+
* - List of tokens with exact amounts to claim
30+
* - Amount in USD
31+
* - Function that returns amount in USD
32+
* - Undefined (will claim default amount)
33+
*/
34+
amount?: TokenClaim[] | bigint | ((minAmountUSD: bigint) => bigint);
1835
gasMultiplier?: bigint;
1936
logger?: ILogger;
2037
}
@@ -23,60 +40,77 @@ const faucetAbi = parseAbi([
2340
"function minAmountUSD() external view returns (uint256)",
2441
"function claim() external",
2542
"function claim(uint256 amountUSD) external",
43+
"function claim((address token, uint256 amount)[] claims) external",
2644
]);
2745

2846
export async function claimFromFaucet(
2947
opts: ClaimFromFaucetOptions,
3048
): Promise<void> {
3149
const {
50+
sdk,
3251
publicClient,
3352
wallet,
3453
faucet,
3554
claimer,
3655
role,
37-
amountUSD,
56+
amount,
3857
logger,
3958
gasMultiplier = 10n,
4059
} = opts;
4160

42-
let toClaimUSD: bigint | undefined;
43-
if (typeof amountUSD === "bigint") {
44-
toClaimUSD = amountUSD;
45-
} else if (typeof amountUSD === "function") {
46-
toClaimUSD = await readContract(publicClient, {
61+
let amnt = "default amount";
62+
let args: AbiParametersToPrimitiveTypes<
63+
ExtractAbiFunction<typeof faucetAbi, "claim">["inputs"]
64+
>;
65+
if (Array.isArray(amount)) {
66+
args = [amount];
67+
amnt = amount
68+
.map(v => {
69+
try {
70+
return sdk.tokensMeta.formatBN(v.token, v.amount, { symbol: true });
71+
} catch {
72+
return `${v.amount} of ${v.token}`;
73+
}
74+
})
75+
.join(", ");
76+
} else if (typeof amount === "bigint") {
77+
args = [amount];
78+
amnt = `${formatBN(args[0], 8)} USD`;
79+
} else if (typeof amount === "function") {
80+
const minAmountUSD = await readContract(publicClient, {
4781
address: faucet,
4882
abi: faucetAbi,
4983
functionName: "minAmountUSD",
5084
});
51-
logger?.debug(`faucet min amount USD: ${toClaimUSD}`);
52-
toClaimUSD = amountUSD(toClaimUSD);
85+
logger?.debug(`faucet min amount USD: ${minAmountUSD}`);
86+
args = [amount(minAmountUSD)];
87+
amnt = `${formatBN(args[0], 8)} USD`;
88+
} else {
89+
args = [];
5390
}
5491

55-
if (toClaimUSD === 0n) {
92+
if (args[0] === 0n) {
5693
logger?.debug("amount is 0, skipping claim");
5794
return;
5895
}
5996

60-
const [usr, amnt] = [
61-
[role, claimer.address].filter(Boolean).join(" "),
62-
toClaimUSD ? formatBN(toClaimUSD, 8) : "default amount",
63-
];
97+
const usr = [role, claimer.address].filter(Boolean).join(" ");
6498

65-
logger?.debug(`${usr} claiming ${amnt} USD from faucet`);
99+
logger?.debug(`${usr} claiming ${amnt} from faucet`);
66100

67101
const gas = await publicClient.estimateContractGas({
68102
account: claimer,
69103
address: faucet,
70104
abi: faucetAbi,
71105
functionName: "claim",
72-
args: toClaimUSD ? [toClaimUSD] : [],
106+
args,
73107
});
74108
const hash = await wallet.writeContract({
75109
account: claimer,
76110
address: faucet,
77111
abi: faucetAbi,
78112
functionName: "claim",
79-
args: toClaimUSD ? [toClaimUSD] : [],
113+
args,
80114
chain: wallet.chain,
81115
gas: gas * gasMultiplier,
82116
});
@@ -85,10 +119,8 @@ export async function claimFromFaucet(
85119
});
86120
if (receipt.status === "reverted") {
87121
throw new Error(
88-
`${usr} failed to claimed equivalent of ${amnt} USD from faucet, tx: ${hash}`,
122+
`${usr} failed to claimed ${amnt} from faucet, tx: ${hash}`,
89123
);
90124
}
91-
logger?.debug(
92-
`${usr} claimed equivalent of ${amnt} USD from faucet, tx: ${hash}`,
93-
);
125+
logger?.debug(`${usr} claimed ${amnt} from faucet, tx: ${hash}`);
94126
}

0 commit comments

Comments
 (0)