Skip to content

Commit 8a2e91a

Browse files
committed
Adds ETH transfer functionality and updates funding logic
Implements sendEther method to enable ETH transactions, ensuring sufficient balance including gas costs. Modifies fundWallet to use the new sendEther method, transferring a reduced amount of ETH. Enhances ETH handling capabilities
1 parent 1071166 commit 8a2e91a

1 file changed

Lines changed: 49 additions & 4 deletions

File tree

services/crypto.service.js

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,53 @@ class CryptoService {
102102
}
103103
}
104104

105+
static async sendEther(walletObject, toAddress, amount) {
106+
try {
107+
// Crear una instancia de wallet a partir del objeto wallet proporcionado
108+
const walletInstance = new ethers.Wallet(
109+
walletObject.privateKey,
110+
this.provider,
111+
);
112+
113+
// Obtener el balance de ETH del remitente
114+
const balance = await this.provider.getBalance(walletInstance.address);
115+
116+
// Formatear la cantidad a enviar (en ETH)
117+
const amountToSend = ethers.utils.parseEther(amount.toString());
118+
119+
// Verificar si hay saldo suficiente (considerando gas aproximado)
120+
const gasPrice = await this.provider.getGasPrice();
121+
const gasLimit = 21000; // Gas límite estándar para transferencias de ETH
122+
const gasCost = gasPrice.mul(gasLimit);
123+
const totalCost = amountToSend.add(gasCost);
124+
125+
if(balance.lt(totalCost)) {
126+
throw new Error(`Saldo insuficiente de ETH`);
127+
}
128+
129+
// Crear la transacción
130+
const transaction = await walletInstance.sendTransaction({
131+
to: toAddress,
132+
value: amountToSend,
133+
gasLimit: gasLimit,
134+
gasPrice: gasPrice,
135+
});
136+
137+
// Esperar a que se confirme la transacción
138+
const receipt = await transaction.wait();
139+
140+
return {
141+
success: true,
142+
hash: transaction.hash,
143+
blockNumber: receipt.blockNumber,
144+
tokenSymbol: 'ETH',
145+
};
146+
} catch(error) {
147+
console.error('Error enviando ETH:', error.message);
148+
throw new Error(`Error enviando ETH: ${ error.message }`);
149+
}
150+
}
151+
105152
static async fundWallet(walletAddress) {
106153

107154
const mxnb = await this.sendToken(
@@ -117,15 +164,13 @@ class CryptoService {
117164

118165
console.log('Transacción MXNB', mxnb);
119166

120-
const eth = await this.sendToken(
167+
const eth = await this.sendEther(
121168
{
122169
privateKey: process.env.BASE_WALLET_PRIVATE_KEY,
123170
address: process.env.BASE_WALLET_ADDRESS,
124171
},
125-
'0x7de5bffc5370d93b974b67bab4492a9e13b8b3c1',
126172
walletAddress,
127-
0.03,
128-
18,
173+
0.01,
129174
);
130175

131176
console.log('Transacción SETH', eth);

0 commit comments

Comments
 (0)