tensaikit
Version:
An autonomous DeFi AI Agent Kit on Katana enabling AI agents to plan and execute on-chain financial operations.
94 lines (93 loc) • 4.52 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeRepayLoan = void 0;
const constants_1 = require("../../erc20/constants");
const errors_1 = require("../../../common/errors");
const fetchMarketConfigFromContract_1 = require("./fetchMarketConfigFromContract");
const decimal_js_1 = __importDefault(require("decimal.js"));
const viem_1 = require("viem");
const utils_1 = require("../../../utils");
const morphoBlueABI_1 = require("../abi/morphoBlueABI");
/**
* Repays a specified amount of loanToken to a Morpho Blue market on behalf of the connected wallet.
*
* This function:
* 1. Validates that the input amount is a positive number.
* 2. Fetches the market configuration from the Morpho Blue contract using the given `marketId`.
* 3. Determines the loan token's decimals and parses the human-readable amount into atomic units.
* 4. Checks and ensures sufficient allowance; triggers approval if required.
* 5. Encodes the `repay` call and sends the transaction to the Morpho Blue contract.
* 6. Waits for the transaction to be confirmed and returns the result.
*
* @param walletProvider - Instance of {@link EvmWalletProvider} connected to the user's wallet.
* @param args - Object matching {@link RepaySchema}, containing:
* @property {string} assets - Amount of loanToken to repay (as a string in user-readable units).
* @property {string} marketId - Unique bytes32 identifier for the market.
*
* @returns A Promise resolving to an object containing:
* @property {string} loanToken - Address of the loan token being repaid.
* @property {string} txHash - Transaction hash of the repay operation.
* @property {object} receipt - Transaction receipt after successful confirmation.
*
* @throws Will throw an error if:
* - The input amount is invalid or zero.
* - Market configuration is missing or malformed.
* - ERC20 allowance is insufficient and approval fails.
* - Transaction fails to send or confirm on-chain.
*/
const writeRepayLoan = async (walletProvider, args) => {
try {
const assets = new decimal_js_1.default(args.assets);
if (assets.lessThanOrEqualTo(0)) {
throw (0, errors_1.createError)("Error: Assets amount must be greater than 0", errors_1.ErrorCode.INVALID_INPUT);
}
const marketResponse = await (0, fetchMarketConfigFromContract_1.fetchMarketConfigFromContract)(walletProvider, {
marketId: args.marketId,
});
if (!marketResponse) {
throw (0, errors_1.createError)("Invalid market id or missing market information", errors_1.ErrorCode.INVALID_INPUT);
}
const loanToken = marketResponse.loanToken;
const decimals = await walletProvider.readContract({
address: loanToken,
abi: constants_1.abi,
functionName: "decimals",
args: [],
});
const atomicAssets = (0, viem_1.parseUnits)(args.assets, decimals);
const currentAllowance = await (0, utils_1.allowance)(walletProvider, loanToken, marketResponse.morphoBlueContractAddress);
if (currentAllowance < atomicAssets) {
const approvalResult = await (0, utils_1.approve)(walletProvider, loanToken, marketResponse.morphoBlueContractAddress, atomicAssets);
if (approvalResult.startsWith("Error")) {
throw (0, errors_1.createError)(`Error approving Morpho Vault as spender: ${approvalResult}`, errors_1.ErrorCode.CONTRACT_ERROR);
}
else {
console.log(approvalResult);
}
}
const data = (0, viem_1.encodeFunctionData)({
abi: morphoBlueABI_1.MORPHO_BLUE_ABI,
functionName: "repay",
args: [
marketResponse,
atomicAssets,
BigInt(0),
walletProvider.getAddress(),
"0x",
],
});
const txHash = await walletProvider.sendTransaction({
to: marketResponse.morphoBlueContractAddress,
data,
});
const receipt = await walletProvider.waitForTransactionReceipt(txHash);
return { loanToken, txHash, receipt };
}
catch (error) {
throw (0, errors_1.handleError)("Error repaying to Morpho Vault", error);
}
};
exports.writeRepayLoan = writeRepayLoan;