FRE-600: Fix code review blockers

- Consolidated duplicate UndoManagers to single instance
- Fixed connection promise to only resolve on 'connected' status
- Fixed WebSocketProvider import (WebsocketProvider)
- Added proper doc.destroy() cleanup
- Renamed isPresenceInitialized property to avoid conflict

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
2026-04-25 00:08:01 -04:00
parent 65b552bb08
commit 7c684a42cc
48450 changed files with 5679671 additions and 383 deletions

201
node_modules/borsh/LICENSE-APACHE generated vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2019 Near
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

23
node_modules/borsh/LICENSE-MIT.txt generated vendored Normal file
View File

@@ -0,0 +1,23 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

83
node_modules/borsh/README.md generated vendored Normal file
View File

@@ -0,0 +1,83 @@
# Borsh JS
[![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM)
[![Travis status](https://travis-ci.com/near/borsh.svg?branch=master)](https://travis-ci.com/near/borsh-js)
[![NPM version](https://img.shields.io/npm/v/borsh.svg?style=flat-square)](https://npmjs.com/borsh)
[![Size on NPM](https://img.shields.io/bundlephobia/minzip/borsh.svg?style=flat-square)](https://npmjs.com/borsh)
**Borsh JS** is an implementation of the [Borsh] binary serialization format for
JavaScript and TypeScript projects.
Borsh stands for _Binary Object Representation Serializer for Hashing_. It is meant to be used in security-critical projects as it prioritizes consistency,
safety, speed, and comes with a strict specification.
## Examples
### Serializing an object
```javascript
const value = new Test({ x: 255, y: 20, z: '123', q: [1, 2, 3] });
const schema = new Map([[Test, { kind: 'struct', fields: [['x', 'u8'], ['y', 'u64'], ['z', 'string'], ['q', [3]]] }]]);
const buffer = borsh.serialize(schema, value);
```
### Deserializing an object
```javascript
const newValue = borsh.deserialize(schema, Test, buffer);
```
## Type Mappings
| Borsh | TypeScript |
|-----------------------|----------------|
| `u8` integer | `number` |
| `u16` integer | `number` |
| `u32` integer | `number` |
| `u64` integer | `BN` |
| `u128` integer | `BN` |
| `u256` integer | `BN` |
| `u512` integer | `BN` |
| `f32` float | N/A |
| `f64` float | N/A |
| fixed-size byte array | `Uint8Array` |
| UTF-8 string | `string` |
| option | `null` or type |
| map | N/A |
| set | N/A |
| structs | `any` |
## Contributing
Install dependencies:
```bash
yarn install
```
Continuously build with:
```bash
yarn dev
```
Run tests:
```bash
yarn test
```
Run linter
```bash
yarn lint
```
## Publish
Prepare `dist` version by running:
```bash
yarn build
```
When publishing to npm use [np](https://github.com/sindresorhus/np).
# License
This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0).
See [LICENSE-MIT](LICENSE-MIT.txt) and [LICENSE-APACHE](LICENSE-APACHE) for details.
[Borsh]: https://borsh.io

52
node_modules/borsh/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,52 @@
/// <reference types="node" />
import BN from "bn.js";
export declare function baseEncode(value: Uint8Array | string): string;
export declare function baseDecode(value: string): Buffer;
export declare type Schema = Map<Function, any>;
export declare class BorshError extends Error {
originalMessage: string;
fieldPath: string[];
constructor(message: string);
addToFieldPath(fieldName: string): void;
}
export declare class BinaryWriter {
buf: Buffer;
length: number;
constructor();
maybeResize(): void;
writeU8(value: number): void;
writeU16(value: number): void;
writeU32(value: number): void;
writeU64(value: number | BN): void;
writeU128(value: number | BN): void;
writeU256(value: number | BN): void;
writeU512(value: number | BN): void;
private writeBuffer;
writeString(str: string): void;
writeFixedArray(array: Uint8Array): void;
writeArray(array: any[], fn: any): void;
toArray(): Uint8Array;
}
export declare class BinaryReader {
buf: Buffer;
offset: number;
constructor(buf: Buffer);
readU8(): number;
readU16(): number;
readU32(): number;
readU64(): BN;
readU128(): BN;
readU256(): BN;
readU512(): BN;
private readBuffer;
readString(): string;
readFixedArray(len: number): Uint8Array;
readArray(fn: any): any[];
}
export declare function serialize(schema: Schema, obj: any, Writer?: typeof BinaryWriter): Uint8Array;
export declare function deserialize<T>(schema: Schema, classType: {
new (args: any): T;
}, buffer: Buffer, Reader?: typeof BinaryReader): T;
export declare function deserializeUnchecked<T>(schema: Schema, classType: {
new (args: any): T;
}, buffer: Buffer, Reader?: typeof BinaryReader): T;

440
node_modules/borsh/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,440 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deserializeUnchecked = exports.deserialize = exports.serialize = exports.BinaryReader = exports.BinaryWriter = exports.BorshError = exports.baseDecode = exports.baseEncode = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const bs58_1 = __importDefault(require("bs58"));
// TODO: Make sure this polyfill not included when not required
const encoding = __importStar(require("text-encoding-utf-8"));
const ResolvedTextDecoder = typeof TextDecoder !== "function" ? encoding.TextDecoder : TextDecoder;
const textDecoder = new ResolvedTextDecoder("utf-8", { fatal: true });
function baseEncode(value) {
if (typeof value === "string") {
value = Buffer.from(value, "utf8");
}
return bs58_1.default.encode(Buffer.from(value));
}
exports.baseEncode = baseEncode;
function baseDecode(value) {
return Buffer.from(bs58_1.default.decode(value));
}
exports.baseDecode = baseDecode;
const INITIAL_LENGTH = 1024;
class BorshError extends Error {
constructor(message) {
super(message);
this.fieldPath = [];
this.originalMessage = message;
}
addToFieldPath(fieldName) {
this.fieldPath.splice(0, 0, fieldName);
// NOTE: Modifying message directly as jest doesn't use .toString()
this.message = this.originalMessage + ": " + this.fieldPath.join(".");
}
}
exports.BorshError = BorshError;
/// Binary encoder.
class BinaryWriter {
constructor() {
this.buf = Buffer.alloc(INITIAL_LENGTH);
this.length = 0;
}
maybeResize() {
if (this.buf.length < 16 + this.length) {
this.buf = Buffer.concat([this.buf, Buffer.alloc(INITIAL_LENGTH)]);
}
}
writeU8(value) {
this.maybeResize();
this.buf.writeUInt8(value, this.length);
this.length += 1;
}
writeU16(value) {
this.maybeResize();
this.buf.writeUInt16LE(value, this.length);
this.length += 2;
}
writeU32(value) {
this.maybeResize();
this.buf.writeUInt32LE(value, this.length);
this.length += 4;
}
writeU64(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 8)));
}
writeU128(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 16)));
}
writeU256(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 32)));
}
writeU512(value) {
this.maybeResize();
this.writeBuffer(Buffer.from(new bn_js_1.default(value).toArray("le", 64)));
}
writeBuffer(buffer) {
// Buffer.from is needed as this.buf.subarray can return plain Uint8Array in browser
this.buf = Buffer.concat([
Buffer.from(this.buf.subarray(0, this.length)),
buffer,
Buffer.alloc(INITIAL_LENGTH),
]);
this.length += buffer.length;
}
writeString(str) {
this.maybeResize();
const b = Buffer.from(str, "utf8");
this.writeU32(b.length);
this.writeBuffer(b);
}
writeFixedArray(array) {
this.writeBuffer(Buffer.from(array));
}
writeArray(array, fn) {
this.maybeResize();
this.writeU32(array.length);
for (const elem of array) {
this.maybeResize();
fn(elem);
}
}
toArray() {
return this.buf.subarray(0, this.length);
}
}
exports.BinaryWriter = BinaryWriter;
function handlingRangeError(target, propertyKey, propertyDescriptor) {
const originalMethod = propertyDescriptor.value;
propertyDescriptor.value = function (...args) {
try {
return originalMethod.apply(this, args);
}
catch (e) {
if (e instanceof RangeError) {
const code = e.code;
if (["ERR_BUFFER_OUT_OF_BOUNDS", "ERR_OUT_OF_RANGE"].indexOf(code) >= 0) {
throw new BorshError("Reached the end of buffer when deserializing");
}
}
throw e;
}
};
}
class BinaryReader {
constructor(buf) {
this.buf = buf;
this.offset = 0;
}
readU8() {
const value = this.buf.readUInt8(this.offset);
this.offset += 1;
return value;
}
readU16() {
const value = this.buf.readUInt16LE(this.offset);
this.offset += 2;
return value;
}
readU32() {
const value = this.buf.readUInt32LE(this.offset);
this.offset += 4;
return value;
}
readU64() {
const buf = this.readBuffer(8);
return new bn_js_1.default(buf, "le");
}
readU128() {
const buf = this.readBuffer(16);
return new bn_js_1.default(buf, "le");
}
readU256() {
const buf = this.readBuffer(32);
return new bn_js_1.default(buf, "le");
}
readU512() {
const buf = this.readBuffer(64);
return new bn_js_1.default(buf, "le");
}
readBuffer(len) {
if (this.offset + len > this.buf.length) {
throw new BorshError(`Expected buffer length ${len} isn't within bounds`);
}
const result = this.buf.slice(this.offset, this.offset + len);
this.offset += len;
return result;
}
readString() {
const len = this.readU32();
const buf = this.readBuffer(len);
try {
// NOTE: Using TextDecoder to fail on invalid UTF-8
return textDecoder.decode(buf);
}
catch (e) {
throw new BorshError(`Error decoding UTF-8 string: ${e}`);
}
}
readFixedArray(len) {
return new Uint8Array(this.readBuffer(len));
}
readArray(fn) {
const len = this.readU32();
const result = Array();
for (let i = 0; i < len; ++i) {
result.push(fn());
}
return result;
}
}
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU8", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU16", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU32", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU64", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU128", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU256", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readU512", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readString", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readFixedArray", null);
__decorate([
handlingRangeError
], BinaryReader.prototype, "readArray", null);
exports.BinaryReader = BinaryReader;
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function serializeField(schema, fieldName, value, fieldType, writer) {
try {
// TODO: Handle missing values properly (make sure they never result in just skipped write)
if (typeof fieldType === "string") {
writer[`write${capitalizeFirstLetter(fieldType)}`](value);
}
else if (fieldType instanceof Array) {
if (typeof fieldType[0] === "number") {
if (value.length !== fieldType[0]) {
throw new BorshError(`Expecting byte array of length ${fieldType[0]}, but got ${value.length} bytes`);
}
writer.writeFixedArray(value);
}
else if (fieldType.length === 2 && typeof fieldType[1] === "number") {
if (value.length !== fieldType[1]) {
throw new BorshError(`Expecting byte array of length ${fieldType[1]}, but got ${value.length} bytes`);
}
for (let i = 0; i < fieldType[1]; i++) {
serializeField(schema, null, value[i], fieldType[0], writer);
}
}
else {
writer.writeArray(value, (item) => {
serializeField(schema, fieldName, item, fieldType[0], writer);
});
}
}
else if (fieldType.kind !== undefined) {
switch (fieldType.kind) {
case "option": {
if (value === null || value === undefined) {
writer.writeU8(0);
}
else {
writer.writeU8(1);
serializeField(schema, fieldName, value, fieldType.type, writer);
}
break;
}
case "map": {
writer.writeU32(value.size);
value.forEach((val, key) => {
serializeField(schema, fieldName, key, fieldType.key, writer);
serializeField(schema, fieldName, val, fieldType.value, writer);
});
break;
}
default:
throw new BorshError(`FieldType ${fieldType} unrecognized`);
}
}
else {
serializeStruct(schema, value, writer);
}
}
catch (error) {
if (error instanceof BorshError) {
error.addToFieldPath(fieldName);
}
throw error;
}
}
function serializeStruct(schema, obj, writer) {
if (typeof obj.borshSerialize === "function") {
obj.borshSerialize(writer);
return;
}
const structSchema = schema.get(obj.constructor);
if (!structSchema) {
throw new BorshError(`Class ${obj.constructor.name} is missing in schema`);
}
if (structSchema.kind === "struct") {
structSchema.fields.map(([fieldName, fieldType]) => {
serializeField(schema, fieldName, obj[fieldName], fieldType, writer);
});
}
else if (structSchema.kind === "enum") {
const name = obj[structSchema.field];
for (let idx = 0; idx < structSchema.values.length; ++idx) {
const [fieldName, fieldType] = structSchema.values[idx];
if (fieldName === name) {
writer.writeU8(idx);
serializeField(schema, fieldName, obj[fieldName], fieldType, writer);
break;
}
}
}
else {
throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${obj.constructor.name}`);
}
}
/// Serialize given object using schema of the form:
/// { class_name -> [ [field_name, field_type], .. ], .. }
function serialize(schema, obj, Writer = BinaryWriter) {
const writer = new Writer();
serializeStruct(schema, obj, writer);
return writer.toArray();
}
exports.serialize = serialize;
function deserializeField(schema, fieldName, fieldType, reader) {
try {
if (typeof fieldType === "string") {
return reader[`read${capitalizeFirstLetter(fieldType)}`]();
}
if (fieldType instanceof Array) {
if (typeof fieldType[0] === "number") {
return reader.readFixedArray(fieldType[0]);
}
else if (typeof fieldType[1] === "number") {
const arr = [];
for (let i = 0; i < fieldType[1]; i++) {
arr.push(deserializeField(schema, null, fieldType[0], reader));
}
return arr;
}
else {
return reader.readArray(() => deserializeField(schema, fieldName, fieldType[0], reader));
}
}
if (fieldType.kind === "option") {
const option = reader.readU8();
if (option) {
return deserializeField(schema, fieldName, fieldType.type, reader);
}
return undefined;
}
if (fieldType.kind === "map") {
let map = new Map();
const length = reader.readU32();
for (let i = 0; i < length; i++) {
const key = deserializeField(schema, fieldName, fieldType.key, reader);
const val = deserializeField(schema, fieldName, fieldType.value, reader);
map.set(key, val);
}
return map;
}
return deserializeStruct(schema, fieldType, reader);
}
catch (error) {
if (error instanceof BorshError) {
error.addToFieldPath(fieldName);
}
throw error;
}
}
function deserializeStruct(schema, classType, reader) {
if (typeof classType.borshDeserialize === "function") {
return classType.borshDeserialize(reader);
}
const structSchema = schema.get(classType);
if (!structSchema) {
throw new BorshError(`Class ${classType.name} is missing in schema`);
}
if (structSchema.kind === "struct") {
const result = {};
for (const [fieldName, fieldType] of schema.get(classType).fields) {
result[fieldName] = deserializeField(schema, fieldName, fieldType, reader);
}
return new classType(result);
}
if (structSchema.kind === "enum") {
const idx = reader.readU8();
if (idx >= structSchema.values.length) {
throw new BorshError(`Enum index: ${idx} is out of range`);
}
const [fieldName, fieldType] = structSchema.values[idx];
const fieldValue = deserializeField(schema, fieldName, fieldType, reader);
return new classType({ [fieldName]: fieldValue });
}
throw new BorshError(`Unexpected schema kind: ${structSchema.kind} for ${classType.constructor.name}`);
}
/// Deserializes object from bytes using schema.
function deserialize(schema, classType, buffer, Reader = BinaryReader) {
const reader = new Reader(buffer);
const result = deserializeStruct(schema, classType, reader);
if (reader.offset < buffer.length) {
throw new BorshError(`Unexpected ${buffer.length - reader.offset} bytes after deserialized data`);
}
return result;
}
exports.deserialize = deserialize;
/// Deserializes object from bytes using schema, without checking the length read
function deserializeUnchecked(schema, classType, buffer, Reader = BinaryReader) {
const reader = new Reader(buffer);
return deserializeStruct(schema, classType, reader);
}
exports.deserializeUnchecked = deserializeUnchecked;

22
node_modules/borsh/node_modules/base-x/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2018 base-x contributors
Copyright (c) 2014-2018 The Bitcoin Core developers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

67
node_modules/borsh/node_modules/base-x/README.md generated vendored Normal file
View File

@@ -0,0 +1,67 @@
# base-x
[![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x)
[![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x)
[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
Fast base encoding / decoding of any given alphabet using bitcoin style leading
zero compression.
**WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner.
## Example
Base58
``` javascript
var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
var bs58 = require('base-x')(BASE58)
var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr')
console.log(decoded)
// => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19>
console.log(bs58.encode(decoded))
// => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr
```
### Alphabets
See below for a list of commonly recognized alphabets, and their respective base.
Base | Alphabet
------------- | -------------
2 | `01`
8 | `01234567`
11 | `0123456789a`
16 | `0123456789abcdef`
32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ`
32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32)
36 | `0123456789abcdefghijklmnopqrstuvwxyz`
58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`
62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`
67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~`
## How it works
It encodes octet arrays by doing long divisions on all significant digits in the
array, creating a representation of that number in the new base. Then for every
leading zero in the input (not significant as a number) it will encode as a
single leader character. This is the first in the alphabet and will decode as 8
bits. The other characters depend upon the base. For example, a base58 alphabet
packs roughly 5.858 bits per character.
This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode
to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each
character.
While unusual, this does mean that no padding is required and it works for bases
like 43.
## LICENSE [MIT](LICENSE)
A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets.

49
node_modules/borsh/node_modules/base-x/package.json generated vendored Normal file
View File

@@ -0,0 +1,49 @@
{
"name": "base-x",
"version": "3.0.11",
"description": "Fast base encoding / decoding of any given alphabet",
"keywords": [
"base-x",
"base58",
"base62",
"base64",
"crypto",
"crytography",
"decode",
"decoding",
"encode",
"encoding"
],
"homepage": "https://github.com/cryptocoinjs/base-x",
"bugs": {
"url": "https://github.com/cryptocoinjs/base-x/issues"
},
"license": "MIT",
"author": "Daniel Cousens",
"files": [
"src"
],
"main": "src/index.js",
"types": "src/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/cryptocoinjs/base-x.git"
},
"scripts": {
"build": "tsc -p ./tsconfig.json ; standard --fix",
"gitdiff": "npm run build && git diff --exit-code",
"prepublish": "npm run gitdiff",
"standard": "standard",
"test": "npm run unit && npm run standard",
"unit": "tape test/*.js"
},
"devDependencies": {
"@types/node": "12.0.10",
"standard": "^10.0.3",
"tape": "^4.5.1",
"typescript": "3.5.2"
},
"dependencies": {
"safe-buffer": "^5.0.1"
}
}

10
node_modules/borsh/node_modules/base-x/src/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
/// <reference types="node" />
declare function base(ALPHABET: string): base.BaseConverter;
export = base;
declare namespace base {
interface BaseConverter {
encode(buffer: Buffer | number[] | Uint8Array): string;
decodeUnsafe(string: string): Buffer | undefined;
decode(string: string): Buffer;
}
}

123
node_modules/borsh/node_modules/base-x/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
'use strict'
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
// @ts-ignore
var _Buffer = require('safe-buffer').Buffer
function base (ALPHABET) {
if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
var BASE_MAP = new Uint8Array(256)
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i)
var xc = x.charCodeAt(0)
if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
BASE_MAP[xc] = i
}
var BASE = ALPHABET.length
var LEADER = ALPHABET.charAt(0)
var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up
function encode (source) {
if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }
if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }
if (source.length === 0) { return '' }
// Skip & count leading zeroes.
var zeroes = 0
var length = 0
var pbegin = 0
var pend = source.length
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++
zeroes++
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0
var b58 = new Uint8Array(size)
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin]
// Apply "b58 = b58 * 256 + ch".
var i = 0
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0
b58[it1] = (carry % BASE) >>> 0
carry = (carry / BASE) >>> 0
}
if (carry !== 0) { throw new Error('Non-zero carry') }
length = i
pbegin++
}
// Skip leading zeroes in base58 result.
var it2 = size - length
while (it2 !== size && b58[it2] === 0) {
it2++
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes)
for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }
return str
}
function decodeUnsafe (source) {
if (typeof source !== 'string') { throw new TypeError('Expected String') }
if (source.length === 0) { return _Buffer.alloc(0) }
var psz = 0
// Skip and count leading '1's.
var zeroes = 0
var length = 0
while (source[psz] === LEADER) {
zeroes++
psz++
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size)
// Process the characters.
while (psz < source.length) {
// Find code of next character
var charCode = source.charCodeAt(psz)
// Base map can not be indexed using char code
if (charCode > 255) { return }
// Decode character
var carry = BASE_MAP[charCode]
// Invalid character
if (carry === 255) { return }
var i = 0
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0
b256[it3] = (carry % 256) >>> 0
carry = (carry / 256) >>> 0
}
if (carry !== 0) { throw new Error('Non-zero carry') }
length = i
psz++
}
// Skip leading zeroes in b256.
var it4 = size - length
while (it4 !== size && b256[it4] === 0) {
it4++
}
var vch = _Buffer.allocUnsafe(zeroes + (size - it4))
vch.fill(0x00, 0, zeroes)
var j = zeroes
while (it4 !== size) {
vch[j++] = b256[it4++]
}
return vch
}
function decode (string) {
var buffer = decodeUnsafe(string)
if (buffer) { return buffer }
throw new Error('Non-base' + BASE + ' character')
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
}
}
module.exports = base

61
node_modules/borsh/node_modules/bs58/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,61 @@
4.0.0 / 2016-12-3
------------------
- `decode` now returns a `Buffer` again, to avoid potential cryptographic errors. [Daniel Cousens / #21](https://github.com/cryptocoinjs/bs58/pull/21)
3.0.0 / 2015-08-18
------------------
- refactored module into generic [`base-x`](https://github.com/cryptocoinjs/base-x).
2.0.1 / 2014-12-23
------------------
- performance boost in `encode()` [#10](https://github.com/cryptocoinjs/bs58/pull/10)
2.0.0 / 2014-10-03
------------------
- `decode` now returns an `Array` instead of `Buffer` to keep things simple. [Daniel Cousens / #9](https://github.com/cryptocoinjs/bs58/pull/9)
1.2.1 / 2014-07-24
------------------
* speed optimizations [Daniel Cousens / #8](https://github.com/cryptocoinjs/bs58/pull/8)
1.2.0 / 2014-06-29
------------------
* removed `bigi` dep, implemented direct byte conversion [Jared Deckard / #6](https://github.com/cryptocoinjs/bs58/pull/6)
1.1.0 / 2014-06-26
------------------
* user `Buffer` internally for calculations, providing cleaner code and a performance increase. [Daniel Cousens](https://github.com/cryptocoinjs/bs58/commit/129c71de8bc1e36f113bce06da0616066f41c5ca)
1.0.0 / 2014-05-27
------------------
* removed `binstring` dep, `Buffer` now only input to `encode()` and output of `decode()`
* update `bigi` from `~0.3.0` to `^1.1.0`
* added travis-ci support
* added coveralls support
* modified tests and library to handle fixture style testing (thanks to bitcoinjs-lib devs and [Daniel Cousens](https://github.com/dcousens))
0.3.0 / 2014-02-24
------------------
* duck type input to `encode` and change output of `decode` to `Buffer`.
0.2.1 / 2014-02-24
------------------
* removed bower and component support. Closes #1
* convert from 4 spaces to 2
0.2.0 / 2013-12-07
------------------
* renamed from `cryptocoin-base58` to `bs58`
0.1.0 / 2013-11-20
------------------
* removed AMD support
0.0.1 / 2013-11-04
------------------
* initial release

71
node_modules/borsh/node_modules/bs58/README.md generated vendored Normal file
View File

@@ -0,0 +1,71 @@
bs58
====
[![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58)
JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin.
**Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library.
Install
-------
npm i --save bs58
API
---
### encode(input)
`input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`.
**example**:
```js
const bs58 = require('bs58')
const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex')
const address = bs58.encode(bytes)
console.log(address)
// => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS
```
### decode(input)
`input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html).
**example**:
```js
const bs58 = require('bs58')
const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS'
const bytes = bs58.decode(address)
console.log(out.toString('hex'))
// => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187
```
Hack / Test
-----------
Uses JavaScript standard style. Read more:
[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
Credits
-------
- [Mike Hearn](https://github.com/mikehearn) for original Java implementation
- [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript
- [Stephan Pair](https://github.com/gasteve) for buffer improvements
- [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib
- [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency
License
-------
MIT

4
node_modules/borsh/node_modules/bs58/index.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
var basex = require('base-x')
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
module.exports = basex(ALPHABET)

37
node_modules/borsh/node_modules/bs58/package.json generated vendored Normal file
View File

@@ -0,0 +1,37 @@
{
"name": "bs58",
"version": "4.0.1",
"description": "Base 58 encoding / decoding",
"keywords": [
"base58",
"bitcoin",
"crypto",
"crytography",
"decode",
"decoding",
"encode",
"encoding",
"litecoin"
],
"license": "MIT",
"devDependencies": {
"standard": "*",
"tape": "^4.6.3"
},
"repository": {
"url": "https://github.com/cryptocoinjs/bs58",
"type": "git"
},
"files": [
"./index.js"
],
"main": "./index.js",
"scripts": {
"standard": "standard",
"test": "npm run standard && npm run unit",
"unit": "tape test/index.js"
},
"dependencies": {
"base-x": "^3.0.2"
}
}

61
node_modules/borsh/package.json generated vendored Normal file
View File

@@ -0,0 +1,61 @@
{
"name": "borsh",
"version": "0.7.0",
"description": "Binary Object Representation Serializer for Hashing",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib",
"LICENSE-APACHE",
"LICENSE-MIT.txt"
],
"scripts": {
"build": "tsc -p ./tsconfig.json",
"test": "jest test --runInBand",
"fuzz": "jsfuzz borsh-ts/test/fuzz/borsh-roundtrip.js borsh-ts/test/fuzz/corpus/",
"dev": "yarn build -w",
"pretest": "yarn build",
"lint": "eslint borsh-ts/**/*.ts",
"pretty": "prettier --write borsh-ts/**/*.ts package.json",
"pretty:check": "yarn prettier --loglevel error --check borsh-ts/**/*.ts package.json",
"fix": "eslint borsh-ts/**/*.ts --fix"
},
"repository": {
"type": "git",
"url": "git+https://github.com/near/borsh-js.git"
},
"keywords": [
"serializer",
"binary",
"serializer",
"deserializer",
"consistency",
"deterministic"
],
"author": "Near Inc",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/near/borsh-js/issues"
},
"homepage": "https://github.com/near/borsh-js#readme",
"devDependencies": {
"@types/babel__core": "^7.1.2",
"@types/babel__template": "^7.0.2",
"@types/bn.js": "^5.1.0",
"@types/node": "^12.7.3",
"@typescript-eslint/eslint-plugin": "^2.18.0",
"@typescript-eslint/parser": "^2.18.0",
"bs58": "^4.0.0",
"eslint": "^6.5.1",
"jest": "^26.0.1",
"js-sha256": "^0.9.0",
"jsfuzz": "^1.0.14",
"prettier": "^2.4.1",
"typescript": "^3.6.2"
},
"dependencies": {
"bn.js": "^5.2.0",
"bs58": "^4.0.0",
"text-encoding-utf-8": "^1.0.2"
}
}