nadcab-labs-crypto-api
Version:
A unified JavaScript library to interact with Ethereum-compatible blockchains and Tron using a simplified API.
86 lines (74 loc) • 2.3 kB
JavaScript
const Web3 = require('web3');
const TronWeb = require('tronweb');
class NC3 {
constructor(chain, providerUrl) {
this.chain = chain.toLowerCase();
if (['ethereum', 'bsc', 'polygon'].includes(this.chain)) {
this.web3 = new Web3(providerUrl); // Initialize Web3 for EVM-compatible chains
} else if (this.chain === 'tron') {
this.tronWeb = new TronWeb({ fullHost: providerUrl }); // Initialize TronWeb for Tron
} else {
throw new Error('Unsupported blockchain');
}
}
// Unified address generation function
generateAddress(privateKey = null) {
switch (this.chain) {
case 'ethereum':
case 'bsc':
case 'polygon':
return this.generateAddressEVM(privateKey);
case 'tron':
return this.generateAddressTron();
default:
throw new Error('Unsupported blockchain.');
}
}
generateAddressEVM(privateKey) {
if (!privateKey) throw new Error('Private key is required for EVM chains');
const account = this.web3.eth.accounts.privateKeyToAccount(privateKey);
return account.address;
}
generateAddressTron() {
return this.tronWeb.createAccount();
}
// Unified function to send transactions
async sendTransaction(txData) {
switch (this.chain) {
case 'ethereum':
case 'bsc':
case 'polygon':
return await this.web3.eth.sendTransaction(txData);
case 'tron':
return await this.tronWeb.trx.sendRawTransaction(txData);
default:
throw new Error('Unsupported blockchain.');
}
}
// Unified function to get balance
async getBalance(address) {
switch (this.chain) {
case 'ethereum':
case 'bsc':
case 'polygon':
return await this.web3.eth.getBalance(address);
case 'tron':
return await this.tronWeb.trx.getBalance(address);
default:
throw new Error('Unsupported blockchain.');
}
}
// Unified function to start webhook server
startWebhookServer(port, callback) {
const app = express();
app.use(bodyParser.json());
app.post('/webhook', (req, res) => {
callback(req.body);
res.sendStatus(200);
});
app.listen(port, () => {
console.log(`Webhook server running on port ${port}`);
});
}
}
module.exports = NC3;