deth
Version:
Ethereum node focused on Developer Experience
44 lines (43 loc) • 1.71 kB
JavaScript
import * as t from 'io-ts';
import { map } from 'fp-ts/lib/Either';
import { makeQuantity, makeHexData, makeHash, makeAddress } from '../../primitives';
const mapCodec = (type, mapInput, mapOutput) => new t.Type(type.name, type.is, (i, c) => mapInput(type.validate(i, c)), a => mapOutput(type.encode(a))); // @TODO: without any I can't get compiler to accept this type...
export const quantity = codecFromMake(makeQuantity);
export const hexData = codecFromMake(makeHexData);
export const hash = codecFromMake(makeHash);
export const address = codecFromMake(makeAddress);
const toNull = (x) => (x !== null && x !== void 0 ? x : null);
const toUndefined = (x) => (x !== null && x !== void 0 ? x : undefined);
// automatically deals with null/undefined conversions across the RPC <-> our code boundary
// decodes: null and undefined to undefined
// encodes undefined to nulls
export const undefinable = (type) => mapCodec(t.union([type, t.null, t.undefined]), map(toUndefined), toNull);
function codecFromMake(make) {
return new t.Type('RPC_QUANTITY', checkFromMake(make), validateFromMake(make), make);
}
function checkFromMake(make) {
return (value) => {
if (typeof value !== 'string') {
return false;
}
try {
return make(value) === value;
}
catch (_a) {
return false;
}
};
}
function validateFromMake(make) {
return (value, c) => {
if (typeof value !== 'string') {
return t.failure('Value is not a string', c);
}
try {
return t.success(make(value));
}
catch (e) {
return t.failure(`Can't parse "${value}"`, c);
}
};
}