@agether/sdk 1.1.0 → 1.2.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/dist/cli.js +295 -5
- package/dist/index.d.mts +194 -1
- package/dist/index.d.ts +194 -1
- package/dist/index.js +429 -17
- package/dist/index.mjs +427 -16
- package/package.json +1 -1
- package/dist/cli.d.mts +0 -2
- package/dist/cli.d.ts +0 -19
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.mjs +0 -0
- package/dist/clients/AgentIdentityClient.d.ts +0 -163
- package/dist/clients/AgentIdentityClient.d.ts.map +0 -1
- package/dist/clients/AgentIdentityClient.js +0 -293
- package/dist/clients/AgetherClient.d.ts +0 -101
- package/dist/clients/AgetherClient.d.ts.map +0 -1
- package/dist/clients/AgetherClient.js +0 -272
- package/dist/clients/ScoringClient.d.ts +0 -138
- package/dist/clients/ScoringClient.d.ts.map +0 -1
- package/dist/clients/ScoringClient.js +0 -135
- package/dist/clients/VaultClient.d.ts +0 -62
- package/dist/clients/VaultClient.d.ts.map +0 -1
- package/dist/clients/VaultClient.js +0 -157
- package/dist/clients/WalletClient.d.ts +0 -73
- package/dist/clients/WalletClient.d.ts.map +0 -1
- package/dist/clients/WalletClient.js +0 -174
- package/dist/clients/X402Client.d.ts +0 -61
- package/dist/clients/X402Client.d.ts.map +0 -1
- package/dist/clients/X402Client.js +0 -303
- package/dist/index.d.ts.map +0 -1
- package/dist/types/index.d.ts +0 -220
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/index.js +0 -52
- package/dist/utils/abis.d.ts +0 -21
- package/dist/utils/abis.d.ts.map +0 -1
- package/dist/utils/abis.js +0 -134
- package/dist/utils/config.d.ts +0 -31
- package/dist/utils/config.d.ts.map +0 -1
- package/dist/utils/config.js +0 -117
- package/dist/utils/format.d.ts +0 -44
- package/dist/utils/format.d.ts.map +0 -1
- package/dist/utils/format.js +0 -75
package/dist/cli.js
CHANGED
|
@@ -51,7 +51,7 @@ var init_X402Client = __esm({
|
|
|
51
51
|
"eip155:42161": { name: "USD Coin", version: "2", address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831" },
|
|
52
52
|
"eip155:10": { name: "USD Coin", version: "2", address: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85" }
|
|
53
53
|
};
|
|
54
|
-
X402Client = class {
|
|
54
|
+
X402Client = class _X402Client {
|
|
55
55
|
constructor(config) {
|
|
56
56
|
this.config = config;
|
|
57
57
|
const provider = new import_ethers.ethers.JsonRpcProvider(config.rpcUrl);
|
|
@@ -100,6 +100,9 @@ var init_X402Client = __esm({
|
|
|
100
100
|
console.log(` amount : ${requirements.amount} (atomic)`);
|
|
101
101
|
console.log(` asset : ${requirements.asset}`);
|
|
102
102
|
console.log(` payTo : ${requirements.payTo}`);
|
|
103
|
+
if (this.config.autoDraw && this.config.accountAddress && this.config.morphoCreditAddress) {
|
|
104
|
+
await this.ensureBalance(BigInt(requirements.amount));
|
|
105
|
+
}
|
|
103
106
|
console.log(" [3/4] Signing EIP-3009 transferWithAuthorization\u2026");
|
|
104
107
|
const paymentPayload = await this.buildPaymentPayload(requirements, resource, url);
|
|
105
108
|
const paymentB64 = Buffer.from(JSON.stringify(paymentPayload)).toString("base64");
|
|
@@ -260,6 +263,73 @@ var init_X402Client = __esm({
|
|
|
260
263
|
}
|
|
261
264
|
};
|
|
262
265
|
}
|
|
266
|
+
static {
|
|
267
|
+
// ──────────── Auto-draw (Flow 9) ────────────
|
|
268
|
+
//
|
|
269
|
+
// When autoDraw is enabled and the AgentAccount has insufficient USDC,
|
|
270
|
+
// automatically borrow from Morpho credit line to cover the payment.
|
|
271
|
+
this.MORPHO_DRAW_ABI = [
|
|
272
|
+
"function drawWithCollateral(address collateralToken, uint256 amount)",
|
|
273
|
+
"function getPosition(address account, address collateralToken) view returns (tuple(uint256 collateralAmount, uint256 borrowedAmount, uint256 borrowShares, bool isActive))"
|
|
274
|
+
];
|
|
275
|
+
}
|
|
276
|
+
static {
|
|
277
|
+
this.AGENT_ACCOUNT_EXEC_ABI = [
|
|
278
|
+
"function execute(address target, uint256 value, bytes data) payable returns (bytes)"
|
|
279
|
+
];
|
|
280
|
+
}
|
|
281
|
+
static {
|
|
282
|
+
this.ERC20_BALANCE_ABI = [
|
|
283
|
+
"function balanceOf(address) view returns (uint256)"
|
|
284
|
+
];
|
|
285
|
+
}
|
|
286
|
+
static {
|
|
287
|
+
this.AUTO_DRAW_COLLATERALS = [
|
|
288
|
+
"0x4200000000000000000000000000000000000006",
|
|
289
|
+
// WETH
|
|
290
|
+
"0xc1CBa3fCea344f92D9239c08C0568f6F2F0ee452",
|
|
291
|
+
// wstETH
|
|
292
|
+
"0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22"
|
|
293
|
+
// cbETH
|
|
294
|
+
];
|
|
295
|
+
}
|
|
296
|
+
async ensureBalance(requiredAmount) {
|
|
297
|
+
const accountAddr = this.config.accountAddress;
|
|
298
|
+
const morphoAddr = this.config.morphoCreditAddress;
|
|
299
|
+
const provider = this.wallet.provider;
|
|
300
|
+
const usdcAddr = USDC_DOMAINS["eip155:8453"]?.address || USDC_DOMAINS["eip155:1"].address;
|
|
301
|
+
const usdc = new import_ethers.ethers.Contract(usdcAddr, _X402Client.ERC20_BALANCE_ABI, provider);
|
|
302
|
+
const balance = await usdc.balanceOf(accountAddr);
|
|
303
|
+
const needed = requiredAmount + requiredAmount / 10n;
|
|
304
|
+
if (balance >= needed) return;
|
|
305
|
+
const deficit = needed - balance;
|
|
306
|
+
const minDraw = import_ethers.ethers.parseUnits("10", 6);
|
|
307
|
+
const drawAmount = deficit > minDraw ? deficit : minDraw;
|
|
308
|
+
console.log(` [auto-draw] USDC balance $${import_ethers.ethers.formatUnits(balance, 6)} < needed $${import_ethers.ethers.formatUnits(needed, 6)}`);
|
|
309
|
+
const morpho = new import_ethers.ethers.Contract(morphoAddr, _X402Client.MORPHO_DRAW_ABI, provider);
|
|
310
|
+
let collateralAddr = null;
|
|
311
|
+
for (const addr of _X402Client.AUTO_DRAW_COLLATERALS) {
|
|
312
|
+
try {
|
|
313
|
+
const pos = await morpho.getPosition(accountAddr, addr);
|
|
314
|
+
if (pos.collateralAmount > 0n) {
|
|
315
|
+
collateralAddr = addr;
|
|
316
|
+
break;
|
|
317
|
+
}
|
|
318
|
+
} catch {
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
if (!collateralAddr) {
|
|
323
|
+
throw new Error("autoDraw failed: no collateral deposited in Morpho. Deposit collateral first.");
|
|
324
|
+
}
|
|
325
|
+
const account = new import_ethers.ethers.Contract(accountAddr, _X402Client.AGENT_ACCOUNT_EXEC_ABI, this.wallet);
|
|
326
|
+
const morphoIface = new import_ethers.ethers.Interface(_X402Client.MORPHO_DRAW_ABI);
|
|
327
|
+
const calldata = morphoIface.encodeFunctionData("drawWithCollateral", [collateralAddr, drawAmount]);
|
|
328
|
+
console.log(` [auto-draw] Borrowing $${import_ethers.ethers.formatUnits(drawAmount, 6)} from Morpho...`);
|
|
329
|
+
const tx = await account.execute(morphoAddr, 0, calldata);
|
|
330
|
+
await tx.wait();
|
|
331
|
+
console.log(` [auto-draw] \u2713 Borrowed (tx: ${tx.hash.slice(0, 14)}\u2026)`);
|
|
332
|
+
}
|
|
263
333
|
// ──────────── Risk check via our backend ────────────
|
|
264
334
|
async riskCheck(paymentPayload, reqs) {
|
|
265
335
|
try {
|
|
@@ -1519,6 +1589,186 @@ async function cmdMorphoRepay(amountUsd) {
|
|
|
1519
1589
|
console.error(`\u274C ${decodeError(e)}`);
|
|
1520
1590
|
}
|
|
1521
1591
|
}
|
|
1592
|
+
async function cmdMorphoDepositAndBorrow(amountStr, tokenSymbol, borrowUsd) {
|
|
1593
|
+
const config = requireConfig();
|
|
1594
|
+
console.log(`
|
|
1595
|
+
\u{1F4B0} Deposit ${amountStr} ${tokenSymbol} + Borrow $${borrowUsd} USDC...
|
|
1596
|
+
`);
|
|
1597
|
+
if (config.agentId === "0") {
|
|
1598
|
+
console.error("\u274C Register agent first: agether register");
|
|
1599
|
+
process.exit(1);
|
|
1600
|
+
}
|
|
1601
|
+
const status = await apiGet(config.backendUrl, "/status");
|
|
1602
|
+
const morphoCreditAddr = status.contracts?.morphoCredit;
|
|
1603
|
+
const accountFactoryAddr = status.contracts?.accountFactory;
|
|
1604
|
+
const usdcAddr = status.contracts?.usdc;
|
|
1605
|
+
if (!morphoCreditAddr || !accountFactoryAddr) {
|
|
1606
|
+
console.error("\u274C Contracts not deployed");
|
|
1607
|
+
process.exit(1);
|
|
1608
|
+
}
|
|
1609
|
+
const provider = new import_ethers2.ethers.JsonRpcProvider(config.rpcUrl);
|
|
1610
|
+
const net = await provider.getNetwork();
|
|
1611
|
+
const COLLATERAL_INFO = getCollateralInfo(Number(net.chainId));
|
|
1612
|
+
const tokenInfo = COLLATERAL_INFO[tokenSymbol];
|
|
1613
|
+
if (!tokenInfo) {
|
|
1614
|
+
console.error(`\u274C Unsupported token: ${tokenSymbol}. Supported: ${Object.keys(COLLATERAL_INFO).join(", ")}`);
|
|
1615
|
+
process.exit(1);
|
|
1616
|
+
}
|
|
1617
|
+
const signer = new import_ethers2.ethers.Wallet(config.privateKey, provider);
|
|
1618
|
+
const collateralWei = import_ethers2.ethers.parseUnits(amountStr, tokenInfo.decimals);
|
|
1619
|
+
const borrowWei = import_ethers2.ethers.parseUnits(borrowUsd, 6);
|
|
1620
|
+
const factory = new import_ethers2.ethers.Contract(accountFactoryAddr, ACCOUNT_FACTORY_ABI, signer);
|
|
1621
|
+
const accountAddr = await factory.getAccount(config.agentId);
|
|
1622
|
+
if (accountAddr === import_ethers2.ethers.ZeroAddress) {
|
|
1623
|
+
console.error("\u274C No AgentAccount. Create one first: agether wallet-create");
|
|
1624
|
+
process.exit(1);
|
|
1625
|
+
}
|
|
1626
|
+
console.log(` AgentAccount: ${accountAddr}`);
|
|
1627
|
+
const token = new import_ethers2.ethers.Contract(tokenInfo.address, ERC20_ABI, signer);
|
|
1628
|
+
const balance = await token.balanceOf(signer.address);
|
|
1629
|
+
if (balance < collateralWei) {
|
|
1630
|
+
console.error(`\u274C Insufficient ${tokenSymbol}: have ${import_ethers2.ethers.formatUnits(balance, tokenInfo.decimals)}, need ${amountStr}`);
|
|
1631
|
+
process.exit(1);
|
|
1632
|
+
}
|
|
1633
|
+
try {
|
|
1634
|
+
console.log(`Step 1/4: Approving ${tokenSymbol}...`);
|
|
1635
|
+
const approveTx = await token.approve(morphoCreditAddr, collateralWei);
|
|
1636
|
+
await approveTx.wait();
|
|
1637
|
+
console.log(` \u2713 Approved`);
|
|
1638
|
+
console.log(`Step 2/4: Depositing collateral...`);
|
|
1639
|
+
const signer2 = getFreshSigner(config);
|
|
1640
|
+
const morpho = new import_ethers2.ethers.Contract(morphoCreditAddr, MORPHO_CREDIT_ABI, signer2);
|
|
1641
|
+
const depositTx = await morpho.depositCollateralFor(accountAddr, tokenInfo.address, collateralWei);
|
|
1642
|
+
await depositTx.wait();
|
|
1643
|
+
console.log(` \u2713 Deposited`);
|
|
1644
|
+
console.log(`Step 3/4: Approving credit provider...`);
|
|
1645
|
+
const signer3 = getFreshSigner(config);
|
|
1646
|
+
const account = new import_ethers2.ethers.Contract(accountAddr, [
|
|
1647
|
+
...AGENT_ACCOUNT_ABI,
|
|
1648
|
+
"function approveCreditProvider(address creditProvider)"
|
|
1649
|
+
], signer3);
|
|
1650
|
+
try {
|
|
1651
|
+
const cpTx = await account.approveCreditProvider(morphoCreditAddr);
|
|
1652
|
+
await cpTx.wait();
|
|
1653
|
+
console.log(` \u2713 Approved`);
|
|
1654
|
+
} catch {
|
|
1655
|
+
console.log(` \u2713 Already approved`);
|
|
1656
|
+
}
|
|
1657
|
+
console.log(`Step 4/4: Borrowing $${borrowUsd} USDC...`);
|
|
1658
|
+
const signer4 = getFreshSigner(config);
|
|
1659
|
+
const account4 = new import_ethers2.ethers.Contract(accountAddr, AGENT_ACCOUNT_ABI, signer4);
|
|
1660
|
+
const morphoIface = new import_ethers2.ethers.Interface(MORPHO_CREDIT_ABI);
|
|
1661
|
+
const borrowCalldata = morphoIface.encodeFunctionData("drawWithCollateral", [tokenInfo.address, borrowWei]);
|
|
1662
|
+
const borrowTx = await account4.execute(morphoCreditAddr, 0, borrowCalldata);
|
|
1663
|
+
await waitForTx(borrowTx);
|
|
1664
|
+
const morphoView = new import_ethers2.ethers.Contract(morphoCreditAddr, MORPHO_CREDIT_ABI, provider);
|
|
1665
|
+
const pos = await morphoView.getPosition(accountAddr, tokenInfo.address);
|
|
1666
|
+
const totalDebt = await morphoView.getTotalDebt(accountAddr);
|
|
1667
|
+
const usdc = new import_ethers2.ethers.Contract(usdcAddr, ERC20_ABI, provider);
|
|
1668
|
+
const accUsdcBal = await usdc.balanceOf(accountAddr);
|
|
1669
|
+
console.log(`
|
|
1670
|
+
\u2705 Deposited ${amountStr} ${tokenSymbol} + Borrowed $${borrowUsd}`);
|
|
1671
|
+
console.log(` Deposit TX: ${depositTx.hash}`);
|
|
1672
|
+
console.log(` Borrow TX: ${borrowTx.hash}`);
|
|
1673
|
+
console.log(` Collateral: ${import_ethers2.ethers.formatUnits(pos.collateralAmount, tokenInfo.decimals)} ${tokenSymbol}`);
|
|
1674
|
+
console.log(` Total debt: $${import_ethers2.ethers.formatUnits(totalDebt, 6)}`);
|
|
1675
|
+
console.log(` AgentAccount USDC: $${import_ethers2.ethers.formatUnits(accUsdcBal, 6)}`);
|
|
1676
|
+
console.log(`
|
|
1677
|
+
USDC is in your AgentAccount \u2014 ready for x402 payments`);
|
|
1678
|
+
} catch (e) {
|
|
1679
|
+
console.error(`\u274C ${decodeError(e)}`);
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
async function cmdMorphoSponsor(amountStr, tokenSymbol, targetAgentId, targetAddress, borrowUsd) {
|
|
1683
|
+
const config = requireConfig();
|
|
1684
|
+
const targetDesc = targetAgentId ? `agent #${targetAgentId}` : targetAddress;
|
|
1685
|
+
console.log(`
|
|
1686
|
+
\u{1F91D} Sponsoring ${targetDesc}: ${amountStr} ${tokenSymbol}${borrowUsd ? ` + borrow $${borrowUsd}` : ""}...
|
|
1687
|
+
`);
|
|
1688
|
+
if (!targetAgentId && !targetAddress) {
|
|
1689
|
+
console.error("\u274C Provide --agent-id or --address");
|
|
1690
|
+
process.exit(1);
|
|
1691
|
+
}
|
|
1692
|
+
const status = await apiGet(config.backendUrl, "/status");
|
|
1693
|
+
const morphoCreditAddr = status.contracts?.morphoCredit;
|
|
1694
|
+
const accountFactoryAddr = status.contracts?.accountFactory;
|
|
1695
|
+
if (!morphoCreditAddr || !accountFactoryAddr) {
|
|
1696
|
+
console.error("\u274C Contracts not deployed");
|
|
1697
|
+
process.exit(1);
|
|
1698
|
+
}
|
|
1699
|
+
const provider = new import_ethers2.ethers.JsonRpcProvider(config.rpcUrl);
|
|
1700
|
+
const net = await provider.getNetwork();
|
|
1701
|
+
const COLLATERAL_INFO = getCollateralInfo(Number(net.chainId));
|
|
1702
|
+
const tokenInfo = COLLATERAL_INFO[tokenSymbol];
|
|
1703
|
+
if (!tokenInfo) {
|
|
1704
|
+
console.error(`\u274C Unsupported token: ${tokenSymbol}. Supported: ${Object.keys(COLLATERAL_INFO).join(", ")}`);
|
|
1705
|
+
process.exit(1);
|
|
1706
|
+
}
|
|
1707
|
+
const signer = new import_ethers2.ethers.Wallet(config.privateKey, provider);
|
|
1708
|
+
const collateralWei = import_ethers2.ethers.parseUnits(amountStr, tokenInfo.decimals);
|
|
1709
|
+
let accountAddr;
|
|
1710
|
+
if (targetAddress) {
|
|
1711
|
+
accountAddr = targetAddress;
|
|
1712
|
+
} else {
|
|
1713
|
+
const factory = new import_ethers2.ethers.Contract(accountFactoryAddr, ACCOUNT_FACTORY_ABI, signer);
|
|
1714
|
+
accountAddr = await factory.getAccount(targetAgentId);
|
|
1715
|
+
if (accountAddr === import_ethers2.ethers.ZeroAddress) {
|
|
1716
|
+
console.error(`\u274C No AgentAccount for agent #${targetAgentId}`);
|
|
1717
|
+
process.exit(1);
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
console.log(` Target AgentAccount: ${accountAddr}`);
|
|
1721
|
+
const token = new import_ethers2.ethers.Contract(tokenInfo.address, ERC20_ABI, signer);
|
|
1722
|
+
const balance = await token.balanceOf(signer.address);
|
|
1723
|
+
if (balance < collateralWei) {
|
|
1724
|
+
console.error(`\u274C Insufficient ${tokenSymbol}: have ${import_ethers2.ethers.formatUnits(balance, tokenInfo.decimals)}, need ${amountStr}`);
|
|
1725
|
+
process.exit(1);
|
|
1726
|
+
}
|
|
1727
|
+
try {
|
|
1728
|
+
console.log(`Step 1/2: Approving + Depositing ${tokenSymbol} for target...`);
|
|
1729
|
+
const approveTx = await token.approve(morphoCreditAddr, collateralWei);
|
|
1730
|
+
await approveTx.wait();
|
|
1731
|
+
const signer2 = getFreshSigner(config);
|
|
1732
|
+
const morpho = new import_ethers2.ethers.Contract(morphoCreditAddr, MORPHO_CREDIT_ABI, signer2);
|
|
1733
|
+
const depositTx = await morpho.depositCollateralFor(accountAddr, tokenInfo.address, collateralWei);
|
|
1734
|
+
await depositTx.wait();
|
|
1735
|
+
console.log(` \u2713 Deposited ${amountStr} ${tokenSymbol} for ${targetDesc}`);
|
|
1736
|
+
if (borrowUsd) {
|
|
1737
|
+
console.log(`Step 2/2: Borrowing $${borrowUsd} for target...`);
|
|
1738
|
+
const signer3 = getFreshSigner(config);
|
|
1739
|
+
const account = new import_ethers2.ethers.Contract(accountAddr, [
|
|
1740
|
+
...AGENT_ACCOUNT_ABI,
|
|
1741
|
+
"function approveCreditProvider(address creditProvider)"
|
|
1742
|
+
], signer3);
|
|
1743
|
+
try {
|
|
1744
|
+
const cpTx = await account.approveCreditProvider(morphoCreditAddr);
|
|
1745
|
+
await cpTx.wait();
|
|
1746
|
+
} catch {
|
|
1747
|
+
}
|
|
1748
|
+
const borrowWei = import_ethers2.ethers.parseUnits(borrowUsd, 6);
|
|
1749
|
+
const signer4 = getFreshSigner(config);
|
|
1750
|
+
const account4 = new import_ethers2.ethers.Contract(accountAddr, AGENT_ACCOUNT_ABI, signer4);
|
|
1751
|
+
const morphoIface = new import_ethers2.ethers.Interface(MORPHO_CREDIT_ABI);
|
|
1752
|
+
const calldata = morphoIface.encodeFunctionData("drawWithCollateral", [tokenInfo.address, borrowWei]);
|
|
1753
|
+
try {
|
|
1754
|
+
const borrowTx = await account4.execute(morphoCreditAddr, 0, calldata);
|
|
1755
|
+
await waitForTx(borrowTx);
|
|
1756
|
+
console.log(` \u2713 Borrowed $${borrowUsd} for target (TX: ${borrowTx.hash})`);
|
|
1757
|
+
} catch (e) {
|
|
1758
|
+
console.log(` \u26A0 Borrow failed (you may not own this AgentAccount): ${decodeError(e)}`);
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
const morphoView = new import_ethers2.ethers.Contract(morphoCreditAddr, MORPHO_CREDIT_ABI, provider);
|
|
1762
|
+
const pos = await morphoView.getPosition(accountAddr, tokenInfo.address);
|
|
1763
|
+
console.log(`
|
|
1764
|
+
\u2705 Sponsored ${targetDesc}`);
|
|
1765
|
+
console.log(` Deposit TX: ${depositTx.hash}`);
|
|
1766
|
+
console.log(` Collateral: ${import_ethers2.ethers.formatUnits(pos.collateralAmount, tokenInfo.decimals)} ${tokenSymbol}`);
|
|
1767
|
+
console.log(` Debt: $${import_ethers2.ethers.formatUnits(pos.borrowedAmount, 6)}`);
|
|
1768
|
+
} catch (e) {
|
|
1769
|
+
console.error(`\u274C ${decodeError(e)}`);
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1522
1772
|
async function cmdMorphoStatus() {
|
|
1523
1773
|
const config = requireConfig();
|
|
1524
1774
|
console.log("\n\u{1F4CA} Morpho Credit Status\n");
|
|
@@ -1822,13 +2072,16 @@ async function cmdWalletFund(amount) {
|
|
|
1822
2072
|
console.log(`
|
|
1823
2073
|
\u2705 Funded. Account USDC balance: $${import_ethers2.ethers.formatUnits(newBalance, 6)}`);
|
|
1824
2074
|
}
|
|
1825
|
-
async function cmdX402Call(url, method = "GET", body) {
|
|
2075
|
+
async function cmdX402Call(url, method = "GET", body, autoDraw = false) {
|
|
1826
2076
|
const config = requireConfig();
|
|
1827
2077
|
console.log("\n\u{1F510} x402 Paid API Call\n");
|
|
2078
|
+
if (autoDraw) console.log(" \u26A1 Auto-draw enabled: will borrow from Morpho if USDC insufficient");
|
|
1828
2079
|
let accountAddress;
|
|
2080
|
+
let morphoCreditAddress;
|
|
1829
2081
|
try {
|
|
1830
2082
|
const status = await apiGet(config.backendUrl, "/status");
|
|
1831
2083
|
const factoryAddr = status.contracts?.accountFactory;
|
|
2084
|
+
morphoCreditAddress = status.contracts?.morphoCredit;
|
|
1832
2085
|
if (factoryAddr && config.agentId) {
|
|
1833
2086
|
const provider = new import_ethers2.ethers.JsonRpcProvider(config.rpcUrl);
|
|
1834
2087
|
const factory = new import_ethers2.ethers.Contract(factoryAddr, ACCOUNT_FACTORY_ABI, provider);
|
|
@@ -1846,7 +2099,9 @@ async function cmdX402Call(url, method = "GET", body) {
|
|
|
1846
2099
|
rpcUrl: config.rpcUrl,
|
|
1847
2100
|
backendUrl: config.backendUrl,
|
|
1848
2101
|
agentId: config.agentId,
|
|
1849
|
-
accountAddress
|
|
2102
|
+
accountAddress,
|
|
2103
|
+
autoDraw,
|
|
2104
|
+
morphoCreditAddress
|
|
1850
2105
|
});
|
|
1851
2106
|
console.log(` Wallet: ${new import_ethers2.ethers.Wallet(config.privateKey).address}`);
|
|
1852
2107
|
console.log(`
|
|
@@ -1903,9 +2158,12 @@ COMMANDS (Morpho - 120% collateral, instant approval):
|
|
|
1903
2158
|
morpho-markets List supported Morpho markets
|
|
1904
2159
|
morpho-open --collateral <token> Open Morpho credit line (WETH/wstETH/WBTC)
|
|
1905
2160
|
morpho-deposit --amount <n> --token <t> Deposit collateral (e.g. 0.5 WETH)
|
|
2161
|
+
morpho-deposit-and-borrow --amount <n> --token <t> --borrow <usd> Deposit + borrow in one go
|
|
1906
2162
|
morpho-borrow --amount <usd> Borrow USDC against collateral
|
|
1907
2163
|
morpho-repay --amount <usd> Repay borrowed USDC
|
|
1908
2164
|
morpho-withdraw --amount <n> --token <t> Withdraw collateral to EOA (e.g. 0.05 WETH or "all")
|
|
2165
|
+
morpho-sponsor --amount <n> --token <t> --agent-id <id> [--borrow <usd>] Sponsor another agent
|
|
2166
|
+
morpho-sponsor --amount <n> --token <t> --address <addr> [--borrow <usd>] Sponsor by address
|
|
1909
2167
|
morpho-status Show Morpho credit lines
|
|
1910
2168
|
unified-status Show ALL credit lines (both types)
|
|
1911
2169
|
|
|
@@ -1917,7 +2175,7 @@ COMMANDS (Agent Wallet - Per-agent execution wallet):
|
|
|
1917
2175
|
wallet-repay --amount <usd> Repay credit line from wallet
|
|
1918
2176
|
|
|
1919
2177
|
COMMANDS (x402 - Paid API Calls):
|
|
1920
|
-
x402 <url> [--method GET|POST] [--body <json>] Make a paid API call using credit
|
|
2178
|
+
x402 <url> [--method GET|POST] [--body <json>] [--auto-draw] Make a paid API call using credit
|
|
1921
2179
|
|
|
1922
2180
|
ENVIRONMENT:
|
|
1923
2181
|
AGETHER_RPC_URL RPC endpoint (default: https://mainnet.base.org)
|
|
@@ -2128,7 +2386,39 @@ async function main() {
|
|
|
2128
2386
|
await cmdX402Call(
|
|
2129
2387
|
positional[0],
|
|
2130
2388
|
options.method || "GET",
|
|
2131
|
-
options.body
|
|
2389
|
+
options.body,
|
|
2390
|
+
!!options["auto-draw"]
|
|
2391
|
+
);
|
|
2392
|
+
break;
|
|
2393
|
+
case "morpho-deposit-and-borrow":
|
|
2394
|
+
if (!options.amount || !options.token || !options.borrow) {
|
|
2395
|
+
console.error("\u274C --amount, --token, and --borrow required");
|
|
2396
|
+
console.error(" agether morpho-deposit-and-borrow --amount 0.01 --token WETH --borrow 10");
|
|
2397
|
+
process.exit(1);
|
|
2398
|
+
}
|
|
2399
|
+
await cmdMorphoDepositAndBorrow(
|
|
2400
|
+
options.amount,
|
|
2401
|
+
options.token,
|
|
2402
|
+
options.borrow
|
|
2403
|
+
);
|
|
2404
|
+
break;
|
|
2405
|
+
case "morpho-sponsor":
|
|
2406
|
+
if (!options.amount || !options.token) {
|
|
2407
|
+
console.error("\u274C --amount and --token required, plus --agent-id or --address");
|
|
2408
|
+
console.error(" agether morpho-sponsor --amount 0.01 --token WETH --agent-id 17676");
|
|
2409
|
+
console.error(" agether morpho-sponsor --amount 0.01 --token WETH --address 0x... --borrow 50");
|
|
2410
|
+
process.exit(1);
|
|
2411
|
+
}
|
|
2412
|
+
if (!options["agent-id"] && !options.address) {
|
|
2413
|
+
console.error("\u274C --agent-id or --address required");
|
|
2414
|
+
process.exit(1);
|
|
2415
|
+
}
|
|
2416
|
+
await cmdMorphoSponsor(
|
|
2417
|
+
options.amount,
|
|
2418
|
+
options.token,
|
|
2419
|
+
options["agent-id"],
|
|
2420
|
+
options.address,
|
|
2421
|
+
options.borrow
|
|
2132
2422
|
);
|
|
2133
2423
|
break;
|
|
2134
2424
|
case "help":
|
package/dist/index.d.mts
CHANGED
|
@@ -729,6 +729,10 @@ interface X402Config {
|
|
|
729
729
|
backendUrl: string;
|
|
730
730
|
agentId?: string;
|
|
731
731
|
accountAddress?: string;
|
|
732
|
+
/** Auto-borrow from Morpho credit line when USDC balance is insufficient for payment */
|
|
733
|
+
autoDraw?: boolean;
|
|
734
|
+
/** MorphoCredit contract address (required for autoDraw) */
|
|
735
|
+
morphoCreditAddress?: string;
|
|
732
736
|
}
|
|
733
737
|
interface X402Response<T = unknown> {
|
|
734
738
|
success: boolean;
|
|
@@ -761,9 +765,198 @@ declare class X402Client {
|
|
|
761
765
|
private request;
|
|
762
766
|
private parsePaymentRequired;
|
|
763
767
|
private buildPaymentPayload;
|
|
768
|
+
private static readonly MORPHO_DRAW_ABI;
|
|
769
|
+
private static readonly AGENT_ACCOUNT_EXEC_ABI;
|
|
770
|
+
private static readonly ERC20_BALANCE_ABI;
|
|
771
|
+
private static readonly AUTO_DRAW_COLLATERALS;
|
|
772
|
+
private ensureBalance;
|
|
764
773
|
private riskCheck;
|
|
765
774
|
}
|
|
766
775
|
|
|
776
|
+
/**
|
|
777
|
+
* MorphoCreditClient — SDK client for Morpho-backed overcollateralized credit
|
|
778
|
+
*
|
|
779
|
+
* Covers all 9 flows:
|
|
780
|
+
* 1. Registration (via AgentIdentityClient) + existing 8004 detection
|
|
781
|
+
* 2. Deposit collateral + borrow in one call
|
|
782
|
+
* 3. Deposit collateral only (no borrow)
|
|
783
|
+
* 4. Sponsor agent by agentId + borrow
|
|
784
|
+
* 5. Sponsor agent by agentId, no borrow
|
|
785
|
+
* 6. Sponsor agent by address + borrow
|
|
786
|
+
* 7. Sponsor agent by address, no borrow
|
|
787
|
+
* 8. Borrow against existing collateral (for x402 payments)
|
|
788
|
+
* 9. (Handled by X402Client.autoDraw)
|
|
789
|
+
*/
|
|
790
|
+
interface MorphoCreditConfig {
|
|
791
|
+
/** Private key for signing */
|
|
792
|
+
privateKey: string;
|
|
793
|
+
/** Base RPC URL */
|
|
794
|
+
rpcUrl: string;
|
|
795
|
+
/** Agent's ERC-8004 ID */
|
|
796
|
+
agentId: string | bigint;
|
|
797
|
+
/** Contract addresses */
|
|
798
|
+
contracts: {
|
|
799
|
+
morphoCredit: string;
|
|
800
|
+
accountFactory: string;
|
|
801
|
+
usdc: string;
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
interface CollateralToken {
|
|
805
|
+
symbol: string;
|
|
806
|
+
address: string;
|
|
807
|
+
decimals: number;
|
|
808
|
+
}
|
|
809
|
+
interface MorphoPosition {
|
|
810
|
+
token: string;
|
|
811
|
+
collateralAmount: bigint;
|
|
812
|
+
borrowedAmount: bigint;
|
|
813
|
+
borrowShares: bigint;
|
|
814
|
+
isActive: boolean;
|
|
815
|
+
}
|
|
816
|
+
interface DepositResult {
|
|
817
|
+
tx: string;
|
|
818
|
+
amount: bigint;
|
|
819
|
+
token: string;
|
|
820
|
+
agentAccount: string;
|
|
821
|
+
totalCollateral: bigint;
|
|
822
|
+
}
|
|
823
|
+
interface BorrowResult {
|
|
824
|
+
tx: string;
|
|
825
|
+
amount: bigint;
|
|
826
|
+
agentAccount: string;
|
|
827
|
+
totalDebt: bigint;
|
|
828
|
+
collateralToken: string;
|
|
829
|
+
}
|
|
830
|
+
interface DepositAndBorrowResult {
|
|
831
|
+
depositTx: string;
|
|
832
|
+
borrowTx: string;
|
|
833
|
+
collateral: {
|
|
834
|
+
amount: bigint;
|
|
835
|
+
token: string;
|
|
836
|
+
};
|
|
837
|
+
borrowed: bigint;
|
|
838
|
+
agentAccount: string;
|
|
839
|
+
totalDebt: bigint;
|
|
840
|
+
}
|
|
841
|
+
interface SponsorResult {
|
|
842
|
+
depositTx: string;
|
|
843
|
+
borrowTx?: string;
|
|
844
|
+
targetAccount: string;
|
|
845
|
+
targetAgentId?: string;
|
|
846
|
+
collateral: {
|
|
847
|
+
amount: bigint;
|
|
848
|
+
token: string;
|
|
849
|
+
};
|
|
850
|
+
borrowed?: bigint;
|
|
851
|
+
totalCollateral: bigint;
|
|
852
|
+
totalDebt: bigint;
|
|
853
|
+
}
|
|
854
|
+
interface RepayResult {
|
|
855
|
+
tx: string;
|
|
856
|
+
amount: bigint;
|
|
857
|
+
remainingDebt: bigint;
|
|
858
|
+
}
|
|
859
|
+
interface WithdrawResult {
|
|
860
|
+
tx: string;
|
|
861
|
+
amount: bigint;
|
|
862
|
+
token: string;
|
|
863
|
+
destination: string;
|
|
864
|
+
remainingCollateral: bigint;
|
|
865
|
+
}
|
|
866
|
+
declare class MorphoCreditClient {
|
|
867
|
+
private signer;
|
|
868
|
+
private config;
|
|
869
|
+
private morpho;
|
|
870
|
+
private factory;
|
|
871
|
+
private accountAddress?;
|
|
872
|
+
private collaterals;
|
|
873
|
+
constructor(config: MorphoCreditConfig, collaterals?: Record<string, CollateralToken>);
|
|
874
|
+
private resolveToken;
|
|
875
|
+
/**
|
|
876
|
+
* Get the AgentAccount address for the configured agentId.
|
|
877
|
+
*/
|
|
878
|
+
getAccountAddress(): Promise<string>;
|
|
879
|
+
/**
|
|
880
|
+
* Get the AgentAccount address for any agentId.
|
|
881
|
+
*/
|
|
882
|
+
getAccountForAgent(agentId: string | bigint): Promise<string>;
|
|
883
|
+
private ensureCreditProvider;
|
|
884
|
+
private approveAndDeposit;
|
|
885
|
+
private executeBorrow;
|
|
886
|
+
/**
|
|
887
|
+
* Deposit collateral from EOA into Morpho for own AgentAccount.
|
|
888
|
+
* Does NOT borrow — use `borrow()` or `depositAndBorrow()` for that.
|
|
889
|
+
*
|
|
890
|
+
* @param tokenSymbol - Collateral token (WETH, wstETH, cbETH)
|
|
891
|
+
* @param amount - Human-readable amount (e.g. "0.05")
|
|
892
|
+
*/
|
|
893
|
+
deposit(tokenSymbol: string, amount: string): Promise<DepositResult>;
|
|
894
|
+
/**
|
|
895
|
+
* Deposit collateral AND borrow USDC in a single SDK call.
|
|
896
|
+
* USDC lands in the AgentAccount.
|
|
897
|
+
*
|
|
898
|
+
* @param tokenSymbol - Collateral token (WETH, wstETH, cbETH)
|
|
899
|
+
* @param collateralAmount - Human-readable collateral amount (e.g. "0.05")
|
|
900
|
+
* @param borrowAmount - Human-readable USDC amount to borrow (e.g. "50")
|
|
901
|
+
*/
|
|
902
|
+
depositAndBorrow(tokenSymbol: string, collateralAmount: string, borrowAmount: string): Promise<DepositAndBorrowResult>;
|
|
903
|
+
/**
|
|
904
|
+
* Borrow USDC against already-deposited collateral.
|
|
905
|
+
* Auto-detects which collateral token has a position.
|
|
906
|
+
* USDC lands in AgentAccount — ready for x402 payments.
|
|
907
|
+
*
|
|
908
|
+
* @param amount - Human-readable USDC amount (e.g. "100")
|
|
909
|
+
*/
|
|
910
|
+
borrow(amount: string): Promise<BorrowResult>;
|
|
911
|
+
/**
|
|
912
|
+
* Deposit collateral for another agent. Caller pays from their wallet.
|
|
913
|
+
* Optionally borrow USDC for the agent (only works if caller owns the AgentAccount).
|
|
914
|
+
*
|
|
915
|
+
* Supports both agentId lookup and direct address.
|
|
916
|
+
*
|
|
917
|
+
* @param target - `{ agentId: "17676" }` or `{ address: "0x..." }`
|
|
918
|
+
* @param tokenSymbol - Collateral token
|
|
919
|
+
* @param amount - Human-readable collateral amount
|
|
920
|
+
* @param borrowAmount - Optional: USDC to borrow (only if caller is owner)
|
|
921
|
+
*/
|
|
922
|
+
sponsor(target: {
|
|
923
|
+
agentId: string | bigint;
|
|
924
|
+
} | {
|
|
925
|
+
address: string;
|
|
926
|
+
}, tokenSymbol: string, amount: string, borrowAmount?: string): Promise<SponsorResult>;
|
|
927
|
+
/**
|
|
928
|
+
* Repay borrowed USDC from AgentAccount back to Morpho.
|
|
929
|
+
*
|
|
930
|
+
* @param amount - Human-readable USDC amount (e.g. "50")
|
|
931
|
+
*/
|
|
932
|
+
repay(amount: string): Promise<RepayResult>;
|
|
933
|
+
/**
|
|
934
|
+
* Withdraw collateral from Morpho back to EOA.
|
|
935
|
+
*
|
|
936
|
+
* @param tokenSymbol - Collateral token
|
|
937
|
+
* @param amount - Human-readable amount or "all"
|
|
938
|
+
*/
|
|
939
|
+
withdraw(tokenSymbol: string, amount: string): Promise<WithdrawResult>;
|
|
940
|
+
/**
|
|
941
|
+
* Get position for a specific collateral token.
|
|
942
|
+
*/
|
|
943
|
+
getPosition(tokenSymbol: string): Promise<MorphoPosition>;
|
|
944
|
+
/**
|
|
945
|
+
* Get all active positions across all collateral tokens.
|
|
946
|
+
*/
|
|
947
|
+
getAllPositions(): Promise<MorphoPosition[]>;
|
|
948
|
+
/**
|
|
949
|
+
* Get total debt across all positions.
|
|
950
|
+
*/
|
|
951
|
+
getTotalDebt(): Promise<bigint>;
|
|
952
|
+
/**
|
|
953
|
+
* Get USDC balance in the AgentAccount.
|
|
954
|
+
*/
|
|
955
|
+
getAccountUSDC(): Promise<bigint>;
|
|
956
|
+
/** Get the wallet (signer) address */
|
|
957
|
+
getAddress(): string;
|
|
958
|
+
}
|
|
959
|
+
|
|
767
960
|
/**
|
|
768
961
|
* WalletClient - SDK for AgentAccount (smart wallet) operations (v2)
|
|
769
962
|
*
|
|
@@ -930,4 +1123,4 @@ declare const VALIDATION_REGISTRY_ABI: string[];
|
|
|
930
1123
|
declare const MORPHO_CREDIT_ABI: string[];
|
|
931
1124
|
declare const ERC20_ABI: string[];
|
|
932
1125
|
|
|
933
|
-
export { ACCOUNT_FACTORY_ABI, AGENT_ACCOUNT_ABI, AGENT_REPUTATION_ABI, AgentIdentityClient, type AgentIdentityClientOptions, type AgentReputation, AgetherClient, type AgetherClientOptions, type AgetherConfig, AgetherError, type BayesianScore, CREDIT_PROVIDER_ABI, ChainId, type ContractAddresses, type CreditApplication, type CreditAppliedEvent, type CreditApprovedEvent, type CreditDrawnEvent, type CreditInfo, type CreditLine, CreditNotActiveError, type CreditRejectedEvent, type CreditRepaidEvent, CreditStatus, type DrawRequest, ERC20_ABI, type GraduationStatus, IDENTITY_REGISTRY_ABI, InsufficientCreditError, type LPPosition, LP_VAULT_ABI, type LoanPosition, MORPHO_CREDIT_ABI, type MorphoMarketParams, type PaymentProof, type PaymentRequirements, type ProviderStatus, REPUTATION_CREDIT_ABI, type RepayRequest, type RiskCheckResponse, type RiskFactor, type ScoreExplanation, type ScoredLimitPreview, ScoringClient, type ScoringContext, ScoringRejectedError, type ScoringRequest, type ScoringResult, type TransactionResult, VALIDATION_REGISTRY_ABI, VaultClient, type VaultClientOptions, type VaultStats, WalletClient, type WalletClientConfig, type WalletInfo, X402Client, type X402Config, type X402PaymentRequest, type X402PaymentResult, type X402Response, bpsToRate, createConfig, formatAPR, formatAddress, formatHealthFactor, formatPercent, formatTimestamp, formatUSD, formatUnits, getDefaultConfig, getUSDCAddress, parseUnits, rateToBps };
|
|
1126
|
+
export { ACCOUNT_FACTORY_ABI, AGENT_ACCOUNT_ABI, AGENT_REPUTATION_ABI, AgentIdentityClient, type AgentIdentityClientOptions, type AgentReputation, AgetherClient, type AgetherClientOptions, type AgetherConfig, AgetherError, type BayesianScore, type BorrowResult, CREDIT_PROVIDER_ABI, ChainId, type CollateralToken, type ContractAddresses, type CreditApplication, type CreditAppliedEvent, type CreditApprovedEvent, type CreditDrawnEvent, type CreditInfo, type CreditLine, CreditNotActiveError, type CreditRejectedEvent, type CreditRepaidEvent, CreditStatus, type DepositAndBorrowResult, type DepositResult, type DrawRequest, ERC20_ABI, type GraduationStatus, IDENTITY_REGISTRY_ABI, InsufficientCreditError, type LPPosition, LP_VAULT_ABI, type LoanPosition, MORPHO_CREDIT_ABI, MorphoCreditClient, type MorphoCreditConfig, type MorphoMarketParams, type MorphoPosition, type PaymentProof, type PaymentRequirements, type ProviderStatus, REPUTATION_CREDIT_ABI, type RepayRequest, type RepayResult, type RiskCheckResponse, type RiskFactor, type ScoreExplanation, type ScoredLimitPreview, ScoringClient, type ScoringContext, ScoringRejectedError, type ScoringRequest, type ScoringResult, type SponsorResult, type TransactionResult, VALIDATION_REGISTRY_ABI, VaultClient, type VaultClientOptions, type VaultStats, WalletClient, type WalletClientConfig, type WalletInfo, type WithdrawResult, X402Client, type X402Config, type X402PaymentRequest, type X402PaymentResult, type X402Response, bpsToRate, createConfig, formatAPR, formatAddress, formatHealthFactor, formatPercent, formatTimestamp, formatUSD, formatUnits, getDefaultConfig, getUSDCAddress, parseUnits, rateToBps };
|