Socket
Socket
Sign inDemoInstall

@celo/utils

Package Overview
Dependencies
Maintainers
16
Versions
144
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@celo/utils - npm Package Compare versions

Comparing version 0.1.17 to 0.1.18

lib/lock.d.ts

32

lib/account.d.ts
/// <reference types="node" />
export declare const CELO_DERIVATION_PATH_BASE = "m/44'/52752'/0'";
export declare enum MnemonicStrength {
s128_12words = 128,
s256_24words = 256
}
export declare enum MnemonicLanguages {
chinese_simplified = 0,
chinese_traditional = 1,
english = 2,
french = 3,
italian = 4,
japanese = 5,
korean = 6,
spanish = 7
}
declare type RandomNumberGenerator = (size: number, callback: (err: Error | null, buf: Buffer) => void) => void;
export interface Bip39 {
mnemonicToSeedSync: (mnemonic: string, password?: string) => Buffer;
mnemonicToSeed: (mnemonic: string, password?: string) => Promise<Buffer>;
generateMnemonic: (strength?: number, rng?: RandomNumberGenerator, wordlist?: string[]) => Promise<string>;
validateMnemonic: (mnemonic: string, wordlist?: string[]) => boolean;
}
import { Bip39, MnemonicLanguages, MnemonicStrength } from '@celo/base/lib/account';
export { Bip39, CELO_DERIVATION_PATH_BASE, MnemonicLanguages, MnemonicStrength, RandomNumberGenerator, } from '@celo/base/lib/account';
export declare function generateMnemonic(strength?: MnemonicStrength, language?: MnemonicLanguages, bip39ToUse?: Bip39): Promise<string>;

@@ -30,2 +10,7 @@ export declare function validateMnemonic(mnemonic: string, language?: MnemonicLanguages, bip39ToUse?: Bip39): boolean;

}>;
export declare function generateSeed(mnemonic: string, password?: string, bip39ToUse?: Bip39, keyByteLength?: number): Promise<Buffer>;
export declare function generateKeysFromSeed(seed: Buffer, changeIndex?: number, addressIndex?: number, derivationPath?: string): {
privateKey: string;
publicKey: string;
};
export declare const AccountUtils: {

@@ -35,3 +20,4 @@ generateMnemonic: typeof generateMnemonic;

generateKeys: typeof generateKeys;
generateSeed: typeof generateSeed;
generateKeysFromSeed: typeof generateKeysFromSeed;
};
export {};

@@ -61,23 +61,13 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountUtils = exports.generateKeys = exports.validateMnemonic = exports.generateMnemonic = exports.MnemonicLanguages = exports.MnemonicStrength = exports.CELO_DERIVATION_PATH_BASE = void 0;
exports.AccountUtils = exports.generateKeysFromSeed = exports.generateSeed = exports.generateKeys = exports.validateMnemonic = exports.generateMnemonic = void 0;
var account_1 = require("@celo/base/lib/account");
var bip32 = __importStar(require("bip32"));
var bip39 = __importStar(require("bip39"));
var randombytes_1 = __importDefault(require("randombytes"));
exports.CELO_DERIVATION_PATH_BASE = "m/44'/52752'/0'";
var MnemonicStrength;
(function (MnemonicStrength) {
MnemonicStrength[MnemonicStrength["s128_12words"] = 128] = "s128_12words";
MnemonicStrength[MnemonicStrength["s256_24words"] = 256] = "s256_24words";
})(MnemonicStrength = exports.MnemonicStrength || (exports.MnemonicStrength = {}));
var MnemonicLanguages;
(function (MnemonicLanguages) {
MnemonicLanguages[MnemonicLanguages["chinese_simplified"] = 0] = "chinese_simplified";
MnemonicLanguages[MnemonicLanguages["chinese_traditional"] = 1] = "chinese_traditional";
MnemonicLanguages[MnemonicLanguages["english"] = 2] = "english";
MnemonicLanguages[MnemonicLanguages["french"] = 3] = "french";
MnemonicLanguages[MnemonicLanguages["italian"] = 4] = "italian";
MnemonicLanguages[MnemonicLanguages["japanese"] = 5] = "japanese";
MnemonicLanguages[MnemonicLanguages["korean"] = 6] = "korean";
MnemonicLanguages[MnemonicLanguages["spanish"] = 7] = "spanish";
})(MnemonicLanguages = exports.MnemonicLanguages || (exports.MnemonicLanguages = {}));
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var account_2 = require("@celo/base/lib/account");
Object.defineProperty(exports, "CELO_DERIVATION_PATH_BASE", { enumerable: true, get: function () { return account_2.CELO_DERIVATION_PATH_BASE; } });
Object.defineProperty(exports, "MnemonicLanguages", { enumerable: true, get: function () { return account_2.MnemonicLanguages; } });
Object.defineProperty(exports, "MnemonicStrength", { enumerable: true, get: function () { return account_2.MnemonicStrength; } });
function defaultGenerateMnemonic(strength, rng, wordlist) {

@@ -104,3 +94,3 @@ return new Promise(function (resolve, reject) {

function generateMnemonic(strength, language, bip39ToUse) {
if (strength === void 0) { strength = MnemonicStrength.s256_24words; }
if (strength === void 0) { strength = account_1.MnemonicStrength.s256_24words; }
if (bip39ToUse === void 0) { bip39ToUse = bip39Wrapper; }

@@ -123,20 +113,34 @@ return __awaiter(this, void 0, void 0, function () {

if (bip39ToUse === void 0) { bip39ToUse = bip39Wrapper; }
if (derivationPath === void 0) { derivationPath = exports.CELO_DERIVATION_PATH_BASE; }
if (derivationPath === void 0) { derivationPath = account_1.CELO_DERIVATION_PATH_BASE; }
return __awaiter(this, void 0, void 0, function () {
var seed, node, newNode;
var seed;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, generateSeed(mnemonic, password, bip39ToUse)];
case 1:
seed = _a.sent();
return [2 /*return*/, generateKeysFromSeed(seed, changeIndex, addressIndex, derivationPath)];
}
});
});
}
exports.generateKeys = generateKeys;
// keyByteLength truncates the seed. *Avoid its use*
// It was added only because a backwards compatibility bug
function generateSeed(mnemonic, password, bip39ToUse, keyByteLength) {
if (bip39ToUse === void 0) { bip39ToUse = bip39Wrapper; }
if (keyByteLength === void 0) { keyByteLength = 64; }
return __awaiter(this, void 0, void 0, function () {
var seed, bufAux;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, bip39ToUse.mnemonicToSeed(mnemonic, password)];
case 1:
seed = _a.sent();
node = bip32.fromSeed(seed);
newNode = node.derivePath(derivationPath + "/" + changeIndex + "/" + addressIndex);
if (!newNode.privateKey) {
// As we are generating the node from a seed, the node will always have a private key and this would never happened
throw new Error('utils-accounts@generateKeys: invalid node to derivate');
if (keyByteLength > 0 && seed.byteLength > keyByteLength) {
bufAux = Buffer.allocUnsafe(keyByteLength);
seed.copy(bufAux, 0, 0, keyByteLength);
seed = bufAux;
}
return [2 /*return*/, {
privateKey: newNode.privateKey.toString('hex'),
publicKey: newNode.publicKey.toString('hex'),
}];
return [2 /*return*/, seed];
}

@@ -146,21 +150,37 @@ });

}
exports.generateKeys = generateKeys;
exports.generateSeed = generateSeed;
function generateKeysFromSeed(seed, changeIndex, addressIndex, derivationPath) {
if (changeIndex === void 0) { changeIndex = 0; }
if (addressIndex === void 0) { addressIndex = 0; }
if (derivationPath === void 0) { derivationPath = account_1.CELO_DERIVATION_PATH_BASE; }
var node = bip32.fromSeed(seed);
var newNode = node.derivePath(derivationPath + "/" + changeIndex + "/" + addressIndex);
if (!newNode.privateKey) {
// As we are generating the node from a seed, the node will always have a private key and this would never happened
throw new Error('utils-accounts@generateKeys: invalid node to derivate');
}
return {
privateKey: newNode.privateKey.toString('hex'),
publicKey: newNode.publicKey.toString('hex'),
};
}
exports.generateKeysFromSeed = generateKeysFromSeed;
// Unify the bip39.wordlists (otherwise depends on the instance of the bip39)
function getWordList(language) {
switch (language) {
case MnemonicLanguages.chinese_simplified:
case account_1.MnemonicLanguages.chinese_simplified:
return bip39.wordlists.chinese_simplified;
case MnemonicLanguages.chinese_traditional:
case account_1.MnemonicLanguages.chinese_traditional:
return bip39.wordlists.chinese_traditional;
case MnemonicLanguages.english:
case account_1.MnemonicLanguages.english:
return bip39.wordlists.english;
case MnemonicLanguages.french:
case account_1.MnemonicLanguages.french:
return bip39.wordlists.french;
case MnemonicLanguages.italian:
case account_1.MnemonicLanguages.italian:
return bip39.wordlists.italian;
case MnemonicLanguages.japanese:
case account_1.MnemonicLanguages.japanese:
return bip39.wordlists.japanese;
case MnemonicLanguages.korean:
case account_1.MnemonicLanguages.korean:
return bip39.wordlists.korean;
case MnemonicLanguages.spanish:
case account_1.MnemonicLanguages.spanish:
return bip39.wordlists.spanish;

@@ -175,3 +195,5 @@ default:

generateKeys: generateKeys,
generateSeed: generateSeed,
generateKeysFromSeed: generateKeysFromSeed,
};
//# sourceMappingURL=account.js.map

@@ -1,12 +0,3 @@

/// <reference types="node" />
export declare type Address = string;
export declare const eqAddress: (a: Address, b: Address) => boolean;
export declare const normalizeAddress: (a: Address) => string;
export declare const normalizeAddressWith0x: (a: Address) => string;
export declare const trimLeading0x: (input: string) => string;
export declare const ensureLeading0x: (input: string) => string;
export declare const getAddressChunks: (input: string) => string[];
export declare const isHexString: (input: string) => boolean;
export declare const hexToBuffer: (input: string) => Buffer;
export declare const bufferToHex: (buf: Buffer) => string;
export { Address, bufferToHex, ensureLeading0x, eqAddress, findAddressIndex, getAddressChunks, hexToBuffer, isHexString, mapAddressListDataOnto, mapAddressListOnto, normalizeAddress, normalizeAddressWith0x, NULL_ADDRESS, trimLeading0x, } from '@celo/base/lib/address';
export { isValidChecksumAddress, toChecksumAddress } from 'ethereumjs-util';
export declare const privateKeyToAddress: (privateKey: string) => string;

@@ -16,7 +7,2 @@ export declare const privateKeyToPublicKey: (privateKey: string) => string;

export declare const isValidPrivateKey: (privateKey: string) => boolean;
export { isValidChecksumAddress, toChecksumAddress } from 'ethereumjs-util';
export declare const isValidAddress: (input: string) => boolean;
export declare const NULL_ADDRESS = "0x0000000000000000000000000000000000000000";
export declare const findAddressIndex: (address: Address, addresses: Address[]) => number;
export declare const mapAddressListOnto: (oldAddress: Address[], newAddress: Address[]) => any[];
export declare function mapAddressListDataOnto<T>(data: T[], oldAddress: Address[], newAddress: Address[], initialValue: T): T[];

@@ -21,87 +21,39 @@ "use strict";

};
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapAddressListDataOnto = exports.mapAddressListOnto = exports.findAddressIndex = exports.NULL_ADDRESS = exports.isValidAddress = exports.isValidPrivateKey = exports.publicKeyToAddress = exports.privateKeyToPublicKey = exports.privateKeyToAddress = exports.bufferToHex = exports.hexToBuffer = exports.isHexString = exports.getAddressChunks = exports.ensureLeading0x = exports.trimLeading0x = exports.normalizeAddressWith0x = exports.normalizeAddress = exports.eqAddress = void 0;
exports.isValidAddress = exports.isValidPrivateKey = exports.publicKeyToAddress = exports.privateKeyToPublicKey = exports.privateKeyToAddress = void 0;
var address_1 = require("@celo/base/lib/address");
var ethereumjs_util_1 = require("ethereumjs-util");
var Web3Utils = __importStar(require("web3-utils"));
var HEX_REGEX = /^0x[0-9A-F]*$/i;
exports.eqAddress = function (a, b) { return exports.normalizeAddress(a) === exports.normalizeAddress(b); };
exports.normalizeAddress = function (a) { return exports.trimLeading0x(a).toLowerCase(); };
exports.normalizeAddressWith0x = function (a) { return exports.ensureLeading0x(a).toLowerCase(); };
exports.trimLeading0x = function (input) { return (input.startsWith('0x') ? input.slice(2) : input); };
exports.ensureLeading0x = function (input) { return (input.startsWith('0x') ? input : "0x" + input); };
// Turns '0xce10ce10ce10ce10ce10ce10ce10ce10ce10ce10'
// into ['ce10','ce10','ce10','ce10','ce10','ce10','ce10','ce10','ce10','ce10']
exports.getAddressChunks = function (input) {
return exports.trimLeading0x(input).match(/.{1,4}/g) || [];
};
exports.isHexString = function (input) { return HEX_REGEX.test(input); };
exports.hexToBuffer = function (input) { return Buffer.from(exports.trimLeading0x(input), 'hex'); };
exports.bufferToHex = function (buf) { return exports.ensureLeading0x(buf.toString('hex')); };
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var address_2 = require("@celo/base/lib/address");
Object.defineProperty(exports, "bufferToHex", { enumerable: true, get: function () { return address_2.bufferToHex; } });
Object.defineProperty(exports, "ensureLeading0x", { enumerable: true, get: function () { return address_2.ensureLeading0x; } });
Object.defineProperty(exports, "eqAddress", { enumerable: true, get: function () { return address_2.eqAddress; } });
Object.defineProperty(exports, "findAddressIndex", { enumerable: true, get: function () { return address_2.findAddressIndex; } });
Object.defineProperty(exports, "getAddressChunks", { enumerable: true, get: function () { return address_2.getAddressChunks; } });
Object.defineProperty(exports, "hexToBuffer", { enumerable: true, get: function () { return address_2.hexToBuffer; } });
Object.defineProperty(exports, "isHexString", { enumerable: true, get: function () { return address_2.isHexString; } });
Object.defineProperty(exports, "mapAddressListDataOnto", { enumerable: true, get: function () { return address_2.mapAddressListDataOnto; } });
Object.defineProperty(exports, "mapAddressListOnto", { enumerable: true, get: function () { return address_2.mapAddressListOnto; } });
Object.defineProperty(exports, "normalizeAddress", { enumerable: true, get: function () { return address_2.normalizeAddress; } });
Object.defineProperty(exports, "normalizeAddressWith0x", { enumerable: true, get: function () { return address_2.normalizeAddressWith0x; } });
Object.defineProperty(exports, "NULL_ADDRESS", { enumerable: true, get: function () { return address_2.NULL_ADDRESS; } });
Object.defineProperty(exports, "trimLeading0x", { enumerable: true, get: function () { return address_2.trimLeading0x; } });
var ethereumjs_util_2 = require("ethereumjs-util");
Object.defineProperty(exports, "isValidChecksumAddress", { enumerable: true, get: function () { return ethereumjs_util_2.isValidChecksumAddress; } });
Object.defineProperty(exports, "toChecksumAddress", { enumerable: true, get: function () { return ethereumjs_util_2.toChecksumAddress; } });
exports.privateKeyToAddress = function (privateKey) {
return ethereumjs_util_1.toChecksumAddress(exports.ensureLeading0x(ethereumjs_util_1.privateToAddress(exports.hexToBuffer(privateKey)).toString('hex')));
return ethereumjs_util_1.toChecksumAddress(address_1.ensureLeading0x(ethereumjs_util_1.privateToAddress(address_1.hexToBuffer(privateKey)).toString('hex')));
};
exports.privateKeyToPublicKey = function (privateKey) {
return ethereumjs_util_1.toChecksumAddress(exports.ensureLeading0x(ethereumjs_util_1.privateToPublic(exports.hexToBuffer(privateKey)).toString('hex')));
return ethereumjs_util_1.toChecksumAddress(address_1.ensureLeading0x(ethereumjs_util_1.privateToPublic(address_1.hexToBuffer(privateKey)).toString('hex')));
};
exports.publicKeyToAddress = function (publicKey) {
return ethereumjs_util_1.toChecksumAddress(exports.ensureLeading0x(ethereumjs_util_1.pubToAddress(exports.hexToBuffer(publicKey)).toString('hex')));
return ethereumjs_util_1.toChecksumAddress(address_1.ensureLeading0x(ethereumjs_util_1.pubToAddress(address_1.hexToBuffer(publicKey)).toString('hex')));
};
exports.isValidPrivateKey = function (privateKey) {
return privateKey.startsWith('0x') && ethereumjs_util_1.isValidPrivate(exports.hexToBuffer(privateKey));
return privateKey.startsWith('0x') && ethereumjs_util_1.isValidPrivate(address_1.hexToBuffer(privateKey));
};
var ethereumjs_util_2 = require("ethereumjs-util");
Object.defineProperty(exports, "isValidChecksumAddress", { enumerable: true, get: function () { return ethereumjs_util_2.isValidChecksumAddress; } });
Object.defineProperty(exports, "toChecksumAddress", { enumerable: true, get: function () { return ethereumjs_util_2.toChecksumAddress; } });
exports.isValidAddress = function (input) { return Web3Utils.isAddress(input); };
exports.NULL_ADDRESS = '0x0000000000000000000000000000000000000000';
exports.findAddressIndex = function (address, addresses) {
return addresses.findIndex(function (x) { return exports.eqAddress(x, address); });
};
// Returns an array of indices mapping the entries of oldAddress[] to newAddress[]
exports.mapAddressListOnto = function (oldAddress, newAddress) {
var oldAddressIndex = oldAddress.map(function (x, index) { return ({ address: exports.normalizeAddress(x), index: index }); });
var newAddressIndex = newAddress.map(function (x, index) { return ({ address: exports.normalizeAddress(x), index: index }); });
oldAddressIndex.sort(function (a, b) { return a.address.localeCompare(b.address); });
newAddressIndex.sort(function (a, b) { return a.address.localeCompare(b.address); });
var res = __spreadArrays(Array(oldAddress.length).fill(-1));
for (var i = 0, j = 0; i < oldAddress.length && j < newAddress.length;) {
var cmp = oldAddressIndex[i].address.localeCompare(newAddressIndex[j].address);
if (cmp < 0) {
i++;
}
else if (cmp > 0) {
j++;
}
else {
// Address is present in both lists
res[oldAddressIndex[i].index] = newAddressIndex[j].index;
i++;
j++;
}
}
return res;
};
// Returns data[] reordered by mapAddressListOnto(), and initiaValue for any entry of
// oldAddress[] not present in newAddress[].
function mapAddressListDataOnto(data, oldAddress, newAddress, initialValue) {
var res = __spreadArrays(Array(oldAddress.length).fill(initialValue));
if (data.length === 0) {
return res;
}
var addressIndexMap = exports.mapAddressListOnto(oldAddress, newAddress);
for (var i = 0; i < addressIndexMap.length; i++) {
if (addressIndexMap[i] >= 0) {
res[addressIndexMap[i]] = data[i];
}
}
return res;
}
exports.mapAddressListDataOnto = mapAddressListDataOnto;
//# sourceMappingURL=address.js.map

@@ -1,22 +0,1 @@

/** Sleep for a number of milliseconds */
export declare function sleep(ms: number): Promise<void>;
declare type InFunction<T extends any[], U> = (...params: T) => Promise<U>;
export declare const retryAsync: <T extends any[], U>(inFunction: InFunction<T, U>, tries: number, params: T, delay?: number) => Promise<U>;
export declare const retryAsyncWithBackOff: <T extends any[], U>(inFunction: InFunction<T, U>, tries: number, params: T, delay?: number, factor?: number) => Promise<U>;
/**
* Map an async function over a list xs with a given concurrency level
*
* @param concurrency number of `mapFn` concurrent executions
* @param xs list of value
* @param mapFn mapping function
*/
export declare function concurrentMap<A, B>(concurrency: number, xs: A[], mapFn: (val: A, idx: number) => Promise<B>): Promise<B[]>;
/**
* Map an async function over the values in Object x with a given concurrency level
*
* @param concurrency number of `mapFn` concurrent executions
* @param x associative array of values
* @param mapFn mapping function
*/
export declare function concurrentValuesMap<IN extends any, OUT extends any>(concurrency: number, x: Record<string, IN>, mapFn: (val: IN, key: string) => Promise<OUT>): Promise<Record<string, OUT>>;
export {};
export { concurrentMap, concurrentValuesMap, retryAsync, retryAsyncWithBackOff, selectiveRetryAsyncWithBackOff, sleep, } from '@celo/base/lib/async';
"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());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.concurrentValuesMap = exports.concurrentMap = exports.retryAsyncWithBackOff = exports.retryAsync = exports.sleep = void 0;
var TAG = 'utils/src/async';
/** Sleep for a number of milliseconds */
function sleep(ms) {
return new Promise(function (resolve) { return setTimeout(resolve, ms); });
}
exports.sleep = sleep;
// Retries an async function when it raises an exeption
// if all the tries fail it raises the last thrown exeption
exports.retryAsync = function (inFunction, tries, params, delay) {
if (delay === void 0) { delay = 100; }
return __awaiter(void 0, void 0, void 0, function () {
var saveError, i, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
i = 0;
_a.label = 1;
case 1:
if (!(i < tries)) return [3 /*break*/, 7];
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 6]);
return [4 /*yield*/, inFunction.apply(void 0, params)];
case 3:
// it awaits otherwise it'd always do all the retries
return [2 /*return*/, _a.sent()];
case 4:
error_1 = _a.sent();
return [4 /*yield*/, sleep(delay)];
case 5:
_a.sent();
saveError = error_1;
console.info(TAG + "/@retryAsync, Failed to execute function on try #" + i, error_1);
return [3 /*break*/, 6];
case 6:
i++;
return [3 /*break*/, 1];
case 7: throw saveError;
}
});
});
};
// Retries an async function when it raises an exeption
// if all the tries fail it raises the last thrown exeption
exports.retryAsyncWithBackOff = function (inFunction, tries, params, delay, factor) {
if (delay === void 0) { delay = 100; }
if (factor === void 0) { factor = 1.5; }
return __awaiter(void 0, void 0, void 0, function () {
var saveError, i, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
i = 0;
_a.label = 1;
case 1:
if (!(i < tries)) return [3 /*break*/, 7];
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 6]);
return [4 /*yield*/, inFunction.apply(void 0, params)];
case 3:
// it awaits otherwise it'd always do all the retries
return [2 /*return*/, _a.sent()];
case 4:
error_2 = _a.sent();
return [4 /*yield*/, sleep(Math.pow(factor, i) * delay)];
case 5:
_a.sent();
saveError = error_2;
console.info(TAG + "/@retryAsync, Failed to execute function on try #" + i, error_2);
return [3 /*break*/, 6];
case 6:
i++;
return [3 /*break*/, 1];
case 7: throw saveError;
}
});
});
};
/**
* Map an async function over a list xs with a given concurrency level
*
* @param concurrency number of `mapFn` concurrent executions
* @param xs list of value
* @param mapFn mapping function
*/
function concurrentMap(concurrency, xs, mapFn) {
return __awaiter(this, void 0, void 0, function () {
var res, _loop_1, i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
res = [];
_loop_1 = function (i) {
var remaining, sliceSize, slice, _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
remaining = xs.length - i;
sliceSize = Math.min(remaining, concurrency);
slice = xs.slice(i, i + sliceSize);
_b = (_a = res).concat;
return [4 /*yield*/, Promise.all(slice.map(function (elem, index) { return mapFn(elem, i + index); }))];
case 1:
res = _b.apply(_a, [_c.sent()]);
return [2 /*return*/];
}
});
};
i = 0;
_a.label = 1;
case 1:
if (!(i < xs.length)) return [3 /*break*/, 4];
return [5 /*yield**/, _loop_1(i)];
case 2:
_a.sent();
_a.label = 3;
case 3:
i += concurrency;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, res];
}
});
});
}
exports.concurrentMap = concurrentMap;
/**
* Map an async function over the values in Object x with a given concurrency level
*
* @param concurrency number of `mapFn` concurrent executions
* @param x associative array of values
* @param mapFn mapping function
*/
function concurrentValuesMap(concurrency, x, mapFn) {
return __awaiter(this, void 0, void 0, function () {
var xk, xv, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
xk = Object.keys(x);
xv = [];
xk.forEach(function (k) { return xv.push(x[k]); });
return [4 /*yield*/, concurrentMap(concurrency, xv, function (val, idx) { return mapFn(val, xk[idx]); })];
case 1:
res = _a.sent();
return [2 /*return*/, res.reduce(function (output, value, index) {
output[xk[index]] = value;
return output;
}, {})];
}
});
});
}
exports.concurrentValuesMap = concurrentValuesMap;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var async_1 = require("@celo/base/lib/async");
Object.defineProperty(exports, "concurrentMap", { enumerable: true, get: function () { return async_1.concurrentMap; } });
Object.defineProperty(exports, "concurrentValuesMap", { enumerable: true, get: function () { return async_1.concurrentValuesMap; } });
Object.defineProperty(exports, "retryAsync", { enumerable: true, get: function () { return async_1.retryAsync; } });
Object.defineProperty(exports, "retryAsyncWithBackOff", { enumerable: true, get: function () { return async_1.retryAsyncWithBackOff; } });
Object.defineProperty(exports, "selectiveRetryAsyncWithBackOff", { enumerable: true, get: function () { return async_1.selectiveRetryAsyncWithBackOff; } });
Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return async_1.sleep; } });
//# sourceMappingURL=async.js.map

@@ -81,2 +81,32 @@ "use strict";

});
describe('selectiveRetryAsyncWithBackOff()', function () {
test('tries only once if error is in dontRetry array', function () { return __awaiter(void 0, void 0, void 0, function () {
var mockFunction, didThrowError, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
mockFunction = jest.fn();
mockFunction.mockImplementation(function () {
throw new Error('test');
});
didThrowError = false;
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, async_1.selectiveRetryAsyncWithBackOff(mockFunction, 3, ['test'], [])];
case 2:
_b.sent();
return [3 /*break*/, 4];
case 3:
_a = _b.sent();
didThrowError = true;
return [3 /*break*/, 4];
case 4:
expect(mockFunction).toHaveBeenCalledTimes(1);
expect(didThrowError).toBeTruthy();
return [2 /*return*/];
}
});
}); });
});
var counter = function () {

@@ -83,0 +113,0 @@ var value = 0;

@@ -0,34 +1,8 @@

import { base64ToHex, extractAttestationCodeFromMessage, getIdentifierPrefix, IdentifierType, isAccountConsideredVerified, messageContainsAttestationCode, sanitizeMessageBase64 } from '@celo/base/lib/attestations';
import { Signature } from './signatureUtils';
export declare enum IdentifierType {
PHONE_NUMBER = 0
}
export declare function getIdentifierPrefix(type: IdentifierType): string;
export { AttestationsStatus, base64ToHex, extractAttestationCodeFromMessage, getIdentifierPrefix, IdentifierType, isAccountConsideredVerified, messageContainsAttestationCode, sanitizeMessageBase64, } from '@celo/base/lib/attestations';
export declare function hashIdentifier(identifier: string, type: IdentifierType, salt?: string): string;
export declare function getAttestationMessageToSignFromIdentifier(identifier: string, account: string): string;
export declare function getAttestationMessageToSignFromPhoneNumber(phoneNumber: string, account: string, phoneSalt?: string): string;
export declare function base64ToHex(base64String: string): string;
export declare function attestToIdentifier(identifier: string, account: string, privateKey: string): Signature;
export declare function sanitizeMessageBase64(base64String: string): string;
export declare function messageContainsAttestationCode(message: string): boolean;
export declare function extractAttestationCodeFromMessage(message: string): string | null;
export interface AttestationsStatus {
isVerified: boolean;
numAttestationsRemaining: number;
total: number;
completed: number;
}
interface AttestationStat {
completed: number;
total: number;
}
/**
* Returns true if an AttestationStat is considered verified using the given factors,
* or defaults if factors are ommited.
* @param stats AttestationStat of the account's attestation identitifer, retrievable via lookupIdentitfiers
* @param numAttestationsRequired Optional number of attestations required. Will default to
* hardcoded value if absent.
* @param attestationThreshold Optional threshold for fraction attestations completed. Will
* default to hardcoded value if absent.
*/
export declare function isAccountConsideredVerified(stats: AttestationStat | undefined, numAttestationsRequired?: number, attestationThreshold?: number): AttestationsStatus;
export declare const AttestationUtils: {

@@ -47,2 +21,1 @@ IdentifierType: typeof IdentifierType;

};
export {};
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttestationUtils = exports.isAccountConsideredVerified = exports.extractAttestationCodeFromMessage = exports.messageContainsAttestationCode = exports.sanitizeMessageBase64 = exports.attestToIdentifier = exports.base64ToHex = exports.getAttestationMessageToSignFromPhoneNumber = exports.getAttestationMessageToSignFromIdentifier = exports.hashIdentifier = exports.getIdentifierPrefix = exports.IdentifierType = void 0;
var Web3Utils = __importStar(require("web3-utils"));
exports.AttestationUtils = exports.attestToIdentifier = exports.getAttestationMessageToSignFromPhoneNumber = exports.getAttestationMessageToSignFromIdentifier = exports.hashIdentifier = void 0;
var attestations_1 = require("@celo/base/lib/attestations");
var web3_utils_1 = require("web3-utils");
var address_1 = require("./address");
var phoneNumbers_1 = require("./phoneNumbers");
var signatureUtils_1 = require("./signatureUtils");
var DEFAULT_NUM_ATTESTATIONS_REQUIRED = 3;
var DEFAULT_ATTESTATION_THRESHOLD = 0.25;
// Supported identifer types for attestations
var IdentifierType;
(function (IdentifierType) {
IdentifierType[IdentifierType["PHONE_NUMBER"] = 0] = "PHONE_NUMBER";
// In the future, other types like usernames or emails could go here
})(IdentifierType = exports.IdentifierType || (exports.IdentifierType = {}));
// Each identifer type has a unique prefix to prevent unlikely but possible collisions
function getIdentifierPrefix(type) {
switch (type) {
case IdentifierType.PHONE_NUMBER:
return 'tel://';
default:
throw new Error('Unsupported Identifier Type');
}
}
exports.getIdentifierPrefix = getIdentifierPrefix;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var attestations_2 = require("@celo/base/lib/attestations");
Object.defineProperty(exports, "base64ToHex", { enumerable: true, get: function () { return attestations_2.base64ToHex; } });
Object.defineProperty(exports, "extractAttestationCodeFromMessage", { enumerable: true, get: function () { return attestations_2.extractAttestationCodeFromMessage; } });
Object.defineProperty(exports, "getIdentifierPrefix", { enumerable: true, get: function () { return attestations_2.getIdentifierPrefix; } });
Object.defineProperty(exports, "IdentifierType", { enumerable: true, get: function () { return attestations_2.IdentifierType; } });
Object.defineProperty(exports, "isAccountConsideredVerified", { enumerable: true, get: function () { return attestations_2.isAccountConsideredVerified; } });
Object.defineProperty(exports, "messageContainsAttestationCode", { enumerable: true, get: function () { return attestations_2.messageContainsAttestationCode; } });
Object.defineProperty(exports, "sanitizeMessageBase64", { enumerable: true, get: function () { return attestations_2.sanitizeMessageBase64; } });
var sha3 = function (v) { return web3_utils_1.soliditySha3({ type: 'string', value: v }); };
function hashIdentifier(identifier, type, salt) {
switch (type) {
case IdentifierType.PHONE_NUMBER:
return phoneNumbers_1.PhoneNumberUtils.getPhoneHash(identifier, salt);
default:
throw new Error('Unsupported Identifier Type');
}
return attestations_1.hashIdentifier(sha3, identifier, type, salt);
}
exports.hashIdentifier = hashIdentifier;
function getAttestationMessageToSignFromIdentifier(identifier, account) {
var messageHash = Web3Utils.soliditySha3({ type: 'bytes32', value: identifier }, { type: 'address', value: account });
var messageHash = web3_utils_1.soliditySha3({ type: 'bytes32', value: identifier }, { type: 'address', value: account });
return messageHash;

@@ -60,9 +29,5 @@ }

function getAttestationMessageToSignFromPhoneNumber(phoneNumber, account, phoneSalt) {
return getAttestationMessageToSignFromIdentifier(hashIdentifier(phoneNumber, IdentifierType.PHONE_NUMBER, phoneSalt), account);
return getAttestationMessageToSignFromIdentifier(hashIdentifier(phoneNumber, attestations_1.IdentifierType.PHONE_NUMBER, phoneSalt), account);
}
exports.getAttestationMessageToSignFromPhoneNumber = getAttestationMessageToSignFromPhoneNumber;
function base64ToHex(base64String) {
return '0x' + Buffer.from(base64String, 'base64').toString('hex');
}
exports.base64ToHex = base64ToHex;
function attestToIdentifier(identifier, account, privateKey) {

@@ -74,70 +39,15 @@ var issuer = address_1.privateKeyToAddress(privateKey);

exports.attestToIdentifier = attestToIdentifier;
function sanitizeMessageBase64(base64String) {
// Replace occurrences of ¿ with _. Unsure why that is happening right now
return base64String.replace(/(¿|§)/gi, '_');
}
exports.sanitizeMessageBase64 = sanitizeMessageBase64;
var attestationCodeRegex = new RegExp(/(.* |^)(?:celo:\/\/wallet\/v\/)?([a-zA-Z0-9=\+\/_-]{87,88})($| .*)/);
function messageContainsAttestationCode(message) {
return attestationCodeRegex.test(message);
}
exports.messageContainsAttestationCode = messageContainsAttestationCode;
function extractAttestationCodeFromMessage(message) {
var sanitizedMessage = sanitizeMessageBase64(message);
if (!messageContainsAttestationCode(sanitizedMessage)) {
return null;
}
var matches = sanitizedMessage.match(attestationCodeRegex);
if (!matches || matches.length < 3) {
return null;
}
return base64ToHex(matches[2]);
}
exports.extractAttestationCodeFromMessage = extractAttestationCodeFromMessage;
/**
* Returns true if an AttestationStat is considered verified using the given factors,
* or defaults if factors are ommited.
* @param stats AttestationStat of the account's attestation identitifer, retrievable via lookupIdentitfiers
* @param numAttestationsRequired Optional number of attestations required. Will default to
* hardcoded value if absent.
* @param attestationThreshold Optional threshold for fraction attestations completed. Will
* default to hardcoded value if absent.
*/
function isAccountConsideredVerified(stats, numAttestationsRequired, attestationThreshold) {
if (numAttestationsRequired === void 0) { numAttestationsRequired = DEFAULT_NUM_ATTESTATIONS_REQUIRED; }
if (attestationThreshold === void 0) { attestationThreshold = DEFAULT_ATTESTATION_THRESHOLD; }
if (!stats) {
return {
isVerified: false,
numAttestationsRemaining: 0,
total: 0,
completed: 0,
};
}
var numAttestationsRemaining = numAttestationsRequired - stats.completed;
var fractionAttestation = stats.total < 1 ? 0 : stats.completed / stats.total;
// 'verified' is a term of convenience to mean that the attestation stats for a
// given identifier are beyond a certain threshold of confidence
var isVerified = numAttestationsRemaining <= 0 && fractionAttestation >= attestationThreshold;
return {
isVerified: isVerified,
numAttestationsRemaining: numAttestationsRemaining,
total: stats.total,
completed: stats.completed,
};
}
exports.isAccountConsideredVerified = isAccountConsideredVerified;
exports.AttestationUtils = {
IdentifierType: IdentifierType,
getIdentifierPrefix: getIdentifierPrefix,
IdentifierType: attestations_1.IdentifierType,
getIdentifierPrefix: attestations_1.getIdentifierPrefix,
hashIdentifier: hashIdentifier,
getAttestationMessageToSignFromIdentifier: getAttestationMessageToSignFromIdentifier,
getAttestationMessageToSignFromPhoneNumber: getAttestationMessageToSignFromPhoneNumber,
base64ToHex: base64ToHex,
base64ToHex: attestations_1.base64ToHex,
attestToIdentifier: attestToIdentifier,
sanitizeMessageBase64: sanitizeMessageBase64,
messageContainsAttestationCode: messageContainsAttestationCode,
extractAttestationCodeFromMessage: extractAttestationCodeFromMessage,
isAccountConsideredVerified: isAccountConsideredVerified,
sanitizeMessageBase64: attestations_1.sanitizeMessageBase64,
messageContainsAttestationCode: attestations_1.messageContainsAttestationCode,
extractAttestationCodeFromMessage: attestations_1.extractAttestationCodeFromMessage,
isAccountConsideredVerified: attestations_1.isAccountConsideredVerified,
};
//# sourceMappingURL=attestations.js.map

@@ -0,10 +1,5 @@

import * as base from '@celo/base/lib/collections';
import BigNumber from 'bignumber.js';
export declare function zip<A, B, C>(fn: (a: A, b: B) => C, as: A[], bs: B[]): C[];
export declare function zip3<A, B, C>(as: A[], bs: B[], cs: C[]): [A, B, C][];
export declare function notEmpty<TValue>(value: TValue | null | undefined): value is TValue;
export declare function intersection<T>(arrays: T[][]): T[];
export interface AddressListItem {
address: string;
value: BigNumber;
}
export { intersection, notEmpty, zip, zip3 } from '@celo/base/lib/collections';
export declare type AddressListItem = base.AddressListItem<BigNumber>;
export declare function linkedListChange(sortedList: AddressListItem[], change: AddressListItem): {

@@ -11,0 +6,0 @@ lesser: string;

"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.linkedListChanges = exports.linkedListChange = exports.intersection = exports.notEmpty = exports.zip3 = exports.zip = void 0;
var address_1 = require("./address");
function zip(fn, as, bs) {
var len = Math.min(as.length, bs.length);
var res = [];
for (var i = 0; i < len; i++) {
res.push(fn(as[i], bs[i]));
}
return res;
}
exports.zip = zip;
function zip3(as, bs, cs) {
var len = Math.min(as.length, bs.length, cs.length);
var res = [];
for (var i = 0; i < len; i++) {
res.push([as[i], bs[i], cs[i]]);
}
return res;
}
exports.zip3 = zip3;
// https://stackoverflow.com/questions/43118692/typescript-filter-out-nulls-from-an-array
function notEmpty(value) {
return value !== null && value !== undefined;
}
exports.notEmpty = notEmpty;
function intersection(arrays) {
if (arrays.length === 0) {
return [];
}
var sets = arrays.map(function (array) { return new Set(array); });
var res = [];
var _loop_1 = function (elem) {
if (sets.every(function (set) { return set.has(elem); })) {
res.push(elem);
}
};
for (var _i = 0, _a = arrays[0]; _i < _a.length; _i++) {
var elem = _a[_i];
_loop_1(elem);
}
return res;
}
exports.intersection = intersection;
function upsert(sortedList, change) {
var oldIdx = sortedList.findIndex(function (a) { return address_1.eqAddress(a.address, change.address); });
if (oldIdx === -1) {
throw new Error('');
}
sortedList.splice(oldIdx, 1);
var newIdx = sortedList.findIndex(function (a) { return a.value.lt(change.value); });
if (newIdx === -1) {
sortedList.push(change);
return sortedList.length - 1;
}
else {
sortedList.splice(newIdx, 0, change);
return newIdx;
}
}
// Warning: sortedList is modified
function _linkedListChange(sortedList, change) {
var idx = upsert(sortedList, change);
var greater = idx === 0 ? address_1.NULL_ADDRESS : sortedList[idx - 1].address;
var lesser = idx === sortedList.length - 1 ? address_1.NULL_ADDRESS : sortedList[idx + 1].address;
return { lesser: lesser, greater: greater };
}
exports.linkedListChanges = exports.linkedListChange = void 0;
var base = __importStar(require("@celo/base/lib/collections"));
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var collections_1 = require("@celo/base/lib/collections");
Object.defineProperty(exports, "intersection", { enumerable: true, get: function () { return collections_1.intersection; } });
Object.defineProperty(exports, "notEmpty", { enumerable: true, get: function () { return collections_1.notEmpty; } });
Object.defineProperty(exports, "zip", { enumerable: true, get: function () { return collections_1.zip; } });
Object.defineProperty(exports, "zip3", { enumerable: true, get: function () { return collections_1.zip3; } });
// BigNumber comparator
var bigNumberComparator = function (a, b) { return a.lt(b); };
function linkedListChange(sortedList, change) {
var list = sortedList.concat();
var _a = _linkedListChange(list, change), lesser = _a.lesser, greater = _a.greater;
return { lesser: lesser, greater: greater, list: list };
return base.linkedListChange(sortedList, change, bigNumberComparator);
}
exports.linkedListChange = linkedListChange;
function linkedListChanges(sortedList, changeList) {
var listClone = __spreadArrays(sortedList);
var lessers = [];
var greaters = [];
for (var _i = 0, changeList_1 = changeList; _i < changeList_1.length; _i++) {
var it_1 = changeList_1[_i];
var _a = _linkedListChange(listClone, it_1), lesser = _a.lesser, greater = _a.greater;
lessers.push(lesser);
greaters.push(greater);
}
return { lessers: lessers, greaters: greaters, list: listClone };
return base.linkedListChanges(sortedList, changeList, bigNumberComparator);
}
exports.linkedListChanges = linkedListChanges;
//# sourceMappingURL=collections.js.map

@@ -1,13 +0,3 @@

export interface ContactPhoneNumber {
label?: string;
number?: string;
}
export interface MinimalContact {
recordID: string;
displayName?: string;
phoneNumbers?: ContactPhoneNumber[];
thumbnailPath?: string;
}
export declare const getContactPhoneNumber: (contact: MinimalContact) => string | null | undefined;
import { MinimalContact } from '@celo/base/lib/contacts';
export { ContactPhoneNumber, getContactPhoneNumber, isContact, MinimalContact, } from '@celo/base/lib/contacts';
export declare const getContactNameHash: (contact: MinimalContact) => any;
export declare function isContact(contactOrNumber: any): contactOrNumber is MinimalContact;

@@ -22,14 +22,9 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.isContact = exports.getContactNameHash = exports.getContactPhoneNumber = void 0;
exports.getContactNameHash = void 0;
var Web3Utils = __importStar(require("web3-utils"));
exports.getContactPhoneNumber = function (contact) {
if (!contact) {
throw new Error('Invalid contact');
}
if (!contact.phoneNumbers || !contact.phoneNumbers.length) {
return null;
}
// TODO(Rossy) find the right phone number based on the address
return contact.phoneNumbers[0].number;
};
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var contacts_1 = require("@celo/base/lib/contacts");
Object.defineProperty(exports, "getContactPhoneNumber", { enumerable: true, get: function () { return contacts_1.getContactPhoneNumber; } });
Object.defineProperty(exports, "isContact", { enumerable: true, get: function () { return contacts_1.isContact; } });
exports.getContactNameHash = function (contact) {

@@ -41,9 +36,2 @@ if (!contact) {

};
function isContact(contactOrNumber) {
if (typeof contactOrNumber === 'object') {
return 'recordID' in contactOrNumber;
}
return false;
}
exports.isContact = isContact;
//# sourceMappingURL=contacts.js.map

@@ -1,26 +0,1 @@

export declare enum CURRENCY_ENUM {
GOLD = "Celo Gold",
DOLLAR = "Celo Dollar"
}
interface Currency {
symbol: string;
code: string;
displayDecimals: number;
}
declare type CurrencyObject = {
[key in CURRENCY_ENUM]: Currency;
};
export declare const CURRENCIES: CurrencyObject;
export declare const resolveCurrency: (label: string) => CURRENCY_ENUM;
export declare enum SHORT_CURRENCIES {
DOLLAR = "dollar",
GOLD = "gold"
}
export declare const currencyToShortMap: {
"Celo Dollar": SHORT_CURRENCIES;
"Celo Gold": SHORT_CURRENCIES;
};
export declare const currencyTranslations: {
[key: string]: any;
};
export {};
export { CURRENCIES, currencyToShortMap, currencyTranslations, CURRENCY_ENUM, resolveCurrency, SHORT_CURRENCIES, } from '@celo/base/lib/currencies';
"use strict";
var _a, _b, _c;
Object.defineProperty(exports, "__esModule", { value: true });
exports.currencyTranslations = exports.currencyToShortMap = exports.SHORT_CURRENCIES = exports.resolveCurrency = exports.CURRENCIES = exports.CURRENCY_ENUM = void 0;
var CURRENCY_ENUM;
(function (CURRENCY_ENUM) {
CURRENCY_ENUM["GOLD"] = "Celo Gold";
CURRENCY_ENUM["DOLLAR"] = "Celo Dollar";
})(CURRENCY_ENUM = exports.CURRENCY_ENUM || (exports.CURRENCY_ENUM = {}));
exports.CURRENCIES = (_a = {},
_a[CURRENCY_ENUM.GOLD] = {
symbol: '',
code: 'cGLD',
displayDecimals: 3,
},
_a[CURRENCY_ENUM.DOLLAR] = {
symbol: '$',
code: 'cUSD',
displayDecimals: 2,
},
_a);
exports.resolveCurrency = function (label) {
if (label && label.toLowerCase().includes('dollar')) {
return CURRENCY_ENUM.DOLLAR;
}
else if (label && label.toLowerCase().includes('gold')) {
return CURRENCY_ENUM.GOLD;
}
else {
console.info('Unable to resolve currency from label: ' + label);
return CURRENCY_ENUM.DOLLAR;
}
};
var SHORT_CURRENCIES;
(function (SHORT_CURRENCIES) {
SHORT_CURRENCIES["DOLLAR"] = "dollar";
SHORT_CURRENCIES["GOLD"] = "gold";
})(SHORT_CURRENCIES = exports.SHORT_CURRENCIES || (exports.SHORT_CURRENCIES = {}));
exports.currencyToShortMap = (_b = {},
_b[CURRENCY_ENUM.DOLLAR] = SHORT_CURRENCIES.DOLLAR,
_b[CURRENCY_ENUM.GOLD] = SHORT_CURRENCIES.GOLD,
_b);
var currencyTranslationsENUS = {
CeloDollars: 'Celo Dollars',
CeloDollar: 'Celo Dollar',
Dollar: 'Dollar',
Dollars: 'Dollars',
dollars: 'dollars',
};
var currencyTranslationsESAR = {
CeloDollars: 'Celo Dólares',
CeloDollar: 'Celo Dólar',
Dollar: 'Dólar',
Dollars: 'Dólares',
dollars: 'dólares',
};
exports.currencyTranslations = (_c = {},
_c['en-US'] = currencyTranslationsENUS,
_c['es-419'] = currencyTranslationsESAR,
_c);
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var currencies_1 = require("@celo/base/lib/currencies");
Object.defineProperty(exports, "CURRENCIES", { enumerable: true, get: function () { return currencies_1.CURRENCIES; } });
Object.defineProperty(exports, "currencyToShortMap", { enumerable: true, get: function () { return currencies_1.currencyToShortMap; } });
Object.defineProperty(exports, "currencyTranslations", { enumerable: true, get: function () { return currencies_1.currencyTranslations; } });
Object.defineProperty(exports, "CURRENCY_ENUM", { enumerable: true, get: function () { return currencies_1.CURRENCY_ENUM; } });
Object.defineProperty(exports, "resolveCurrency", { enumerable: true, get: function () { return currencies_1.resolveCurrency; } });
Object.defineProperty(exports, "SHORT_CURRENCIES", { enumerable: true, get: function () { return currencies_1.SHORT_CURRENCIES; } });
//# sourceMappingURL=currencies.js.map

@@ -1,1 +0,1 @@

export declare function getErrorMessage(error: Error): string;
export { getErrorMessage } from '@celo/base/lib/displayFormatting';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getErrorMessage = void 0;
function getErrorMessage(error) {
// This replacement is because when the error reaches here, it's been wrapped
// by Error: multiple times
var errorMsg = error.message || error.name || 'unknown';
errorMsg = errorMsg.replace(/Error:/g, '');
if (error.stack) {
errorMsg += ' in ' + error.stack.substring(0, 100);
}
return errorMsg;
}
exports.getErrorMessage = getErrorMessage;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var displayFormatting_1 = require("@celo/base/lib/displayFormatting");
Object.defineProperty(exports, "getErrorMessage", { enumerable: true, get: function () { return displayFormatting_1.getErrorMessage; } });
//# sourceMappingURL=displayFormatting.js.map

@@ -1,16 +0,1 @@

export declare class Future<T> {
private promise;
private _finished;
private _error;
private _resolve;
private _reject;
constructor();
get finished(): boolean;
get error(): any;
resolve(value: T): void;
reject(error: any): void;
wait(): Promise<T>;
asPromise(): Promise<T>;
}
export declare function toFuture<A>(p: Promise<A>): Future<A>;
export declare function pipeToFuture<A>(p: Promise<A>, future: Future<A>): Future<A>;
export { Future, pipeToFuture, toFuture } from '@celo/base/lib/future';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pipeToFuture = exports.toFuture = exports.Future = void 0;
// A Future is like an exernally fulfillable (resolvable) promise
var Future = /** @class */ (function () {
function Future() {
var _this = this;
this._finished = false;
this._error = null;
this.promise = new Promise(function (resolve, reject) {
_this._resolve = resolve;
_this._reject = reject;
});
}
Object.defineProperty(Future.prototype, "finished", {
get: function () {
return this._finished;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Future.prototype, "error", {
get: function () {
return this._error;
},
enumerable: false,
configurable: true
});
Future.prototype.resolve = function (value) {
this._finished = true;
this._error = null;
this._resolve(value);
};
Future.prototype.reject = function (error) {
this._finished = true;
this._error = error;
this._reject(error);
};
Future.prototype.wait = function () {
return this.promise;
};
Future.prototype.asPromise = function () {
return this.promise;
};
return Future;
}());
exports.Future = Future;
function toFuture(p) {
var future = new Future();
return pipeToFuture(p, future);
}
exports.toFuture = toFuture;
function pipeToFuture(p, future) {
p.then(future.resolve.bind(future)).catch(future.reject.bind(future));
return future;
}
exports.pipeToFuture = pipeToFuture;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var future_1 = require("@celo/base/lib/future");
Object.defineProperty(exports, "Future", { enumerable: true, get: function () { return future_1.Future; } });
Object.defineProperty(exports, "pipeToFuture", { enumerable: true, get: function () { return future_1.pipeToFuture; } });
Object.defineProperty(exports, "toFuture", { enumerable: true, get: function () { return future_1.toFuture; } });
//# sourceMappingURL=future.js.map

@@ -1,16 +0,4 @@

export declare enum ValidatorKind {
Custom = "custom",
Decimal = "decimal",
Integer = "integer",
Phone = "phone"
}
export interface BaseProps {
validator?: ValidatorKind;
customValidator?: (input: string) => string;
countryCallingCode?: string;
decimalSeparator?: string;
}
export declare function validateInteger(input: string): string;
export declare function validateDecimal(input: string, decimalSeparator?: string): string;
import { BaseProps } from '@celo/base/lib/inputValidation';
export { BaseProps, validateDecimal, validateInteger, ValidatorKind, } from '@celo/base/lib/inputValidation';
export declare function validatePhone(input: string, countryCallingCode?: string): string;
export declare function validateInput(input: string, props: BaseProps): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateInput = exports.validatePhone = exports.validateDecimal = exports.validateInteger = exports.ValidatorKind = void 0;
exports.validateInput = exports.validatePhone = void 0;
var inputValidation_1 = require("@celo/base/lib/inputValidation");
var phoneNumbers_1 = require("./phoneNumbers");
var ValidatorKind;
(function (ValidatorKind) {
ValidatorKind["Custom"] = "custom";
ValidatorKind["Decimal"] = "decimal";
ValidatorKind["Integer"] = "integer";
ValidatorKind["Phone"] = "phone";
})(ValidatorKind = exports.ValidatorKind || (exports.ValidatorKind = {}));
function validateInteger(input) {
return input.replace(/[^0-9]/g, '');
}
exports.validateInteger = validateInteger;
function validateDecimal(input, decimalSeparator) {
if (decimalSeparator === void 0) { decimalSeparator = '.'; }
var regex = decimalSeparator === ',' ? /[^0-9,]/g : /[^0-9.]/g;
var cleanedArray = input.replace(regex, '').split(decimalSeparator);
if (cleanedArray.length <= 1) {
// Empty string or no decimals
return cleanedArray.join('');
}
else {
return cleanedArray.shift() + decimalSeparator + cleanedArray.join('');
}
}
exports.validateDecimal = validateDecimal;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var inputValidation_2 = require("@celo/base/lib/inputValidation");
Object.defineProperty(exports, "validateDecimal", { enumerable: true, get: function () { return inputValidation_2.validateDecimal; } });
Object.defineProperty(exports, "validateInteger", { enumerable: true, get: function () { return inputValidation_2.validateInteger; } });
Object.defineProperty(exports, "ValidatorKind", { enumerable: true, get: function () { return inputValidation_2.ValidatorKind; } });
function validatePhone(input, countryCallingCode) {

@@ -47,5 +30,5 @@ input = input.replace(/[^0-9()\- ]/g, '');

case 'decimal':
return validateDecimal(input, props.decimalSeparator);
return inputValidation_1.validateDecimal(input, props.decimalSeparator);
case 'integer':
return validateInteger(input);
return inputValidation_1.validateInteger(input);
case 'phone':

@@ -52,0 +35,0 @@ return validatePhone(input, props.countryCallingCode);

import * as t from 'io-ts';
export declare const URL_REGEX: RegExp;
export declare const isValidUrl: (url: string) => boolean;
export { isValidUrl, URL_REGEX } from '@celo/base/lib/io';
export declare const UrlType: t.Type<string, string, unknown>;

@@ -5,0 +4,0 @@ export declare const JSONStringType: t.Type<string, string, unknown>;

@@ -22,3 +22,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.AttestationServiceTestRequestType = exports.AttestationServiceStatusResponseType = exports.SaltType = exports.SignatureType = exports.PublicKeyType = exports.AddressType = exports.E164PhoneNumberType = exports.JSONStringType = exports.UrlType = exports.isValidUrl = exports.URL_REGEX = void 0;
exports.AttestationServiceTestRequestType = exports.AttestationServiceStatusResponseType = exports.SaltType = exports.SignatureType = exports.PublicKeyType = exports.AddressType = exports.E164PhoneNumberType = exports.JSONStringType = exports.UrlType = void 0;
var io_1 = require("@celo/base/lib/io");
var ethereumjs_util_1 = require("ethereumjs-util");

@@ -29,8 +30,10 @@ var Either_1 = require("fp-ts/lib/Either");

var phoneNumbers_1 = require("./phoneNumbers");
// from http://urlregex.com/
exports.URL_REGEX = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/);
exports.isValidUrl = function (url) { return exports.URL_REGEX.test(url); };
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var io_2 = require("@celo/base/lib/io");
Object.defineProperty(exports, "isValidUrl", { enumerable: true, get: function () { return io_2.isValidUrl; } });
Object.defineProperty(exports, "URL_REGEX", { enumerable: true, get: function () { return io_2.URL_REGEX; } });
exports.UrlType = new t.Type('Url', t.string.is, function (input, context) {
return Either_1.either.chain(t.string.validate(input, context), function (stringValue) {
return exports.URL_REGEX.test(stringValue)
return io_1.URL_REGEX.test(stringValue)
? t.success(stringValue)

@@ -37,0 +40,0 @@ : t.failure(stringValue, context, 'is not a valid url');

@@ -1,4 +0,1 @@

export declare type Logger = (...args: any[]) => void;
export declare const noopLogger: Logger;
export declare const prefixLogger: (prefix: string, logger: Logger) => Logger;
export declare const consoleLogger: Logger;
export { consoleLogger, Logger, noopLogger, prefixLogger } from '@celo/base/lib/logger';
"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.consoleLogger = exports.prefixLogger = exports.noopLogger = void 0;
exports.noopLogger = function () {
/*noop*/
};
exports.prefixLogger = function (prefix, logger) {
if (logger === exports.noopLogger) {
return exports.noopLogger;
}
else {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return logger.apply(void 0, __spreadArrays([prefix + ":: "], args));
};
}
};
exports.consoleLogger = console.log;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var logger_1 = require("@celo/base/lib/logger");
Object.defineProperty(exports, "consoleLogger", { enumerable: true, get: function () { return logger_1.consoleLogger; } });
Object.defineProperty(exports, "noopLogger", { enumerable: true, get: function () { return logger_1.noopLogger; } });
Object.defineProperty(exports, "prefixLogger", { enumerable: true, get: function () { return logger_1.prefixLogger; } });
//# sourceMappingURL=logger.js.map
import BigNumber from 'bignumber.js';
export declare const stringToBoolean: (inputString: string) => boolean;
export { parseSolidityStringArray, stringToBoolean } from '@celo/base/lib/parsing';
export declare const parseInputAmount: (inputString: string, decimalSeparator?: string) => BigNumber;
/**
* Parses an "array of strings" that is returned from a Solidity function
*
* @param stringLengths length of each string in bytes
* @param data 0x-prefixed, hex-encoded string data in utf-8 bytes
*/
export declare const parseSolidityStringArray: (stringLengths: number[], data: string) => string[];

@@ -6,14 +6,9 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.parseSolidityStringArray = exports.parseInputAmount = exports.stringToBoolean = void 0;
exports.parseInputAmount = void 0;
var bignumber_js_1 = __importDefault(require("bignumber.js"));
exports.stringToBoolean = function (inputString) {
var lowercasedInput = inputString.toLowerCase().trim();
if (lowercasedInput === 'true') {
return true;
}
else if (lowercasedInput === 'false') {
return false;
}
throw new Error("Unable to parse '" + inputString + "' as boolean");
};
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var parsing_1 = require("@celo/base/lib/parsing");
Object.defineProperty(exports, "parseSolidityStringArray", { enumerable: true, get: function () { return parsing_1.parseSolidityStringArray; } });
Object.defineProperty(exports, "stringToBoolean", { enumerable: true, get: function () { return parsing_1.stringToBoolean; } });
exports.parseInputAmount = function (inputString, decimalSeparator) {

@@ -26,24 +21,2 @@ if (decimalSeparator === void 0) { decimalSeparator = '.'; }

};
/**
* Parses an "array of strings" that is returned from a Solidity function
*
* @param stringLengths length of each string in bytes
* @param data 0x-prefixed, hex-encoded string data in utf-8 bytes
*/
exports.parseSolidityStringArray = function (stringLengths, data) {
if (data === null) {
data = '0x';
}
var ret = [];
var offset = 0;
// @ts-ignore
var rawData = Buffer.from(data.slice(2), 'hex');
// tslint:disable-next-line:prefer-for-of
for (var i = 0; i < stringLengths.length; i++) {
var string = rawData.toString('utf-8', offset, offset + stringLengths[i]);
offset += stringLengths[i];
ret.push(string);
}
return ret;
};
//# sourceMappingURL=parsing.js.map

@@ -1,10 +0,5 @@

export interface ParsedPhoneNumber {
e164Number: string;
displayNumber: string;
displayNumberInternational: string;
countryCode?: number;
regionCode?: string;
}
import { isE164Number, ParsedPhoneNumber } from '@celo/base/lib/phoneNumbers';
export { anonymizedPhone, isE164Number, ParsedPhoneNumber } from '@celo/base/lib/phoneNumbers';
export declare const getPhoneHash: (phoneNumber: string, salt?: string | undefined) => string;
export declare function getCountryEmoji(e164PhoneNumber: string, countryCodePossible?: number, regionCodePossible?: string): string;
export declare const getPhoneHash: (phoneNumber: string, salt?: string | undefined) => string;
export declare function getCountryCode(e164PhoneNumber: string): number | null | undefined;

@@ -17,6 +12,4 @@ export declare function getRegionCode(e164PhoneNumber: string): string | null | undefined;

export declare function getE164Number(phoneNumber: string, defaultCountryCode: string): string | null;
export declare function isE164Number(phoneNumber: string): boolean;
export declare function isE164NumberStrict(phoneNumber: string): boolean;
export declare function parsePhoneNumber(phoneNumberRaw: string, defaultCountryCode?: string): ParsedPhoneNumber | null;
export declare function anonymizedPhone(phoneNumber: string): string;
export declare function getExampleNumber(regionCode: string, useOnlyZeroes?: boolean, isInternational?: boolean): string | undefined;

@@ -23,0 +16,0 @@ export declare const PhoneNumberUtils: {

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -25,11 +6,18 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
exports.PhoneNumberUtils = exports.getExampleNumber = exports.anonymizedPhone = exports.parsePhoneNumber = exports.isE164NumberStrict = exports.isE164Number = exports.getE164Number = exports.getE164DisplayNumber = exports.getDisplayNumberInternational = exports.getDisplayPhoneNumber = exports.getRegionCodeFromCountryCode = exports.getRegionCode = exports.getCountryCode = exports.getPhoneHash = exports.getCountryEmoji = void 0;
exports.PhoneNumberUtils = exports.getExampleNumber = exports.parsePhoneNumber = exports.isE164NumberStrict = exports.getE164Number = exports.getE164DisplayNumber = exports.getDisplayNumberInternational = exports.getDisplayPhoneNumber = exports.getRegionCodeFromCountryCode = exports.getRegionCode = exports.getCountryCode = exports.getCountryEmoji = exports.getPhoneHash = void 0;
var phoneNumbers_1 = require("@celo/base/lib/phoneNumbers");
var country_data_1 = __importDefault(require("country-data"));
var google_libphonenumber_1 = require("google-libphonenumber");
var Web3Utils = __importStar(require("web3-utils"));
var attestations_1 = require("./attestations");
var web3_utils_1 = require("web3-utils");
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var phoneNumbers_2 = require("@celo/base/lib/phoneNumbers");
Object.defineProperty(exports, "anonymizedPhone", { enumerable: true, get: function () { return phoneNumbers_2.anonymizedPhone; } });
Object.defineProperty(exports, "isE164Number", { enumerable: true, get: function () { return phoneNumbers_2.isE164Number; } });
var sha3 = function (v) { return web3_utils_1.soliditySha3({ type: 'string', value: v }); };
exports.getPhoneHash = function (phoneNumber, salt) {
return phoneNumbers_1.getPhoneHash(sha3, phoneNumber, salt);
};
var phoneUtil = google_libphonenumber_1.PhoneNumberUtil.getInstance();
var MIN_PHONE_LENGTH = 4;
var PHONE_SALT_SEPARATOR = '__';
var E164_REGEX = /^\+[1-9][0-9]{1,14}$/;
function getCountryEmoji(e164PhoneNumber, countryCodePossible, regionCodePossible) {

@@ -51,10 +39,2 @@ // The country code and region code can both be passed in, or it can be inferred from the e164PhoneNumber

exports.getCountryEmoji = getCountryEmoji;
exports.getPhoneHash = function (phoneNumber, salt) {
if (!phoneNumber || !isE164Number(phoneNumber)) {
throw Error('Attempting to hash a non-e164 number: ' + phoneNumber);
}
var prefix = attestations_1.getIdentifierPrefix(attestations_1.IdentifierType.PHONE_NUMBER);
var value = prefix + (salt ? phoneNumber + PHONE_SALT_SEPARATOR + salt : phoneNumber);
return Web3Utils.soliditySha3({ type: 'string', value: value });
};
function getCountryCode(e164PhoneNumber) {

@@ -129,3 +109,3 @@ if (!e164PhoneNumber) {

var phoneDetails = parsePhoneNumber(phoneNumber, defaultCountryCode);
if (phoneDetails && isE164Number(phoneDetails.e164Number)) {
if (phoneDetails && phoneNumbers_1.isE164Number(phoneDetails.e164Number)) {
return phoneDetails.e164Number;

@@ -138,6 +118,2 @@ }

exports.getE164Number = getE164Number;
function isE164Number(phoneNumber) {
return E164_REGEX.test(phoneNumber);
}
exports.isE164Number = isE164Number;
// Actually runs through the parsing instead of using a regex

@@ -236,6 +212,2 @@ function isE164NumberStrict(phoneNumber) {

}
function anonymizedPhone(phoneNumber) {
return phoneNumber.slice(0, -4) + 'XXXX';
}
exports.anonymizedPhone = anonymizedPhone;
function getExampleNumber(regionCode, useOnlyZeroes, isInternational) {

@@ -264,5 +236,5 @@ if (useOnlyZeroes === void 0) { useOnlyZeroes = true; }

getE164Number: getE164Number,
isE164Number: isE164Number,
isE164Number: phoneNumbers_1.isE164Number,
parsePhoneNumber: parsePhoneNumber,
};
//# sourceMappingURL=phoneNumbers.js.map

@@ -1,9 +0,6 @@

export declare const POP_SIZE = 65;
import { NativeSigner, serializeSignature, Signer } from '@celo/base/lib/signatureUtils';
export { NativeSigner, POP_SIZE, serializeSignature, Signature, Signer, } from '@celo/base/lib/signatureUtils';
export declare function hashMessageWithPrefix(message: string): any;
export declare function hashMessage(message: string): string;
export interface Signer {
sign: (message: string) => Promise<string>;
}
export declare function addressToPublicKey(signer: string, signFn: (message: string, signer: string) => Promise<string>): Promise<string>;
export declare function NativeSigner(signFn: (message: string, signer: string) => Promise<string>, signer: string): Signer;
export declare function LocalSigner(privateKey: string): Signer;

@@ -21,8 +18,2 @@ export declare function signedMessageToPublicKey(message: string, v: number, r: string, s: string): string;

};
export interface Signature {
v: number;
r: string;
s: string;
}
export declare function serializeSignature(signature: Signature): string;
export declare function verifySignature(message: string, signature: string, signer: string): boolean;

@@ -29,0 +20,0 @@ export declare function parseSignature(message: string, signature: string, signer: string): {

@@ -58,6 +58,12 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.SignatureUtils = exports.guessSigner = exports.parseSignatureWithoutPrefix = exports.parseSignature = exports.verifySignature = exports.serializeSignature = exports.signMessageWithoutPrefix = exports.signMessage = exports.signedMessageToPublicKey = exports.LocalSigner = exports.NativeSigner = exports.addressToPublicKey = exports.hashMessage = exports.hashMessageWithPrefix = exports.POP_SIZE = void 0;
exports.SignatureUtils = exports.guessSigner = exports.parseSignatureWithoutPrefix = exports.parseSignature = exports.verifySignature = exports.signMessageWithoutPrefix = exports.signMessage = exports.signedMessageToPublicKey = exports.LocalSigner = exports.addressToPublicKey = exports.hashMessage = exports.hashMessageWithPrefix = void 0;
var signatureUtils_1 = require("@celo/base/lib/signatureUtils");
var Web3Utils = __importStar(require("web3-utils"));
var address_1 = require("./address");
exports.POP_SIZE = 65;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var signatureUtils_2 = require("@celo/base/lib/signatureUtils");
Object.defineProperty(exports, "NativeSigner", { enumerable: true, get: function () { return signatureUtils_2.NativeSigner; } });
Object.defineProperty(exports, "POP_SIZE", { enumerable: true, get: function () { return signatureUtils_2.POP_SIZE; } });
Object.defineProperty(exports, "serializeSignature", { enumerable: true, get: function () { return signatureUtils_2.serializeSignature; } });
var ethjsutil = require('ethereumjs-util');

@@ -106,14 +112,2 @@ // If messages is a hex, the length of it should be the number of bytes

exports.addressToPublicKey = addressToPublicKey;
// Uses a native function to sign (as signFn), most commonly `web.eth.sign`
function NativeSigner(signFn, signer) {
var _this = this;
return {
sign: function (message) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, signFn(message, signer)];
});
}); },
};
}
exports.NativeSigner = NativeSigner;
function LocalSigner(privateKey) {

@@ -124,3 +118,3 @@ var _this = this;

return __generator(this, function (_a) {
return [2 /*return*/, Promise.resolve(serializeSignature(signMessage(message, privateKey, address_1.privateKeyToAddress(privateKey))))];
return [2 /*return*/, Promise.resolve(signatureUtils_1.serializeSignature(signMessage(message, privateKey, address_1.privateKeyToAddress(privateKey))))];
});

@@ -153,9 +147,2 @@ }); },

exports.signMessageWithoutPrefix = signMessageWithoutPrefix;
function serializeSignature(signature) {
var serializedV = signature.v.toString(16);
var serializedR = signature.r.slice(2);
var serializedS = signature.s.slice(2);
return '0x' + serializedV + serializedR + serializedS;
}
exports.serializeSignature = serializeSignature;
function verifySignature(message, signature, signer) {

@@ -225,3 +212,3 @@ try {

exports.SignatureUtils = {
NativeSigner: NativeSigner,
NativeSigner: signatureUtils_1.NativeSigner,
LocalSigner: LocalSigner,

@@ -232,4 +219,4 @@ signMessage: signMessage,

parseSignatureWithoutPrefix: parseSignatureWithoutPrefix,
serializeSignature: serializeSignature,
serializeSignature: signatureUtils_1.serializeSignature,
};
//# sourceMappingURL=signatureUtils.js.map

@@ -1,4 +0,5 @@

export declare function appendPath(baseUrl: string, path: string): string;
import { appendPath } from '@celo/base/lib/string';
export { appendPath } from '@celo/base/lib/string';
export declare const StringUtils: {
appendPath: typeof appendPath;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringUtils = exports.appendPath = void 0;
function appendPath(baseUrl, path) {
var lastChar = baseUrl[baseUrl.length - 1];
if (lastChar === '/') {
return baseUrl + path;
}
return baseUrl + '/' + path;
}
exports.appendPath = appendPath;
exports.StringUtils = void 0;
var string_1 = require("@celo/base/lib/string");
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var string_2 = require("@celo/base/lib/string");
Object.defineProperty(exports, "appendPath", { enumerable: true, get: function () { return string_2.appendPath; } });
exports.StringUtils = {
appendPath: appendPath,
appendPath: string_1.appendPath,
};
//# sourceMappingURL=string.js.map

@@ -1,53 +0,1 @@

import { Logger } from './logger';
/**
* Represent a running task that can be stopped
*
* Examples: A poller, a watcher.
*/
export interface RunningTask {
/** Flag task to be stopped. Might not be inmediate */
stop(): void;
/** Indicates wether the task is running */
isRunning(): boolean;
}
export interface TaskOptions {
/** Name for the task. To be used in logging messages */
name: string;
/** Logger function */
logger?: Logger;
}
interface RepeatTaskOptions extends TaskOptions {
/** seconds between repetition */
timeInBetweenMS: number;
/** initial delay for first run */
initialDelayMS?: number;
}
export interface RepeatTaskContext {
/** Number of times the task has been executed (starts in 1) */
executionNumber: number;
/** Flag task to be stopped. Might not be inmediate */
stopTask(): void;
}
/**
* Runs an async function eternally until stopped
*
* @param fn function to run
*/
export declare function repeatTask(opts: RepeatTaskOptions, fn: (ctx: RepeatTaskContext) => Promise<void>): RunningTask;
export declare function conditionWatcher(opts: RepeatTaskOptions & {
pollCondition: () => Promise<boolean>;
onSuccess: () => void | Promise<void>;
}): RunningTask;
export interface RunningTaskWithValue<A> extends RunningTask {
onValue(): Promise<A>;
}
export interface RetryTaskOptions<A> extends TaskOptions {
/** seconds between repetition */
timeInBetweenMS: number;
/** Maximum number of attemps */
maxAttemps: number;
/** Function that tries to obtain a value A or returns null */
tryGetValue: () => Promise<A | null>;
}
export declare function tryObtainValueWithRetries<A>(opts: RetryTaskOptions<A>): RunningTaskWithValue<A>;
export {};
export { conditionWatcher, repeatTask, RepeatTaskContext, RetryTaskOptions, RunningTask, RunningTaskWithValue, TaskOptions, tryObtainValueWithRetries, } from '@celo/base/lib/task';
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
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());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.tryObtainValueWithRetries = exports.conditionWatcher = exports.repeatTask = void 0;
var future_1 = require("./future");
var logger_1 = require("./logger");
/**
* Given task options, creates the task logger
*
* It will prefix taskName to the logs
*/
var createTaskLogger = function (opts) {
if (opts.logger) {
return logger_1.prefixLogger(opts.name, opts.logger);
}
else {
return logger_1.noopLogger;
}
};
/**
* Runs an async function eternally until stopped
*
* @param fn function to run
*/
function repeatTask(opts, fn) {
var _this = this;
var logger = createTaskLogger(opts);
var isActive = true;
var ctx = {
executionNumber: 0,
stopTask: function () {
isActive = false;
},
};
var loop = function () { return __awaiter(_this, void 0, void 0, function () {
var err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!isActive) {
return [2 /*return*/];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, 4, 5]);
ctx.executionNumber++;
return [4 /*yield*/, fn(ctx)];
case 2:
_a.sent();
return [3 /*break*/, 5];
case 3:
err_1 = _a.sent();
logger("Failed with error: " + err_1.message);
logger(err_1);
return [3 /*break*/, 5];
case 4:
if (isActive) {
setTimeout(loop, opts.timeInBetweenMS);
}
return [7 /*endfinally*/];
case 5: return [2 /*return*/];
}
});
}); };
if (opts.initialDelayMS != null) {
setTimeout(loop, opts.initialDelayMS);
}
else {
// tslint:disable-next-line: no-floating-promises
loop();
}
return {
stop: ctx.stopTask,
isRunning: function () {
return isActive;
},
};
}
exports.repeatTask = repeatTask;
function conditionWatcher(opts) {
var _this = this;
return repeatTask(opts, function (ctx) { return __awaiter(_this, void 0, void 0, function () {
var val;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, opts.pollCondition()];
case 1:
val = _a.sent();
if (!val) return [3 /*break*/, 3];
ctx.stopTask();
return [4 /*yield*/, opts.onSuccess()];
case 2:
_a.sent();
_a.label = 3;
case 3: return [2 /*return*/];
}
});
}); });
}
exports.conditionWatcher = conditionWatcher;
function tryObtainValueWithRetries(opts) {
var _this = this;
var futureValue = new future_1.Future();
var task = repeatTask(opts, function (ctx) { return __awaiter(_this, void 0, void 0, function () {
var val;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(ctx.executionNumber > opts.maxAttemps)) return [3 /*break*/, 1];
ctx.stopTask();
futureValue.reject(new Error('Max Retries & no value'));
return [3 /*break*/, 3];
case 1: return [4 /*yield*/, opts.tryGetValue()];
case 2:
val = _a.sent();
if (val != null) {
futureValue.resolve(val);
ctx.stopTask();
}
_a.label = 3;
case 3: return [2 /*return*/];
}
});
}); });
return __assign(__assign({}, task), { stop: function () {
task.stop();
futureValue.reject(new Error('Cancelled'));
}, onValue: function () { return futureValue.asPromise(); } });
}
exports.tryObtainValueWithRetries = tryObtainValueWithRetries;
// Exports moved to @celo/base, forwarding them
// here for backwards compatibility
var task_1 = require("@celo/base/lib/task");
Object.defineProperty(exports, "conditionWatcher", { enumerable: true, get: function () { return task_1.conditionWatcher; } });
Object.defineProperty(exports, "repeatTask", { enumerable: true, get: function () { return task_1.repeatTask; } });
Object.defineProperty(exports, "tryObtainValueWithRetries", { enumerable: true, get: function () { return task_1.tryObtainValueWithRetries; } });
//# sourceMappingURL=task.js.map
{
"name": "@celo/utils",
"version": "0.1.17",
"version": "0.1.18",
"description": "Celo common utils",

@@ -21,2 +21,3 @@ "author": "Celo",

"dependencies": {
"@celo/base": "0.0.1",
"@umpirsky/country-list": "git://github.com/umpirsky/country-list#05fda51",

@@ -35,8 +36,12 @@ "bigi": "^1.1.0",

"google-libphonenumber": "^3.2.4",
"io-ts": "2.0.1",
"fp-ts": "2.1.1",
"keccak256": "^1.0.0",
"lodash": "^4.17.14",
"numeral": "^2.0.6",
"web3-eth-abi": "1.2.4",
"web3-utils": "1.2.4"
},
"devDependencies": {
"@celo/flake-tracker": "0.0.1-dev",
"@celo/typescript": "0.0.1",

@@ -43,0 +48,0 @@ "@types/country-data": "^0.0.0",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc