-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathWeb3-JavaScript.js
More file actions
3189 lines (2746 loc) · 105 KB
/
Web3-JavaScript.js
File metadata and controls
3189 lines (2746 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// WEB3 JAVASCRIPT - Comprehensive Frontend/dApp Development Reference - by Richard Rembert
// JavaScript is the essential language for Web3 frontend development, powering dApps,
// wallet integrations, and blockchain user interfaces across all major networks
// ═══════════════════════════════════════════════════════════════════════════════
// 1. SETUP AND ENVIRONMENT
// ═══════════════════════════════════════════════════════════════════════════════
/*
WEB3 JAVASCRIPT DEVELOPMENT SETUP:
1. Node.js and npm/yarn:
- Install Node.js 18+ (LTS recommended)
- Use npm or yarn for package management
- Consider using nvm for Node version management
2. Essential Web3 libraries:
# Core Web3 libraries
npm install web3@latest ethers@^6.0.0
npm install @web3-react/core @web3-react/injected-connector
npm install wagmi viem
# Wallet connectors
npm install @walletconnect/web3-provider
npm install @coinbase/wallet-sdk
npm install @metamask/sdk
# Framework integrations
npm install react react-dom next.js
npm install vue@next nuxt3
npm install svelte @sveltejs/kit
# UI libraries
npm install @rainbow-me/rainbowkit
npm install @chakra-ui/react
npm install tailwindcss
# Utility libraries
npm install axios
npm install lodash
npm install moment
npm install big.js bignumber.js
npm install crypto-js
# Development tools
npm install --save-dev hardhat @nomiclabs/hardhat-ethers
npm install --save-dev @testing-library/react jest
npm install --save-dev eslint prettier
3. Development environment:
# Create new project
npx create-react-app my-dapp
# or
npx create-next-app@latest my-dapp
# or
npm create vue@latest my-dapp
4. Browser extensions for testing:
- MetaMask
- Coinbase Wallet
- WalletConnect
- Rainbow Wallet
5. Testing networks:
- Ethereum Goerli/Sepolia testnet
- Polygon Mumbai testnet
- Arbitrum Goerli
- Optimism Goerli
*/
// ═══════════════════════════════════════════════════════════════════════════════
// 2. CORE WEB3 INTEGRATION
// ═══════════════════════════════════════════════════════════════════════════════
// Web3 Provider Management
class Web3Manager {
constructor() {
this.web3 = null;
this.provider = null;
this.account = null;
this.chainId = null;
this.isConnected = false;
this.listeners = [];
this.init();
}
async init() {
// Check if Web3 is already injected
if (typeof window !== 'undefined' && window.ethereum) {
this.provider = window.ethereum;
await this.setupEventListeners();
// Check if already connected
const accounts = await this.provider.request({ method: 'eth_accounts' });
if (accounts.length > 0) {
this.account = accounts[0];
this.isConnected = true;
this.chainId = await this.provider.request({ method: 'eth_chainId' });
this.notifyListeners('accountsChanged', accounts);
}
}
}
async connectWallet(walletType = 'metamask') {
try {
switch (walletType) {
case 'metamask':
return await this.connectMetaMask();
case 'walletconnect':
return await this.connectWalletConnect();
case 'coinbase':
return await this.connectCoinbase();
default:
throw new Error(`Unsupported wallet type: ${walletType}`);
}
} catch (error) {
console.error('Wallet connection failed:', error);
throw error;
}
}
async connectMetaMask() {
if (!window.ethereum || !window.ethereum.isMetaMask) {
throw new Error('MetaMask not detected');
}
try {
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
this.provider = window.ethereum;
this.account = accounts[0];
this.isConnected = true;
this.chainId = await this.provider.request({ method: 'eth_chainId' });
await this.setupEventListeners();
this.notifyListeners('connected', { account: this.account, chainId: this.chainId });
return {
account: this.account,
chainId: this.chainId,
provider: this.provider
};
} catch (error) {
throw new Error(`MetaMask connection failed: ${error.message}`);
}
}
async connectWalletConnect() {
const WalletConnectProvider = (await import('@walletconnect/web3-provider')).default;
const provider = new WalletConnectProvider({
infuraId: process.env.REACT_APP_INFURA_ID,
rpc: {
1: `https://mainnet.infura.io/v3/${process.env.REACT_APP_INFURA_ID}`,
5: `https://goerli.infura.io/v3/${process.env.REACT_APP_INFURA_ID}`,
}
});
try {
await provider.enable();
this.provider = provider;
this.account = provider.accounts[0];
this.isConnected = true;
this.chainId = provider.chainId;
this.notifyListeners('connected', { account: this.account, chainId: this.chainId });
return {
account: this.account,
chainId: this.chainId,
provider: this.provider
};
} catch (error) {
throw new Error(`WalletConnect connection failed: ${error.message}`);
}
}
async connectCoinbase() {
const { CoinbaseWalletSDK } = await import('@coinbase/wallet-sdk');
const coinbaseWallet = new CoinbaseWalletSDK({
appName: 'My dApp',
appLogoUrl: 'https://example.com/logo.png',
darkMode: false
});
const provider = coinbaseWallet.makeWeb3Provider(
`https://mainnet.infura.io/v3/${process.env.REACT_APP_INFURA_ID}`,
1
);
try {
const accounts = await provider.request({
method: 'eth_requestAccounts'
});
this.provider = provider;
this.account = accounts[0];
this.isConnected = true;
this.chainId = await provider.request({ method: 'eth_chainId' });
this.notifyListeners('connected', { account: this.account, chainId: this.chainId });
return {
account: this.account,
chainId: this.chainId,
provider: this.provider
};
} catch (error) {
throw new Error(`Coinbase Wallet connection failed: ${error.message}`);
}
}
async disconnect() {
if (this.provider && this.provider.disconnect) {
await this.provider.disconnect();
}
this.provider = null;
this.account = null;
this.isConnected = false;
this.chainId = null;
this.notifyListeners('disconnected', {});
}
async setupEventListeners() {
if (!this.provider) return;
this.provider.on('accountsChanged', (accounts) => {
if (accounts.length === 0) {
this.disconnect();
} else {
this.account = accounts[0];
this.notifyListeners('accountsChanged', accounts);
}
});
this.provider.on('chainChanged', (chainId) => {
this.chainId = chainId;
this.notifyListeners('chainChanged', chainId);
});
this.provider.on('disconnect', () => {
this.disconnect();
});
}
async switchNetwork(chainId) {
if (!this.provider) {
throw new Error('No provider connected');
}
try {
await this.provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId }],
});
} catch (switchError) {
// Chain not added, try to add it
if (switchError.code === 4902) {
const networkConfig = this.getNetworkConfig(chainId);
if (networkConfig) {
await this.provider.request({
method: 'wallet_addEthereumChain',
params: [networkConfig],
});
}
} else {
throw switchError;
}
}
}
getNetworkConfig(chainId) {
const networks = {
'0x1': { // Ethereum Mainnet
chainName: 'Ethereum Mainnet',
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
rpcUrls: ['https://mainnet.infura.io/v3/YOUR_INFURA_ID'],
blockExplorerUrls: ['https://etherscan.io/']
},
'0x89': { // Polygon Mainnet
chainName: 'Polygon Mainnet',
nativeCurrency: { name: 'MATIC', symbol: 'MATIC', decimals: 18 },
rpcUrls: ['https://polygon-rpc.com/'],
blockExplorerUrls: ['https://polygonscan.com/']
},
'0xa4b1': { // Arbitrum One
chainName: 'Arbitrum One',
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
rpcUrls: ['https://arb1.arbitrum.io/rpc'],
blockExplorerUrls: ['https://arbiscan.io/']
}
};
return networks[chainId];
}
addListener(callback) {
this.listeners.push(callback);
}
removeListener(callback) {
this.listeners = this.listeners.filter(listener => listener !== callback);
}
notifyListeners(event, data) {
this.listeners.forEach(callback => {
try {
callback(event, data);
} catch (error) {
console.error('Listener error:', error);
}
});
}
getWeb3Instance() {
if (!this.provider) {
throw new Error('No provider connected');
}
if (!this.web3) {
const Web3 = require('web3');
this.web3 = new Web3(this.provider);
}
return this.web3;
}
getEthersProvider() {
if (!this.provider) {
throw new Error('No provider connected');
}
const { ethers } = require('ethers');
return new ethers.providers.Web3Provider(this.provider);
}
}
// Singleton instance
const web3Manager = new Web3Manager();
// ═══════════════════════════════════════════════════════════════════════════════
// 3. SMART CONTRACT INTERACTION
// ═══════════════════════════════════════════════════════════════════════════════
// Contract interaction utilities
class ContractManager {
constructor(web3Manager) {
this.web3Manager = web3Manager;
this.contracts = new Map();
this.abis = new Map();
}
// Register contract ABI
registerContract(name, address, abi) {
this.abis.set(name, { address, abi });
// Create contract instance
const web3 = this.web3Manager.getWeb3Instance();
const contract = new web3.eth.Contract(abi, address);
this.contracts.set(name, contract);
return contract;
}
// Get contract instance
getContract(name) {
if (!this.contracts.has(name)) {
throw new Error(`Contract ${name} not registered`);
}
return this.contracts.get(name);
}
// Call read-only contract method
async callMethod(contractName, methodName, ...args) {
try {
const contract = this.getContract(contractName);
const result = await contract.methods[methodName](...args).call();
return result;
} catch (error) {
console.error(`Error calling ${contractName}.${methodName}:`, error);
throw error;
}
}
// Send transaction to contract
async sendTransaction(contractName, methodName, args = [], options = {}) {
try {
const contract = this.getContract(contractName);
const account = this.web3Manager.account;
if (!account) {
throw new Error('No account connected');
}
const method = contract.methods[methodName](...args);
// Estimate gas
const gasEstimate = await method.estimateGas({ from: account });
const gasPrice = await this.web3Manager.getWeb3Instance().eth.getGasPrice();
const txOptions = {
from: account,
gas: Math.floor(gasEstimate * 1.1), // Add 10% buffer
gasPrice: gasPrice,
...options
};
// Send transaction
const receipt = await method.send(txOptions);
return {
transactionHash: receipt.transactionHash,
blockNumber: receipt.blockNumber,
gasUsed: receipt.gasUsed,
receipt
};
} catch (error) {
console.error(`Error sending transaction to ${contractName}.${methodName}:`, error);
throw error;
}
}
// Listen to contract events
addEventListener(contractName, eventName, callback, filter = {}) {
try {
const contract = this.getContract(contractName);
const eventListener = contract.events[eventName](filter)
.on('data', callback)
.on('error', (error) => {
console.error(`Event listener error for ${contractName}.${eventName}:`, error);
});
return eventListener;
} catch (error) {
console.error(`Error setting up event listener for ${contractName}.${eventName}:`, error);
throw error;
}
}
// Get past events
async getPastEvents(contractName, eventName, filter = {}) {
try {
const contract = this.getContract(contractName);
const events = await contract.getPastEvents(eventName, {
fromBlock: filter.fromBlock || 0,
toBlock: filter.toBlock || 'latest',
filter: filter.filter || {}
});
return events;
} catch (error) {
console.error(`Error getting past events for ${contractName}.${eventName}:`, error);
throw error;
}
}
}
// ERC-20 Token utilities
class ERC20Manager extends ContractManager {
constructor(web3Manager) {
super(web3Manager);
// Standard ERC-20 ABI
this.erc20ABI = [
{
"constant": true,
"inputs": [],
"name": "name",
"outputs": [{"name": "", "type": "string"}],
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "symbol",
"outputs": [{"name": "", "type": "string"}],
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [{"name": "", "type": "uint8"}],
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
},
{
"constant": true,
"inputs": [{"name": "_owner", "type": "address"}],
"name": "balanceOf",
"outputs": [{"name": "balance", "type": "uint256"}],
"type": "function"
},
{
"constant": false,
"inputs": [
{"name": "_to", "type": "address"},
{"name": "_value", "type": "uint256"}
],
"name": "transfer",
"outputs": [{"name": "", "type": "bool"}],
"type": "function"
},
{
"constant": false,
"inputs": [
{"name": "_spender", "type": "address"},
{"name": "_value", "type": "uint256"}
],
"name": "approve",
"outputs": [{"name": "", "type": "bool"}],
"type": "function"
},
{
"constant": true,
"inputs": [
{"name": "_owner", "type": "address"},
{"name": "_spender", "type": "address"}
],
"name": "allowance",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
}
];
}
// Add ERC-20 token
addToken(symbol, address) {
return this.registerContract(`ERC20_${symbol}`, address, this.erc20ABI);
}
// Get token info
async getTokenInfo(symbol) {
const contractName = `ERC20_${symbol}`;
try {
const [name, tokenSymbol, decimals, totalSupply] = await Promise.all([
this.callMethod(contractName, 'name'),
this.callMethod(contractName, 'symbol'),
this.callMethod(contractName, 'decimals'),
this.callMethod(contractName, 'totalSupply')
]);
return {
name,
symbol: tokenSymbol,
decimals: parseInt(decimals),
totalSupply: totalSupply.toString()
};
} catch (error) {
console.error(`Error getting token info for ${symbol}:`, error);
throw error;
}
}
// Get token balance
async getBalance(symbol, address) {
const contractName = `ERC20_${symbol}`;
try {
const balance = await this.callMethod(contractName, 'balanceOf', address);
const decimals = await this.callMethod(contractName, 'decimals');
return {
raw: balance.toString(),
formatted: this.formatTokenAmount(balance, parseInt(decimals))
};
} catch (error) {
console.error(`Error getting balance for ${symbol}:`, error);
throw error;
}
}
// Transfer tokens
async transfer(symbol, to, amount, decimals = 18) {
const contractName = `ERC20_${symbol}`;
const amountWei = this.parseTokenAmount(amount, decimals);
try {
return await this.sendTransaction(contractName, 'transfer', [to, amountWei]);
} catch (error) {
console.error(`Error transferring ${symbol}:`, error);
throw error;
}
}
// Approve tokens
async approve(symbol, spender, amount, decimals = 18) {
const contractName = `ERC20_${symbol}`;
const amountWei = this.parseTokenAmount(amount, decimals);
try {
return await this.sendTransaction(contractName, 'approve', [spender, amountWei]);
} catch (error) {
console.error(`Error approving ${symbol}:`, error);
throw error;
}
}
// Get allowance
async getAllowance(symbol, owner, spender) {
const contractName = `ERC20_${symbol}`;
try {
const allowance = await this.callMethod(contractName, 'allowance', owner, spender);
const decimals = await this.callMethod(contractName, 'decimals');
return {
raw: allowance.toString(),
formatted: this.formatTokenAmount(allowance, parseInt(decimals))
};
} catch (error) {
console.error(`Error getting allowance for ${symbol}:`, error);
throw error;
}
}
// Utility functions
parseTokenAmount(amount, decimals) {
const BigNumber = require('bignumber.js');
return new BigNumber(amount).multipliedBy(new BigNumber(10).pow(decimals)).toString();
}
formatTokenAmount(amount, decimals) {
const BigNumber = require('bignumber.js');
return new BigNumber(amount).dividedBy(new BigNumber(10).pow(decimals)).toString();
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// 4. DEFI PROTOCOL INTEGRATION
// ═══════════════════════════════════════════════════════════════════════════════
// Uniswap V3 integration
class UniswapV3Manager extends ContractManager {
constructor(web3Manager) {
super(web3Manager);
// Uniswap V3 contract addresses (Ethereum mainnet)
this.addresses = {
factory: '0x1F98431c8aD98523631AE4a59f267346ea31F984',
router: '0xE592427A0AEce92De3Edee1F18E0157C05861564',
quoter: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6',
nftManager: '0xC36442b4a4522E871399CD717aBDD847Ab11FE88'
};
// Common token addresses
this.tokens = {
WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
USDC: '0xA0b86a33E6eA0dcdeA23e5B4a73c36e9c5b8a22F',
USDT: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
DAI: '0x6B175474E89094C44Da98b954EedeAC495271d0F'
};
this.initializeContracts();
}
async initializeContracts() {
// Router ABI (simplified)
const routerABI = [
{
"inputs": [
{
"components": [
{"name": "tokenIn", "type": "address"},
{"name": "tokenOut", "type": "address"},
{"name": "fee", "type": "uint24"},
{"name": "recipient", "type": "address"},
{"name": "deadline", "type": "uint256"},
{"name": "amountIn", "type": "uint256"},
{"name": "amountOutMinimum", "type": "uint256"},
{"name": "sqrtPriceLimitX96", "type": "uint160"}
],
"name": "params",
"type": "tuple"
}
],
"name": "exactInputSingle",
"outputs": [{"name": "amountOut", "type": "uint256"}],
"type": "function"
}
];
// Quoter ABI (simplified)
const quoterABI = [
{
"inputs": [
{"name": "tokenIn", "type": "address"},
{"name": "tokenOut", "type": "address"},
{"name": "fee", "type": "uint24"},
{"name": "amountIn", "type": "uint256"},
{"name": "sqrtPriceLimitX96", "type": "uint160"}
],
"name": "quoteExactInputSingle",
"outputs": [{"name": "amountOut", "type": "uint256"}],
"type": "function"
}
];
this.registerContract('UniswapRouter', this.addresses.router, routerABI);
this.registerContract('UniswapQuoter', this.addresses.quoter, quoterABI);
}
// Get quote for token swap
async getQuote(tokenIn, tokenOut, amountIn, fee = 3000) {
try {
const amountOut = await this.callMethod(
'UniswapQuoter',
'quoteExactInputSingle',
tokenIn,
tokenOut,
fee,
amountIn,
0
);
return amountOut.toString();
} catch (error) {
console.error('Error getting Uniswap quote:', error);
throw error;
}
}
// Execute token swap
async swapTokens(tokenIn, tokenOut, amountIn, amountOutMinimum, fee = 3000, deadline = null) {
try {
const account = this.web3Manager.account;
if (!account) {
throw new Error('No account connected');
}
const swapDeadline = deadline || Math.floor(Date.now() / 1000) + 1800; // 30 minutes
const params = {
tokenIn,
tokenOut,
fee,
recipient: account,
deadline: swapDeadline,
amountIn,
amountOutMinimum,
sqrtPriceLimitX96: 0
};
return await this.sendTransaction('UniswapRouter', 'exactInputSingle', [params]);
} catch (error) {
console.error('Error executing Uniswap swap:', error);
throw error;
}
}
}
// Aave lending protocol integration
class AaveManager extends ContractManager {
constructor(web3Manager) {
super(web3Manager);
// Aave V3 contract addresses (Ethereum mainnet)
this.addresses = {
pool: '0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2',
dataProvider: '0x7B4EB56E7CD4b454BA8ff71E4518426369a138a3'
};
this.initializeContracts();
}
async initializeContracts() {
// Simplified Aave Pool ABI
const poolABI = [
{
"inputs": [
{"name": "asset", "type": "address"},
{"name": "amount", "type": "uint256"},
{"name": "onBehalfOf", "type": "address"},
{"name": "referralCode", "type": "uint16"}
],
"name": "supply",
"outputs": [],
"type": "function"
},
{
"inputs": [
{"name": "asset", "type": "address"},
{"name": "amount", "type": "uint256"},
{"name": "to", "type": "address"}
],
"name": "withdraw",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
},
{
"inputs": [
{"name": "asset", "type": "address"},
{"name": "amount", "type": "uint256"},
{"name": "interestRateMode", "type": "uint256"},
{"name": "referralCode", "type": "uint16"},
{"name": "onBehalfOf", "type": "address"}
],
"name": "borrow",
"outputs": [],
"type": "function"
},
{
"inputs": [
{"name": "asset", "type": "address"},
{"name": "amount", "type": "uint256"},
{"name": "rateMode", "type": "uint256"},
{"name": "onBehalfOf", "type": "address"}
],
"name": "repay",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
}
];
this.registerContract('AavePool', this.addresses.pool, poolABI);
}
// Supply tokens to Aave
async supply(asset, amount) {
try {
const account = this.web3Manager.account;
if (!account) {
throw new Error('No account connected');
}
return await this.sendTransaction('AavePool', 'supply', [
asset,
amount,
account,
0 // referral code
]);
} catch (error) {
console.error('Error supplying to Aave:', error);
throw error;
}
}
// Withdraw tokens from Aave
async withdraw(asset, amount) {
try {
const account = this.web3Manager.account;
if (!account) {
throw new Error('No account connected');
}
return await this.sendTransaction('AavePool', 'withdraw', [
asset,
amount,
account
]);
} catch (error) {
console.error('Error withdrawing from Aave:', error);
throw error;
}
}
// Borrow tokens from Aave
async borrow(asset, amount, interestRateMode = 2) {
try {
const account = this.web3Manager.account;
if (!account) {
throw new Error('No account connected');
}
return await this.sendTransaction('AavePool', 'borrow', [
asset,
amount,
interestRateMode, // 1 = stable, 2 = variable
0, // referral code
account
]);
} catch (error) {
console.error('Error borrowing from Aave:', error);
throw error;
}
}
// Repay borrowed tokens
async repay(asset, amount, rateMode = 2) {
try {
const account = this.web3Manager.account;
if (!account) {
throw new Error('No account connected');
}
return await this.sendTransaction('AavePool', 'repay', [
asset,
amount,
rateMode, // 1 = stable, 2 = variable
account
]);
} catch (error) {
console.error('Error repaying to Aave:', error);
throw error;
}
}
}
// Compound protocol integration
class CompoundManager extends ContractManager {
constructor(web3Manager) {
super(web3Manager);
// Compound token addresses (Ethereum mainnet)
this.cTokens = {
cETH: '0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5',
cUSDC: '0x39AA39c021dfbaE8faC545936693aC917d5E7563',
cDAI: '0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643'
};
this.initializeContracts();
}
async initializeContracts() {
// Simplified cToken ABI
const cTokenABI = [
{
"inputs": [],
"name": "mint",
"outputs": [{"name": "", "type": "uint256"}],
"payable": true,
"type": "function"
},
{
"inputs": [{"name": "mintAmount", "type": "uint256"}],
"name": "mint",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
},
{
"inputs": [{"name": "redeemTokens", "type": "uint256"}],
"name": "redeem",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
},
{
"inputs": [{"name": "borrowAmount", "type": "uint256"}],
"name": "borrow",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
},
{
"inputs": [{"name": "repayAmount", "type": "uint256"}],
"name": "repayBorrow",
"outputs": [{"name": "", "type": "uint256"}],
"type": "function"
}
];
// Register all cTokens
Object.entries(this.cTokens).forEach(([symbol, address]) => {
this.registerContract(symbol, address, cTokenABI);
});
}
// Supply tokens to Compound
async supply(cTokenSymbol, amount = null) {
try {
if (cTokenSymbol === 'cETH') {
// ETH supply
return await this.sendTransaction('cETH', 'mint', [], {
value: amount
});
} else {
// ERC-20 token supply
return await this.sendTransaction(cTokenSymbol, 'mint', [amount]);
}
} catch (error) {
console.error('Error supplying to Compound:', error);
throw error;
}
}
// Redeem tokens from Compound
async redeem(cTokenSymbol, cTokenAmount) {
try {
return await this.sendTransaction(cTokenSymbol, 'redeem', [cTokenAmount]);
} catch (error) {
console.error('Error redeeming from Compound:', error);
throw error;
}
}
}