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.55 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeSupplyLoanToken = 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");
/**
* Supplies a specified amount of loanToken into a Morpho Blue market on behalf of the connected wallet.
*
* This function:
* 1. Validates input and ensures asset amount is greater than zero.
* 2. Fetches market configuration using the provided marketId.
* 3. Reads the loanToken's decimals and parses the asset amount into atomic units.
* 4. Checks allowance and, if necessary, approves the Morpho Blue contract to spend tokens.
* 5. Prepares the calldata for the `supply` function on the Morpho Blue contract.
* 6. Sends the supply transaction and returns the transaction hash and receipt.
*
* @param walletProvider - Instance of {@link EvmWalletProvider} connected to the user's wallet.
* @param args - Validated input matching {@link SupplySchema}, containing:
* @property {string} assets - Amount of loanToken to supply (as a string in human-readable units).
* @property {string} marketId - Unique market identifier (bytes32 hex string).
*
* @returns A Promise resolving to an object containing:
* @property {string} loanToken - The address of the loan token used.
* @property {string} txHash - The hash of the supply transaction.
* @property {object} receipt - The transaction receipt from the network.
*
* @throws Will throw if:
* - The input `assets` value is zero or invalid.
* - Market configuration cannot be fetched or is invalid.
* - Approve call fails, or allowance check/setting fails.
* - The transaction fails to send or confirm.
*/
const writeSupplyLoanToken = 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: "supply",
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 supplying loan token to Morpho Vault", error);
}
};
exports.writeSupplyLoanToken = writeSupplyLoanToken;