agentwallet-sdk 3.1.0 → 3.1.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.
Files changed (90) hide show
  1. package/README.md +13 -10
  2. package/dist/flash/executor.d.ts +119 -0
  3. package/dist/flash/executor.d.ts.map +1 -0
  4. package/dist/flash/executor.js +195 -0
  5. package/dist/flash/executor.js.map +1 -0
  6. package/dist/flash/index.d.ts +28 -0
  7. package/dist/flash/index.d.ts.map +1 -0
  8. package/dist/flash/index.js +25 -0
  9. package/dist/flash/index.js.map +1 -0
  10. package/dist/flash/scanner.d.ts +133 -0
  11. package/dist/flash/scanner.d.ts.map +1 -0
  12. package/dist/flash/scanner.js +212 -0
  13. package/dist/flash/scanner.js.map +1 -0
  14. package/dist/flash/types.d.ts +136 -0
  15. package/dist/flash/types.d.ts.map +1 -0
  16. package/dist/flash/types.js +23 -0
  17. package/dist/flash/types.js.map +1 -0
  18. package/dist/index.d.ts +12 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +18 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/mev/index.d.ts +4 -0
  23. package/dist/mev/index.d.ts.map +1 -0
  24. package/dist/mev/index.js +4 -0
  25. package/dist/mev/index.js.map +1 -0
  26. package/dist/mev/protection.d.ts +54 -0
  27. package/dist/mev/protection.d.ts.map +1 -0
  28. package/dist/mev/protection.js +185 -0
  29. package/dist/mev/protection.js.map +1 -0
  30. package/dist/mev/risk.d.ts +19 -0
  31. package/dist/mev/risk.d.ts.map +1 -0
  32. package/dist/mev/risk.js +95 -0
  33. package/dist/mev/risk.js.map +1 -0
  34. package/dist/mev/types.d.ts +49 -0
  35. package/dist/mev/types.d.ts.map +1 -0
  36. package/dist/mev/types.js +2 -0
  37. package/dist/mev/types.js.map +1 -0
  38. package/dist/solver/adapter.d.ts +47 -0
  39. package/dist/solver/adapter.d.ts.map +1 -0
  40. package/dist/solver/adapter.js +138 -0
  41. package/dist/solver/adapter.js.map +1 -0
  42. package/dist/solver/analyzer.d.ts +48 -0
  43. package/dist/solver/analyzer.d.ts.map +1 -0
  44. package/dist/solver/analyzer.js +89 -0
  45. package/dist/solver/analyzer.js.map +1 -0
  46. package/dist/solver/builder.d.ts +31 -0
  47. package/dist/solver/builder.d.ts.map +1 -0
  48. package/dist/solver/builder.js +60 -0
  49. package/dist/solver/builder.js.map +1 -0
  50. package/dist/solver/index.d.ts +22 -0
  51. package/dist/solver/index.d.ts.map +1 -0
  52. package/dist/solver/index.js +21 -0
  53. package/dist/solver/index.js.map +1 -0
  54. package/dist/solver/types.d.ts +115 -0
  55. package/dist/solver/types.d.ts.map +1 -0
  56. package/dist/solver/types.js +10 -0
  57. package/dist/solver/types.js.map +1 -0
  58. package/dist/tax/engine.d.ts +131 -0
  59. package/dist/tax/engine.d.ts.map +1 -0
  60. package/dist/tax/engine.js +307 -0
  61. package/dist/tax/engine.js.map +1 -0
  62. package/dist/tax/index.d.ts +9 -0
  63. package/dist/tax/index.d.ts.map +1 -0
  64. package/dist/tax/index.js +8 -0
  65. package/dist/tax/index.js.map +1 -0
  66. package/dist/tax/lots.d.ts +60 -0
  67. package/dist/tax/lots.d.ts.map +1 -0
  68. package/dist/tax/lots.js +129 -0
  69. package/dist/tax/lots.js.map +1 -0
  70. package/dist/tax/types.d.ts +113 -0
  71. package/dist/tax/types.d.ts.map +1 -0
  72. package/dist/tax/types.js +18 -0
  73. package/dist/tax/types.js.map +1 -0
  74. package/dist/yield/index.d.ts +26 -0
  75. package/dist/yield/index.d.ts.map +1 -0
  76. package/dist/yield/index.js +25 -0
  77. package/dist/yield/index.js.map +1 -0
  78. package/dist/yield/rates.d.ts +114 -0
  79. package/dist/yield/rates.d.ts.map +1 -0
  80. package/dist/yield/rates.js +351 -0
  81. package/dist/yield/rates.js.map +1 -0
  82. package/dist/yield/types.d.ts +134 -0
  83. package/dist/yield/types.d.ts.map +1 -0
  84. package/dist/yield/types.js +24 -0
  85. package/dist/yield/types.js.map +1 -0
  86. package/dist/yield/vault.d.ts +112 -0
  87. package/dist/yield/vault.d.ts.map +1 -0
  88. package/dist/yield/vault.js +264 -0
  89. package/dist/yield/vault.js.map +1 -0
  90. package/package.json +2 -2
package/README.md CHANGED
@@ -12,16 +12,19 @@ Agent spent $490 today → 🛑 Next tx queued ($500/day limit hit)
12
12
 
13
13
  ## How We Compare
14
14
 
15
- | | **agentwallet-sdk** | **Coinbase Agentic Wallet** | **MoonPay Agents** |
16
- |---|---|---|---|
17
- | **Custody** | Non-custodial (keys on device) | Semi-custodial (TEE) | Non-custodial (claimed) |
18
- | **Spend Limits** | On-chain (smart contract) | API-enforced | Not documented |
19
- | **Chains** | **17** (Base, ETH, Arb, Polygon + 12 EVM + **Solana**) | Base only | Unclear |
20
- | **Agent Identity** | ERC-8004 + ERC-6551 | None | None |
21
- | **Open Source** | MIT | Partial | Closed |
22
- | **x402 Payments** | Native | Supported | "Compatible" |
23
-
24
- > On-chain spend limits can't be bypassed even if the API layer is compromised. That's the difference between policy and math.
15
+ | | **agentwallet-sdk** | **Coinbase Agentic** | **OKX OnchainOS** | **Binance Agent** | **MoonPay Agents** |
16
+ |---|---|---|---|---|---|
17
+ | **Custody** | Non-custodial (agent holds keys) | Semi-custodial (TEE) | Custodial (exchange) | Custodial (exchange) | Non-custodial (claimed) |
18
+ | **Spend Limits** | On-chain (smart contract) | API-enforced | Not documented | Not documented | Not documented |
19
+ | **Chains** | **17** (16 EVM + Solana) | Base only | 60+ (custodial) | Binance chain | Unclear |
20
+ | **Agent Identity** | ERC-8004 + ERC-6551 | None | None | None | None |
21
+ | **Open Source** | MIT | Partial | Closed | Closed | Closed |
22
+ | **x402 Payments** | Native | Supported | Supported | No | "Compatible" |
23
+ | **Jupiter Swaps** | Yes (Solana) | No | No | No | No |
24
+ | **CCTP Bridging** | 17-chain V2 | No | Partial | No | No |
25
+ | **If exchange goes down** | Agent keeps working | Degraded | Agent stops | Agent stops | Unknown |
26
+
27
+ > On-chain spend limits can't be bypassed even if the API layer is compromised. Exchanges can freeze your agent's account. A non-custodial smart contract can't. That's the difference between policy and math.
25
28
 
26
29
  ## Why Agent Wallet?
27
30
 
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Flash Loan Executor
3
+ *
4
+ * Builds signed transactions for Aave V3 flash loan execution.
5
+ *
6
+ * ⚠️ PRODUCTION NOTICE — REQUIRED BEFORE USE:
7
+ * Flash loans use Aave's callback pattern. Aave calls `executeOperation()` on a
8
+ * receiver contract mid-transaction. This SDK generates the transaction calldata,
9
+ * but you MUST deploy `FlashLoanExecutor.sol` first.
10
+ *
11
+ * Deployment steps:
12
+ * 1. Deploy `src/flash/contracts/FlashLoanExecutor.sol` with the Aave Pool address
13
+ * 2. Fund it with enough gas token for operations
14
+ * 3. Pass the deployed address as `executorContractAddress` in FlashLoanConfig
15
+ *
16
+ * Architecture (approach C — agent-signed transactions):
17
+ * - Agent calls this executor's `buildArbitrageTx()` or `buildLiquidationTx()`
18
+ * - Executor returns a transaction object (to, data, value, gasEstimate)
19
+ * - Agent signs and broadcasts the transaction using their wallet
20
+ * - The deployed FlashLoanExecutor.sol contract handles the Aave callback atomically
21
+ *
22
+ * No private keys are held by this SDK. All signing is performed by the agent's wallet.
23
+ */
24
+ import { ethers } from 'ethers';
25
+ import type { FlashLoanConfig, FlashLoanProvider, ArbitrageOpportunity, LiquidationOpportunity } from './types.js';
26
+ /**
27
+ * Aave V3 Pool — methods needed by the executor.
28
+ * Full ABI: https://github.com/aave/aave-v3-core/blob/master/contracts/interfaces/IPool.sol
29
+ */
30
+ declare const AAVE_POOL_ABI: readonly ["function flashLoanSimple(address receiverAddress, address asset, uint256 amount, bytes calldata params, uint16 referralCode) external", "function liquidationCall(address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken) external"];
31
+ /**
32
+ * FlashLoanExecutor contract ABI (our deployed contract).
33
+ * The contract implements IFlashLoanReceiver and handles the Aave callback.
34
+ * See: src/flash/contracts/FlashLoanExecutor.sol
35
+ */
36
+ declare const FLASH_EXECUTOR_ABI: readonly ["function executeArbitrage(address asset, uint256 amount, address buyDex, address sellDex, bytes calldata buyCalldata, bytes calldata sellCalldata) external", "function executeLiquidation(address collateralAsset, address debtAsset, address user, uint256 debtAmount, address aavePool) external"];
37
+ /**
38
+ * Canonical Aave V3 Pool addresses by chain.
39
+ * Source: https://docs.aave.com/developers/deployed-contracts/v3-mainnet
40
+ */
41
+ declare const AAVE_POOL_ADDRESSES: Record<string, string>;
42
+ /** A built transaction ready for agent signing */
43
+ export interface BuiltTransaction {
44
+ /** Target contract address (Aave Pool or FlashLoanExecutor) */
45
+ to: string;
46
+ /** ABI-encoded calldata */
47
+ data: string;
48
+ /** ETH value to send (0n for token flash loans) */
49
+ value: bigint;
50
+ /** Estimated gas units required */
51
+ gasEstimate: bigint;
52
+ }
53
+ /**
54
+ * Builds flash loan transactions for agent signing.
55
+ *
56
+ * Usage:
57
+ * ```typescript
58
+ * const executor = new FlashLoanExecutor({ chain: 'base', rpcUrl: '...' });
59
+ * const tx = executor.buildArbitrageTx(opportunity, wallet);
60
+ * const receipt = await wallet.sendTransaction(tx);
61
+ * ```
62
+ *
63
+ * ⚠️ Requires a deployed `FlashLoanExecutor.sol` contract (see config).
64
+ */
65
+ export declare class FlashLoanExecutor {
66
+ private readonly config;
67
+ constructor(config: FlashLoanConfig);
68
+ /**
69
+ * Build a flash loan arbitrage transaction.
70
+ *
71
+ * Flow:
72
+ * 1. Encodes arbitrage params (buy/sell DEX calldata) into bytes
73
+ * 2. Wraps in `flashLoanSimple()` call to Aave Pool
74
+ * 3. Aave calls back `FlashLoanExecutor.executeOperation()` on our contract
75
+ * 4. Contract buys on DEX A, sells on DEX B, repays loan + fee
76
+ *
77
+ * @param opportunity - Arbitrage opportunity from the scanner
78
+ * @param wallet - Agent's ethers.Wallet (used only for address; does not sign here)
79
+ * @returns Transaction object ready for wallet.sendTransaction()
80
+ */
81
+ buildArbitrageTx(opportunity: ArbitrageOpportunity, wallet: ethers.Wallet): BuiltTransaction;
82
+ /**
83
+ * Build a flash loan liquidation transaction.
84
+ *
85
+ * Flow:
86
+ * 1. Flash-borrows the borrower's debt token from Aave
87
+ * 2. Calls `liquidationCall()` on Aave with the borrowed funds
88
+ * 3. Receives discounted collateral (5–10% bonus)
89
+ * 4. Swaps collateral back to debt token to repay flash loan
90
+ * 5. Profit = collateral bonus - flash loan fee - gas
91
+ *
92
+ * @param opportunity - Liquidation opportunity from the scanner
93
+ * @param wallet - Agent's ethers.Wallet
94
+ * @returns Transaction object ready for wallet.sendTransaction()
95
+ */
96
+ buildLiquidationTx(opportunity: LiquidationOpportunity, wallet: ethers.Wallet): BuiltTransaction;
97
+ /**
98
+ * Get the canonical Aave V3 Pool address for a chain.
99
+ *
100
+ * @param chain - Chain name (case-insensitive)
101
+ * @returns Pool address, or empty string if chain is not supported
102
+ */
103
+ getAavePoolAddress(chain: string): string;
104
+ /**
105
+ * Estimate the flash loan fee for a given borrow amount.
106
+ *
107
+ * Fee schedule:
108
+ * - Aave V3: 0.09% (9 bps) — configurable by Aave governance
109
+ * - Balancer: 0.00% (0 bps) — free flash loans (gas only)
110
+ * - Uniswap V3: 0.30% (30 bps) — same as the pool's swap fee tier
111
+ *
112
+ * @param amount - Borrow amount in token's native decimals
113
+ * @param provider - Flash loan provider (default: 'aave-v3')
114
+ * @returns Fee amount in the same units as `amount`
115
+ */
116
+ estimateFee(amount: bigint, provider?: FlashLoanProvider): bigint;
117
+ }
118
+ export { AAVE_POOL_ABI, FLASH_EXECUTOR_ABI, AAVE_POOL_ADDRESSES };
119
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../src/flash/executor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAInH;;;GAGG;AACH,QAAA,MAAM,aAAa,4RAGT,CAAC;AAEX;;;;GAIG;AACH,QAAA,MAAM,kBAAkB,kTAGd,CAAC;AAIX;;;GAGG;AACH,QAAA,MAAM,mBAAmB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAK/C,CAAC;AAaF,kDAAkD;AAClD,MAAM,WAAW,gBAAgB;IAC/B,+DAA+D;IAC/D,EAAE,EAAE,MAAM,CAAC;IACX,2BAA2B;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,mDAAmD;IACnD,KAAK,EAAE,MAAM,CAAC;IACd,mCAAmC;IACnC,WAAW,EAAE,MAAM,CAAC;CACrB;AAID;;;;;;;;;;;GAWG;AACH,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkB;gBAE7B,MAAM,EAAE,eAAe;IAInC;;;;;;;;;;;;OAYG;IACH,gBAAgB,CACd,WAAW,EAAE,oBAAoB,EACjC,MAAM,EAAE,MAAM,CAAC,MAAM,GACpB,gBAAgB;IAoCnB;;;;;;;;;;;;;OAaG;IACH,kBAAkB,CAChB,WAAW,EAAE,sBAAsB,EACnC,MAAM,EAAE,MAAM,CAAC,MAAM,GACpB,gBAAgB;IAmCnB;;;;;OAKG;IACH,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM;IAIzC;;;;;;;;;;;OAWG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,GAAE,iBAA6B,GAAG,MAAM;CAY7E;AAGD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Flash Loan Executor
3
+ *
4
+ * Builds signed transactions for Aave V3 flash loan execution.
5
+ *
6
+ * ⚠️ PRODUCTION NOTICE — REQUIRED BEFORE USE:
7
+ * Flash loans use Aave's callback pattern. Aave calls `executeOperation()` on a
8
+ * receiver contract mid-transaction. This SDK generates the transaction calldata,
9
+ * but you MUST deploy `FlashLoanExecutor.sol` first.
10
+ *
11
+ * Deployment steps:
12
+ * 1. Deploy `src/flash/contracts/FlashLoanExecutor.sol` with the Aave Pool address
13
+ * 2. Fund it with enough gas token for operations
14
+ * 3. Pass the deployed address as `executorContractAddress` in FlashLoanConfig
15
+ *
16
+ * Architecture (approach C — agent-signed transactions):
17
+ * - Agent calls this executor's `buildArbitrageTx()` or `buildLiquidationTx()`
18
+ * - Executor returns a transaction object (to, data, value, gasEstimate)
19
+ * - Agent signs and broadcasts the transaction using their wallet
20
+ * - The deployed FlashLoanExecutor.sol contract handles the Aave callback atomically
21
+ *
22
+ * No private keys are held by this SDK. All signing is performed by the agent's wallet.
23
+ */
24
+ import { ethers } from 'ethers';
25
+ // ─── ABIs ─────────────────────────────────────────────────────────────────────
26
+ /**
27
+ * Aave V3 Pool — methods needed by the executor.
28
+ * Full ABI: https://github.com/aave/aave-v3-core/blob/master/contracts/interfaces/IPool.sol
29
+ */
30
+ const AAVE_POOL_ABI = [
31
+ 'function flashLoanSimple(address receiverAddress, address asset, uint256 amount, bytes calldata params, uint16 referralCode) external',
32
+ 'function liquidationCall(address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken) external',
33
+ ];
34
+ /**
35
+ * FlashLoanExecutor contract ABI (our deployed contract).
36
+ * The contract implements IFlashLoanReceiver and handles the Aave callback.
37
+ * See: src/flash/contracts/FlashLoanExecutor.sol
38
+ */
39
+ const FLASH_EXECUTOR_ABI = [
40
+ 'function executeArbitrage(address asset, uint256 amount, address buyDex, address sellDex, bytes calldata buyCalldata, bytes calldata sellCalldata) external',
41
+ 'function executeLiquidation(address collateralAsset, address debtAsset, address user, uint256 debtAmount, address aavePool) external',
42
+ ];
43
+ // ─── Canonical Aave V3 Pool Addresses ─────────────────────────────────────────
44
+ /**
45
+ * Canonical Aave V3 Pool addresses by chain.
46
+ * Source: https://docs.aave.com/developers/deployed-contracts/v3-mainnet
47
+ */
48
+ const AAVE_POOL_ADDRESSES = {
49
+ ethereum: '0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2',
50
+ base: '0xA238Dd80C259a72e81d7e4664a9801593F98d1c5',
51
+ arbitrum: '0x794a61358D6845594F94dc1DB02A252b5b4814aD',
52
+ optimism: '0x794a61358D6845594F94dc1DB02A252b5b4814aD',
53
+ };
54
+ /** Default gas limit for flash loan arbitrage transactions */
55
+ const DEFAULT_ARB_GAS_ESTIMATE = 500000n;
56
+ /** Default gas limit for flash loan liquidation transactions */
57
+ const DEFAULT_LIQ_GAS_ESTIMATE = 400000n;
58
+ /** Aave V3 referral code (0 = no referral) */
59
+ const AAVE_REFERRAL_CODE = 0;
60
+ // ─── FlashLoanExecutor Class ──────────────────────────────────────────────────
61
+ /**
62
+ * Builds flash loan transactions for agent signing.
63
+ *
64
+ * Usage:
65
+ * ```typescript
66
+ * const executor = new FlashLoanExecutor({ chain: 'base', rpcUrl: '...' });
67
+ * const tx = executor.buildArbitrageTx(opportunity, wallet);
68
+ * const receipt = await wallet.sendTransaction(tx);
69
+ * ```
70
+ *
71
+ * ⚠️ Requires a deployed `FlashLoanExecutor.sol` contract (see config).
72
+ */
73
+ export class FlashLoanExecutor {
74
+ constructor(config) {
75
+ this.config = config;
76
+ }
77
+ /**
78
+ * Build a flash loan arbitrage transaction.
79
+ *
80
+ * Flow:
81
+ * 1. Encodes arbitrage params (buy/sell DEX calldata) into bytes
82
+ * 2. Wraps in `flashLoanSimple()` call to Aave Pool
83
+ * 3. Aave calls back `FlashLoanExecutor.executeOperation()` on our contract
84
+ * 4. Contract buys on DEX A, sells on DEX B, repays loan + fee
85
+ *
86
+ * @param opportunity - Arbitrage opportunity from the scanner
87
+ * @param wallet - Agent's ethers.Wallet (used only for address; does not sign here)
88
+ * @returns Transaction object ready for wallet.sendTransaction()
89
+ */
90
+ buildArbitrageTx(opportunity, wallet) {
91
+ const aavePoolAddress = this.getAavePoolAddress(this.config.chain);
92
+ if (!aavePoolAddress) {
93
+ throw new Error(`No Aave V3 Pool address for chain: ${this.config.chain}`);
94
+ }
95
+ const pool = new ethers.Interface(AAVE_POOL_ABI);
96
+ // Encode the arbitrage strategy params that will be passed through Aave's callback.
97
+ // The FlashLoanExecutor.sol contract decodes these in executeOperation().
98
+ const innerParams = ethers.AbiCoder.defaultAbiCoder().encode(['address', 'address', 'bytes', 'bytes'], [
99
+ opportunity.buyDex, // DEX router to buy from
100
+ opportunity.sellDex, // DEX router to sell to
101
+ '0x', // buy calldata (filled by router in production)
102
+ '0x', // sell calldata (filled by router in production)
103
+ ]);
104
+ const data = pool.encodeFunctionData('flashLoanSimple', [
105
+ this.config.aavePoolAddress ?? wallet.address, // receiverAddress (FlashLoanExecutor.sol)
106
+ opportunity.tokenAddress, // asset to borrow
107
+ opportunity.amount, // amount
108
+ innerParams, // params passed to executeOperation
109
+ AAVE_REFERRAL_CODE,
110
+ ]);
111
+ return {
112
+ to: aavePoolAddress,
113
+ data,
114
+ value: 0n, // Token flash loans never require ETH value
115
+ gasEstimate: DEFAULT_ARB_GAS_ESTIMATE,
116
+ };
117
+ }
118
+ /**
119
+ * Build a flash loan liquidation transaction.
120
+ *
121
+ * Flow:
122
+ * 1. Flash-borrows the borrower's debt token from Aave
123
+ * 2. Calls `liquidationCall()` on Aave with the borrowed funds
124
+ * 3. Receives discounted collateral (5–10% bonus)
125
+ * 4. Swaps collateral back to debt token to repay flash loan
126
+ * 5. Profit = collateral bonus - flash loan fee - gas
127
+ *
128
+ * @param opportunity - Liquidation opportunity from the scanner
129
+ * @param wallet - Agent's ethers.Wallet
130
+ * @returns Transaction object ready for wallet.sendTransaction()
131
+ */
132
+ buildLiquidationTx(opportunity, wallet) {
133
+ const aavePoolAddress = this.getAavePoolAddress(this.config.chain);
134
+ if (!aavePoolAddress) {
135
+ throw new Error(`No Aave V3 Pool address for chain: ${this.config.chain}`);
136
+ }
137
+ const pool = new ethers.Interface(AAVE_POOL_ABI);
138
+ // Encode liquidation params for the callback
139
+ const innerParams = ethers.AbiCoder.defaultAbiCoder().encode(['address', 'address', 'address', 'address'], [
140
+ opportunity.collateralAddress, // collateral to seize
141
+ opportunity.debtAddress, // debt token to repay
142
+ opportunity.borrower, // target borrower
143
+ aavePoolAddress, // Aave Pool for repayment
144
+ ]);
145
+ const data = pool.encodeFunctionData('flashLoanSimple', [
146
+ this.config.aavePoolAddress ?? wallet.address, // receiverAddress (FlashLoanExecutor.sol)
147
+ opportunity.debtAddress, // asset = debt token
148
+ opportunity.debtAmount, // amount = debt to repay
149
+ innerParams,
150
+ AAVE_REFERRAL_CODE,
151
+ ]);
152
+ return {
153
+ to: aavePoolAddress,
154
+ data,
155
+ value: 0n,
156
+ gasEstimate: DEFAULT_LIQ_GAS_ESTIMATE,
157
+ };
158
+ }
159
+ /**
160
+ * Get the canonical Aave V3 Pool address for a chain.
161
+ *
162
+ * @param chain - Chain name (case-insensitive)
163
+ * @returns Pool address, or empty string if chain is not supported
164
+ */
165
+ getAavePoolAddress(chain) {
166
+ return AAVE_POOL_ADDRESSES[chain.toLowerCase()] ?? '';
167
+ }
168
+ /**
169
+ * Estimate the flash loan fee for a given borrow amount.
170
+ *
171
+ * Fee schedule:
172
+ * - Aave V3: 0.09% (9 bps) — configurable by Aave governance
173
+ * - Balancer: 0.00% (0 bps) — free flash loans (gas only)
174
+ * - Uniswap V3: 0.30% (30 bps) — same as the pool's swap fee tier
175
+ *
176
+ * @param amount - Borrow amount in token's native decimals
177
+ * @param provider - Flash loan provider (default: 'aave-v3')
178
+ * @returns Fee amount in the same units as `amount`
179
+ */
180
+ estimateFee(amount, provider = 'aave-v3') {
181
+ switch (provider) {
182
+ case 'aave-v3':
183
+ return (amount * 9n) / 10000n; // 0.09%
184
+ case 'balancer':
185
+ return 0n; // Balancer V2: 0% fee
186
+ case 'uniswap-v3':
187
+ return (amount * 30n) / 10000n; // 0.30% (same as default pool fee)
188
+ default:
189
+ return (amount * 9n) / 10000n;
190
+ }
191
+ }
192
+ }
193
+ // Re-export ABIs for users who want to interact with contracts directly
194
+ export { AAVE_POOL_ABI, FLASH_EXECUTOR_ABI, AAVE_POOL_ADDRESSES };
195
+ //# sourceMappingURL=executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../src/flash/executor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,iFAAiF;AAEjF;;;GAGG;AACH,MAAM,aAAa,GAAG;IACpB,uIAAuI;IACvI,sIAAsI;CAC9H,CAAC;AAEX;;;;GAIG;AACH,MAAM,kBAAkB,GAAG;IACzB,6JAA6J;IAC7J,sIAAsI;CAC9H,CAAC;AAEX,iFAAiF;AAEjF;;;GAGG;AACH,MAAM,mBAAmB,GAA2B;IAClD,QAAQ,EAAE,4CAA4C;IACtD,IAAI,EAAM,4CAA4C;IACtD,QAAQ,EAAE,4CAA4C;IACtD,QAAQ,EAAE,4CAA4C;CACvD,CAAC;AAEF,8DAA8D;AAC9D,MAAM,wBAAwB,GAAG,OAAQ,CAAC;AAE1C,gEAAgE;AAChE,MAAM,wBAAwB,GAAG,OAAQ,CAAC;AAE1C,8CAA8C;AAC9C,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAgB7B,iFAAiF;AAEjF;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,iBAAiB;IAG5B,YAAY,MAAuB;QACjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,gBAAgB,CACd,WAAiC,EACjC,MAAqB;QAErB,MAAM,eAAe,GAAG,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACnE,IAAI,CAAC,eAAe,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,sCAAsC,IAAI,CAAC,MAAM,CAAC,KAAK,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AAC;CACF;AAED,wEAAwE;AACxE,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,CAAC"}
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Flash Loan Module — Public API
3
+ *
4
+ * Exports the scanner (opportunity detection) and executor (transaction building)
5
+ * for Aave V3 flash loans.
6
+ *
7
+ * ⚠️ PRODUCTION NOTICE:
8
+ * Executing flash loans requires a deployed `FlashLoanExecutor.sol` contract.
9
+ * See `src/flash/contracts/FlashLoanExecutor.sol` for the Solidity scaffold.
10
+ *
11
+ * Quick start:
12
+ * ```typescript
13
+ * import { FlashOpportunityScanner, FlashLoanExecutor } from '@agentwallet/sdk/flash';
14
+ *
15
+ * const scanner = new FlashOpportunityScanner();
16
+ * const opportunities = await scanner.scanArbitrage({ tokens: ['WETH'], chain: 'base' });
17
+ *
18
+ * const executor = new FlashLoanExecutor({ chain: 'base', rpcUrl: '...' });
19
+ * const tx = executor.buildArbitrageTx(opportunities[0], wallet);
20
+ * await wallet.sendTransaction(tx);
21
+ * ```
22
+ */
23
+ export { FlashOpportunityScanner } from './scanner.js';
24
+ export type { ScanArbitrageParams, ScanLiquidationsParams } from './scanner.js';
25
+ export { FlashLoanExecutor, AAVE_POOL_ABI, FLASH_EXECUTOR_ABI, AAVE_POOL_ADDRESSES } from './executor.js';
26
+ export type { BuiltTransaction } from './executor.js';
27
+ export type { FlashLoanConfig, FlashLoanResult, FlashOpportunity, ArbitrageOpportunity, LiquidationOpportunity, FlashScanResult, FlashOpportunityType, FlashLoanProvider, } from './types.js';
28
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/flash/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,YAAY,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAEhF,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC1G,YAAY,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEtD,YAAY,EACV,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,oBAAoB,EACpB,sBAAsB,EACtB,eAAe,EACf,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,YAAY,CAAC"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Flash Loan Module — Public API
3
+ *
4
+ * Exports the scanner (opportunity detection) and executor (transaction building)
5
+ * for Aave V3 flash loans.
6
+ *
7
+ * ⚠️ PRODUCTION NOTICE:
8
+ * Executing flash loans requires a deployed `FlashLoanExecutor.sol` contract.
9
+ * See `src/flash/contracts/FlashLoanExecutor.sol` for the Solidity scaffold.
10
+ *
11
+ * Quick start:
12
+ * ```typescript
13
+ * import { FlashOpportunityScanner, FlashLoanExecutor } from '@agentwallet/sdk/flash';
14
+ *
15
+ * const scanner = new FlashOpportunityScanner();
16
+ * const opportunities = await scanner.scanArbitrage({ tokens: ['WETH'], chain: 'base' });
17
+ *
18
+ * const executor = new FlashLoanExecutor({ chain: 'base', rpcUrl: '...' });
19
+ * const tx = executor.buildArbitrageTx(opportunities[0], wallet);
20
+ * await wallet.sendTransaction(tx);
21
+ * ```
22
+ */
23
+ export { FlashOpportunityScanner } from './scanner.js';
24
+ export { FlashLoanExecutor, AAVE_POOL_ABI, FLASH_EXECUTOR_ABI, AAVE_POOL_ADDRESSES } from './executor.js';
25
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/flash/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAGvD,OAAO,EAAE,iBAAiB,EAAE,aAAa,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC"}
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Flash Loan Opportunity Scanner
3
+ *
4
+ * Scans for profitable flash loan opportunities across DEXs and lending protocols.
5
+ *
6
+ * ⚠️ PRODUCTION NOTICE:
7
+ * Real arbitrage scanning requires live DEX price quotes (SmartSwapRouter integration)
8
+ * and Aave borrower tracking (subgraph or event indexing). The methods below implement
9
+ * the full interface and calculation logic — wire in the SmartSwapRouter for live quotes.
10
+ */
11
+ import type { ArbitrageOpportunity, LiquidationOpportunity, FlashScanResult } from './types.js';
12
+ /** Parameters for DEX arbitrage scanning */
13
+ export interface ScanArbitrageParams {
14
+ /** Token addresses or symbols to scan for price discrepancies */
15
+ tokens: string[];
16
+ /** Chain to scan on */
17
+ chain: string;
18
+ /**
19
+ * Notional trade size in USD used to measure price impact.
20
+ * Default: $10,000 — large enough to show real price differences.
21
+ */
22
+ amountUsd?: number;
23
+ /**
24
+ * Minimum net profit in basis points to report an opportunity.
25
+ * Default: 5 bps (0.05%). Filters noise from tiny spreads.
26
+ */
27
+ minNetProfitBps?: number;
28
+ }
29
+ /** Parameters for liquidation scanning */
30
+ export interface ScanLiquidationsParams {
31
+ /** Chain to scan on */
32
+ chain: string;
33
+ /**
34
+ * Known borrower addresses to check for underwater positions.
35
+ * In production, populate this from Aave subgraph or event logs.
36
+ * If empty, returns an empty array.
37
+ */
38
+ borrowers?: string[];
39
+ /**
40
+ * Ethers provider for on-chain calls.
41
+ * If not provided, on-chain health factor checks are skipped.
42
+ */
43
+ provider?: import('ethers').JsonRpcProvider;
44
+ /**
45
+ * Minimum estimated profit (USD) to report a liquidation opportunity.
46
+ * Default: $50
47
+ */
48
+ minProfitUsd?: number;
49
+ }
50
+ /**
51
+ * Scans for flash loan opportunities: DEX arbitrage and protocol liquidations.
52
+ *
53
+ * **DEX Arbitrage**: Compares buy/sell prices across DEX aggregators.
54
+ * A spread exceeding the Aave flash loan fee (0.09%) + gas becomes a
55
+ * profitable arbitrage opportunity.
56
+ *
57
+ * **Liquidations**: Checks known borrowers' health factors on Aave V3.
58
+ * Positions with healthFactor < 1.0 are liquidatable; the liquidator
59
+ * receives a bonus (typically 5–10%) on the seized collateral.
60
+ *
61
+ * ⚠️ PRODUCTION NOTICE:
62
+ * Requires a deployed `FlashLoanExecutor.sol` to actually execute opportunities.
63
+ * See `src/flash/contracts/FlashLoanExecutor.sol`.
64
+ */
65
+ export declare class FlashOpportunityScanner {
66
+ /**
67
+ * Scan for DEX arbitrage opportunities across a token list.
68
+ *
69
+ * Algorithm:
70
+ * 1. For each token, simulate buying $amountUsd on each available DEX aggregator
71
+ * 2. Simulate selling the same amount on each DEX aggregator
72
+ * 3. Compute the spread: (bestSell - bestBuy) / bestBuy * 10000 (bps)
73
+ * 4. Subtract Aave flash loan fee (9 bps) and estimated gas cost
74
+ * 5. Return opportunities where netProfitBps > minNetProfitBps, sorted desc
75
+ *
76
+ * In production, wire `SmartSwapRouter.getQuote()` to fetch real DEX prices.
77
+ * Without live quotes, returns an empty array (no false positives).
78
+ *
79
+ * @param params - Scan configuration
80
+ * @returns Viable arbitrage opportunities sorted by netProfitBps descending
81
+ */
82
+ scanArbitrage(params: ScanArbitrageParams): Promise<ArbitrageOpportunity[]>;
83
+ /**
84
+ * Check for liquidation opportunities on Aave V3.
85
+ *
86
+ * Algorithm:
87
+ * 1. For each known borrower address, call getUserAccountData() on Aave Pool
88
+ * 2. If healthFactor < 1e18 (i.e., < 1.0 in 18-decimal representation) → liquidatable
89
+ * 3. Estimate profit: debtToRepay × liquidationBonus%
90
+ * 4. Return opportunities where estimatedProfitUsd > minProfitUsd
91
+ *
92
+ * ⚠️ PRODUCTION NOTICE:
93
+ * This requires tracking active Aave borrowers via:
94
+ * - Aave subgraph (https://thegraph.com/explorer/subgraphs/...)
95
+ * - Indexing Borrow events from the Aave Pool contract
96
+ * Without a borrower list, returns empty array.
97
+ *
98
+ * @param params - Scan configuration
99
+ * @returns Liquidatable positions sorted by estimatedProfitUsd descending
100
+ */
101
+ scanLiquidations(params: ScanLiquidationsParams): Promise<LiquidationOpportunity[]>;
102
+ /**
103
+ * Run a full scan: both DEX arbitrage and liquidations.
104
+ * Returns a FlashScanResult with the best opportunity highlighted.
105
+ */
106
+ scan(arbitrageParams: ScanArbitrageParams, liquidationParams?: ScanLiquidationsParams): Promise<FlashScanResult>;
107
+ /**
108
+ * Calculate net profit in basis points for an arbitrage opportunity.
109
+ * Public helper used by tests and external callers.
110
+ *
111
+ * @param grossProfitBps - Raw spread between buy and sell price
112
+ * @param flashLoanFeeBps - Flash loan fee (default: 9 for Aave V3)
113
+ * @param gasBps - Estimated gas as % of trade size (default: 10 bps)
114
+ */
115
+ static calcNetProfitBps(grossProfitBps: number, flashLoanFeeBps?: number, gasBps?: number): number;
116
+ /**
117
+ * Build an ArbitrageOpportunity object from raw price data.
118
+ * Useful for testing the scanner logic without live DEX quotes.
119
+ */
120
+ static buildArbitrageOpportunity(params: {
121
+ token: string;
122
+ tokenAddress: string;
123
+ amount: bigint;
124
+ buyDex: string;
125
+ buyPrice: bigint;
126
+ sellDex: string;
127
+ sellPrice: bigint;
128
+ chain: string;
129
+ amountUsd?: number;
130
+ gasBps?: number;
131
+ }): ArbitrageOpportunity;
132
+ }
133
+ //# sourceMappingURL=scanner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner.d.ts","sourceRoot":"","sources":["../../src/flash/scanner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EACV,oBAAoB,EACpB,sBAAsB,EACtB,eAAe,EAEhB,MAAM,YAAY,CAAC;AAqCpB,4CAA4C;AAC5C,MAAM,WAAW,mBAAmB;IAClC,iEAAiE;IACjE,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,uBAAuB;IACvB,KAAK,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAA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