@q-dev/q-js-sdk
Version:
Typescript Library to interact with Q System Contracts
72 lines • 2.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Web3Adapter = void 0;
const version_json_1 = require("./version.json");
const ethers_1 = require("ethers");
const unit_converter_1 = require("../utils/unit-converter");
const c = new unit_converter_1.UnitConverter();
class Web3Adapter {
constructor(signerOrProvider) {
this.signerOrProvider = signerOrProvider;
this.ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
this.ZERO_BYTES_32 = '0x0000000000000000000000000000000000000000000000000000000000000000';
this.SDK_VERSION = version_json_1.version;
this.toWei = ethers_1.utils.parseUnits;
this.provider = (signerOrProvider === null || signerOrProvider === void 0 ? void 0 : signerOrProvider._isSigner)
? signerOrProvider.provider
: signerOrProvider;
this.signer = (signerOrProvider === null || signerOrProvider === void 0 ? void 0 : signerOrProvider._isSigner)
? signerOrProvider
: undefined;
}
fromWei(value, unitName) {
return c.toBigNumber(ethers_1.utils.formatUnits(value, unitName)).toFixed();
}
async getDefaultAccount() {
var _a;
return ((_a = this.signer) === null || _a === void 0 ? void 0 : _a.getAddress()) || '';
}
async getBalance(address, convertToQ = true) {
const balance = await this.provider.getBalance(address);
if (!convertToQ)
return balance.toString();
return this.fromWei(balance);
}
async getBalances(addresses, convertToQ = true) {
const getBalanceOperation = async (address) => {
const balance = await this.getBalance(address, convertToQ);
return {
address,
balance,
};
};
return this.forEachAddress(addresses, getBalanceOperation);
}
async forEachAddress(addresses, operation) {
const values = [];
const errors = [];
const robustOperation = async (address, i) => {
var _a;
try {
const value = await operation(address, i);
values[i] = value;
}
catch (error) {
const reason = (_a = error.message) !== null && _a !== void 0 ? _a : error.toString();
errors.push({ address, reason });
}
};
const promises = addresses.map(robustOperation);
await Promise.all(promises);
if (errors.length > 0) {
const msg = errors.map(e => `operation rejected for address ${e.address}: ${e.reason}`).join('\n');
throw new Error(msg);
}
return values;
}
async getBlockNumber() {
return this.provider.getBlockNumber();
}
}
exports.Web3Adapter = Web3Adapter;
//# sourceMappingURL=web3-adapter.js.map