Socket
Socket
Sign inDemoInstall

ripple-binary-codec

Package Overview
Dependencies
Maintainers
6
Versions
86
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ripple-binary-codec - npm Package Compare versions

Comparing version 1.1.3 to 1.1.4-beta.0

test/fixtures/nf-token.json

12

dist/binary.d.ts

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

import { BinaryParser } from "./serdes/binary-parser";
import { AccountID } from "./types/account-id";
import { BinarySerializer, BytesList } from "./serdes/binary-serializer";
import { sha512Half, transactionID } from "./hashes";
import { JsonObject } from "./types/serialized-type";
import { Buffer } from "buffer/";
import { BinaryParser } from './serdes/binary-parser';
import { AccountID } from './types/account-id';
import { BinarySerializer, BytesList } from './serdes/binary-serializer';
import { sha512Half, transactionID } from './hashes';
import { JsonObject } from './types/serialized-type';
import { Buffer } from 'buffer/';
/**

@@ -8,0 +8,0 @@ * Construct a BinaryParser

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

import { Field, TransactionType, LedgerEntryType, Type, TransactionResult } from "./enums";
import * as types from "./types";
import * as binary from "./binary";
import { ShaMap } from "./shamap";
import * as ledgerHashes from "./ledger-hashes";
import * as hashes from "./hashes";
import { quality } from "./quality";
import { HashPrefix } from "./hash-prefixes";
import { Field, TransactionType, LedgerEntryType, Type, TransactionResult } from './enums';
import * as types from './types';
import * as binary from './binary';
import { ShaMap } from './shamap';
import * as ledgerHashes from './ledger-hashes';
import * as hashes from './hashes';
import { quality } from './quality';
import { HashPrefix } from './hash-prefixes';
export { hashes, binary, ledgerHashes, Field, TransactionType, LedgerEntryType, Type, TransactionResult, quality, HashPrefix, ShaMap, types, };

@@ -43,3 +43,4 @@ {

"Contract": 99,
"GeneratorMap": 103,
"NFTokenPage": 80,
"NFTokenOffer": 55,
"NegativeUNL": 78

@@ -99,2 +100,12 @@ },

[
"TransferFee",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt16"
}
],
[
"Flags",

@@ -630,2 +641,12 @@ {

[
"TokenID",
{
"nth": 10,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"BookDirectory",

@@ -901,3 +922,3 @@ {

[
"Generator",
"URI",
{

@@ -1142,2 +1163,12 @@ "nth": 5,

[
"Minter",
{
"nth": 9,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"ObjectEndMarker",

@@ -1253,2 +1284,12 @@ {

[
"NonFungibleToken",
{
"nth": 12,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"Signer",

@@ -1364,2 +1405,12 @@ {

[
"NonFungibleTokens",
{
"nth": 10,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"Majorities",

@@ -1495,2 +1546,12 @@ {

[
"TokenIDs",
{
"nth": 4,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Vector256"
}
],
[
"Transaction",

@@ -1566,2 +1627,32 @@ {

[
"TokenTaxon",
{
"nth": 42,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"MintedTokens",
{
"nth": 43,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"BurnedTokens",
{
"nth": 44,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"Channel",

@@ -1597,2 +1688,52 @@ {

[
"ValidatedHash",
{
"nth": 25,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"PreviousPageMin",
{
"nth": 26,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"NextPageMin",
{
"nth": 27,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"BuyOffer",
{
"nth": 28,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"SellOffer",
{
"nth": 29,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"TickSize",

@@ -1626,2 +1767,32 @@ {

}
],
[
"Cookie",
{
"nth": 10,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"ServerVersion",
{
"nth": 11,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"OfferNode",
{
"nth": 12,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
]

@@ -1751,3 +1922,14 @@ ],

"tecHAS_OBLIGATIONS": 151,
"tecTOO_SOON": 152
"tecTOO_SOON": 152,
"tecMAX_SEQUENCE_REACHED": 154,
"tecNO_SUITABLE_PAGE": 155,
"tecBUY_SELL_MISMATCH": 156,
"tecOFFER_TYPE_MISMATCH": 157,
"tecCANT_ACCEPT_OWN_OFFER": 158,
"tecINSUFFICIENT_FUNDS": 159,
"tecOBJECT_NOT_FOUND": 160,
"tecINSUFFICIENT_PAYMENT": 161,
"tecINCORRECT_ASSET": 162,
"tecTOO_MANY": 163
},

@@ -1779,3 +1961,7 @@ "TRANSACTION_TYPES": {

"AccountDelete": 21,
"NFTokenMint": 25,
"NFTokenBurn": 26,
"NFTokenCreateOffer": 27,
"NFTokenCancelOffer": 28,
"NFTokenAcceptOffer": 29,
"EnableAmendment": 100,

@@ -1782,0 +1968,0 @@ "SetFee": 101,

@@ -1,11 +0,12 @@

import { SerializedType } from "../types/serialized-type";
import { Buffer } from "buffer/";
declare class Bytes {
import { SerializedType } from '../types/serialized-type';
import { Buffer } from 'buffer/';
import { BytesList } from '../binary';
export declare class Bytes {
readonly name: string;
readonly ordinal: number;
readonly ordinalWidth: number;
readonly bytes: Uint8Array;
readonly bytes: Buffer;
constructor(name: string, ordinal: number, ordinalWidth: number);
toJSON(): string;
toBytesSink(sink: any): void;
toBytesSink(sink: BytesList): void;
toBytes(): Uint8Array;

@@ -12,0 +13,0 @@ }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransactionType = exports.TransactionResult = exports.LedgerEntryType = exports.Type = exports.Field = void 0;
exports.TransactionType = exports.TransactionResult = exports.LedgerEntryType = exports.Type = exports.Field = exports.Bytes = void 0;
var enums = require("./definitions.json");

@@ -56,2 +56,3 @@ var serialized_type_1 = require("../types/serialized-type");

}());
exports.Bytes = Bytes;
/*

@@ -58,0 +59,0 @@ * @brief: Collection of Bytes objects, mapping bidirectionally

@@ -102,3 +102,3 @@ "use strict";

var startingFromTecDIRFULL = 121;
var previousKey = "tem";
var previousKey = 'tem';
Object.keys(input).forEach(function (key) {

@@ -109,16 +109,16 @@ if (key.substring(0, 3) !== previousKey.substring(0, 3)) {

}
if (key.substring(0, 3) === "tem") {
if (key.substring(0, 3) === 'tem') {
console.log(" \"" + key + "\": " + startingFromTemBADSENDXRPPATHS++ + ",");
}
else if (key.substring(0, 3) === "tef") {
else if (key.substring(0, 3) === 'tef') {
console.log(" \"" + key + "\": " + startingFromTefFAILURE++ + ",");
}
else if (key.substring(0, 3) === "ter") {
else if (key.substring(0, 3) === 'ter') {
console.log(" \"" + key + "\": " + startingFromTerRETRY++ + ",");
}
else if (key.substring(0, 3) === "tes") {
else if (key.substring(0, 3) === 'tes') {
console.log(" \"" + key + "\": " + tesSUCCESS + ",");
}
else if (key.substring(0, 3) === "tec") {
if (key === "tecDIR_FULL") {
else if (key.substring(0, 3) === 'tec') {
if (key === 'tecDIR_FULL') {
startingFromTecCLAIM = startingFromTecDIRFULL;

@@ -125,0 +125,0 @@ }

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

import { Buffer } from "buffer/";
import { Buffer } from 'buffer/';
/**

@@ -3,0 +3,0 @@ * Maps HashPrefix names to their byte representation

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

import { Hash256 } from "./types/hash-256";
import { BytesList } from "./serdes/binary-serializer";
import { Buffer } from "buffer/";
import { Hash256 } from './types/hash-256';
import { BytesList } from './serdes/binary-serializer';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Class for hashing with SHA512

@@ -21,2 +21,3 @@ "use strict";

var binary_serializer_1 = require("./serdes/binary-serializer");
var buffer_1 = require("buffer/");
/**

@@ -30,3 +31,3 @@ * Class for hashing with SHA512

var _this = _super !== null && _super.apply(this, arguments) || this;
_this.hash = createHash("sha512");
_this.hash = createHash('sha512');
return _this;

@@ -59,4 +60,3 @@ }

Sha512Half.prototype.finish256 = function () {
var bytes = this.hash.digest();
return bytes.slice(0, 32);
return buffer_1.Buffer.from(this.hash.digest().slice(0, 32));
};

@@ -63,0 +63,0 @@ /**

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

import { decodeLedgerData } from "./ledger-hashes";
import { JsonObject } from "./types/serialized-type";
import { decodeLedgerData } from './ledger-hashes';
import { JsonObject } from './types/serialized-type';
/**

@@ -4,0 +4,0 @@ * Decode a transaction

@@ -13,3 +13,3 @@ "use strict";

function decode(binary) {
assert(typeof binary === "string", "binary must be a hex string");
assert.ok(typeof binary === 'string', 'binary must be a hex string');
return binaryToJSON(binary);

@@ -24,5 +24,5 @@ }

function encode(json) {
assert(typeof json === "object");
assert.ok(typeof json === 'object');
return serializeObject(json)
.toString("hex")
.toString('hex')
.toUpperCase();

@@ -38,5 +38,5 @@ }

function encodeForSigning(json) {
assert(typeof json === "object");
assert.ok(typeof json === 'object');
return signingData(json)
.toString("hex")
.toString('hex')
.toUpperCase();

@@ -52,5 +52,5 @@ }

function encodeForSigningClaim(json) {
assert(typeof json === "object");
assert.ok(typeof json === 'object');
return signingClaimData(json)
.toString("hex")
.toString('hex')
.toUpperCase();

@@ -66,6 +66,6 @@ }

function encodeForMultisigning(json, signer) {
assert(typeof json === "object");
assert.equal(json["SigningPubKey"], "");
assert.ok(typeof json === 'object');
assert.equal(json['SigningPubKey'], '');
return multiSigningData(json, signer)
.toString("hex")
.toString('hex')
.toUpperCase();

@@ -80,4 +80,4 @@ }

function encodeQuality(value) {
assert(typeof value === "string");
return coretypes_1.quality.encode(value).toString("hex").toUpperCase();
assert.ok(typeof value === 'string');
return coretypes_1.quality.encode(value).toString('hex').toUpperCase();
}

@@ -91,3 +91,3 @@ /**

function decodeQuality(value) {
assert(typeof value === "string");
assert.ok(typeof value === 'string');
return coretypes_1.quality.decode(value).toString();

@@ -94,0 +94,0 @@ }

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

import { Hash256 } from "./types/hash-256";
import { JsonObject } from "./types/serialized-type";
import * as bigInt from "big-integer";
import { Hash256 } from './types/hash-256';
import { JsonObject } from './types/serialized-type';
import * as bigInt from 'big-integer';
/**

@@ -5,0 +5,0 @@ * Function computing the hash of a transaction tree

@@ -35,3 +35,3 @@ "use strict";

function transactionItemizer(json) {
assert(json.hash);
assert.ok(json.hash);
var index = hash_256_1.Hash256.from(json.hash);

@@ -100,4 +100,4 @@ var item = {

hash.put(hash_prefixes_1.HashPrefix.ledgerHeader);
assert(header.parent_close_time !== undefined);
assert(header.close_flags !== undefined);
assert.ok(header.parent_close_time !== undefined);
assert.ok(header.close_flags !== undefined);
uint_32_1.UInt32.from(header.ledger_index).toBytesSink(hash);

@@ -122,3 +122,3 @@ uint_64_1.UInt64.from(bigInt(String(header.total_coins))).toBytesSink(hash);

function decodeLedgerData(binary) {
assert(typeof binary === "string", "binary must be a hex string");
assert.ok(typeof binary === 'string', 'binary must be a hex string');
var parser = new binary_parser_1.BinaryParser(binary);

@@ -125,0 +125,0 @@ return {

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

import { Decimal } from "decimal.js";
import { Buffer } from "buffer/";
import { Decimal } from 'decimal.js';
import { Buffer } from 'buffer/';
/**

@@ -4,0 +4,0 @@ * class for encoding and decoding quality

@@ -35,5 +35,5 @@ "use strict";

quality.decode = function (quality) {
var bytes = buffer_1.Buffer.from(quality, "hex").slice(-8);
var bytes = buffer_1.Buffer.from(quality, 'hex').slice(-8);
var exponent = bytes[0] - 100;
var mantissa = new decimal_js_1.Decimal("0x" + bytes.slice(1).toString("hex"));
var mantissa = new decimal_js_1.Decimal("0x" + bytes.slice(1).toString('hex'));
return mantissa.times("1e" + exponent);

@@ -40,0 +40,0 @@ };

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

import { FieldInstance } from "../enums";
import { SerializedType } from "../types/serialized-type";
import { Buffer } from "buffer/";
import { FieldInstance } from '../enums';
import { SerializedType } from '../types/serialized-type';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * BinaryParser is used to compute fields and values from a HexString

@@ -17,3 +17,3 @@ "use strict";

function BinaryParser(hexBytes) {
this.bytes = buffer_1.Buffer.from(hexBytes, "hex");
this.bytes = buffer_1.Buffer.from(hexBytes, 'hex');
}

@@ -26,3 +26,3 @@ /**

BinaryParser.prototype.peek = function () {
assert(this.bytes.byteLength !== 0);
assert.ok(this.bytes.byteLength !== 0);
return this.bytes[0];

@@ -36,3 +36,3 @@ };

BinaryParser.prototype.skip = function (n) {
assert(n <= this.bytes.byteLength);
assert.ok(n <= this.bytes.byteLength);
this.bytes = this.bytes.slice(n);

@@ -47,3 +47,3 @@ };

BinaryParser.prototype.read = function (n) {
assert(n <= this.bytes.byteLength);
assert.ok(n <= this.bytes.byteLength);
var slice = this.bytes.slice(0, n);

@@ -60,3 +60,3 @@ this.skip(n);

BinaryParser.prototype.readUIntN = function (n) {
assert(0 < n && n <= 4, "invalid n");
assert.ok(0 < n && n <= 4, 'invalid n');
return this.read(n).reduce(function (a, b) { return (a << 8) | b; }) >>> 0;

@@ -107,3 +107,3 @@ };

}
throw new Error("Invalid variable length indicator");
throw new Error('Invalid variable length indicator');
};

@@ -122,3 +122,3 @@ /**

if (type === 0 || type < 16) {
throw new Error("Cannot read FieldOrdinal, type_code out of range");
throw new Error('Cannot read FieldOrdinal, type_code out of range');
}

@@ -129,3 +129,3 @@ }

if (nth === 0 || nth < 16) {
throw new Error("Cannot read FieldOrdinal, field_code out of range");
throw new Error('Cannot read FieldOrdinal, field_code out of range');
}

@@ -132,0 +132,0 @@ }

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

import { FieldInstance } from "../enums";
import { SerializedType } from "../types/serialized-type";
import { Buffer } from "buffer/";
import { FieldInstance } from '../enums';
import { SerializedType } from '../types/serialized-type';
import { Buffer } from 'buffer/';
/**

@@ -74,3 +74,3 @@ * Bytes list is a collection of buffer objects

*/
writeFieldAndValue(field: FieldInstance, value: SerializedType): void;
writeFieldAndValue(field: FieldInstance, value: SerializedType, isUnlModifyWorkaround?: boolean): void;
/**

@@ -81,4 +81,4 @@ * Write a variable length encoded value to the BinarySerializer

*/
writeLengthEncoded(value: SerializedType): void;
writeLengthEncoded(value: SerializedType, isUnlModifyWorkaround?: boolean): void;
}
export { BytesList, BinarySerializer };

@@ -44,3 +44,3 @@ "use strict";

BytesList.prototype.toHex = function () {
return this.toBytes().toString("hex").toUpperCase();
return this.toBytes().toString('hex').toUpperCase();
};

@@ -115,3 +115,3 @@ return BytesList;

}
throw new Error("Overflow error");
throw new Error('Overflow error');
};

@@ -124,9 +124,10 @@ /**

*/
BinarySerializer.prototype.writeFieldAndValue = function (field, value) {
BinarySerializer.prototype.writeFieldAndValue = function (field, value, isUnlModifyWorkaround) {
if (isUnlModifyWorkaround === void 0) { isUnlModifyWorkaround = false; }
var associatedValue = field.associatedType.from(value);
assert(associatedValue.toBytesSink !== undefined);
assert(field.name !== undefined);
assert.ok(associatedValue.toBytesSink !== undefined);
assert.ok(field.name !== undefined);
this.sink.put(field.header);
if (field.isVariableLengthEncoded) {
this.writeLengthEncoded(associatedValue);
this.writeLengthEncoded(associatedValue, isUnlModifyWorkaround);
}

@@ -142,5 +143,7 @@ else {

*/
BinarySerializer.prototype.writeLengthEncoded = function (value) {
BinarySerializer.prototype.writeLengthEncoded = function (value, isUnlModifyWorkaround) {
if (isUnlModifyWorkaround === void 0) { isUnlModifyWorkaround = false; }
var bytes = new BytesList();
value.toBytesSink(bytes);
if (!isUnlModifyWorkaround)
value.toBytesSink(bytes);
this.put(this.encodeVariableLength(bytes.getLength()));

@@ -147,0 +150,0 @@ this.writeBytesList(bytes);

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

import { Hash256 } from "./types/hash-256";
import { BytesList } from "./serdes/binary-serializer";
import { Buffer } from "buffer/";
import { Hash256 } from './types/hash-256';
import { BytesList } from './serdes/binary-serializer';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Abstract class describing a SHAMapNode

@@ -167,3 +167,3 @@ "use strict";

ShaMapInner.prototype.addItem = function (index, item, leaf) {
assert_1.strict(index !== undefined);
assert_1.strict.ok(index !== undefined);
var nibble = index.nibblet(this.depth);

@@ -184,3 +184,3 @@ var existing = this.branches[nibble];

else {
throw new Error("invalid ShaMap.addItem call");
throw new Error('invalid ShaMap.addItem call');
}

@@ -187,0 +187,0 @@ };

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

import { Hash160 } from "./hash-160";
import { Buffer } from "buffer/";
import { Hash160 } from './hash-160';
import { Buffer } from 'buffer/';
/**

@@ -4,0 +4,0 @@ * Class defining how to encode and decode an AccountID

@@ -39,11 +39,11 @@ "use strict";

}
if (typeof value === "string") {
if (value === "") {
if (typeof value === 'string') {
if (value === '') {
return new AccountID();
}
return HEX_REGEX.test(value)
? new AccountID(buffer_1.Buffer.from(value, "hex"))
? new AccountID(buffer_1.Buffer.from(value, 'hex'))
: this.fromBase58(value);
}
throw new Error("Cannot construct AccountID from value given");
throw new Error('Cannot construct AccountID from value given');
};

@@ -60,3 +60,3 @@ /**

if (classic.tag !== false)
throw new Error("Only allowed to have tag on Account or Destination");
throw new Error('Only allowed to have tag on Account or Destination');
value = classic.classicAddress;

@@ -63,0 +63,0 @@ }

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

import { BinaryParser } from "../serdes/binary-parser";
import { JsonObject, SerializedType } from "./serialized-type";
import { Buffer } from "buffer/";
import { BinaryParser } from '../serdes/binary-parser';
import { JsonObject, SerializedType } from './serialized-type';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Interface for JSON objects that represent amounts

@@ -30,4 +30,4 @@ "use strict";

var MAX_IOU_PRECISION = 16;
var MAX_DROPS = new decimal_js_1.Decimal("1e17");
var MIN_XRP = new decimal_js_1.Decimal("1e-6");
var MAX_DROPS = new decimal_js_1.Decimal('1e17');
var MIN_XRP = new decimal_js_1.Decimal('1e-6');
var mask = bigInt(0x00000000ffffffff);

@@ -47,5 +47,5 @@ /**

return (keys.length === 3 &&
keys[0] === "currency" &&
keys[1] === "issuer" &&
keys[2] === "value");
keys[0] === 'currency' &&
keys[1] === 'issuer' &&
keys[2] === 'value');
}

@@ -72,3 +72,3 @@ /**

var amount = buffer_1.Buffer.alloc(8);
if (typeof value === "string") {
if (typeof value === 'string') {
Amount.assertXrpIsValid(value);

@@ -112,3 +112,3 @@ var number = bigInt(value);

}
throw new Error("Invalid type to construct an Amount");
throw new Error('Invalid type to construct an Amount');
};

@@ -135,3 +135,3 @@ /**

var isPositive = bytes[0] & 0x40;
var sign = isPositive ? "" : "-";
var sign = isPositive ? '' : '-';
bytes[0] &= 0x3f;

@@ -151,7 +151,7 @@ var msb = bigInt(bytes.slice(0, 4).readUInt32BE(0));

var isPositive = b1 & 0x40;
var sign = isPositive ? "" : "-";
var sign = isPositive ? '' : '-';
var exponent = ((b1 & 0x3f) << 2) + ((b2 & 0xff) >> 6) - 97;
mantissa[0] = 0;
mantissa[1] &= 0x3f;
var value = new decimal_js_1.Decimal(sign + "0x" + mantissa.toString("hex")).times("1e" + exponent);
var value = new decimal_js_1.Decimal(sign + "0x" + mantissa.toString('hex')).times("1e" + exponent);
Amount.assertIouIsValid(value);

@@ -172,3 +172,3 @@ return {

Amount.assertXrpIsValid = function (amount) {
if (amount.indexOf(".") !== -1) {
if (amount.indexOf('.') !== -1) {
throw new Error(amount.toString() + " is an illegal amount");

@@ -196,3 +196,3 @@ }

e < MIN_IOU_EXPONENT) {
throw new Error("Decimal precision out of range");
throw new Error('Decimal precision out of range');
}

@@ -214,4 +214,4 @@ this.verifyNoDecimal(decimal);

.toString();
if (integerNumberString.indexOf(".") !== -1) {
throw new Error("Decimal place found in integerNumberString");
if (integerNumberString.indexOf('.') !== -1) {
throw new Error('Decimal place found in integerNumberString');
}

@@ -227,3 +227,3 @@ };

};
Amount.defaultAmount = new Amount(buffer_1.Buffer.from("4000000000000000", "hex"));
Amount.defaultAmount = new Amount(buffer_1.Buffer.from('4000000000000000', 'hex'));
return Amount;

@@ -230,0 +230,0 @@ }(serialized_type_1.SerializedType));

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

import { SerializedType } from "./serialized-type";
import { BinaryParser } from "../serdes/binary-parser";
import { Buffer } from "buffer/";
import { SerializedType } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Variable length encoded type

@@ -47,6 +47,6 @@ "use strict";

}
if (typeof value === "string") {
return new Blob(buffer_1.Buffer.from(value, "hex"));
if (typeof value === 'string') {
return new Blob(buffer_1.Buffer.from(value, 'hex'));
}
throw new Error("Cannot construct Blob from value given");
throw new Error('Cannot construct Blob from value given');
};

@@ -53,0 +53,0 @@ return Blob;

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

import { Hash160 } from "./hash-160";
import { Buffer } from "buffer/";
import { Hash160 } from './hash-160';
import { Buffer } from 'buffer/';
/**

@@ -8,17 +8,10 @@ * Class defining how to encode and decode Currencies

static readonly XRP: Currency;
private readonly _iso?;
private readonly _isNative;
private readonly _iso;
constructor(byteBuf: Buffer);
/**
* Tells if this currency is native
*
* @returns true if native, false if not
*/
isNative(): boolean;
/**
* Return the ISO code of this currency
*
* @returns ISO code if it exists, else undefined
* @returns ISO code if it exists, else null
*/
iso(): string | undefined;
iso(): string | null;
/**

@@ -25,0 +18,0 @@ * Constructs a Currency object

@@ -26,4 +26,4 @@ "use strict";

var bytes = buffer_1.Buffer.alloc(20);
if (iso !== "XRP") {
var isoBytes = iso.split("").map(function (c) { return c.charCodeAt(0); });
if (iso !== 'XRP') {
var isoBytes = iso.split('').map(function (c) { return c.charCodeAt(0); });
bytes.set(isoBytes, 12);

@@ -37,4 +37,14 @@ }

function isIsoCode(iso) {
return iso.length === 3;
return ISO_REGEX.test(iso);
}
function isoCodeFromHex(code) {
var iso = code.toString();
if (iso === 'XRP') {
throw new Error('Disallowed currency code: to indicate the currency XRP you must use 20 bytes of 0s');
}
if (isIsoCode(iso)) {
return iso;
}
return null;
}
/**

@@ -50,3 +60,3 @@ * Tests if hex is a valid hex-string

function isStringRepresentation(input) {
return isIsoCode(input) || isHex(input);
return input.length === 3 || isHex(input);
}

@@ -74,3 +84,3 @@ /**

}
return input.length === 3 ? isoToBytes(input) : buffer_1.Buffer.from(input, "hex");
return input.length === 3 ? isoToBytes(input) : buffer_1.Buffer.from(input, 'hex');
}

@@ -84,29 +94,18 @@ /**

var _this = _super.call(this, byteBuf !== null && byteBuf !== void 0 ? byteBuf : Currency.XRP.bytes) || this;
var onlyISO = true;
var bytes = _this.bytes;
var code = _this.bytes.slice(12, 15);
var iso = code.toString();
for (var i = bytes.length - 1; i >= 0; i--) {
if (bytes[i] !== 0 && !(i === 12 || i === 13 || i === 14)) {
onlyISO = false;
break;
}
if (_this.bytes[0] !== 0) {
_this._iso = null;
}
var lossLessISO = onlyISO && iso !== "XRP" && ISO_REGEX.test(iso);
_this._isNative = onlyISO && code.toString("hex") === "000000";
_this._iso = _this._isNative ? "XRP" : lossLessISO ? iso : undefined;
else if (code.toString('hex') === '000000') {
_this._iso = 'XRP';
}
else {
_this._iso = isoCodeFromHex(code);
}
return _this;
}
/**
* Tells if this currency is native
*
* @returns true if native, false if not
*/
Currency.prototype.isNative = function () {
return this._isNative;
};
/**
* Return the ISO code of this currency
*
* @returns ISO code if it exists, else undefined
* @returns ISO code if it exists, else null
*/

@@ -125,6 +124,6 @@ Currency.prototype.iso = function () {

}
if (typeof value === "string") {
if (typeof value === 'string') {
return new Currency(bytesFromRepresentation(value));
}
throw new Error("Cannot construct Currency from value given");
throw new Error('Cannot construct Currency from value given');
};

@@ -138,6 +137,6 @@ /**

var iso = this.iso();
if (iso !== undefined) {
if (iso !== null) {
return iso;
}
return this.bytes.toString("hex").toUpperCase();
return this.bytes.toString('hex').toUpperCase();
};

@@ -144,0 +143,0 @@ Currency.XRP = new Currency(buffer_1.Buffer.alloc(20));

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

import { Hash } from "./hash";
import { Buffer } from "buffer/";
import { Hash } from './hash';
import { Buffer } from 'buffer/';
/**

@@ -4,0 +4,0 @@ * Hash with a width of 128 bits

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

import { Hash } from "./hash";
import { Buffer } from "buffer/";
import { Hash } from './hash';
import { Buffer } from 'buffer/';
/**

@@ -4,0 +4,0 @@ * Hash with a width of 160 bits

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

import { Hash } from "./hash";
import { Buffer } from "buffer/";
import { Hash } from './hash';
import { Buffer } from 'buffer/';
/**

@@ -4,0 +4,0 @@ * Hash with a width of 256 bits

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

import { Comparable } from "./serialized-type";
import { BinaryParser } from "../serdes/binary-parser";
import { Buffer } from "buffer/";
import { Comparable } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Base class defining how to encode and decode hashes

@@ -40,6 +40,6 @@ "use strict";

}
if (typeof value === "string") {
return new this(buffer_1.Buffer.from(value, "hex"));
if (typeof value === 'string') {
return new this(buffer_1.Buffer.from(value, 'hex'));
}
throw new Error("Cannot construct Hash from given value");
throw new Error('Cannot construct Hash from given value');
};

@@ -46,0 +46,0 @@ /**

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

import { AccountID } from "./account-id";
import { Amount } from "./amount";
import { Blob } from "./blob";
import { Currency } from "./currency";
import { Hash128 } from "./hash-128";
import { Hash160 } from "./hash-160";
import { Hash256 } from "./hash-256";
import { PathSet } from "./path-set";
import { STArray } from "./st-array";
import { STObject } from "./st-object";
import { UInt16 } from "./uint-16";
import { UInt32 } from "./uint-32";
import { UInt64 } from "./uint-64";
import { UInt8 } from "./uint-8";
import { Vector256 } from "./vector-256";
import { AccountID } from './account-id';
import { Amount } from './amount';
import { Blob } from './blob';
import { Currency } from './currency';
import { Hash128 } from './hash-128';
import { Hash160 } from './hash-160';
import { Hash256 } from './hash-256';
import { PathSet } from './path-set';
import { STArray } from './st-array';
import { STObject } from './st-object';
import { UInt16 } from './uint-16';
import { UInt32 } from './uint-32';
import { UInt64 } from './uint-64';
import { UInt8 } from './uint-8';
import { Vector256 } from './vector-256';
declare const coreTypes: {

@@ -17,0 +17,0 @@ AccountID: typeof AccountID;

@@ -41,5 +41,5 @@ "use strict";

});
enums_1.Field["TransactionType"].associatedType = enums_1.TransactionType;
enums_1.Field["TransactionResult"].associatedType = enums_1.TransactionResult;
enums_1.Field["LedgerEntryType"].associatedType = enums_1.LedgerEntryType;
enums_1.Field['TransactionType'].associatedType = enums_1.TransactionType;
enums_1.Field['TransactionResult'].associatedType = enums_1.TransactionResult;
enums_1.Field['LedgerEntryType'].associatedType = enums_1.LedgerEntryType;
//# sourceMappingURL=index.js.map

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

import { BinaryParser } from "../serdes/binary-parser";
import { SerializedType, JsonObject } from "./serialized-type";
import { BinaryParser } from '../serdes/binary-parser';
import { SerializedType, JsonObject } from './serialized-type';
/**

@@ -4,0 +4,0 @@ * The object representation of a Hop, an issuer AccountID, an account AccountID, and a Currency

@@ -108,3 +108,3 @@ "use strict";

Hop.prototype.toJSON = function () {
var hopParser = new binary_parser_1.BinaryParser(this.bytes.toString("hex"));
var hopParser = new binary_parser_1.BinaryParser(this.bytes.toString('hex'));
var type = hopParser.readUInt8();

@@ -226,3 +226,3 @@ var account, currency, issuer;

}
throw new Error("Cannot construct PathSet from given value");
throw new Error('Cannot construct PathSet from given value');
};

@@ -229,0 +229,0 @@ /**

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

import { BytesList } from "../serdes/binary-serializer";
import { BinaryParser } from "../serdes/binary-parser";
import * as bigInt from "big-integer";
import { Buffer } from "buffer/";
import { BytesList } from '../serdes/binary-serializer';
import { BinaryParser } from '../serdes/binary-parser';
import * as bigInt from 'big-integer';
import { Buffer } from 'buffer/';
declare type JSON = string | number | boolean | null | undefined | JSON[] | JsonObject;

@@ -6,0 +6,0 @@ declare type JsonObject = {

@@ -28,7 +28,7 @@ "use strict";

SerializedType.fromParser = function (parser, hint) {
throw new Error("fromParser not implemented");
throw new Error('fromParser not implemented');
return this.fromParser(parser, hint);
};
SerializedType.from = function (value) {
throw new Error("from not implemented");
throw new Error('from not implemented');
return this.from(value);

@@ -50,3 +50,3 @@ };

SerializedType.prototype.toHex = function () {
return this.toBytes().toString("hex").toUpperCase();
return this.toBytes().toString('hex').toUpperCase();
};

@@ -53,0 +53,0 @@ /**

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

import { SerializedType, JsonObject } from "./serialized-type";
import { BinaryParser } from "../serdes/binary-parser";
import { SerializedType, JsonObject } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
/**

@@ -4,0 +4,0 @@ * Class for serializing and deserializing Arrays of Objects

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

var ARRAY_END_MARKER = buffer_1.Buffer.from([0xf1]);
var ARRAY_END_MARKER_NAME = "ArrayEndMarker";
var ARRAY_END_MARKER_NAME = 'ArrayEndMarker';
var OBJECT_END_MARKER = buffer_1.Buffer.from([0xe1]);

@@ -29,3 +29,3 @@ /**

function isObjects(args) {
return (Array.isArray(args) && (args.length === 0 || typeof args[0] === "object"));
return (Array.isArray(args) && (args.length === 0 || typeof args[0] === 'object'));
}

@@ -76,3 +76,3 @@ /**

}
throw new Error("Cannot construct STArray from value given");
throw new Error('Cannot construct STArray from value given');
};

@@ -79,0 +79,0 @@ /**

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

import { SerializedType, JsonObject } from "./serialized-type";
import { BinaryParser } from "../serdes/binary-parser";
import { SerializedType, JsonObject } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
/**

@@ -4,0 +4,0 @@ * Class for Serializing/Deserializing objects

@@ -24,8 +24,8 @@ "use strict";

var OBJECT_END_MARKER_BYTE = buffer_1.Buffer.from([0xe1]);
var OBJECT_END_MARKER = "ObjectEndMarker";
var ST_OBJECT = "STObject";
var DESTINATION = "Destination";
var ACCOUNT = "Account";
var SOURCE_TAG = "SourceTag";
var DEST_TAG = "DestinationTag";
var OBJECT_END_MARKER = 'ObjectEndMarker';
var ST_OBJECT = 'STObject';
var DESTINATION = 'Destination';
var ACCOUNT = 'Account';
var SOURCE_TAG = 'SourceTag';
var DEST_TAG = 'DestinationTag';
/**

@@ -59,5 +59,5 @@ * Break down an X-Address into an account and a tag

if (!(obj1[SOURCE_TAG] === undefined || obj2[SOURCE_TAG] === undefined))
throw new Error("Cannot have Account X-Address and SourceTag");
throw new Error('Cannot have Account X-Address and SourceTag');
if (!(obj1[DEST_TAG] === undefined || obj2[DEST_TAG] === undefined))
throw new Error("Cannot have Destination X-Address and DestinationTag");
throw new Error('Cannot have Destination X-Address and DestinationTag');
}

@@ -107,2 +107,3 @@ /**

var bytes = new binary_serializer_1.BinarySerializer(list);
var isUnlModify = false;
var xAddressDecoded = Object.entries(value).reduce(function (acc, _a) {

@@ -112,4 +113,4 @@ var _b;

var handled = undefined;
if (ripple_address_codec_1.isValidXAddress(val)) {
handled = handleXAddress(key, val);
if (val && ripple_address_codec_1.isValidXAddress(val.toString())) {
handled = handleXAddress(key, val.toString());
checkForDuplicateTags(handled, value);

@@ -134,3 +135,7 @@ }

var associatedValue = field.associatedType.from(xAddressDecoded[field.name]);
bytes.writeFieldAndValue(field, associatedValue);
if (associatedValue.name === 'UNLModify') {
isUnlModify = true;
}
var isUnlModifyWorkaround = field.name == 'Account' && isUnlModify;
bytes.writeFieldAndValue(field, associatedValue, isUnlModifyWorkaround);
if (field.type.name === ST_OBJECT) {

@@ -137,0 +142,0 @@ bytes.put(OBJECT_END_MARKER_BYTE);

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

import { UInt } from "./uint";
import { BinaryParser } from "../serdes/binary-parser";
import { Buffer } from "buffer/";
import { UInt } from './uint';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Derived UInt class for serializing/deserializing 16 bit UInt

@@ -39,3 +39,3 @@ "use strict";

}
if (typeof val === "number") {
if (typeof val === 'number') {
var buf = buffer_1.Buffer.alloc(UInt16.width);

@@ -45,3 +45,3 @@ buf.writeUInt16BE(val, 0);

}
throw new Error("Can not construct UInt16 with given value");
throw new Error('Can not construct UInt16 with given value');
};

@@ -48,0 +48,0 @@ /**

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

import { UInt } from "./uint";
import { BinaryParser } from "../serdes/binary-parser";
import { Buffer } from "buffer/";
import { UInt } from './uint';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Derived UInt class for serializing/deserializing 32 bit UInt

@@ -40,3 +40,3 @@ "use strict";

var buf = buffer_1.Buffer.alloc(UInt32.width);
if (typeof val === "string") {
if (typeof val === 'string') {
var num = Number.parseInt(val);

@@ -46,7 +46,7 @@ buf.writeUInt32BE(num, 0);

}
if (typeof val === "number") {
if (typeof val === 'number') {
buf.writeUInt32BE(val, 0);
return new UInt32(buf);
}
throw new Error("Cannot construct UInt32 from given value");
throw new Error('Cannot construct UInt32 from given value');
};

@@ -53,0 +53,0 @@ /**

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

import { UInt } from "./uint";
import { BinaryParser } from "../serdes/binary-parser";
import * as bigInt from "big-integer";
import { Buffer } from "buffer/";
import { UInt } from './uint';
import { BinaryParser } from '../serdes/binary-parser';
import * as bigInt from 'big-integer';
import { Buffer } from 'buffer/';
/**

@@ -6,0 +6,0 @@ * Derived UInt class for serializing/deserializing 64 bit UInt

@@ -45,5 +45,5 @@ "use strict";

var buf = buffer_1.Buffer.alloc(UInt64.width);
if (typeof val === "number") {
if (typeof val === 'number') {
if (val < 0) {
throw new Error("value must be an unsigned integer");
throw new Error('value must be an unsigned integer');
}

@@ -56,8 +56,8 @@ var number = bigInt(val);

}
if (typeof val === "string") {
if (typeof val === 'string') {
if (!HEX_REGEX.test(val)) {
throw new Error(val + " is not a valid hex-string");
}
var strBuf = val.padStart(16, "0");
buf = buffer_1.Buffer.from(strBuf, "hex");
var strBuf = val.padStart(16, '0');
buf = buffer_1.Buffer.from(strBuf, 'hex');
return new UInt64(buf);

@@ -71,3 +71,3 @@ }

}
throw new Error("Cannot construct UInt64 from given value");
throw new Error('Cannot construct UInt64 from given value');
};

@@ -80,3 +80,3 @@ /**

UInt64.prototype.toJSON = function () {
return this.bytes.toString("hex").toUpperCase();
return this.bytes.toString('hex').toUpperCase();
};

@@ -83,0 +83,0 @@ /**

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

import { UInt } from "./uint";
import { BinaryParser } from "../serdes/binary-parser";
import { Buffer } from "buffer/";
import { UInt } from './uint';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Derived UInt class for serializing/deserializing 8 bit UInt

@@ -39,3 +39,3 @@ "use strict";

}
if (typeof val === "number") {
if (typeof val === 'number') {
var buf = buffer_1.Buffer.alloc(UInt8.width);

@@ -45,3 +45,3 @@ buf.writeUInt8(val, 0);

}
throw new Error("Cannot construct UInt8 from given value");
throw new Error('Cannot construct UInt8 from given value');
};

@@ -48,0 +48,0 @@ /**

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

import * as bigInt from "big-integer";
import { Comparable } from "./serialized-type";
import { Buffer } from "buffer/";
import * as bigInt from 'big-integer';
import { Comparable } from './serialized-type';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Base class for serializing and deserializing unsigned integers.

@@ -52,3 +52,3 @@ "use strict";

var val = this.valueOf();
return typeof val === "number" ? val : val.toString();
return typeof val === 'number' ? val : val.toString();
};

@@ -55,0 +55,0 @@ return UInt;

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

import { SerializedType } from "./serialized-type";
import { BinaryParser } from "../serdes/binary-parser";
import { Buffer } from "buffer/";
import { SerializedType } from './serialized-type';
import { BinaryParser } from '../serdes/binary-parser';
import { Buffer } from 'buffer/';
/**

@@ -5,0 +5,0 @@ * Class for serializing and deserializing vectors of Hash256

@@ -24,3 +24,3 @@ "use strict";

function isStrings(arg) {
return Array.isArray(arg) && (arg.length === 0 || typeof arg[0] === "string");
return Array.isArray(arg) && (arg.length === 0 || typeof arg[0] === 'string');
}

@@ -68,3 +68,3 @@ /**

}
throw new Error("Cannot construct Vector256 from given value");
throw new Error('Cannot construct Vector256 from given value');
};

@@ -78,3 +78,3 @@ /**

if (this.bytes.byteLength % 32 !== 0) {
throw new Error("Invalid bytes for Vector256");
throw new Error('Invalid bytes for Vector256');
}

@@ -85,3 +85,3 @@ var result = [];

.slice(i, i + 32)
.toString("hex")
.toString('hex')
.toUpperCase());

@@ -88,0 +88,0 @@ }

{
"name": "ripple-binary-codec",
"version": "1.1.3",
"version": "1.1.4-beta.0",
"description": "XRP Ledger binary codec",

@@ -58,4 +58,4 @@ "files": [

"node": ">=10.22.0",
"yarn": "^1.22.4"
"npm": ">=7.0.0"
}
}

@@ -1,107 +0,2 @@

# ripple-binary-codec [![NPM](https://img.shields.io/npm/v/ripple-binary-codec.svg)](https://npmjs.org/package/ripple-binary-codec)
Functions to encode/decode to/from the ripple [binary serialization format](https://xrpl.org/serialization.html)
[![NPM](https://nodei.co/npm/ripple-binary-codec.png)](https://www.npmjs.org/package/ripple-binary-codec)
## API
```js
> const api = require('ripple-binary-codec')
```
### decode(binary: string): object
Decode a hex-string into a transaction object.
```js
> api.decode('1100612200000000240000000125000000072D0000000055DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF6240000002540BE4008114D0F5430B66E06498D4CEEC816C7B3337F9982337')
{
LedgerEntryType: 'AccountRoot',
Flags: 0,
Sequence: 1,
PreviousTxnLgrSeq: 7,
OwnerCount: 0,
PreviousTxnID: 'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Balance: '10000000000',
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv'
}
```
### encode(json: object): string
Encode a transaction object into a hex-string. Note that encode filters out fields with undefined values.
```js
> api.encode({
LedgerEntryType: 'AccountRoot',
Flags: 0,
Sequence: 1,
PreviousTxnLgrSeq: 7,
OwnerCount: 0,
PreviousTxnID: 'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Balance: '10000000000',
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv'
})
'1100612200000000240000000125000000072D0000000055DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF6240000002540BE4008114D0F5430B66E06498D4CEEC816C7B3337F9982337'
```
#### X-Address Compatibility
* ripple-binary-codec handles X-addresses by looking for a few specific files (Account/SourceTag, Destination/DestinationTag).
* If other fields (in the future) must to support X-addresses with tags, this library will need to be updated.
* When decoding rippled binary, the output will always output classic address + tag, with no X-addresses. X-address support only applies when encoding to binary.
#### Encoding Currency Codes
* The standard format for currency codes is a three-letter string such as `USD`. This is intended for use with ISO 4217 Currency Codes.
* Currency codes must be exactly 3 ASCII characters in length and there are [a few other rules](https://xrpl.org/currency-formats.html#currency-codes).
* ripple-binary-codec allows any 3-character ASCII string to be encoded as a currency code, although rippled may enforce tighter restrictions.
* When _decoding_, if a currency code is three uppercase letters or numbers (`/^[A-Z0-9]{3}$/`), then it will be decoded into that string. For example,`0000000000000000000000004142430000000000` decodes as `ABC`.
* When decoding, if a currency code is does not match the regex, then it is not considered to be an ISO 4217 or pseudo-ISO currency. ripple-binary-codec will return a 160-bit hex-string (40 hex characters). For example, `0000000000000000000000006142430000000000` (`aBC`) decodes as `0000000000000000000000006142430000000000` because it contains a lowercase letter.
### encodeForSigning(json: object): string
Encode the transaction object for signing.
### encodeForSigningClaim(json: object): string
Encode the transaction object for payment channel claim.
### encodeForMultisigning(json: object, signer: string): string
Encode the transaction object for multi-signing.
### encodeQuality(value: string): string
```js
> api.encodeQuality('195796912.5171664')
'5D06F4C3362FE1D0'
```
### decodeQuality(value: string): string
```js
> api.decodeQuality('5D06F4C3362FE1D0')
'195796912.5171664'
```
### decodeLedgerData(binary: string): object
```js
> api.decodeLedgerData("01E91435016340767BF1C4A3EACEB081770D8ADE216C85445DD6FB002C6B5A2930F2DECE006DA18150CB18F6DD33F6F0990754C962A7CCE62F332FF9C13939B03B864117F0BDA86B6E9B4F873B5C3E520634D343EF5D9D9A4246643D64DAD278BA95DC0EAC6EB5350CF970D521276CDE21276CE60A00")
{
ledger_index: 32052277,
total_coins: '99994494362043555',
parent_hash: 'EACEB081770D8ADE216C85445DD6FB002C6B5A2930F2DECE006DA18150CB18F6',
transaction_hash: 'DD33F6F0990754C962A7CCE62F332FF9C13939B03B864117F0BDA86B6E9B4F87',
account_hash: '3B5C3E520634D343EF5D9D9A4246643D64DAD278BA95DC0EAC6EB5350CF970D5',
parent_close_time: 556231902,
close_time: 556231910,
close_time_resolution: 10,
close_flags: 0
}
```
## Tests
Run unit tests with:
yarn test
Use `--coverage` to generate and display code coverage information:
yarn test --coverage
This tells jest to output code coverage info in the `./coverage` directory, in addition to showing it on the command line.
## Development Migration
Development of this package has been moved to a mono-repo [xrpl.js](https://github.com/XRPLF/xrpl.js/tree/develop/packages/ripple-binary-codec)

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

const { loadFixture } = require("./utils");
const { coreTypes } = require("../dist/types");
const { Amount } = coreTypes;
const fixtures = loadFixture("data-driven-tests.json");
const { loadFixture } = require('./utils')
const { coreTypes } = require('../dist/types')
const { Amount } = coreTypes
const fixtures = loadFixture('data-driven-tests.json')
function amountErrorTests() {
fixtures.values_tests
.filter((obj) => obj.type === "Amount")
.filter((obj) => obj.type === 'Amount')
.forEach((f) => {
// We only want these with errors
if (!f.error) {
return;
return
}
const testName =
`${JSON.stringify(f.test_json)}\n\tis invalid ` + `because: ${f.error}`;
`${JSON.stringify(f.test_json)}\n\tis invalid ` + `because: ${f.error}`
it(testName, () => {
expect(() => {
Amount.from(f.test_json);
JSON.stringify(f.test_json);
}).toThrow();
});
});
Amount.from(f.test_json)
JSON.stringify(f.test_json)
}).toThrow()
})
})
}
describe("Amount", function () {
it("can be parsed from", function () {
expect(Amount.from("1000000") instanceof Amount).toBe(true);
expect(Amount.from("1000000").toJSON()).toEqual("1000000");
describe('Amount', function () {
it('can be parsed from', function () {
expect(Amount.from('1000000') instanceof Amount).toBe(true)
expect(Amount.from('1000000').toJSON()).toEqual('1000000')
const fixture = {
value: "1",
issuer: "0000000000000000000000000000000000000000",
currency: "USD",
};
const amt = Amount.from(fixture);
value: '1',
issuer: '0000000000000000000000000000000000000000',
currency: 'USD',
}
const amt = Amount.from(fixture)
const rewritten = {
value: "1",
issuer: "rrrrrrrrrrrrrrrrrrrrrhoLvTp",
currency: "USD",
};
expect(amt.toJSON()).toEqual(rewritten);
});
amountErrorTests();
});
value: '1',
issuer: 'rrrrrrrrrrrrrrrrrrrrrhoLvTp',
currency: 'USD',
}
expect(amt.toJSON()).toEqual(rewritten)
})
amountErrorTests()
})

@@ -1,47 +0,45 @@

const fixtures = require("./fixtures/codec-fixtures.json");
const { decode, encode, decodeLedgerData } = require("../dist");
const fixtures = require('./fixtures/codec-fixtures.json')
const { decode, encode, decodeLedgerData } = require('../dist')
function json(object) {
return JSON.stringify(object);
return JSON.stringify(object)
}
function truncateForDisplay(longStr) {
return `${longStr.slice(0, 10)} ... ${longStr.slice(-10)}`;
return `${longStr.slice(0, 10)} ... ${longStr.slice(-10)}`
}
describe("ripple-binary-codec", function () {
describe('ripple-binary-codec', function () {
function makeSuite(name, entries) {
describe(name, function () {
entries.forEach((t, testN) => {
// eslint-disable-next-line max-len
test(`${name}[${testN}] can encode ${truncateForDisplay(
json(t.json)
json(t.json),
)} to ${truncateForDisplay(t.binary)}`, () => {
expect(encode(t.json)).toEqual(t.binary);
});
// eslint-disable-next-line max-len
expect(encode(t.json)).toEqual(t.binary)
})
test(`${name}[${testN}] can decode ${truncateForDisplay(
t.binary
t.binary,
)} to ${truncateForDisplay(json(t.json))}`, () => {
const decoded = decode(t.binary);
expect(decoded).toEqual(t.json);
});
});
});
const decoded = decode(t.binary)
expect(decoded).toEqual(t.json)
})
})
})
}
makeSuite("transactions", fixtures.transactions);
makeSuite("accountState", fixtures.accountState);
makeSuite('transactions', fixtures.transactions)
makeSuite('accountState', fixtures.accountState)
describe("ledgerData", function () {
describe('ledgerData', function () {
if (fixtures.ledgerData) {
fixtures.ledgerData.forEach((t, testN) => {
test(`ledgerData[${testN}] can decode ${t.binary} to ${json(
t.json
t.json,
)}`, () => {
const decoded = decodeLedgerData(t.binary);
expect(t.json).toEqual(decoded);
});
});
const decoded = decodeLedgerData(t.binary)
expect(t.json).toEqual(decoded)
})
})
}
});
});
})
})

@@ -1,51 +0,49 @@

/* eslint-disable func-style */
const { coreTypes } = require('../dist/types')
const Decimal = require('decimal.js')
const { coreTypes } = require("../dist/types");
const Decimal = require("decimal.js");
const { encodeAccountID } = require('ripple-address-codec')
const { binary } = require('../dist/coretypes')
const { Amount, Hash160 } = coreTypes
const { makeParser, readJSON } = binary
const { Field, TransactionType } = require('./../dist/enums')
const { parseHexOnly, hexOnly, loadFixture } = require('./utils')
const fixtures = loadFixture('data-driven-tests.json')
const { BytesList } = require('../dist/serdes/binary-serializer')
const { Buffer } = require('buffer/')
const { encodeAccountID } = require("ripple-address-codec");
const { binary } = require("../dist/coretypes");
const { Amount, Hash160 } = coreTypes;
const { makeParser, readJSON } = binary;
const { Field, TransactionType } = require("./../dist/enums");
const { parseHexOnly, hexOnly, loadFixture } = require("./utils");
const fixtures = loadFixture("data-driven-tests.json");
const { BytesList } = require("../dist/serdes/binary-serializer");
const { Buffer } = require("buffer/");
const __ = hexOnly;
const __ = hexOnly
function toJSON(v) {
return v.toJSON ? v.toJSON() : v;
return v.toJSON ? v.toJSON() : v
}
function assertEqualAmountJSON(actual, expected) {
expect(typeof actual === typeof expected).toBe(true);
if (typeof actual === "string") {
expect(actual).toEqual(expected);
return;
expect(typeof actual === typeof expected).toBe(true)
if (typeof actual === 'string') {
expect(actual).toEqual(expected)
return
}
expect(actual.currency).toEqual(expected.currency);
expect(actual.issuer).toEqual(expected.issuer);
expect(actual.currency).toEqual(expected.currency)
expect(actual.issuer).toEqual(expected.issuer)
expect(
actual.value === expected.value ||
new Decimal(actual.value).equals(new Decimal(expected.value))
).toBe(true);
new Decimal(actual.value).equals(new Decimal(expected.value)),
).toBe(true)
}
function basicApiTests() {
const bytes = parseHexOnly("00,01020304,0506", Uint8Array);
test("can read slices of bytes", () => {
const parser = makeParser(bytes);
expect(parser.bytes instanceof Buffer).toBe(true);
const read1 = parser.read(1);
expect(read1 instanceof Buffer).toBe(true);
expect(read1).toEqual(Buffer.from([0]));
expect(parser.read(4)).toEqual(Buffer.from([1, 2, 3, 4]));
expect(parser.read(2)).toEqual(Buffer.from([5, 6]));
expect(() => parser.read(1)).toThrow();
});
test("can read a Uint32 at full", () => {
const parser = makeParser("FFFFFFFF");
expect(parser.readUInt32()).toEqual(0xffffffff);
});
const bytes = parseHexOnly('00,01020304,0506', Uint8Array)
test('can read slices of bytes', () => {
const parser = makeParser(bytes)
expect(parser.bytes instanceof Buffer).toBe(true)
const read1 = parser.read(1)
expect(read1 instanceof Buffer).toBe(true)
expect(read1).toEqual(Buffer.from([0]))
expect(parser.read(4)).toEqual(Buffer.from([1, 2, 3, 4]))
expect(parser.read(2)).toEqual(Buffer.from([5, 6]))
expect(() => parser.read(1)).toThrow()
})
test('can read a Uint32 at full', () => {
const parser = makeParser('FFFFFFFF')
expect(parser.readUInt32()).toEqual(0xffffffff)
})
}

@@ -56,15 +54,15 @@

json: {
Account: "raD5qJMAShLeHZXf9wjUmo6vRK4arj9cF3",
Fee: "10",
Account: 'raD5qJMAShLeHZXf9wjUmo6vRK4arj9cF3',
Fee: '10',
Flags: 0,
Sequence: 103929,
SigningPubKey:
"028472865AF4CB32AA285834B57576B7290AA8C31B459047DB27E16F418D6A7166",
'028472865AF4CB32AA285834B57576B7290AA8C31B459047DB27E16F418D6A7166',
TakerGets: {
currency: "ILS",
issuer: "rNPRNzBB92BVpAhhZr4iXDTveCgV5Pofm9",
value: "1694.768",
currency: 'ILS',
issuer: 'rNPRNzBB92BVpAhhZr4iXDTveCgV5Pofm9',
value: '1694.768',
},
TakerPays: "98957503520",
TransactionType: "OfferCreate",
TakerPays: '98957503520',
TransactionType: 'OfferCreate',
TxnSignature: __(`

@@ -84,110 +82,110 @@ 304502202ABE08D5E78D1E74A4C18F2714F64E87B8BD57444AF

A69F0895E62149CFCC006FB89FA7D1E6E5D`),
};
}
const tx_json = transaction.json;
const tx_json = transaction.json
// These tests are basically development logs
test("can be done with low level apis", () => {
const parser = makeParser(transaction.binary);
test('can be done with low level apis', () => {
const parser = makeParser(transaction.binary)
expect(parser.readField()).toEqual(Field.TransactionType);
expect(parser.readUInt16()).toEqual(7);
expect(parser.readField()).toEqual(Field.Flags);
expect(parser.readUInt32()).toEqual(0);
expect(parser.readField()).toEqual(Field.Sequence);
expect(parser.readUInt32()).toEqual(103929);
expect(parser.readField()).toEqual(Field.TakerPays);
parser.read(8);
expect(parser.readField()).toEqual(Field.TakerGets);
expect(parser.readField()).toEqual(Field.TransactionType)
expect(parser.readUInt16()).toEqual(7)
expect(parser.readField()).toEqual(Field.Flags)
expect(parser.readUInt32()).toEqual(0)
expect(parser.readField()).toEqual(Field.Sequence)
expect(parser.readUInt32()).toEqual(103929)
expect(parser.readField()).toEqual(Field.TakerPays)
parser.read(8)
expect(parser.readField()).toEqual(Field.TakerGets)
// amount value
expect(parser.read(8)).not.toBe([]);
expect(parser.read(8)).not.toBe([])
// amount currency
expect(Hash160.fromParser(parser)).not.toBe([]);
expect(encodeAccountID(parser.read(20))).toEqual(tx_json.TakerGets.issuer);
expect(parser.readField()).toEqual(Field.Fee);
expect(parser.read(8)).not.toEqual([]);
expect(parser.readField()).toEqual(Field.SigningPubKey);
expect(parser.readVariableLengthLength()).toBe(33);
expect(parser.read(33).toString("hex").toUpperCase()).toEqual(
tx_json.SigningPubKey
);
expect(parser.readField()).toEqual(Field.TxnSignature);
expect(parser.readVariableLength().toString("hex").toUpperCase()).toEqual(
tx_json.TxnSignature
);
expect(parser.readField()).toEqual(Field.Account);
expect(Hash160.fromParser(parser)).not.toBe([])
expect(encodeAccountID(parser.read(20))).toEqual(tx_json.TakerGets.issuer)
expect(parser.readField()).toEqual(Field.Fee)
expect(parser.read(8)).not.toEqual([])
expect(parser.readField()).toEqual(Field.SigningPubKey)
expect(parser.readVariableLengthLength()).toBe(33)
expect(parser.read(33).toString('hex').toUpperCase()).toEqual(
tx_json.SigningPubKey,
)
expect(parser.readField()).toEqual(Field.TxnSignature)
expect(parser.readVariableLength().toString('hex').toUpperCase()).toEqual(
tx_json.TxnSignature,
)
expect(parser.readField()).toEqual(Field.Account)
expect(encodeAccountID(parser.readVariableLength())).toEqual(
tx_json.Account
);
expect(parser.end()).toBe(true);
});
tx_json.Account,
)
expect(parser.end()).toBe(true)
})
test("can be done with high level apis", () => {
const parser = makeParser(transaction.binary);
test('can be done with high level apis', () => {
const parser = makeParser(transaction.binary)
function readField() {
return parser.readFieldAndValue();
return parser.readFieldAndValue()
}
{
const [field, value] = readField();
expect(field).toEqual(Field.TransactionType);
expect(value).toEqual(TransactionType.OfferCreate);
const [field, value] = readField()
expect(field).toEqual(Field.TransactionType)
expect(value).toEqual(TransactionType.OfferCreate)
}
{
const [field, value] = readField();
expect(field).toEqual(Field.Flags);
expect(value.valueOf()).toEqual(0);
const [field, value] = readField()
expect(field).toEqual(Field.Flags)
expect(value.valueOf()).toEqual(0)
}
{
const [field, value] = readField();
expect(field).toEqual(Field.Sequence);
expect(value.valueOf()).toEqual(103929);
const [field, value] = readField()
expect(field).toEqual(Field.Sequence)
expect(value.valueOf()).toEqual(103929)
}
{
const [field, value] = readField();
expect(field).toEqual(Field.TakerPays);
expect(value.isNative()).toEqual(true);
expect(value.toJSON()).toEqual("98957503520");
const [field, value] = readField()
expect(field).toEqual(Field.TakerPays)
expect(value.isNative()).toEqual(true)
expect(value.toJSON()).toEqual('98957503520')
}
{
const [field, value] = readField();
expect(field).toEqual(Field.TakerGets);
expect(value.isNative()).toEqual(false);
expect(value.toJSON().issuer).toEqual(tx_json.TakerGets.issuer);
const [field, value] = readField()
expect(field).toEqual(Field.TakerGets)
expect(value.isNative()).toEqual(false)
expect(value.toJSON().issuer).toEqual(tx_json.TakerGets.issuer)
}
{
const [field, value] = readField();
expect(field).toEqual(Field.Fee);
expect(value.isNative()).toEqual(true);
const [field, value] = readField()
expect(field).toEqual(Field.Fee)
expect(value.isNative()).toEqual(true)
}
{
const [field, value] = readField();
expect(field).toEqual(Field.SigningPubKey);
expect(value.toJSON()).toEqual(tx_json.SigningPubKey);
const [field, value] = readField()
expect(field).toEqual(Field.SigningPubKey)
expect(value.toJSON()).toEqual(tx_json.SigningPubKey)
}
{
const [field, value] = readField();
expect(field).toEqual(Field.TxnSignature);
expect(value.toJSON()).toEqual(tx_json.TxnSignature);
const [field, value] = readField()
expect(field).toEqual(Field.TxnSignature)
expect(value.toJSON()).toEqual(tx_json.TxnSignature)
}
{
const [field, value] = readField();
expect(field).toEqual(Field.Account);
expect(value.toJSON()).toEqual(tx_json.Account);
const [field, value] = readField()
expect(field).toEqual(Field.Account)
expect(value.toJSON()).toEqual(tx_json.Account)
}
expect(parser.end()).toBe(true);
});
expect(parser.end()).toBe(true)
})
test("can be done with higher level apis", () => {
const parser = makeParser(transaction.binary);
const jsonFromBinary = readJSON(parser);
expect(jsonFromBinary).toEqual(tx_json);
});
test('can be done with higher level apis', () => {
const parser = makeParser(transaction.binary)
const jsonFromBinary = readJSON(parser)
expect(jsonFromBinary).toEqual(tx_json)
})
test("readJSON (binary.decode) does not return STObject ", () => {
const parser = makeParser(transaction.binary);
const jsonFromBinary = readJSON(parser);
expect(jsonFromBinary instanceof coreTypes.STObject).toBe(false);
expect(jsonFromBinary instanceof Object).toBe(true);
expect(jsonFromBinary.prototype).toBe(undefined);
});
test('readJSON (binary.decode) does not return STObject ', () => {
const parser = makeParser(transaction.binary)
const jsonFromBinary = readJSON(parser)
expect(jsonFromBinary instanceof coreTypes.STObject).toBe(false)
expect(jsonFromBinary instanceof Object).toBe(true)
expect(jsonFromBinary.prototype).toBe(undefined)
})
}

@@ -197,25 +195,25 @@

fixtures.values_tests
.filter((obj) => obj.type === "Amount")
.filter((obj) => obj.type === 'Amount')
.forEach((f, i) => {
if (f.error) {
return;
return
}
const parser = makeParser(f.expected_hex);
const parser = makeParser(f.expected_hex)
const testName = `values_tests[${i}] parses ${f.expected_hex.slice(
0,
16
16,
)}...
as ${JSON.stringify(f.test_json)}`;
as ${JSON.stringify(f.test_json)}`
test(testName, () => {
const value = parser.readType(Amount);
const value = parser.readType(Amount)
// May not actually be in canonical form. The fixtures are to be used
// also for json -> binary;
const json = toJSON(value);
assertEqualAmountJSON(json, f.test_json);
const json = toJSON(value)
assertEqualAmountJSON(json, f.test_json)
if (f.exponent) {
const exponent = new Decimal(json.value);
expect(exponent.e - 15).toEqual(f.exponent);
const exponent = new Decimal(json.value)
expect(exponent.e - 15).toEqual(f.exponent)
}
});
});
})
})
}

@@ -225,37 +223,37 @@

fixtures.fields_tests.forEach((f, i) => {
const parser = makeParser(f.expected_hex);
const parser = makeParser(f.expected_hex)
test(`fields[${i}]: parses ${f.expected_hex} as ${f.name}`, () => {
const field = parser.readField();
expect(field.name).toEqual(f.name);
expect(field.type.name).toEqual(f.type_name);
});
});
test("Field throws when type code out of range", () => {
const parser = makeParser("0101");
const field = parser.readField()
expect(field.name).toEqual(f.name)
expect(field.type.name).toEqual(f.type_name)
})
})
test('Field throws when type code out of range', () => {
const parser = makeParser('0101')
expect(() => parser.readField()).toThrow(
new Error("Cannot read FieldOrdinal, type_code out of range")
);
});
test("Field throws when field code out of range", () => {
const parser = makeParser("1001");
new Error('Cannot read FieldOrdinal, type_code out of range'),
)
})
test('Field throws when field code out of range', () => {
const parser = makeParser('1001')
expect(() => parser.readFieldOrdinal()).toThrowError(
new Error("Cannot read FieldOrdinal, field_code out of range")
);
});
test("Field throws when both type and field code out of range", () => {
const parser = makeParser("000101");
new Error('Cannot read FieldOrdinal, field_code out of range'),
)
})
test('Field throws when both type and field code out of range', () => {
const parser = makeParser('000101')
expect(() => parser.readFieldOrdinal()).toThrowError(
new Error("Cannot read FieldOrdinal, type_code out of range")
);
});
new Error('Cannot read FieldOrdinal, type_code out of range'),
)
})
}
function assertRecyclable(json, forField) {
const Type = forField.associatedType;
const recycled = Type.from(json).toJSON();
expect(recycled).toEqual(json);
const sink = new BytesList();
Type.from(recycled).toBytesSink(sink);
const recycledAgain = makeParser(sink.toHex()).readType(Type).toJSON();
expect(recycledAgain).toEqual(json);
const Type = forField.associatedType
const recycled = Type.from(json).toJSON()
expect(recycled).toEqual(json)
const sink = new BytesList()
Type.from(recycled).toBytesSink(sink)
const recycledAgain = makeParser(sink.toHex()).readType(Type).toJSON()
expect(recycledAgain).toEqual(json)
}

@@ -267,24 +265,24 @@

${JSON.stringify(
f.tx_json
f.tx_json,
)}`, /* */ () => {
const parser = makeParser(f.blob_with_no_signing);
let ix = 0;
const parser = makeParser(f.blob_with_no_signing)
let ix = 0
while (!parser.end()) {
const [field, value] = parser.readFieldAndValue();
const expected = f.fields[ix];
const expectedJSON = expected[1].json;
const expectedField = expected[0];
const actual = toJSON(value);
const [field, value] = parser.readFieldAndValue()
const expected = f.fields[ix]
const expectedJSON = expected[1].json
const expectedField = expected[0]
const actual = toJSON(value)
try {
expect(actual).toEqual(expectedJSON);
expect(actual).toEqual(expectedJSON)
} catch (e) {
throw new Error(`${e} ${field} a: ${actual} e: ${expectedJSON}`);
throw new Error(`${e} ${field} a: ${actual} e: ${expectedJSON}`)
}
expect(field.name).toEqual(expectedField);
assertRecyclable(actual, field);
ix++;
expect(field.name).toEqual(expectedField)
assertRecyclable(actual, field)
ix++
}
});
});
})
})
}

@@ -321,5 +319,5 @@

180C769B66D942EE69E6DCC940CA48D82337AD10000000000000000000000000
58525000000000003000000000000000000000000055534400000000000A20B3
C85F482532A9578DBB3950B85CA06594D100`
);
00000000000000003000000000000000000000000055534400000000000A20B3
C85F482532A9578DBB3950B85CA06594D100`,
)

@@ -329,19 +327,19 @@ const expectedJSON = [

{
account: "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
currency: "BTC",
issuer: "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
account: 'r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K',
currency: 'BTC',
issuer: 'r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K',
},
{
account: "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo",
currency: "BTC",
issuer: "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo",
account: 'rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo',
currency: 'BTC',
issuer: 'rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo',
},
{
account: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
currency: "BTC",
issuer: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
account: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B',
currency: 'BTC',
issuer: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B',
},
{
currency: "USD",
issuer: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
currency: 'USD',
issuer: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B',
},

@@ -351,19 +349,19 @@ ],

{
account: "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
currency: "BTC",
issuer: "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
account: 'r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K',
currency: 'BTC',
issuer: 'r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K',
},
{
account: "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo",
currency: "BTC",
issuer: "rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo",
account: 'rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo',
currency: 'BTC',
issuer: 'rM1oqKtfh1zgjdAgbFmaRm3btfGBX25xVo',
},
{
account: "rpvfJ4mR6QQAeogpXEKnuyGBx8mYCSnYZi",
currency: "BTC",
issuer: "rpvfJ4mR6QQAeogpXEKnuyGBx8mYCSnYZi",
account: 'rpvfJ4mR6QQAeogpXEKnuyGBx8mYCSnYZi',
currency: 'BTC',
issuer: 'rpvfJ4mR6QQAeogpXEKnuyGBx8mYCSnYZi',
},
{
currency: "USD",
issuer: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
currency: 'USD',
issuer: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B',
},

@@ -373,35 +371,35 @@ ],

{
account: "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
currency: "BTC",
issuer: "r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K",
account: 'r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K',
currency: 'BTC',
issuer: 'r9hEDb4xBGRfBCcX3E4FirDWQBAYtpxC8K',
},
{
account: "r3AWbdp2jQLXLywJypdoNwVSvr81xs3uhn",
currency: "BTC",
issuer: "r3AWbdp2jQLXLywJypdoNwVSvr81xs3uhn",
account: 'r3AWbdp2jQLXLywJypdoNwVSvr81xs3uhn',
currency: 'BTC',
issuer: 'r3AWbdp2jQLXLywJypdoNwVSvr81xs3uhn',
},
{ currency: "0000000000000000000000005852500000000000" },
{ currency: 'XRP' },
{
currency: "USD",
issuer: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
currency: 'USD',
issuer: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B',
},
],
];
]
test("works with long paths", () => {
const parser = makeParser(bytes);
const txn = readJSON(parser);
expect(txn.Paths).toEqual(expectedJSON);
test('works with long paths', () => {
const parser = makeParser(bytes)
const txn = readJSON(parser)
expect(txn.Paths).toEqual(expectedJSON)
// TODO: this should go elsewhere
expect(coreTypes.PathSet.from(txn.Paths).toJSON()).toEqual(expectedJSON);
});
expect(coreTypes.PathSet.from(txn.Paths).toJSON()).toEqual(expectedJSON)
})
}
describe("Binary Parser", function () {
describe("pathSetBinaryTests", () => pathSetBinaryTests());
describe("nestedObjectTests", () => nestedObjectTests());
describe("fieldParsingTests", () => fieldParsingTests());
describe("amountParsingTests", () => amountParsingTests());
describe("transactionParsingTests", () => transactionParsingTests());
describe("basicApiTests", () => basicApiTests());
});
describe('Binary Parser', function () {
describe('pathSetBinaryTests', () => pathSetBinaryTests())
describe('nestedObjectTests', () => nestedObjectTests())
describe('fieldParsingTests', () => fieldParsingTests())
describe('amountParsingTests', () => amountParsingTests())
describe('transactionParsingTests', () => transactionParsingTests())
describe('basicApiTests', () => basicApiTests())
})

@@ -1,71 +0,69 @@

/* eslint-disable func-style */
const { binary } = require('../dist/coretypes')
const { encode, decode } = require('../dist')
const { makeParser, BytesList, BinarySerializer } = binary
const { coreTypes } = require('../dist/types')
const { UInt8, UInt16, UInt32, UInt64, STObject } = coreTypes
const bigInt = require('big-integer')
const { Buffer } = require('buffer/')
const { binary } = require("../dist/coretypes");
const { encode, decode } = require("../dist");
const { makeParser, BytesList, BinarySerializer } = binary;
const { coreTypes } = require("../dist/types");
const { UInt8, UInt16, UInt32, UInt64, STObject } = coreTypes;
const bigInt = require("big-integer");
const { Buffer } = require("buffer/");
const { loadFixture } = require("./utils");
const fixtures = loadFixture("data-driven-tests.json");
const deliverMinTx = require("./fixtures/delivermin-tx.json");
const deliverMinTxBinary = require("./fixtures/delivermin-tx-binary.json");
const { loadFixture } = require('./utils')
const fixtures = loadFixture('data-driven-tests.json')
const deliverMinTx = require('./fixtures/delivermin-tx.json')
const deliverMinTxBinary = require('./fixtures/delivermin-tx-binary.json')
const SignerListSet = {
tx: require("./fixtures/signerlistset-tx.json"),
binary: require("./fixtures/signerlistset-tx-binary.json"),
meta: require("./fixtures/signerlistset-tx-meta-binary.json"),
};
tx: require('./fixtures/signerlistset-tx.json'),
binary: require('./fixtures/signerlistset-tx-binary.json'),
meta: require('./fixtures/signerlistset-tx-meta-binary.json'),
}
const DepositPreauth = {
tx: require("./fixtures/deposit-preauth-tx.json"),
binary: require("./fixtures/deposit-preauth-tx-binary.json"),
meta: require("./fixtures/deposit-preauth-tx-meta-binary.json"),
};
tx: require('./fixtures/deposit-preauth-tx.json'),
binary: require('./fixtures/deposit-preauth-tx-binary.json'),
meta: require('./fixtures/deposit-preauth-tx-meta-binary.json'),
}
const Escrow = {
create: {
tx: require("./fixtures/escrow-create-tx.json"),
binary: require("./fixtures/escrow-create-binary.json"),
tx: require('./fixtures/escrow-create-tx.json'),
binary: require('./fixtures/escrow-create-binary.json'),
},
finish: {
tx: require("./fixtures/escrow-finish-tx.json"),
binary: require("./fixtures/escrow-finish-binary.json"),
meta: require("./fixtures/escrow-finish-meta-binary.json"),
tx: require('./fixtures/escrow-finish-tx.json'),
binary: require('./fixtures/escrow-finish-binary.json'),
meta: require('./fixtures/escrow-finish-meta-binary.json'),
},
cancel: {
tx: require("./fixtures/escrow-cancel-tx.json"),
binary: require("./fixtures/escrow-cancel-binary.json"),
tx: require('./fixtures/escrow-cancel-tx.json'),
binary: require('./fixtures/escrow-cancel-binary.json'),
},
};
}
const PaymentChannel = {
create: {
tx: require("./fixtures/payment-channel-create-tx.json"),
binary: require("./fixtures/payment-channel-create-binary.json"),
tx: require('./fixtures/payment-channel-create-tx.json'),
binary: require('./fixtures/payment-channel-create-binary.json'),
},
fund: {
tx: require("./fixtures/payment-channel-fund-tx.json"),
binary: require("./fixtures/payment-channel-fund-binary.json"),
tx: require('./fixtures/payment-channel-fund-tx.json'),
binary: require('./fixtures/payment-channel-fund-binary.json'),
},
claim: {
tx: require("./fixtures/payment-channel-claim-tx.json"),
binary: require("./fixtures/payment-channel-claim-binary.json"),
tx: require('./fixtures/payment-channel-claim-tx.json'),
binary: require('./fixtures/payment-channel-claim-binary.json'),
},
};
}
const Ticket = {
create: {
tx: require("./fixtures/ticket-create-tx.json"),
binary: require("./fixtures/ticket-create-binary.json"),
tx: require('./fixtures/ticket-create-tx.json'),
binary: require('./fixtures/ticket-create-binary.json'),
},
};
}
let json_undefined = {
TakerPays: "223174650",
Account: "rPk2dXr27rMw9G5Ej9ad2Tt7RJzGy8ycBp",
TransactionType: "OfferCreate",
TakerPays: '223174650',
Account: 'rPk2dXr27rMw9G5Ej9ad2Tt7RJzGy8ycBp',
TransactionType: 'OfferCreate',
Memos: [
{
Memo: {
MemoType: "584D4D2076616C7565",
MemoData: "322E3230393635",
MemoType: '584D4D2076616C7565',
MemoData: '322E3230393635',
MemoFormat: undefined,

@@ -75,8 +73,8 @@ },

],
Fee: "15",
Fee: '15',
OfferSequence: undefined,
TakerGets: {
currency: "XMM",
value: "100",
issuer: "rExAPEZvbkZqYPuNcZ7XEBLENEshsWDQc8",
currency: 'XMM',
value: '100',
issuer: 'rExAPEZvbkZqYPuNcZ7XEBLENEshsWDQc8',
},

@@ -86,27 +84,27 @@ Flags: 524288,

LastLedgerSequence: 6220135,
};
}
let json_omitted = {
TakerPays: "223174650",
Account: "rPk2dXr27rMw9G5Ej9ad2Tt7RJzGy8ycBp",
TransactionType: "OfferCreate",
TakerPays: '223174650',
Account: 'rPk2dXr27rMw9G5Ej9ad2Tt7RJzGy8ycBp',
TransactionType: 'OfferCreate',
Memos: [
{
Memo: {
MemoType: "584D4D2076616C7565",
MemoData: "322E3230393635",
MemoType: '584D4D2076616C7565',
MemoData: '322E3230393635',
},
},
],
Fee: "15",
Fee: '15',
TakerGets: {
currency: "XMM",
value: "100",
issuer: "rExAPEZvbkZqYPuNcZ7XEBLENEshsWDQc8",
currency: 'XMM',
value: '100',
issuer: 'rExAPEZvbkZqYPuNcZ7XEBLENEshsWDQc8',
},
Flags: 524288,
LastLedgerSequence: 6220135,
};
}
const NegativeUNL = require("./fixtures/negative-unl.json");
const NegativeUNL = require('./fixtures/negative-unl.json')

@@ -117,25 +115,25 @@ function bytesListTest() {

.put(Buffer.from([2, 3]))
.put(Buffer.from([4, 5]));
test("is an Array<Buffer>", function () {
expect(Array.isArray(list.bytesArray)).toBe(true);
expect(list.bytesArray[0] instanceof Buffer).toBe(true);
});
test("keeps track of the length itself", function () {
expect(list.getLength()).toBe(5);
});
test("can join all arrays into one via toBytes", function () {
const joined = list.toBytes();
expect(joined).toHaveLength(5);
expect(joined).toEqual(Buffer.from([0, 2, 3, 4, 5]));
});
.put(Buffer.from([4, 5]))
test('is an Array<Buffer>', function () {
expect(Array.isArray(list.bytesArray)).toBe(true)
expect(list.bytesArray[0] instanceof Buffer).toBe(true)
})
test('keeps track of the length itself', function () {
expect(list.getLength()).toBe(5)
})
test('can join all arrays into one via toBytes', function () {
const joined = list.toBytes()
expect(joined).toHaveLength(5)
expect(joined).toEqual(Buffer.from([0, 2, 3, 4, 5]))
})
}
function assertRecycles(blob) {
const parser = makeParser(blob);
const so = parser.readType(STObject);
const out = new BytesList();
so.toBytesSink(out);
const hex = out.toHex();
expect(hex).toEqual(blob);
expect(hex + ":").not.toEqual(blob);
const parser = makeParser(blob)
const so = parser.readType(STObject)
const out = new BytesList()
so.toBytesSink(out)
const hex = out.toHex()
expect(hex).toEqual(blob)
expect(hex + ':').not.toEqual(blob)
}

@@ -145,8 +143,6 @@

fixtures.whole_objects.forEach((f, i) => {
/*eslint-disable jest/expect-expect*/
test(`whole_objects[${i}]: can parse blob and dump out same blob`, () => {
assertRecycles(f.blob_with_no_signing);
});
/*eslint-enable jest/expect-expect*/
});
assertRecycles(f.blob_with_no_signing)
})
})
}

@@ -156,114 +152,143 @@

test(`Uint${type.width * 8} serializes ${n} as ${expected}`, function () {
const bl = new BytesList();
const serializer = new BinarySerializer(bl);
if (expected === "throws") {
expect(() => serializer.writeType(type, n)).toThrow();
return;
const bl = new BytesList()
const serializer = new BinarySerializer(bl)
if (expected === 'throws') {
expect(() => serializer.writeType(type, n)).toThrow()
return
}
serializer.writeType(type, n);
expect(bl.toBytes()).toEqual(Buffer.from(expected));
});
serializer.writeType(type, n)
expect(bl.toBytes()).toEqual(Buffer.from(expected))
})
}
check(UInt8, 5, [5]);
check(UInt16, 5, [0, 5]);
check(UInt32, 5, [0, 0, 0, 5]);
check(UInt32, 0xffffffff, [255, 255, 255, 255]);
check(UInt8, 0xfeffffff, "throws");
check(UInt16, 0xfeffffff, "throws");
check(UInt16, 0xfeffffff, "throws");
check(UInt64, 0xfeffffff, [0, 0, 0, 0, 254, 255, 255, 255]);
check(UInt64, -1, "throws");
check(UInt64, 0, [0, 0, 0, 0, 0, 0, 0, 0]);
check(UInt64, 1, [0, 0, 0, 0, 0, 0, 0, 1]);
check(UInt64, bigInt(1), [0, 0, 0, 0, 0, 0, 0, 1]);
check(UInt8, 5, [5])
check(UInt16, 5, [0, 5])
check(UInt32, 5, [0, 0, 0, 5])
check(UInt32, 0xffffffff, [255, 255, 255, 255])
check(UInt8, 0xfeffffff, 'throws')
check(UInt16, 0xfeffffff, 'throws')
check(UInt16, 0xfeffffff, 'throws')
check(UInt64, 0xfeffffff, [0, 0, 0, 0, 254, 255, 255, 255])
check(UInt64, -1, 'throws')
check(UInt64, 0, [0, 0, 0, 0, 0, 0, 0, 0])
check(UInt64, 1, [0, 0, 0, 0, 0, 0, 0, 1])
check(UInt64, bigInt(1), [0, 0, 0, 0, 0, 0, 0, 1])
function deliverMinTest() {
test("can serialize DeliverMin", () => {
expect(encode(deliverMinTx)).toEqual(deliverMinTxBinary);
});
test('can serialize DeliverMin', () => {
expect(encode(deliverMinTx)).toEqual(deliverMinTxBinary)
})
}
function SignerListSetTest() {
test("can serialize SignerListSet", () => {
expect(encode(SignerListSet.tx)).toEqual(SignerListSet.binary);
});
test("can serialize SignerListSet metadata", () => {
expect(encode(SignerListSet.tx.meta)).toEqual(SignerListSet.meta);
});
test('can serialize SignerListSet', () => {
expect(encode(SignerListSet.tx)).toEqual(SignerListSet.binary)
})
test('can serialize SignerListSet metadata', () => {
expect(encode(SignerListSet.tx.meta)).toEqual(SignerListSet.meta)
})
}
function DepositPreauthTest() {
test("can serialize DepositPreauth", () => {
expect(encode(DepositPreauth.tx)).toEqual(DepositPreauth.binary);
});
test("can serialize DepositPreauth metadata", () => {
expect(encode(DepositPreauth.tx.meta)).toEqual(DepositPreauth.meta);
});
test('can serialize DepositPreauth', () => {
expect(encode(DepositPreauth.tx)).toEqual(DepositPreauth.binary)
})
test('can serialize DepositPreauth metadata', () => {
expect(encode(DepositPreauth.tx.meta)).toEqual(DepositPreauth.meta)
})
}
function EscrowTest() {
test("can serialize EscrowCreate", () => {
expect(encode(Escrow.create.tx)).toEqual(Escrow.create.binary);
});
test("can serialize EscrowFinish", () => {
expect(encode(Escrow.finish.tx)).toEqual(Escrow.finish.binary);
expect(encode(Escrow.finish.tx.meta)).toEqual(Escrow.finish.meta);
});
test("can serialize EscrowCancel", () => {
expect(encode(Escrow.cancel.tx)).toEqual(Escrow.cancel.binary);
});
test('can serialize EscrowCreate', () => {
expect(encode(Escrow.create.tx)).toEqual(Escrow.create.binary)
})
test('can serialize EscrowFinish', () => {
expect(encode(Escrow.finish.tx)).toEqual(Escrow.finish.binary)
expect(encode(Escrow.finish.tx.meta)).toEqual(Escrow.finish.meta)
})
test('can serialize EscrowCancel', () => {
expect(encode(Escrow.cancel.tx)).toEqual(Escrow.cancel.binary)
})
}
function PaymentChannelTest() {
test("can serialize PaymentChannelCreate", () => {
test('can serialize PaymentChannelCreate', () => {
expect(encode(PaymentChannel.create.tx)).toEqual(
PaymentChannel.create.binary
);
});
test("can serialize PaymentChannelFund", () => {
expect(encode(PaymentChannel.fund.tx)).toEqual(PaymentChannel.fund.binary);
});
test("can serialize PaymentChannelClaim", () => {
expect(encode(PaymentChannel.claim.tx)).toEqual(
PaymentChannel.claim.binary
);
});
PaymentChannel.create.binary,
)
})
test('can serialize PaymentChannelFund', () => {
expect(encode(PaymentChannel.fund.tx)).toEqual(PaymentChannel.fund.binary)
})
test('can serialize PaymentChannelClaim', () => {
expect(encode(PaymentChannel.claim.tx)).toEqual(PaymentChannel.claim.binary)
})
}
function NegativeUNLTest() {
test("can serialize NegativeUNL", () => {
expect(encode(NegativeUNL.tx)).toEqual(NegativeUNL.binary);
});
test("can deserialize NegativeUNL", () => {
expect(decode(NegativeUNL.binary)).toEqual(NegativeUNL.tx);
});
test('can serialize NegativeUNL', () => {
expect(encode(NegativeUNL.tx)).toEqual(NegativeUNL.binary)
})
test('can deserialize NegativeUNL', () => {
expect(decode(NegativeUNL.binary)).toEqual(NegativeUNL.tx)
})
}
function omitUndefinedTest() {
test("omits fields with undefined value", () => {
let encodedOmitted = encode(json_omitted);
let encodedUndefined = encode(json_undefined);
expect(encodedOmitted).toEqual(encodedUndefined);
expect(decode(encodedOmitted)).toEqual(decode(encodedUndefined));
});
test('omits fields with undefined value', () => {
let encodedOmitted = encode(json_omitted)
let encodedUndefined = encode(json_undefined)
expect(encodedOmitted).toEqual(encodedUndefined)
expect(decode(encodedOmitted)).toEqual(decode(encodedUndefined))
})
}
function ticketTest() {
test("can serialize TicketCreate", () => {
expect(encode(Ticket.create.tx)).toEqual(Ticket.create.binary);
});
test('can serialize TicketCreate', () => {
expect(encode(Ticket.create.tx)).toEqual(Ticket.create.binary)
})
}
describe("Binary Serialization", function () {
describe("nestedObjectTests", () => nestedObjectTests());
describe("BytesList", () => bytesListTest());
describe("DeliverMin", () => deliverMinTest());
describe("DepositPreauth", () => DepositPreauthTest());
describe("SignerListSet", () => SignerListSetTest());
describe("Escrow", () => EscrowTest());
describe("PaymentChannel", () => PaymentChannelTest());
describe("NegativeUNLTest", () => NegativeUNLTest());
describe("OmitUndefined", () => omitUndefinedTest());
describe("TicketTest", () => ticketTest());
});
function nfTokenTest() {
const fixtures = require('./fixtures/nf-token.json')
for (const txName of Object.keys(fixtures)) {
test(`can serialize transaction ${txName}`, () => {
expect(encode(fixtures[txName].tx.json)).toEqual(
fixtures[txName].tx.binary,
)
})
test(`can deserialize transaction ${txName}`, () => {
expect(decode(fixtures[txName].tx.binary)).toEqual(
fixtures[txName].tx.json,
)
})
test(`can serialize meta ${txName}`, () => {
expect(encode(fixtures[txName].meta.json)).toEqual(
fixtures[txName].meta.binary,
)
})
test(`can deserialize meta ${txName}`, () => {
expect(decode(fixtures[txName].meta.binary)).toEqual(
fixtures[txName].meta.json,
)
})
}
}
describe('Binary Serialization', function () {
describe('nestedObjectTests', nestedObjectTests)
describe('BytesList', bytesListTest)
describe('DeliverMin', deliverMinTest)
describe('DepositPreauth', DepositPreauthTest)
describe('SignerListSet', SignerListSetTest)
describe('Escrow', EscrowTest)
describe('PaymentChannel', PaymentChannelTest)
describe('NegativeUNLTest', NegativeUNLTest)
describe('OmitUndefined', omitUndefinedTest)
describe('TicketTest', ticketTest)
describe('NFToken', nfTokenTest)
})
{
"binary": "120066240000000026000003006840000000000000007300701321ED9D593004CC501CACD261BD8E31E863F2B3F6CA69505E7FD54DA8F5690BEFB7AE8114000000000000000000000000000000000000000000101101",
"binary": "120066240000000026040B52006840000000000000007300701321EDB6FC8E803EE8EDC2793F1EC917B2EE41D35255618DEB91D3F9B1FC89B75D4539810000101101",
"tx": {
"UNLModifyDisabling": 1,
"LedgerSequence": 768,
"UNLModifyValidator": "ED9D593004CC501CACD261BD8E31E863F2B3F6CA69505E7FD54DA8F5690BEFB7AE",
"LedgerSequence": 67850752,
"UNLModifyValidator": "EDB6FC8E803EE8EDC2793F1EC917B2EE41D35255618DEB91D3F9B1FC89B75D4539",
"TransactionType": "UNLModify",

@@ -12,2 +12,2 @@ "Account": "rrrrrrrrrrrrrrrrrrrrrhoLvTp",

"SigningPubKey": ""}
}
}

@@ -1,83 +0,87 @@

const { coreTypes } = require("../dist/types");
const { Hash160, Hash256, AccountID, Currency } = coreTypes;
const { Buffer } = require("buffer/");
const { coreTypes } = require('../dist/types')
const { Hash160, Hash256, AccountID, Currency } = coreTypes
const { Buffer } = require('buffer/')
describe("Hash160", function () {
test("has a static width member", function () {
expect(Hash160.width).toBe(20);
});
test("inherited by subclasses", function () {
expect(AccountID.width).toBe(20);
expect(Currency.width).toBe(20);
});
test("can be compared against another", function () {
const h1 = Hash160.from("1000000000000000000000000000000000000000");
const h2 = Hash160.from("2000000000000000000000000000000000000000");
const h3 = Hash160.from("0000000000000000000000000000000000000003");
expect(h1.lt(h2)).toBe(true);
expect(h3.lt(h2)).toBe(true);
});
test("throws when constructed from invalid hash length", () => {
describe('Hash160', function () {
test('has a static width member', function () {
expect(Hash160.width).toBe(20)
})
test('inherited by subclasses', function () {
expect(AccountID.width).toBe(20)
expect(Currency.width).toBe(20)
})
test('can be compared against another', function () {
const h1 = Hash160.from('1000000000000000000000000000000000000000')
const h2 = Hash160.from('2000000000000000000000000000000000000000')
const h3 = Hash160.from('0000000000000000000000000000000000000003')
expect(h1.lt(h2)).toBe(true)
expect(h3.lt(h2)).toBe(true)
})
test('throws when constructed from invalid hash length', () => {
expect(() =>
Hash160.from("10000000000000000000000000000000000000")
).toThrow("Invalid Hash length 19");
Hash160.from('10000000000000000000000000000000000000'),
).toThrow('Invalid Hash length 19')
expect(() =>
Hash160.from("100000000000000000000000000000000000000000")
).toThrow("Invalid Hash length 21");
});
});
Hash160.from('100000000000000000000000000000000000000000'),
).toThrow('Invalid Hash length 21')
})
})
describe("Hash256", function () {
test("has a static width member", function () {
expect(Hash256.width).toBe(32);
});
test("has a ZERO_256 member", function () {
describe('Hash256', function () {
test('has a static width member', function () {
expect(Hash256.width).toBe(32)
})
test('has a ZERO_256 member', function () {
expect(Hash256.ZERO_256.toJSON()).toBe(
"0000000000000000000000000000000000000000000000000000000000000000"
);
});
test("supports getting the nibblet values at given positions", function () {
'0000000000000000000000000000000000000000000000000000000000000000',
)
})
test('supports getting the nibblet values at given positions', function () {
const h = Hash256.from(
"1359BD0000000000000000000000000000000000000000000000000000000000"
);
expect(h.nibblet(0)).toBe(0x1);
expect(h.nibblet(1)).toBe(0x3);
expect(h.nibblet(2)).toBe(0x5);
expect(h.nibblet(3)).toBe(0x9);
expect(h.nibblet(4)).toBe(0x0b);
expect(h.nibblet(5)).toBe(0xd);
});
});
'1359BD0000000000000000000000000000000000000000000000000000000000',
)
expect(h.nibblet(0)).toBe(0x1)
expect(h.nibblet(1)).toBe(0x3)
expect(h.nibblet(2)).toBe(0x5)
expect(h.nibblet(3)).toBe(0x9)
expect(h.nibblet(4)).toBe(0x0b)
expect(h.nibblet(5)).toBe(0xd)
})
})
describe("Currency", function () {
test("Will have a null iso() for dodgy XRP ", function () {
const bad = Currency.from("0000000000000000000000005852500000000000");
expect(bad.iso()).toBeUndefined();
expect(bad.isNative()).toBe(false);
});
test("Currency with lowercase letters decode to hex", () => {
expect(Currency.from("xRp").toJSON()).toBe(
"0000000000000000000000007852700000000000"
);
});
test("Currency codes with symbols decode to hex", () => {
expect(Currency.from("x|p").toJSON()).toBe(
"000000000000000000000000787C700000000000"
);
});
test("Currency codes with uppercase and 0-9 decode to ISO codes", () => {
expect(Currency.from("X8P").toJSON()).toBe("X8P");
expect(Currency.from("USD").toJSON()).toBe("USD");
});
test("can be constructed from a Buffer", function () {
const xrp = new Currency(Buffer.alloc(20));
expect(xrp.iso()).toBe("XRP");
});
test("throws on invalid reprs", function () {
expect(() => Currency.from(Buffer.alloc(19))).toThrow();
expect(() => Currency.from(1)).toThrow();
describe('Currency', function () {
test('Will throw an error for dodgy XRP ', function () {
expect(() =>
Currency.from("00000000000000000000000000000000000000m")
).toThrow();
});
});
Currency.from('0000000000000000000000005852500000000000'),
).toThrow()
})
test('Currency with lowercase letters decode to hex', () => {
expect(Currency.from('xRp').toJSON()).toBe(
'0000000000000000000000007852700000000000',
)
})
test('Currency codes with symbols decode to hex', () => {
expect(Currency.from('x|p').toJSON()).toBe(
'000000000000000000000000787C700000000000',
)
})
test('Currency codes with uppercase and 0-9 decode to ISO codes', () => {
expect(Currency.from('X8P').toJSON()).toBe('X8P')
expect(Currency.from('USD').toJSON()).toBe('USD')
})
test('can be constructed from a Buffer', function () {
const xrp = new Currency(Buffer.alloc(20))
expect(xrp.iso()).toBe('XRP')
})
test('Can handle non-standard currency codes', () => {
const currency = '015841551A748AD2C1F76FF6ECB0CCCD00000000'
expect(Currency.from(currency).toJSON()).toBe(currency)
})
test('throws on invalid reprs', function () {
expect(() => Currency.from(Buffer.alloc(19))).toThrow()
expect(() => Currency.from(1)).toThrow()
expect(() =>
Currency.from('00000000000000000000000000000000000000m'),
).toThrow()
})
})

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

const { loadFixture } = require("./utils");
const { loadFixture } = require('./utils')
const {

@@ -6,25 +6,25 @@ transactionTreeHash,

accountStateHash,
} = require("../dist/ledger-hashes");
} = require('../dist/ledger-hashes')
describe("Ledger Hashes", function () {
describe('Ledger Hashes', function () {
function testFactory(ledgerFixture) {
describe(`can calculate hashes for ${ledgerFixture}`, function () {
const ledger = loadFixture(ledgerFixture);
test("computes correct account state hash", function () {
const ledger = loadFixture(ledgerFixture)
test('computes correct account state hash', function () {
expect(accountStateHash(ledger.accountState).toHex()).toBe(
ledger.account_hash
);
});
test("computes correct transaction tree hash", function () {
ledger.account_hash,
)
})
test('computes correct transaction tree hash', function () {
expect(transactionTreeHash(ledger.transactions).toHex()).toBe(
ledger.transaction_hash
);
});
test("computes correct ledger header hash", function () {
expect(ledgerHash(ledger).toHex()).toBe(ledger.hash);
});
});
ledger.transaction_hash,
)
})
test('computes correct ledger header hash', function () {
expect(ledgerHash(ledger).toHex()).toBe(ledger.hash)
})
})
}
testFactory("ledger-full-40000.json");
testFactory("ledger-full-38129.json");
});
testFactory('ledger-full-40000.json')
testFactory('ledger-full-38129.json')
})

@@ -1,45 +0,46 @@

const { encode, decode } = require("../dist");
const { encode, decode } = require('../dist')
let str =
"1100612200000000240000000125000068652D0000000055B6632D6376A2D9319F20A1C6DCCB486432D1E4A79951229D4C3DE2946F51D56662400009184E72A00081140DD319918CD5AE792BF7EC80D63B0F01B4573BBC";
let lower = str.toLowerCase();
'1100612200000000240000000125000068652D0000000055B6632D6376A2D9319F20A1C6DCCB486432D1E4A79951229D4C3DE2946F51D56662400009184E72A00081140DD319918CD5AE792BF7EC80D63B0F01B4573BBC'
let lower = str.toLowerCase()
let bin =
"1100612200000000240000000125000000082D00000000550735A0B32B2A3F4C938B76D6933003E29447DB8C7CE382BBE089402FF12A03E56240000002540BE400811479927BAFFD3D04A26096C0C97B1B0D45B01AD3C0";
'1100612200000000240000000125000000082D00000000550735A0B32B2A3F4C938B76D6933003E29447DB8C7CE382BBE089402FF12A03E56240000002540BE400811479927BAFFD3D04A26096C0C97B1B0D45B01AD3C0'
let json = {
OwnerCount: 0,
Account: "rUnFEsHjxqTswbivzL2DNHBb34rhAgZZZK",
Account: 'rUnFEsHjxqTswbivzL2DNHBb34rhAgZZZK',
PreviousTxnLgrSeq: 8,
LedgerEntryType: "AccountRoot",
PreviousTxnID: "0735A0B32B2A3F4C938B76D6933003E29447DB8C7CE382BBE089402FF12A03E5".toLowerCase(),
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
'0735A0B32B2A3F4C938B76D6933003E29447DB8C7CE382BBE089402FF12A03E5'.toLowerCase(),
Flags: 0,
Sequence: 1,
Balance: "10000000000",
};
Balance: '10000000000',
}
let jsonUpper = {
OwnerCount: 0,
Account: "rUnFEsHjxqTswbivzL2DNHBb34rhAgZZZK",
Account: 'rUnFEsHjxqTswbivzL2DNHBb34rhAgZZZK',
PreviousTxnLgrSeq: 8,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"0735A0B32B2A3F4C938B76D6933003E29447DB8C7CE382BBE089402FF12A03E5",
'0735A0B32B2A3F4C938B76D6933003E29447DB8C7CE382BBE089402FF12A03E5',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
};
Balance: '10000000000',
}
describe("Lowercase hex test", () => {
test("Correctly decodes", () => {
expect(decode(lower)).toEqual(decode(str));
});
test("Re-encodes to uppercase hex", () => {
expect(encode(decode(lower))).toEqual(str);
});
test("Encode when hex field lowercase", () => {
expect(encode(json)).toBe(bin);
});
test("Re-decodes to uppercase hex", () => {
expect(decode(encode(json))).toEqual(jsonUpper);
});
});
describe('Lowercase hex test', () => {
test('Correctly decodes', () => {
expect(decode(lower)).toEqual(decode(str))
})
test('Re-encodes to uppercase hex', () => {
expect(encode(decode(lower))).toEqual(str)
})
test('Encode when hex field lowercase', () => {
expect(encode(json)).toBe(bin)
})
test('Re-decodes to uppercase hex', () => {
expect(decode(encode(json))).toEqual(jsonUpper)
})
})

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

const { encode, decode } = require("../dist");
const { encode, decode } = require('../dist')
let json = {
Account: "rrrrrrrrrrrrrrrrrrrrrhoLvTp",
Account: 'rrrrrrrrrrrrrrrrrrrrrhoLvTp',
Sequence: 0,
Fee: "0",
SigningPubKey: "",
Signature: "",
};
Fee: '0',
SigningPubKey: '',
Signature: '',
}
let json_blank_acct = {
Account: "",
Account: '',
Sequence: 0,
Fee: "0",
SigningPubKey: "",
Signature: "",
};
Fee: '0',
SigningPubKey: '',
Signature: '',
}
let binary =
"24000000006840000000000000007300760081140000000000000000000000000000000000000000";
'24000000006840000000000000007300760081140000000000000000000000000000000000000000'
describe("Can encode Pseudo Transactions", () => {
test("Correctly encodes Pseudo Transaciton", () => {
expect(encode(json)).toEqual(binary);
});
describe('Can encode Pseudo Transactions', () => {
test('Correctly encodes Pseudo Transaciton', () => {
expect(encode(json)).toEqual(binary)
})
test("Can decode account objects", () => {
expect(decode(encode(json))).toEqual(json);
});
test('Can decode account objects', () => {
expect(decode(encode(json))).toEqual(json)
})
test("Blank AccountID is ACCOUNT_ZERO", () => {
expect(encode(json_blank_acct)).toEqual(binary);
});
test('Blank AccountID is ACCOUNT_ZERO', () => {
expect(encode(json_blank_acct)).toEqual(binary)
})
test("Decodes Blank AccountID", () => {
expect(decode(encode(json_blank_acct))).toEqual(json);
});
});
test('Decodes Blank AccountID', () => {
expect(decode(encode(json_blank_acct))).toEqual(json)
})
})

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

const { quality } = require("../dist/coretypes");
const { quality } = require('../dist/coretypes')
describe("Quality encode/decode", function () {
describe('Quality encode/decode', function () {
const bookDirectory =
"4627DFFCFF8B5A265EDBD8AE8C14A52325DBFEDAF4F5C32E5D06F4C3362FE1D0";
const expectedQuality = "195796912.5171664";
test("can decode", function () {
const decimal = quality.decode(bookDirectory);
expect(decimal.toString()).toBe(expectedQuality);
});
test("can encode", function () {
const bytes = quality.encode(expectedQuality);
expect(bytes.toString("hex").toUpperCase()).toBe(bookDirectory.slice(-16));
});
});
'4627DFFCFF8B5A265EDBD8AE8C14A52325DBFEDAF4F5C32E5D06F4C3362FE1D0'
const expectedQuality = '195796912.5171664'
test('can decode', function () {
const decimal = quality.decode(bookDirectory)
expect(decimal.toString()).toBe(expectedQuality)
})
test('can encode', function () {
const bytes = quality.encode(expectedQuality)
expect(bytes.toString('hex').toUpperCase()).toBe(bookDirectory.slice(-16))
})
})

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

const { ShaMap } = require("../dist/shamap.js");
const { binary, HashPrefix } = require("../dist/coretypes");
const { coreTypes } = require("../dist/types");
const { loadFixture } = require("./utils");
const { Buffer } = require("buffer/");
const { ShaMap } = require('../dist/shamap.js')
const { binary, HashPrefix } = require('../dist/coretypes')
const { coreTypes } = require('../dist/types')
const { loadFixture } = require('./utils')
const { Buffer } = require('buffer/')
function now() {
return Number(Date.now()) / 1000;
return Number(Date.now()) / 1000
}
const ZERO = "0000000000000000000000000000000000000000000000000000000000000000";
const ZERO = '0000000000000000000000000000000000000000000000000000000000000000'
function makeItem(indexArg) {
let str = indexArg;
let str = indexArg
while (str.length < 64) {
str += "0";
str += '0'
}
const index = coreTypes.Hash256.from(str);
const index = coreTypes.Hash256.from(str)
const item = {
toBytesSink(sink) {
index.toBytesSink(sink);
index.toBytesSink(sink)
},
hashPrefix() {
return Buffer.from([1, 3, 3, 7]);
return Buffer.from([1, 3, 3, 7])
},
};
return [index, item];
}
return [index, item]
}
describe("ShaMap", () => {
now();
describe('ShaMap', () => {
now()
test("hashes to zero when empty", () => {
const map = new ShaMap();
expect(map.hash().toHex()).toBe(ZERO);
});
test("creates the same hash no matter which order items are added", () => {
let map = new ShaMap();
test('hashes to zero when empty', () => {
const map = new ShaMap()
expect(map.hash().toHex()).toBe(ZERO)
})
test('creates the same hash no matter which order items are added', () => {
let map = new ShaMap()
const items = [
"0",
"1",
"11",
"7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E20000000000000000",
"7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E21000000000000000",
"7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E22000000000000000",
"7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E23000000000000000",
"12",
"122",
];
items.forEach((i) => map.addItem(...makeItem(i)));
const h1 = map.hash();
expect(h1.eq(h1)).toBe(true);
map = new ShaMap();
items.reverse().forEach((i) => map.addItem(...makeItem(i)));
expect(map.hash()).toStrictEqual(h1);
});
'0',
'1',
'11',
'7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E20000000000000000',
'7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E21000000000000000',
'7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E22000000000000000',
'7000DE445E22CB9BB7E1717589FA858736BAA5FD192310E23000000000000000',
'12',
'122',
]
items.forEach((i) => map.addItem(...makeItem(i)))
const h1 = map.hash()
expect(h1.eq(h1)).toBe(true)
map = new ShaMap()
items.reverse().forEach((i) => map.addItem(...makeItem(i)))
expect(map.hash()).toStrictEqual(h1)
})
function factory(fixture) {
test(`recreate account state hash from ${fixture}`, () => {
const map = new ShaMap();
const ledger = loadFixture(fixture);
const map = new ShaMap()
const ledger = loadFixture(fixture)
// const t = now();
const leafNodePrefix = HashPrefix.accountStateEntry;
const leafNodePrefix = HashPrefix.accountStateEntry
ledger.accountState
.map((e, i) => {
if ((i > 1000) & (i % 1000 === 0)) {
console.log(e.index);
console.log(i);
console.log(e.index)
console.log(i)
}
const bytes = binary.serializeObject(e);
const bytes = binary.serializeObject(e)
return {
index: coreTypes.Hash256.from(e.index),
hashPrefix() {
return leafNodePrefix;
return leafNodePrefix
},
toBytesSink(sink) {
sink.put(bytes);
sink.put(bytes)
},
};
}
})
.forEach((so) => map.addItem(so.index, so));
expect(map.hash().toHex()).toBe(ledger.account_hash);
.forEach((so) => map.addItem(so.index, so))
expect(map.hash().toHex()).toBe(ledger.account_hash)
// console.log('took seconds: ', (now() - t));
});
})
}
factory("ledger-full-38129.json");
factory("ledger-full-40000.json");
factory('ledger-full-38129.json')
factory('ledger-full-40000.json')
// factory('ledger-4320277.json');
// factory('14280680.json');
});
})

@@ -5,126 +5,126 @@ const {

encodeForMultisigning,
} = require("../dist");
} = require('../dist')
const tx_json = {
Account: "r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ",
Amount: "1000",
Destination: "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh",
Fee: "10",
Account: 'r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ',
Amount: '1000',
Destination: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
Fee: '10',
Flags: 2147483648,
Sequence: 1,
TransactionType: "Payment",
TransactionType: 'Payment',
TxnSignature:
"30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1" +
"E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80" +
"ECA3CD7B9B",
'30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1' +
'E721B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80' +
'ECA3CD7B9B',
Signature:
"30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E72" +
"1B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA" +
"3CD7B9B",
'30440220718D264EF05CAED7C781FF6DE298DCAC68D002562C9BF3A07C1E72' +
'1B420C0DAB02203A5A4779EF4D2CCC7BC3EF886676D803A9981B928D3B8ACA483B80ECA' +
'3CD7B9B',
SigningPubKey:
"ED5F5AC8B98974A3CA843326D9B88CEBD0560177B973EE0B149F782CFAA06DC66A",
};
'ED5F5AC8B98974A3CA843326D9B88CEBD0560177B973EE0B149F782CFAA06DC66A',
}
describe("Signing data", function () {
test("can create single signing blobs", function () {
const actual = encodeForSigning(tx_json);
describe('Signing data', function () {
test('can create single signing blobs', function () {
const actual = encodeForSigning(tx_json)
expect(actual).toBe(
[
"53545800", // signingPrefix
'53545800', // signingPrefix
// TransactionType
"12",
"0000",
'12',
'0000',
// Flags
"22",
"80000000",
'22',
'80000000',
// Sequence
"24",
"00000001",
'24',
'00000001',
// Amount
"61",
'61',
// native amount
"40000000000003E8",
'40000000000003E8',
// Fee
"68",
'68',
// native amount
"400000000000000A",
'400000000000000A',
// SigningPubKey
"73",
'73',
// VLLength
"21",
"ED5F5AC8B98974A3CA843326D9B88CEBD0560177B973EE0B149F782CFAA06DC66A",
'21',
'ED5F5AC8B98974A3CA843326D9B88CEBD0560177B973EE0B149F782CFAA06DC66A',
// Account
"81",
'81',
// VLLength
"14",
"5B812C9D57731E27A2DA8B1830195F88EF32A3B6",
'14',
'5B812C9D57731E27A2DA8B1830195F88EF32A3B6',
// Destination
"83",
'83',
// VLLength
"14",
"B5F762798A53D543A014CAF8B297CFF8F2F937E8",
].join("")
);
});
test("can create multi signing blobs", function () {
const signingAccount = "rJZdUusLDtY9NEsGea7ijqhVrXv98rYBYN";
const signingJson = Object.assign({}, tx_json, { SigningPubKey: "" });
const actual = encodeForMultisigning(signingJson, signingAccount);
'14',
'B5F762798A53D543A014CAF8B297CFF8F2F937E8',
].join(''),
)
})
test('can create multi signing blobs', function () {
const signingAccount = 'rJZdUusLDtY9NEsGea7ijqhVrXv98rYBYN'
const signingJson = Object.assign({}, tx_json, { SigningPubKey: '' })
const actual = encodeForMultisigning(signingJson, signingAccount)
expect(actual).toBe(
[
"534D5400", // signingPrefix
'534D5400', // signingPrefix
// TransactionType
"12",
"0000",
'12',
'0000',
// Flags
"22",
"80000000",
'22',
'80000000',
// Sequence
"24",
"00000001",
'24',
'00000001',
// Amount
"61",
'61',
// native amount
"40000000000003E8",
'40000000000003E8',
// Fee
"68",
'68',
// native amount
"400000000000000A",
'400000000000000A',
// SigningPubKey
"73",
'73',
// VLLength
"00",
'00',
// '',
// Account
"81",
'81',
// VLLength
"14",
"5B812C9D57731E27A2DA8B1830195F88EF32A3B6",
'14',
'5B812C9D57731E27A2DA8B1830195F88EF32A3B6',
// Destination
"83",
'83',
// VLLength
"14",
"B5F762798A53D543A014CAF8B297CFF8F2F937E8",
'14',
'B5F762798A53D543A014CAF8B297CFF8F2F937E8',
// signingAccount suffix
"C0A5ABEF242802EFED4B041E8F2D4A8CC86AE3D1",
].join("")
);
});
test("can create claim blob", function () {
'C0A5ABEF242802EFED4B041E8F2D4A8CC86AE3D1',
].join(''),
)
})
test('can create claim blob', function () {
const channel =
"43904CBFCDCEC530B4037871F86EE90BF799DF8D2E0EA564BC8A3F332E4F5FB1";
const amount = "1000";
const json = { channel, amount };
const actual = encodeForSigningClaim(json);
'43904CBFCDCEC530B4037871F86EE90BF799DF8D2E0EA564BC8A3F332E4F5FB1'
const amount = '1000'
const json = { channel, amount }
const actual = encodeForSigningClaim(json)
expect(actual).toBe(
[
// hash prefix
"434C4D00",
'434C4D00',
// channel ID
"43904CBFCDCEC530B4037871F86EE90BF799DF8D2E0EA564BC8A3F332E4F5FB1",
'43904CBFCDCEC530B4037871F86EE90BF799DF8D2E0EA564BC8A3F332E4F5FB1',
// amount as a uint64
"00000000000003E8",
].join("")
);
});
});
'00000000000003E8',
].join(''),
)
})
})

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

const { encode, decode } = require("../dist");
const { encode, decode } = require('../dist')
// Notice: no Amount or Fee
const tx_json = {
Account: "r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ",
Account: 'r9LqNeG6qHxjeUocjvVki2XR35weJ9mZgQ',
// Amount: '1000',
Destination: "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh",
Destination: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
// Fee: '10',

@@ -15,84 +15,84 @@

Sequence: 1,
TransactionType: "Payment",
TransactionType: 'Payment',
// TxnSignature,
// Signature,
// SigningPubKey
};
}
describe("encoding and decoding tx_json", function () {
test("can encode tx_json without Amount or Fee", function () {
const encoded = encode(tx_json);
const decoded = decode(encoded);
expect(tx_json).toEqual(decoded);
});
test("can encode tx_json with Amount and Fee", function () {
describe('encoding and decoding tx_json', function () {
test('can encode tx_json without Amount or Fee', function () {
const encoded = encode(tx_json)
const decoded = decode(encoded)
expect(tx_json).toEqual(decoded)
})
test('can encode tx_json with Amount and Fee', function () {
const my_tx = Object.assign({}, tx_json, {
Amount: "1000",
Fee: "10",
});
const encoded = encode(my_tx);
const decoded = decode(encoded);
expect(my_tx).toEqual(decoded);
});
test("can encode tx_json with TicketCount", function () {
Amount: '1000',
Fee: '10',
})
const encoded = encode(my_tx)
const decoded = decode(encoded)
expect(my_tx).toEqual(decoded)
})
test('can encode tx_json with TicketCount', function () {
const my_tx = Object.assign({}, tx_json, {
TicketCount: 2,
});
const encoded = encode(my_tx);
const decoded = decode(encoded);
expect(my_tx).toEqual(decoded);
});
test("can encode tx_json with TicketSequence", function () {
})
const encoded = encode(my_tx)
const decoded = decode(encoded)
expect(my_tx).toEqual(decoded)
})
test('can encode tx_json with TicketSequence', function () {
const my_tx = Object.assign({}, tx_json, {
Sequence: 0,
TicketSequence: 2,
});
const encoded = encode(my_tx);
const decoded = decode(encoded);
expect(my_tx).toEqual(decoded);
});
test("throws when Amount is invalid", function () {
})
const encoded = encode(my_tx)
const decoded = decode(encoded)
expect(my_tx).toEqual(decoded)
})
test('throws when Amount is invalid', function () {
const my_tx = Object.assign({}, tx_json, {
Amount: "1000.001",
Fee: "10",
});
Amount: '1000.001',
Fee: '10',
})
expect(() => {
encode(my_tx);
}).toThrow();
});
test("throws when Fee is invalid", function () {
encode(my_tx)
}).toThrow()
})
test('throws when Fee is invalid', function () {
const my_tx = Object.assign({}, tx_json, {
Amount: "1000",
Fee: "10.123",
});
Amount: '1000',
Fee: '10.123',
})
expect(() => {
encode(my_tx);
}).toThrow();
});
test("throws when Amount and Fee are invalid", function () {
encode(my_tx)
}).toThrow()
})
test('throws when Amount and Fee are invalid', function () {
const my_tx = Object.assign({}, tx_json, {
Amount: "1000.789",
Fee: "10.123",
});
Amount: '1000.789',
Fee: '10.123',
})
expect(() => {
encode(my_tx);
}).toThrow();
});
test("throws when Amount is a number instead of a string-encoded integer", function () {
encode(my_tx)
}).toThrow()
})
test('throws when Amount is a number instead of a string-encoded integer', function () {
const my_tx = Object.assign({}, tx_json, {
Amount: 1000.789,
});
})
expect(() => {
encode(my_tx);
}).toThrow();
});
encode(my_tx)
}).toThrow()
})
test("throws when Fee is a number instead of a string-encoded integer", function () {
test('throws when Fee is a number instead of a string-encoded integer', function () {
const my_tx = Object.assign({}, tx_json, {
Amount: 1234.56,
});
})
expect(() => {
encode(my_tx);
}).toThrow();
});
});
encode(my_tx)
}).toThrow()
})
})

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

const { coreTypes } = require("../dist/types");
const { SerializedType } = require("../dist/types/serialized-type");
const { coreTypes } = require('../dist/types')
const { SerializedType } = require('../dist/types/serialized-type')
describe("SerializedType interfaces", () => {
describe('SerializedType interfaces', () => {
Object.entries(coreTypes).forEach(([name, Value]) => {
test(`${name} has a \`from\` static constructor`, () => {
expect(Value.from && Value.from !== Array.from).toBe(true);
});
expect(Value.from && Value.from !== Array.from).toBe(true)
})
test(`${name} has a default constructor`, () => {
expect(new Value()).not.toBe(undefined);
});
expect(new Value()).not.toBe(undefined)
})
test(`${name}.from will return the same object`, () => {
const instance = new Value();
expect(Value.from(instance) === instance).toBe(true);
});
const instance = new Value()
expect(Value.from(instance) === instance).toBe(true)
})
test(`${name} instances have toBytesSink`, () => {
expect(new Value().toBytesSink).not.toBe(undefined);
});
expect(new Value().toBytesSink).not.toBe(undefined)
})
test(`${name} instances have toJSON`, () => {
expect(new Value().toJSON).not.toBe(undefined);
});
expect(new Value().toJSON).not.toBe(undefined)
})
test(`${name}.from(json).toJSON() == json`, () => {
const newJSON = new Value().toJSON();
expect(Value.from(newJSON).toJSON()).toEqual(newJSON);
});
const newJSON = new Value().toJSON()
expect(Value.from(newJSON).toJSON()).toEqual(newJSON)
})
describe(`${name} supports all methods of the SerializedType mixin`, () => {
Object.keys(SerializedType.prototype).forEach((k) => {
test(`new ${name}.prototype.${k} !== undefined`, () => {
expect(Value.prototype[k]).not.toBe(undefined);
});
});
});
});
});
expect(Value.prototype[k]).not.toBe(undefined)
})
})
})
})
})

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

const { coreTypes } = require("../dist/types");
const { UInt8, UInt64 } = coreTypes;
const { coreTypes } = require('../dist/types')
const { UInt8, UInt64 } = coreTypes
const { encode } = require("../dist");
const { encode } = require('../dist')
const binary =
"11007222000300003700000000000000003800000000000000006280000000000000000000000000000000000000005553440000000000000000000000000000000000000000000000000166D5438D7EA4C680000000000000000000000000005553440000000000AE123A8556F3CF91154711376AFB0F894F832B3D67D5438D7EA4C680000000000000000000000000005553440000000000F51DFC2A09D62CBBA1DFBDD4691DAC96AD98B90F";
'11007222000300003700000000000000003800000000000000006280000000000000000000000000000000000000005553440000000000000000000000000000000000000000000000000166D5438D7EA4C680000000000000000000000000005553440000000000AE123A8556F3CF91154711376AFB0F894F832B3D67D5438D7EA4C680000000000000000000000000005553440000000000F51DFC2A09D62CBBA1DFBDD4691DAC96AD98B90F'
const json = {
Balance: {
currency: "USD",
issuer: "rrrrrrrrrrrrrrrrrrrrBZbvji",
value: "0",
currency: 'USD',
issuer: 'rrrrrrrrrrrrrrrrrrrrBZbvji',
value: '0',
},
Flags: 196608,
HighLimit: {
currency: "USD",
issuer: "rPMh7Pi9ct699iZUTWaytJUoHcJ7cgyziK",
value: "1000",
currency: 'USD',
issuer: 'rPMh7Pi9ct699iZUTWaytJUoHcJ7cgyziK',
value: '1000',
},
HighNode: "0",
LedgerEntryType: "RippleState",
HighNode: '0',
LedgerEntryType: 'RippleState',
LowLimit: {
currency: "USD",
issuer: "rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn",
value: "1000",
currency: 'USD',
issuer: 'rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn',
value: '1000',
},
LowNode: "0",
};
LowNode: '0',
}
const binaryEntry0 =
"11007222001100002501EC24873700000000000000003800000000000000A35506FC7DE374089D50F81AAE13E7BBF3D0E694769331E14F55351B38D0148018EA62D44BF89AC2A40B800000000000000000000000004A50590000000000000000000000000000000000000000000000000166D6C38D7EA4C680000000000000000000000000004A5059000000000047C1258B4B79774B28176324068F759EDE226F686780000000000000000000000000000000000000004A505900000000005BBC0F22F61D9224A110650CFE21CC0C4BE13098";
'11007222001100002501EC24873700000000000000003800000000000000A35506FC7DE374089D50F81AAE13E7BBF3D0E694769331E14F55351B38D0148018EA62D44BF89AC2A40B800000000000000000000000004A50590000000000000000000000000000000000000000000000000166D6C38D7EA4C680000000000000000000000000004A5059000000000047C1258B4B79774B28176324068F759EDE226F686780000000000000000000000000000000000000004A505900000000005BBC0F22F61D9224A110650CFE21CC0C4BE13098'
const jsonEntry0 = {
Balance: {
currency: "JPY",
issuer: "rrrrrrrrrrrrrrrrrrrrBZbvji",
value: "0.3369568318",
currency: 'JPY',
issuer: 'rrrrrrrrrrrrrrrrrrrrBZbvji',
value: '0.3369568318',
},
Flags: 1114112,
HighLimit: {
currency: "JPY",
issuer: "r94s8px6kSw1uZ1MV98dhSRTvc6VMPoPcN",
value: "0",
currency: 'JPY',
issuer: 'r94s8px6kSw1uZ1MV98dhSRTvc6VMPoPcN',
value: '0',
},
HighNode: "a3",
LedgerEntryType: "RippleState",
HighNode: 'a3',
LedgerEntryType: 'RippleState',
LowLimit: {
currency: "JPY",
issuer: "rfYQMgj3g3Qp8VLoZNvvU35mEuuJC8nCmY",
value: "1000000000",
currency: 'JPY',
issuer: 'rfYQMgj3g3Qp8VLoZNvvU35mEuuJC8nCmY',
value: '1000000000',
},
LowNode: "0",
LowNode: '0',
PreviousTxnID:
"06FC7DE374089D50F81AAE13E7BBF3D0E694769331E14F55351B38D0148018EA",
'06FC7DE374089D50F81AAE13E7BBF3D0E694769331E14F55351B38D0148018EA',
PreviousTxnLgrSeq: 32253063,
index: "000319BAE0A618A7D3BB492F17E98E5D92EA0C6458AFEBED44206B5B4798A840",
};
index: '000319BAE0A618A7D3BB492F17E98E5D92EA0C6458AFEBED44206B5B4798A840',
}
const binaryEntry1 =
"1100642200000000320000000000000002580CB3C1AD2C371136AEA434246D971C5FCCD32CBF520667E131AB7B10D706E7528214BA53D10260FFCC968ACD16BA30F7CEABAD6E5D92011340A3454ACED87177146EABD5E4A256021D836D1E3617618B1EB362D10B0D1BAC6AE1ED9E8D280BBE0B6656748FD647231851C6C650794D5E6852DFA1E35E68630F";
'1100642200000000320000000000000002580CB3C1AD2C371136AEA434246D971C5FCCD32CBF520667E131AB7B10D706E7528214BA53D10260FFCC968ACD16BA30F7CEABAD6E5D92011340A3454ACED87177146EABD5E4A256021D836D1E3617618B1EB362D10B0D1BAC6AE1ED9E8D280BBE0B6656748FD647231851C6C650794D5E6852DFA1E35E68630F'
const jsonEntry1 = {
Flags: 0,
IndexPrevious: "2",
IndexPrevious: '2',
Indexes: [
"A3454ACED87177146EABD5E4A256021D836D1E3617618B1EB362D10B0D1BAC6A",
"E1ED9E8D280BBE0B6656748FD647231851C6C650794D5E6852DFA1E35E68630F",
'A3454ACED87177146EABD5E4A256021D836D1E3617618B1EB362D10B0D1BAC6A',
'E1ED9E8D280BBE0B6656748FD647231851C6C650794D5E6852DFA1E35E68630F',
],
LedgerEntryType: "DirectoryNode",
Owner: "rHzDaMNybxQppiE3uWyt2N265KvAKdiRdP",
RootIndex: "0CB3C1AD2C371136AEA434246D971C5FCCD32CBF520667E131AB7B10D706E752",
index: "0B4A2E68C111F7E42FAEEE405F7344560C8240840B151D9D04131EB79D080167",
};
LedgerEntryType: 'DirectoryNode',
Owner: 'rHzDaMNybxQppiE3uWyt2N265KvAKdiRdP',
RootIndex: '0CB3C1AD2C371136AEA434246D971C5FCCD32CBF520667E131AB7B10D706E752',
index: '0B4A2E68C111F7E42FAEEE405F7344560C8240840B151D9D04131EB79D080167',
}
const binaryEntry2 =
"1100722200210000250178D1CA37000000000000000038000000000000028355C0C37CE200B509E0A529880634F7841A9EF4CB65F03C12E6004CFAD9718D66946280000000000000000000000000000000000000004743420000000000000000000000000000000000000000000000000166D6071AFD498D000000000000000000000000000047434200000000002599D1D255BCA61189CA64C84528F2FCBE4BFC3867800000000000000000000000000000000000000047434200000000006EEBB1D1852CE667876A0B3630861FB6C6AB358E";
'1100722200210000250178D1CA37000000000000000038000000000000028355C0C37CE200B509E0A529880634F7841A9EF4CB65F03C12E6004CFAD9718D66946280000000000000000000000000000000000000004743420000000000000000000000000000000000000000000000000166D6071AFD498D000000000000000000000000000047434200000000002599D1D255BCA61189CA64C84528F2FCBE4BFC3867800000000000000000000000000000000000000047434200000000006EEBB1D1852CE667876A0B3630861FB6C6AB358E'
const jsonEntry2 = {
Balance: {
currency: "GCB",
issuer: "rrrrrrrrrrrrrrrrrrrrBZbvji",
value: "0",
currency: 'GCB',
issuer: 'rrrrrrrrrrrrrrrrrrrrBZbvji',
value: '0',
},
Flags: 2162688,
HighLimit: {
currency: "GCB",
issuer: "rBfVgTnsdh8ckC19RM8aVGNuMZnpwrMP6n",
value: "0",
currency: 'GCB',
issuer: 'rBfVgTnsdh8ckC19RM8aVGNuMZnpwrMP6n',
value: '0',
},
HighNode: "283",
LedgerEntryType: "RippleState",
HighNode: '283',
LedgerEntryType: 'RippleState',
LowLimit: {
currency: "GCB",
issuer: "rhRFGCy2RJTA8oxkjjtYTvofPVGqcgvXWj",
value: "2000000",
currency: 'GCB',
issuer: 'rhRFGCy2RJTA8oxkjjtYTvofPVGqcgvXWj',
value: '2000000',
},
LowNode: "0",
LowNode: '0',
PreviousTxnID:
"C0C37CE200B509E0A529880634F7841A9EF4CB65F03C12E6004CFAD9718D6694",
'C0C37CE200B509E0A529880634F7841A9EF4CB65F03C12E6004CFAD9718D6694',
PreviousTxnLgrSeq: 24695242,
index: "0000041EFD027808D3F78C8352F97E324CB816318E00B977C74ECDDC7CD975B2",
};
index: '0000041EFD027808D3F78C8352F97E324CB816318E00B977C74ECDDC7CD975B2',
}
test("compareToTests[0]", () => {
expect(UInt8.from(124).compareTo(UInt64.from(124))).toBe(0);
});
test('compareToTests[0]', () => {
expect(UInt8.from(124).compareTo(UInt64.from(124))).toBe(0)
})
test("compareToTest[1]", () => {
expect(UInt64.from(124).compareTo(UInt8.from(124))).toBe(0);
});
test('compareToTest[1]', () => {
expect(UInt64.from(124).compareTo(UInt8.from(124))).toBe(0)
})
test("compareToTest[2]", () => {
expect(UInt64.from(124).compareTo(UInt8.from(123))).toBe(1);
});
test('compareToTest[2]', () => {
expect(UInt64.from(124).compareTo(UInt8.from(123))).toBe(1)
})
test("compareToTest[3]", () => {
expect(UInt8.from(124).compareTo(UInt8.from(13))).toBe(1);
});
test('compareToTest[3]', () => {
expect(UInt8.from(124).compareTo(UInt8.from(13))).toBe(1)
})
test("compareToTest[4]", () => {
expect(UInt8.from(124).compareTo(124)).toBe(0);
});
test('compareToTest[4]', () => {
expect(UInt8.from(124).compareTo(124)).toBe(0)
})
test("compareToTest[5]", () => {
expect(UInt64.from(124).compareTo(124)).toBe(0);
});
test('compareToTest[5]', () => {
expect(UInt64.from(124).compareTo(124)).toBe(0)
})
test("compareToTest[6]", () => {
expect(UInt64.from(124).compareTo(123)).toBe(1);
});
test('compareToTest[6]', () => {
expect(UInt64.from(124).compareTo(123)).toBe(1)
})
test("compareToTest[7]", () => {
expect(UInt8.from(124).compareTo(13)).toBe(1);
});
test('compareToTest[7]', () => {
expect(UInt8.from(124).compareTo(13)).toBe(1)
})
test("UInt64 from string zero", () => {
expect(UInt64.from("0")).toEqual(UInt64.from(0));
expect(encode(json)).toEqual(binary);
});
test('UInt64 from string zero', () => {
expect(UInt64.from('0')).toEqual(UInt64.from(0))
expect(encode(json)).toEqual(binary)
})
test("UInt64 from non 16 length hex", () => {
expect(encode(jsonEntry0)).toEqual(binaryEntry0);
expect(encode(jsonEntry1)).toEqual(binaryEntry1);
expect(encode(jsonEntry2)).toEqual(binaryEntry2);
});
test('UInt64 from non 16 length hex', () => {
expect(encode(jsonEntry0)).toEqual(binaryEntry0)
expect(encode(jsonEntry1)).toEqual(binaryEntry1)
expect(encode(jsonEntry2)).toEqual(binaryEntry2)
})
test("valueOfTests", () => {
let val = UInt8.from(1);
val |= 0x2;
expect(val).toBe(3);
});
test('valueOfTests', () => {
let val = UInt8.from(1)
val |= 0x2
expect(val).toBe(3)
})

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

const { encode, decode } = require("./../dist/index");
const fixtures = require("./fixtures/x-codec-fixtures.json");
const { encode, decode } = require('./../dist/index')
const fixtures = require('./fixtures/x-codec-fixtures.json')
let json_x1 = {
OwnerCount: 0,
Account: "XVXdn5wEVm5G4UhEHWDPqjvdeH361P7BsapL4m2D2XnPSwT",
Account: 'XVXdn5wEVm5G4UhEHWDPqjvdeH361P7BsapL4m2D2XnPSwT',
PreviousTxnLgrSeq: 7,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF",
'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
};
Balance: '10000000000',
}
let json_r1 = {
OwnerCount: 0,
Account: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
PreviousTxnLgrSeq: 7,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF",
'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
Balance: '10000000000',
SourceTag: 12345,
};
}
let json_null_x = {
OwnerCount: 0,
Account: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Destination: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Issuer: "XVXdn5wEVm5G4UhEHWDPqjvdeH361P4GETfNyyXGaoqBj71",
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Destination: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Issuer: 'XVXdn5wEVm5G4UhEHWDPqjvdeH361P4GETfNyyXGaoqBj71',
PreviousTxnLgrSeq: 7,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF",
'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
};
Balance: '10000000000',
}
let json_invalid_x = {
OwnerCount: 0,
Account: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Destination: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Issuer: "XVXdn5wEVm5g4UhEHWDPqjvdeH361P4GETfNyyXGaoqBj71",
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Destination: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Issuer: 'XVXdn5wEVm5g4UhEHWDPqjvdeH361P4GETfNyyXGaoqBj71',
PreviousTxnLgrSeq: 7,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF",
'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
};
Balance: '10000000000',
}
let json_null_r = {
OwnerCount: 0,
Account: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Destination: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Issuer: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Destination: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Issuer: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
PreviousTxnLgrSeq: 7,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF",
'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
};
Balance: '10000000000',
}
let invalid_json_issuer_tagged = {
OwnerCount: 0,
Account: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Destination: "rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv",
Issuer: "XVXdn5wEVm5G4UhEHWDPqjvdeH361P7BsapL4m2D2XnPSwT",
Account: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Destination: 'rLs1MzkFWCxTbuAHgjeTZK4fcCDDnf2KRv',
Issuer: 'XVXdn5wEVm5G4UhEHWDPqjvdeH361P7BsapL4m2D2XnPSwT',
PreviousTxnLgrSeq: 7,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF",
'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
};
Balance: '10000000000',
}
let invalid_json_x_and_tagged = {
OwnerCount: 0,
Account: "XVXdn5wEVm5G4UhEHWDPqjvdeH361P7BsapL4m2D2XnPSwT",
Account: 'XVXdn5wEVm5G4UhEHWDPqjvdeH361P7BsapL4m2D2XnPSwT',
PreviousTxnLgrSeq: 7,
LedgerEntryType: "AccountRoot",
LedgerEntryType: 'AccountRoot',
PreviousTxnID:
"DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF",
'DF530FB14C5304852F20080B0A8EEF3A6BDD044F41F4EBBD68B8B321145FE4FF',
Flags: 0,
Sequence: 1,
Balance: "10000000000",
Balance: '10000000000',
SourceTag: 12345,
};
}
let json_issued_x = {
TakerPays: {
currency: "USD",
issuer: "X7WZKEeNVS2p9Tire9DtNFkzWBZbFtJHWxDjN9fCrBGqVA4",
value: "7072.8",
currency: 'USD',
issuer: 'X7WZKEeNVS2p9Tire9DtNFkzWBZbFtJHWxDjN9fCrBGqVA4',
value: '7072.8',
},
};
}
let json_issued_r = {
TakerPays: {
currency: "USD",
issuer: "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
value: "7072.8",
currency: 'USD',
issuer: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B',
value: '7072.8',
},
};
}
let json_issued_with_tag = {
TakerPays: {
currency: "USD",
issuer: "X7WZKEeNVS2p9Tire9DtNFkzWBZbFtSiS2eDBib7svZXuc2",
value: "7072.8",
currency: 'USD',
issuer: 'X7WZKEeNVS2p9Tire9DtNFkzWBZbFtSiS2eDBib7svZXuc2',
value: '7072.8',
},
};
}
describe("X-Address Account is equivalent to a classic address w/ SourceTag", () => {
let encoded_x = encode(json_x1);
let encoded_r = encode(json_r1);
test("Can encode with x-Address", () => {
expect(encoded_x).toEqual(encoded_r);
});
describe('X-Address Account is equivalent to a classic address w/ SourceTag', () => {
let encoded_x = encode(json_x1)
let encoded_r = encode(json_r1)
test('Can encode with x-Address', () => {
expect(encoded_x).toEqual(encoded_r)
})
test("decoded X-address is object w/ source and tag", () => {
let decoded_x = decode(encoded_x);
expect(decoded_x).toEqual(json_r1);
});
test('decoded X-address is object w/ source and tag', () => {
let decoded_x = decode(encoded_x)
expect(decoded_x).toEqual(json_r1)
})
test("Encoding issuer X-Address w/ undefined destination tag", () => {
expect(encode(json_null_x)).toEqual(encode(json_null_r));
});
test('Encoding issuer X-Address w/ undefined destination tag', () => {
expect(encode(json_null_x)).toEqual(encode(json_null_r))
})
test("Throws when X-Address is invalid", () => {
expect(() => encode(json_invalid_x)).toThrow("checksum_invalid");
});
test('Throws when X-Address is invalid', () => {
expect(() => encode(json_invalid_x)).toThrow('checksum_invalid')
})
test("Encodes issued currency w/ x-address", () => {
expect(encode(json_issued_x)).toEqual(encode(json_issued_r));
});
});
test('Encodes issued currency w/ x-address', () => {
expect(encode(json_issued_x)).toEqual(encode(json_issued_r))
})
})
describe("Invalid X-Address behavior", () => {
test("X-Address with tag throws value for invalid field", () => {
describe('Invalid X-Address behavior', () => {
test('X-Address with tag throws value for invalid field', () => {
expect(() => encode(invalid_json_issuer_tagged)).toThrow(
new Error("Issuer cannot have an associated tag")
);
});
new Error('Issuer cannot have an associated tag'),
)
})
test("Throws when Account has both X-Addr and Destination Tag", () => {
test('Throws when Account has both X-Addr and Destination Tag', () => {
expect(() => encode(invalid_json_x_and_tagged)).toThrow(
new Error("Cannot have Account X-Address and SourceTag")
);
});
new Error('Cannot have Account X-Address and SourceTag'),
)
})
test("Throws when issued currency has tag", () => {
test('Throws when issued currency has tag', () => {
expect(() => encode(json_issued_with_tag)).toThrow(
"Only allowed to have tag on Account or Destination"
);
});
});
'Only allowed to have tag on Account or Destination',
)
})
})
describe("ripple-binary-codec x-address test", function () {
describe('ripple-binary-codec x-address test', function () {
function makeSuite(name, entries) {

@@ -172,11 +172,11 @@ describe(name, function () {

test(`${name}[${testN}] encodes X-address json equivalent to classic address json`, () => {
expect(encode(t.rjson)).toEqual(encode(t.xjson));
});
expect(encode(t.rjson)).toEqual(encode(t.xjson))
})
test(`${name}[${testN}] decodes X-address json equivalent to classic address json`, () => {
expect(decode(encode(t.xjson))).toEqual(t.rjson);
});
});
});
expect(decode(encode(t.xjson))).toEqual(t.rjson)
})
})
})
}
makeSuite("transactions", fixtures.transactions);
});
makeSuite('transactions', fixtures.transactions)
})

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

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 too big to display

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