@celo/contractkit
Version:
Celo's ContractKit to interact with Celo network
227 lines • 9.83 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContractKit = exports.newKitFromWeb3 = exports.newKitWithApiKey = exports.newKit = exports.API_KEY_HEADER_KEY = void 0;
const connect_1 = require("@celo/connect");
const wallet_local_1 = require("@celo/wallet-local");
const bignumber_js_1 = require("bignumber.js");
const address_registry_1 = require("./address-registry");
const base_1 = require("./base");
const celo_tokens_1 = require("./celo-tokens");
const contract_cache_1 = require("./contract-cache");
const setupForKits_1 = require("./setupForKits");
const web3_contract_cache_1 = require("./web3-contract-cache");
var setupForKits_2 = require("./setupForKits");
Object.defineProperty(exports, "API_KEY_HEADER_KEY", { enumerable: true, get: function () { return setupForKits_2.API_KEY_HEADER_KEY; } });
/**
* Creates a new instance of `ContractKit` given a nodeUrl
* @param url CeloBlockchain node url
* @param wallet to reuse or add a wallet different than the default (example ledger-wallet)
* @param options to pass to the Web3 HttpProvider constructor
*/
function newKit(url, wallet, options) {
const web3 = (0, setupForKits_1.getWeb3ForKit)(url, options);
return newKitFromWeb3(web3, wallet);
}
exports.newKit = newKit;
/**
* Creates a new instance of `ContractKit` given a nodeUrl and apiKey
* @param url CeloBlockchain node url
* @param apiKey to include in the http request header
* @param wallet to reuse or add a wallet different than the default (example ledger-wallet)
*/
function newKitWithApiKey(url, apiKey, wallet) {
const options = (0, setupForKits_1.setupAPIKey)(apiKey);
return newKit(url, wallet, options);
}
exports.newKitWithApiKey = newKitWithApiKey;
/**
* Creates a new instance of the `ContractKit` with a web3 instance
* @param web3 Web3 instance
*/
function newKitFromWeb3(web3, wallet = new wallet_local_1.LocalWallet()) {
(0, setupForKits_1.ensureCurrentProvider)(web3);
return new ContractKit(new connect_1.Connection(web3, wallet));
}
exports.newKitFromWeb3 = newKitFromWeb3;
/*
* ContractKit provides a convenient interface for All Celo Contracts
*
* @remarks
*
* For most use cases this ContractKit class might be more than you need.
* Consider {@link MiniContractKit} for a scaled down subset of contract Wrappers,
* or {@link Connection} for a lighter package without contract Wrappers
*
* @param connection – an instance of @celo/connect {@link Connection}
*/
class ContractKit {
constructor(connection) {
this.connection = connection;
/** @deprecated no longer needed since gasPrice is available on node rpc */
this.gasPriceSuggestionMultiplier = 5;
this.getHumanReadableNetworkConfig = () => this.getNetworkConfig(true);
this.registry = new address_registry_1.AddressRegistry(connection);
this._web3Contracts = new web3_contract_cache_1.Web3ContractCache(this.registry);
this.contracts = new contract_cache_1.WrapperCache(connection, this._web3Contracts, this.registry);
this.celoTokens = new celo_tokens_1.CeloTokens(this.contracts, this.registry);
}
getWallet() {
return this.connection.wallet;
}
getTotalBalance(address) {
return __awaiter(this, void 0, void 0, function* () {
const lockedCelo = yield this.contracts.getLockedGold();
const lockedBalance = yield lockedCelo.getAccountTotalLockedGold(address);
let pending = new bignumber_js_1.BigNumber(0);
try {
pending = yield lockedCelo.getPendingWithdrawalsTotalValue(address);
}
catch (err) {
// Just means that it's not an account
}
return Object.assign({ lockedCELO: lockedBalance, pending }, (yield this.celoTokens.balancesOf(address)));
});
}
getNetworkConfig(humanReadable = false) {
return __awaiter(this, void 0, void 0, function* () {
const configContracts = [
base_1.CeloContract.Election,
base_1.CeloContract.Governance,
base_1.CeloContract.LockedCelo,
base_1.CeloContract.SortedOracles,
base_1.CeloContract.Reserve,
base_1.CeloContract.Validators,
base_1.CeloContract.FeeCurrencyDirectory,
base_1.CeloContract.EpochManager,
];
const configMethod = (contract) => __awaiter(this, void 0, void 0, function* () {
try {
const eachTokenAddress = yield this.celoTokens.getAddresses();
const addresses = Object.values(eachTokenAddress);
const configContractWrapper = yield this.contracts.getContract(contract);
if (humanReadable && 'getHumanReadableConfig' in configContractWrapper) {
return yield configContractWrapper.getHumanReadableConfig(addresses);
}
else if ('getConfig' in configContractWrapper) {
return yield configContractWrapper.getConfig(addresses);
}
else {
throw new Error('No config endpoint found');
}
}
catch (e) {
return new Error(`Failed to fetch config for contract ${contract}: \n${e}`);
}
});
const configArray = yield Promise.all(configContracts.map(configMethod));
const configMap = {};
configArray.forEach((config, index) => (configMap[configContracts[index]] = config));
return Object.assign({}, configMap);
});
}
/**
* Set an addressed to use to pay for gas fees
* @param address any hexadecimal address
* @dev Throws if supplied address is not a valid hexadecimal address
*/
setFeeCurrency(address) {
if (!this.web3.utils.isAddress(address)) {
throw new Error('Supplied address is not a valid hexadecimal address.');
}
this.connection.defaultFeeCurrency = address;
}
/**
* @returns epoch duration (in seconds)
*/
getEpochSize() {
return __awaiter(this, void 0, void 0, function* () {
const epochManagerWrapper = yield this.contracts.getEpochManager();
return epochManagerWrapper.epochDuration();
});
}
getFirstBlockNumberForEpoch(epochNumber) {
return __awaiter(this, void 0, void 0, function* () {
const epochManagerWrapper = yield this.contracts.getEpochManager();
return yield epochManagerWrapper.getFirstBlockAtEpoch(epochNumber);
});
}
getLastBlockNumberForEpoch(epochNumber) {
return __awaiter(this, void 0, void 0, function* () {
const epochManagerWrapper = yield this.contracts.getEpochManager();
return yield epochManagerWrapper.getLastBlockAtEpoch(epochNumber);
});
}
getEpochNumberOfBlock(blockNumber) {
return __awaiter(this, void 0, void 0, function* () {
const epochManagerWrapper = yield this.contracts.getEpochManager();
try {
return epochManagerWrapper.getEpochNumberOfBlock(blockNumber);
}
catch (_) {
throw new Error(`Block number ${blockNumber} is not in any known L2 epoch`);
}
});
}
// *** NOTICE ***
// Next functions exists for backwards compatibility
// These should be consumed via connection to avoid future deprecation issues
addAccount(privateKey) {
this.connection.addAccount(privateKey);
}
set defaultAccount(address) {
this.connection.defaultAccount = address;
}
get defaultAccount() {
return this.connection.defaultAccount;
}
set gasInflationFactor(factor) {
this.connection.defaultGasInflationFactor = factor;
}
get gasInflationFactor() {
return this.connection.defaultGasInflationFactor;
}
set defaultFeeCurrency(address) {
this.connection.defaultFeeCurrency = address;
}
get defaultFeeCurrency() {
return this.connection.defaultFeeCurrency;
}
isListening() {
return this.connection.isListening();
}
isSyncing() {
return this.connection.isSyncing();
}
sendTransaction(tx) {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.sendTransaction(tx);
});
}
sendTransactionObject(txObj, tx) {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.sendTransactionObject(txObj, tx);
});
}
signTypedData(signer, typedData) {
return __awaiter(this, void 0, void 0, function* () {
return this.connection.signTypedData(signer, typedData);
});
}
stop() {
this.connection.stop();
}
get web3() {
return this.connection.web3;
}
}
exports.ContractKit = ContractKit;
//# sourceMappingURL=kit.js.map