airgap-coin-lib
Version:
The airgap-coin-lib is a protocol agnostic library to prepare, sign and broadcast cryptocurrency transactions.
1,393 lines (1,380 loc) • 5.22 MB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.airgapCoinLib = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Lazy = /** @class */ (function () {
function Lazy(init) {
this.init = init;
this.isInitialized = false;
this.value = undefined;
}
Lazy.prototype.get = function () {
if (!this.isInitialized) {
this.value = this.init();
this.isInitialized = true;
}
return this.value;
};
return Lazy;
}());
exports.Lazy = Lazy;
},{}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var RPCBody = /** @class */ (function () {
function RPCBody(method, params, id, jsonrpc) {
if (id === void 0) { id = 1; }
if (jsonrpc === void 0) { jsonrpc = '2.0'; }
this.method = method;
this.params = params;
this.id = id;
this.jsonrpc = jsonrpc;
}
return RPCBody;
}());
exports.RPCBody = RPCBody;
},{}],3:[function(require,module,exports){
(function (Buffer){(function (){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var taquito_utils_1 = require("../../../../../@taquito/utils-6.3.5-beta.0/packages/taquito-utils/src/taquito-utils");
var bignumber_1 = require("../../../../../bignumber.js-9.0.0/bignumber");
var constants_1 = require("./constants");
var codec_1 = require("./michelson/codec");
var uint8array_consumer_1 = require("./uint8array-consumer");
var utils_1 = require("./utils");
exports.prefixEncoder = function (prefix) { return function (str) {
return taquito_utils_1.buf2hex(Buffer.from(taquito_utils_1.b58cdecode(str, taquito_utils_1.prefix[prefix])));
}; };
exports.prefixDecoder = function (pre) { return function (str) {
var val = str.consume(taquito_utils_1.prefixLength[pre]);
return taquito_utils_1.b58cencode(val, taquito_utils_1.prefix[pre]);
}; };
exports.tz1Decoder = exports.prefixDecoder(taquito_utils_1.Prefix.TZ1);
exports.branchDecoder = exports.prefixDecoder(taquito_utils_1.Prefix.B);
exports.pkhDecoder = function (val) {
var prefix = val.consume(1);
if (prefix[0] === 0x00) {
return exports.prefixDecoder(taquito_utils_1.Prefix.TZ1)(val);
}
else if (prefix[0] === 0x01) {
return exports.prefixDecoder(taquito_utils_1.Prefix.TZ2)(val);
}
else if (prefix[0] === 0x02) {
return exports.prefixDecoder(taquito_utils_1.Prefix.TZ3)(val);
}
};
exports.branchEncoder = exports.prefixEncoder(taquito_utils_1.Prefix.B);
exports.tz1Encoder = exports.prefixEncoder(taquito_utils_1.Prefix.TZ1);
exports.boolEncoder = function (bool) { return (bool ? 'ff' : '00'); };
exports.proposalEncoder = function (proposal) {
return exports.prefixEncoder(taquito_utils_1.Prefix.P)(proposal);
};
exports.proposalDecoder = function (proposal) {
return exports.prefixDecoder(taquito_utils_1.Prefix.P)(proposal);
};
exports.proposalsDecoder = function (proposal) {
var proposals = [];
proposal.consume(4);
while (proposal.length() > 0) {
proposals.push(exports.proposalDecoder(proposal));
}
return proposals;
};
exports.proposalsEncoder = function (proposals) {
return utils_1.pad(32 * proposals.length) + proposals.map(function (x) { return exports.proposalEncoder(x); }).join('');
};
exports.ballotEncoder = function (ballot) {
switch (ballot) {
case 'yay':
return '00';
case 'nay':
return '01';
case 'pass':
return '02';
default:
throw new Error("Invalid ballot value: " + ballot);
}
};
exports.ballotDecoder = function (ballot) {
var value = ballot.consume(1);
switch (value[0]) {
case 0x00:
return 'yay';
case 0x01:
return 'nay';
case 0x02:
return 'pass';
default:
throw new Error("Unable to decode ballot value " + value[0]);
}
};
exports.delegateEncoder = function (val) {
if (val) {
return exports.boolEncoder(true) + exports.pkhEncoder(val);
}
else {
return exports.boolEncoder(false);
}
};
exports.int32Encoder = function (val) {
var num = parseInt(String(val), 10);
var byte = [];
for (var i = 0; i < 4; i++) {
var shiftBy = (4 - (i + 1)) * 8;
byte.push((num & (0xff << shiftBy)) >> shiftBy);
}
return Buffer.from(byte).toString('hex');
};
exports.int32Decoder = function (val) {
var num = val.consume(4);
var finalNum = 0;
for (var i = 0; i < num.length; i++) {
finalNum = finalNum | (num[i] << ((num.length - (i + 1)) * 8));
}
return finalNum;
};
exports.boolDecoder = function (val) {
var bool = val.consume(1);
return bool[0] === 0xff;
};
exports.delegateDecoder = function (val) {
var hasDelegate = exports.boolDecoder(val);
if (hasDelegate) {
return exports.pkhDecoder(val);
}
};
exports.pkhEncoder = function (val) {
var pubkeyPrefix = val.substr(0, 3);
switch (pubkeyPrefix) {
case taquito_utils_1.Prefix.TZ1:
return '00' + exports.prefixEncoder(taquito_utils_1.Prefix.TZ1)(val);
case taquito_utils_1.Prefix.TZ2:
return '01' + exports.prefixEncoder(taquito_utils_1.Prefix.TZ2)(val);
case taquito_utils_1.Prefix.TZ3:
return '02' + exports.prefixEncoder(taquito_utils_1.Prefix.TZ3)(val);
default:
throw new Error('Invalid public key hash');
}
};
exports.publicKeyEncoder = function (val) {
var pubkeyPrefix = val.substr(0, 4);
switch (pubkeyPrefix) {
case taquito_utils_1.Prefix.EDPK:
return '00' + exports.prefixEncoder(taquito_utils_1.Prefix.EDPK)(val);
case taquito_utils_1.Prefix.SPPK:
return '01' + exports.prefixEncoder(taquito_utils_1.Prefix.SPPK)(val);
case taquito_utils_1.Prefix.P2PK:
return '02' + exports.prefixEncoder(taquito_utils_1.Prefix.P2PK)(val);
default:
throw new Error('Invalid PK');
}
};
exports.addressEncoder = function (val) {
var pubkeyPrefix = val.substr(0, 3);
switch (pubkeyPrefix) {
case taquito_utils_1.Prefix.TZ1:
case taquito_utils_1.Prefix.TZ2:
case taquito_utils_1.Prefix.TZ3:
return '00' + exports.pkhEncoder(val);
case taquito_utils_1.Prefix.KT1:
return '01' + exports.prefixEncoder(taquito_utils_1.Prefix.KT1)(val) + '00';
default:
throw new Error('Invalid address');
}
};
exports.publicKeyDecoder = function (val) {
var preamble = val.consume(1);
switch (preamble[0]) {
case 0x00:
return exports.prefixDecoder(taquito_utils_1.Prefix.EDPK)(val);
case 0x01:
return exports.prefixDecoder(taquito_utils_1.Prefix.SPPK)(val);
case 0x02:
return exports.prefixDecoder(taquito_utils_1.Prefix.P2PK)(val);
default:
throw new Error('Invalid PK');
}
};
exports.addressDecoder = function (val) {
var preamble = val.consume(1);
switch (preamble[0]) {
case 0x00:
return exports.pkhDecoder(val);
case 0x01:
var address = exports.prefixDecoder(taquito_utils_1.Prefix.KT1)(val);
val.consume(1);
return address;
default:
throw new Error('Invalid Address');
}
};
exports.zarithEncoder = function (n) {
var fn = [];
var nn = new bignumber_1.default(n, 10);
if (nn.isNaN()) {
throw new TypeError("Invalid zarith number " + n);
}
while (true) {
// eslint-disable-line
if (nn.lt(128)) {
if (nn.lt(16))
fn.push('0');
fn.push(nn.toString(16));
break;
}
else {
var b = nn.mod(128);
nn = nn.minus(b);
nn = nn.dividedBy(128);
b = b.plus(128);
fn.push(b.toString(16));
}
}
return fn.join('');
};
exports.zarithDecoder = function (n) {
var mostSignificantByte = 0;
while (mostSignificantByte < n.length() && (n.get(mostSignificantByte) & 128) !== 0) {
mostSignificantByte += 1;
}
var num = new bignumber_1.default(0);
for (var i = mostSignificantByte; i >= 0; i -= 1) {
var tmp = n.get(i) & 0x7f;
num = num.multipliedBy(128);
num = num.plus(tmp);
}
n.consume(mostSignificantByte + 1);
return new bignumber_1.default(num).toString();
};
exports.entrypointDecoder = function (value) {
var preamble = utils_1.pad(value.consume(1)[0], 2);
if (preamble in constants_1.entrypointMapping) {
return constants_1.entrypointMapping[preamble];
}
else {
var entry = codec_1.extractRequiredLen(value, 1);
var entrypoint = Buffer.from(entry).toString('utf8');
if (entrypoint.length > constants_1.ENTRYPOINT_MAX_LENGTH) {
throw new Error("Oversized entrypoint: " + entrypoint + ". The maximum length of entrypoint is " + constants_1.ENTRYPOINT_MAX_LENGTH);
}
return entrypoint;
}
};
exports.parametersDecoder = function (val) {
var preamble = val.consume(1);
if (preamble[0] === 0x00) {
return;
}
else {
var encodedEntrypoint = exports.entrypointDecoder(val);
var params = codec_1.extractRequiredLen(val);
var parameters = codec_1.valueDecoder(new uint8array_consumer_1.Uint8ArrayConsumer(params));
return {
entrypoint: encodedEntrypoint,
value: parameters,
};
}
};
exports.entrypointEncoder = function (entrypoint) {
if (entrypoint in constants_1.entrypointMappingReverse) {
return "" + constants_1.entrypointMappingReverse[entrypoint];
}
else {
if (entrypoint.length > constants_1.ENTRYPOINT_MAX_LENGTH) {
throw new Error("Oversized entrypoint: " + entrypoint + ". The maximum length of entrypoint is " + constants_1.ENTRYPOINT_MAX_LENGTH);
}
var value = { string: entrypoint };
return "ff" + codec_1.valueEncoder(value).slice(8);
}
};
exports.parametersEncoder = function (val) {
if (!val || (val.entrypoint === 'default' && 'prim' in val.value && val.value.prim === 'Unit')) {
return '00';
}
var encodedEntrypoint = exports.entrypointEncoder(val.entrypoint);
var parameters = codec_1.valueEncoder(val.value);
var length = (parameters.length / 2).toString(16).padStart(8, '0');
return "ff" + encodedEntrypoint + length + parameters;
};
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../../../../@taquito/utils-6.3.5-beta.0/packages/taquito-utils/src/taquito-utils":13,"../../../../../bignumber.js-9.0.0/bignumber":49,"./constants":4,"./michelson/codec":7,"./uint8array-consumer":10,"./utils":11,"buffer":592}],4:[function(require,module,exports){
"use strict";
/*
* Some code in this file is originally from sotez
* Copyright (c) 2018 Andrew Kishino
*/
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("./utils");
// See: https://tezos.gitlab.io/protocols/005_babylon.html#transactions-now-have-an-entrypoint
exports.ENTRYPOINT_MAX_LENGTH = 31;
var CODEC;
(function (CODEC) {
CODEC["SECRET"] = "secret";
CODEC["RAW"] = "raw";
CODEC["TZ1"] = "tz1";
CODEC["BRANCH"] = "branch";
CODEC["ZARITH"] = "zarith";
CODEC["PUBLIC_KEY"] = "public_key";
CODEC["PKH"] = "pkh";
CODEC["DELEGATE"] = "delegate";
CODEC["SCRIPT"] = "script";
CODEC["BALLOT_STATEMENT"] = "ballotStmt";
CODEC["PROPOSAL"] = "proposal";
CODEC["PROPOSAL_ARR"] = "proposalArr";
CODEC["INT32"] = "int32";
CODEC["PARAMETERS"] = "parameters";
CODEC["ADDRESS"] = "address";
CODEC["OPERATION"] = "operation";
CODEC["OP_ACTIVATE_ACCOUNT"] = "activate_account";
CODEC["OP_DELEGATION"] = "delegation";
CODEC["OP_TRANSACTION"] = "transaction";
CODEC["OP_ORIGINATION"] = "origination";
CODEC["OP_BALLOT"] = "ballot";
CODEC["OP_ENDORSEMENT"] = "endorsement";
CODEC["OP_SEED_NONCE_REVELATION"] = "seed_nonce_revelation";
CODEC["OP_REVEAL"] = "reveal";
CODEC["OP_PROPOSALS"] = "proposals";
CODEC["MANAGER"] = "manager";
})(CODEC = exports.CODEC || (exports.CODEC = {}));
// See https://tezos.gitlab.io/whitedoc/michelson.html#full-grammar
exports.opMapping = {
'00': 'parameter',
'01': 'storage',
'02': 'code',
'03': 'False',
'04': 'Elt',
'05': 'Left',
'06': 'None',
'07': 'Pair',
'08': 'Right',
'09': 'Some',
'0a': 'True',
'0b': 'Unit',
'0c': 'PACK',
'0d': 'UNPACK',
'0e': 'BLAKE2B',
'0f': 'SHA256',
'10': 'SHA512',
'11': 'ABS',
'12': 'ADD',
'13': 'AMOUNT',
'14': 'AND',
'15': 'BALANCE',
'16': 'CAR',
'17': 'CDR',
'18': 'CHECK_SIGNATURE',
'19': 'COMPARE',
'1a': 'CONCAT',
'1b': 'CONS',
'1c': 'CREATE_ACCOUNT',
'1d': 'CREATE_CONTRACT',
'1e': 'IMPLICIT_ACCOUNT',
'1f': 'DIP',
'20': 'DROP',
'21': 'DUP',
'22': 'EDIV',
'23': 'EMPTY_MAP',
'24': 'EMPTY_SET',
'25': 'EQ',
'26': 'EXEC',
'27': 'FAILWITH',
'28': 'GE',
'29': 'GET',
'2a': 'GT',
'2b': 'HASH_KEY',
'2c': 'IF',
'2d': 'IF_CONS',
'2e': 'IF_LEFT',
'2f': 'IF_NONE',
'30': 'INT',
'31': 'LAMBDA',
'32': 'LE',
'33': 'LEFT',
'34': 'LOOP',
'35': 'LSL',
'36': 'LSR',
'37': 'LT',
'38': 'MAP',
'39': 'MEM',
'3a': 'MUL',
'3b': 'NEG',
'3c': 'NEQ',
'3d': 'NIL',
'3e': 'NONE',
'3f': 'NOT',
'40': 'NOW',
'41': 'OR',
'42': 'PAIR',
'43': 'PUSH',
'44': 'RIGHT',
'45': 'SIZE',
'46': 'SOME',
'47': 'SOURCE',
'48': 'SENDER',
'49': 'SELF',
'4a': 'STEPS_TO_QUOTA',
'4b': 'SUB',
'4c': 'SWAP',
'4d': 'TRANSFER_TOKENS',
'4e': 'SET_DELEGATE',
'4f': 'UNIT',
'50': 'UPDATE',
'51': 'XOR',
'52': 'ITER',
'53': 'LOOP_LEFT',
'54': 'ADDRESS',
'55': 'CONTRACT',
'56': 'ISNAT',
'57': 'CAST',
'58': 'RENAME',
'59': 'bool',
'5a': 'contract',
'5b': 'int',
'5c': 'key',
'5d': 'key_hash',
'5e': 'lambda',
'5f': 'list',
'60': 'map',
'61': 'big_map',
'62': 'nat',
'63': 'option',
'64': 'or',
'65': 'pair',
'66': 'set',
'67': 'signature',
'68': 'string',
'69': 'bytes',
'6a': 'mutez',
'6b': 'timestamp',
'6c': 'unit',
'6d': 'operation',
'6e': 'address',
'6f': 'SLICE',
'70': 'DIG',
'71': 'DUG',
'72': 'EMPTY_BIG_MAP',
'73': 'APPLY',
'74': 'chain_id',
'75': 'CHAIN_ID',
};
exports.opMappingReverse = (function () {
var result = {};
Object.keys(exports.opMapping).forEach(function (key) {
result[exports.opMapping[key]] = key;
});
return result;
})();
// See https://tezos.gitlab.io/api/p2p.html
exports.kindMapping = {
0x04: 'activate_account',
0x6b: 'reveal',
0x6e: 'delegation',
0x6c: 'transaction',
0x6d: 'origination',
0x06: 'ballot',
0x00: 'endorsement',
0x01: 'seed_nonce_revelation',
0x05: 'proposals',
};
exports.kindMappingReverse = (function () {
var result = {};
Object.keys(exports.kindMapping).forEach(function (key) {
var keyNum = typeof key === 'string' ? parseInt(key, 10) : key;
result[exports.kindMapping[keyNum]] = utils_1.pad(keyNum, 2);
});
return result;
})();
// See https://tezos.gitlab.io/protocols/005_babylon.html#transactions-now-have-an-entrypoint
exports.entrypointMapping = {
'00': 'default',
'01': 'root',
'02': 'do',
'03': 'set_delegate',
'04': 'remove_delegate',
};
exports.entrypointMappingReverse = (function () {
var result = {};
Object.keys(exports.entrypointMapping).forEach(function (key) {
result[exports.entrypointMapping[key]] = key;
});
return result;
})();
},{"./utils":11}],5:[function(require,module,exports){
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var codec_1 = require("./codec");
var constants_1 = require("./constants");
var codec_2 = require("./michelson/codec");
var operation_1 = require("./schema/operation");
var utils_1 = require("./utils");
exports.decoders = (_a = {},
_a[constants_1.CODEC.SECRET] = function (val) { return utils_1.toHexString(val.consume(20)); },
_a[constants_1.CODEC.RAW] = function (val) { return utils_1.toHexString(val.consume(32)); },
_a[constants_1.CODEC.TZ1] = codec_1.tz1Decoder,
_a[constants_1.CODEC.BRANCH] = codec_1.branchDecoder,
_a[constants_1.CODEC.ZARITH] = codec_1.zarithDecoder,
_a[constants_1.CODEC.PUBLIC_KEY] = codec_1.publicKeyDecoder,
_a[constants_1.CODEC.PKH] = codec_1.pkhDecoder,
_a[constants_1.CODEC.DELEGATE] = codec_1.delegateDecoder,
_a[constants_1.CODEC.INT32] = codec_1.int32Decoder,
_a[constants_1.CODEC.SCRIPT] = codec_2.scriptDecoder,
_a[constants_1.CODEC.BALLOT_STATEMENT] = codec_1.ballotDecoder,
_a[constants_1.CODEC.PROPOSAL] = codec_1.proposalDecoder,
_a[constants_1.CODEC.PROPOSAL_ARR] = codec_1.proposalsDecoder,
_a[constants_1.CODEC.PARAMETERS] = codec_1.parametersDecoder,
_a[constants_1.CODEC.ADDRESS] = codec_1.addressDecoder,
_a);
exports.decoders[constants_1.CODEC.OPERATION] = operation_1.operationDecoder(exports.decoders);
exports.decoders[constants_1.CODEC.OP_ACTIVATE_ACCOUNT] = function (val) {
return operation_1.schemaDecoder(exports.decoders)(operation_1.ActivationSchema)(val);
};
exports.decoders[constants_1.CODEC.OP_DELEGATION] = function (val) {
return operation_1.schemaDecoder(exports.decoders)(operation_1.DelegationSchema)(val);
};
exports.decoders[constants_1.CODEC.OP_TRANSACTION] = function (val) {
return operation_1.schemaDecoder(exports.decoders)(operation_1.TransactionSchema)(val);
};
exports.decoders[constants_1.CODEC.OP_ORIGINATION] = function (val) {
return operation_1.schemaDecoder(exports.decoders)(operation_1.OriginationSchema)(val);
};
exports.decoders[constants_1.CODEC.OP_BALLOT] = function (val) { return operation_1.schemaDecoder(exports.decoders)(operation_1.BallotSchema)(val); };
exports.decoders[constants_1.CODEC.OP_ENDORSEMENT] = function (val) {
return operation_1.schemaDecoder(exports.decoders)(operation_1.EndorsementSchema)(val);
};
exports.decoders[constants_1.CODEC.OP_SEED_NONCE_REVELATION] = function (val) {
return operation_1.schemaDecoder(exports.decoders)(operation_1.SeedNonceRevelationSchema)(val);
};
exports.decoders[constants_1.CODEC.OP_PROPOSALS] = function (val) {
return operation_1.schemaDecoder(exports.decoders)(operation_1.ProposalsSchema)(val);
};
exports.decoders[constants_1.CODEC.OP_REVEAL] = function (val) { return operation_1.schemaDecoder(exports.decoders)(operation_1.RevealSchema)(val); };
exports.decoders[constants_1.CODEC.MANAGER] = operation_1.schemaDecoder(exports.decoders)(operation_1.ManagerOperationSchema);
},{"./codec":3,"./constants":4,"./michelson/codec":7,"./schema/operation":8,"./utils":11}],6:[function(require,module,exports){
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
var codec_1 = require("./codec");
var constants_1 = require("./constants");
var codec_2 = require("./michelson/codec");
var operation_1 = require("./schema/operation");
exports.encoders = (_a = {},
_a[constants_1.CODEC.SECRET] = function (val) { return val; },
_a[constants_1.CODEC.RAW] = function (val) { return val; },
_a[constants_1.CODEC.TZ1] = codec_1.tz1Encoder,
_a[constants_1.CODEC.BRANCH] = codec_1.branchEncoder,
_a[constants_1.CODEC.ZARITH] = codec_1.zarithEncoder,
_a[constants_1.CODEC.PUBLIC_KEY] = codec_1.publicKeyEncoder,
_a[constants_1.CODEC.PKH] = codec_1.pkhEncoder,
_a[constants_1.CODEC.DELEGATE] = codec_1.delegateEncoder,
_a[constants_1.CODEC.SCRIPT] = codec_2.scriptEncoder,
_a[constants_1.CODEC.BALLOT_STATEMENT] = codec_1.ballotEncoder,
_a[constants_1.CODEC.PROPOSAL] = codec_1.proposalEncoder,
_a[constants_1.CODEC.PROPOSAL_ARR] = codec_1.proposalsEncoder,
_a[constants_1.CODEC.INT32] = codec_1.int32Encoder,
_a[constants_1.CODEC.PARAMETERS] = codec_1.parametersEncoder,
_a[constants_1.CODEC.ADDRESS] = codec_1.addressEncoder,
_a);
exports.encoders[constants_1.CODEC.OPERATION] = operation_1.operationEncoder(exports.encoders);
exports.encoders[constants_1.CODEC.OP_ACTIVATE_ACCOUNT] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.ActivationSchema)(val); };
exports.encoders[constants_1.CODEC.OP_DELEGATION] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.DelegationSchema)(val); };
exports.encoders[constants_1.CODEC.OP_TRANSACTION] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.TransactionSchema)(val); };
exports.encoders[constants_1.CODEC.OP_ORIGINATION] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.OriginationSchema)(val); };
exports.encoders[constants_1.CODEC.OP_BALLOT] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.BallotSchema)(val); };
exports.encoders[constants_1.CODEC.OP_ENDORSEMENT] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.EndorsementSchema)(val); };
exports.encoders[constants_1.CODEC.OP_SEED_NONCE_REVELATION] = function (val) {
return operation_1.schemaEncoder(exports.encoders)(operation_1.SeedNonceRevelationSchema)(val);
};
exports.encoders[constants_1.CODEC.OP_PROPOSALS] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.ProposalsSchema)(val); };
exports.encoders[constants_1.CODEC.OP_REVEAL] = function (val) { return operation_1.schemaEncoder(exports.encoders)(operation_1.RevealSchema)(val); };
exports.encoders[constants_1.CODEC.MANAGER] = operation_1.schemaEncoder(exports.encoders)(operation_1.ManagerOperationSchema);
},{"./codec":3,"./constants":4,"./michelson/codec":7,"./schema/operation":8}],7:[function(require,module,exports){
(function (Buffer){(function (){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var bignumber_1 = require("../../../../../../bignumber.js-9.0.0/bignumber");
var uint8array_consumer_1 = require("../uint8array-consumer");
var constants_1 = require("../constants");
var utils_1 = require("../utils");
exports.isPrim = function (value) {
return 'prim' in value;
};
exports.isBytes = function (value) {
// tslint:disable-next-line: strict-type-predicates
return 'bytes' in value && typeof value.bytes === 'string';
};
exports.isString = function (value) {
// tslint:disable-next-line: strict-type-predicates
return 'string' in value && typeof value.string === 'string';
};
exports.isInt = function (value) {
// tslint:disable-next-line: strict-type-predicates
return 'int' in value && typeof value.int === 'string';
};
exports.scriptEncoder = function (script) {
var code = exports.valueEncoder(script.code);
var storage = exports.valueEncoder(script.storage);
return "" + utils_1.pad(code.length / 2, 8) + code + utils_1.pad(storage.length / 2, 8) + storage;
};
exports.scriptDecoder = function (value) {
var code = exports.extractRequiredLen(value);
var storage = exports.extractRequiredLen(value);
return {
code: exports.valueDecoder(new uint8array_consumer_1.Uint8ArrayConsumer(code)),
storage: exports.valueDecoder(new uint8array_consumer_1.Uint8ArrayConsumer(storage)),
};
};
exports.valueEncoder = function (value) {
if (Array.isArray(value)) {
var encoded = value.map(function (x) { return exports.valueEncoder(x); }).join('');
var len = encoded.length / 2;
return "02" + utils_1.pad(len) + encoded;
}
else if (exports.isPrim(value)) {
return exports.primEncoder(value);
}
else if (exports.isBytes(value)) {
return exports.bytesEncoder(value);
}
else if (exports.isString(value)) {
return exports.stringEncoder(value);
}
else if (exports.isInt(value)) {
return exports.intEncoder(value);
}
throw new Error('Unexpected value');
};
exports.valueDecoder = function (value) {
var preamble = value.consume(1);
switch (preamble[0]) {
case 0x0a:
return exports.bytesDecoder(value);
case 0x01:
return exports.stringDecoder(value);
case 0x00:
return exports.intDecoder(value);
case 0x02:
var val = new uint8array_consumer_1.Uint8ArrayConsumer(exports.extractRequiredLen(value));
var results = [];
while (val.length() > 0) {
results.push(exports.valueDecoder(val));
}
return results;
default:
return exports.primDecoder(value, preamble);
}
};
exports.extractRequiredLen = function (value, bytesLength) {
if (bytesLength === void 0) { bytesLength = 4; }
var len = value.consume(bytesLength);
var valueLen = parseInt(Buffer.from(len).toString('hex'), 16);
return value.consume(valueLen);
};
exports.bytesEncoder = function (value) {
if (!/^([A-Fa-f0-9]{2})*$/.test(value.bytes)) {
throw new Error("Invalid hex string: " + value.bytes);
}
var len = value.bytes.length / 2;
return "0a" + utils_1.pad(len) + value.bytes;
};
exports.bytesDecoder = function (value) {
var bytes = exports.extractRequiredLen(value);
return {
bytes: Buffer.from(bytes).toString('hex'),
};
};
exports.stringEncoder = function (value) {
var str = Buffer.from(value.string, 'utf8').toString('hex');
var hexLength = str.length / 2;
return "01" + utils_1.pad(hexLength) + str;
};
exports.stringDecoder = function (value) {
var str = exports.extractRequiredLen(value);
return {
string: Buffer.from(str).toString('utf8'),
};
};
exports.intEncoder = function (_a) {
var int = _a.int;
var num = new bignumber_1.BigNumber(int, 10);
var positiveMark = num.toString(2)[0] === '-' ? '1' : '0';
var binary = num.toString(2).replace(/-/g, '');
var pad = binary.length <= 6
? 6
: (binary.length - 6) % 7
? binary.length + 7 - ((binary.length - 6) % 7)
: binary.length;
var splitted = binary.padStart(pad, '0').match(/\d{6,7}/g);
var reversed = splitted.reverse();
reversed[0] = positiveMark + reversed[0];
var numHex = reversed.map(function (x, i) {
// Add one to the last chunk
return parseInt((i === reversed.length - 1 ? '0' : '1') + x, 2)
.toString(16)
.padStart(2, '0');
});
return "00" + numHex.join('');
};
exports.intDecoder = function (value) {
var c = value.consume(1)[0];
var hexNumber = [];
var isNotLastChunkMask = 1 << 7;
while (c & isNotLastChunkMask) {
hexNumber.push(c);
c = value.consume(1)[0];
}
hexNumber.push(c);
var isNegative = !!((1 << 6) & hexNumber[0]);
hexNumber[0] = hexNumber[0] & 127;
var numBin = hexNumber
.map(function (x, i) {
return x
.toString(2)
.slice(i === 0 ? -6 : -7)
.padStart(i === 0 ? 6 : 7, '0');
})
.reverse();
var num = new bignumber_1.BigNumber(numBin.join(''), 2);
if (isNegative) {
num = num.times(-1);
}
return {
int: num.toFixed(),
};
};
exports.primEncoder = function (value) {
var hasAnnot = +Array.isArray(value.annots);
var argsCount = Array.isArray(value.args) ? value.args.length : 0;
// Specify the number of args max is 3 without annotation
var preamble = utils_1.pad(Math.min(2 * argsCount + hasAnnot + 0x03, 9), 2);
var op = constants_1.opMappingReverse[value.prim];
var encodedArgs = (value.args || []).map(function (arg) { return exports.valueEncoder(arg); }).join('');
var encodedAnnots = Array.isArray(value.annots) ? exports.encodeAnnots(value.annots) : '';
if (value.prim === 'LAMBDA' && argsCount) {
encodedArgs = utils_1.pad(encodedArgs.length / 2) + encodedArgs + utils_1.pad(0);
}
return "" + preamble + op + encodedArgs + encodedAnnots;
};
exports.primDecoder = function (value, preamble) {
var hasAnnot = (preamble[0] - 0x03) % 2 === 1;
var argsCount = Math.floor((preamble[0] - 0x03) / 2);
var op = value
.consume(1)[0]
.toString(16)
.padStart(2, '0');
if (constants_1.opMapping[op] === 'LAMBDA') {
value.consume(4);
}
var args = new Array(argsCount).fill(0).map(function () { return exports.valueDecoder(value); });
if (constants_1.opMapping[op] === 'LAMBDA') {
value.consume(4);
}
var result = {
prim: constants_1.opMapping[op],
};
if (args.length) {
result['args'] = args;
}
if (hasAnnot) {
result['annots'] = exports.decodeAnnots(value);
}
return result;
};
exports.encodeAnnots = function (value) {
var mergedAnnot = value
.map(function (x) {
return Buffer.from(x, 'utf8').toString('hex');
})
.join('20');
var len = mergedAnnot.length / 2;
return "" + utils_1.pad(len) + mergedAnnot;
};
exports.decodeAnnots = function (val) {
var len = val.consume(4);
var annotLen = parseInt(Buffer.from(len).toString('hex'), 16);
var restOfAnnot = val.consume(annotLen);
var restOfAnnotHex = Buffer.from(restOfAnnot).toString('hex');
return restOfAnnotHex.split('20').map(function (x) { return Buffer.from(x, 'hex').toString('utf8'); });
};
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../../../../../bignumber.js-9.0.0/bignumber":49,"../constants":4,"../uint8array-consumer":10,"../utils":11,"buffer":592}],8:[function(require,module,exports){
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var constants_1 = require("../constants");
exports.ManagerOperationSchema = {
branch: 'branch',
contents: ['operation'],
};
exports.ActivationSchema = {
pkh: 'tz1',
secret: 'secret',
};
exports.RevealSchema = {
source: 'pkh',
fee: 'zarith',
counter: 'zarith',
gas_limit: 'zarith',
storage_limit: 'zarith',
public_key: 'public_key',
};
exports.DelegationSchema = {
source: 'pkh',
fee: 'zarith',
counter: 'zarith',
gas_limit: 'zarith',
storage_limit: 'zarith',
delegate: 'delegate',
};
exports.TransactionSchema = {
source: 'pkh',
fee: 'zarith',
counter: 'zarith',
gas_limit: 'zarith',
storage_limit: 'zarith',
amount: 'zarith',
destination: 'address',
parameters: 'parameters',
};
exports.OriginationSchema = {
source: 'pkh',
fee: 'zarith',
counter: 'zarith',
gas_limit: 'zarith',
storage_limit: 'zarith',
balance: 'zarith',
delegate: 'delegate',
script: 'script',
};
exports.BallotSchema = {
source: 'pkh',
period: 'int32',
proposal: 'proposal',
ballot: 'ballotStmt',
};
exports.EndorsementSchema = {
level: 'int32',
};
exports.SeedNonceRevelationSchema = {
level: 'int32',
nonce: 'raw',
};
exports.ProposalsSchema = {
source: 'pkh',
period: 'int32',
proposals: 'proposalArr',
};
exports.operationEncoder = function (encoders) { return function (operation) {
if (!(operation.kind in encoders) || !(operation.kind in constants_1.kindMappingReverse)) {
throw new Error("Unsupported operation kind: " + operation.kind);
}
return constants_1.kindMappingReverse[operation.kind] + encoders[operation.kind](operation);
}; };
exports.operationDecoder = function (decoders) { return function (value) {
var op = value.consume(1);
var operationName = constants_1.kindMapping[op[0]];
var decodedObj = decoders[operationName](value);
if (typeof decodedObj !== 'object') {
throw new Error('Decoded invalid operation');
}
if (operationName) {
return __assign({ kind: operationName }, decodedObj);
}
else {
throw new Error("Unsupported operation " + op[0]);
}
}; };
exports.schemaEncoder = function (encoders) { return function (schema) { return function (value) {
var keys = Object.keys(schema);
return keys.reduce(function (prev, key) {
var valueToEncode = schema[key];
if (Array.isArray(valueToEncode)) {
var encoder_1 = encoders[valueToEncode[0]];
var values = value[key];
if (!Array.isArray(values)) {
throw new Error("Exepected value to be Array " + JSON.stringify(values));
}
return prev + values.reduce(function (prevBytes, current) { return prevBytes + encoder_1(current); }, '');
}
else {
var encoder = encoders[valueToEncode];
return prev + encoder(value[key]);
}
}, '');
}; }; };
exports.schemaDecoder = function (decoders) { return function (schema) { return function (value) {
var keys = Object.keys(schema);
return keys.reduce(function (prev, key) {
var _a, _b;
var valueToEncode = schema[key];
if (Array.isArray(valueToEncode)) {
var decoder = decoders[valueToEncode[0]];
var decoded = [];
var lastLength = value.length();
while (value.length() > 0) {
decoded.push(decoder(value));
if (lastLength === value.length()) {
throw new Error('Unable to decode value');
}
}
return __assign(__assign({}, prev), (_a = {}, _a[key] = decoded, _a));
}
else {
var decoder = decoders[valueToEncode];
var result = decoder(value);
if (result) {
return __assign(__assign({}, prev), (_b = {}, _b[key] = result, _b));
}
else {
return __assign({}, prev);
}
}
}, {});
}; }; };
},{"../constants":4}],9:[function(require,module,exports){
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var constants_1 = require("./constants");
var decoder_1 = require("./decoder");
var encoder_1 = require("./encoder");
var uint8array_consumer_1 = require("./uint8array-consumer");
var constants_2 = require("./constants");
exports.CODEC = constants_2.CODEC;
__export(require("./decoder"));
__export(require("./encoder"));
__export(require("./uint8array-consumer"));
function getCodec(codec) {
return {
encoder: encoder_1.encoders[codec],
decoder: function (hex) {
var consumer = uint8array_consumer_1.Uint8ArrayConsumer.fromHexString(hex);
return decoder_1.decoders[codec](consumer);
},
};
}
exports.getCodec = getCodec;
var LocalForger = /** @class */ (function () {
function LocalForger() {
this.codec = getCodec(constants_1.CODEC.MANAGER);
}
LocalForger.prototype.forge = function (params) {
return Promise.resolve(this.codec.encoder(params));
};
LocalForger.prototype.parse = function (hex) {
return Promise.resolve(this.codec.decoder(hex));
};
return LocalForger;
}());
exports.LocalForger = LocalForger;
exports.localForger = new LocalForger();
},{"./constants":4,"./decoder":5,"./encoder":6,"./uint8array-consumer":10}],10:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Uint8ArrayConsumer = /** @class */ (function () {
function Uint8ArrayConsumer(arr, offset) {
if (offset === void 0) { offset = 0; }
this.arr = arr;
this.offset = offset;
}
Uint8ArrayConsumer.fromHexString = function (hex) {
var lowHex = hex.toLowerCase();
if (/^(([a-f]|\d){2})*$/.test(lowHex)) {
var arr = new Uint8Array((lowHex.match(/([a-z]|\d){2}/g) || []).map(function (byte) { return parseInt(byte, 16); }));
return new Uint8ArrayConsumer(arr);
}
else {
throw new Error('Invalid hex string');
}
};
Uint8ArrayConsumer.prototype.consume = function (count) {
var subArr = this.arr.subarray(this.offset, this.offset + count);
this.offset += count;
return subArr;
};
Uint8ArrayConsumer.prototype.get = function (idx) {
return this.arr[this.offset + idx];
};
Uint8ArrayConsumer.prototype.length = function () {
return this.arr.length - this.offset;
};
return Uint8ArrayConsumer;
}());
exports.Uint8ArrayConsumer = Uint8ArrayConsumer;
},{}],11:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.concat = function () {
var arr = [];
for (var _i = 0; _i < arguments.length; _i++) {
arr[_i] = arguments[_i];
}
return arr.reduce(function (a, b) {
var c = new Uint8Array(a.length + b.length);
c.set(a);
c.set(b, a.length);
return c;
}, new Uint8Array());
};
exports.toHexString = function (bytes) {
return bytes.reduce(function (str, byte) { return str + byte.toString(16).padStart(2, '0'); }, '');
};
exports.pad = function (num, paddingLen) {
if (paddingLen === void 0) { paddingLen = 8; }
return num.toString(16).padStart(paddingLen, '0');
};
},{}],12:[function(require,module,exports){
"use strict";
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
var Prefix;
(function (Prefix) {
Prefix["TZ1"] = "tz1";
Prefix["TZ2"] = "tz2";
Prefix["TZ3"] = "tz3";
Prefix["KT"] = "KT";
Prefix["KT1"] = "KT1";
Prefix["EDSK2"] = "edsk2";
Prefix["SPSK"] = "spsk";
Prefix["P2SK"] = "p2sk";
Prefix["EDPK"] = "edpk";
Prefix["SPPK"] = "sppk";
Prefix["P2PK"] = "p2pk";
Prefix["EDESK"] = "edesk";
Prefix["SPESK"] = "spesk";
Prefix["P2ESK"] = "p2esk";
Prefix["EDSK"] = "edsk";
Prefix["EDSIG"] = "edsig";
Prefix["SPSIG"] = "spsig";
Prefix["P2SIG"] = "p2sig";
Prefix["SIG"] = "sig";
Prefix["NET"] = "Net";
Prefix["NCE"] = "nce";
Prefix["B"] = "b";
Prefix["O"] = "o";
Prefix["LO"] = "Lo";
Prefix["LLO"] = "LLo";
Prefix["P"] = "P";
Prefix["CO"] = "Co";
Prefix["ID"] = "id";
Prefix["EXPR"] = "expr";
Prefix["TZ"] = "TZ";
})(Prefix = exports.Prefix || (exports.Prefix = {}));
exports.prefix = (_a = {},
_a[Prefix.TZ1] = new Uint8Array([6, 161, 159]),
_a[Prefix.TZ2] = new Uint8Array([6, 161, 161]),
_a[Prefix.TZ3] = new Uint8Array([6, 161, 164]),
_a[Prefix.KT] = new Uint8Array([2, 90, 121]),
_a[Prefix.KT1] = new Uint8Array([2, 90, 121]),
_a[Prefix.EDSK] = new Uint8Array([43, 246, 78, 7]),
_a[Prefix.EDSK2] = new Uint8Array([13, 15, 58, 7]),
_a[Prefix.SPSK] = new Uint8Array([17, 162, 224, 201]),
_a[Prefix.P2SK] = new Uint8Array([16, 81, 238, 189]),
_a[Prefix.EDPK] = new Uint8Array([13, 15, 37, 217]),
_a[Prefix.SPPK] = new Uint8Array([3, 254, 226, 86]),
_a[Prefix.P2PK] = new Uint8Array([3, 178, 139, 127]),
_a[Prefix.EDESK] = new Uint8Array([7, 90, 60, 179, 41]),
_a[Prefix.SPESK] = new Uint8Array([0x09, 0xed, 0xf1, 0xae, 0x96]),
_a[Prefix.P2ESK] = new Uint8Array([0x09, 0x30, 0x39, 0x73, 0xab]),
_a[Prefix.EDSIG] = new Uint8Array([9, 245, 205, 134, 18]),
_a[Prefix.SPSIG] = new Uint8Array([13, 115, 101, 19, 63]),
_a[Prefix.P2SIG] = new Uint8Array([54, 240, 44, 52]),
_a[Prefix.SIG] = new Uint8Array([4, 130, 43]),
_a[Prefix.NET] = new Uint8Array([87, 82, 0]),
_a[Prefix.NCE] = new Uint8Array([69, 220, 169]),
_a[Prefix.B] = new Uint8Array([1, 52]),
_a[Prefix.O] = new Uint8Array([5, 116]),
_a[Prefix.LO] = new Uint8Array([133, 233]),
_a[Prefix.LLO] = new Uint8Array([29, 159, 109]),
_a[Prefix.P] = new Uint8Array([2, 170]),
_a[Prefix.CO] = new Uint8Array([79, 179]),
_a[Prefix.ID] = new Uint8Array([153, 103]),
_a[Prefix.EXPR] = new Uint8Array([13, 44, 64, 27]),
// Legacy prefix
_a[Prefix.TZ] = new Uint8Array([2, 90, 121]),
_a);
exports.prefixLength = (_b = {},
_b[Prefix.TZ1] = 20,
_b[Prefix.TZ2] = 20,
_b[Prefix.TZ3] = 20,
_b[Prefix.KT] = 20,
_b[Prefix.KT1] = 20,
_b[Prefix.EDPK] = 32,
_b[Prefix.SPPK] = 33,
_b[Prefix.P2PK] = 33,
_b[Prefix.EDSIG] = 64,
_b[Prefix.SPSIG] = 64,
_b[Prefix.P2SIG] = 64,
_b[Prefix.SIG] = 64,
_b[Prefix.NET] = 4,
_b[Prefix.B] = 32,
_b[Prefix.P] = 32,
_b);
},{}],13:[function(require,module,exports){
"use strict";
/*
* Some code in this file is originally from sotez and eztz
* Copyright (c) 2018 Andrew Kishino
* Copyright (c) 2017 Stephen Andrews
*/
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = require("../../../../../buffer-5.6.0/index");
var constants_1 = require("./constants");
var blake = require('../../../../../blakejs-1.1.0/index');
var bs58check = require('../../../../../bs58check-2.1.2/index');
__export(require("./validators"));
var constants_2 = require("./constants");
exports.prefix = constants_2.prefix;
exports.Prefix = constants_2.Prefix;
exports.prefixLength = constants_2.prefixLength;
/**
*
* @description Hash a string using the BLAKE2b algorithm, base58 encode the hash obtained and appends the prefix 'expr' to it
*
* @param value Value in hex
*/
function encodeExpr(value) {
var blakeHash = blake.blake2b(exports.hex2buf(value), null, 32);
return b58cencode(blakeHash, constants_1.prefix['expr']);
}
exports.encodeExpr = encodeExpr;
/**
*
* @description Base58 encode a string or a Uint8Array and append a prefix to it
*
* @param value Value to base58 encode
* @param prefix prefix to append to the encoded string
*/
function b58cencode(value, prefix) {
var payloadAr = typeof value === 'string' ? Uint8Array.from(index_1.Buffer.from(value, 'hex')) : value;
var n = new Uint8Array(prefix.length + payloadAr.length);
n.set(prefix);
n.set(payloadAr, prefix.length);
return bs58check.encode(index_1.Buffer.from(n.buffer));
}
exports.b58cencode = b58cencode;
/**
*
* @description Base58 decode a string and remove the prefix from it
*
* @param value Value to base58 decode
* @param prefix prefix to remove from the decoded string
*/
exports.b58cdecode = function (enc, prefixArg) {
return bs58check.decode(enc).slice(prefixArg.length);
};
/**
*
* @description Base58 decode a string with predefined prefix
*
* @param value Value to base58 decode
*/
function b58decode(payload) {
var _a;
var buf = bs58check.decode(payload);
var prefixMap = (_a = {},
_a[constants_1.prefix.tz1.toString()] = '0000',
_a[constants_1.prefix.tz2.toString()] = '0001',
_a[constants_1.prefix.tz3.toString()] = '0002',
_a);
var pref = prefixMap[new Uint8Array(buf.slice(0, 3)).toString()];
if (pref) {
// tz addresses
var hex = exports.buf2hex(buf.slice(3));
return pref + hex;
}
else {
// other (kt addresses)
return '01' + exports.buf2hex(buf.slice(3, 42)) + '00';
}
}
exports.b58decode = b58decode;
/**
*
* @description Base58 encode a public key using predefined prefix
*
* @param value Public Key to base58 encode
*/
function encodePubKey(value) {
if (value.substring(0, 2) === '00') {
var pref = {
'0000': constants_1.prefix.tz1,
'0001': constants_1.prefix.tz2,
'0002': constants_1.prefix.tz3,
};
return b58cencode(value.substring(4), pref[value.substring(0, 4)]);
}
return b58cencode(value.substring(2, 42), constants_1.prefix.KT);
}
exports.encodePubKey = encodePubKey;
/**
*
* @description Base58 encode a key according to its prefix
*
* @param value Key to base58 encode
*/
function encodeKey(value) {
if (value[0] === '0') {
var pref = {
'00': new Uint8Array([13, 15, 37, 217]),
'01': new Uint8Array([3, 254, 226, 86]),
'02': new Uint8Array([3, 178, 139, 127]),
};
return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
}
}
exports.encodeKey = encodeKey;
/**
*
* @description Base58 encode a key hash according to its prefix
*
* @param value Key to base58 encode
*/
function encodeKeyHash(value) {
if (value[0] === '0') {
var pref = {
'00': new Uint8Array([6, 161, 159]),
'01': new Uint8Array([6, 161, 161]),
'02': new Uint8Array([6, 161, 164]),
};
return b58cencode(value.substring(2), pref[value.substring(0, 2)]);
}
}
exports.encodeKeyHash = encodeKeyHash;
/**
*
* @description Convert an hex string to a Uint8Array
*
* @param hex Hex string to convert
*/
exports.hex2buf = function (hex) {
return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) { return parseInt(h, 16); }));
};
/**
*
* @description Merge 2 buffers together
*
* @param b1 First buffer
* @param b2 Second buffer
*/
exports.mergebuf = function (b1, b2) {
var r = new Uint8Array(b1.length + b2.length);
r.set(b1);
r.set(b2, b1.length);
return r;
};
/**
*
* @description Flatten a michelson json representation to an array
*
* @param s michelson json
*/
exports.mic2arr = function me2(s) {
var ret = [];
if (Object.prototype.hasOwnProperty.call(s, 'prim')) {
if (s.prim === 'Pair') {
ret.push(me2(s.args[0]));
ret = ret.concat(me2(s.args[1]));
}
else if (s.prim === 'Elt') {
ret = {
key: me2(s.args[0]),
val: me2(s.args[1]),
};
}
else if (s.prim === 'True') {
ret = true;
}
else if (s.prim === 'False') {
ret = false;
}
}
else if (Array.isArray(s)) {
var sc = s.length;
for (var i = 0; i < sc; i++) {
var n = me2(s[i]);
if (typeof n.key !== 'undefined') {
if (Array.isArray(ret)) {
ret = {
keys: [],
vals: [],
};
}
ret.keys.push(n.key);
ret.vals.push(n.val);
}
else {
ret.push(n);
}
}
}
else if (Object.prototype.hasOwnProperty.call(s, 'string')) {
ret = s.string;
}
else if (Object.prototype.hasOwnProperty.call(s, 'int')) {
ret = parseInt(s.int, 10);
}
else {
ret = s;
}
return ret;
};
/**
*
* @description Convert a buffer to an hex string
*
* @param buffer Buffer to convert
*/
exports.buf2hex = function (buffer) {
var byteArray = new Uint8Array(buffer);
var hexParts = [];
byteArray.forEach(function (byte) {
var hex = byte.toString(16);
var paddedHex = ("00" + hex).slice(-2);
hexParts.push(paddedHex);
});
return hexParts.join('');
};
},{"../../../../../blakejs-1.1.0/index":112,"../../../../../bs58check-2.1.2/index":118,"../../../../../buffer-5.6.0/index":121,"./constants":12,"./validators":14}],14:[function(require,module,exports){
"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var constants_1 = require("./constants");
var bs58check = require('../../../../../bs58check-2.1.2/index');
var ValidationResult;
(function (ValidationResult) {
ValidationResult[ValidationResult["NO_PREFIX_MATCHED"] = 0] = "NO_PREFIX_MATCHED";
ValidationResult[ValidationResult["INVALID_CHECKSUM"] = 1] = "INVALID_CHECKSUM";
ValidationResult[ValidationResult["INVALID_LENGTH"] = 2] = "INVALID_LENGTH";
ValidationResult[ValidationResult["VALID"] = 3] = "VALID";
})(ValidationResult = exports.ValidationResult || (exports.ValidationResult = {}));
function isValidPrefix(value) {
if (typeof value !== 'string') {
return false;
}
return value in constants_1.prefix;
}
exports.isValidPrefix = isValidPrefix;
/**
* @description This function is called by the validation functions ([[validateAddress]], [[validateChain]], [[validateContractAddress]], [[validateKeyHash]], [[validateSignature]], [[validatePublicK