Repay & Withdraw (T4 Vault)
T4 vaults use LP-style collateral (e.g. USDai/USDC) and dual-token debt (e.g. USDC/USDT). Use the NFT API (fetchNft) to get position and vault data. Supports both operate() (token-amount based) and operatePerfect() (share-based).
Helper: calculateColSharesMinMax (withdraw)
For withdraw: based on your initial deposit, pass one token amount if you want to withdraw entirely in that token, or pass both amounts in any desired split. Use depositAndBorrow: false.
Helper: calculatePerfectColAmounts (withdraw)
Pass supply0AmountWei (or supply1AmountWei) only; the other amount is auto-computed from pool proportion. Use depositAndBorrow: false, paybackAndWithdraw: true.
Helper: calculateDebtSharesMinMax (payback)
For payback: based on your initial borrow, pass one token amount if you want to repay entirely in that token, or pass both amounts in any desired split. Use depositAndBorrow: false.
Helper: calculatePerfectDebtAmounts (payback)
Pass borrow0AmountWei (or borrow1AmountWei) only; the other amount is auto-computed from pool proportion. Use paybackAndWithdraw: true.
Repay Debt
- Approve the vault to spend both borrow tokens (e.g. USDC, USDT). Use a 1% buffer for accrued interest:typescript
const approveAmt0 = (repay0Wei * 101n) / 100n; const approveAmt1 = (repay1Wei * 101n) / 100n;
Exact amounts: operate()
For exact token amounts, use calculateColSharesMinMax with depositAndBorrow: false for collateral and calculateDebtSharesMinMax with depositAndBorrow: false for debt, then pass negative amounts:
const nft = await fetchNft(chainId, nftId);
const vault = nft.vault;
const colResult = calculateColSharesMinMax({
vault,
supply0AmountInWei: withdrawCol0Wei.toString(),
supply1AmountInWei: withdrawCol1Wei.toString(),
supplySlippage: SLIPPAGE,
borrowSlippage: 0,
depositAndBorrow: false,
});
const debtResult = calculateDebtSharesMinMax({
vault,
borrow0AmountInWei: repay0Wei.toString(),
borrow1AmountInWei: repay1Wei.toString(),
supplySlippage: 0,
borrowSlippage: SLIPPAGE,
depositAndBorrow: false,
});
// operate() with negative values for repay-and-withdraw
args: [
nftId,
-withdrawCol0Wei,
-withdrawCol1Wei,
BigInt(colResult.sharesWithSlippage),
-repay0Wei,
-repay1Wei,
BigInt(debtResult.sharesWithSlippage),
accountAddress
]Exact amounts: operatePerfect()
Use calculatePerfectColAmounts for collateral shares and token min/max, and calculatePerfectDebtAmounts for debt shares and token min/max:
const colResult = calculatePerfectColAmounts({
vault: nft.vault,
supplySlippage: SLIPPAGE,
depositAndBorrow: false,
paybackAndWithdraw: true,
proportion: "fixed",
supply0AmountWei: withdrawCol0Wei.toString(),
supply1AmountWei: "", // auto-computed from pool proportion
});
const debtResult = calculatePerfectDebtAmounts({
vault: nft.vault,
borrowSlippage: SLIPPAGE,
paybackAndWithdraw: true,
proportion: "fixed",
borrow0AmountWei: repay0Wei.toString(),
borrow1AmountWei: "", // auto-computed from pool proportion
});
const perfectColShares = BigInt(colResult.shares);
const colToken0MinMax = -BigInt(colResult.token0AmtWithSlippage);
const colToken1MinMax = -BigInt(colResult.token1AmtWithSlippage);
const perfectDebtShares = -BigInt(debtResult.shares);
const debtToken0MinMax = -BigInt(debtResult.token0AmtWithSlippage);
const debtToken1MinMax = -BigInt(debtResult.token1AmtWithSlippage);
args: [nftId, perfectColShares, colToken0MinMax, colToken1MinMax, perfectDebtShares, debtToken0MinMax, debtToken1MinMax, accountAddress]Max (close position): operatePerfect()
For full close with operatePerfect(), use minInt for shares and calculatePerfectMaxWithdrawAmounts / calculatePerfectMaxPaybackAmounts for token amounts:
perfectColShares = minIntcolToken0MinMax = -withdrawResult.token0AmtWithSlippagecolToken1MinMax = -withdrawResult.token1AmtWithSlippageperfectDebtShares = minIntdebtToken0MinMax = -paybackResult.token0AmtWithSlippagedebtToken1MinMax = -paybackResult.token1AmtWithSlippage
Examples
Exact amounts with operate():
/**
* Example: Repay borrowed USDC + USDT and withdraw USDai + USDC (exact amounts) using operate().
*
* Flow:
* (1) Fetch NFT, compute colSharesMinMax via calculateColSharesMinMax, debtSharesMinMax via calculateDebtSharesMinMax.
* (2) Approve vault to spend both borrow tokens for repay.
* (3) Call operate() with negative token amounts, colSharesMinMax, debtSharesMinMax.
* Set PRIVATE_KEY and RPC_URL in .env.
*
* Run: pnpm run borrow:t4-withdraw-repay -- --network arbitrum
*/
import { encodeFunctionData, erc20Abi, formatUnits, parseUnits } from "viem";
import { vaultT4Abi } from "../shared/abis/vaultT4Abi.js";
import {
chain,
walletClient,
account,
publicClient,
} from "../shared/config.js";
import { fetchNft } from "../shared/utils/utils.js";
import {
calculateColSharesMinMax,
calculateDebtSharesMinMax,
} from "../shared/utils/dex/shares.js";
const SLIPPAGE = 0.1;
// Set your NFT position ID here
const NFT_ID = "";
// Exact amounts to withdraw (collateral) and repay (debt)
const withdrawCol0Wei = parseUnits("0.1", 18); // USDai
const withdrawCol1Wei = parseUnits("0.1", 6); // USDC
const repay0Wei = parseUnits("0.5", 6); // USDC
const repay1Wei = parseUnits("0.5", 6); // USDT
async function main() {
if (!NFT_ID.trim()) {
console.error("Set NFT_ID in this file");
process.exit(1);
}
const nftId = BigInt(NFT_ID.trim());
const nft = await fetchNft(chain.id, NFT_ID.trim());
const vault = nft.vault;
const vaultAddr = vault.address as `0x${string}`;
const supplyToken0 = vault.supplyToken.token0;
const supplyToken1 = vault.supplyToken.token1;
if (!supplyToken1) throw new Error("T4 vault must have supplyToken.token1");
if (!vault.borrowToken.token1)
throw new Error("T4 vault must have borrowToken.token1");
// calculateColSharesMinMax (withdraw): pass one token if paying all from it, or both in any split
const colResult = calculateColSharesMinMax({
vault,
supply0AmountInWei: withdrawCol0Wei.toString(),
supply1AmountInWei: withdrawCol1Wei.toString(),
borrow0AmountInWei: "",
borrow1AmountInWei: "",
supplySlippage: SLIPPAGE,
borrowSlippage: 0,
depositAndBorrow: false,
});
if (!colResult) throw new Error("calculateColSharesMinMax failed");
// calculateDebtSharesMinMax (payback): pass one token if repaying all from it, or both in any split
const debtResult = calculateDebtSharesMinMax({
vault,
supply0AmountInWei: "",
supply1AmountInWei: "",
borrow0AmountInWei: repay0Wei.toString(),
borrow1AmountInWei: repay1Wei.toString(),
supplySlippage: 0,
borrowSlippage: SLIPPAGE,
depositAndBorrow: false,
});
if (!debtResult) throw new Error("calculateDebtSharesMinMax failed");
const newColToken0 = -withdrawCol0Wei;
const newColToken1 = -withdrawCol1Wei;
const colSharesMinMax = BigInt(colResult.sharesWithSlippage);
const newDebtToken0 = -repay0Wei;
const newDebtToken1 = -repay1Wei;
const debtSharesMinMax = BigInt(debtResult.sharesWithSlippage);
console.log("T4 operate: repay & withdraw (exact amounts, Arbitrum)");
console.log(" Vault:", vaultAddr);
console.log(" NFT ID:", nftId.toString());
console.log(
" Repay:",
formatUnits(repay0Wei, vault.borrowToken.token0.decimals),
vault.borrowToken.token0.symbol,
"+",
formatUnits(repay1Wei, vault.borrowToken.token1.decimals),
vault.borrowToken.token1.symbol,
);
console.log(
" Withdraw col:",
formatUnits(withdrawCol0Wei, supplyToken0.decimals),
supplyToken0.symbol,
"+",
formatUnits(withdrawCol1Wei, supplyToken1.decimals),
supplyToken1.symbol,
);
const approveAmt0 = (repay0Wei * 101n) / 100n;
const approveAmt1 = (repay1Wei * 101n) / 100n;
const approve = async (token: `0x${string}`, amount: bigint) => {
const data = encodeFunctionData({
abi: erc20Abi,
functionName: "approve",
args: [vaultAddr, amount],
});
const hash = await walletClient.sendTransaction({
to: token,
data,
account,
});
await publicClient.waitForTransactionReceipt({ hash });
console.log(" Approve tx:", hash);
};
// Step 1 - Approve both borrow tokens for repay
await approve(vault.borrowToken.token0.address as `0x${string}`, approveAmt0);
await approve(
vault.borrowToken.token1!.address as `0x${string}`,
approveAmt1,
);
// Step 2 - Call operate() to repay and withdraw
const operateData = encodeFunctionData({
abi: vaultT4Abi,
functionName: "operate",
args: [
nftId,
newColToken0,
newColToken1,
colSharesMinMax,
newDebtToken0,
newDebtToken1,
debtSharesMinMax,
account.address,
],
});
const hash = await walletClient.sendTransaction({
to: vaultAddr,
data: operateData,
value: 0n,
account,
});
console.log(" Operate tx:", hash);
console.log("Explorer:", `${chain.blockExplorers?.default?.url}/tx/${hash}`);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
console.error("Operate tx reverted");
process.exit(1);
}
console.log(
"Position updated. USDC + USDT repaid, USDai + USDC withdrawn.",
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});Exact amounts with operatePerfect():
/**
* Example: Repay borrowed USDC + USDT and withdraw USDai + USDC (exact amounts) using operatePerfect().
*
* Flow:
* (1) Fetch NFT, compute collateral via calculatePerfectColAmounts, debt via calculatePerfectDebtAmounts.
* (2) Approve vault to spend both borrow tokens for repay.
* (3) Call operatePerfect() with perfectColShares, colToken0MinMax, colToken1MinMax, perfectDebtShares, debtToken0MinMax, debtToken1MinMax.
* Set PRIVATE_KEY and RPC_URL in .env.
*
* Run: pnpm run borrow:t4-withdraw-repay-perfect -- --network arbitrum
*/
import { encodeFunctionData, erc20Abi, formatUnits, parseUnits } from "viem";
import { vaultT4Abi } from "../shared/abis/vaultT4Abi.js";
import {
chain,
walletClient,
account,
publicClient,
} from "../shared/config.js";
import { fetchNft } from "../shared/utils/utils.js";
import {
calculatePerfectColAmounts,
calculatePerfectDebtAmounts,
} from "../shared/utils/dex/perfectAmounts.js";
const SLIPPAGE = 0.1;
// Set your NFT position ID here
const NFT_ID = "";
// Exact amounts to withdraw (supply) and repay (borrow)
const withdrawCol0Wei = parseUnits("0.2", 18); // USDai
const withdrawCol1Wei = parseUnits("0.5", 6); // USDC
const repay0Wei = parseUnits("0.9", 6); // USDC
const repay1Wei = parseUnits("0.2", 6); // USDT
async function main() {
if (!NFT_ID.trim()) {
console.error("Set NFT_ID in this file");
process.exit(1);
}
const nftId = BigInt(NFT_ID.trim());
const nft = await fetchNft(chain.id, NFT_ID.trim());
const vault = nft.vault;
const vaultAddr = vault.address as `0x${string}`;
const supplyToken0 = vault.supplyToken.token0;
const supplyToken1 = vault.supplyToken.token1;
if (!supplyToken1) throw new Error("T4 vault must have supplyToken.token1");
if (!vault.borrowToken.token1)
throw new Error("T4 vault must have borrowToken.token1");
// calculatePerfectColAmounts: pass only supply0; supply1 auto-computed from pool proportion
const colResult = calculatePerfectColAmounts({
vault: nft.vault,
supplySlippage: SLIPPAGE,
depositAndBorrow: false,
paybackAndWithdraw: true,
proportion: "fixed",
supply0AmountWei: withdrawCol0Wei.toString(),
supply1AmountWei: "",
});
if (!colResult) throw new Error("calculatePerfectColAmounts failed");
// calculatePerfectDebtAmounts: pass only borrow0; borrow1 auto-computed from pool proportion
const debtResult = calculatePerfectDebtAmounts({
vault: nft.vault,
borrowSlippage: SLIPPAGE,
paybackAndWithdraw: true,
proportion: "fixed",
borrow0AmountWei: repay0Wei.toString(),
borrow1AmountWei: "",
});
if (!debtResult) throw new Error("calculatePerfectDebtAmounts failed");
const perfectColShares = BigInt(colResult.shares);
const colToken0MinMax = BigInt(colResult.token0AmtWithSlippage);
const colToken1MinMax = BigInt(colResult.token1AmtWithSlippage);
const perfectDebtShares = BigInt(debtResult.shares);
const debtToken0MinMax = BigInt(debtResult.token0AmtWithSlippage);
const debtToken1MinMax = BigInt(debtResult.token1AmtWithSlippage);
console.log("T4 operatePerfect: repay & withdraw (exact amounts, Arbitrum)");
console.log(" Vault:", vaultAddr);
console.log(" NFT ID:", nftId.toString());
console.log(
" Repay:",
formatUnits(repay0Wei, vault.borrowToken.token0.decimals),
vault.borrowToken.token0.symbol,
"+",
formatUnits(repay1Wei, vault.borrowToken.token1.decimals),
vault.borrowToken.token1.symbol,
);
console.log(
" Withdraw col:",
formatUnits(withdrawCol0Wei, supplyToken0.decimals),
supplyToken0.symbol,
"+",
formatUnits(withdrawCol1Wei, supplyToken1.decimals),
supplyToken1.symbol,
);
const approve = async (token: `0x${string}`, amount: bigint) => {
const data = encodeFunctionData({
abi: erc20Abi,
functionName: "approve",
args: [vaultAddr, amount],
});
const hash = await walletClient.sendTransaction({
to: token,
data,
account,
});
await publicClient.waitForTransactionReceipt({ hash });
console.log(" Approve tx:", hash);
};
// Step 1 - Approve both borrow tokens for repay
await approve(vault.borrowToken.token0.address as `0x${string}`, parseUnits("2", 6));
await approve(
vault.borrowToken.token1!.address as `0x${string}`,
parseUnits("2", 6),
);
// Step 2 - Call operatePerfect() to repay and withdraw
const operateData = encodeFunctionData({
abi: vaultT4Abi,
functionName: "operatePerfect",
args: [
nftId,
perfectColShares,
colToken0MinMax,
colToken1MinMax,
perfectDebtShares,
debtToken0MinMax,
debtToken1MinMax,
account.address,
],
});
const hash = await walletClient.sendTransaction({
to: vaultAddr,
data: operateData,
value: 0n,
account,
});
console.log(" OperatePerfect tx:", hash);
console.log("Explorer:", `${chain.blockExplorers?.default?.url}/tx/${hash}`);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
console.error("OperatePerfect tx reverted");
process.exit(1);
}
console.log(
"Position updated. USDC + USDT repaid, USDai + USDC withdrawn.",
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});Close position (operatePerfect):
/**
* Example: Repay all borrowed USDC + USDT and withdraw all USDai + USDC (close position) using operatePerfect().
*
* Flow:
* (1) Fetch NFT, compute max withdraw via calculatePerfectMaxWithdrawAmounts, max payback via calculatePerfectMaxPaybackAmounts.
* (2) Approve vault to spend both borrow tokens (USDC, USDT) for max repay.
* (3) Call operatePerfect() with minInt for shares to repay max and withdraw max.
* Set PRIVATE_KEY and RPC_URL in .env.
*
* Run: pnpm run borrow:t4-withdraw-repay-max-perfect -- --network arbitrum
*/
import { encodeFunctionData, erc20Abi, formatUnits } from "viem";
import { vaultT4Abi } from "../shared/abis/vaultT4Abi.js";
import {
chain,
walletClient,
account,
publicClient,
} from "../shared/config.js";
import { fetchNft } from "../shared/utils/utils.js";
import {
calculatePerfectMaxWithdrawAmounts,
calculatePerfectMaxPaybackAmounts,
} from "../shared/utils/dex/perfectAmounts.js";
import { minInt } from "../shared/utils/constants.js";
const SLIPPAGE = 0.1;
// Set your NFT position ID here
const NFT_ID = "";
async function main() {
if (!NFT_ID.trim()) {
console.error("Set NFT_ID in this file");
process.exit(1);
}
const nftId = BigInt(NFT_ID.trim());
const nft = await fetchNft(chain.id, NFT_ID.trim());
const vault = nft.vault;
const vaultAddr = vault.address as `0x${string}`;
const supplyToken0 = vault.supplyToken.token0;
const supplyToken1 = vault.supplyToken.token1;
if (!supplyToken1) throw new Error("T4 vault must have supplyToken.token1");
if (!vault.borrowToken.token1)
throw new Error("T4 vault must have borrowToken.token1");
// calculatePerfectMaxWithdrawAmounts: computes max withdraw amounts for full close
const withdrawResult = calculatePerfectMaxWithdrawAmounts({
nft,
supplySlippage: SLIPPAGE,
});
if (!withdrawResult)
throw new Error("calculatePerfectMaxWithdrawAmounts failed");
// calculatePerfectMaxPaybackAmounts: computes max repay amounts for full close
const paybackResult = calculatePerfectMaxPaybackAmounts({
nft,
borrowSlippage: SLIPPAGE,
});
if (!paybackResult)
throw new Error("calculatePerfectMaxPaybackAmounts failed");
const perfectColShares = BigInt(minInt);
const colToken0MinMax = -BigInt(withdrawResult.token0AmtWithSlippage);
const colToken1MinMax = -BigInt(withdrawResult.token1AmtWithSlippage);
const perfectDebtShares = BigInt(minInt);
const debtToken0MinMax = -BigInt(paybackResult.token0AmtWithSlippage);
const debtToken1MinMax = -BigInt(paybackResult.token1AmtWithSlippage);
const repay0Wei = BigInt(paybackResult.token0AmtWithSlippage);
const repay1Wei = BigInt(paybackResult.token1AmtWithSlippage);
const approveAmt0 = (repay0Wei * 101n) / 100n;
const approveAmt1 = (repay1Wei * 101n) / 100n;
console.log("T4 operatePerfect: repay max & withdraw max (Arbitrum)");
console.log(" Vault:", vaultAddr);
console.log(" NFT ID:", nftId.toString());
console.log(
" Repay: ~",
formatUnits(repay0Wei, vault.borrowToken.token0.decimals),
vault.borrowToken.token0.symbol,
"+",
formatUnits(repay1Wei, vault.borrowToken.token1.decimals),
vault.borrowToken.token1.symbol,
);
console.log(
" Withdraw col: ~",
formatUnits(BigInt(withdrawResult.token0Amt), supplyToken0.decimals),
supplyToken0.symbol,
"+",
formatUnits(BigInt(withdrawResult.token1Amt), supplyToken1.decimals),
supplyToken1.symbol,
);
const approve = async (token: `0x${string}`, amount: bigint) => {
const data = encodeFunctionData({
abi: erc20Abi,
functionName: "approve",
args: [vaultAddr, amount],
});
const hash = await walletClient.sendTransaction({
to: token,
data,
account,
});
await publicClient.waitForTransactionReceipt({ hash });
console.log(" Approve tx:", hash);
};
// Step 1 - Approve both borrow tokens for max repay
await approve(
vault.borrowToken.token0.address as `0x${string}`,
approveAmt0,
);
await approve(
vault.borrowToken.token1!.address as `0x${string}`,
approveAmt1,
);
// Step 2 - Call operatePerfect() to repay max and withdraw max
const operateData = encodeFunctionData({
abi: vaultT4Abi,
functionName: "operatePerfect",
args: [
nftId,
perfectColShares,
colToken0MinMax,
colToken1MinMax,
perfectDebtShares,
debtToken0MinMax,
debtToken1MinMax,
account.address,
],
});
const hash = await walletClient.sendTransaction({
to: vaultAddr,
data: operateData,
value: 0n,
account,
});
console.log(" OperatePerfect tx:", hash);
console.log("Explorer:", `${chain.blockExplorers?.default?.url}/tx/${hash}`);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
console.error("OperatePerfect tx reverted");
process.exit(1);
}
console.log(
"Position closed. USDC + USDT repaid, USDai + USDC withdrawn (max).",
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
