@bronlabs/intents-sdk
Version:
SDK for Intents DeFi smart contracts
101 lines • 3.51 kB
JavaScript
import { ethers } from 'ethers';
import { log } from '../utils.js';
export class EvmNetwork {
constructor(rpcUrl, confirmations = 6) {
this.nativeAssetDecimals = 18;
this.retryDelay = 5000;
this.rpcUrl = rpcUrl;
this.provider = new ethers.JsonRpcProvider(rpcUrl);
this.confirmations = confirmations;
}
async getDecimals(tokenAddress) {
if (tokenAddress === "0x0") {
return this.nativeAssetDecimals;
}
const { result } = await fetch(this.rpcUrl, {
method: 'POST',
body: JSON.stringify({
id: 1,
jsonrpc: "2.0",
method: "eth_call",
params: [
{
to: tokenAddress,
data: "0x313ce567"
},
"latest"
]
})
}).then((res) => res.json());
return parseInt(result, 16);
}
async getTxData(txHash, tokenAddress) {
const currentBlock = await this.provider.getBlockNumber();
const { result: receiptResult } = await fetch(this.rpcUrl, {
method: 'POST',
body: JSON.stringify({
id: 1,
jsonrpc: "2.0",
method: "eth_getTransactionReceipt",
params: [txHash]
})
}).then((res) => res.json());
if (!receiptResult) {
return;
}
const receipt = receiptResult;
const confirmed = (currentBlock - parseInt(receipt.blockNumber, 16)) >= this.confirmations;
log.info(`Confirmations ${txHash}: ${currentBlock - parseInt(receipt.blockNumber, 16)}, confirmed: ${confirmed}`);
if (receipt.status !== '0x1') {
log.warn(`Transaction ${txHash} failed on blockchain: ${JSON.stringify(receipt)}`);
return {
to: "",
token: "",
amount: 0n,
confirmed
};
}
// Native token - ETH
if (tokenAddress === "0x0") {
const { result } = await fetch(this.rpcUrl, {
method: 'POST',
body: JSON.stringify({
id: 1,
jsonrpc: "2.0",
method: "eth_getTransactionByHash",
params: [txHash]
})
}).then((res) => res.json());
if (!result) {
return;
}
const { to, value } = result;
return {
to: to,
token: tokenAddress,
amount: BigInt(value),
confirmed
};
}
// ERC20 token
return {
to: '0x' + receipt.logs[0].topics[2].slice(26),
token: receipt.to,
amount: BigInt(receipt.logs[0].data),
confirmed
};
}
async transfer(privateKey, to, value, tokenAddress) {
const signer = new ethers.Wallet(privateKey, this.provider);
if (tokenAddress === "0x0") {
const { hash } = await signer.sendTransaction({ to, value });
return hash;
}
const tokenContract = new ethers.Contract(tokenAddress, [
'function transfer(address to, uint256 amount) returns (bool)'
], signer);
const { hash } = await tokenContract.transfer(to, value);
return hash;
}
}
//# sourceMappingURL=evm.js.map