Socket
Socket
Sign inDemoInstall

@mysten/bcs

Package Overview
Dependencies
Maintainers
2
Versions
518
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mysten/bcs - npm Package Compare versions

Comparing version 0.1.0 to 0.2.0

CHANGELOG.md

210

dist/bcs.cjs.development.js

@@ -404,3 +404,3 @@ 'use strict';

function fromB64(sBase64, nBlocksSize) {
var sB64Enc = sBase64.replace(/[^A-Za-z0-9+/]/g, ""),
var sB64Enc = sBase64.replace(/[^A-Za-z0-9+/]/g, ''),
nInLen = sB64Enc.length,

@@ -433,3 +433,3 @@ nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2,

var nMod3 = 2,
sB64Enc = "";
sB64Enc = '';

@@ -440,3 +440,3 @@ for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {

if (nIdx > 0 && nIdx * 4 / 3 % 76 === 0) {
sB64Enc += "";
sB64Enc += '';
}

@@ -452,3 +452,3 @@

return sB64Enc.slice(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "==");
return sB64Enc.slice(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '==');
}

@@ -460,3 +460,3 @@

// @ts-ignore
var intArr = hexStr.replace("0x", "").match(/.{1,2}/g).map(function (_byte) {
var intArr = hexStr.replace('0x', '').match(/.{1,2}/g).map(function (_byte) {
return parseInt(_byte, 16);

@@ -473,4 +473,4 @@ });

return bytes.reduce(function (str, _byte2) {
return str + _byte2.toString(16).padStart(2, "0");
}, "");
return str + _byte2.toString(16).padStart(2, '0');
}, '');
}

@@ -494,3 +494,3 @@

*
* Reading vectors is another deal in BCS. To read a vector, you first need to read
* Reading vectors is another deal in bcs. To read a vector, you first need to read
* its length using {@link readULEB}. Here's an example:

@@ -574,3 +574,3 @@ * @example

var value2 = this.read32();
var result = value2.toString(16) + value1.toString(16).padStart(8, "0");
var result = value2.toString(16) + value1.toString(16).padStart(8, '0');
return new BN.BN(result, 16);

@@ -587,3 +587,3 @@ }

var value2 = this.read64();
var result = value2.toString(16) + value1.toString(16).padStart(8, "0");
var result = value2.toString(16) + value1.toString(16).padStart(8, '0');
return new BN.BN(result, 16);

@@ -676,7 +676,7 @@ }

switch (typeof number) {
case "boolean":
case 'boolean':
number = +number;
return new BN.BN(number.toString());
case "bigint":
case 'bigint':
return new BN.BN(number.toString());

@@ -745,3 +745,3 @@

BcsWriter.toBN(value).toArray("le", 8).forEach(function (el) {
BcsWriter.toBN(value).toArray('le', 8).forEach(function (el) {
return _this.write8(el);

@@ -763,3 +763,3 @@ });

BcsWriter.toBN(value).toArray("le", 16).forEach(function (el) {
BcsWriter.toBN(value).toArray('le', 16).forEach(function (el) {
return _this2.write8(el);

@@ -846,3 +846,3 @@ });

* Get underlying buffer taking only value bytes (in case initial buffer size was bigger).
* @returns {Uint8Array} Resulting BCS.
* @returns {Uint8Array} Resulting bcs.
*/

@@ -918,10 +918,10 @@ ;

var BCS = /*#__PURE__*/function () {
function BCS() {}
var bcs = /*#__PURE__*/function () {
function bcs() {}
/**
* Serialize data into BCS.
* Serialize data into bcs.
*
* @example
* BCS.registerVectorType('vector<u8>', 'u8');
* bcs.registerVectorType('vector<u8>', 'u8');
*

@@ -932,3 +932,3 @@ * let serialized = BCS

*
* console.assert(BCS.util.toHex(serialized) === '06010203040506');
* console.assert(toHex(serialized) === '06010203040506');
*

@@ -940,3 +940,3 @@ * @param type Name of the type to serialize (must be registered).

*/
BCS.ser = function ser(type, data, size) {
bcs.ser = function ser(type, data, size) {
if (size === void 0) {

@@ -952,8 +952,9 @@ size = 1024;

* @example
* // use util to form an Uint8Array buffer
* let data = BCS.de(BCS.U32, new Uint8Array([255, 255, 255, 255]));
* console.assert(data.toString() == '4294967295');
* let num = bcs.ser('u64', '4294967295').toString('hex');
* let deNum = bcs.de('u64', num, 'hex');
* console.assert(deNum.toString(10) === '4294967295');
*
* @param type Name of the type to deserialize (must be registered).
* @param data Data to deserialize.
* @param encoding Optional - encoding to use if data is of type String
* @return Deserialized data.

@@ -963,3 +964,11 @@ */

BCS.de = function de(type, data) {
bcs.de = function de(type, data, encoding) {
if (typeof data == 'string') {
if (encoding) {
data = decodeStr(data, encoding);
} else {
throw new Error('To pass a string to `bcs.de`, specify encoding');
}
}
return this.getTypeInterface(type).decode(data);

@@ -974,3 +983,3 @@ }

BCS.hasType = function hasType(type) {
bcs.hasType = function hasType(type) {
return this.types.has(type);

@@ -988,3 +997,3 @@ }

* // our type would be a string that consists only of numbers
* BCS.registerType('number_string',
* bcs.registerType('number_string',
* (writer, data) => writer.writeVec(data, (w, el) => w.write8(el)),

@@ -994,3 +1003,3 @@ * (reader) => reader.readVec((r) => r.read8()).join(''), // read each value as u8

* );
* console.log(Array.from(BCS.set('number_string', '12345').toBytes()) == [5,1,2,3,4,5]);
* console.log(Array.from(bcs.ser('number_string', '12345').toBytes()) == [5,1,2,3,4,5]);
*

@@ -1004,3 +1013,3 @@ * @param name

BCS.registerType = function registerType(name, encodeCb, decodeCb, validateCb) {
bcs.registerType = function registerType(name, encodeCb, decodeCb, validateCb) {
if (validateCb === void 0) {

@@ -1041,4 +1050,4 @@ validateCb = function validateCb() {

* @example
* BCS.registerAddressType('address', 20);
* let addr = BCS.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026');
* bcs.registerAddressType('address', 20);
* let addr = bcs.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026');
*

@@ -1052,9 +1061,9 @@ * @param name Name of the address type.

BCS.registerAddressType = function registerAddressType(name, length, encoding) {
bcs.registerAddressType = function registerAddressType(name, length, encoding) {
if (encoding === void 0) {
encoding = "hex";
encoding = 'hex';
}
switch (encoding) {
case "base64":
case 'base64':
return this.registerType(name, function (writer, data) {

@@ -1068,3 +1077,3 @@ return fromB64(data).reduce(function (writer, el) {

case "hex":
case 'hex':
return this.registerType(name, function (writer, data) {

@@ -1079,19 +1088,15 @@ return fromHEX(data).reduce(function (writer, el) {

default:
throw new Error("Unsupported encoding! Use either hex or base64");
throw new Error('Unsupported encoding! Use either hex or base64');
}
}
/**
* Register custom vector type inside the BCS.
* Register custom vector type inside the bcs.
*
* @example
* BCS.registerVectorType('vector<u8>', 'u8');
* let array = BCS.de('vector<u8>', new Uint8Array([6,1,2,3,4,5,6])); // [1,2,3,4,5,6];
* let again = BCS.set('vector<u8>', [1,2,3,4,5,6]).toBytes();
* bcs.registerVectorType('vector<u8>', 'u8');
* let array = bcs.de('vector<u8>', '06010203040506', 'hex'); // [1,2,3,4,5,6];
* let again = bcs.ser('vector<u8>', [1,2,3,4,5,6]).toString('hex');
*
* BCS.registerVectorType('vector<u8>', 'u8', 'hex');
* let array =
*
* @param name Name of the type to register.
* @param elementType Name of the inner type of the vector.
* @param encoding Either 'base64' or 'hex' to enable string<->vector conversions
* @param name Name of the type to register
* @param elementType Name of the inner type of the vector
* @return Returns self for chaining.

@@ -1101,10 +1106,10 @@ */

BCS.registerVectorType = function registerVectorType(name, elementType) {
bcs.registerVectorType = function registerVectorType(name, elementType) {
return this.registerType(name, function (writer, data) {
return writer.writeVec(data, function (writer, el) {
return BCS.getTypeInterface(elementType)._encodeRaw(writer, el);
return bcs.getTypeInterface(elementType)._encodeRaw(writer, el);
});
}, function (reader) {
return reader.readVec(function (reader) {
return BCS.getTypeInterface(elementType)._decodeRaw(reader);
return bcs.getTypeInterface(elementType)._decodeRaw(reader);
});

@@ -1129,6 +1134,6 @@ });

*
* BCS.registerStructType('Coin', {
* value: BCS.U64,
* owner: BCS.STRING,
* is_locked: BCS.BOOL
* bcs.registerStructType('Coin', {
* value: bcs.U64,
* owner: bcs.STRING,
* is_locked: bcs.BOOL
* });

@@ -1138,3 +1143,3 @@ *

* // let rust_bcs_str = '80d1b105600000000e4269672057616c6c65742047757900';
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Buffer
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Array
* 128, 209, 177, 5, 96, 0, 0,

@@ -1147,3 +1152,3 @@ * 0, 14, 66, 105, 103, 32, 87,

* // Let's encode the value as well
* let test_set = BCS.set('Coin', {
* let test_set = bcs.ser('Coin', {
* owner: 'Big Wallet Guy',

@@ -1162,3 +1167,3 @@ * value: '412412400000',

BCS.registerStructType = function registerStructType(name, fields) {
bcs.registerStructType = function registerStructType(name, fields) {
var struct = Object.freeze(fields); // Make sure the order doesn't get changed

@@ -1181,3 +1186,3 @@ // IMPORTANT: we need to store canonical order of fields for each registered

if (key in data) {
BCS.getTypeInterface(struct[key])._encodeRaw(writer, data[key]);
bcs.getTypeInterface(struct[key])._encodeRaw(writer, data[key]);
} else {

@@ -1194,3 +1199,3 @@ throw new Error("Struct " + name + " requires field " + key + ":" + struct[key]);

var key = _step2.value;
result[key] = BCS.getTypeInterface(struct[key])._decodeRaw(reader);
result[key] = bcs.getTypeInterface(struct[key])._decodeRaw(reader);
}

@@ -1204,5 +1209,5 @@

* @example
* BCS.registerStructType('Coin', { value: 'u64' });
* BCS.registerVectorType('vector<Coin>', 'Coin');
* BCS.registerEnumType('MyEnum', {
* bcs.registerStructType('Coin', { value: 'u64' });
* bcs.registerVectorType('vector<Coin>', 'Coin');
* bcs.registerEnumType('MyEnum', {
* single: 'Coin',

@@ -1212,13 +1217,10 @@ * multi: 'vector<Coin>'

*
* let example1 = Buffer.from('AICWmAAAAAAA', 'base64');
* let example2 = Buffer.from('AQIBAAAAAAAAAAIAAAAAAAAA', 'base64');
*
* console.log(
* BCS.de('MyEnum', new Uint8Array(example1)), // { single: { value: 10000000 } }
* BCS.de('MyEnum', new Uint8Array(example2)) // { multi: [ { value: 1 }, { value: 2 } ] }
* }
* bcs.de('MyEnum', 'AICWmAAAAAAA', 'base64'), // { single: { value: 10000000 } }
* bcs.de('MyEnum', 'AQIBAAAAAAAAAAIAAAAAAAAA', 'base64') // { multi: [ { value: 1 }, { value: 2 } ] }
* )
*
* // and serialization
* BCS.set('MyEnum', { single: { value: 10000000 } }).toBytes();
* BCS.set('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] });
* bcs.ser('MyEnum', { single: { value: 10000000 } }).toBytes();
* bcs.ser('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] });
*

@@ -1230,3 +1232,3 @@ * @param name

BCS.registerEnumType = function registerEnumType(name, variants) {
bcs.registerEnumType = function registerEnumType(name, variants) {
var struct = Object.freeze(variants); // Make sure the order doesn't get changed

@@ -1258,3 +1260,3 @@ // IMPORTANT: enum is an ordered type and we have to preserve ordering in BCS

return invariantType !== null ? BCS.getTypeInterface(invariantType)._encodeRaw(writer, data[key]) : writer;
return invariantType !== null ? bcs.getTypeInterface(invariantType)._encodeRaw(writer, data[key]) : writer;
}, function (reader) {

@@ -1271,8 +1273,16 @@ var _ref;

return _ref = {}, _ref[invariant] = invariantType !== null ? BCS.getTypeInterface(invariantType)._decodeRaw(reader) : true, _ref;
return _ref = {}, _ref[invariant] = invariantType !== null ? bcs.getTypeInterface(invariantType)._decodeRaw(reader) : true, _ref;
});
};
}
/**
* Get a set of encoders/decoders for specific type.
* Mainly used to define custom type de/serialization logic.
*
* @param type
* @returns {TypeInterface}
*/
;
BCS.getTypeInterface = function getTypeInterface(type) {
var typeInterface = BCS.types.get(type);
bcs.getTypeInterface = function getTypeInterface(type) {
var typeInterface = bcs.types.get(type);

@@ -1286,14 +1296,14 @@ if (typeInterface === undefined) {

return BCS;
return bcs;
}(); // Prefefined types constants
BCS.U8 = "u8";
BCS.U32 = "u32";
BCS.U64 = "u64";
BCS.U128 = "u128";
BCS.BOOL = "bool";
BCS.VECTOR = "vector";
BCS.ADDRESS = "address";
BCS.STRING = "string";
BCS.types = /*#__PURE__*/new Map();
bcs.U8 = 'u8';
bcs.U32 = 'u32';
bcs.U64 = 'u64';
bcs.U128 = 'u128';
bcs.BOOL = 'bool';
bcs.VECTOR = 'vector';
bcs.ADDRESS = 'address';
bcs.STRING = 'string';
bcs.types = /*#__PURE__*/new Map();
/**

@@ -1309,10 +1319,10 @@ * Encode data with either `hex` or `base64`.

switch (encoding) {
case "base64":
case 'base64':
return toB64(data);
case "hex":
case 'hex':
return toHEX(data);
default:
throw new Error("Unsupported encoding, supported values are: base64, hex");
throw new Error('Unsupported encoding, supported values are: base64, hex');
}

@@ -1330,10 +1340,10 @@ }

switch (encoding) {
case "base64":
case 'base64':
return fromB64(data);
case "hex":
case 'hex':
return fromHEX(data);
default:
throw new Error("Unsupported encoding, supported values are: base64, hex");
throw new Error('Unsupported encoding, supported values are: base64, hex');
}

@@ -1343,3 +1353,3 @@ }

(function registerPrimitives() {
BCS.registerType(BCS.U8, function (writer, data) {
bcs.registerType(bcs.U8, function (writer, data) {
return writer.write8(data);

@@ -1351,3 +1361,3 @@ }, function (reader) {

});
BCS.registerType(BCS.U32, function (writer, data) {
bcs.registerType(bcs.U32, function (writer, data) {
return writer.write32(data);

@@ -1359,3 +1369,3 @@ }, function (reader) {

});
BCS.registerType(BCS.U64, function (writer, data) {
bcs.registerType(bcs.U64, function (writer, data) {
return writer.write64(data);

@@ -1367,3 +1377,3 @@ }, function (reader) {

});
BCS.registerType(BCS.U128, function (writer, data) {
bcs.registerType(bcs.U128, function (writer, data) {
return writer.write128(data);

@@ -1375,10 +1385,10 @@ }, function (reader) {

});
BCS.registerType(BCS.BOOL, function (writer, data) {
bcs.registerType(bcs.BOOL, function (writer, data) {
return writer.write8(data);
}, function (reader) {
return reader.read8().toString(10) === "1";
return reader.read8().toString(10) === '1';
}, function (_bool) {
return true;
});
BCS.registerType(BCS.STRING, function (writer, data) {
bcs.registerType(bcs.STRING, function (writer, data) {
return writer.writeVec(Array.from(data), function (writer, el) {

@@ -1392,3 +1402,3 @@ return writer.write8(el.charCodeAt(0));

return String.fromCharCode(el);
}).join("");
}).join('');
}, function (_str) {

@@ -1399,5 +1409,5 @@ return true;

exports.BCS = BCS;
exports.BcsReader = BcsReader;
exports.BcsWriter = BcsWriter;
exports.bcs = bcs;
exports.decodeStr = decodeStr;

@@ -1404,0 +1414,0 @@ exports.encodeStr = encodeStr;

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("bn.js");function e(){e=function(){return t};var t={},r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{c({},"")}catch(t){c=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=Object.create((e&&e.prototype instanceof d?e:d).prototype),o=new T(n||[]);return i._invoke=function(t,e,r){var n="suspendedStart";return function(i,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw o;return{value:void 0,done:!0}}for(r.method=i,r.arg=o;;){var a=r.delegate;if(a){var u=x(a,r);if(u){if(u===h)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=f(t,e,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===h)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}(t,r,o),i}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var h={};function d(){}function l(){}function p(){}var y={};c(y,o,(function(){return this}));var v=Object.getPrototypeOf,w=v&&v(v(L([])));w&&w!==r&&n.call(w,o)&&(y=w);var g=p.prototype=d.prototype=Object.create(y);function m(t){["next","throw","return"].forEach((function(e){c(t,e,(function(t){return this._invoke(e,t)}))}))}function b(t,e){var r;this._invoke=function(i,o){function a(){return new e((function(r,a){!function r(i,o,a,u){var c=f(t[i],t,o);if("throw"!==c.type){var s=c.arg,h=s.value;return h&&"object"==typeof h&&n.call(h,"__await")?e.resolve(h.__await).then((function(t){r("next",t,a,u)}),(function(t){r("throw",t,a,u)})):e.resolve(h).then((function(t){s.value=t,a(s)}),(function(t){return r("throw",t,a,u)}))}u(c.arg)}(i,o,r,a)}))}return r=r?r.then(a,a):a()}}function x(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,x(t,e),"throw"===e.method))return h;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var n=f(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,h;var i=n.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function E(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function S(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function T(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(E,this),this.reset(!0)}function L(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,i=function e(){for(;++r<t.length;)if(n.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:U}}function U(){return{value:void 0,done:!0}}return l.prototype=p,c(g,"constructor",p),c(p,"constructor",l),l.displayName=c(p,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===l||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,p):(t.__proto__=p,c(t,u,"GeneratorFunction")),t.prototype=Object.create(g),t},t.awrap=function(t){return{__await:t}},m(b.prototype),c(b.prototype,a,(function(){return this})),t.AsyncIterator=b,t.async=function(e,r,n,i,o){void 0===o&&(o=Promise);var a=new b(s(e,r,n,i),o);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},m(g),c(g,u,"Generator"),c(g,o,(function(){return this})),c(g,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=L,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(S),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],a=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var u=n.call(o,"catchLoc"),c=n.call(o,"finallyLoc");if(u&&c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,h):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),S(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;S(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:L(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),h}},t}function r(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function n(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return r(t,void 0);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(t,void 0):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function i(t,e){for(var r,n,i,o=t.replace(/[^A-Za-z0-9+/]/g,""),a=o.length,u=e?Math.ceil((3*a+1>>2)/e)*e:3*a+1>>2,c=new Uint8Array(u),s=0,f=0,h=0;h<a;h++)if(n=3&h,s|=((i=o.charCodeAt(h))>64&&i<91?i-65:i>96&&i<123?i-71:i>47&&i<58?i+4:43===i?62:47===i?63:0)<<6*(3-n),3===n||a-h==1){for(r=0;r<3&&f<u;r++,f++)c[f]=s>>>(16>>>r&24)&255;s=0}return c}function o(t){return t<26?t+65:t<52?t+71:t<62?t-4:62===t?43:63===t?47:65}function a(t){for(var e=2,r="",n=t.length,i=0,a=0;a<n;a++)a>0&&4*a/3%76==0&&(r+=""),i|=t[a]<<(16>>>(e=a%3)&24),2!==e&&t.length-a!=1||(r+=String.fromCodePoint(o(i>>>18&63),o(i>>>12&63),o(i>>>6&63),o(63&i)),i=0);return r.slice(0,r.length-2+e)+(2===e?"":1===e?"=":"==")}function u(t){var e=t.replace("0x","").match(/.{1,2}/g).map((function(t){return parseInt(t,16)}));if(null===e)throw new Error("Unable to parse HEX: "+t);return Uint8Array.from(e)}function c(t){return t.reduce((function(t,e){return t+e.toString(16).padStart(2,"0")}),"")}var s=function(){function e(t){this.bytePosition=0,this.dataView=new DataView(t.buffer)}var r=e.prototype;return r.shift=function(t){return this.bytePosition+=t,this},r.read8=function(){var e=this.dataView.getUint8(this.bytePosition);return this.shift(1),new t.BN(e,10)},r.read16=function(){var e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),new t.BN(e,10)},r.read32=function(){var e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),new t.BN(e,10)},r.read64=function(){var e=this.read32(),r=this.read32().toString(16)+e.toString(16).padStart(8,"0");return new t.BN(r,16)},r.read128=function(){var e=this.read64(),r=this.read64().toString(16)+e.toString(16).padStart(8,"0");return new t.BN(r,16)},r.readBytes=function(t){var e=new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset,t);return this.shift(t),e},r.readULEB=function(){var t=function(t){for(var e=0,r=0,n=0;;){var i=t[n];if(n+=1,e|=(127&i)<<r,0==(128&i))break;r+=7}return{value:e,length:n}}(new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset)),e=t.value;return this.shift(t.length),e},r.readVec=function(t){for(var e=this.readULEB(),r=[],n=0;n<e;n++)r.push(t(this,n,e));return r},e}(),f=function(r){function n(t){void 0===t&&(t=1024),this.bytePosition=0,this.dataView=new DataView(new ArrayBuffer(t))}n.toBN=function(e){switch(typeof e){case"boolean":return new t.BN((e=+e).toString());case"bigint":return new t.BN(e.toString());default:return new t.BN(e)}};var i=n.prototype;return i.shift=function(t){return this.bytePosition+=t,this},i.write8=function(t){return this.dataView.setUint8(this.bytePosition,+n.toBN(t)),this.shift(1)},i.write16=function(t){return this.dataView.setUint16(this.bytePosition,+n.toBN(t),!0),this.shift(2)},i.write32=function(t){return this.dataView.setUint32(this.bytePosition,+n.toBN(t),!0),this.shift(4)},i.write64=function(t){var e=this;return n.toBN(t).toArray("le",8).forEach((function(t){return e.write8(t)})),this},i.write128=function(t){var e=this;return n.toBN(t).toArray("le",16).forEach((function(t){return e.write8(t)})),this},i.writeULEB=function(t){var e=this;return function(t){var e=[],r=0;if(0===t)return[0];for(;t>0;)e[r]=127&t,(t>>=7)&&(e[r]|=128),r+=1;return e}(t).forEach((function(t){return e.write8(t)})),this},i.writeVec=function(t,e){var r=this;return this.writeULEB(t.length),Array.from(t).forEach((function(n,i){return e(r,n,i,t.length)})),this},i[r]=e().mark((function t(){var r;return e().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=0;case 1:if(!(r<this.bytePosition)){t.next=7;break}return t.next=4,this.dataView.getUint8(r);case 4:r++,t.next=1;break;case 7:return t.abrupt("return",this.toBytes());case 8:case"end":return t.stop()}}),t,this)})),i.toBytes=function(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))},i.toString=function(t){return d(this.toBytes(),t)},n}(Symbol.iterator),h=function(){function t(){}return t.ser=function(t,e,r){return void 0===r&&(r=1024),this.getTypeInterface(t).encode(e,r)},t.de=function(t,e){return this.getTypeInterface(t).decode(e)},t.hasType=function(t){return this.types.has(t)},t.registerType=function(t,e,r,n){return void 0===n&&(n=function(){return!0}),this.types.set(t,{encode:function(t,e){return void 0===e&&(e=1024),this._encodeRaw(new f(e),t)},decode:function(t){return this._decodeRaw(new s(t))},_encodeRaw:function(r,i){if(n(i))return e(r,i);throw new Error("Validation failed for type "+t+", data: "+i)},_decodeRaw:function(t){return r(t)}}),this},t.registerAddressType=function(t,e,r){switch(void 0===r&&(r="hex"),r){case"base64":return this.registerType(t,(function(t,e){return i(e).reduce((function(t,e){return t.write8(e)}),t)}),(function(t){return a(t.readBytes(e))}));case"hex":return this.registerType(t,(function(t,e){return u(e).reduce((function(t,e){return t.write8(e)}),t)}),(function(t){return c(t.readBytes(e))}));default:throw new Error("Unsupported encoding! Use either hex or base64")}},t.registerVectorType=function(e,r){return this.registerType(e,(function(e,n){return e.writeVec(n,(function(e,n){return t.getTypeInterface(r)._encodeRaw(e,n)}))}),(function(e){return e.readVec((function(e){return t.getTypeInterface(r)._decodeRaw(e)}))}))},t.registerStructType=function(e,r){var i=Object.freeze(r),o=Object.keys(i);return this.registerType(e,(function(r,a){if(!a||a.constructor!==Object)throw new Error("Expected "+e+" to be an Object, got: "+a);for(var u,c=n(o);!(u=c()).done;){var s=u.value;if(!(s in a))throw new Error("Struct "+e+" requires field "+s+":"+i[s]);t.getTypeInterface(i[s])._encodeRaw(r,a[s])}return r}),(function(e){for(var r,a={},u=n(o);!(r=u()).done;){var c=r.value;a[c]=t.getTypeInterface(i[c])._decodeRaw(e)}return a}))},t.registerEnumType=function(e,r){var n=Object.freeze(r),i=Object.keys(n);return this.registerType(e,(function(r,o){if(void 0===o)throw new Error("Unable to write enum "+e+", missing data");var a=Object.keys(o)[0];if(void 0===a)throw new Error("Unknown invariant of the enum "+e);var u=i.indexOf(a);if(-1===u)throw new Error("Unknown invariant of the enum "+e+", allowed values: "+i);var c=n[i[u]];return r.write8(u),null!==c?t.getTypeInterface(c)._encodeRaw(r,o[a]):r}),(function(r){var o,a=r.readULEB(),u=i[a],c=n[u];if(-1===a)throw new Error("Decoding type mismatch, expected enum "+e+" invariant index, received "+a);return(o={})[u]=null===c||t.getTypeInterface(c)._decodeRaw(r),o}))},t.getTypeInterface=function(e){var r=t.types.get(e);if(void 0===r)throw new Error("Type "+e+" is not registered");return r},t}();function d(t,e){switch(e){case"base64":return a(t);case"hex":return c(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}h.U8="u8",h.U32="u32",h.U64="u64",h.U128="u128",h.BOOL="bool",h.VECTOR="vector",h.ADDRESS="address",h.STRING="string",h.types=new Map,h.registerType(h.U8,(function(t,e){return t.write8(e)}),(function(t){return t.read8()}),(function(t){return t<256})),h.registerType(h.U32,(function(t,e){return t.write32(e)}),(function(t){return t.read32()}),(function(t){return t<4294967296})),h.registerType(h.U64,(function(t,e){return t.write64(e)}),(function(t){return t.read64()}),(function(t){return!0})),h.registerType(h.U128,(function(t,e){return t.write128(e)}),(function(t){return t.read128()}),(function(t){return!0})),h.registerType(h.BOOL,(function(t,e){return t.write8(e)}),(function(t){return"1"===t.read8().toString(10)}),(function(t){return!0})),h.registerType(h.STRING,(function(t,e){return t.writeVec(Array.from(e),(function(t,e){return t.write8(e.charCodeAt(0))}))}),(function(t){return t.readVec((function(t){return t.read8()})).map((function(t){return String.fromCharCode(t)})).join("")}),(function(t){return!0})),exports.BCS=h,exports.BcsReader=s,exports.BcsWriter=f,exports.decodeStr=function(t,e){switch(e){case"base64":return i(t);case"hex":return u(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}},exports.encodeStr=d,exports.fromB64=i,exports.fromHEX=u,exports.toB64=a,exports.toHEX=c;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("bn.js");function e(){e=function(){return t};var t={},r=Object.prototype,n=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag";function c(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{c({},"")}catch(t){c=function(t,e,r){return t[e]=r}}function s(t,e,r,n){var i=Object.create((e&&e.prototype instanceof d?e:d).prototype),o=new L(n||[]);return i._invoke=function(t,e,r){var n="suspendedStart";return function(i,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===i)throw o;return{value:void 0,done:!0}}for(r.method=i,r.arg=o;;){var a=r.delegate;if(a){var u=x(a,r);if(u){if(u===h)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=f(t,e,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===h)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}(t,r,o),i}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var h={};function d(){}function l(){}function p(){}var y={};c(y,o,(function(){return this}));var w=Object.getPrototypeOf,v=w&&w(w(S([])));v&&v!==r&&n.call(v,o)&&(y=v);var g=p.prototype=d.prototype=Object.create(y);function m(t){["next","throw","return"].forEach((function(e){c(t,e,(function(t){return this._invoke(e,t)}))}))}function b(t,e){var r;this._invoke=function(i,o){function a(){return new e((function(r,a){!function r(i,o,a,u){var c=f(t[i],t,o);if("throw"!==c.type){var s=c.arg,h=s.value;return h&&"object"==typeof h&&n.call(h,"__await")?e.resolve(h.__await).then((function(t){r("next",t,a,u)}),(function(t){r("throw",t,a,u)})):e.resolve(h).then((function(t){s.value=t,a(s)}),(function(t){return r("throw",t,a,u)}))}u(c.arg)}(i,o,r,a)}))}return r=r?r.then(a,a):a()}}function x(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,x(t,e),"throw"===e.method))return h;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var n=f(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,h;var i=n.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,h):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,h)}function E(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function T(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function L(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(E,this),this.reset(!0)}function S(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,i=function e(){for(;++r<t.length;)if(n.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:U}}function U(){return{value:void 0,done:!0}}return l.prototype=p,c(g,"constructor",p),c(p,"constructor",l),l.displayName=c(p,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===l||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,p):(t.__proto__=p,c(t,u,"GeneratorFunction")),t.prototype=Object.create(g),t},t.awrap=function(t){return{__await:t}},m(b.prototype),c(b.prototype,a,(function(){return this})),t.AsyncIterator=b,t.async=function(e,r,n,i,o){void 0===o&&(o=Promise);var a=new b(s(e,r,n,i),o);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},m(g),c(g,u,"Generator"),c(g,o,(function(){return this})),c(g,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},t.values=S,L.prototype={constructor:L,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(T),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],a=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var u=n.call(o,"catchLoc"),c=n.call(o,"finallyLoc");if(u&&c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,h):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),h},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),T(r),h}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var i=n.arg;T(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:S(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),h}},t}function r(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function n(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(n)return(n=n.call(t)).next.bind(n);if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return r(t,void 0);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(t,void 0):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function i(t,e){for(var r,n,i,o=t.replace(/[^A-Za-z0-9+/]/g,""),a=o.length,u=e?Math.ceil((3*a+1>>2)/e)*e:3*a+1>>2,c=new Uint8Array(u),s=0,f=0,h=0;h<a;h++)if(n=3&h,s|=((i=o.charCodeAt(h))>64&&i<91?i-65:i>96&&i<123?i-71:i>47&&i<58?i+4:43===i?62:47===i?63:0)<<6*(3-n),3===n||a-h==1){for(r=0;r<3&&f<u;r++,f++)c[f]=s>>>(16>>>r&24)&255;s=0}return c}function o(t){return t<26?t+65:t<52?t+71:t<62?t-4:62===t?43:63===t?47:65}function a(t){for(var e=2,r="",n=t.length,i=0,a=0;a<n;a++)a>0&&4*a/3%76==0&&(r+=""),i|=t[a]<<(16>>>(e=a%3)&24),2!==e&&t.length-a!=1||(r+=String.fromCodePoint(o(i>>>18&63),o(i>>>12&63),o(i>>>6&63),o(63&i)),i=0);return r.slice(0,r.length-2+e)+(2===e?"":1===e?"=":"==")}function u(t){var e=t.replace("0x","").match(/.{1,2}/g).map((function(t){return parseInt(t,16)}));if(null===e)throw new Error("Unable to parse HEX: "+t);return Uint8Array.from(e)}function c(t){return t.reduce((function(t,e){return t+e.toString(16).padStart(2,"0")}),"")}var s=function(){function e(t){this.bytePosition=0,this.dataView=new DataView(t.buffer)}var r=e.prototype;return r.shift=function(t){return this.bytePosition+=t,this},r.read8=function(){var e=this.dataView.getUint8(this.bytePosition);return this.shift(1),new t.BN(e,10)},r.read16=function(){var e=this.dataView.getUint16(this.bytePosition,!0);return this.shift(2),new t.BN(e,10)},r.read32=function(){var e=this.dataView.getUint32(this.bytePosition,!0);return this.shift(4),new t.BN(e,10)},r.read64=function(){var e=this.read32(),r=this.read32().toString(16)+e.toString(16).padStart(8,"0");return new t.BN(r,16)},r.read128=function(){var e=this.read64(),r=this.read64().toString(16)+e.toString(16).padStart(8,"0");return new t.BN(r,16)},r.readBytes=function(t){var e=new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset,t);return this.shift(t),e},r.readULEB=function(){var t=function(t){for(var e=0,r=0,n=0;;){var i=t[n];if(n+=1,e|=(127&i)<<r,0==(128&i))break;r+=7}return{value:e,length:n}}(new Uint8Array(this.dataView.buffer,this.bytePosition+this.dataView.byteOffset)),e=t.value;return this.shift(t.length),e},r.readVec=function(t){for(var e=this.readULEB(),r=[],n=0;n<e;n++)r.push(t(this,n,e));return r},e}(),f=function(r){function n(t){void 0===t&&(t=1024),this.bytePosition=0,this.dataView=new DataView(new ArrayBuffer(t))}n.toBN=function(e){switch(typeof e){case"boolean":return new t.BN((e=+e).toString());case"bigint":return new t.BN(e.toString());default:return new t.BN(e)}};var i=n.prototype;return i.shift=function(t){return this.bytePosition+=t,this},i.write8=function(t){return this.dataView.setUint8(this.bytePosition,+n.toBN(t)),this.shift(1)},i.write16=function(t){return this.dataView.setUint16(this.bytePosition,+n.toBN(t),!0),this.shift(2)},i.write32=function(t){return this.dataView.setUint32(this.bytePosition,+n.toBN(t),!0),this.shift(4)},i.write64=function(t){var e=this;return n.toBN(t).toArray("le",8).forEach((function(t){return e.write8(t)})),this},i.write128=function(t){var e=this;return n.toBN(t).toArray("le",16).forEach((function(t){return e.write8(t)})),this},i.writeULEB=function(t){var e=this;return function(t){var e=[],r=0;if(0===t)return[0];for(;t>0;)e[r]=127&t,(t>>=7)&&(e[r]|=128),r+=1;return e}(t).forEach((function(t){return e.write8(t)})),this},i.writeVec=function(t,e){var r=this;return this.writeULEB(t.length),Array.from(t).forEach((function(n,i){return e(r,n,i,t.length)})),this},i[r]=e().mark((function t(){var r;return e().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=0;case 1:if(!(r<this.bytePosition)){t.next=7;break}return t.next=4,this.dataView.getUint8(r);case 4:r++,t.next=1;break;case 7:return t.abrupt("return",this.toBytes());case 8:case"end":return t.stop()}}),t,this)})),i.toBytes=function(){return new Uint8Array(this.dataView.buffer.slice(0,this.bytePosition))},i.toString=function(t){return d(this.toBytes(),t)},n}(Symbol.iterator),h=function(){function t(){}return t.ser=function(t,e,r){return void 0===r&&(r=1024),this.getTypeInterface(t).encode(e,r)},t.de=function(t,e,r){if("string"==typeof e){if(!r)throw new Error("To pass a string to `bcs.de`, specify encoding");e=l(e,r)}return this.getTypeInterface(t).decode(e)},t.hasType=function(t){return this.types.has(t)},t.registerType=function(t,e,r,n){return void 0===n&&(n=function(){return!0}),this.types.set(t,{encode:function(t,e){return void 0===e&&(e=1024),this._encodeRaw(new f(e),t)},decode:function(t){return this._decodeRaw(new s(t))},_encodeRaw:function(r,i){if(n(i))return e(r,i);throw new Error("Validation failed for type "+t+", data: "+i)},_decodeRaw:function(t){return r(t)}}),this},t.registerAddressType=function(t,e,r){switch(void 0===r&&(r="hex"),r){case"base64":return this.registerType(t,(function(t,e){return i(e).reduce((function(t,e){return t.write8(e)}),t)}),(function(t){return a(t.readBytes(e))}));case"hex":return this.registerType(t,(function(t,e){return u(e).reduce((function(t,e){return t.write8(e)}),t)}),(function(t){return c(t.readBytes(e))}));default:throw new Error("Unsupported encoding! Use either hex or base64")}},t.registerVectorType=function(e,r){return this.registerType(e,(function(e,n){return e.writeVec(n,(function(e,n){return t.getTypeInterface(r)._encodeRaw(e,n)}))}),(function(e){return e.readVec((function(e){return t.getTypeInterface(r)._decodeRaw(e)}))}))},t.registerStructType=function(e,r){var i=Object.freeze(r),o=Object.keys(i);return this.registerType(e,(function(r,a){if(!a||a.constructor!==Object)throw new Error("Expected "+e+" to be an Object, got: "+a);for(var u,c=n(o);!(u=c()).done;){var s=u.value;if(!(s in a))throw new Error("Struct "+e+" requires field "+s+":"+i[s]);t.getTypeInterface(i[s])._encodeRaw(r,a[s])}return r}),(function(e){for(var r,a={},u=n(o);!(r=u()).done;){var c=r.value;a[c]=t.getTypeInterface(i[c])._decodeRaw(e)}return a}))},t.registerEnumType=function(e,r){var n=Object.freeze(r),i=Object.keys(n);return this.registerType(e,(function(r,o){if(void 0===o)throw new Error("Unable to write enum "+e+", missing data");var a=Object.keys(o)[0];if(void 0===a)throw new Error("Unknown invariant of the enum "+e);var u=i.indexOf(a);if(-1===u)throw new Error("Unknown invariant of the enum "+e+", allowed values: "+i);var c=n[i[u]];return r.write8(u),null!==c?t.getTypeInterface(c)._encodeRaw(r,o[a]):r}),(function(r){var o,a=r.readULEB(),u=i[a],c=n[u];if(-1===a)throw new Error("Decoding type mismatch, expected enum "+e+" invariant index, received "+a);return(o={})[u]=null===c||t.getTypeInterface(c)._decodeRaw(r),o}))},t.getTypeInterface=function(e){var r=t.types.get(e);if(void 0===r)throw new Error("Type "+e+" is not registered");return r},t}();function d(t,e){switch(e){case"base64":return a(t);case"hex":return c(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}function l(t,e){switch(e){case"base64":return i(t);case"hex":return u(t);default:throw new Error("Unsupported encoding, supported values are: base64, hex")}}h.U8="u8",h.U32="u32",h.U64="u64",h.U128="u128",h.BOOL="bool",h.VECTOR="vector",h.ADDRESS="address",h.STRING="string",h.types=new Map,h.registerType(h.U8,(function(t,e){return t.write8(e)}),(function(t){return t.read8()}),(function(t){return t<256})),h.registerType(h.U32,(function(t,e){return t.write32(e)}),(function(t){return t.read32()}),(function(t){return t<4294967296})),h.registerType(h.U64,(function(t,e){return t.write64(e)}),(function(t){return t.read64()}),(function(t){return!0})),h.registerType(h.U128,(function(t,e){return t.write128(e)}),(function(t){return t.read128()}),(function(t){return!0})),h.registerType(h.BOOL,(function(t,e){return t.write8(e)}),(function(t){return"1"===t.read8().toString(10)}),(function(t){return!0})),h.registerType(h.STRING,(function(t,e){return t.writeVec(Array.from(e),(function(t,e){return t.write8(e.charCodeAt(0))}))}),(function(t){return t.readVec((function(t){return t.read8()})).map((function(t){return String.fromCharCode(t)})).join("")}),(function(t){return!0})),exports.BcsReader=s,exports.BcsWriter=f,exports.bcs=h,exports.decodeStr=l,exports.encodeStr=d,exports.fromB64=i,exports.fromHEX=u,exports.toB64=a,exports.toHEX=c;
//# sourceMappingURL=bcs.cjs.production.min.js.map

@@ -400,3 +400,3 @@ import { BN } from 'bn.js';

function fromB64(sBase64, nBlocksSize) {
var sB64Enc = sBase64.replace(/[^A-Za-z0-9+/]/g, ""),
var sB64Enc = sBase64.replace(/[^A-Za-z0-9+/]/g, ''),
nInLen = sB64Enc.length,

@@ -429,3 +429,3 @@ nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2,

var nMod3 = 2,
sB64Enc = "";
sB64Enc = '';

@@ -436,3 +436,3 @@ for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {

if (nIdx > 0 && nIdx * 4 / 3 % 76 === 0) {
sB64Enc += "";
sB64Enc += '';
}

@@ -448,3 +448,3 @@

return sB64Enc.slice(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? "" : nMod3 === 1 ? "=" : "==");
return sB64Enc.slice(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '==');
}

@@ -456,3 +456,3 @@

// @ts-ignore
var intArr = hexStr.replace("0x", "").match(/.{1,2}/g).map(function (_byte) {
var intArr = hexStr.replace('0x', '').match(/.{1,2}/g).map(function (_byte) {
return parseInt(_byte, 16);

@@ -469,4 +469,4 @@ });

return bytes.reduce(function (str, _byte2) {
return str + _byte2.toString(16).padStart(2, "0");
}, "");
return str + _byte2.toString(16).padStart(2, '0');
}, '');
}

@@ -490,3 +490,3 @@

*
* Reading vectors is another deal in BCS. To read a vector, you first need to read
* Reading vectors is another deal in bcs. To read a vector, you first need to read
* its length using {@link readULEB}. Here's an example:

@@ -570,3 +570,3 @@ * @example

var value2 = this.read32();
var result = value2.toString(16) + value1.toString(16).padStart(8, "0");
var result = value2.toString(16) + value1.toString(16).padStart(8, '0');
return new BN(result, 16);

@@ -583,3 +583,3 @@ }

var value2 = this.read64();
var result = value2.toString(16) + value1.toString(16).padStart(8, "0");
var result = value2.toString(16) + value1.toString(16).padStart(8, '0');
return new BN(result, 16);

@@ -672,7 +672,7 @@ }

switch (typeof number) {
case "boolean":
case 'boolean':
number = +number;
return new BN(number.toString());
case "bigint":
case 'bigint':
return new BN(number.toString());

@@ -741,3 +741,3 @@

BcsWriter.toBN(value).toArray("le", 8).forEach(function (el) {
BcsWriter.toBN(value).toArray('le', 8).forEach(function (el) {
return _this.write8(el);

@@ -759,3 +759,3 @@ });

BcsWriter.toBN(value).toArray("le", 16).forEach(function (el) {
BcsWriter.toBN(value).toArray('le', 16).forEach(function (el) {
return _this2.write8(el);

@@ -842,3 +842,3 @@ });

* Get underlying buffer taking only value bytes (in case initial buffer size was bigger).
* @returns {Uint8Array} Resulting BCS.
* @returns {Uint8Array} Resulting bcs.
*/

@@ -914,10 +914,10 @@ ;

var BCS = /*#__PURE__*/function () {
function BCS() {}
var bcs = /*#__PURE__*/function () {
function bcs() {}
/**
* Serialize data into BCS.
* Serialize data into bcs.
*
* @example
* BCS.registerVectorType('vector<u8>', 'u8');
* bcs.registerVectorType('vector<u8>', 'u8');
*

@@ -928,3 +928,3 @@ * let serialized = BCS

*
* console.assert(BCS.util.toHex(serialized) === '06010203040506');
* console.assert(toHex(serialized) === '06010203040506');
*

@@ -936,3 +936,3 @@ * @param type Name of the type to serialize (must be registered).

*/
BCS.ser = function ser(type, data, size) {
bcs.ser = function ser(type, data, size) {
if (size === void 0) {

@@ -948,8 +948,9 @@ size = 1024;

* @example
* // use util to form an Uint8Array buffer
* let data = BCS.de(BCS.U32, new Uint8Array([255, 255, 255, 255]));
* console.assert(data.toString() == '4294967295');
* let num = bcs.ser('u64', '4294967295').toString('hex');
* let deNum = bcs.de('u64', num, 'hex');
* console.assert(deNum.toString(10) === '4294967295');
*
* @param type Name of the type to deserialize (must be registered).
* @param data Data to deserialize.
* @param encoding Optional - encoding to use if data is of type String
* @return Deserialized data.

@@ -959,3 +960,11 @@ */

BCS.de = function de(type, data) {
bcs.de = function de(type, data, encoding) {
if (typeof data == 'string') {
if (encoding) {
data = decodeStr(data, encoding);
} else {
throw new Error('To pass a string to `bcs.de`, specify encoding');
}
}
return this.getTypeInterface(type).decode(data);

@@ -970,3 +979,3 @@ }

BCS.hasType = function hasType(type) {
bcs.hasType = function hasType(type) {
return this.types.has(type);

@@ -984,3 +993,3 @@ }

* // our type would be a string that consists only of numbers
* BCS.registerType('number_string',
* bcs.registerType('number_string',
* (writer, data) => writer.writeVec(data, (w, el) => w.write8(el)),

@@ -990,3 +999,3 @@ * (reader) => reader.readVec((r) => r.read8()).join(''), // read each value as u8

* );
* console.log(Array.from(BCS.set('number_string', '12345').toBytes()) == [5,1,2,3,4,5]);
* console.log(Array.from(bcs.ser('number_string', '12345').toBytes()) == [5,1,2,3,4,5]);
*

@@ -1000,3 +1009,3 @@ * @param name

BCS.registerType = function registerType(name, encodeCb, decodeCb, validateCb) {
bcs.registerType = function registerType(name, encodeCb, decodeCb, validateCb) {
if (validateCb === void 0) {

@@ -1037,4 +1046,4 @@ validateCb = function validateCb() {

* @example
* BCS.registerAddressType('address', 20);
* let addr = BCS.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026');
* bcs.registerAddressType('address', 20);
* let addr = bcs.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026');
*

@@ -1048,9 +1057,9 @@ * @param name Name of the address type.

BCS.registerAddressType = function registerAddressType(name, length, encoding) {
bcs.registerAddressType = function registerAddressType(name, length, encoding) {
if (encoding === void 0) {
encoding = "hex";
encoding = 'hex';
}
switch (encoding) {
case "base64":
case 'base64':
return this.registerType(name, function (writer, data) {

@@ -1064,3 +1073,3 @@ return fromB64(data).reduce(function (writer, el) {

case "hex":
case 'hex':
return this.registerType(name, function (writer, data) {

@@ -1075,19 +1084,15 @@ return fromHEX(data).reduce(function (writer, el) {

default:
throw new Error("Unsupported encoding! Use either hex or base64");
throw new Error('Unsupported encoding! Use either hex or base64');
}
}
/**
* Register custom vector type inside the BCS.
* Register custom vector type inside the bcs.
*
* @example
* BCS.registerVectorType('vector<u8>', 'u8');
* let array = BCS.de('vector<u8>', new Uint8Array([6,1,2,3,4,5,6])); // [1,2,3,4,5,6];
* let again = BCS.set('vector<u8>', [1,2,3,4,5,6]).toBytes();
* bcs.registerVectorType('vector<u8>', 'u8');
* let array = bcs.de('vector<u8>', '06010203040506', 'hex'); // [1,2,3,4,5,6];
* let again = bcs.ser('vector<u8>', [1,2,3,4,5,6]).toString('hex');
*
* BCS.registerVectorType('vector<u8>', 'u8', 'hex');
* let array =
*
* @param name Name of the type to register.
* @param elementType Name of the inner type of the vector.
* @param encoding Either 'base64' or 'hex' to enable string<->vector conversions
* @param name Name of the type to register
* @param elementType Name of the inner type of the vector
* @return Returns self for chaining.

@@ -1097,10 +1102,10 @@ */

BCS.registerVectorType = function registerVectorType(name, elementType) {
bcs.registerVectorType = function registerVectorType(name, elementType) {
return this.registerType(name, function (writer, data) {
return writer.writeVec(data, function (writer, el) {
return BCS.getTypeInterface(elementType)._encodeRaw(writer, el);
return bcs.getTypeInterface(elementType)._encodeRaw(writer, el);
});
}, function (reader) {
return reader.readVec(function (reader) {
return BCS.getTypeInterface(elementType)._decodeRaw(reader);
return bcs.getTypeInterface(elementType)._decodeRaw(reader);
});

@@ -1125,6 +1130,6 @@ });

*
* BCS.registerStructType('Coin', {
* value: BCS.U64,
* owner: BCS.STRING,
* is_locked: BCS.BOOL
* bcs.registerStructType('Coin', {
* value: bcs.U64,
* owner: bcs.STRING,
* is_locked: bcs.BOOL
* });

@@ -1134,3 +1139,3 @@ *

* // let rust_bcs_str = '80d1b105600000000e4269672057616c6c65742047757900';
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Buffer
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Array
* 128, 209, 177, 5, 96, 0, 0,

@@ -1143,3 +1148,3 @@ * 0, 14, 66, 105, 103, 32, 87,

* // Let's encode the value as well
* let test_set = BCS.set('Coin', {
* let test_set = bcs.ser('Coin', {
* owner: 'Big Wallet Guy',

@@ -1158,3 +1163,3 @@ * value: '412412400000',

BCS.registerStructType = function registerStructType(name, fields) {
bcs.registerStructType = function registerStructType(name, fields) {
var struct = Object.freeze(fields); // Make sure the order doesn't get changed

@@ -1177,3 +1182,3 @@ // IMPORTANT: we need to store canonical order of fields for each registered

if (key in data) {
BCS.getTypeInterface(struct[key])._encodeRaw(writer, data[key]);
bcs.getTypeInterface(struct[key])._encodeRaw(writer, data[key]);
} else {

@@ -1190,3 +1195,3 @@ throw new Error("Struct " + name + " requires field " + key + ":" + struct[key]);

var key = _step2.value;
result[key] = BCS.getTypeInterface(struct[key])._decodeRaw(reader);
result[key] = bcs.getTypeInterface(struct[key])._decodeRaw(reader);
}

@@ -1200,5 +1205,5 @@

* @example
* BCS.registerStructType('Coin', { value: 'u64' });
* BCS.registerVectorType('vector<Coin>', 'Coin');
* BCS.registerEnumType('MyEnum', {
* bcs.registerStructType('Coin', { value: 'u64' });
* bcs.registerVectorType('vector<Coin>', 'Coin');
* bcs.registerEnumType('MyEnum', {
* single: 'Coin',

@@ -1208,13 +1213,10 @@ * multi: 'vector<Coin>'

*
* let example1 = Buffer.from('AICWmAAAAAAA', 'base64');
* let example2 = Buffer.from('AQIBAAAAAAAAAAIAAAAAAAAA', 'base64');
*
* console.log(
* BCS.de('MyEnum', new Uint8Array(example1)), // { single: { value: 10000000 } }
* BCS.de('MyEnum', new Uint8Array(example2)) // { multi: [ { value: 1 }, { value: 2 } ] }
* }
* bcs.de('MyEnum', 'AICWmAAAAAAA', 'base64'), // { single: { value: 10000000 } }
* bcs.de('MyEnum', 'AQIBAAAAAAAAAAIAAAAAAAAA', 'base64') // { multi: [ { value: 1 }, { value: 2 } ] }
* )
*
* // and serialization
* BCS.set('MyEnum', { single: { value: 10000000 } }).toBytes();
* BCS.set('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] });
* bcs.ser('MyEnum', { single: { value: 10000000 } }).toBytes();
* bcs.ser('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] });
*

@@ -1226,3 +1228,3 @@ * @param name

BCS.registerEnumType = function registerEnumType(name, variants) {
bcs.registerEnumType = function registerEnumType(name, variants) {
var struct = Object.freeze(variants); // Make sure the order doesn't get changed

@@ -1254,3 +1256,3 @@ // IMPORTANT: enum is an ordered type and we have to preserve ordering in BCS

return invariantType !== null ? BCS.getTypeInterface(invariantType)._encodeRaw(writer, data[key]) : writer;
return invariantType !== null ? bcs.getTypeInterface(invariantType)._encodeRaw(writer, data[key]) : writer;
}, function (reader) {

@@ -1267,8 +1269,16 @@ var _ref;

return _ref = {}, _ref[invariant] = invariantType !== null ? BCS.getTypeInterface(invariantType)._decodeRaw(reader) : true, _ref;
return _ref = {}, _ref[invariant] = invariantType !== null ? bcs.getTypeInterface(invariantType)._decodeRaw(reader) : true, _ref;
});
};
}
/**
* Get a set of encoders/decoders for specific type.
* Mainly used to define custom type de/serialization logic.
*
* @param type
* @returns {TypeInterface}
*/
;
BCS.getTypeInterface = function getTypeInterface(type) {
var typeInterface = BCS.types.get(type);
bcs.getTypeInterface = function getTypeInterface(type) {
var typeInterface = bcs.types.get(type);

@@ -1282,14 +1292,14 @@ if (typeInterface === undefined) {

return BCS;
return bcs;
}(); // Prefefined types constants
BCS.U8 = "u8";
BCS.U32 = "u32";
BCS.U64 = "u64";
BCS.U128 = "u128";
BCS.BOOL = "bool";
BCS.VECTOR = "vector";
BCS.ADDRESS = "address";
BCS.STRING = "string";
BCS.types = /*#__PURE__*/new Map();
bcs.U8 = 'u8';
bcs.U32 = 'u32';
bcs.U64 = 'u64';
bcs.U128 = 'u128';
bcs.BOOL = 'bool';
bcs.VECTOR = 'vector';
bcs.ADDRESS = 'address';
bcs.STRING = 'string';
bcs.types = /*#__PURE__*/new Map();
/**

@@ -1305,10 +1315,10 @@ * Encode data with either `hex` or `base64`.

switch (encoding) {
case "base64":
case 'base64':
return toB64(data);
case "hex":
case 'hex':
return toHEX(data);
default:
throw new Error("Unsupported encoding, supported values are: base64, hex");
throw new Error('Unsupported encoding, supported values are: base64, hex');
}

@@ -1326,10 +1336,10 @@ }

switch (encoding) {
case "base64":
case 'base64':
return fromB64(data);
case "hex":
case 'hex':
return fromHEX(data);
default:
throw new Error("Unsupported encoding, supported values are: base64, hex");
throw new Error('Unsupported encoding, supported values are: base64, hex');
}

@@ -1339,3 +1349,3 @@ }

(function registerPrimitives() {
BCS.registerType(BCS.U8, function (writer, data) {
bcs.registerType(bcs.U8, function (writer, data) {
return writer.write8(data);

@@ -1347,3 +1357,3 @@ }, function (reader) {

});
BCS.registerType(BCS.U32, function (writer, data) {
bcs.registerType(bcs.U32, function (writer, data) {
return writer.write32(data);

@@ -1355,3 +1365,3 @@ }, function (reader) {

});
BCS.registerType(BCS.U64, function (writer, data) {
bcs.registerType(bcs.U64, function (writer, data) {
return writer.write64(data);

@@ -1363,3 +1373,3 @@ }, function (reader) {

});
BCS.registerType(BCS.U128, function (writer, data) {
bcs.registerType(bcs.U128, function (writer, data) {
return writer.write128(data);

@@ -1371,10 +1381,10 @@ }, function (reader) {

});
BCS.registerType(BCS.BOOL, function (writer, data) {
bcs.registerType(bcs.BOOL, function (writer, data) {
return writer.write8(data);
}, function (reader) {
return reader.read8().toString(10) === "1";
return reader.read8().toString(10) === '1';
}, function (_bool) {
return true;
});
BCS.registerType(BCS.STRING, function (writer, data) {
bcs.registerType(bcs.STRING, function (writer, data) {
return writer.writeVec(Array.from(data), function (writer, el) {

@@ -1388,3 +1398,3 @@ return writer.write8(el.charCodeAt(0));

return String.fromCharCode(el);
}).join("");
}).join('');
}, function (_str) {

@@ -1395,3 +1405,3 @@ return true;

export { BCS, BcsReader, BcsWriter, decodeStr, encodeStr, fromB64, fromHEX, toB64, toHEX };
export { BcsReader, BcsWriter, bcs, decodeStr, encodeStr, fromB64, fromHEX, toB64, toHEX };
//# sourceMappingURL=bcs.esm.js.map

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

import * as BN from "bn.js";
import { toB64, fromB64 } from "./b64";
import { toHEX, fromHEX } from "./hex";
import * as BN from 'bn.js';
import { toB64, fromB64 } from './b64';
import { toHEX, fromHEX } from './hex';
export { toB64, fromB64, fromHEX, toHEX };

@@ -21,3 +21,3 @@ /**

*
* Reading vectors is another deal in BCS. To read a vector, you first need to read
* Reading vectors is another deal in bcs. To read a vector, you first need to read
* its length using {@link readULEB}. Here's an example:

@@ -181,3 +181,3 @@ * @example

* Get underlying buffer taking only value bytes (in case initial buffer size was bigger).
* @returns {Uint8Array} Resulting BCS.
* @returns {Uint8Array} Resulting bcs.
*/

@@ -195,3 +195,3 @@ toBytes(): Uint8Array;

*/
interface TypeInterface {
export interface TypeInterface {
encode: (data: any, size: number) => BcsWriter;

@@ -205,3 +205,3 @@ decode: (data: Uint8Array) => any;

*/
export declare class BCS {
export declare class bcs {
static readonly U8: string;

@@ -217,6 +217,6 @@ static readonly U32: string;

/**
* Serialize data into BCS.
* Serialize data into bcs.
*
* @example
* BCS.registerVectorType('vector<u8>', 'u8');
* bcs.registerVectorType('vector<u8>', 'u8');
*

@@ -227,3 +227,3 @@ * let serialized = BCS

*
* console.assert(BCS.util.toHex(serialized) === '06010203040506');
* console.assert(toHex(serialized) === '06010203040506');
*

@@ -240,11 +240,12 @@ * @param type Name of the type to serialize (must be registered).

* @example
* // use util to form an Uint8Array buffer
* let data = BCS.de(BCS.U32, new Uint8Array([255, 255, 255, 255]));
* console.assert(data.toString() == '4294967295');
* let num = bcs.ser('u64', '4294967295').toString('hex');
* let deNum = bcs.de('u64', num, 'hex');
* console.assert(deNum.toString(10) === '4294967295');
*
* @param type Name of the type to deserialize (must be registered).
* @param data Data to deserialize.
* @param encoding Optional - encoding to use if data is of type String
* @return Deserialized data.
*/
static de(type: string, data: Uint8Array): any;
static de(type: string, data: Uint8Array | string, encoding?: string): any;
/**

@@ -266,3 +267,3 @@ * Check whether a TypeInterface has been loaded for the `Type`

* // our type would be a string that consists only of numbers
* BCS.registerType('number_string',
* bcs.registerType('number_string',
* (writer, data) => writer.writeVec(data, (w, el) => w.write8(el)),

@@ -272,3 +273,3 @@ * (reader) => reader.readVec((r) => r.read8()).join(''), // read each value as u8

* );
* console.log(Array.from(BCS.set('number_string', '12345').toBytes()) == [5,1,2,3,4,5]);
* console.log(Array.from(bcs.ser('number_string', '12345').toBytes()) == [5,1,2,3,4,5]);
*

@@ -280,8 +281,8 @@ * @param name

*/
static registerType(name: string, encodeCb: (writer: BcsWriter, data: any) => BcsWriter, decodeCb: (reader: BcsReader) => any, validateCb?: (data: any) => boolean): typeof BCS;
static registerType(name: string, encodeCb: (writer: BcsWriter, data: any) => BcsWriter, decodeCb: (reader: BcsReader) => any, validateCb?: (data: any) => boolean): typeof bcs;
/**
* Register an address type which is a sequence of U8s of specified length.
* @example
* BCS.registerAddressType('address', 20);
* let addr = BCS.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026');
* bcs.registerAddressType('address', 20);
* let addr = bcs.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026');
*

@@ -293,20 +294,16 @@ * @param name Name of the address type.

*/
static registerAddressType(name: string, length: number, encoding?: string | void): typeof BCS;
static registerAddressType(name: string, length: number, encoding?: string | void): typeof bcs;
/**
* Register custom vector type inside the BCS.
* Register custom vector type inside the bcs.
*
* @example
* BCS.registerVectorType('vector<u8>', 'u8');
* let array = BCS.de('vector<u8>', new Uint8Array([6,1,2,3,4,5,6])); // [1,2,3,4,5,6];
* let again = BCS.set('vector<u8>', [1,2,3,4,5,6]).toBytes();
* bcs.registerVectorType('vector<u8>', 'u8');
* let array = bcs.de('vector<u8>', '06010203040506', 'hex'); // [1,2,3,4,5,6];
* let again = bcs.ser('vector<u8>', [1,2,3,4,5,6]).toString('hex');
*
* BCS.registerVectorType('vector<u8>', 'u8', 'hex');
* let array =
*
* @param name Name of the type to register.
* @param elementType Name of the inner type of the vector.
* @param encoding Either 'base64' or 'hex' to enable string<->vector conversions
* @param name Name of the type to register
* @param elementType Name of the inner type of the vector
* @return Returns self for chaining.
*/
static registerVectorType(name: string, elementType: string): typeof BCS;
static registerVectorType(name: string, elementType: string): typeof bcs;
/**

@@ -328,6 +325,6 @@ * Safe method to register a custom Move struct. The first argument is a name of the

*
* BCS.registerStructType('Coin', {
* value: BCS.U64,
* owner: BCS.STRING,
* is_locked: BCS.BOOL
* bcs.registerStructType('Coin', {
* value: bcs.U64,
* owner: bcs.STRING,
* is_locked: bcs.BOOL
* });

@@ -337,3 +334,3 @@ *

* // let rust_bcs_str = '80d1b105600000000e4269672057616c6c65742047757900';
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Buffer
* let rust_bcs_str = [ // using an Array here as BCS works with Uint8Array
* 128, 209, 177, 5, 96, 0, 0,

@@ -346,3 +343,3 @@ * 0, 14, 66, 105, 103, 32, 87,

* // Let's encode the value as well
* let test_set = BCS.set('Coin', {
* let test_set = bcs.ser('Coin', {
* owner: 'Big Wallet Guy',

@@ -361,9 +358,9 @@ * value: '412412400000',

[key: string]: string;
}): typeof BCS;
}): typeof bcs;
/**
* Safe method to register custom enum type where each invariant holds the value of another type.
* @example
* BCS.registerStructType('Coin', { value: 'u64' });
* BCS.registerVectorType('vector<Coin>', 'Coin');
* BCS.registerEnumType('MyEnum', {
* bcs.registerStructType('Coin', { value: 'u64' });
* bcs.registerVectorType('vector<Coin>', 'Coin');
* bcs.registerEnumType('MyEnum', {
* single: 'Coin',

@@ -373,13 +370,10 @@ * multi: 'vector<Coin>'

*
* let example1 = Buffer.from('AICWmAAAAAAA', 'base64');
* let example2 = Buffer.from('AQIBAAAAAAAAAAIAAAAAAAAA', 'base64');
*
* console.log(
* BCS.de('MyEnum', new Uint8Array(example1)), // { single: { value: 10000000 } }
* BCS.de('MyEnum', new Uint8Array(example2)) // { multi: [ { value: 1 }, { value: 2 } ] }
* }
* bcs.de('MyEnum', 'AICWmAAAAAAA', 'base64'), // { single: { value: 10000000 } }
* bcs.de('MyEnum', 'AQIBAAAAAAAAAAIAAAAAAAAA', 'base64') // { multi: [ { value: 1 }, { value: 2 } ] }
* )
*
* // and serialization
* BCS.set('MyEnum', { single: { value: 10000000 } }).toBytes();
* BCS.set('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] });
* bcs.ser('MyEnum', { single: { value: 10000000 } }).toBytes();
* bcs.ser('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] });
*

@@ -391,3 +385,10 @@ * @param name

[key: string]: string | null;
}): typeof BCS;
}): typeof bcs;
/**
* Get a set of encoders/decoders for specific type.
* Mainly used to define custom type de/serialization logic.
*
* @param type
* @returns {TypeInterface}
*/
static getTypeInterface(type: string): TypeInterface;

@@ -394,0 +395,0 @@ }

{
"name": "@mysten/bcs",
"version": "0.1.0",
"version": "0.2.0",
"description": "BCS - Canonical Binary Serialization implementation for JavaScript",

@@ -12,5 +12,5 @@ "main": "dist/index.js",

"scripts": {
"prepublish": "tsdx build",
"prepublish": "tsdx lint && tsdx build",
"build": "tsdx build",
"test": "echo \"Error: no test specified\" && exit 1"
"test": "tsdx test"
},

@@ -17,0 +17,0 @@ "repository": {

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

# Move BCS
# BCS - Binary Canonical Serialization

@@ -8,55 +8,129 @@ This library implements [Binary Canonical Serialization (BCS)](https://github.com/diem/bcs) in JavaScript, making BCS available in both Browser and NodeJS environments.

- Move's primitive types de/serialization: u8, u64, u128, bool
- Ability to define custom types such as `vector` or `struct`
- Ability to define custom types such as `vector<T>` or `struct`
- Extendable and allows registering any custom types (e.g. vectors of structs)
- Custom addresses length. Example: `BCS.registerAddressType('Address', 20, 'hex')` - 20 bytes;
- Custom addresses length. Example: `BCS.registerAddressType('Address', 20, 'hex')` - 20 bytes
- Built-in support for enums (and potentially tuples)
- And again - full browser support!
## Examples
### Working with primitive types
At the high level, BCS gives a set of handy abstractions to (de)serialize data.
To deserialize data, use a `BCS.de(type: string, data: string)`. Type parameter is a name of the type; data is a BCS encoded as hex.
> Important: by default there's no type `address` in this library. To define it, use `registerAddressType`.
> Also, there's no built-in support for generics yet. For each `vector<T>` you have to define custom type
> using `registerVectorType('vector<u8>', 'u8')`. Default support for vectors is intentionally omitted (for now)
> because of type difference between Rust and Move vector types.
### Struct
In BCS structs are merely sequences of fields, they contain no type information but the order in
which fields are defined. It also means that you can use any field names - they won't affect serialization!
```
bcs.registerStructType(<TYPE>, {
[<FIELD>]: <FIELD_TYPE>,
...
})
```
```js
import { BCS } from '@mysten/bcs';
import { bcs } from "@mysten/bcs";
// MyAddr is an address of 20 bytes; encoded and decoded as HEX
bcs.registerAddressType('MyAddr', 20, 'hex');
bcs.registerStructType('Item', {
owner: 'MyAddr',
price: 'u64'
});
// bcs preserves order of fields according to struct definition, so you're free to
// use any order while serializing your structs
let bcs_bytes = bcs.ser('Item', {
price: '100000000000',
owner: '9c88e852aa66b346860ada31aa75c6c27695ae4b',
});
let item = bcs.de('Item', bcs_bytes);
console.log(item);
```
### Vector
Vector generics are not supported by default. To use a vector type, add it first:
```
bcs.registerVectorType(<TYPE>, <ELEMENT_TYPE>);
```
```js
import { bcs } from "@mysten/bcs";
bcs.registerVectorType('vector<u8>', 'u8');
let array = bcs.de('vector<u8>', '06010203040506', 'hex'); // [1,2,3,4,5,6];
let again = bcs.ser('vector<u8>', [1,2,3,4,5,6]).toString('hex');
console.assert(again === '06010203040506', 'Whoopsie!');
```
### Address
Even though the way of serializing Move addresses stays the same, the length of the address
varies depending on the network. To register an address type use:
```
bcs.registerAddressType(<TYPE>, <LENGTH>);
```
```js
import { bcs } from "@mysten/bcs";
bcs.registerAddressType('FiveByte', 5);
bcs.registerAddressType('DiemAddress', 20);
let de = bcs.de('FiveBytes', '0x00C0FFEE00', 'hex');
let ser = bcs.ser('DiemAddress', '9c88e852aa66b346860ada31aa75c6c27695ae4b').toString('hex');
console.assert(de === '00c0ffee00', 'Short address mismatch');
console.assert(ser === '9c88e852aa66b346860ada31aa75c6c27695ae4b', 'Long address mismatch');
```
### Primitive types
To deserialize data, use a `BCS.de(type: string, data: Uint8Array)`. Type parameter is a name of the type; data is a BCS encoded as hex.
```js
import { bcs } from '@mysten/bcs';
// BCS has a set of built ins:
// U8, U32, U64, U128, BOOL, STRING
console.assert(BCS.U64 === 'u64');
console.assert(BCS.BOOL === 'bool');
console.assert(BCS.STRING === 'string');
console.assert(bcs.U64 === 'u64');
console.assert(bcs.BOOL === 'bool');
console.assert(bcs.STRING === 'string');
const hex = BCS.util.fromHex;
// De/serialization of primitives is included by default;
let u8 = BCS.de(BCS.U8, hex('00')); // '0'
let u32 = BCS.de(BCS.U32, hex('78563412')); // '78563412'
let u64 = BCS.de(BCS.U64, hex('ffffffffffffffff')); // '18446744073709551615'
let u128 = BCS.de(BCS.U128, hex('FFFFFFFF000000000000000000000000')); // '4294967295'
let bool = BCS.de(BCS.BOOL, hex('00')); // false
let u8 = bcs.de(bcs.U8, '00', 'hex'); // '0'
let u32 = bcs.de(bcs.U32, '78563412', 'hex'); // '78563412'
let u64 = bcs.de(bcs.U64, 'ffffffffffffffff', 'hex'); // '18446744073709551615'
let u128 = bcs.de(bcs.U128, 'FFFFFFFF000000000000000000000000', 'hex'); // '4294967295'
let bool = bcs.de(bcs.BOOL, '00', 'hex'); // false
// There's also a handy built-in for ASCII strings (which are `vector<u8>` under the hood)
let str = BCS.de(BCS.STRING, hex('0a68656c6c6f5f6d6f7665')); // hello_move
let str = bcs.de(bcs.STRING, '0a68656c6c6f5f6d6f7665', 'hex'); // hello_move
// Address support TBD once the best API is figured out;
// let addr = BCS.de(Move.ADDRESS, '0a68656c6c6f5f6d6f7665'); // 0a68656c6c6f5f6d6f7665
console.log(str);
```
To serialize any type, use `BCS.ser(type: string, data: any)`. Type parameter is a name of the type to serialize, data is any data, depending on the type (can be object for structs or string for big integers - such as `u128`).
To serialize any type, use `bcs.ser(type: string, data: any)`. Type parameter is a name of the type to serialize, data is any data, depending on the type (can be object for structs or string for big integers - such as `u128`).
```js
import { BCS } from '@mysten/bcs';
import { bcs } from '@mysten/bcs';
let bcs_u8 = BCS.ser('u8', 255).toBytes(); // uint Array
let bcs_u8 = bcs.ser('u8', 255).toString('hex'); // uint Array
console.assert(bcs_u8 === 'ff');
console.assert(BCS.util.toHex(bcs_u8) === 'ff');
let bcs_ascii = BCS.ser('string', 'hello_move').toBytes();
console.assert(BCS.util.toHex(bcs_ascii) === '0a68656c6c6f5f6d6f7665');
let bcs_ascii = bcs.ser('string', 'hello_move').toString('hex');
console.assert(bcs_ascii === '0a68656c6c6f5f6d6f7665');
```
### Adding custom types
### Working with Move structs
```js
import { BCS } from '@mysten/bcs';
import { bcs } from '@mysten/bcs';

@@ -70,17 +144,15 @@ // Move / Rust struct

BCS.registerStructType('Coin', {
value: BCS.U64,
owner: BCS.STRING,
is_locked: BCS.BOOL
bcs.registerStructType('Coin', {
value: bcs.U64,
owner: bcs.STRING,
is_locked: bcs.BOOL
});
// Created in Rust with diem/bcs
let rust_bcs_str = '80d1b105600000000e4269672057616c6c65742047757900';
console.log(BCS.de('Coin', BCS.util.fromHex(rust_bcs_str)));
console.log(bcs.de('Coin', rust_bcs_str, 'hex'));
// Let's encode the value as well
let test_ser = BCS.ser('Coin', {
let test_ser = bcs.ser('Coin', {
owner: 'Big Wallet Guy',

@@ -92,3 +164,3 @@ value: '412412400000',

console.log(test_ser.toBytes());
console.assert(BCS.util.toHex(test_ser.toBytes()) === rust_bcs_str, 'Whoopsie, result mismatch');
console.assert(test_ser.toString('hex') === rust_bcs_str, 'Whoopsie, result mismatch');
```
// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
import { BCS as bcs, fromB64, toB64 } from './../src/index';
import { bcs, fromB64, toB64 } from './../src/index';
import { BN } from 'bn.js';

@@ -16,6 +16,6 @@

const num = BigInt('1311768467750121216');
const set = bcs.ser('u64', num).toBytes();
const set = bcs.ser('u64', num).toString('base64');
expect(toB64(set)).toEqual(exp);
expect(bcs.de('u64', fromB64(exp))).toEqual(
expect(set).toEqual(exp);
expect(bcs.de('u64', exp, 'base64')).toEqual(
new BN('1311768467750121216')

@@ -29,3 +29,3 @@ );

expect(bcs.de('u128', fromB64(sample)).toString(10)).toEqual(
expect(bcs.de('u128', sample, 'base64').toString(10)).toEqual(
'1111311768467750121216'

@@ -32,0 +32,0 @@ );

// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
import { BCS as bcs } from './../src/index';
import { bcs } from './../src/index';

@@ -6,0 +6,0 @@ describe('serde', () => {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc